code:
// https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc
const safariFix = `!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();`

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { semver } = require('@vue/cli-shared-utils')
const { projectModuleTargets } = require('../util/targets')

const minSafariVersion = projectModuleTargets.safari
const minIOSVersion = projectModuleTargets.ios
const supportsSafari10 =
  (minSafariVersion && semver.lt(semver.coerce(minSafariVersion), '11.0.0')) ||
  (minIOSVersion && semver.lt(semver.coerce(minIOSVersion), '11.0.0'))
const needsSafariFix = supportsSafari10

class SafariNomoduleFixPlugin {
  constructor ({ unsafeInline, jsDirectory }) {
    this.unsafeInline = unsafeInline
    this.jsDirectory = jsDirectory
  }

  apply (compiler) {
    if (!needsSafariFix) {
      return
    }
    const { RawSource } = compiler.webpack
      ? compiler.webpack.sources
      : require('webpack-sources')

    const ID = 'SafariNomoduleFixPlugin'
    compiler.hooks.compilation.tap(ID, compilation => {
      HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tap(ID, data => {
        let scriptTag

        if (this.unsafeInline) {
          // inject inline Safari 10 nomodule fix
          scriptTag = {
            tagName: 'script',
            closeTag: true,
            innerHTML: safariFix
          }
        } else {
          // inject the fix as an external script
          const safariFixPath = path.join(this.jsDirectory, 'safari-nomodule-fix.js')
          const fullSafariFixPath = path.join(compilation.options.output.publicPath, safariFixPath)
          compilation.assets[safariFixPath] = new RawSource(safariFix)
          scriptTag = {
            tagName: 'script',
            closeTag: true,
            attributes: {
              src: fullSafariFixPath
            }
          }
        }

        let tags = data.bodyTags
        if (data.plugin.options.scriptLoading === 'defer') {
          tags = data.headTags
        }

        // insert just before the first actual script tag,
        // and after all other tags such as `meta`
        const firstScriptIndex = tags.findIndex(tag => tag.tagName === 'script')
        tags.splice(firstScriptIndex, 0, scriptTag)
      })
    })
  }
}

SafariNomoduleFixPlugin.safariFix = safariFix
module.exports = SafariNomoduleFixPlugin


code:
// From https://github.com/webpack-contrib/webpack-bundle-analyzer/blob/4abac503c789bac94118e5bbfc410686fb5112c7/src/parseUtils.js
// Modified by Guillaume Chau (Akryum)

const acorn = require('acorn')
const walk = require('acorn-walk')
const mapValues = require('lodash.mapvalues')
const zlib = require('zlib')
const { warn } = require('@vue/cli-shared-utils')

exports.analyzeBundle = function analyzeBundle (bundleStats, assetSources) {
  // Picking only `*.js` assets from bundle that has non-empty `chunks` array
  const jsAssets = []
  const otherAssets = []

  // Separate JS assets
  bundleStats.assets.forEach(asset => {
    if (asset.name.endsWith('.js') && asset.chunks && asset.chunks.length) {
      jsAssets.push(asset)
    } else {
      otherAssets.push(asset)
    }
  })

  // Trying to parse bundle assets and get real module sizes
  let bundlesSources = null
  let parsedModules = null

  bundlesSources = {}
  parsedModules = {}

  for (const asset of jsAssets) {
    const source = assetSources.get(asset.name)
    let bundleInfo

    try {
      bundleInfo = parseBundle(source)
    } catch (err) {
      const msg = (err.code === 'ENOENT') ? 'no such file' : err.message
      warn(`Error parsing bundle asset "${asset.fullPath}": ${msg}`)
      continue
    }

    bundlesSources[asset.name] = bundleInfo.src
    Object.assign(parsedModules, bundleInfo.modules)
  }

  if (!Object.keys(bundlesSources).length) {
    bundlesSources = null
    parsedModules = null
    warn('\nNo bundles were parsed. Analyzer will show only original module sizes from stats file.\n')
  }

  // Update sizes

  bundleStats.modules.forEach(module => {
    const parsedSrc = parsedModules && parsedModules[module.id]
    module.size = {
      stats: module.size
    }
    if (parsedSrc) {
      module.size.parsed = parsedSrc.length
      module.size.gzip = getGzipSize(parsedSrc)
    } else {
      module.size.parsed = module.size.stats
      module.size.gzip = 0
    }
  })

  jsAssets.forEach(asset => {
    const src = bundlesSources && bundlesSources[asset.name]
    asset.size = {
      stats: asset.size
    }
    if (src) {
      asset.size.parsed = src.length
      asset.size.gzip = getGzipSize(src)
    } else {
      asset.size.parsed = asset.size.stats
      asset.size.gzip = 0
    }
  }, {})

  otherAssets.forEach(asset => {
    const src = assetSources.get(asset.name)
    asset.size = {
      stats: asset.size,
      parsed: asset.size
    }
    if (src) {
      asset.size.gzip = getGzipSize(src)
    } else {
      asset.size.gzip = 0
    }
  })
}

function parseBundle (bundleContent) {
  const ast = acorn.parse(bundleContent, {
    sourceType: 'script',
    // I believe in a bright future of ECMAScript!
    // Actually, it's set to `2050` to support the latest ECMAScript version that currently exists.
    // Seems like `acorn` supports such weird option value.
    ecmaVersion: 2050
  })

  const walkState = {
    locations: null,
    expressionStatementDepth: 0
  }

  walk.recursive(
    ast,
    walkState,
    {
      ExpressionStatement (node, state, c) {
        if (state.locations) return

        state.expressionStatementDepth++

        if (
          // Webpack 5 stores modules in the the top-level IIFE
          state.expressionStatementDepth === 1 &&
          ast.body.includes(node) &&
          isIIFE(node)
        ) {
          const fn = getIIFECallExpression(node)

          if (
            // It should not contain neither arguments
            fn.arguments.length === 0 &&
            // ...nor parameters
            fn.callee.params.length === 0
          ) {
            // Modules are stored in the very first variable declaration as hash
            const firstVariableDeclaration = fn.callee.body.body.find(n => n.type === 'VariableDeclaration')

            if (firstVariableDeclaration) {
              for (const declaration of firstVariableDeclaration.declarations) {
                if (declaration.init) {
                  state.locations = getModulesLocations(declaration.init)

                  if (state.locations) {
                    break
                  }
                }
              }
            }
          }
        }

        if (!state.locations) {
          c(node.expression, state)
        }

        state.expressionStatementDepth--
      },
      AssignmentExpression (node, state) {
        if (state.locations) return

        // Modules are stored in exports.modules:
        // exports.modules = {};
        const { left, right } = node

        if (
          left &&
          left.object && left.object.name === 'exports' &&
          left.property && left.property.name === 'modules' &&
          isModulesHash(right)
        ) {
          state.locations = getModulesLocations(right)
        }
      },
      CallExpression (node, state, c) {
        if (state.locations) return

        const args = node.arguments

        // Main chunk with webpack loader.
        // Modules are stored in first argument:
        // (function (...) {...})(<modules>)
        if (
          node.callee.type === 'FunctionExpression' &&
          !node.callee.id &&
          args.length === 1 &&
          isSimpleModulesList(args[0])
        ) {
          state.locations = getModulesLocations(args[0])
          return
        }

        // Async Webpack < v4 chunk without webpack loader.
        // webpackJsonp([<chunks>], <modules>, ...)

        // As function name may be changed with `output.jsonpFunction` option we can't rely on it's default name.
        if (
          node.callee.type === 'Identifier' &&
          mayBeAsyncChunkArguments(args) &&
          isModulesList(args[1])
        ) {
          state.locations = getModulesLocations(args[1])
          return
        }

        // Async Webpack v4 chunk without webpack loader.
        // (window.webpackJsonp=window.webpackJsonp||[]).push([[<chunks>], <modules>, ...]);
        // As function name may be changed with `output.jsonpFunction` option we can't rely on it's default name.
        if (isAsyncChunkPushExpression(node)) {
          state.locations = getModulesLocations(args[0].elements[1])
          return
        }

        // Webpack v4 WebWorkerChunkTemplatePlugin
        // globalObject.chunkCallbackName([<chunks>],<modules>, ...);
        // Both globalObject and chunkCallbackName can be changed through the config, so we can't check them.
        if (isAsyncWebWorkerChunkExpression(node)) {
          state.locations = getModulesLocations(args[1])
          return
        }

        // Walking into arguments because some of plugins (e.g. `DedupePlugin`) or some Webpack
        // features (e.g. `umd` library output) can wrap modules list into additional IIFE.
        args.forEach(arg => c(arg, state))
      }
    }
  )

  let modules

  if (walkState.locations) {
    modules = mapValues(walkState.locations,
      loc => bundleContent.slice(loc.start, loc.end)
    )
  } else {
    modules = {}
  }

  return {
    modules: modules,
    src: bundleContent,
    runtimeSrc: getBundleRuntime(bundleContent, walkState.locations)
  }
}

function getGzipSize (buffer) {
  return zlib.gzipSync(buffer).length
}

/**
 * Returns bundle source except modules
 */
function getBundleRuntime (content, modulesLocations) {
  const sortedLocations = Object.values(modulesLocations || {})
    .sort((a, b) => a.start - b.start)

  let result = ''
  let lastIndex = 0

  for (const { start, end } of sortedLocations) {
    result += content.slice(lastIndex, start)
    lastIndex = end
  }

  return result + content.slice(lastIndex, content.length)
}

function isIIFE (node) {
  return (
    node.type === 'ExpressionStatement' &&
    (
      node.expression.type === 'CallExpression' ||
      (node.expression.type === 'UnaryExpression' && node.expression.argument.type === 'CallExpression')
    )
  )
}

function getIIFECallExpression (node) {
  if (node.expression.type === 'UnaryExpression') {
    return node.expression.argument
  } else {
    return node.expression
  }
}

function isModulesList (node) {
  return (
    isSimpleModulesList(node) ||
    // Modules are contained in expression `Array([minimum ID]).concat([<module>, <module>, ...])`
    isOptimizedModulesArray(node)
  )
}

function isSimpleModulesList (node) {
  return (
    // Modules are contained in hash. Keys are module ids.
    isModulesHash(node) ||
    // Modules are contained in array. Indexes are module ids.
    isModulesArray(node)
  )
}

function isModulesHash (node) {
  return (
    node.type === 'ObjectExpression' &&
    node.properties
      .map(p => p.value)
      .every(isModuleWrapper)
  )
}

function isModulesArray (node) {
  return (
    node.type === 'ArrayExpression' &&
    node.elements.every(elem =>
      // Some of array items may be skipped because there is no module with such id
      !elem ||
      isModuleWrapper(elem)
    )
  )
}

function isOptimizedModulesArray (node) {
  // Checking whether modules are contained in `Array(<minimum ID>).concat(...modules)` array:
  // https://github.com/webpack/webpack/blob/v1.14.0/lib/Template.js#L91
  // The `<minimum ID>` + array indexes are module ids
  return (
    node.type === 'CallExpression' &&
    node.callee.type === 'MemberExpression' &&
    // Make sure the object called is `Array(<some number>)`
    node.callee.object.type === 'CallExpression' &&
    node.callee.object.callee.type === 'Identifier' &&
    node.callee.object.callee.name === 'Array' &&
    node.callee.object.arguments.length === 1 &&
    isNumericId(node.callee.object.arguments[0]) &&
    // Make sure the property X called for `Array(<some number>).X` is `concat`
    node.callee.property.type === 'Identifier' &&
    node.callee.property.name === 'concat' &&
    // Make sure exactly one array is passed in to `concat`
    node.arguments.length === 1 &&
    isModulesArray(node.arguments[0])
  )
}

function isModuleWrapper (node) {
  return (
    // It's an anonymous function expression that wraps module
    ((node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') && !node.id) ||
    // If `DedupePlugin` is used it can be an ID of duplicated module...
    isModuleId(node) ||
    // or an array of shape [<module_id>, ...args]
    (node.type === 'ArrayExpression' && node.elements.length > 1 && isModuleId(node.elements[0]))
  )
}

function isModuleId (node) {
  return (node.type === 'Literal' && (isNumericId(node) || typeof node.value === 'string'))
}

function isNumericId (node) {
  return (node.type === 'Literal' && Number.isInteger(node.value) && node.value >= 0)
}

function isChunkIds (node) {
  // Array of numeric or string ids. Chunk IDs are strings when NamedChunksPlugin is used
  return (
    node.type === 'ArrayExpression' &&
    node.elements.every(isModuleId)
  )
}

function isAsyncChunkPushExpression (node) {
  const {
    callee,
    arguments: args
  } = node

  return (
    callee.type === 'MemberExpression' &&
    callee.property.name === 'push' &&
    callee.object.type === 'AssignmentExpression' &&
    args.length === 1 &&
    args[0].type === 'ArrayExpression' &&
    mayBeAsyncChunkArguments(args[0].elements) &&
    isModulesList(args[0].elements[1])
  )
}

function mayBeAsyncChunkArguments (args) {
  return (
    args.length >= 2 &&
    isChunkIds(args[0])
  )
}

function isAsyncWebWorkerChunkExpression (node) {
  const { callee, type, arguments: args } = node

  return (
    type === 'CallExpression' &&
    callee.type === 'MemberExpression' &&
    args.length === 2 &&
    isChunkIds(args[0]) &&
    isModulesList(args[1])
  )
}

function getModulesLocations (node) {
  if (node.type === 'ObjectExpression') {
    // Modules hash
    const modulesNodes = node.properties

    return modulesNodes.reduce((result, moduleNode) => {
      const moduleId = moduleNode.key.name || moduleNode.key.value

      result[moduleId] = getModuleLocation(moduleNode.value)
      return result
    }, {})
  }

  const isOptimizedArray = (node.type === 'CallExpression')

  if (node.type === 'ArrayExpression' || isOptimizedArray) {
    // Modules array or optimized array
    const minId = isOptimizedArray
      // Get the [minId] value from the Array() call first argument literal value
      ? node.callee.object.arguments[0].value
      // `0` for simple array
      : 0
    const modulesNodes = isOptimizedArray
      // The modules reside in the `concat()` function call arguments
      ? node.arguments[0].elements
      : node.elements

    return modulesNodes.reduce((result, moduleNode, i) => {
      if (moduleNode) {
        result[i + minId] = getModuleLocation(moduleNode)
      }
      return result
    }, {})
  }

  return {}
}

function getModuleLocation (node) {
  return { start: node.start, end: node.end }
}

license: mit


code:
module.exports = (api) => {
  if (api.hasPlugin('vue-next')) {
    api.extendPackage({
      devDependencies: {
        'vue-cli-plugin-vue-next': null
      }
    },
    {
      prune: true
    })

    api.exitLog('vue-cli-plugin-vue-next is removed because Vue 3 support has been built into the core plugins.')
  }

  // TODO: lint-staged update
}


@vue/cli-service

description: local service for vue-cli projects

type: git

keywords: vue cli

author: Evan You

license: MIT

access: public


code:
import ChainableWebpackConfig = require('webpack-chain')
import { Configuration as WebpackOptions } from 'webpack'

type PredefinedOptions<T> = T & { [key: string]: any }

type PageEntry = string | string[];

interface PageConfig {
  entry: PageEntry;
  [key: string]: any;
}

interface LoaderOptions {
  css?: object;
  sass?: object;
  scss?: object;
  less?: object;
  stylus?: object;
  postcss?: object;
}

// mini-css-extract-plugin options
interface ExtractOptions {
  filename?: string;
  chunkFilename?: string;
}

interface CSSOptions {
  /**
   * Default: `true`
   *
   * By default, only files that ends in `*.module.[ext]` are treated as CSS modules
   */
  requireModuleExtension?: boolean;
  /**
   * Default: `true`
   *
   * Whether to extract CSS in your components into a standalone CSS files (instead of inlined in JavaScript and injected dynamically)
   */
  extract?: boolean | ExtractOptions;
  /**
   * Default: `false`
   *
   * Whether to enable source maps for CSS. Setting this to `true` may affect build performance
   */
  sourceMap?: boolean;
  /**
   * Default: `{}`
   *
   * Pass options to CSS-related loaders
   */
  loaderOptions?: LoaderOptions;
}

interface ProjectOptions {
  /**
   * Default: `'/'`
   *
   * The base URL your application bundle will be deployed at
   */
  publicPath?: string;
  /**
   * Default: `'dist'`
   *
   * The directory where the production build files will be generated in when running `vue-cli-service build`
   */
  outputDir?: string;
  /**
   * Default: `''`
   *
   * A directory (relative to `outputDir`) to nest generated static assets (js, css, img, fonts) under
   */
  assetsDir?: string;
  /**
   * Default: `'index.html'`
   *
   * Specify the output path for the generated `index.html` (relative to `outputDir`). Can also be an absolute path
   */
  indexPath?: string;
  /**
   * Default: `true`
   *
   * By default, generated static assets contains hashes in their filenames for better caching control
   */
  filenameHashing?: boolean;
  /**
   * Default: `false`
   *
   * Whether to use the build of Vue core that includes the runtime compiler
   */
  runtimeCompiler?: boolean;
  /**
   * Default: `false`
   *
   * If set to `true`, all dependencies in `node_modules` will be transpiled by Babel;
   * Or, if you only want to selectively transpile some of the dependencies, you can list them
   * in this option.
   */
  transpileDependencies?: boolean | Array<string | RegExp>;
  /**
   * Default: `true`
   *
   * Setting this to `false` can speed up production builds if you don't need source maps for production
   */
  productionSourceMap?: boolean;
  /**
   * Default: `require('os').cpus().length > 1`
   *
   * Whether to use `thread-loader` for Babel or TypeScript transpilation
   */
  parallel?: boolean | number;
  /**
   * [All options for `webpack-dev-server`](https://webpack.js.org/configuration/dev-server/) are supported
   */
  devServer?: { proxy?: string | object, [key: string]: any };
  /**
   * Default: `undefined`
   *
   * Build the app in multi-page mode
   */
  pages?: {
    [key: string]: PageEntry | PageConfig;
  };
  /**
   * Default: `undefined`
   *
   * Configure the `crossorigin` attribute on `<link rel="stylesheet">` and `<script>` tags in generated HTML
   */
  crossorigin?: '' | 'anonymous' | 'use-credentials';
  /**
   * Default: `false`
   *
   * Set to `true` to enable [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) (SRI) on `<link rel="stylesheet">` and `<script>` tags in generated HTML
   */
  integrity?: boolean;

  css?: CSSOptions;

  /**
   * A function that will receive an instance of `ChainableConfig` powered by [webpack-chain](https://github.com/mozilla-neutrino/webpack-chain)
   */
  chainWebpack?: (config: ChainableWebpackConfig) => void;
  /**
   * Set webpack configuration.  If the value is `Object`, will be merged into config.  If value is `Function`, will receive current config as argument
   */
  configureWebpack?: WebpackOptions | ((config: WebpackOptions) => (WebpackOptions | void));

  /**
   * Default: `'default'`
   *
   * Whether to perform lint-on-save during development using [eslint-loader](https://github.com/webpack-contrib/eslint-loader)
   */
  lintOnSave?: boolean | 'default' | 'warning' | 'error';
  /**
   * Pass options to the [PWA Plugin](https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwa)
   */
  pwa?: object;

  /**
   * set terser-webpack-plugin minify and terserOptions
   */
  terser?: {
    /**
     * Supported minify: [terser](https://github.com/webpack-contrib/terser-webpack-plugin#minify), [esbuild](https://github.com/webpack-contrib/terser-webpack-plugin#esbuild), [swc](https://github.com/webpack-contrib/terser-webpack-plugin#swc), [uglifyJs](https://github.com/webpack-contrib/terser-webpack-plugin#uglify-js). currently we do not allow custom minify function
     *
     * In the non-terser case, you should install the corresponding package (eg. `npm i esbuild -D`)
     *
     */
    minify: 'terser' | 'esbuild' | 'swc' | 'uglifyJs';
    /**
     * `terserOptions` options will be passed to minify
     *
     * [All options for `terser`](https://github.com/webpack-contrib/terser-webpack-plugin#terseroptions)
     *
     * [All options for `esbuild`](https://github.com/evanw/esbuild/blob/master/lib/shared/types.ts#L160-L174)
     *
     * [All options for `swc`](https://swc.rs/docs/config-js-minify)
     *
     * [All options for `uglifyJs`](https://github.com/mishoo/UglifyJS#minify-options)
     */
    terserOptions?: PredefinedOptions<import("terser").MinifyOptions>;
  };

  /**
   * This is an object that doesn't go through any schema validation, so it can be used to pass arbitrary options to 3rd party plugins
   */
  pluginOptions?: object;
}

type ConfigFunction = () => ProjectOptions

export { ProjectOptions, ConfigFunction }


code:
import { ServicePlugin } from '@vue/cli-service'

const servicePlugin: ServicePlugin = (api, options) => {
  const version = api.version
  api.assertVersion(4)
  api.assertVersion('^100')
  api.getCwd()
  api.resolve('src/main.js')
  api.hasPlugin('eslint')
  api.registerCommand(
    'lint',
    {
      description: 'lint and fix source files',
      usage: 'vue-cli-service lint [options] [...files]',
      options: {
        '--format [formatter]': 'specify formatter (default: stylish)'
      },
      details: 'For more options, see https://eslint.org/docs/user-guide/command-line-interface#options'
    },
    async args => {
      await require('./lint')(args, api)
    }
  )
  api.registerCommand('lint', args => {})

  api.chainWebpack(webpackConfig => {
    if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') {
      webpackConfig.devtool('eval-cheap-module-source-map')

      webpackConfig.plugin('hmr').use(require('webpack/lib/HotModuleReplacementPlugin'))

      webpackConfig.output.globalObject(`(typeof self !== 'undefined' ? self : this)`)
    }
  })

  api.configureWebpack(config => {
    config.output = {
      path: 'test-dist-2'
    }
  })

  api.configureWebpack(config => {
    return {
      devtool: config.devtool || 'source-map'
    }
  })

  api.resolveWebpackConfig()

  api.resolveWebpackConfig(api.resolveChainableWebpackConfig())

  const { cacheIdentifier, cacheDirectory } = api.genCacheConfig(
    'babel-loader',
    {
      '@babel/core': require('@babel/core/package.json').version,
      '@vue/babel-preset-app': require('@vue/babel-preset-app/package.json').version,
      'babel-loader': require('babel-loader/package.json').version,
      modern: !!process.env.VUE_CLI_MODERN_BUILD,
      browserslist: api.service.pkg.browserslist
    },
    ['babel.config.js', '.browserslistrc']
  )
}
export = servicePlugin


code:
import minimist = require('minimist')
import ChainableConfig = require('webpack-chain')
import webpack = require('webpack')
import WebpackDevServer = require('webpack-dev-server')
import express = require('express') // @types/webpack-dev-server depends on @types/express
import { ProjectOptions, ConfigFunction } from './ProjectOptions'

type RegisterCommandFn = (args: minimist.ParsedArgs, rawArgv: string[]) => any

type RegisterCommandOpts = Partial<{
  description: string
  usage: string
  options: {
    [flags: string]: string
  }
  details: string
}>

type WebpackChainFn = (chainableConfig: ChainableConfig) => void

type webpackRawConfigFn = ((config: webpack.Configuration) => webpack.Configuration | void) | webpack.Configuration

type DevServerConfigFn = (app: express.Application, server: WebpackDevServer) => void

interface CacheConfig {
  cacheDirectory: string
  cacheIdentifier: string
}
declare class PluginAPI {
  id: string

  service: any

  readonly version: string

  assertVersion(range: number | string): void

  /**
   * Current working directory.
   */
  getCwd(): string

  /**
   * Resolve path for a project.
   *
   * @param  _path - Relative path from project root
   * @return The resolved absolute path.
   */
  resolve(_path: string): string

  /**
   * Check if the project has a given plugin.
   *
   * @param id - Plugin id, can omit the (@vue/|vue-|@scope/vue)-cli-plugin- prefix
   * @return `boolean`
   */
  hasPlugin(id: string): boolean

  /**
   * Register a command that will become available as `vue-cli-service [name]`.
   *
   * @param name
   * @param  [opts]
   * @param  fn
   */
  registerCommand(name: string, fn: RegisterCommandFn): void
  registerCommand(name: string, opts: RegisterCommandOpts, fn: RegisterCommandFn): void

  /**
   * Register a function that will receive a chainable webpack config
   * the function is lazy and won't be called until `resolveWebpackConfig` is
   * called
   *
   * @param fn
   */
  chainWebpack(fn: WebpackChainFn): void

  /**
   * Register
   * - a webpack configuration object that will be merged into the config
   * OR
   * - a function that will receive the raw webpack config.
   *   the function can either mutate the config directly or return an object
   *   that will be merged into the config.
   *
   * @param fn
   */
  configureWebpack(fn: webpackRawConfigFn): void

  /**
   * Register a dev serve config function. It will receive the express `app`
   * instance of the dev server.
   *
   * @param fn
   */
  configureDevServer(fn: DevServerConfigFn): void

  /**
   * Resolve the final raw webpack config, that will be passed to webpack.
   *
   * @param [chainableConfig]
   * @return Raw webpack config.
   */
  resolveWebpackConfig(chainableConfig?: ChainableConfig): webpack.Configuration

  /**
   * Resolve an intermediate chainable webpack config instance, which can be
   * further tweaked before generating the final raw webpack config.
   * You can call this multiple times to generate different branches of the
   * base webpack config.
   * See https://github.com/mozilla-neutrino/webpack-chain
   *
   * @return ChainableWebpackConfig
   */
  resolveChainableWebpackConfig(): ChainableConfig

  /**
   * Generate a cache identifier from a number of variables
   */
  genCacheConfig(id: string, partialIdentifier: any, configFiles?: string | string[]): CacheConfig
}

/**
 * Service plugin serves for modifying webpack config,
 * creating new vue-cli service commands or changing existing commands
 *
 * @param api - A PluginAPI instance
 * @param options - An object containing project local options specified in vue.config.js,
 *    or in the "vue" field in package.json.
 */
type ServicePlugin = (
  api: PluginAPI,
  options: ProjectOptions
) => any

export { ProjectOptions, ServicePlugin, PluginAPI }
type UserConfig = ProjectOptions | ConfigFunction
export function defineConfig(config: UserConfig): UserConfig


code:
// this file is for cases where we need to access the
// webpack config as a file when using CLI commands.

let service = process.VUE_CLI_SERVICE

if (!service || process.env.VUE_CLI_API_MODE) {
  const Service = require('./lib/Service')
  service = new Service(process.env.VUE_CLI_CONTEXT || process.cwd())
  service.init(process.env.VUE_CLI_MODE || process.env.NODE_ENV)
}

module.exports = service.resolveWebpackConfig()


code:
# @vue/cli-shared-utils

> shared-utils for vue-cli


code:
[
  'env',
  'exit',
  'ipc',
  'logger',
  'module',
  'object',
  'openBrowser',
  'pkg',
  'pluginResolution',
  'pluginOrder',
  'launch',
  'request',
  'spinner',
  'validate'
].forEach(m => {
  Object.assign(exports, require(`./lib/${m}`))
})

exports.chalk = require('chalk')
exports.execa = require('execa')
exports.semver = require('semver')

Object.defineProperty(exports, 'installedBrowsers', {
  enumerable: true,
  get () {
    return exports.getInstalledBrowsers()
  }
})


code:
module.exports = function silence (logName, exports) {
  const logs = {}
  Object.keys(exports).forEach(key => {
    if (key !== 'error') {
      exports[key] = (...args) => {
        if (!logs[key]) logs[key] = []
        logs[key].push(args)
      }
    }
  })
  exports[logName] = logs
}


code:
const { execSync } = require('child_process')
const fs = require('fs')
const path = require('path')
const LRU = require('lru-cache')
const semver = require('semver')

let _hasYarn
const _yarnProjects = new LRU({
  max: 10,
  maxAge: 1000
})
let _hasGit
const _gitProjects = new LRU({
  max: 10,
  maxAge: 1000
})

// env detection
exports.hasYarn = () => {
  if (process.env.VUE_CLI_TEST) {
    return true
  }
  if (_hasYarn != null) {
    return _hasYarn
  }
  try {
    execSync('yarn --version', { stdio: 'ignore' })
    return (_hasYarn = true)
  } catch (e) {
    return (_hasYarn = false)
  }
}

exports.hasProjectYarn = (cwd) => {
  if (_yarnProjects.has(cwd)) {
    return checkYarn(_yarnProjects.get(cwd))
  }

  const lockFile = path.join(cwd, 'yarn.lock')
  const result = fs.existsSync(lockFile)
  _yarnProjects.set(cwd, result)
  return checkYarn(result)
}

function checkYarn (result) {
  if (result && !exports.hasYarn()) throw new Error(`The project seems to require yarn but it's not installed.`)
  return result
}

exports.hasGit = () => {
  if (process.env.VUE_CLI_TEST) {
    return true
  }
  if (_hasGit != null) {
    return _hasGit
  }
  try {
    execSync('git --version', { stdio: 'ignore' })
    return (_hasGit = true)
  } catch (e) {
    return (_hasGit = false)
  }
}

exports.hasProjectGit = (cwd) => {
  if (_gitProjects.has(cwd)) {
    return _gitProjects.get(cwd)
  }

  let result
  try {
    execSync('git status', { stdio: 'ignore', cwd })
    result = true
  } catch (e) {
    result = false
  }
  _gitProjects.set(cwd, result)
  return result
}

let _hasPnpm
let _pnpmVersion
const _pnpmProjects = new LRU({
  max: 10,
  maxAge: 1000
})

function getPnpmVersion () {
  if (_pnpmVersion != null) {
    return _pnpmVersion
  }
  try {
    _pnpmVersion = execSync('pnpm --version', {
      stdio: ['pipe', 'pipe', 'ignore']
    }).toString()
    // there's a critical bug in pnpm 2
    // https://github.com/pnpm/pnpm/issues/1678#issuecomment-469981972
    // so we only support pnpm >= 3.0.0
    _hasPnpm = true
  } catch (e) {}
  return _pnpmVersion || '0.0.0'
}

exports.hasPnpmVersionOrLater = (version) => {
  if (process.env.VUE_CLI_TEST) {
    return true
  }
  return semver.gte(getPnpmVersion(), version)
}

exports.hasPnpm3OrLater = () => {
  return this.hasPnpmVersionOrLater('3.0.0')
}

exports.hasProjectPnpm = (cwd) => {
  if (_pnpmProjects.has(cwd)) {
    return checkPnpm(_pnpmProjects.get(cwd))
  }

  const lockFile = path.join(cwd, 'pnpm-lock.yaml')
  const result = fs.existsSync(lockFile)
  _pnpmProjects.set(cwd, result)
  return checkPnpm(result)
}

function checkPnpm (result) {
  if (result && !exports.hasPnpm3OrLater()) {
    throw new Error(`The project seems to require pnpm${_hasPnpm ? ' >= 3' : ''} but it's not installed.`)
  }
  return result
}

const _npmProjects = new LRU({
  max: 10,
  maxAge: 1000
})
exports.hasProjectNpm = (cwd) => {
  if (_npmProjects.has(cwd)) {
    return _npmProjects.get(cwd)
  }

  const lockFile = path.join(cwd, 'package-lock.json')
  const result = fs.existsSync(lockFile)
  _npmProjects.set(cwd, result)
  return result
}

// OS
exports.isWindows = process.platform === 'win32'
exports.isMacintosh = process.platform === 'darwin'
exports.isLinux = process.platform === 'linux'

const browsers = {}
let hasCheckedBrowsers = false

function tryRun (cmd) {
  try {
    return execSync(cmd, {
      stdio: [0, 'pipe', 'ignore'],
      timeout: 10000
    }).toString().trim()
  } catch (e) {
    return ''
  }
}

function getLinuxAppVersion (binary) {
  return tryRun(`${binary} --version`).replace(/^.* ([^ ]*)/g, '$1')
}

function getMacAppVersion (bundleIdentifier) {
  const bundlePath = tryRun(`mdfind "kMDItemCFBundleIdentifier=='${bundleIdentifier}'"`)

  if (bundlePath) {
    return tryRun(`/usr/libexec/PlistBuddy -c Print:CFBundleShortVersionString ${
      bundlePath.replace(/(\s)/g, '\\ ')
    }/Contents/Info.plist`)
  }
}

exports.getInstalledBrowsers = () => {
  if (hasCheckedBrowsers) {
    return browsers
  }
  hasCheckedBrowsers = true

  if (exports.isLinux) {
    browsers.chrome = getLinuxAppVersion('google-chrome')
    browsers.firefox = getLinuxAppVersion('firefox')
  } else if (exports.isMacintosh) {
    browsers.chrome = getMacAppVersion('com.google.Chrome')
    browsers.firefox = getMacAppVersion('org.mozilla.firefox')
  } else if (exports.isWindows) {
    // get chrome stable version
    // https://stackoverflow.com/a/51773107/2302258
    const chromeQueryResult = tryRun(
      'reg query "HKLM\\Software\\Google\\Update\\Clients\\{8A69D345-D564-463c-AFF1-A69D9E530F96}" /v pv /reg:32'
    ) || tryRun(
      'reg query "HKCU\\Software\\Google\\Update\\Clients\\{8A69D345-D564-463c-AFF1-A69D9E530F96}" /v pv /reg:32'
    )
    if (chromeQueryResult) {
      const matched = chromeQueryResult.match(/REG_SZ\s+(\S*)$/)
      browsers.chrome = matched && matched[1]
    }

    // get firefox version
    // https://community.spiceworks.com/topic/111518-how-to-determine-version-of-installed-firefox-in-windows-batchscript
    const ffQueryResult = tryRun(
      'reg query "HKLM\\Software\\Mozilla\\Mozilla Firefox" /v CurrentVersion'
    )
    if (ffQueryResult) {
      const matched = ffQueryResult.match(/REG_SZ\s+(\S*)$/)
      browsers.firefox = matched && matched[1]
    }
  }

  return browsers
}


code:
exports.exitProcess = !process.env.VUE_CLI_API_MODE && !process.env.VUE_CLI_TEST

exports.exit = function (code) {
  if (exports.exitProcess) {
    process.exit(code)
  } else if (code > 0) {
    throw new Error(`Process exited with code ${code}`)
  }
}


code:
const ipc = require('@achrinza/node-ipc')

const DEFAULT_ID = process.env.VUE_CLI_IPC || 'vue-cli'
const DEFAULT_IDLE_TIMEOUT = 3000
const DEFAULT_OPTIONS = {
  networkId: DEFAULT_ID,
  autoConnect: true,
  disconnectOnIdle: false,
  idleTimeout: DEFAULT_IDLE_TIMEOUT,
  namespaceOnProject: true
}

const PROJECT_ID = process.env.VUE_CLI_PROJECT_ID

exports.IpcMessenger = class IpcMessenger {
  constructor (options = {}) {
    options = Object.assign({}, DEFAULT_OPTIONS, options)
    ipc.config.id = this.id = options.networkId
    ipc.config.retry = 1500
    ipc.config.silent = true

    this.connected = false
    this.connecting = false
    this.disconnecting = false
    this.queue = null
    this.options = options

    this.listeners = []

    this.disconnectTimeout = 15000
    this.idleTimer = null

    // Prevent forced process exit
    // (or else ipc messages may not be sent before kill)
    process.exit = code => {
      process.exitCode = code
    }

    this._reset()
  }

  checkConnection () {
    if (!ipc.of[this.id]) {
      this.connected = false
    }
  }

  send (data, type = 'message') {
    this.checkConnection()
    if (this.connected) {
      if (this.options.namespaceOnProject && PROJECT_ID) {
        data = {
          _projectId: PROJECT_ID,
          _data: data
        }
      }

      ipc.of[this.id].emit(type, data)

      clearTimeout(this.idleTimer)
      if (this.options.disconnectOnIdle) {
        this.idleTimer = setTimeout(() => {
          this.disconnect()
        }, this.options.idleTimeout)
      }
    } else {
      this.queue.push(data)
      if (this.options.autoConnect && !this.connecting) {
        this.connect()
      }
    }
  }

  connect () {
    this.checkConnection()
    if (this.connected || this.connecting) return
    this.connecting = true
    this.disconnecting = false
    ipc.connectTo(this.id, () => {
      this.connected = true
      this.connecting = false
      this.queue && this.queue.forEach(data => this.send(data))
      this.queue = null

      ipc.of[this.id].on('message', this._onMessage)
    })
  }

  disconnect () {
    this.checkConnection()
    if (!this.connected || this.disconnecting) return
    this.disconnecting = true
    this.connecting = false

    const ipcTimer = setTimeout(() => {
      this._disconnect()
    }, this.disconnectTimeout)

    this.send({ done: true }, 'ack')

    ipc.of[this.id].on('ack', data => {
      if (data.ok) {
        clearTimeout(ipcTimer)
        this._disconnect()
      }
    })
  }

  on (listener) {
    this.listeners.push(listener)
  }

  off (listener) {
    const index = this.listeners.indexOf(listener)
    if (index !== -1) this.listeners.splice(index, 1)
  }

  _reset () {
    this.queue = []
    this.connected = false
  }

  _disconnect () {
    this.connected = false
    this.disconnecting = false
    ipc.disconnect(this.id)
    this._reset()
  }

  _onMessage (data) {
    this.listeners.forEach(fn => {
      if (this.options.namespaceOnProject && data._projectId) {
        if (data._projectId === PROJECT_ID) {
          data = data._data
        } else {
          return
        }
      }
      fn(data)
    })
  }
}


code:
const launch = require('launch-editor')

exports.launch = (...args) => {
  const file = args[0]
  console.log(`Opening ${file}...`)
  let cb = args[args.length - 1]
  if (typeof cb !== 'function') {
    cb = null
  }
  launch(...args, (fileName, errorMessage) => {
    console.error(`Unable to open '${fileName}'`, errorMessage)
    console.log(`Try setting the EDITOR env variable. More info: https://github.com/yyx990803/launch-editor`)

    if (cb) cb(fileName, errorMessage)
  })
}


code:
const chalk = require('chalk')
const stripAnsi = require('strip-ansi')
const readline = require('readline')
const EventEmitter = require('events')

const { stopSpinner } = require('./spinner')

exports.events = new EventEmitter()

function _log (type, tag, message) {
  if (process.env.VUE_CLI_API_MODE && message) {
    exports.events.emit('log', {
      message,
      type,
      tag
    })
  }
}

const format = (label, msg) => {
  return msg.split('\n').map((line, i) => {
    return i === 0
      ? `${label} ${line}`
      : line.padStart(stripAnsi(label).length + line.length + 1)
  }).join('\n')
}

const chalkTag = msg => chalk.bgBlackBright.white.dim(` ${msg} `)

exports.log = (msg = '', tag = null) => {
  tag ? console.log(format(chalkTag(tag), msg)) : console.log(msg)
  _log('log', tag, msg)
}

exports.info = (msg, tag = null) => {
  console.log(format(chalk.bgBlue.black(' INFO ') + (tag ? chalkTag(tag) : ''), msg))
  _log('info', tag, msg)
}

exports.done = (msg, tag = null) => {
  console.log(format(chalk.bgGreen.black(' DONE ') + (tag ? chalkTag(tag) : ''), msg))
  _log('done', tag, msg)
}

exports.warn = (msg, tag = null) => {
  console.warn(format(chalk.bgYellow.black(' WARN ') + (tag ? chalkTag(tag) : ''), chalk.yellow(msg)))
  _log('warn', tag, msg)
}

exports.error = (msg, tag = null) => {
  stopSpinner()
  console.error(format(chalk.bgRed(' ERROR ') + (tag ? chalkTag(tag) : ''), chalk.red(msg)))
  _log('error', tag, msg)
  if (msg instanceof Error) {
    console.error(msg.stack)
    _log('error', tag, msg.stack)
  }
}

exports.clearConsole = title => {
  if (process.stdout.isTTY) {
    const blank = '\n'.repeat(process.stdout.rows)
    console.log(blank)
    readline.cursorTo(process.stdout, 0, 0)
    readline.clearScreenDown(process.stdout)
    if (title) {
      console.log(title)
    }
  }
}

// silent all logs except errors during tests and keep record
if (process.env.VUE_CLI_TEST) {
  require('./_silence')('logs', exports)
}


code:
const Module = require('module')
const path = require('path')

const semver = require('semver')

// https://github.com/benmosher/eslint-plugin-import/pull/1591
// https://github.com/benmosher/eslint-plugin-import/pull/1602
// Polyfill Node's `Module.createRequireFromPath` if not present (added in Node v10.12.0)
// Use `Module.createRequire` if available (added in Node v12.2.0)
// eslint-disable-next-line node/no-deprecated-api
const createRequire = Module.createRequire || Module.createRequireFromPath || function (filename) {
  const mod = new Module(filename, null)
  mod.filename = filename
  mod.paths = Module._nodeModulePaths(path.dirname(filename))

  mod._compile(`module.exports = require;`, filename)

  return mod.exports
}

function resolveFallback (request, options) {
  const isMain = false
  const fakeParent = new Module('', null)

  const paths = []

  for (let i = 0; i < options.paths.length; i++) {
    const p = options.paths[i]
    fakeParent.paths = Module._nodeModulePaths(p)
    const lookupPaths = Module._resolveLookupPaths(request, fakeParent, true)

    if (!paths.includes(p)) paths.push(p)

    for (let j = 0; j < lookupPaths.length; j++) {
      if (!paths.includes(lookupPaths[j])) paths.push(lookupPaths[j])
    }
  }

  const filename = Module._findPath(request, paths, isMain)
  if (!filename) {
    const err = new Error(`Cannot find module '${request}'`)
    err.code = 'MODULE_NOT_FOUND'
    throw err
  }
  return filename
}

const resolve = semver.satisfies(process.version, '>=10.0.0')
  ? require.resolve
  : resolveFallback

exports.resolveModule = function (request, context) {
  // createRequire doesn't work with jest mock modules
  // (which we used in migrator for inquirer, and in tests for cli-service)
  // TODO: it's supported in Jest 25
  if (process.env.VUE_CLI_TEST && (request.endsWith('migrator') || context === '/')) {
    return request
  }

  let resolvedPath
  try {
    try {
      resolvedPath = createRequire(path.resolve(context, 'package.json')).resolve(request)
    } catch (e) {
      resolvedPath = resolve(request, { paths: [context] })
    }
  } catch (e) {}
  return resolvedPath
}

exports.loadModule = function (request, context, force = false) {
  // createRequire doesn't work with jest mocked fs
  // (which we used in tests for cli-service)
  if (process.env.VUE_CLI_TEST && context === '/') {
    return require(request)
  }

  try {
    return createRequire(path.resolve(context, 'package.json'))(request)
  } catch (e) {
    const resolvedPath = exports.resolveModule(request, context)
    if (resolvedPath) {
      if (force) {
        clearRequireCache(resolvedPath)
      }
      return require(resolvedPath)
    }
  }
}

exports.clearModule = function (request, context) {
  const resolvedPath = exports.resolveModule(request, context)
  if (resolvedPath) {
    clearRequireCache(resolvedPath)
  }
}

function clearRequireCache (id, map = new Map()) {
  const module = require.cache[id]
  if (module) {
    map.set(id, true)
    // Clear children modules
    module.children.forEach(child => {
      if (!map.get(child.id)) clearRequireCache(child.id, map)
    })
    delete require.cache[id]
  }
}


code:
exports.set = function (target, path, value) {
  const fields = path.split('.')
  let obj = target
  const l = fields.length
  for (let i = 0; i < l - 1; i++) {
    const key = fields[i]
    if (!obj[key]) {
      obj[key] = {}
    }
    obj = obj[key]
  }
  obj[fields[l - 1]] = value
}

exports.get = function (target, path) {
  const fields = path.split('.')
  let obj = target
  const l = fields.length
  for (let i = 0; i < l - 1; i++) {
    const key = fields[i]
    if (!obj[key]) {
      return undefined
    }
    obj = obj[key]
  }
  return obj[fields[l - 1]]
}

exports.unset = function (target, path) {
  const fields = path.split('.')
  let obj = target
  const l = fields.length
  const objs = []
  for (let i = 0; i < l - 1; i++) {
    const key = fields[i]
    if (!obj[key]) {
      return
    }
    objs.unshift({ parent: obj, key, value: obj[key] })
    obj = obj[key]
  }
  delete obj[fields[l - 1]]
  // Clear empty objects
  for (const { parent, key, value } of objs) {
    if (!Object.keys(value).length) {
      delete parent[key]
    }
  }
}


code:
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file at
 * https://github.com/facebook/create-react-app/blob/master/LICENSE
 */

const open = require('open')
const execa = require('execa')
const chalk = require('chalk')
const execSync = require('child_process').execSync

// https://github.com/sindresorhus/open#app
const OSX_CHROME = 'google chrome'

const Actions = Object.freeze({
  NONE: 0,
  BROWSER: 1,
  SCRIPT: 2
})

function getBrowserEnv () {
  // Attempt to honor this environment variable.
  // It is specific to the operating system.
  // See https://github.com/sindresorhus/open#app for documentation.
  const value = process.env.BROWSER
  let action
  if (!value) {
    // Default.
    action = Actions.BROWSER
  } else if (value.toLowerCase().endsWith('.js')) {
    action = Actions.SCRIPT
  } else if (value.toLowerCase() === 'none') {
    action = Actions.NONE
  } else {
    action = Actions.BROWSER
  }
  return { action, value }
}

function executeNodeScript (scriptPath, url) {
  const extraArgs = process.argv.slice(2)
  const child = execa('node', [scriptPath, ...extraArgs, url], {
    stdio: 'inherit'
  })
  child.on('close', code => {
    if (code !== 0) {
      console.log()
      console.log(
        chalk.red(
          'The script specified as BROWSER environment variable failed.'
        )
      )
      console.log(chalk.cyan(scriptPath) + ' exited with code ' + code + '.')
      console.log()
    }
  })
  return true
}

function startBrowserProcess (browser, url) {
  // If we're on OS X, the user hasn't specifically
  // requested a different browser, we can try opening
  // Chrome with AppleScript. This lets us reuse an
  // existing tab when possible instead of creating a new one.
  const shouldTryOpenChromeWithAppleScript =
    process.platform === 'darwin' &&
    (typeof browser !== 'string' || browser === OSX_CHROME)

  if (shouldTryOpenChromeWithAppleScript) {
    try {
      // Try our best to reuse existing tab
      // on OS X Google Chrome with AppleScript
      execSync('ps cax | grep "Google Chrome"')
      execSync('osascript openChrome.applescript "' + encodeURI(url) + '"', {
        cwd: __dirname,
        stdio: 'ignore'
      })
      return true
    } catch (err) {
      // Ignore errors.
    }
  }

  // Another special case: on OS X, check if BROWSER has been set to "open".
  // In this case, instead of passing the string `open` to `open` function (which won't work),
  // just ignore it (thus ensuring the intended behavior, i.e. opening the system browser):
  // https://github.com/facebook/create-react-app/pull/1690#issuecomment-283518768
  if (process.platform === 'darwin' && browser === 'open') {
    browser = undefined
  }

  // Fallback to open
  // (It will always open new tab)
  try {
    const options = { app: { name: browser }, url: true }
    open(url, options).catch(() => {}) // Prevent `unhandledRejection` error.
    return true
  } catch (err) {
    return false
  }
}

/**
 * Reads the BROWSER environment variable and decides what to do with it. Returns
 * true if it opened a browser or ran a node.js script, otherwise false.
 */
exports.openBrowser = function (url) {
  const { action, value } = getBrowserEnv()
  switch (action) {
  case Actions.NONE:
    // Special case: BROWSER="none" will prevent opening completely.
    return false
  case Actions.SCRIPT:
    return executeNodeScript(value, url)
  case Actions.BROWSER:
    return startBrowserProcess(value, url)
  default:
    throw new Error('Not implemented.')
  }
}


code:
(*
Copyright (c) 2015-present, Facebook, Inc.

This source code is licensed under the MIT license found in the
LICENSE file at
https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
*)

property targetTab: null
property targetTabIndex: -1
property targetWindow: null

on run argv
  set theURL to item 1 of argv

  with timeout of 2 seconds
    tell application "Chrome"

      if (count every window) = 0 then
        make new window
      end if

      -- 1: Looking for tab running debugger
      -- then, Reload debugging tab if found
      -- then return
      set found to my lookupTabWithUrl(theURL)
      if found then
        set targetWindow's active tab index to targetTabIndex
        tell targetTab to reload
        tell targetWindow to activate
        set index of targetWindow to 1
        return
      end if

      -- 2: Looking for Empty tab
      -- In case debugging tab was not found
      -- We try to find an empty tab instead
      set found to my lookupTabWithUrl("chrome://newtab/")
      if found then
        set targetWindow's active tab index to targetTabIndex
        set URL of targetTab to theURL
        tell targetWindow to activate
        return
      end if

      -- 3: Create new tab
      -- both debugging and empty tab were not found
      -- make a new tab with url
      tell window 1
        activate
        make new tab with properties {URL:theURL}
      end tell
    end tell
  end timeout
end run

-- Function:
-- Lookup tab with given url
-- if found, store tab, index, and window in properties
-- (properties were declared on top of file)
on lookupTabWithUrl(lookupUrl)
  tell application "Chrome"
    -- Find a tab with the given url
    set found to false
    set theTabIndex to -1
    repeat with theWindow in every window
      set theTabIndex to 0
      repeat with theTab in every tab of theWindow
        set theTabIndex to theTabIndex + 1
        if (theTab's URL as string) contains lookupUrl then
          -- assign tab, tab index, and window to properties
          set targetTab to theTab
          set targetTabIndex to theTabIndex
          set targetWindow to theWindow
          set found to true
          exit repeat
        end if
      end repeat

      if found then
        exit repeat
      end if
    end repeat
  end tell
  return found
end lookupTabWithUrl


code:
const fs = require('fs')
const path = require('path')
const readPkg = require('read-pkg')

exports.resolvePkg = function (context) {
  if (fs.existsSync(path.join(context, 'package.json'))) {
    return readPkg.sync({ cwd: context })
  }
  return {}
}


code:
// @ts-check
const { warn } = require('./logger')

/** @typedef {{after?: string|Array<string>}} Apply */
/** @typedef {{id: string, apply: Apply}} Plugin */
/** @typedef {{after: Set<string>}} OrderParams */

/** @type {Map<string, OrderParams>} */
const orderParamsCache = new Map()

/**
 *
 * @param {Plugin} plugin
 * @returns {OrderParams}
 */
function getOrderParams (plugin) {
  if (!process.env.VUE_CLI_TEST && orderParamsCache.has(plugin.id)) {
    return orderParamsCache.get(plugin.id)
  }
  const apply = plugin.apply

  let after = new Set()
  if (typeof apply.after === 'string') {
    after = new Set([apply.after])
  } else if (Array.isArray(apply.after)) {
    after = new Set(apply.after)
  }
  if (!process.env.VUE_CLI_TEST) {
    orderParamsCache.set(plugin.id, { after })
  }

  return { after }
}

/**
 * See leetcode 210
 * @param {Array<Plugin>} plugins
 * @returns {Array<Plugin>}
 */
function topologicalSorting (plugins) {
  /** @type {Map<string, Plugin>} */
  const pluginsMap = new Map(plugins.map(p => [p.id, p]))

  /** @type {Map<Plugin, number>} */
  const indegrees = new Map()

  /** @type {Map<Plugin, Array<Plugin>>} */
  const graph = new Map()

  plugins.forEach(p => {
    const after = getOrderParams(p).after
    indegrees.set(p, after.size)
    if (after.size === 0) return
    for (const id of after) {
      const prerequisite = pluginsMap.get(id)
      // remove invalid data
      if (!prerequisite) {
        indegrees.set(p, indegrees.get(p) - 1)
        continue
      }

      if (!graph.has(prerequisite)) {
        graph.set(prerequisite, [])
      }
      graph.get(prerequisite).push(p)
    }
  })

  const res = []
  const queue = []
  indegrees.forEach((d, p) => {
    if (d === 0) queue.push(p)
  })
  while (queue.length) {
    const cur = queue.shift()
    res.push(cur)
    const neighbors = graph.get(cur)
    if (!neighbors) continue

    neighbors.forEach(n => {
      const degree = indegrees.get(n) - 1
      indegrees.set(n, degree)
      if (degree === 0) {
        queue.push(n)
      }
    })
  }
  const valid = res.length === plugins.length
  if (!valid) {
    warn(`No proper plugin execution order found.`)
    return plugins
  }
  return res
}

/**
 * Arrange plugins by 'after' property.
 * @param {Array<Plugin>} plugins
 * @returns {Array<Plugin>}
 */
function sortPlugins (plugins) {
  if (plugins.length < 2) return plugins

  return topologicalSorting(plugins)
}

module.exports = {
  topologicalSorting,
  sortPlugins
}


code:
const pluginRE = /^(@vue\/|vue-|@[\w-]+(\.)?[\w-]+\/vue-)cli-plugin-/
const scopeRE = /^@[\w-]+(\.)?[\w-]+\//
const officialRE = /^@vue\//

const officialPlugins = [
  'babel',
  'e2e-cypress',
  'e2e-nightwatch',
  'e2e-webdriverio',
  'eslint',
  'pwa',
  'router',
  'typescript',
  'unit-jest',
  'unit-mocha',
  'vuex',
  'webpack-4'
]

exports.isPlugin = id => pluginRE.test(id)

exports.isOfficialPlugin = id => exports.isPlugin(id) && officialRE.test(id)

exports.toShortPluginId = id => id.replace(pluginRE, '')

exports.resolvePluginId = id => {
  // already full id
  // e.g. vue-cli-plugin-foo, @vue/cli-plugin-foo, @bar/vue-cli-plugin-foo
  if (pluginRE.test(id)) {
    return id
  }

  if (id === '@vue/cli-service') {
    return id
  }

  if (officialPlugins.includes(id)) {
    return `@vue/cli-plugin-${id}`
  }
  // scoped short
  // e.g. @vue/foo, @bar/foo
  if (id.charAt(0) === '@') {
    const scopeMatch = id.match(scopeRE)
    if (scopeMatch) {
      const scope = scopeMatch[0]
      const shortId = id.replace(scopeRE, '')
      return `${scope}${scope === '@vue/' ? `` : `vue-`}cli-plugin-${shortId}`
    }
  }
  // default short
  // e.g. foo
  return `vue-cli-plugin-${id}`
}

exports.matchesPluginId = (input, full) => {
  const short = full.replace(pluginRE, '')
  return (
    // input is full
    full === input ||
    // input is short without scope
    short === input ||
    // input is short with scope
    short === input.replace(scopeRE, '')
  )
}

exports.getPluginLink = id => {
  if (officialRE.test(id)) {
    return `https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-${
      exports.toShortPluginId(id)
    }`
  }
  let pkg = {}
  try {
    pkg = require(`${id}/package.json`)
  } catch (e) {}
  return (
    pkg.homepage ||
    (pkg.repository && pkg.repository.url) ||
    `https://www.npmjs.com/package/${id.replace(`/`, `%2F`)}`
  )
}


code:
exports.request = {
  get (url, opts) {
    // lazy require
    const fetch = require('node-fetch')
    const reqOpts = {
      method: 'GET',
      timeout: 30000,
      ...opts
    }

    return fetch(url, reqOpts).then(result => result.json())
  }
}


code:
const ora = require('ora')
const chalk = require('chalk')

const spinner = ora()
let lastMsg = null
let isPaused = false

exports.logWithSpinner = (symbol, msg) => {
  if (!msg) {
    msg = symbol
    symbol = chalk.green('✔')
  }
  if (lastMsg) {
    spinner.stopAndPersist({
      symbol: lastMsg.symbol,
      text: lastMsg.text
    })
  }
  spinner.text = ' ' + msg
  lastMsg = {
    symbol: symbol + ' ',
    text: msg
  }
  spinner.start()
}

exports.stopSpinner = (persist) => {
  if (!spinner.isSpinning) {
    return
  }

  if (lastMsg && persist !== false) {
    spinner.stopAndPersist({
      symbol: lastMsg.symbol,
      text: lastMsg.text
    })
  } else {
    spinner.stop()
  }
  lastMsg = null
}

exports.pauseSpinner = () => {
  if (spinner.isSpinning) {
    spinner.stop()
    isPaused = true
  }
}

exports.resumeSpinner = () => {
  if (isPaused) {
    spinner.start()
    isPaused = false
  }
}

exports.failSpinner = (text) => {
  spinner.fail(text)
}

// silent all logs except errors during tests and keep record
if (process.env.VUE_CLI_TEST) {
  require('./_silence')('spinner', exports)
}


code:
const { exit } = require('./exit')

// proxy to joi for option validation
exports.createSchema = fn => {
  const joi = require('joi')

  let schema = fn(joi)
  if (typeof schema === 'object' && typeof schema.validate !== 'function') {
    schema = joi.object(schema)
  }

  return schema
}

exports.validate = (obj, schema, cb) => {
  const { error } = schema.validate(obj)
  if (error) {
    cb(error.details[0].message)

    if (process.env.VUE_CLI_TEST) {
      throw error
    } else {
      exit(1)
    }
  }
}

exports.validateSync = (obj, schema) => {
  const { error } = schema.validate(obj)
  if (error) {
    throw error
  }
}


code:
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")

case `uname` in
    *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac

if [ -x "$basedir/node" ]; then
  exec "$basedir/node"  "$basedir/../semver/bin/semver.js" "$@"
else
  exec node  "$basedir/../semver/bin/semver.js" "$@"
fi


code:
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0

IF EXIST "%dp0%\node.exe" (
  SET "_prog=%dp0%\node.exe"
) ELSE (
  SET "_prog=node"
  SET PATHEXT=%PATHEXT:;.JS;=;%
)

endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%"  "%dp0%\..\semver\bin\semver.js" %*


code:
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent

$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
  # Fix case when both the Windows and Linux builds of Node
  # are installed in the same directory
  $exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
  # Support pipeline input
  if ($MyInvocation.ExpectingInput) {
    $input | & "$basedir/node$exe"  "$basedir/../semver/bin/semver.js" $args
  } else {
    & "$basedir/node$exe"  "$basedir/../semver/bin/semver.js" $args
  }
  $ret=$LASTEXITCODE
} else {
  # Support pipeline input
  if ($MyInvocation.ExpectingInput) {
    $input | & "node$exe"  "$basedir/../semver/bin/semver.js" $args
  } else {
    & "node$exe"  "$basedir/../semver/bin/semver.js" $args
  }
  $ret=$LASTEXITCODE
}
exit $ret


code:
declare type CSSColor =
	| 'aliceblue'
	| 'antiquewhite'
	| 'aqua'
	| 'aquamarine'
	| 'azure'
	| 'beige'
	| 'bisque'
	| 'black'
	| 'blanchedalmond'
	| 'blue'
	| 'blueviolet'
	| 'brown'
	| 'burlywood'
	| 'cadetblue'
	| 'chartreuse'
	| 'chocolate'
	| 'coral'
	| 'cornflowerblue'
	| 'cornsilk'
	| 'crimson'
	| 'cyan'
	| 'darkblue'
	| 'darkcyan'
	| 'darkgoldenrod'
	| 'darkgray'
	| 'darkgreen'
	| 'darkgrey'
	| 'darkkhaki'
	| 'darkmagenta'
	| 'darkolivegreen'
	| 'darkorange'
	| 'darkorchid'
	| 'darkred'
	| 'darksalmon'
	| 'darkseagreen'
	| 'darkslateblue'
	| 'darkslategray'
	| 'darkslategrey'
	| 'darkturquoise'
	| 'darkviolet'
	| 'deeppink'
	| 'deepskyblue'
	| 'dimgray'
	| 'dimgrey'
	| 'dodgerblue'
	| 'firebrick'
	| 'floralwhite'
	| 'forestgreen'
	| 'fuchsia'
	| 'gainsboro'
	| 'ghostwhite'
	| 'gold'
	| 'goldenrod'
	| 'gray'
	| 'green'
	| 'greenyellow'
	| 'grey'
	| 'honeydew'
	| 'hotpink'
	| 'indianred'
	| 'indigo'
	| 'ivory'
	| 'khaki'
	| 'lavender'
	| 'lavenderblush'
	| 'lawngreen'
	| 'lemonchiffon'
	| 'lightblue'
	| 'lightcoral'
	| 'lightcyan'
	| 'lightgoldenrodyellow'
	| 'lightgray'
	| 'lightgreen'
	| 'lightgrey'
	| 'lightpink'
	| 'lightsalmon'
	| 'lightseagreen'
	| 'lightskyblue'
	| 'lightslategray'
	| 'lightslategrey'
	| 'lightsteelblue'
	| 'lightyellow'
	| 'lime'
	| 'limegreen'
	| 'linen'
	| 'magenta'
	| 'maroon'
	| 'mediumaquamarine'
	| 'mediumblue'
	| 'mediumorchid'
	| 'mediumpurple'
	| 'mediumseagreen'
	| 'mediumslateblue'
	| 'mediumspringgreen'
	| 'mediumturquoise'
	| 'mediumvioletred'
	| 'midnightblue'
	| 'mintcream'
	| 'mistyrose'
	| 'moccasin'
	| 'navajowhite'
	| 'navy'
	| 'oldlace'
	| 'olive'
	| 'olivedrab'
	| 'orange'
	| 'orangered'
	| 'orchid'
	| 'palegoldenrod'
	| 'palegreen'
	| 'paleturquoise'
	| 'palevioletred'
	| 'papayawhip'
	| 'peachpuff'
	| 'peru'
	| 'pink'
	| 'plum'
	| 'powderblue'
	| 'purple'
	| 'rebeccapurple'
	| 'red'
	| 'rosybrown'
	| 'royalblue'
	| 'saddlebrown'
	| 'salmon'
	| 'sandybrown'
	| 'seagreen'
	| 'seashell'
	| 'sienna'
	| 'silver'
	| 'skyblue'
	| 'slateblue'
	| 'slategray'
	| 'slategrey'
	| 'snow'
	| 'springgreen'
	| 'steelblue'
	| 'tan'
	| 'teal'
	| 'thistle'
	| 'tomato'
	| 'turquoise'
	| 'violet'
	| 'wheat'
	| 'white'
	| 'whitesmoke'
	| 'yellow'
	| 'yellowgreen';

declare namespace ansiStyles {
	interface ColorConvert {
		/**
		The RGB color space.

		@param red - (`0`-`255`)
		@param green - (`0`-`255`)
		@param blue - (`0`-`255`)
		*/
		rgb(red: number, green: number, blue: number): string;

		/**
		The RGB HEX color space.

		@param hex - A hexadecimal string containing RGB data.
		*/
		hex(hex: string): string;

		/**
		@param keyword - A CSS color name.
		*/
		keyword(keyword: CSSColor): string;

		/**
		The HSL color space.

		@param hue - (`0`-`360`)
		@param saturation - (`0`-`100`)
		@param lightness - (`0`-`100`)
		*/
		hsl(hue: number, saturation: number, lightness: number): string;

		/**
		The HSV color space.

		@param hue - (`0`-`360`)
		@param saturation - (`0`-`100`)
		@param value - (`0`-`100`)
		*/
		hsv(hue: number, saturation: number, value: number): string;

		/**
		The HSV color space.

		@param hue - (`0`-`360`)
		@param whiteness - (`0`-`100`)
		@param blackness - (`0`-`100`)
		*/
		hwb(hue: number, whiteness: number, blackness: number): string;

		/**
		Use a [4-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4-bit) to set text color.
		*/
		ansi(ansi: number): string;

		/**
		Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
		*/
		ansi256(ansi: number): string;
	}

	interface CSPair {
		/**
		The ANSI terminal control sequence for starting this style.
		*/
		readonly open: string;

		/**
		The ANSI terminal control sequence for ending this style.
		*/
		readonly close: string;
	}

	interface ColorBase {
		readonly ansi: ColorConvert;
		readonly ansi256: ColorConvert;
		readonly ansi16m: ColorConvert;

		/**
		The ANSI terminal control sequence for ending this color.
		*/
		readonly close: string;
	}

	interface Modifier {
		/**
		Resets the current color chain.
		*/
		readonly reset: CSPair;

		/**
		Make text bold.
		*/
		readonly bold: CSPair;

		/**
		Emitting only a small amount of light.
		*/
		readonly dim: CSPair;

		/**
		Make text italic. (Not widely supported)
		*/
		readonly italic: CSPair;

		/**
		Make text underline. (Not widely supported)
		*/
		readonly underline: CSPair;

		/**
		Inverse background and foreground colors.
		*/
		readonly inverse: CSPair;

		/**
		Prints the text, but makes it invisible.
		*/
		readonly hidden: CSPair;

		/**
		Puts a horizontal line through the center of the text. (Not widely supported)
		*/
		readonly strikethrough: CSPair;
	}

	interface ForegroundColor {
		readonly black: CSPair;
		readonly red: CSPair;
		readonly green: CSPair;
		readonly yellow: CSPair;
		readonly blue: CSPair;
		readonly cyan: CSPair;
		readonly magenta: CSPair;
		readonly white: CSPair;

		/**
		Alias for `blackBright`.
		*/
		readonly gray: CSPair;

		/**
		Alias for `blackBright`.
		*/
		readonly grey: CSPair;

		readonly blackBright: CSPair;
		readonly redBright: CSPair;
		readonly greenBright: CSPair;
		readonly yellowBright: CSPair;
		readonly blueBright: CSPair;
		readonly cyanBright: CSPair;
		readonly magentaBright: CSPair;
		readonly whiteBright: CSPair;
	}

	interface BackgroundColor {
		readonly bgBlack: CSPair;
		readonly bgRed: CSPair;
		readonly bgGreen: CSPair;
		readonly bgYellow: CSPair;
		readonly bgBlue: CSPair;
		readonly bgCyan: CSPair;
		readonly bgMagenta: CSPair;
		readonly bgWhite: CSPair;

		/**
		Alias for `bgBlackBright`.
		*/
		readonly bgGray: CSPair;

		/**
		Alias for `bgBlackBright`.
		*/
		readonly bgGrey: CSPair;

		readonly bgBlackBright: CSPair;
		readonly bgRedBright: CSPair;
		readonly bgGreenBright: CSPair;
		readonly bgYellowBright: CSPair;
		readonly bgBlueBright: CSPair;
		readonly bgCyanBright: CSPair;
		readonly bgMagentaBright: CSPair;
		readonly bgWhiteBright: CSPair;
	}
}

declare const ansiStyles: {
	readonly modifier: ansiStyles.Modifier;
	readonly color: ansiStyles.ForegroundColor & ansiStyles.ColorBase;
	readonly bgColor: ansiStyles.BackgroundColor & ansiStyles.ColorBase;
	readonly codes: ReadonlyMap<number, number>;
} & ansiStyles.BackgroundColor & ansiStyles.ForegroundColor & ansiStyles.Modifier;

export = ansiStyles;


code:
'use strict';

const wrapAnsi16 = (fn, offset) => (...args) => {
	const code = fn(...args);
	return `\u001B[${code + offset}m`;
};

const wrapAnsi256 = (fn, offset) => (...args) => {
	const code = fn(...args);
	return `\u001B[${38 + offset};5;${code}m`;
};

const wrapAnsi16m = (fn, offset) => (...args) => {
	const rgb = fn(...args);
	return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
};

const ansi2ansi = n => n;
const rgb2rgb = (r, g, b) => [r, g, b];

const setLazyProperty = (object, property, get) => {
	Object.defineProperty(object, property, {
		get: () => {
			const value = get();

			Object.defineProperty(object, property, {
				value,
				enumerable: true,
				configurable: true
			});

			return value;
		},
		enumerable: true,
		configurable: true
	});
};

/** @type {typeof import('color-convert')} */
let colorConvert;
const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
	if (colorConvert === undefined) {
		colorConvert = require('color-convert');
	}

	const offset = isBackground ? 10 : 0;
	const styles = {};

	for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
		const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
		if (sourceSpace === targetSpace) {
			styles[name] = wrap(identity, offset);
		} else if (typeof suite === 'object') {
			styles[name] = wrap(suite[targetSpace], offset);
		}
	}

	return styles;
};

function assembleStyles() {
	const codes = new Map();
	const styles = {
		modifier: {
			reset: [0, 0],
			// 21 isn't widely supported and 22 does the same thing
			bold: [1, 22],
			dim: [2, 22],
			italic: [3, 23],
			underline: [4, 24],
			inverse: [7, 27],
			hidden: [8, 28],
			strikethrough: [9, 29]
		},
		color: {
			black: [30, 39],
			red: [31, 39],
			green: [32, 39],
			yellow: [33, 39],
			blue: [34, 39],
			magenta: [35, 39],
			cyan: [36, 39],
			white: [37, 39],

			// Bright color
			blackBright: [90, 39],
			redBright: [91, 39],
			greenBright: [92, 39],
			yellowBright: [93, 39],
			blueBright: [94, 39],
			magentaBright: [95, 39],
			cyanBright: [96, 39],
			whiteBright: [97, 39]
		},
		bgColor: {
			bgBlack: [40, 49],
			bgRed: [41, 49],
			bgGreen: [42, 49],
			bgYellow: [43, 49],
			bgBlue: [44, 49],
			bgMagenta: [45, 49],
			bgCyan: [46, 49],
			bgWhite: [47, 49],

			// Bright color
			bgBlackBright: [100, 49],
			bgRedBright: [101, 49],
			bgGreenBright: [102, 49],
			bgYellowBright: [103, 49],
			bgBlueBright: [104, 49],
			bgMagentaBright: [105, 49],
			bgCyanBright: [106, 49],
			bgWhiteBright: [107, 49]
		}
	};

	// Alias bright black as gray (and grey)
	styles.color.gray = styles.color.blackBright;
	styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
	styles.color.grey = styles.color.blackBright;
	styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;

	for (const [groupName, group] of Object.entries(styles)) {
		for (const [styleName, style] of Object.entries(group)) {
			styles[styleName] = {
				open: `\u001B[${style[0]}m`,
				close: `\u001B[${style[1]}m`
			};

			group[styleName] = styles[styleName];

			codes.set(style[0], style[1]);
		}

		Object.defineProperty(styles, groupName, {
			value: group,
			enumerable: false
		});
	}

	Object.defineProperty(styles, 'codes', {
		value: codes,
		enumerable: false
	});

	styles.color.close = '\u001B[39m';
	styles.bgColor.close = '\u001B[49m';

	setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
	setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
	setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
	setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
	setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
	setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));

	return styles;
}

// Make the export immutable
Object.defineProperty(module, 'exports', {
	enumerable: true,
	get: assembleStyles
});


ansi-styles

description: ANSI escape codes for styling strings in the terminal

repository: chalk/ansi-styles

test: xo && ava && tsd

screenshot: svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor

keywords: ansi styles color colour colors terminal console cli string tty escape formatting rgb 256 shell xterm log logging command-line text


code:
# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles)

> [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal

You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings.

<img src="screenshot.svg" width="900">

## Install

```
$ npm install ansi-styles
```

## Usage

```js
const style = require('ansi-styles');

console.log(`${style.green.open}Hello world!${style.green.close}`);

// Color conversion between 16/256/truecolor
// NOTE: If conversion goes to 16 colors or 256 colors, the original color
//       may be degraded to fit that color palette. This means terminals
//       that do not support 16 million colors will best-match the
//       original color.
console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close);
console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close);
console.log(style.color.ansi16m.hex('#abcdef') + 'Hello world!' + style.color.close);
```

## API

Each style has an `open` and `close` property.

## Styles

### Modifiers

- `reset`
- `bold`
- `dim`
- `italic` *(Not widely supported)*
- `underline`
- `inverse`
- `hidden`
- `strikethrough` *(Not widely supported)*

### Colors

- `black`
- `red`
- `green`
- `yellow`
- `blue`
- `magenta`
- `cyan`
- `white`
- `blackBright` (alias: `gray`, `grey`)
- `redBright`
- `greenBright`
- `yellowBright`
- `blueBright`
- `magentaBright`
- `cyanBright`
- `whiteBright`

### Background colors

- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
- `bgBlackBright` (alias: `bgGray`, `bgGrey`)
- `bgRedBright`
- `bgGreenBright`
- `bgYellowBright`
- `bgBlueBright`
- `bgMagentaBright`
- `bgCyanBright`
- `bgWhiteBright`

## Advanced usage

By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module.

- `style.modifier`
- `style.color`
- `style.bgColor`

###### Example

```js
console.log(style.color.green.open);
```

Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values.

###### Example

```js
console.log(style.codes.get(36));
//=> 39
```

## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728)

`ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors.

The following color spaces from `color-convert` are supported:

- `rgb`
- `hex`
- `keyword`
- `hsl`
- `hsv`
- `hwb`
- `ansi`
- `ansi256`

To use these, call the associated conversion function with the intended output, for example:

```js
style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code
style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code

style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code
style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code

style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code
style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code
```

## Related

- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal

## Maintainers

- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)

## For enterprise

Available as part of the Tidelift Subscription.

The maintainers of `ansi-styles` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)


code:
/**
Basic foreground colors.

[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
*/
declare type ForegroundColor =
	| 'black'
	| 'red'
	| 'green'
	| 'yellow'
	| 'blue'
	| 'magenta'
	| 'cyan'
	| 'white'
	| 'gray'
	| 'grey'
	| 'blackBright'
	| 'redBright'
	| 'greenBright'
	| 'yellowBright'
	| 'blueBright'
	| 'magentaBright'
	| 'cyanBright'
	| 'whiteBright';

/**
Basic background colors.

[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
*/
declare type BackgroundColor =
	| 'bgBlack'
	| 'bgRed'
	| 'bgGreen'
	| 'bgYellow'
	| 'bgBlue'
	| 'bgMagenta'
	| 'bgCyan'
	| 'bgWhite'
	| 'bgGray'
	| 'bgGrey'
	| 'bgBlackBright'
	| 'bgRedBright'
	| 'bgGreenBright'
	| 'bgYellowBright'
	| 'bgBlueBright'
	| 'bgMagentaBright'
	| 'bgCyanBright'
	| 'bgWhiteBright';

/**
Basic colors.

[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
*/
declare type Color = ForegroundColor | BackgroundColor;

declare type Modifiers =
	| 'reset'
	| 'bold'
	| 'dim'
	| 'italic'
	| 'underline'
	| 'inverse'
	| 'hidden'
	| 'strikethrough'
	| 'visible';

declare namespace chalk {
	/**
	Levels:
	- `0` - All colors disabled.
	- `1` - Basic 16 colors support.
	- `2` - ANSI 256 colors support.
	- `3` - Truecolor 16 million colors support.
	*/
	type Level = 0 | 1 | 2 | 3;

	interface Options {
		/**
		Specify the color support for Chalk.

		By default, color support is automatically detected based on the environment.

		Levels:
		- `0` - All colors disabled.
		- `1` - Basic 16 colors support.
		- `2` - ANSI 256 colors support.
		- `3` - Truecolor 16 million colors support.
		*/
		level?: Level;
	}

	/**
	Return a new Chalk instance.
	*/
	type Instance = new (options?: Options) => Chalk;

	/**
	Detect whether the terminal supports color.
	*/
	interface ColorSupport {
		/**
		The color level used by Chalk.
		*/
		level: Level;

		/**
		Return whether Chalk supports basic 16 colors.
		*/
		hasBasic: boolean;

		/**
		Return whether Chalk supports ANSI 256 colors.
		*/
		has256: boolean;

		/**
		Return whether Chalk supports Truecolor 16 million colors.
		*/
		has16m: boolean;
	}

	interface ChalkFunction {
		/**
		Use a template string.

		@remarks Template literals are unsupported for nested calls (see [issue #341](https://github.com/chalk/chalk/issues/341))

		@example
		```
		import chalk = require('chalk');

		log(chalk`
		CPU: {red ${cpu.totalPercent}%}
		RAM: {green ${ram.used / ram.total * 100}%}
		DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
		`);
		```

		@example
		```
		import chalk = require('chalk');

		log(chalk.red.bgBlack`2 + 3 = {bold ${2 + 3}}`)
		```
		*/
		(text: TemplateStringsArray, ...placeholders: unknown[]): string;

		(...text: unknown[]): string;
	}

	interface Chalk extends ChalkFunction {
		/**
		Return a new Chalk instance.
		*/
		Instance: Instance;

		/**
		The color support for Chalk.

		By default, color support is automatically detected based on the environment.

		Levels:
		- `0` - All colors disabled.
		- `1` - Basic 16 colors support.
		- `2` - ANSI 256 colors support.
		- `3` - Truecolor 16 million colors support.
		*/
		level: Level;

		/**
		Use HEX value to set text color.

		@param color - Hexadecimal value representing the desired color.

		@example
		```
		import chalk = require('chalk');

		chalk.hex('#DEADED');
		```
		*/
		hex(color: string): Chalk;

		/**
		Use keyword color value to set text color.

		@param color - Keyword value representing the desired color.

		@example
		```
		import chalk = require('chalk');

		chalk.keyword('orange');
		```
		*/
		keyword(color: string): Chalk;

		/**
		Use RGB values to set text color.
		*/
		rgb(red: number, green: number, blue: number): Chalk;

		/**
		Use HSL values to set text color.
		*/
		hsl(hue: number, saturation: number, lightness: number): Chalk;

		/**
		Use HSV values to set text color.
		*/
		hsv(hue: number, saturation: number, value: number): Chalk;

		/**
		Use HWB values to set text color.
		*/
		hwb(hue: number, whiteness: number, blackness: number): Chalk;

		/**
		Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set text color.

		30 <= code && code < 38 || 90 <= code && code < 98
		For example, 31 for red, 91 for redBright.
		*/
		ansi(code: number): Chalk;

		/**
		Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
		*/
		ansi256(index: number): Chalk;

		/**
		Use HEX value to set background color.

		@param color - Hexadecimal value representing the desired color.

		@example
		```
		import chalk = require('chalk');

		chalk.bgHex('#DEADED');
		```
		*/
		bgHex(color: string): Chalk;

		/**
		Use keyword color value to set background color.

		@param color - Keyword value representing the desired color.

		@example
		```
		import chalk = require('chalk');

		chalk.bgKeyword('orange');
		```
		*/
		bgKeyword(color: string): Chalk;

		/**
		Use RGB values to set background color.
		*/
		bgRgb(red: number, green: number, blue: number): Chalk;

		/**
		Use HSL values to set background color.
		*/
		bgHsl(hue: number, saturation: number, lightness: number): Chalk;

		/**
		Use HSV values to set background color.
		*/
		bgHsv(hue: number, saturation: number, value: number): Chalk;

		/**
		Use HWB values to set background color.
		*/
		bgHwb(hue: number, whiteness: number, blackness: number): Chalk;

		/**
		Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set background color.

		30 <= code && code < 38 || 90 <= code && code < 98
		For example, 31 for red, 91 for redBright.
		Use the foreground code, not the background code (for example, not 41, nor 101).
		*/
		bgAnsi(code: number): Chalk;

		/**
		Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color.
		*/
		bgAnsi256(index: number): Chalk;

		/**
		Modifier: Resets the current color chain.
		*/
		readonly reset: Chalk;

		/**
		Modifier: Make text bold.
		*/
		readonly bold: Chalk;

		/**
		Modifier: Emitting only a small amount of light.
		*/
		readonly dim: Chalk;

		/**
		Modifier: Make text italic. (Not widely supported)
		*/
		readonly italic: Chalk;

		/**
		Modifier: Make text underline. (Not widely supported)
		*/
		readonly underline: Chalk;

		/**
		Modifier: Inverse background and foreground colors.
		*/
		readonly inverse: Chalk;

		/**
		Modifier: Prints the text, but makes it invisible.
		*/
		readonly hidden: Chalk;

		/**
		Modifier: Puts a horizontal line through the center of the text. (Not widely supported)
		*/
		readonly strikethrough: Chalk;

		/**
		Modifier: Prints the text only when Chalk has a color support level > 0.
		Can be useful for things that are purely cosmetic.
		*/
		readonly visible: Chalk;

		readonly black: Chalk;
		readonly red: Chalk;
		readonly green: Chalk;
		readonly yellow: Chalk;
		readonly blue: Chalk;
		readonly magenta: Chalk;
		readonly cyan: Chalk;
		readonly white: Chalk;

		/*
		Alias for `blackBright`.
		*/
		readonly gray: Chalk;

		/*
		Alias for `blackBright`.
		*/
		readonly grey: Chalk;

		readonly blackBright: Chalk;
		readonly redBright: Chalk;
		readonly greenBright: Chalk;
		readonly yellowBright: Chalk;
		readonly blueBright: Chalk;
		readonly magentaBright: Chalk;
		readonly cyanBright: Chalk;
		readonly whiteBright: Chalk;

		readonly bgBlack: Chalk;
		readonly bgRed: Chalk;
		readonly bgGreen: Chalk;
		readonly bgYellow: Chalk;
		readonly bgBlue: Chalk;
		readonly bgMagenta: Chalk;
		readonly bgCyan: Chalk;
		readonly bgWhite: Chalk;

		/*
		Alias for `bgBlackBright`.
		*/
		readonly bgGray: Chalk;

		/*
		Alias for `bgBlackBright`.
		*/
		readonly bgGrey: Chalk;

		readonly bgBlackBright: Chalk;
		readonly bgRedBright: Chalk;
		readonly bgGreenBright: Chalk;
		readonly bgYellowBright: Chalk;
		readonly bgBlueBright: Chalk;
		readonly bgMagentaBright: Chalk;
		readonly bgCyanBright: Chalk;
		readonly bgWhiteBright: Chalk;
	}
}

/**
Main Chalk object that allows to chain styles together.
Call the last one as a method with a string argument.
Order doesn't matter, and later styles take precedent in case of a conflict.
This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
*/
declare const chalk: chalk.Chalk & chalk.ChalkFunction & {
	supportsColor: chalk.ColorSupport | false;
	Level: chalk.Level;
	Color: Color;
	ForegroundColor: ForegroundColor;
	BackgroundColor: BackgroundColor;
	Modifiers: Modifiers;
	stderr: chalk.Chalk & {supportsColor: chalk.ColorSupport | false};
};

export = chalk;


chalk

description: Terminal string styling done right

repository: chalk/chalk

main: source

test: xo && nyc ava && tsd

bench: matcha benchmark.js

keywords: color colour colors terminal console cli string str ansi style styles tty formatting rgb 256 shell xterm log logging command-line text

unicorn/prefer-string-slice: off

unicorn/prefer-includes: off

@typescript-eslint/member-ordering: off

no-redeclare: off

unicorn/string-content: off

unicorn/better-regex: off


code:
> Terminal string styling done right

[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) ![TypeScript-ready](https://img.shields.io/npm/types/chalk.svg) [![run on repl.it](https://repl.it/badge/github/chalk/chalk)](https://repl.it/github/chalk/chalk)

---

				Sindre Sorhus' open source work is supported by the community on GitHub Sponsors and Dev

		Special thanks to:

			All your environment variables, in one place

				Stop struggling with scattered API keys, hacking together home-brewed tools,

				and avoiding access controls. Keep your team and servers in sync with Doppler.

---

## Highlights

- Expressive API
- Highly performant
- Ability to nest styles
- [256/Truecolor color support](#256-and-truecolor-color-support)
- Auto-detects color support
- Doesn't extend `String.prototype`
- Clean and focused
- Actively maintained
- [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020

## Install

```console
$ npm install chalk
```

## Usage

```js
const chalk = require('chalk');

console.log(chalk.blue('Hello world!'));
```

Chalk comes with an easy to use composable API where you just chain and nest the styles you want.

```js
const chalk = require('chalk');
const log = console.log;

// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));

// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));

// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));

// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));

// Nest styles of the same type even (color, underline, background)
log(chalk.green(
	'I am a green line ' +
	chalk.blue.underline.bold('with a blue substring') +
	' that becomes green again!'
));

// ES2015 template literal
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);

// ES2015 tagged template literal
log(chalk`
CPU: {red ${cpu.totalPercent}%}
RAM: {green ${ram.used / ram.total * 100}%}
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
`);

// Use RGB colors in terminal emulators that support it.
log(chalk.keyword('orange')('Yay for orange colored text!'));
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));
```

Easily define your own themes:

```js
const chalk = require('chalk');

const error = chalk.bold.red;
const warning = chalk.keyword('orange');

console.log(error('Error!'));
console.log(warning('Warning!'));
```

Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):

```js
const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> 'Hello Sindre'
```

## API

### chalk.`<style>[.<style>...](string, [string...])`

Example: `chalk.red.bold.underline('Hello', 'world');`

Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.

Multiple arguments will be separated by space.

### chalk.level

Specifies the level of color support.

Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers.

If you need to change this in a reusable module, create a new instance:

```js
const ctx = new chalk.Instance({level: 0});
```

| Level | Description |
| :---: | :--- |
| `0` | All colors disabled |
| `1` | Basic color support (16 colors) |
| `2` | 256 color support |
| `3` | Truecolor support (16 million colors) |

### chalk.supportsColor

Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.

Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.

Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.

### chalk.stderr and chalk.stderr.supportsColor

`chalk.stderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `chalk.supportsColor` apply to this too. `chalk.stderr.supportsColor` is exposed for convenience.

## Styles

### Modifiers

- `reset` - Resets the current color chain.
- `bold` - Make text bold.
- `dim` - Emitting only a small amount of light.
- `italic` - Make text italic. *(Not widely supported)*
- `underline` - Make text underline. *(Not widely supported)*
- `inverse`- Inverse background and foreground colors.
- `hidden` - Prints the text, but makes it invisible.
- `strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)*
- `visible`- Prints the text only when Chalk has a color level > 0. Can be useful for things that are purely cosmetic.

### Colors

- `black`
- `red`
- `green`
- `yellow`
- `blue`
- `magenta`
- `cyan`
- `white`
- `blackBright` (alias: `gray`, `grey`)
- `redBright`
- `greenBright`
- `yellowBright`
- `blueBright`
- `magentaBright`
- `cyanBright`
- `whiteBright`

### Background colors

- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
- `bgBlackBright` (alias: `bgGray`, `bgGrey`)
- `bgRedBright`
- `bgGreenBright`
- `bgYellowBright`
- `bgBlueBright`
- `bgMagentaBright`
- `bgCyanBright`
- `bgWhiteBright`

## Tagged template literal

Chalk can be used as a [tagged template literal](https://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).

```js
const chalk = require('chalk');

const miles = 18;
const calculateFeet = miles => miles * 5280;

console.log(chalk`
	There are {bold 5280 feet} in a mile.
	In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
`);
```

Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`).

Template styles are chained exactly like normal Chalk styles. The following three statements are equivalent:

```js
console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
console.log(chalk.bold.rgb(10, 100, 200)`Hello!`);
console.log(chalk`{bold.rgb(10,100,200) Hello!}`);
```

Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters.

All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.

## 256 and Truecolor color support

Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps.

Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).

Examples:

- `chalk.hex('#DEADED').underline('Hello, world!')`
- `chalk.keyword('orange')('Some orange text')`
- `chalk.rgb(15, 100, 204).inverse('Hello!')`

Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors).

- `chalk.bgHex('#DEADED').underline('Hello, world!')`
- `chalk.bgKeyword('orange')('Some orange text')`
- `chalk.bgRgb(15, 100, 204).inverse('Hello!')`

The following color models can be used:

- [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')`
- [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')`
- [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')`
- [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')`
- [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsv(32, 100, 100).bold('Orange!')`
- [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hwb(32, 0, 50).bold('Orange!')`
- [`ansi`](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) - Example: `chalk.ansi(31).bgAnsi(93)('red on yellowBright')`
- [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')`

## Windows

If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`.

## Origin story

[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.

## chalk for enterprise

Available as part of the Tidelift Subscription.

The maintainers of chalk and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-chalk?utm_source=npm-chalk&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)

## Related

- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal
- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings
- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings
- [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal

## Maintainers

- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)