(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, global.prettier = factory()); }(this, (function () { 'use strict'; var name = "prettier"; var version = "2.0.5"; var description = "Prettier is an opinionated code formatter"; var bin = "./bin/prettier.js"; var repository = "prettier/prettier"; var homepage = "https://prettier.io"; var author = "James Long"; var license = "MIT"; var main = "./index.js"; var engines = { node: ">=10.13.0" }; var dependencies = { "@angular/compiler": "9.0.5", "@babel/code-frame": "7.8.0", "@babel/parser": "7.9.4", "@glimmer/syntax": "0.50.0", "@iarna/toml": "2.2.3", "@typescript-eslint/typescript-estree": "2.26.0", "angular-estree-parser": "1.3.0", "angular-html-parser": "1.4.0", camelcase: "5.3.1", chalk: "4.0.0", "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540", "cjk-regex": "2.0.0", cosmiconfig: "6.0.0", dashify: "2.0.0", dedent: "0.7.0", diff: "4.0.2", editorconfig: "0.15.3", "editorconfig-to-prettier": "0.1.1", "escape-string-regexp": "2.0.0", esutils: "2.0.3", "fast-glob": "3.2.2", "find-parent-dir": "0.3.0", "find-project-root": "1.1.1", "flow-parser": "0.122.0", "get-stream": "5.1.0", globby: "11.0.0", graphql: "15.0.0", "html-element-attributes": "2.2.1", "html-styles": "1.0.0", "html-tag-names": "1.1.5", ignore: "4.0.6", "jest-docblock": "25.2.6", "json-stable-stringify": "1.0.1", leven: "3.1.0", "lines-and-columns": "1.1.6", "linguist-languages": "7.9.0", lodash: "4.17.15", mem: "6.0.1", minimatch: "3.0.4", minimist: "1.2.5", "n-readlines": "1.0.0", "please-upgrade-node": "3.2.0", "postcss-less": "3.1.4", "postcss-media-query-parser": "0.2.3", "postcss-scss": "2.0.0", "postcss-selector-parser": "2.2.3", "postcss-values-parser": "2.0.1", "regexp-util": "1.2.2", "remark-math": "1.0.6", "remark-parse": "5.0.0", resolve: "1.16.1", semver: "7.1.3", srcset: "2.0.1", "string-width": "4.2.0", typescript: "3.8.3", "unicode-regex": "3.0.0", unified: "9.0.0", vnopts: "1.0.2", "yaml-unist-parser": "1.1.1" }; var devDependencies = { "@babel/core": "7.9.0", "@babel/preset-env": "7.9.0", "@rollup/plugin-alias": "3.0.1", "@rollup/plugin-commonjs": "11.0.2", "@rollup/plugin-json": "4.0.2", "@rollup/plugin-node-resolve": "7.1.1", "@rollup/plugin-replace": "2.3.1", "babel-loader": "8.1.0", benchmark: "2.1.4", "builtin-modules": "3.1.0", codecov: "3.6.5", "cross-env": "7.0.2", cspell: "4.0.55", eslint: "6.8.0", "eslint-config-prettier": "6.10.1", "eslint-formatter-friendly": "7.0.0", "eslint-plugin-import": "2.20.2", "eslint-plugin-prettier": "3.1.2", "eslint-plugin-react": "7.19.0", "eslint-plugin-unicorn": "18.0.1", execa: "4.0.0", jest: "25.2.7", "jest-snapshot-serializer-ansi": "1.0.0", "jest-snapshot-serializer-raw": "1.1.0", "jest-watch-typeahead": "0.5.0", prettier: "2.0.4", rimraf: "3.0.2", rollup: "2.3.2", "rollup-plugin-babel": "4.4.0", "rollup-plugin-node-globals": "1.4.0", "rollup-plugin-terser": "5.3.0", shelljs: "0.8.3", "snapshot-diff": "0.7.0", "strip-ansi": "6.0.0", "synchronous-promise": "2.0.10", tempy: "0.5.0", "terser-webpack-plugin": "2.3.5", webpack: "4.42.1" }; var scripts = { prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1", "prepare-release": "yarn && yarn build && yarn test:dist", test: "jest", "test:dist": "cross-env NODE_ENV=production jest", "test:dist-standalone": "cross-env NODE_ENV=production TEST_STANDALONE=1 jest tests/", "test:integration": "jest tests_integration", "perf:repeat": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", "perf:repeat-inspect": "yarn && yarn build && cross-env NODE_ENV=production node --inspect-brk ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", "perf:benchmark": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-benchmark --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", "lint:typecheck": "tsc", "lint:eslint": "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly", "lint:changelog": "node ./scripts/lint-changelog.js", "lint:prettier": "prettier \"**/*.{md,json,yml,html,css}\" --check", "lint:dist": "eslint --no-eslintrc --no-ignore --env=es6,browser --parser-options=ecmaVersion:2016 \"dist/!(bin-prettier|index|third-party).js\"", "lint:spellcheck": "cspell {bin,scripts,src,website}/**/*.js {docs,website/blog,changelog_unreleased}/**/*.md", "lint:deps": "node ./scripts/check-deps.js", build: "node --max-old-space-size=3072 ./scripts/build/build.js", "build-docs": "node ./scripts/build-docs.js" }; var _package = { name: name, version: version, description: description, bin: bin, repository: repository, homepage: homepage, author: author, license: license, main: main, engines: engines, dependencies: dependencies, devDependencies: devDependencies, scripts: scripts }; var _package$1 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name, version: version, description: description, bin: bin, repository: repository, homepage: homepage, author: author, license: license, main: main, engines: engines, dependencies: dependencies, devDependencies: devDependencies, scripts: scripts, 'default': _package }); function Diff() {} Diff.prototype = { diff: function diff(oldString, newString) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var callback = options.callback; if (typeof options === 'function') { callback = options; options = {}; } this.options = options; var self = this; function done(value) { if (callback) { setTimeout(function () { callback(undefined, value); }, 0); return true; } else { return value; } } // Allow subclasses to massage the input prior to running oldString = this.castInput(oldString); newString = this.castInput(newString); oldString = this.removeEmpty(this.tokenize(oldString)); newString = this.removeEmpty(this.tokenize(newString)); var newLen = newString.length, oldLen = oldString.length; var editLength = 1; var maxEditLength = newLen + oldLen; var bestPath = [{ newPos: -1, components: [] }]; // Seed editLength = 0, i.e. the content starts with the same values var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { // Identity per the equality and tokenizer return done([{ value: this.join(newString), count: newString.length }]); } // Main worker method. checks all permutations of a given edit length for acceptance. function execEditLength() { for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { var basePath = void 0; var addPath = bestPath[diagonalPath - 1], removePath = bestPath[diagonalPath + 1], _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; if (addPath) { // No one else is going to attempt to use this value, clear it bestPath[diagonalPath - 1] = undefined; } var canAdd = addPath && addPath.newPos + 1 < newLen, canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; if (!canAdd && !canRemove) { // If this path is a terminal then prune bestPath[diagonalPath] = undefined; continue; } // Select the diagonal that we want to branch from. We select the prior // path whose position in the new string is the farthest from the origin // and does not pass the bounds of the diff graph if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { basePath = clonePath(removePath); self.pushComponent(basePath.components, undefined, true); } else { basePath = addPath; // No need to clone, we've pulled it from the list basePath.newPos++; self.pushComponent(basePath.components, true, undefined); } _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); } else { // Otherwise track this path as a potential candidate and continue. bestPath[diagonalPath] = basePath; } } editLength++; } // Performs the length of edit iteration. Is a bit fugly as this has to support the // sync and async mode which is never fun. Loops over execEditLength until a value // is produced. if (callback) { (function exec() { setTimeout(function () { // This should not happen, but we want to be safe. /* istanbul ignore next */ if (editLength > maxEditLength) { return callback(); } if (!execEditLength()) { exec(); } }, 0); })(); } else { while (editLength <= maxEditLength) { var ret = execEditLength(); if (ret) { return ret; } } } }, pushComponent: function pushComponent(components, added, removed) { var last = components[components.length - 1]; if (last && last.added === added && last.removed === removed) { // We need to clone here as the component clone operation is just // as shallow array clone components[components.length - 1] = { count: last.count + 1, added: added, removed: removed }; } else { components.push({ count: 1, added: added, removed: removed }); } }, extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { var newLen = newString.length, oldLen = oldString.length, newPos = basePath.newPos, oldPos = newPos - diagonalPath, commonCount = 0; while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { newPos++; oldPos++; commonCount++; } if (commonCount) { basePath.components.push({ count: commonCount }); } basePath.newPos = newPos; return oldPos; }, equals: function equals(left, right) { if (this.options.comparator) { return this.options.comparator(left, right); } else { return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); } }, removeEmpty: function removeEmpty(array) { var ret = []; for (var i = 0; i < array.length; i++) { if (array[i]) { ret.push(array[i]); } } return ret; }, castInput: function castInput(value) { return value; }, tokenize: function tokenize(value) { return value.split(''); }, join: function join(chars) { return chars.join(''); } }; function buildValues(diff, components, newString, oldString, useLongestToken) { var componentPos = 0, componentLen = components.length, newPos = 0, oldPos = 0; for (; componentPos < componentLen; componentPos++) { var component = components[componentPos]; if (!component.removed) { if (!component.added && useLongestToken) { var value = newString.slice(newPos, newPos + component.count); value = value.map(function (value, i) { var oldValue = oldString[oldPos + i]; return oldValue.length > value.length ? oldValue : value; }); component.value = diff.join(value); } else { component.value = diff.join(newString.slice(newPos, newPos + component.count)); } newPos += component.count; // Common case if (!component.added) { oldPos += component.count; } } else { component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); oldPos += component.count; // Reverse add and remove so removes are output first to match common convention // The diffing algorithm is tied to add then remove output and this is the simplest // route to get the desired output with minimal overhead. if (componentPos && components[componentPos - 1].added) { var tmp = components[componentPos - 1]; components[componentPos - 1] = components[componentPos]; components[componentPos] = tmp; } } } // Special case handle for when one terminal is ignored (i.e. whitespace). // For this case we merge the terminal into the prior string and drop the change. // This is only available for string mode. var lastComponent = components[componentLen - 1]; if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { components[componentLen - 2].value += lastComponent.value; components.pop(); } return components; } function clonePath(path) { return { newPos: path.newPos, components: path.components.slice(0) }; } var characterDiff = new Diff(); function diffChars(oldStr, newStr, options) { return characterDiff.diff(oldStr, newStr, options); } function generateOptions(options, defaults) { if (typeof options === 'function') { defaults.callback = options; } else if (options) { for (var name in options) { /* istanbul ignore else */ if (options.hasOwnProperty(name)) { defaults[name] = options[name]; } } } return defaults; } // // Ranges and exceptions: // Latin-1 Supplement, 0080–00FF // - U+00D7 × Multiplication sign // - U+00F7 ÷ Division sign // Latin Extended-A, 0100–017F // Latin Extended-B, 0180–024F // IPA Extensions, 0250–02AF // Spacing Modifier Letters, 02B0–02FF // - U+02C7 ˇ ˇ Caron // - U+02D8 ˘ ˘ Breve // - U+02D9 ˙ ˙ Dot Above // - U+02DA ˚ ˚ Ring Above // - U+02DB ˛ ˛ Ogonek // - U+02DC ˜ ˜ Small Tilde // - U+02DD ˝ ˝ Double Acute Accent // Latin Extended Additional, 1E00–1EFF var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; var reWhitespace = /\S/; var wordDiff = new Diff(); wordDiff.equals = function (left, right) { if (this.options.ignoreCase) { left = left.toLowerCase(); right = right.toLowerCase(); } return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); }; wordDiff.tokenize = function (value) { var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. for (var i = 0; i < tokens.length - 1; i++) { // If we have an empty string in the next field and we have only word chars before and after, merge if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { tokens[i] += tokens[i + 2]; tokens.splice(i + 1, 2); i--; } } return tokens; }; function diffWords(oldStr, newStr, options) { options = generateOptions(options, { ignoreWhitespace: true }); return wordDiff.diff(oldStr, newStr, options); } function diffWordsWithSpace(oldStr, newStr, options) { return wordDiff.diff(oldStr, newStr, options); } var lineDiff = new Diff(); lineDiff.tokenize = function (value) { var retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line if (!linesAndNewlines[linesAndNewlines.length - 1]) { linesAndNewlines.pop(); } // Merge the content and line separators into single tokens for (var i = 0; i < linesAndNewlines.length; i++) { var line = linesAndNewlines[i]; if (i % 2 && !this.options.newlineIsToken) { retLines[retLines.length - 1] += line; } else { if (this.options.ignoreWhitespace) { line = line.trim(); } retLines.push(line); } } return retLines; }; function diffLines(oldStr, newStr, callback) { return lineDiff.diff(oldStr, newStr, callback); } function diffTrimmedLines(oldStr, newStr, callback) { var options = generateOptions(callback, { ignoreWhitespace: true }); return lineDiff.diff(oldStr, newStr, options); } var sentenceDiff = new Diff(); sentenceDiff.tokenize = function (value) { return value.split(/(\S.+?[.!?])(?=\s+|$)/); }; function diffSentences(oldStr, newStr, callback) { return sentenceDiff.diff(oldStr, newStr, callback); } var cssDiff = new Diff(); cssDiff.tokenize = function (value) { return value.split(/([{}:;,]|\s+)/); }; function diffCss(oldStr, newStr, callback) { return cssDiff.diff(oldStr, newStr, callback); } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } var objectPrototypeToString = Object.prototype.toString; var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: jsonDiff.useLongestToken = true; jsonDiff.tokenize = lineDiff.tokenize; jsonDiff.castInput = function (value) { var _this$options = this.options, undefinedReplacement = _this$options.undefinedReplacement, _this$options$stringi = _this$options.stringifyReplacer, stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { return typeof v === 'undefined' ? undefinedReplacement : v; } : _this$options$stringi; return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); }; jsonDiff.equals = function (left, right) { return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); }; function diffJson(oldObj, newObj, options) { return jsonDiff.diff(oldObj, newObj, options); } // This function handles the presence of circular references by bailing out when encountering an // object that is already on the "stack" of items being processed. Accepts an optional replacer function canonicalize(obj, stack, replacementStack, replacer, key) { stack = stack || []; replacementStack = replacementStack || []; if (replacer) { obj = replacer(key, obj); } var i; for (i = 0; i < stack.length; i += 1) { if (stack[i] === obj) { return replacementStack[i]; } } var canonicalizedObj; if ('[object Array]' === objectPrototypeToString.call(obj)) { stack.push(obj); canonicalizedObj = new Array(obj.length); replacementStack.push(canonicalizedObj); for (i = 0; i < obj.length; i += 1) { canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); } stack.pop(); replacementStack.pop(); return canonicalizedObj; } if (obj && obj.toJSON) { obj = obj.toJSON(); } if (_typeof(obj) === 'object' && obj !== null) { stack.push(obj); canonicalizedObj = {}; replacementStack.push(canonicalizedObj); var sortedKeys = [], _key; for (_key in obj) { /* istanbul ignore else */ if (obj.hasOwnProperty(_key)) { sortedKeys.push(_key); } } sortedKeys.sort(); for (i = 0; i < sortedKeys.length; i += 1) { _key = sortedKeys[i]; canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); } stack.pop(); replacementStack.pop(); } else { canonicalizedObj = obj; } return canonicalizedObj; } var arrayDiff = new Diff(); arrayDiff.tokenize = function (value) { return value.slice(); }; arrayDiff.join = arrayDiff.removeEmpty = function (value) { return value; }; function diffArrays(oldArr, newArr, callback) { return arrayDiff.diff(oldArr, newArr, callback); } function parsePatch(uniDiff) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], list = [], i = 0; function parseIndex() { var index = {}; list.push(index); // Parse diff metadata while (i < diffstr.length) { var line = diffstr[i]; // File header found, end parsing diff metadata if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { break; } // Diff index var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); if (header) { index.index = header[1]; } i++; } // Parse file headers if they are defined. Unified diff requires them, but // there's no technical issues to have an isolated hunk without file header parseFileHeader(index); parseFileHeader(index); // Parse hunks index.hunks = []; while (i < diffstr.length) { var _line = diffstr[i]; if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { break; } else if (/^@@/.test(_line)) { index.hunks.push(parseHunk()); } else if (_line && options.strict) { // Ignore unexpected content unless in strict mode throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); } else { i++; } } } // Parses the --- and +++ headers, if none are found, no lines // are consumed. function parseFileHeader(index) { var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); if (fileHeader) { var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; var data = fileHeader[2].split('\t', 2); var fileName = data[0].replace(/\\\\/g, '\\'); if (/^".*"$/.test(fileName)) { fileName = fileName.substr(1, fileName.length - 2); } index[keyPrefix + 'FileName'] = fileName; index[keyPrefix + 'Header'] = (data[1] || '').trim(); i++; } } // Parses a hunk // This assumes that we are at the start of a hunk. function parseHunk() { var chunkHeaderIndex = i, chunkHeaderLine = diffstr[i++], chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); var hunk = { oldStart: +chunkHeader[1], oldLines: +chunkHeader[2] || 1, newStart: +chunkHeader[3], newLines: +chunkHeader[4] || 1, lines: [], linedelimiters: [] }; var addCount = 0, removeCount = 0; for (; i < diffstr.length; i++) { // Lines starting with '---' could be mistaken for the "remove line" operation // But they could be the header for the next file. Therefore prune such cases out. if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { break; } var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { hunk.lines.push(diffstr[i]); hunk.linedelimiters.push(delimiters[i] || '\n'); if (operation === '+') { addCount++; } else if (operation === '-') { removeCount++; } else if (operation === ' ') { addCount++; removeCount++; } } else { break; } } // Handle the empty block count case if (!addCount && hunk.newLines === 1) { hunk.newLines = 0; } if (!removeCount && hunk.oldLines === 1) { hunk.oldLines = 0; } // Perform optional sanity checking if (options.strict) { if (addCount !== hunk.newLines) { throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } if (removeCount !== hunk.oldLines) { throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); } } return hunk; } while (i < diffstr.length) { parseIndex(); } return list; } // Iterator that traverses in the range of [min, max], stepping // by distance from a given start position. I.e. for [0, 4], with // start of 2, this will iterate 2, 3, 1, 4, 0. function distanceIterator(start, minLine, maxLine) { var wantForward = true, backwardExhausted = false, forwardExhausted = false, localOffset = 1; return function iterator() { if (wantForward && !forwardExhausted) { if (backwardExhausted) { localOffset++; } else { wantForward = false; } // Check if trying to fit beyond text length, and if not, check it fits // after offset location (or desired location on first iteration) if (start + localOffset <= maxLine) { return localOffset; } forwardExhausted = true; } if (!backwardExhausted) { if (!forwardExhausted) { wantForward = true; } // Check if trying to fit before text beginning, and if not, check it fits // before offset location if (minLine <= start - localOffset) { return -localOffset++; } backwardExhausted = true; return iterator(); } // We tried to fit hunk before text beginning and beyond text length, then // hunk can't fit on the text. Return undefined }; } function applyPatch(source, uniDiff) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } if (Array.isArray(uniDiff)) { if (uniDiff.length > 1) { throw new Error('applyPatch only works with a single input.'); } uniDiff = uniDiff[0]; } // Apply the diff to the input var lines = source.split(/\r\n|[\n\v\f\r\x85]/), delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], hunks = uniDiff.hunks, compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { return line === patchContent; }, errorCount = 0, fuzzFactor = options.fuzzFactor || 0, minLine = 0, offset = 0, removeEOFNL, addEOFNL; /** * Checks if the hunk exactly fits on the provided location */ function hunkFits(hunk, toPos) { for (var j = 0; j < hunk.lines.length; j++) { var line = hunk.lines[j], operation = line.length > 0 ? line[0] : ' ', content = line.length > 0 ? line.substr(1) : line; if (operation === ' ' || operation === '-') { // Context sanity check if (!compareLine(toPos + 1, lines[toPos], operation, content)) { errorCount++; if (errorCount > fuzzFactor) { return false; } } toPos++; } } return true; } // Search best fit offsets for each hunk based on the previous ones for (var i = 0; i < hunks.length; i++) { var hunk = hunks[i], maxLine = lines.length - hunk.oldLines, localOffset = 0, toPos = offset + hunk.oldStart - 1; var iterator = distanceIterator(toPos, minLine, maxLine); for (; localOffset !== undefined; localOffset = iterator()) { if (hunkFits(hunk, toPos + localOffset)) { hunk.offset = offset += localOffset; break; } } if (localOffset === undefined) { return false; } // Set lower text limit to end of the current hunk, so next ones don't try // to fit over already patched text minLine = hunk.offset + hunk.oldStart + hunk.oldLines; } // Apply patch hunks var diffOffset = 0; for (var _i = 0; _i < hunks.length; _i++) { var _hunk = hunks[_i], _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; diffOffset += _hunk.newLines - _hunk.oldLines; if (_toPos < 0) { // Creating a new file _toPos = 0; } for (var j = 0; j < _hunk.lines.length; j++) { var line = _hunk.lines[j], operation = line.length > 0 ? line[0] : ' ', content = line.length > 0 ? line.substr(1) : line, delimiter = _hunk.linedelimiters[j]; if (operation === ' ') { _toPos++; } else if (operation === '-') { lines.splice(_toPos, 1); delimiters.splice(_toPos, 1); /* istanbul ignore else */ } else if (operation === '+') { lines.splice(_toPos, 0, content); delimiters.splice(_toPos, 0, delimiter); _toPos++; } else if (operation === '\\') { var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; if (previousOperation === '+') { removeEOFNL = true; } else if (previousOperation === '-') { addEOFNL = true; } } } } // Handle EOFNL insertion/removal if (removeEOFNL) { while (!lines[lines.length - 1]) { lines.pop(); delimiters.pop(); } } else if (addEOFNL) { lines.push(''); delimiters.push('\n'); } for (var _k = 0; _k < lines.length - 1; _k++) { lines[_k] = lines[_k] + delimiters[_k]; } return lines.join(''); } // Wrapper that supports multiple file patches via callbacks. function applyPatches(uniDiff, options) { if (typeof uniDiff === 'string') { uniDiff = parsePatch(uniDiff); } var currentIndex = 0; function processIndex() { var index = uniDiff[currentIndex++]; if (!index) { return options.complete(); } options.loadFile(index, function (err, data) { if (err) { return options.complete(err); } var updatedContent = applyPatch(data, index, options); options.patched(index, updatedContent, function (err) { if (err) { return options.complete(err); } processIndex(); }); }); } processIndex(); } function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { if (!options) { options = {}; } if (typeof options.context === 'undefined') { options.context = 4; } var diff = diffLines(oldStr, newStr, options); diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier function contextLines(lines) { return lines.map(function (entry) { return ' ' + entry; }); } var hunks = []; var oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; var _loop = function _loop(i) { var current = diff[i], lines = current.lines || current.value.replace(/\n$/, '').split('\n'); current.lines = lines; if (current.added || current.removed) { var _curRange; // If we have previous context, start with that if (!oldRangeStart) { var prev = diff[i - 1]; oldRangeStart = oldLine; newRangeStart = newLine; if (prev) { curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; oldRangeStart -= curRange.length; newRangeStart -= curRange.length; } } // Output our changes (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { return (current.added ? '+' : '-') + entry; }))); // Track the updated file position if (current.added) { newLine += lines.length; } else { oldLine += lines.length; } } else { // Identical context lines. Track line changes if (oldRangeStart) { // Close out any changes that have been output (or join overlapping) if (lines.length <= options.context * 2 && i < diff.length - 2) { var _curRange2; // Overlapping (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); } else { var _curRange3; // end the range and output var contextSize = Math.min(lines.length, options.context); (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); var hunk = { oldStart: oldRangeStart, oldLines: oldLine - oldRangeStart + contextSize, newStart: newRangeStart, newLines: newLine - newRangeStart + contextSize, lines: curRange }; if (i >= diff.length - 2 && lines.length <= options.context) { // EOF is inside this hunk var oldEOFNewline = /\n$/.test(oldStr); var newEOFNewline = /\n$/.test(newStr); var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; if (!oldEOFNewline && noNlBeforeAdds) { // special case: old has no eol and no trailing context; no-nl can end up before adds curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); } if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { curRange.push('\\ No newline at end of file'); } } hunks.push(hunk); oldRangeStart = 0; newRangeStart = 0; curRange = []; } } oldLine += lines.length; newLine += lines.length; } }; for (var i = 0; i < diff.length; i++) { _loop(i); } return { oldFileName: oldFileName, newFileName: newFileName, oldHeader: oldHeader, newHeader: newHeader, hunks: hunks }; } function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); var ret = []; if (oldFileName == newFileName) { ret.push('Index: ' + oldFileName); } ret.push('==================================================================='); ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); for (var i = 0; i < diff.hunks.length; i++) { var hunk = diff.hunks[i]; ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); ret.push.apply(ret, hunk.lines); } return ret.join('\n') + '\n'; } function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); } function arrayEqual(a, b) { if (a.length !== b.length) { return false; } return arrayStartsWith(a, b); } function arrayStartsWith(array, start) { if (start.length > array.length) { return false; } for (var i = 0; i < start.length; i++) { if (start[i] !== array[i]) { return false; } } return true; } function calcLineCount(hunk) { var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), oldLines = _calcOldNewLineCount.oldLines, newLines = _calcOldNewLineCount.newLines; if (oldLines !== undefined) { hunk.oldLines = oldLines; } else { delete hunk.oldLines; } if (newLines !== undefined) { hunk.newLines = newLines; } else { delete hunk.newLines; } } function merge(mine, theirs, base) { mine = loadPatch(mine, base); theirs = loadPatch(theirs, base); var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. // Leaving sanity checks on this to the API consumer that may know more about the // meaning in their own context. if (mine.index || theirs.index) { ret.index = mine.index || theirs.index; } if (mine.newFileName || theirs.newFileName) { if (!fileNameChanged(mine)) { // No header or no change in ours, use theirs (and ours if theirs does not exist) ret.oldFileName = theirs.oldFileName || mine.oldFileName; ret.newFileName = theirs.newFileName || mine.newFileName; ret.oldHeader = theirs.oldHeader || mine.oldHeader; ret.newHeader = theirs.newHeader || mine.newHeader; } else if (!fileNameChanged(theirs)) { // No header or no change in theirs, use ours ret.oldFileName = mine.oldFileName; ret.newFileName = mine.newFileName; ret.oldHeader = mine.oldHeader; ret.newHeader = mine.newHeader; } else { // Both changed... figure it out ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); } } ret.hunks = []; var mineIndex = 0, theirsIndex = 0, mineOffset = 0, theirsOffset = 0; while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { var mineCurrent = mine.hunks[mineIndex] || { oldStart: Infinity }, theirsCurrent = theirs.hunks[theirsIndex] || { oldStart: Infinity }; if (hunkBefore(mineCurrent, theirsCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); mineIndex++; theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; } else if (hunkBefore(theirsCurrent, mineCurrent)) { // This patch does not overlap with any of the others, yay. ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); theirsIndex++; mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; } else { // Overlap, merge as best we can var mergedHunk = { oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), oldLines: 0, newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), newLines: 0, lines: [] }; mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); theirsIndex++; mineIndex++; ret.hunks.push(mergedHunk); } } return ret; } function loadPatch(param, base) { if (typeof param === 'string') { if (/^@@/m.test(param) || /^Index:/m.test(param)) { return parsePatch(param)[0]; } if (!base) { throw new Error('Must provide a base reference or pass in a patch'); } return structuredPatch(undefined, undefined, base, param); } return param; } function fileNameChanged(patch) { return patch.newFileName && patch.newFileName !== patch.oldFileName; } function selectField(index, mine, theirs) { if (mine === theirs) { return mine; } else { index.conflict = true; return { mine: mine, theirs: theirs }; } } function hunkBefore(test, check) { return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; } function cloneHunk(hunk, offset) { return { oldStart: hunk.oldStart, oldLines: hunk.oldLines, newStart: hunk.newStart + offset, newLines: hunk.newLines, lines: hunk.lines }; } function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { // This will generally result in a conflicted hunk, but there are cases where the context // is the only overlap where we can successfully merge the content here. var mine = { offset: mineOffset, lines: mineLines, index: 0 }, their = { offset: theirOffset, lines: theirLines, index: 0 }; // Handle any leading content insertLeading(hunk, mine, their); insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. while (mine.index < mine.lines.length && their.index < their.lines.length) { var mineCurrent = mine.lines[mine.index], theirCurrent = their.lines[their.index]; if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { // Both modified ... mutualChange(hunk, mine, their); } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { var _hunk$lines; // Mine inserted (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { var _hunk$lines2; // Theirs inserted (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { // Mine removed or edited removal(hunk, mine, their); } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { // Their removed or edited removal(hunk, their, mine, true); } else if (mineCurrent === theirCurrent) { // Context identity hunk.lines.push(mineCurrent); mine.index++; their.index++; } else { // Context mismatch conflict(hunk, collectChange(mine), collectChange(their)); } } // Now push anything that may be remaining insertTrailing(hunk, mine); insertTrailing(hunk, their); calcLineCount(hunk); } function mutualChange(hunk, mine, their) { var myChanges = collectChange(mine), theirChanges = collectChange(their); if (allRemoves(myChanges) && allRemoves(theirChanges)) { // Special case for remove changes that are supersets of one another if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { var _hunk$lines3; (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); return; } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { var _hunk$lines4; (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); return; } } else if (arrayEqual(myChanges, theirChanges)) { var _hunk$lines5; (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); return; } conflict(hunk, myChanges, theirChanges); } function removal(hunk, mine, their, swap) { var myChanges = collectChange(mine), theirChanges = collectContext(their, myChanges); if (theirChanges.merged) { var _hunk$lines6; (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); } else { conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); } } function conflict(hunk, mine, their) { hunk.conflict = true; hunk.lines.push({ conflict: true, mine: mine, theirs: their }); } function insertLeading(hunk, insert, their) { while (insert.offset < their.offset && insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); insert.offset++; } } function insertTrailing(hunk, insert) { while (insert.index < insert.lines.length) { var line = insert.lines[insert.index++]; hunk.lines.push(line); } } function collectChange(state) { var ret = [], operation = state.lines[state.index][0]; while (state.index < state.lines.length) { var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. if (operation === '-' && line[0] === '+') { operation = '+'; } if (operation === line[0]) { ret.push(line); state.index++; } else { break; } } return ret; } function collectContext(state, matchChanges) { var changes = [], merged = [], matchIndex = 0, contextChanges = false, conflicted = false; while (matchIndex < matchChanges.length && state.index < state.lines.length) { var change = state.lines[state.index], match = matchChanges[matchIndex]; // Once we've hit our add, then we are done if (match[0] === '+') { break; } contextChanges = contextChanges || change[0] !== ' '; merged.push(match); matchIndex++; // Consume any additions in the other block as a conflict to attempt // to pull in the remaining context after this if (change[0] === '+') { conflicted = true; while (change[0] === '+') { changes.push(change); change = state.lines[++state.index]; } } if (match.substr(1) === change.substr(1)) { changes.push(change); state.index++; } else { conflicted = true; } } if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { conflicted = true; } if (conflicted) { return changes; } while (matchIndex < matchChanges.length) { merged.push(matchChanges[matchIndex++]); } return { merged: merged, changes: changes }; } function allRemoves(changes) { return changes.reduce(function (prev, change) { return prev && change[0] === '-'; }, true); } function skipRemoveSuperset(state, removeChanges, delta) { for (var i = 0; i < delta; i++) { var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); if (state.lines[state.index + i] !== ' ' + changeContent) { return false; } } state.index += delta; return true; } function calcOldNewLineCount(lines) { var oldLines = 0; var newLines = 0; lines.forEach(function (line) { if (typeof line !== 'string') { var myCount = calcOldNewLineCount(line.mine); var theirCount = calcOldNewLineCount(line.theirs); if (oldLines !== undefined) { if (myCount.oldLines === theirCount.oldLines) { oldLines += myCount.oldLines; } else { oldLines = undefined; } } if (newLines !== undefined) { if (myCount.newLines === theirCount.newLines) { newLines += myCount.newLines; } else { newLines = undefined; } } } else { if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { newLines++; } if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { oldLines++; } } }); return { oldLines: oldLines, newLines: newLines }; } // See: http://code.google.com/p/google-diff-match-patch/wiki/API function convertChangesToDMP(changes) { var ret = [], change, operation; for (var i = 0; i < changes.length; i++) { change = changes[i]; if (change.added) { operation = 1; } else if (change.removed) { operation = -1; } else { operation = 0; } ret.push([operation, change.value]); } return ret; } function convertChangesToXML(changes) { var ret = []; for (var i = 0; i < changes.length; i++) { var change = changes[i]; if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } ret.push(escapeHTML(change.value)); if (change.added) { ret.push(''); } else if (change.removed) { ret.push(''); } } return ret.join(''); } function escapeHTML(s) { var n = s; n = n.replace(/&/g, '&'); n = n.replace(//g, '>'); n = n.replace(/"/g, '"'); return n; } var index_es6 = /*#__PURE__*/Object.freeze({ __proto__: null, Diff: Diff, diffChars: diffChars, diffWords: diffWords, diffWordsWithSpace: diffWordsWithSpace, diffLines: diffLines, diffTrimmedLines: diffTrimmedLines, diffSentences: diffSentences, diffCss: diffCss, diffJson: diffJson, diffArrays: diffArrays, structuredPatch: structuredPatch, createTwoFilesPatch: createTwoFilesPatch, createPatch: createPatch, applyPatch: applyPatch, applyPatches: applyPatches, parsePatch: parsePatch, merge: merge, convertChangesToDMP: convertChangesToDMP, convertChangesToXML: convertChangesToXML, canonicalize: canonicalize }); var _shim_fs = {}; var _shim_fs$1 = /*#__PURE__*/Object.freeze({ __proto__: null, 'default': _shim_fs }); const sep = /[\\/]/; function extname(path) { const filename = basename(path); const dotIndex = filename.lastIndexOf("."); if (dotIndex === -1) return ""; return filename.slice(dotIndex); } function basename(path) { return path.split(sep).pop(); } function isAbsolute() { return true; } var path = /*#__PURE__*/Object.freeze({ __proto__: null, extname: extname, basename: basename, isAbsolute: isAbsolute }); var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; var lookup = []; var revLookup = []; var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; var inited = false; function init() { inited = true; var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i]; revLookup[code.charCodeAt(i)] = i; } revLookup['-'.charCodeAt(0)] = 62; revLookup['_'.charCodeAt(0)] = 63; } function toByteArray(b64) { if (!inited) { init(); } var i, j, l, tmp, placeHolders, arr; var len = b64.length; if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4'); } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; // base64 is 4/3 + up to two characters of the original data arr = new Arr(len * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len; var L = 0; for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; arr[L++] = tmp >> 16 & 0xFF; arr[L++] = tmp >> 8 & 0xFF; arr[L++] = tmp & 0xFF; } if (placeHolders === 2) { tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; arr[L++] = tmp & 0xFF; } else if (placeHolders === 1) { tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; arr[L++] = tmp >> 8 & 0xFF; arr[L++] = tmp & 0xFF; } return arr; } function tripletToBase64(num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; } function encodeChunk(uint8, start, end) { var tmp; var output = []; for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2]; output.push(tripletToBase64(tmp)); } return output.join(''); } function fromByteArray(uint8) { if (!inited) { init(); } var tmp; var len = uint8.length; var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes var output = ''; var parts = []; var maxChunkLength = 16383; // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1]; output += lookup[tmp >> 2]; output += lookup[tmp << 4 & 0x3F]; output += '=='; } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + uint8[len - 1]; output += lookup[tmp >> 10]; output += lookup[tmp >> 4 & 0x3F]; output += lookup[tmp << 2 & 0x3F]; output += '='; } parts.push(output); return parts.join(''); } function read(buffer, offset, isLE, mLen, nBytes) { var e, m; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var nBits = -7; var i = isLE ? nBytes - 1 : 0; var d = isLE ? -1 : 1; var s = buffer[offset + i]; i += d; e = s & (1 << -nBits) - 1; s >>= -nBits; nBits += eLen; for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & (1 << -nBits) - 1; e >>= -nBits; nBits += mLen; for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias; } else if (e === eMax) { return m ? NaN : (s ? -1 : 1) * Infinity; } else { m = m + Math.pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * Math.pow(2, e - mLen); } function write(buffer, value, offset, isLE, mLen, nBytes) { var e, m, c; var eLen = nBytes * 8 - mLen - 1; var eMax = (1 << eLen) - 1; var eBias = eMax >> 1; var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; var i = isLE ? 0 : nBytes - 1; var d = isLE ? 1 : -1; var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; value = Math.abs(value); if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0; e = eMax; } else { e = Math.floor(Math.log(value) / Math.LN2); if (value * (c = Math.pow(2, -e)) < 1) { e--; c *= 2; } if (e + eBias >= 1) { value += rt / c; } else { value += rt * Math.pow(2, 1 - eBias); } if (value * c >= 2) { e++; c /= 2; } if (e + eBias >= eMax) { m = 0; e = eMax; } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen); e = e + eBias; } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); e = 0; } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = e << mLen | m; eLen += mLen; for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128; } var toString = {}.toString; var isArray = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; var INSPECT_MAX_BYTES = 50; /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; function kMaxLength() { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff; } function createBuffer(that, length) { if (kMaxLength() < length) { throw new RangeError('Invalid typed array length'); } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); that.__proto__ = Buffer.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { that = new Buffer(length); } that.length = length; } return that; } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer(arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length); } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error('If encoding is specified then the first argument must be a string'); } return allocUnsafe(this, arg); } return from(this, arg, encodingOrOffset, length); } Buffer.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype; return arr; }; function from(that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number'); } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(that, value, encodingOrOffset, length); } if (typeof value === 'string') { return fromString(that, value, encodingOrOffset); } return fromObject(that, value); } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length); }; if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype; Buffer.__proto__ = Uint8Array; } function assertSize(size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number'); } else if (size < 0) { throw new RangeError('"size" argument must not be negative'); } } function alloc(that, size, fill, encoding) { assertSize(size); if (size <= 0) { return createBuffer(that, size); } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill); } return createBuffer(that, size); } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding); }; function allocUnsafe(that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } } return that; } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(null, size); }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(null, size); }; function fromString(that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8'; } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding'); } var length = byteLength(string, encoding) | 0; that = createBuffer(that, length); var actual = that.write(string, encoding); if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') that = that.slice(0, actual); } return that; } function fromArrayLike(that, array) { var length = array.length < 0 ? 0 : checked(array.length) | 0; that = createBuffer(that, length); for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255; } return that; } function fromArrayBuffer(that, array, byteOffset, length) { array.byteLength; // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds'); } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds'); } if (byteOffset === undefined && length === undefined) { array = new Uint8Array(array); } else if (length === undefined) { array = new Uint8Array(array, byteOffset); } else { array = new Uint8Array(array, byteOffset, length); } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; that.__proto__ = Buffer.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); } return that; } function fromObject(that, obj) { if (internalIsBuffer(obj)) { var len = checked(obj.length) | 0; that = createBuffer(that, len); if (that.length === 0) { return that; } obj.copy(that, 0, 0, len); return that; } if (obj) { if (typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(that, 0); } return fromArrayLike(that, obj); } if (obj.type === 'Buffer' && isArray(obj.data)) { return fromArrayLike(that, obj.data); } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.'); } function checked(length) { // Note: cannot use `length < kMaxLength()` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes'); } return length | 0; } Buffer.isBuffer = isBuffer; function internalIsBuffer(b) { return !!(b != null && b._isBuffer); } Buffer.compare = function compare(a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers'); } if (a === b) return 0; var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } } if (x < y) return -1; if (y < x) return 1; return 0; }; Buffer.isEncoding = function isEncoding(encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true; default: return false; } }; Buffer.concat = function concat(list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers'); } if (list.length === 0) { return Buffer.alloc(0); } var i; if (length === undefined) { length = 0; for (i = 0; i < list.length; ++i) { length += list[i].length; } } var buffer = Buffer.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; if (!internalIsBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers'); } buf.copy(buffer, pos); pos += buf.length; } return buffer; }; function byteLength(string, encoding) { if (internalIsBuffer(string)) { return string.length; } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength; } if (typeof string !== 'string') { string = '' + string; } var len = string.length; if (len === 0) return 0; // Use a for loop to avoid recursion var loweredCase = false; for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len; case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2; case 'hex': return len >>> 1; case 'base64': return base64ToBytes(string).length; default: if (loweredCase) return utf8ToBytes(string).length; // assume utf8 encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } } Buffer.byteLength = byteLength; function slowToString(encoding, start, end) { var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0; } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return ''; } if (end === undefined || end > this.length) { end = this.length; } if (end <= 0) { return ''; } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0; start >>>= 0; if (end <= start) { return ''; } if (!encoding) encoding = 'utf8'; while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end); case 'utf8': case 'utf-8': return utf8Slice(this, start, end); case 'ascii': return asciiSlice(this, start, end); case 'latin1': case 'binary': return latin1Slice(this, start, end); case 'base64': return base64Slice(this, start, end); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end); default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); encoding = (encoding + '').toLowerCase(); loweredCase = true; } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true; function swap(b, n, m) { var i = b[n]; b[n] = b[m]; b[m] = i; } Buffer.prototype.swap16 = function swap16() { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits'); } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1); } return this; }; Buffer.prototype.swap32 = function swap32() { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits'); } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3); swap(this, i + 1, i + 2); } return this; }; Buffer.prototype.swap64 = function swap64() { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits'); } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7); swap(this, i + 1, i + 6); swap(this, i + 2, i + 5); swap(this, i + 3, i + 4); } return this; }; Buffer.prototype.toString = function toString() { var length = this.length | 0; if (length === 0) return ''; if (arguments.length === 0) return utf8Slice(this, 0, length); return slowToString.apply(this, arguments); }; Buffer.prototype.equals = function equals(b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer'); if (this === b) return true; return Buffer.compare(this, b) === 0; }; Buffer.prototype.inspect = function inspect() { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); if (this.length > max) str += ' ... '; } return ''; }; Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer'); } if (start === undefined) { start = 0; } if (end === undefined) { end = target ? target.length : 0; } if (thisStart === undefined) { thisStart = 0; } if (thisEnd === undefined) { thisEnd = this.length; } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index'); } if (thisStart >= thisEnd && start >= end) { return 0; } if (thisStart >= thisEnd) { return -1; } if (start >= end) { return 1; } start >>>= 0; end >>>= 0; thisStart >>>= 0; thisEnd >>>= 0; if (this === target) return 0; var x = thisEnd - thisStart; var y = end - start; var len = Math.min(x, y); var thisCopy = this.slice(thisStart, thisEnd); var targetCopy = target.slice(start, end); for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i]; y = targetCopy[i]; break; } } if (x < y) return -1; if (y < x) return 1; return 0; }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1; // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = 0; } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff; } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000; } byteOffset = +byteOffset; // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : buffer.length - 1; } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset; if (byteOffset >= buffer.length) { if (dir) return -1;else byteOffset = buffer.length - 1; } else if (byteOffset < 0) { if (dir) byteOffset = 0;else return -1; } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf if (internalIsBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1; } return arrayIndexOf(buffer, val, byteOffset, encoding, dir); } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); } } return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); } throw new TypeError('val must be string, number or Buffer'); } function arrayIndexOf(arr, val, byteOffset, encoding, dir) { var indexSize = 1; var arrLength = arr.length; var valLength = val.length; if (encoding !== undefined) { encoding = String(encoding).toLowerCase(); if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1; } indexSize = 2; arrLength /= 2; valLength /= 2; byteOffset /= 2; } } function read(buf, i) { if (indexSize === 1) { return buf[i]; } else { return buf.readUInt16BE(i * indexSize); } } var i; if (dir) { var foundIndex = -1; for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i; if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; } else { if (foundIndex !== -1) i -= i - foundIndex; foundIndex = -1; } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; for (i = byteOffset; i >= 0; i--) { var found = true; for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false; break; } } if (found) return i; } } return -1; } Buffer.prototype.includes = function includes(val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1; }; Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true); }; Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false); }; function hexWrite(buf, string, offset, length) { offset = Number(offset) || 0; var remaining = buf.length - offset; if (!length) { length = remaining; } else { length = Number(length); if (length > remaining) { length = remaining; } } // must be an even number of digits var strLen = string.length; if (strLen % 2 !== 0) throw new TypeError('Invalid hex string'); if (length > strLen / 2) { length = strLen / 2; } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16); if (isNaN(parsed)) return i; buf[offset + i] = parsed; } return i; } function utf8Write(buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); } function asciiWrite(buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length); } function latin1Write(buf, string, offset, length) { return asciiWrite(buf, string, offset, length); } function base64Write(buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length); } function ucs2Write(buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); } Buffer.prototype.write = function write(string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; length = this.length; offset = 0; // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset; length = this.length; offset = 0; // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0; if (isFinite(length)) { length = length | 0; if (encoding === undefined) encoding = 'utf8'; } else { encoding = length; length = undefined; } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported'); } var remaining = this.length - offset; if (length === undefined || length > remaining) length = remaining; if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds'); } if (!encoding) encoding = 'utf8'; var loweredCase = false; for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length); case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length); case 'ascii': return asciiWrite(this, string, offset, length); case 'latin1': case 'binary': return latin1Write(this, string, offset, length); case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length); case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length); default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); encoding = ('' + encoding).toLowerCase(); loweredCase = true; } } }; Buffer.prototype.toJSON = function toJSON() { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) }; }; function base64Slice(buf, start, end) { if (start === 0 && end === buf.length) { return fromByteArray(buf); } else { return fromByteArray(buf.slice(start, end)); } } function utf8Slice(buf, start, end) { end = Math.min(buf.length, end); var res = []; var i = start; while (i < end) { var firstByte = buf[i]; var codePoint = null; var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint; switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte; } break; case 2: secondByte = buf[i + 1]; if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; if (tempCodePoint > 0x7F) { codePoint = tempCodePoint; } } break; case 3: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint; } } break; case 4: secondByte = buf[i + 1]; thirdByte = buf[i + 2]; fourthByte = buf[i + 3]; if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint; } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD; bytesPerSequence = 1; } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000; res.push(codePoint >>> 10 & 0x3FF | 0xD800); codePoint = 0xDC00 | codePoint & 0x3FF; } res.push(codePoint); i += bytesPerSequence; } return decodeCodePointsArray(res); } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000; function decodeCodePointsArray(codePoints) { var len = codePoints.length; if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints); // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = ''; var i = 0; while (i < len) { res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); } return res; } function asciiSlice(buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F); } return ret; } function latin1Slice(buf, start, end) { var ret = ''; end = Math.min(buf.length, end); for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]); } return ret; } function hexSlice(buf, start, end) { var len = buf.length; if (!start || start < 0) start = 0; if (!end || end < 0 || end > len) end = len; var out = ''; for (var i = start; i < end; ++i) { out += toHex(buf[i]); } return out; } function utf16leSlice(buf, start, end) { var bytes = buf.slice(start, end); var res = ''; for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); } return res; } Buffer.prototype.slice = function slice(start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; if (start < 0) { start += len; if (start < 0) start = 0; } else if (start > len) { start = len; } if (end < 0) { end += len; if (end < 0) end = 0; } else if (end > len) { end = len; } if (end < start) end = start; var newBuf; if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); newBuf.__proto__ = Buffer.prototype; } else { var sliceLen = end - start; newBuf = new Buffer(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } } return newBuf; }; /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset(offset, ext, length) { if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); } Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } return val; }; Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { checkOffset(offset, byteLength, this.length); } var val = this[offset + --byteLength]; var mul = 1; while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul; } return val; }; Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset]; }; Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | this[offset + 1] << 8; }; Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] << 8 | this[offset + 1]; }; Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000; }; Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); }; Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var val = this[offset]; var mul = 1; var i = 0; while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); var i = byteLength; var mul = 1; var val = this[offset + --i]; while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul; } mul *= 0x80; if (val >= mul) val -= Math.pow(2, 8 * byteLength); return val; }; Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return this[offset]; return (0xff - this[offset] + 1) * -1; }; Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | this[offset + 1] << 8; return val & 0x8000 ? val | 0xFFFF0000 : val; }; Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | this[offset] << 8; return val & 0x8000 ? val | 0xFFFF0000 : val; }; Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; }; Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; }; Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, true, 23, 4); }; Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read(this, offset, false, 23, 4); }; Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, true, 52, 8); }; Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read(this, offset, false, 52, 8); }; function checkInt(buf, value, offset, ext, max, min) { if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); if (offset + ext > buf.length) throw new RangeError('Index out of range'); } Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var mul = 1; var i = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = value / mul & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1; checkInt(this, value, offset, byteLength, maxBytes, 0); } var i = byteLength - 1; var mul = 1; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = value / mul & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = value & 0xff; return offset + 1; }; function objectWriteUInt16(buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1; for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { buf[offset + i] = (value & 0xff << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8; } } Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value & 0xff; this[offset + 1] = value >>> 8; } else { objectWriteUInt16(this, value, offset, true); } return offset + 2; }; Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value >>> 8; this[offset + 1] = value & 0xff; } else { objectWriteUInt16(this, value, offset, false); } return offset + 2; }; function objectWriteUInt32(buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1; for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 0xff; } } Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = value >>> 24; this[offset + 2] = value >>> 16; this[offset + 1] = value >>> 8; this[offset] = value & 0xff; } else { objectWriteUInt32(this, value, offset, true); } return offset + 4; }; Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 0xff; } else { objectWriteUInt32(this, value, offset, false); } return offset + 4; }; Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = 0; var mul = 1; var sub = 0; this[offset] = value & 0xFF; while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1; } this[offset + i] = (value / mul >> 0) - sub & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1); checkInt(this, value, offset, byteLength, limit - 1, -limit); } var i = byteLength - 1; var mul = 1; var sub = 0; this[offset + i] = value & 0xFF; while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1; } this[offset + i] = (value / mul >> 0) - sub & 0xFF; } return offset + byteLength; }; Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = value & 0xff; return offset + 1; }; Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value & 0xff; this[offset + 1] = value >>> 8; } else { objectWriteUInt16(this, value, offset, true); } return offset + 2; }; Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value >>> 8; this[offset + 1] = value & 0xff; } else { objectWriteUInt16(this, value, offset, false); } return offset + 2; }; Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value & 0xff; this[offset + 1] = value >>> 8; this[offset + 2] = value >>> 16; this[offset + 3] = value >>> 24; } else { objectWriteUInt32(this, value, offset, true); } return offset + 4; }; Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (value < 0) value = 0xffffffff + value + 1; if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = value >>> 24; this[offset + 1] = value >>> 16; this[offset + 2] = value >>> 8; this[offset + 3] = value & 0xff; } else { objectWriteUInt32(this, value, offset, false); } return offset + 4; }; function checkIEEE754(buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range'); if (offset < 0) throw new RangeError('Index out of range'); } function writeFloat(buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4); } write(buf, value, offset, littleEndian, 23, 4); return offset + 4; } Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert); }; Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert); }; function writeDouble(buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8); } write(buf, value, offset, littleEndian, 52, 8); return offset + 8; } Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert); }; Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert); }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy(target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; if (!targetStart) targetStart = 0; if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done if (end === start) return 0; if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds'); } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds'); if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? if (end > this.length) end = this.length; if (target.length - targetStart < end - start) { end = target.length - targetStart + start; } var len = end - start; var i; if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; } } else { Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart); } return len; }; // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill(val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start; start = 0; end = this.length; } else if (typeof end === 'string') { encoding = end; end = this.length; } if (val.length === 1) { var code = val.charCodeAt(0); if (code < 256) { val = code; } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string'); } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding); } } else if (typeof val === 'number') { val = val & 255; } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index'); } if (end <= start) { return this; } start = start >>> 0; end = end === undefined ? this.length : end >>> 0; if (!val) val = 0; var i; if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val; } } else { var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; } } return this; }; // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; function base64clean(str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '='; } return str; } function stringtrim(str) { if (str.trim) return str.trim(); return str.replace(/^\s+|\s+$/g, ''); } function toHex(n) { if (n < 16) return '0' + n.toString(16); return n.toString(16); } function utf8ToBytes(string, units) { units = units || Infinity; var codePoint; var length = string.length; var leadSurrogate = null; var bytes = []; for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i); // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue; } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); continue; } // valid lead leadSurrogate = codePoint; continue; } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); leadSurrogate = codePoint; continue; } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); } leadSurrogate = null; // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break; bytes.push(codePoint); } else if (codePoint < 0x800) { if ((units -= 2) < 0) break; bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break; bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break; bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); } else { throw new Error('Invalid code point'); } } return bytes; } function asciiToBytes(str) { var byteArray = []; for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF); } return byteArray; } function utf16leToBytes(str, units) { var c, hi, lo; var byteArray = []; for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break; c = str.charCodeAt(i); hi = c >> 8; lo = c % 256; byteArray.push(lo); byteArray.push(hi); } return byteArray; } function base64ToBytes(str) { return toByteArray(base64clean(str)); } function blitBuffer(src, dst, offset, length) { for (var i = 0; i < length; ++i) { if (i + offset >= dst.length || i >= src.length) break; dst[i + offset] = src[i]; } return i; } function isnan(val) { return val !== val; // eslint-disable-line no-self-compare } // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually function isBuffer(obj) { return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)); } function isFastBuffer(obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj); } // For Node v0.10 support. Remove this eventually. function isSlowBuffer(obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)); } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function unwrapExports (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } function getCjsExportFromNamespace (n) { return n && n['default'] || n; } var fs = getCjsExportFromNamespace(_shim_fs$1); /** * @class */ class LineByLine { constructor(file, options) { options = options || {}; if (!options.readChunk) options.readChunk = 1024; if (!options.newLineCharacter) { options.newLineCharacter = 0x0a; //linux line ending } else { options.newLineCharacter = options.newLineCharacter.charCodeAt(0); } if (typeof file === 'number') { this.fd = file; } else { this.fd = fs.openSync(file, 'r'); } this.options = options; this.newLineCharacter = options.newLineCharacter; this.reset(); } _searchInBuffer(buffer, hexNeedle) { let found = -1; for (let i = 0; i <= buffer.length; i++) { let b_byte = buffer[i]; if (b_byte === hexNeedle) { found = i; break; } } return found; } reset() { this.eofReached = false; this.linesCache = []; this.fdPosition = 0; } close() { fs.closeSync(this.fd); this.fd = null; } _extractLines(buffer) { let line; const lines = []; let bufferPosition = 0; let lastNewLineBufferPosition = 0; while (true) { let bufferPositionValue = buffer[bufferPosition++]; if (bufferPositionValue === this.newLineCharacter) { line = buffer.slice(lastNewLineBufferPosition, bufferPosition); lines.push(line); lastNewLineBufferPosition = bufferPosition; } else if (!bufferPositionValue) { break; } } let leftovers = buffer.slice(lastNewLineBufferPosition, bufferPosition); if (leftovers.length) { lines.push(leftovers); } return lines; } _readChunk(lineLeftovers) { let totalBytesRead = 0; let bytesRead; const buffers = []; do { const readBuffer = new Buffer(this.options.readChunk); bytesRead = fs.readSync(this.fd, readBuffer, 0, this.options.readChunk, this.fdPosition); totalBytesRead = totalBytesRead + bytesRead; this.fdPosition = this.fdPosition + bytesRead; buffers.push(readBuffer); } while (bytesRead && this._searchInBuffer(buffers[buffers.length - 1], this.options.newLineCharacter) === -1); let bufferData = Buffer.concat(buffers); if (bytesRead < this.options.readChunk) { this.eofReached = true; bufferData = bufferData.slice(0, totalBytesRead); } if (totalBytesRead) { this.linesCache = this._extractLines(bufferData); if (lineLeftovers) { this.linesCache[0] = Buffer.concat([lineLeftovers, this.linesCache[0]]); } } return totalBytesRead; } next() { if (!this.fd) return false; let line = false; if (this.eofReached && this.linesCache.length === 0) { return line; } let bytesRead; if (!this.linesCache.length) { bytesRead = this._readChunk(); } if (this.linesCache.length) { line = this.linesCache.shift(); const lastLineCharacter = line[line.length - 1]; if (lastLineCharacter !== 0x0a) { bytesRead = this._readChunk(line); if (bytesRead) { line = this.linesCache.shift(); } } } if (this.eofReached && this.linesCache.length === 0) { this.close(); } if (line && line[line.length - 1] === this.newLineCharacter) { line = line.slice(0, line.length - 1); } return line; } } var readlines = LineByLine; /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ function fromPairs(pairs) { var index = -1, length = pairs == null ? 0 : pairs.length, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } var fromPairs_1 = fromPairs; class ConfigError extends Error {} class DebugError extends Error {} class UndefinedParserError extends Error {} var errors = { ConfigError, DebugError, UndefinedParserError }; function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } // based off https://github.com/defunctzombie/node-process/blob/master/browser.js function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout() { throw new Error('clearTimeout has not been defined'); } var cachedSetTimeout = defaultSetTimout; var cachedClearTimeout = defaultClearTimeout; if (typeof global$1.setTimeout === 'function') { cachedSetTimeout = setTimeout; } if (typeof global$1.clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } function nextTick(fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; var title = 'browser'; var platform = 'browser'; var browser = true; var env = {}; var argv = []; var version$1 = ''; // empty string to avoid regexp issues var versions = {}; var release = {}; var config = {}; function noop() {} var on = noop; var addListener = noop; var once = noop; var off = noop; var removeListener = noop; var removeAllListeners = noop; var emit = noop; function binding(name) { throw new Error('process.binding is not supported'); } function cwd() { return '/'; } function chdir(dir) { throw new Error('process.chdir is not supported'); } function umask() { return 0; } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js var performance = global$1.performance || {}; var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () { return new Date().getTime(); }; // generate timestamp or delta // see http://nodejs.org/api/process.html#process_process_hrtime function hrtime(previousTimestamp) { var clocktime = performanceNow.call(performance) * 1e-3; var seconds = Math.floor(clocktime); var nanoseconds = Math.floor(clocktime % 1 * 1e9); if (previousTimestamp) { seconds = seconds - previousTimestamp[0]; nanoseconds = nanoseconds - previousTimestamp[1]; if (nanoseconds < 0) { seconds--; nanoseconds += 1e9; } } return [seconds, nanoseconds]; } var startTime = new Date(); function uptime() { var currentTime = new Date(); var dif = currentTime - startTime; return dif / 1000; } var process = { nextTick: nextTick, title: title, browser: browser, env: env, argv: argv, version: version$1, versions: versions, on: on, addListener: addListener, once: once, off: off, removeListener: removeListener, removeAllListeners: removeAllListeners, emit: emit, binding: binding, cwd: cwd, chdir: chdir, umask: umask, hrtime: hrtime, platform: platform, release: release, config: config, uptime: uptime }; const debug = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error('SEMVER', ...args) : () => {}; var debug_1 = debug; // Note: this is the semver.org version of the spec that it implements // Not necessarily the package version of this code. const SEMVER_SPEC_VERSION = '2.0.0'; const MAX_LENGTH = 256; const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || /* istanbul ignore next */ 9007199254740991; // Max safe segment length for coercion. const MAX_SAFE_COMPONENT_LENGTH = 16; var constants = { SEMVER_SPEC_VERSION, MAX_LENGTH, MAX_SAFE_INTEGER, MAX_SAFE_COMPONENT_LENGTH }; var re_1 = createCommonjsModule(function (module, exports) { const { MAX_SAFE_COMPONENT_LENGTH } = constants; exports = module.exports = {}; // The actual regexps go on exports.re const re = exports.re = []; const src = exports.src = []; const t = exports.t = {}; let R = 0; const createToken = (name, value, isGlobal) => { const index = R++; debug_1(index, value); t[name] = index; src[index] = value; re[index] = new RegExp(value, isGlobal ? 'g' : undefined); }; // The following Regular Expressions can be used for tokenizing, // validating, and parsing SemVer version strings. // ## Numeric Identifier // A single `0`, or a non-zero digit followed by zero or more digits. createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); // ## Non-numeric Identifier // Zero or more digits, followed by a letter or hyphen, and then zero or // more letters, digits, or hyphens. createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); // ## Main Version // Three dot-separated numeric identifiers. createToken('MAINVERSION', "(".concat(src[t.NUMERICIDENTIFIER], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIER], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIER], ")")); createToken('MAINVERSIONLOOSE', "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")")); // ## Pre-release Version Identifier // A numeric identifier, or a non-numeric identifier. createToken('PRERELEASEIDENTIFIER', "(?:".concat(src[t.NUMERICIDENTIFIER], "|").concat(src[t.NONNUMERICIDENTIFIER], ")")); createToken('PRERELEASEIDENTIFIERLOOSE', "(?:".concat(src[t.NUMERICIDENTIFIERLOOSE], "|").concat(src[t.NONNUMERICIDENTIFIER], ")")); // ## Pre-release Version // Hyphen, followed by one or more dot-separated pre-release version // identifiers. createToken('PRERELEASE', "(?:-(".concat(src[t.PRERELEASEIDENTIFIER], "(?:\\.").concat(src[t.PRERELEASEIDENTIFIER], ")*))")); createToken('PRERELEASELOOSE', "(?:-?(".concat(src[t.PRERELEASEIDENTIFIERLOOSE], "(?:\\.").concat(src[t.PRERELEASEIDENTIFIERLOOSE], ")*))")); // ## Build Metadata Identifier // Any combination of digits, letters, or hyphens. createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); // ## Build Metadata // Plus sign, followed by one or more period-separated build metadata // identifiers. createToken('BUILD', "(?:\\+(".concat(src[t.BUILDIDENTIFIER], "(?:\\.").concat(src[t.BUILDIDENTIFIER], ")*))")); // ## Full Version String // A main version, followed optionally by a pre-release version and // build metadata. // Note that the only major, minor, patch, and pre-release sections of // the version string are capturing groups. The build metadata is not a // capturing group, because it should not ever be used in version // comparison. createToken('FULLPLAIN', "v?".concat(src[t.MAINVERSION]).concat(src[t.PRERELEASE], "?").concat(src[t.BUILD], "?")); createToken('FULL', "^".concat(src[t.FULLPLAIN], "$")); // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty // common in the npm registry. createToken('LOOSEPLAIN', "[v=\\s]*".concat(src[t.MAINVERSIONLOOSE]).concat(src[t.PRERELEASELOOSE], "?").concat(src[t.BUILD], "?")); createToken('LOOSE', "^".concat(src[t.LOOSEPLAIN], "$")); createToken('GTLT', '((?:<|>)?=?)'); // Something like "2.*" or "1.2.x". // Note that "x.x" is a valid xRange identifer, meaning "any version" // Only the first item is strictly required. createToken('XRANGEIDENTIFIERLOOSE', "".concat(src[t.NUMERICIDENTIFIERLOOSE], "|x|X|\\*")); createToken('XRANGEIDENTIFIER', "".concat(src[t.NUMERICIDENTIFIER], "|x|X|\\*")); createToken('XRANGEPLAIN', "[v=\\s]*(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:".concat(src[t.PRERELEASE], ")?").concat(src[t.BUILD], "?") + ")?)?"); createToken('XRANGEPLAINLOOSE', "[v=\\s]*(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:".concat(src[t.PRERELEASELOOSE], ")?").concat(src[t.BUILD], "?") + ")?)?"); createToken('XRANGE', "^".concat(src[t.GTLT], "\\s*").concat(src[t.XRANGEPLAIN], "$")); createToken('XRANGELOOSE', "^".concat(src[t.GTLT], "\\s*").concat(src[t.XRANGEPLAINLOOSE], "$")); // Coercion. // Extract anything that could conceivably be a part of a valid semver createToken('COERCE', "".concat('(^|[^\\d])' + '(\\d{1,').concat(MAX_SAFE_COMPONENT_LENGTH, "})") + "(?:\\.(\\d{1,".concat(MAX_SAFE_COMPONENT_LENGTH, "}))?") + "(?:\\.(\\d{1,".concat(MAX_SAFE_COMPONENT_LENGTH, "}))?") + "(?:$|[^\\d])"); createToken('COERCERTL', src[t.COERCE], true); // Tilde ranges. // Meaning is "reasonably at or greater than" createToken('LONETILDE', '(?:~>?)'); createToken('TILDETRIM', "(\\s*)".concat(src[t.LONETILDE], "\\s+"), true); exports.tildeTrimReplace = '$1~'; createToken('TILDE', "^".concat(src[t.LONETILDE]).concat(src[t.XRANGEPLAIN], "$")); createToken('TILDELOOSE', "^".concat(src[t.LONETILDE]).concat(src[t.XRANGEPLAINLOOSE], "$")); // Caret ranges. // Meaning is "at least and backwards compatible with" createToken('LONECARET', '(?:\\^)'); createToken('CARETTRIM', "(\\s*)".concat(src[t.LONECARET], "\\s+"), true); exports.caretTrimReplace = '$1^'; createToken('CARET', "^".concat(src[t.LONECARET]).concat(src[t.XRANGEPLAIN], "$")); createToken('CARETLOOSE', "^".concat(src[t.LONECARET]).concat(src[t.XRANGEPLAINLOOSE], "$")); // A simple gt/lt/eq thing, or just "" to indicate "any version" createToken('COMPARATORLOOSE', "^".concat(src[t.GTLT], "\\s*(").concat(src[t.LOOSEPLAIN], ")$|^$")); createToken('COMPARATOR', "^".concat(src[t.GTLT], "\\s*(").concat(src[t.FULLPLAIN], ")$|^$")); // An expression to strip any whitespace between the gtlt and the thing // it modifies, so that `> 1.2.3` ==> `>1.2.3` createToken('COMPARATORTRIM', "(\\s*)".concat(src[t.GTLT], "\\s*(").concat(src[t.LOOSEPLAIN], "|").concat(src[t.XRANGEPLAIN], ")"), true); exports.comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4` // Note that these all use the loose form, because they'll be // checked against either the strict or loose comparator form // later. createToken('HYPHENRANGE', "^\\s*(".concat(src[t.XRANGEPLAIN], ")") + "\\s+-\\s+" + "(".concat(src[t.XRANGEPLAIN], ")") + "\\s*$"); createToken('HYPHENRANGELOOSE', "^\\s*(".concat(src[t.XRANGEPLAINLOOSE], ")") + "\\s+-\\s+" + "(".concat(src[t.XRANGEPLAINLOOSE], ")") + "\\s*$"); // Star ranges basically just allow anything at all. createToken('STAR', '(<|>)?=?\\s*\\*'); }); var re_2 = re_1.re; var re_3 = re_1.src; var re_4 = re_1.t; var re_5 = re_1.tildeTrimReplace; var re_6 = re_1.caretTrimReplace; var re_7 = re_1.comparatorTrimReplace; const numeric = /^[0-9]+$/; const compareIdentifiers = (a, b) => { const anum = numeric.test(a); const bnum = numeric.test(b); if (anum && bnum) { a = +a; b = +b; } return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; }; const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a); var identifiers = { compareIdentifiers, rcompareIdentifiers }; const { MAX_LENGTH: MAX_LENGTH$1, MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1 } = constants; const { re, t } = re_1; const { compareIdentifiers: compareIdentifiers$1 } = identifiers; class SemVer { constructor(version, options) { if (!options || typeof options !== 'object') { options = { loose: !!options, includePrerelease: false }; } if (version instanceof SemVer) { if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { return version; } else { version = version.version; } } else if (typeof version !== 'string') { throw new TypeError("Invalid Version: ".concat(version)); } if (version.length > MAX_LENGTH$1) { throw new TypeError("version is longer than ".concat(MAX_LENGTH$1, " characters")); } debug_1('SemVer', version, options); this.options = options; this.loose = !!options.loose; // this isn't actually relevant for versions, but keep it so that we // don't run into trouble passing this.options around. this.includePrerelease = !!options.includePrerelease; const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]); if (!m) { throw new TypeError("Invalid Version: ".concat(version)); } this.raw = version; // these are actually numbers this.major = +m[1]; this.minor = +m[2]; this.patch = +m[3]; if (this.major > MAX_SAFE_INTEGER$1 || this.major < 0) { throw new TypeError('Invalid major version'); } if (this.minor > MAX_SAFE_INTEGER$1 || this.minor < 0) { throw new TypeError('Invalid minor version'); } if (this.patch > MAX_SAFE_INTEGER$1 || this.patch < 0) { throw new TypeError('Invalid patch version'); } // numberify any prerelease numeric ids if (!m[4]) { this.prerelease = []; } else { this.prerelease = m[4].split('.').map(id => { if (/^[0-9]+$/.test(id)) { const num = +id; if (num >= 0 && num < MAX_SAFE_INTEGER$1) { return num; } } return id; }); } this.build = m[5] ? m[5].split('.') : []; this.format(); } format() { this.version = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); if (this.prerelease.length) { this.version += "-".concat(this.prerelease.join('.')); } return this.version; } toString() { return this.version; } compare(other) { debug_1('SemVer.compare', this.version, this.options, other); if (!(other instanceof SemVer)) { if (typeof other === 'string' && other === this.version) { return 0; } other = new SemVer(other, this.options); } if (other.version === this.version) { return 0; } return this.compareMain(other) || this.comparePre(other); } compareMain(other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options); } return compareIdentifiers$1(this.major, other.major) || compareIdentifiers$1(this.minor, other.minor) || compareIdentifiers$1(this.patch, other.patch); } comparePre(other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options); } // NOT having a prerelease is > having one if (this.prerelease.length && !other.prerelease.length) { return -1; } else if (!this.prerelease.length && other.prerelease.length) { return 1; } else if (!this.prerelease.length && !other.prerelease.length) { return 0; } let i = 0; do { const a = this.prerelease[i]; const b = other.prerelease[i]; debug_1('prerelease compare', i, a, b); if (a === undefined && b === undefined) { return 0; } else if (b === undefined) { return 1; } else if (a === undefined) { return -1; } else if (a === b) { continue; } else { return compareIdentifiers$1(a, b); } } while (++i); } compareBuild(other) { if (!(other instanceof SemVer)) { other = new SemVer(other, this.options); } let i = 0; do { const a = this.build[i]; const b = other.build[i]; debug_1('prerelease compare', i, a, b); if (a === undefined && b === undefined) { return 0; } else if (b === undefined) { return 1; } else if (a === undefined) { return -1; } else if (a === b) { continue; } else { return compareIdentifiers$1(a, b); } } while (++i); } // preminor will bump the version up to the next minor release, and immediately // down to pre-release. premajor and prepatch work the same way. inc(release, identifier) { switch (release) { case 'premajor': this.prerelease.length = 0; this.patch = 0; this.minor = 0; this.major++; this.inc('pre', identifier); break; case 'preminor': this.prerelease.length = 0; this.patch = 0; this.minor++; this.inc('pre', identifier); break; case 'prepatch': // If this is already a prerelease, it will bump to the next version // drop any prereleases that might already exist, since they are not // relevant at this point. this.prerelease.length = 0; this.inc('patch', identifier); this.inc('pre', identifier); break; // If the input is a non-prerelease version, this acts the same as // prepatch. case 'prerelease': if (this.prerelease.length === 0) { this.inc('patch', identifier); } this.inc('pre', identifier); break; case 'major': // If this is a pre-major version, bump up to the same major version. // Otherwise increment major. // 1.0.0-5 bumps to 1.0.0 // 1.1.0 bumps to 2.0.0 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { this.major++; } this.minor = 0; this.patch = 0; this.prerelease = []; break; case 'minor': // If this is a pre-minor version, bump up to the same minor version. // Otherwise increment minor. // 1.2.0-5 bumps to 1.2.0 // 1.2.1 bumps to 1.3.0 if (this.patch !== 0 || this.prerelease.length === 0) { this.minor++; } this.patch = 0; this.prerelease = []; break; case 'patch': // If this is not a pre-release version, it will increment the patch. // If it is a pre-release it will bump up to the same patch version. // 1.2.0-5 patches to 1.2.0 // 1.2.0 patches to 1.2.1 if (this.prerelease.length === 0) { this.patch++; } this.prerelease = []; break; // This probably shouldn't be used publicly. // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. case 'pre': if (this.prerelease.length === 0) { this.prerelease = [0]; } else { let i = this.prerelease.length; while (--i >= 0) { if (typeof this.prerelease[i] === 'number') { this.prerelease[i]++; i = -2; } } if (i === -1) { // didn't increment anything this.prerelease.push(0); } } if (identifier) { // 1.2.0-beta.1 bumps to 1.2.0-beta.2, // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 if (this.prerelease[0] === identifier) { if (isNaN(this.prerelease[1])) { this.prerelease = [identifier, 0]; } } else { this.prerelease = [identifier, 0]; } } break; default: throw new Error("invalid increment argument: ".concat(release)); } this.format(); this.raw = this.version; return this; } } var semver = SemVer; const compare = (a, b, loose) => new semver(a, loose).compare(new semver(b, loose)); var compare_1 = compare; const lt = (a, b, loose) => compare_1(a, b, loose) < 0; var lt_1 = lt; const gte = (a, b, loose) => compare_1(a, b, loose) >= 0; var gte_1 = gte; var arrayify = (object, keyName) => Object.entries(object).map(([key, value]) => Object.assign({ [keyName]: key }, value)); var dedent_1 = createCommonjsModule(function (module) { function dedent(strings) { var raw = void 0; if (typeof strings === "string") { // dedent can be used as a plain function raw = [strings]; } else { raw = strings.raw; } // first, perform interpolation var result = ""; for (var i = 0; i < raw.length; i++) { result += raw[i]. // join lines when there is a suppressed newline replace(/\\\n[ \t]*/g, ""). // handle escaped backticks replace(/\\`/g, "`"); if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) { result += arguments.length <= i + 1 ? undefined : arguments[i + 1]; } } // now strip indentation var lines = result.split("\n"); var mindent = null; lines.forEach(function (l) { var m = l.match(/^(\s+)\S+/); if (m) { var indent = m[1].length; if (!mindent) { // this is the first indented line mindent = indent; } else { mindent = Math.min(mindent, indent); } } }); if (mindent !== null) { result = lines.map(function (l) { return l[0] === " " ? l.slice(mindent) : l; }).join("\n"); } // dedent eats leading and trailing whitespace too result = result.trim(); // handle escaped newlines at the end to ensure they don't get stripped too return result.replace(/\\n/g, "\n"); } { module.exports = dedent; } }); function _templateObject6() { const data = _taggedTemplateLiteral(["\n Require either '@prettier' or '@format' to be present in the file's first docblock comment\n in order for it to be formatted.\n "]); _templateObject6 = function _templateObject6() { return data; }; return data; } function _templateObject5() { const data = _taggedTemplateLiteral(["\n Format code starting at a given character offset.\n The range will extend backwards to the start of the first line containing the selected statement.\n This option cannot be used with --cursor-offset.\n "]); _templateObject5 = function _templateObject5() { return data; }; return data; } function _templateObject4() { const data = _taggedTemplateLiteral(["\n Format code ending at a given character offset (exclusive).\n The range will extend forwards to the end of the selected statement.\n This option cannot be used with --cursor-offset.\n "]); _templateObject4 = function _templateObject4() { return data; }; return data; } function _templateObject3() { const data = _taggedTemplateLiteral(["\n Custom directory that contains prettier plugins in node_modules subdirectory.\n Overrides default behavior when plugins are searched relatively to the location of Prettier.\n Multiple values are accepted.\n "]); _templateObject3 = function _templateObject3() { return data; }; return data; } function _templateObject2() { const data = _taggedTemplateLiteral(["\n Maintain existing\n (mixed values within one file are normalised by looking at what's used after the first line)\n "]); _templateObject2 = function _templateObject2() { return data; }; return data; } function _templateObject() { const data = _taggedTemplateLiteral(["\n Print (to stderr) where a cursor at the given position would move to after formatting.\n This option cannot be used with --range-start and --range-end.\n "]); _templateObject = function _templateObject() { return data; }; return data; } const CATEGORY_CONFIG = "Config"; const CATEGORY_EDITOR = "Editor"; const CATEGORY_FORMAT = "Format"; const CATEGORY_OTHER = "Other"; const CATEGORY_OUTPUT = "Output"; const CATEGORY_GLOBAL = "Global"; const CATEGORY_SPECIAL = "Special"; /** * @typedef {Object} OptionInfo * @property {string} [since] - available since version * @property {string} category * @property {'int' | 'boolean' | 'choice' | 'path'} type * @property {boolean} [array] - indicate it's an array of the specified type * @property {OptionValueInfo} [default] * @property {OptionRangeInfo} [range] - for type int * @property {string} description * @property {string} [deprecated] - deprecated since version * @property {OptionRedirectInfo} [redirect] - redirect deprecated option * @property {(value: any) => boolean} [exception] * @property {OptionChoiceInfo[]} [choices] - for type choice * @property {string} [cliName] * @property {string} [cliCategory] * @property {string} [cliDescription] * * @typedef {number | boolean | string} OptionValue * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo * * @typedef {Object} OptionRedirectInfo * @property {string} option * @property {OptionValue} value * * @typedef {Object} OptionRangeInfo * @property {number} start - recommended range start * @property {number} end - recommended range end * @property {number} step - recommended range step * * @typedef {Object} OptionChoiceInfo * @property {boolean | string} value - boolean for the option that is originally boolean type * @property {string} description * @property {string} [since] - undefined if available since the first version of the option * @property {string} [deprecated] - deprecated since version * @property {OptionValueInfo} [redirect] - redirect deprecated value */ /** @type {{ [name: string]: OptionInfo }} */ const options = { cursorOffset: { since: "1.4.0", category: CATEGORY_SPECIAL, type: "int", default: -1, range: { start: -1, end: Infinity, step: 1 }, description: dedent_1(_templateObject()), cliCategory: CATEGORY_EDITOR }, endOfLine: { since: "1.15.0", category: CATEGORY_GLOBAL, type: "choice", default: [{ since: "1.15.0", value: "auto" }, { since: "2.0.0", value: "lf" }], description: "Which end of line characters to apply.", choices: [{ value: "lf", description: "Line Feed only (\\n), common on Linux and macOS as well as inside git repos" }, { value: "crlf", description: "Carriage Return + Line Feed characters (\\r\\n), common on Windows" }, { value: "cr", description: "Carriage Return character only (\\r), used very rarely" }, { value: "auto", description: dedent_1(_templateObject2()) }] }, filepath: { since: "1.4.0", category: CATEGORY_SPECIAL, type: "path", description: "Specify the input filepath. This will be used to do parser inference.", cliName: "stdin-filepath", cliCategory: CATEGORY_OTHER, cliDescription: "Path to the file to pretend that stdin comes from." }, insertPragma: { since: "1.8.0", category: CATEGORY_SPECIAL, type: "boolean", default: false, description: "Insert @format pragma into file's first docblock comment.", cliCategory: CATEGORY_OTHER }, parser: { since: "0.0.10", category: CATEGORY_GLOBAL, type: "choice", default: [{ since: "0.0.10", value: "babylon" }, { since: "1.13.0", value: undefined }], description: "Which parser to use.", exception: value => typeof value === "string" || typeof value === "function", choices: [{ value: "flow", description: "Flow" }, { value: "babel", since: "1.16.0", description: "JavaScript" }, { value: "babel-flow", since: "1.16.0", description: "Flow" }, { value: "babel-ts", since: "2.0.0", description: "TypeScript" }, { value: "typescript", since: "1.4.0", description: "TypeScript" }, { value: "css", since: "1.7.1", description: "CSS" }, { value: "less", since: "1.7.1", description: "Less" }, { value: "scss", since: "1.7.1", description: "SCSS" }, { value: "json", since: "1.5.0", description: "JSON" }, { value: "json5", since: "1.13.0", description: "JSON5" }, { value: "json-stringify", since: "1.13.0", description: "JSON.stringify" }, { value: "graphql", since: "1.5.0", description: "GraphQL" }, { value: "markdown", since: "1.8.0", description: "Markdown" }, { value: "mdx", since: "1.15.0", description: "MDX" }, { value: "vue", since: "1.10.0", description: "Vue" }, { value: "yaml", since: "1.14.0", description: "YAML" }, { value: "glimmer", since: null, description: "Handlebars" }, { value: "html", since: "1.15.0", description: "HTML" }, { value: "angular", since: "1.15.0", description: "Angular" }, { value: "lwc", since: "1.17.0", description: "Lightning Web Components" }] }, plugins: { since: "1.10.0", type: "path", array: true, default: [{ value: [] }], category: CATEGORY_GLOBAL, description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.", exception: value => typeof value === "string" || typeof value === "object", cliName: "plugin", cliCategory: CATEGORY_CONFIG }, pluginSearchDirs: { since: "1.13.0", type: "path", array: true, default: [{ value: [] }], category: CATEGORY_GLOBAL, description: dedent_1(_templateObject3()), exception: value => typeof value === "string" || typeof value === "object", cliName: "plugin-search-dir", cliCategory: CATEGORY_CONFIG }, printWidth: { since: "0.0.0", category: CATEGORY_GLOBAL, type: "int", default: 80, description: "The line length where Prettier will try wrap.", range: { start: 0, end: Infinity, step: 1 } }, rangeEnd: { since: "1.4.0", category: CATEGORY_SPECIAL, type: "int", default: Infinity, range: { start: 0, end: Infinity, step: 1 }, description: dedent_1(_templateObject4()), cliCategory: CATEGORY_EDITOR }, rangeStart: { since: "1.4.0", category: CATEGORY_SPECIAL, type: "int", default: 0, range: { start: 0, end: Infinity, step: 1 }, description: dedent_1(_templateObject5()), cliCategory: CATEGORY_EDITOR }, requirePragma: { since: "1.7.0", category: CATEGORY_SPECIAL, type: "boolean", default: false, description: dedent_1(_templateObject6()), cliCategory: CATEGORY_OTHER }, tabWidth: { type: "int", category: CATEGORY_GLOBAL, default: 2, description: "Number of spaces per indentation level.", range: { start: 0, end: Infinity, step: 1 } }, useTabs: { since: "1.0.0", category: CATEGORY_GLOBAL, type: "boolean", default: false, description: "Indent with tabs instead of spaces." } }; var coreOptions = { CATEGORY_CONFIG, CATEGORY_EDITOR, CATEGORY_FORMAT, CATEGORY_OTHER, CATEGORY_OUTPUT, CATEGORY_GLOBAL, CATEGORY_SPECIAL, options }; var require$$0 = getCjsExportFromNamespace(_package$1); const semver$1 = { compare: compare_1, lt: lt_1, gte: gte_1 }; const currentVersion = require$$0.version; const coreOptions$1 = coreOptions.options; /** * Strings in `plugins` and `pluginSearchDirs` are handled by a wrapped version * of this function created by `withPlugins`. Don't pass them here directly. * @param {object} param0 * @param {(string | object)[]=} param0.plugins Strings are resolved by `withPlugins`. * @param {string[]=} param0.pluginSearchDirs Added by `withPlugins`. * @param {boolean=} param0.showUnreleased * @param {boolean=} param0.showDeprecated * @param {boolean=} param0.showInternal */ function getSupportInfo({ plugins = [], showUnreleased = false, showDeprecated = false, showInternal = false } = {}) { // pre-release version is smaller than the normal version in semver, // we need to treat it as the normal one so as to test new features. const version = currentVersion.split("-", 1)[0]; const options = arrayify(Object.assign({}, ...plugins.map(({ options }) => options), coreOptions$1), "name").filter(option => filterSince(option) && filterDeprecated(option)).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1).map(mapInternal).map(option => { option = Object.assign({}, option); if (Array.isArray(option.default)) { option.default = option.default.length === 1 ? option.default[0].value : option.default.filter(filterSince).sort((info1, info2) => semver$1.compare(info2.since, info1.since))[0].value; } if (Array.isArray(option.choices)) { option.choices = option.choices.filter(option => filterSince(option) && filterDeprecated(option)); } const filteredPlugins = plugins.filter(plugin => plugin.defaultOptions && plugin.defaultOptions[option.name] !== undefined); const pluginDefaults = filteredPlugins.reduce((reduced, plugin) => { reduced[plugin.name] = plugin.defaultOptions[option.name]; return reduced; }, {}); return Object.assign({}, option, { pluginDefaults }); }); const languages = plugins.reduce((all, plugin) => all.concat(plugin.languages || []), []).filter(filterSince); return { languages, options }; function filterSince(object) { return showUnreleased || !("since" in object) || object.since && semver$1.gte(version, object.since); } function filterDeprecated(object) { return showDeprecated || !("deprecated" in object) || object.deprecated && semver$1.lt(version, object.deprecated); } function mapInternal(object) { if (showInternal) { return object; } const newObject = _objectWithoutPropertiesLoose(object, ["cliName", "cliCategory", "cliDescription"]); return newObject; } } var support = { getSupportInfo }; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var _extendStatics = function extendStatics(d, b) { _extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; } || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return _extendStatics(d, b); }; function __extends(d, b) { _extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var _assign = function __assign() { _assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return _assign.apply(this, arguments); }; function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); }; } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function sent() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __exportStar(m, exports) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } function __values(o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function next() { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __spreadArrays() { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result.default = mod; return result; } function __importDefault(mod) { return mod && mod.__esModule ? mod : { default: mod }; } var tslib_es6 = /*#__PURE__*/Object.freeze({ __proto__: null, __extends: __extends, get __assign () { return _assign; }, __rest: __rest, __decorate: __decorate, __param: __param, __metadata: __metadata, __awaiter: __awaiter, __generator: __generator, __exportStar: __exportStar, __values: __values, __read: __read, __spread: __spread, __spreadArrays: __spreadArrays, __await: __await, __asyncGenerator: __asyncGenerator, __asyncDelegator: __asyncDelegator, __asyncValues: __asyncValues, __makeTemplateObject: __makeTemplateObject, __importStar: __importStar, __importDefault: __importDefault }); var api = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.apiDescriptor = { key: _key => /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(_key) ? _key : JSON.stringify(_key), value(value) { if (value === null || typeof value !== 'object') { return JSON.stringify(value); } if (Array.isArray(value)) { return "[".concat(value.map(subValue => exports.apiDescriptor.value(subValue)).join(', '), "]"); } const keys = Object.keys(value); return keys.length === 0 ? '{}' : "{ ".concat(keys.map(key => "".concat(exports.apiDescriptor.key(key), ": ").concat(exports.apiDescriptor.value(value[key]))).join(', '), " }"); }, pair: ({ key, value }) => exports.apiDescriptor.value({ [key]: value }) }; }); unwrapExports(api); var api_1 = api.apiDescriptor; var tslib_1 = getCjsExportFromNamespace(tslib_es6); var descriptors = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(api, exports); }); unwrapExports(descriptors); var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; var escapeStringRegexp = function escapeStringRegexp(str) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } return str.replace(matchOperatorsRe, '\\$&'); }; var colorName = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; var conversions = createCommonjsModule(function (module) { /* MIT license */ // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) var reverseKeywords = {}; for (var key in colorName) { if (colorName.hasOwnProperty(key)) { reverseKeywords[colorName[key]] = key; } } var convert = module.exports = { rgb: { channels: 3, labels: 'rgb' }, hsl: { channels: 3, labels: 'hsl' }, hsv: { channels: 3, labels: 'hsv' }, hwb: { channels: 3, labels: 'hwb' }, cmyk: { channels: 4, labels: 'cmyk' }, xyz: { channels: 3, labels: 'xyz' }, lab: { channels: 3, labels: 'lab' }, lch: { channels: 3, labels: 'lch' }, hex: { channels: 1, labels: ['hex'] }, keyword: { channels: 1, labels: ['keyword'] }, ansi16: { channels: 1, labels: ['ansi16'] }, ansi256: { channels: 1, labels: ['ansi256'] }, hcg: { channels: 3, labels: ['h', 'c', 'g'] }, apple: { channels: 3, labels: ['r16', 'g16', 'b16'] }, gray: { channels: 1, labels: ['gray'] } }; // hide .channels and .labels properties for (var model in convert) { if (convert.hasOwnProperty(model)) { if (!('channels' in convert[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert[model])) { throw new Error('missing channel labels property: ' + model); } if (convert[model].labels.length !== convert[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } var channels = convert[model].channels; var labels = convert[model].labels; delete convert[model].channels; delete convert[model].labels; Object.defineProperty(convert[model], 'channels', { value: channels }); Object.defineProperty(convert[model], 'labels', { value: labels }); } } convert.rgb.hsl = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var min = Math.min(r, g, b); var max = Math.max(r, g, b); var delta = max - min; var h; var s; var l; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert.rgb.hsv = function (rgb) { var rdif; var gdif; var bdif; var h; var s; var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var v = Math.max(r, g, b); var diff = v - Math.min(r, g, b); var diffc = function diffc(c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = 1 / 3 + rdif - bdif; } else if (b === v) { h = 2 / 3 + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [h * 360, s * 100, v * 100]; }; convert.rgb.hwb = function (rgb) { var r = rgb[0]; var g = rgb[1]; var b = rgb[2]; var h = convert.rgb.hsl(rgb)[0]; var w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert.rgb.cmyk = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var c; var m; var y; var k; k = Math.min(1 - r, 1 - g, 1 - b); c = (1 - r - k) / (1 - k) || 0; m = (1 - g - k) / (1 - k) || 0; y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; /** * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance * */ function comparativeDistance(x, y) { return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2); } convert.rgb.keyword = function (rgb) { var reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } var currentClosestDistance = Infinity; var currentClosestKeyword; for (var keyword in colorName) { if (colorName.hasOwnProperty(keyword)) { var value = colorName[keyword]; // Compute comparative distance var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } } return currentClosestKeyword; }; convert.keyword.rgb = function (keyword) { return colorName[keyword]; }; convert.rgb.xyz = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; // assume sRGB r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; var x = r * 0.4124 + g * 0.3576 + b * 0.1805; var y = r * 0.2126 + g * 0.7152 + b * 0.0722; var z = r * 0.0193 + g * 0.1192 + b * 0.9505; return [x * 100, y * 100, z * 100]; }; convert.rgb.lab = function (rgb) { var xyz = convert.rgb.xyz(rgb); var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; l = 116 * y - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.hsl.rgb = function (hsl) { var h = hsl[0] / 360; var s = hsl[1] / 100; var l = hsl[2] / 100; var t1; var t2; var t3; var rgb; var val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } t1 = 2 * l - t2; rgb = [0, 0, 0]; for (var i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert.hsl.hsv = function (hsl) { var h = hsl[0]; var s = hsl[1] / 100; var l = hsl[2] / 100; var smin = s; var lmin = Math.max(l, 0.01); var sv; var v; l *= 2; s *= l <= 1 ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; v = (l + s) / 2; sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); return [h, sv * 100, v * 100]; }; convert.hsv.rgb = function (hsv) { var h = hsv[0] / 60; var s = hsv[1] / 100; var v = hsv[2] / 100; var hi = Math.floor(h) % 6; var f = h - Math.floor(h); var p = 255 * v * (1 - s); var q = 255 * v * (1 - s * f); var t = 255 * v * (1 - s * (1 - f)); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert.hsv.hsl = function (hsv) { var h = hsv[0]; var s = hsv[1] / 100; var v = hsv[2] / 100; var vmin = Math.max(v, 0.01); var lmin; var sl; var l; l = (2 - s) * v; lmin = (2 - s) * vmin; sl = s * vmin; sl /= lmin <= 1 ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert.hwb.rgb = function (hwb) { var h = hwb[0] / 360; var wh = hwb[1] / 100; var bl = hwb[2] / 100; var ratio = wh + bl; var i; var v; var f; var n; // wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } i = Math.floor(6 * h); v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } n = wh + f * (v - wh); // linear interpolation var r; var g; var b; switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } return [r * 255, g * 255, b * 255]; }; convert.cmyk.rgb = function (cmyk) { var c = cmyk[0] / 100; var m = cmyk[1] / 100; var y = cmyk[2] / 100; var k = cmyk[3] / 100; var r; var g; var b; r = 1 - Math.min(1, c * (1 - k) + k); g = 1 - Math.min(1, m * (1 - k) + k); b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert.xyz.rgb = function (xyz) { var x = xyz[0] / 100; var y = xyz[1] / 100; var z = xyz[2] / 100; var r; var g; var b; r = x * 3.2406 + y * -1.5372 + z * -0.4986; g = x * -0.9689 + y * 1.8758 + z * 0.0415; b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92; g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92; b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert.xyz.lab = function (xyz) { var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; l = 116 * y - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.lab.xyz = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var x; var y; var z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; var y2 = Math.pow(y, 3); var x2 = Math.pow(x, 3); var z2 = Math.pow(z, 3); y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert.lab.lch = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var hr; var h; var c; hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert.lch.lab = function (lch) { var l = lch[0]; var c = lch[1]; var h = lch[2]; var a; var b; var hr; hr = h / 360 * 2 * Math.PI; a = c * Math.cos(hr); b = c * Math.sin(hr); return [l, a, b]; }; convert.rgb.ansi16 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert.hsv.ansi16 = function (args) { // optimization here; we already know the value and don't need to get // it converted for us. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); }; convert.rgb.ansi256 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; // we use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round((r - 8) / 247 * 24) + 232; } var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); return ansi; }; convert.ansi16.rgb = function (args) { var color = args % 10; // handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } var mult = (~~(args > 50) + 1) * 0.5; var r = (color & 1) * mult * 255; var g = (color >> 1 & 1) * mult * 255; var b = (color >> 2 & 1) * mult * 255; return [r, g, b]; }; convert.ansi256.rgb = function (args) { // handle greyscale if (args >= 232) { var c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; var rem; var r = Math.floor(args / 36) / 5 * 255; var g = Math.floor((rem = args % 36) / 6) / 5 * 255; var b = rem % 6 / 5 * 255; return [r, g, b]; }; convert.rgb.hex = function (args) { var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.hex.rgb = function (args) { var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } var colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(function (char) { return char + char; }).join(''); } var integer = parseInt(colorString, 16); var r = integer >> 16 & 0xFF; var g = integer >> 8 & 0xFF; var b = integer & 0xFF; return [r, g, b]; }; convert.rgb.hcg = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var max = Math.max(Math.max(r, g), b); var min = Math.min(Math.min(r, g), b); var chroma = max - min; var grayscale; var hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = (g - b) / chroma % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma + 4; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert.hsl.hcg = function (hsl) { var s = hsl[1] / 100; var l = hsl[2] / 100; var c = 1; var f = 0; if (l < 0.5) { c = 2.0 * s * l; } else { c = 2.0 * s * (1.0 - l); } if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert.hsv.hcg = function (hsv) { var s = hsv[1] / 100; var v = hsv[2] / 100; var c = s * v; var f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert.hcg.rgb = function (hcg) { var h = hcg[0] / 360; var c = hcg[1] / 100; var g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } var pure = [0, 0, 0]; var hi = h % 1 * 6; var v = hi % 1; var w = 1 - v; var mg = 0; switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } mg = (1.0 - c) * g; return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255]; }; convert.hcg.hsv = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); var f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert.hcg.hsl = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var l = g * (1.0 - c) + 0.5 * c; var s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert.hcg.hwb = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert.hwb.hcg = function (hwb) { var w = hwb[1] / 100; var b = hwb[2] / 100; var v = 1 - b; var c = v - w; var g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert.apple.rgb = function (apple) { return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; }; convert.rgb.apple = function (rgb) { return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; }; convert.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert.gray.hsl = convert.gray.hsv = function (args) { return [0, 0, args[0]]; }; convert.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert.gray.hex = function (gray) { var val = Math.round(gray[0] / 100 * 255) & 0xFF; var integer = (val << 16) + (val << 8) + val; var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.rgb.gray = function (rgb) { var val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; }); var conversions_1 = conversions.rgb; var conversions_2 = conversions.hsl; var conversions_3 = conversions.hsv; var conversions_4 = conversions.hwb; var conversions_5 = conversions.cmyk; var conversions_6 = conversions.xyz; var conversions_7 = conversions.lab; var conversions_8 = conversions.lch; var conversions_9 = conversions.hex; var conversions_10 = conversions.keyword; var conversions_11 = conversions.ansi16; var conversions_12 = conversions.ansi256; var conversions_13 = conversions.hcg; var conversions_14 = conversions.apple; var conversions_15 = conversions.gray; /* this function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph() { var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 var models = Object.keys(conversions); for (var len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS(fromModel) { var graph = buildGraph(); var queue = [fromModel]; // unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { var current = queue.pop(); var adjacents = Object.keys(conversions[current]); for (var len = adjacents.length, i = 0; i < len; i++) { var adjacent = adjacents[i]; var node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion(toModel, graph) { var path = [graph[toModel].parent, toModel]; var fn = conversions[graph[toModel].parent][toModel]; var cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link(conversions[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } var route = function route(fromModel) { var graph = deriveBFS(fromModel); var conversion = {}; var models = Object.keys(graph); for (var len = models.length, i = 0; i < len; i++) { var toModel = models[i]; var node = graph[toModel]; if (node.parent === null) { // no possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion(toModel, graph); } return conversion; }; var convert = {}; var models = Object.keys(conversions); function wrapRaw(fn) { var wrappedFn = function wrappedFn(args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } return fn(args); }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded(fn) { var wrappedFn = function wrappedFn(args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } var result = fn(args); // we're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (var len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models.forEach(function (fromModel) { convert[fromModel] = {}; Object.defineProperty(convert[fromModel], 'channels', { value: conversions[fromModel].channels }); Object.defineProperty(convert[fromModel], 'labels', { value: conversions[fromModel].labels }); var routes = route(fromModel); var routeModels = Object.keys(routes); routeModels.forEach(function (toModel) { var fn = routes[toModel]; convert[fromModel][toModel] = wrapRounded(fn); convert[fromModel][toModel].raw = wrapRaw(fn); }); }); var colorConvert = convert; var ansiStyles = createCommonjsModule(function (module) { const wrapAnsi16 = (fn, offset) => function () { const code = fn.apply(colorConvert, arguments); return "\x1B[".concat(code + offset, "m"); }; const wrapAnsi256 = (fn, offset) => function () { const code = fn.apply(colorConvert, arguments); return "\x1B[".concat(38 + offset, ";5;").concat(code, "m"); }; const wrapAnsi16m = (fn, offset) => function () { const rgb = fn.apply(colorConvert, arguments); return "\x1B[".concat(38 + offset, ";2;").concat(rgb[0], ";").concat(rgb[1], ";").concat(rgb[2], "m"); }; 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], gray: [90, 39], // Bright color 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] } }; // Fix humans styles.color.grey = styles.color.gray; for (const groupName of Object.keys(styles)) { const group = styles[groupName]; for (const styleName of Object.keys(group)) { const style = group[styleName]; styles[styleName] = { open: "\x1B[".concat(style[0], "m"), close: "\x1B[".concat(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 }); } const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = { ansi: wrapAnsi16(ansi2ansi, 0) }; styles.color.ansi256 = { ansi256: wrapAnsi256(ansi2ansi, 0) }; styles.color.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 0) }; styles.bgColor.ansi = { ansi: wrapAnsi16(ansi2ansi, 10) }; styles.bgColor.ansi256 = { ansi256: wrapAnsi256(ansi2ansi, 10) }; styles.bgColor.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 10) }; for (let key of Object.keys(colorConvert)) { if (typeof colorConvert[key] !== 'object') { continue; } const suite = colorConvert[key]; if (key === 'ansi16') { key = 'ansi'; } if ('ansi16' in suite) { styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); } if ('ansi256' in suite) { styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); } if ('rgb' in suite) { styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); } } return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); }); var require$$0$1 = { EOL: "\n" }; var hasFlag = (flag, argv) => { argv = argv || process.argv; const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--'; const pos = argv.indexOf(prefix + flag); const terminatorPos = argv.indexOf('--'); return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); }; const env$1 = process.env; let forceColor; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { forceColor = false; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { forceColor = true; } if ('FORCE_COLOR' in env$1) { forceColor = env$1.FORCE_COLOR.length === 0 || parseInt(env$1.FORCE_COLOR, 10) !== 0; } function translateLevel(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor(stream) { if (forceColor === false) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (stream && !stream.isTTY && forceColor !== true) { return 0; } const min = forceColor ? 1 : 0; if (process.platform === 'win32') { // Node.js 7.5.0 is the first version of Node.js to include a patch to // libuv that enables 256 color output on Windows. Anything earlier and it // won't work. However, here we target Node.js 8 at minimum as it is an LTS // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows // release that supports 256 colors. Windows 10 build 14931 is the first release // that supports 16m/TrueColor. const osRelease = require$$0$1.release().split('.'); if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env$1) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env$1) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0; } if (env$1.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env$1) { const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env$1.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env$1.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) { return 1; } if ('COLORTERM' in env$1) { return 1; } if (env$1.TERM === 'dumb') { return min; } return min; } function getSupportLevel(stream) { const level = supportsColor(stream); return translateLevel(level); } var supportsColor_1 = { supportsColor: getSupportLevel, stdout: getSupportLevel(process.stdout), stderr: getSupportLevel(process.stderr) }; const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]); function unescape(c) { if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) { return String.fromCharCode(parseInt(c.slice(1), 16)); } return ESCAPES.get(c) || c; } function parseArguments(name, args) { const results = []; const chunks = args.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { if (!isNaN(chunk)) { results.push(Number(chunk)); } else if (matches = chunk.match(STRING_REGEX)) { results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); } else { throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')")); } } return results; } function parseStyle(style) { STYLE_REGEX.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const styleName of Object.keys(enabled)) { if (Array.isArray(enabled[styleName])) { if (!(styleName in current)) { throw new Error("Unknown Chalk style: ".concat(styleName)); } if (enabled[styleName].length > 0) { current = current[styleName].apply(current, enabled[styleName]); } else { current = current[styleName]; } } } return current; } var templates = (chalk, tmp) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { if (escapeChar) { chunk.push(unescape(escapeChar)); } else if (style) { const str = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); styles.push({ inverse, styles: parseStyle(style) }); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(chr); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMsg = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)"); throw new Error(errMsg); } return chunks.join(''); }; var chalk = createCommonjsModule(function (module) { const stdoutColor = supportsColor_1.stdout; const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such const skipModels = new Set(['gray']); const styles = Object.create(null); function applyOptions(obj, options) { options = options || {}; // Detect level if not set manually const scLevel = stdoutColor ? stdoutColor.level : 0; obj.level = options.level === undefined ? scLevel : options.level; obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; } function Chalk(options) { // We check for this.template here since calling `chalk.constructor()` // by itself will have a `this` of a previously constructed chalk object if (!this || !(this instanceof Chalk) || this.template) { const chalk = {}; applyOptions(chalk, options); chalk.template = function () { const args = [].slice.call(arguments); return chalkTag.apply(null, [chalk.template].concat(args)); }; Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = Chalk; return chalk.template; } applyOptions(this, options); } // Use bright blue on Windows as the normal blue color is illegible if (isSimpleWindowsTerm) { ansiStyles.blue.open = '\u001B[94m'; } for (const key of Object.keys(ansiStyles)) { ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); styles[key] = { get() { const codes = ansiStyles[key]; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); } }; } styles.visible = { get() { return build.call(this, this._styles || [], true, 'visible'); } }; ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g'); for (const model of Object.keys(ansiStyles.color.ansi)) { if (skipModels.has(model)) { continue; } styles[model] = { get() { const level = this.level; return function () { const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles.color.close, closeRe: ansiStyles.color.closeRe }; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); }; } }; } ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g'); for (const model of Object.keys(ansiStyles.bgColor.ansi)) { if (skipModels.has(model)) { continue; } const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const level = this.level; return function () { const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles.bgColor.close, closeRe: ansiStyles.bgColor.closeRe }; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); }; } }; } const proto = Object.defineProperties(() => {}, styles); function build(_styles, _empty, key) { const builder = function builder() { return applyStyle.apply(builder, arguments); }; builder._styles = _styles; builder._empty = _empty; const self = this; Object.defineProperty(builder, 'level', { enumerable: true, get() { return self.level; }, set(level) { self.level = level; } }); Object.defineProperty(builder, 'enabled', { enumerable: true, get() { return self.enabled; }, set(enabled) { self.enabled = enabled; } }); // See below for fix regarding invisible grey/dim combination on Windows builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is // no way to create a function with a different prototype builder.__proto__ = proto; // eslint-disable-line no-proto return builder; } function applyStyle() { // Support varags, but simply cast to string in case there's only one arg const args = arguments; const argsLen = args.length; let str = String(arguments[0]); if (argsLen === 0) { return ''; } if (argsLen > 1) { // Don't slice `arguments`, it prevents V8 optimizations for (let a = 1; a < argsLen; a++) { str += ' ' + args[a]; } } if (!this.enabled || this.level <= 0 || !str) { return this._empty ? '' : str; } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, // see https://github.com/chalk/chalk/issues/58 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. const originalDim = ansiStyles.dim.open; if (isSimpleWindowsTerm && this.hasGrey) { ansiStyles.dim.open = ''; } for (const code of this._styles.slice().reverse()) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS // https://github.com/chalk/chalk/pull/92 str = str.replace(/\r?\n/g, "".concat(code.close, "$&").concat(code.open)); } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue ansiStyles.dim.open = originalDim; return str; } function chalkTag(chalk, strings) { if (!Array.isArray(strings)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return [].slice.call(arguments, 1).join(' '); } const args = [].slice.call(arguments, 2); const parts = [strings.raw[0]]; for (let i = 1; i < strings.length; i++) { parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); parts.push(String(strings.raw[i])); } return templates(chalk, parts.join('')); } Object.defineProperties(Chalk.prototype, styles); module.exports = Chalk(); // eslint-disable-line new-cap module.exports.supportsColor = stdoutColor; module.exports.default = module.exports; // For TypeScript }); var chalk_1 = chalk.supportsColor; var common = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.commonDeprecatedHandler = (keyOrPair, redirectTo, { descriptor }) => { const messages = ["".concat(chalk.default.yellow(typeof keyOrPair === 'string' ? descriptor.key(keyOrPair) : descriptor.pair(keyOrPair)), " is deprecated")]; if (redirectTo) { messages.push("we now treat it as ".concat(chalk.default.blue(typeof redirectTo === 'string' ? descriptor.key(redirectTo) : descriptor.pair(redirectTo)))); } return messages.join('; ') + '.'; }; }); unwrapExports(common); var common_1 = common.commonDeprecatedHandler; var deprecated = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(common, exports); }); unwrapExports(deprecated); var common$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.commonInvalidHandler = (key, value, utils) => ["Invalid ".concat(chalk.default.red(utils.descriptor.key(key)), " value."), "Expected ".concat(chalk.default.blue(utils.schemas[key].expected(utils)), ","), "but received ".concat(chalk.default.red(utils.descriptor.value(value)), ".")].join(' '); }); unwrapExports(common$1); var common_1$1 = common$1.commonInvalidHandler; var invalid = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(common$1, exports); }); unwrapExports(invalid); /* eslint-disable no-nested-ternary */ var arr = []; var charCodeCache = []; var leven = function leven(a, b) { if (a === b) { return 0; } var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the // shortest & which one is the longest if (a.length > b.length) { a = b; b = swap; } var aLen = a.length; var bLen = b.length; if (aLen === 0) { return bLen; } if (bLen === 0) { return aLen; } // Performing suffix trimming: // We can linearly drop suffix common to both strings since they // don't increase distance at all // Note: `~-` is the bitwise way to perform a `- 1` operation while (aLen > 0 && a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen)) { aLen--; bLen--; } if (aLen === 0) { return bLen; } // Performing prefix trimming // We can linearly drop prefix common to both strings since they // don't increase distance at all var start = 0; while (start < aLen && a.charCodeAt(start) === b.charCodeAt(start)) { start++; } aLen -= start; bLen -= start; if (aLen === 0) { return bLen; } var bCharCode; var ret; var tmp; var tmp2; var i = 0; var j = 0; while (i < aLen) { charCodeCache[start + i] = a.charCodeAt(start + i); arr[i] = ++i; } while (j < bLen) { bCharCode = b.charCodeAt(start + j); tmp = j++; ret = j; for (i = 0; i < aLen; i++) { tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1; tmp = arr[i]; ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2; } } return ret; }; var leven_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.levenUnknownHandler = (key, value, { descriptor, logger, schemas }) => { const messages = ["Ignored unknown option ".concat(chalk.default.yellow(descriptor.pair({ key, value })), ".")]; const suggestion = Object.keys(schemas).sort().find(knownKey => leven(key, knownKey) < 3); if (suggestion) { messages.push("Did you mean ".concat(chalk.default.blue(descriptor.key(suggestion)), "?")); } logger.warn(messages.join(' ')); }; }); unwrapExports(leven_1); var leven_2 = leven_1.levenUnknownHandler; var unknown = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(leven_1, exports); }); unwrapExports(unknown); var handlers = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(deprecated, exports); tslib_1.__exportStar(invalid, exports); tslib_1.__exportStar(unknown, exports); }); unwrapExports(handlers); var schema = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); const HANDLER_KEYS = ['default', 'expected', 'validate', 'deprecated', 'forward', 'redirect', 'overlap', 'preprocess', 'postprocess']; function createSchema(SchemaConstructor, parameters) { const schema = new SchemaConstructor(parameters); const subSchema = Object.create(schema); for (const handlerKey of HANDLER_KEYS) { if (handlerKey in parameters) { subSchema[handlerKey] = normalizeHandler(parameters[handlerKey], schema, Schema.prototype[handlerKey].length); } } return subSchema; } exports.createSchema = createSchema; class Schema { constructor(parameters) { this.name = parameters.name; } static create(parameters) { // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/5863 return createSchema(this, parameters); } default(_utils) { return undefined; } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length` expected(_utils) { return 'nothing'; } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length` validate(_value, _utils) { return false; } deprecated(_value, _utils) { return false; } forward(_value, _utils) { return undefined; } redirect(_value, _utils) { return undefined; } overlap(currentValue, _newValue, _utils) { return currentValue; } preprocess(value, _utils) { return value; } postprocess(value, _utils) { return value; } } exports.Schema = Schema; function normalizeHandler(handler, superSchema, handlerArgumentsLength) { return typeof handler === 'function' ? (...args) => handler(...args.slice(0, handlerArgumentsLength - 1), superSchema, ...args.slice(handlerArgumentsLength - 1)) : () => handler; } }); unwrapExports(schema); var schema_1 = schema.createSchema; var schema_2 = schema.Schema; var alias = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class AliasSchema extends schema.Schema { constructor(parameters) { super(parameters); this._sourceName = parameters.sourceName; } expected(utils) { return utils.schemas[this._sourceName].expected(utils); } validate(value, utils) { return utils.schemas[this._sourceName].validate(value, utils); } redirect(_value, _utils) { return this._sourceName; } } exports.AliasSchema = AliasSchema; }); unwrapExports(alias); var alias_1 = alias.AliasSchema; var any = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class AnySchema extends schema.Schema { expected() { return 'anything'; } validate() { return true; } } exports.AnySchema = AnySchema; }); unwrapExports(any); var any_1 = any.AnySchema; var array = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class ArraySchema extends schema.Schema { constructor(_a) { var { valueSchema, name = valueSchema.name } = _a, handlers = tslib_1.__rest(_a, ["valueSchema", "name"]); super(Object.assign({}, handlers, { name })); this._valueSchema = valueSchema; } expected(utils) { return "an array of ".concat(this._valueSchema.expected(utils)); } validate(value, utils) { if (!Array.isArray(value)) { return false; } const invalidValues = []; for (const subValue of value) { const subValidateResult = utils.normalizeValidateResult(this._valueSchema.validate(subValue, utils), subValue); if (subValidateResult !== true) { invalidValues.push(subValidateResult.value); } } return invalidValues.length === 0 ? true : { value: invalidValues }; } deprecated(value, utils) { const deprecatedResult = []; for (const subValue of value) { const subDeprecatedResult = utils.normalizeDeprecatedResult(this._valueSchema.deprecated(subValue, utils), subValue); if (subDeprecatedResult !== false) { deprecatedResult.push(...subDeprecatedResult.map(({ value: deprecatedValue }) => ({ value: [deprecatedValue] }))); } } return deprecatedResult; } forward(value, utils) { const forwardResult = []; for (const subValue of value) { const subForwardResult = utils.normalizeForwardResult(this._valueSchema.forward(subValue, utils), subValue); forwardResult.push(...subForwardResult.map(wrapTransferResult)); } return forwardResult; } redirect(value, utils) { const remain = []; const redirect = []; for (const subValue of value) { const subRedirectResult = utils.normalizeRedirectResult(this._valueSchema.redirect(subValue, utils), subValue); if ('remain' in subRedirectResult) { remain.push(subRedirectResult.remain); } redirect.push(...subRedirectResult.redirect.map(wrapTransferResult)); } return remain.length === 0 ? { redirect } : { redirect, remain }; } overlap(currentValue, newValue) { return currentValue.concat(newValue); } } exports.ArraySchema = ArraySchema; function wrapTransferResult({ from, to }) { return { from: [from], to }; } }); unwrapExports(array); var array_1 = array.ArraySchema; var boolean_1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class BooleanSchema extends schema.Schema { expected() { return 'true or false'; } validate(value) { return typeof value === 'boolean'; } } exports.BooleanSchema = BooleanSchema; }); unwrapExports(boolean_1); var boolean_2 = boolean_1.BooleanSchema; var utils = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); function recordFromArray(array, mainKey) { const record = Object.create(null); for (const value of array) { const key = value[mainKey]; // istanbul ignore next if (record[key]) { throw new Error("Duplicate ".concat(mainKey, " ").concat(JSON.stringify(key))); } // @ts-ignore record[key] = value; } return record; } exports.recordFromArray = recordFromArray; function mapFromArray(array, mainKey) { const map = new Map(); for (const value of array) { const key = value[mainKey]; // istanbul ignore next if (map.has(key)) { throw new Error("Duplicate ".concat(mainKey, " ").concat(JSON.stringify(key))); } map.set(key, value); } return map; } exports.mapFromArray = mapFromArray; function createAutoChecklist() { const map = Object.create(null); return id => { const idString = JSON.stringify(id); if (map[idString]) { return true; } map[idString] = true; return false; }; } exports.createAutoChecklist = createAutoChecklist; function partition(array, predicate) { const trueArray = []; const falseArray = []; for (const value of array) { if (predicate(value)) { trueArray.push(value); } else { falseArray.push(value); } } return [trueArray, falseArray]; } exports.partition = partition; function isInt(value) { return value === Math.floor(value); } exports.isInt = isInt; function comparePrimitive(a, b) { if (a === b) { return 0; } const typeofA = typeof a; const typeofB = typeof b; const orders = ['undefined', 'object', 'boolean', 'number', 'string']; if (typeofA !== typeofB) { return orders.indexOf(typeofA) - orders.indexOf(typeofB); } if (typeofA !== 'string') { return Number(a) - Number(b); } return a.localeCompare(b); } exports.comparePrimitive = comparePrimitive; function normalizeDefaultResult(result) { return result === undefined ? {} : result; } exports.normalizeDefaultResult = normalizeDefaultResult; function normalizeValidateResult(result, value) { return result === true ? true : result === false ? { value } : result; } exports.normalizeValidateResult = normalizeValidateResult; function normalizeDeprecatedResult(result, value, doNotNormalizeTrue = false) { return result === false ? false : result === true ? doNotNormalizeTrue ? true : [{ value }] : 'value' in result ? [result] : result.length === 0 ? false : result; } exports.normalizeDeprecatedResult = normalizeDeprecatedResult; function normalizeTransferResult(result, value) { return typeof result === 'string' || 'key' in result ? { from: value, to: result } : 'from' in result ? { from: result.from, to: result.to } : { from: value, to: result.to }; } exports.normalizeTransferResult = normalizeTransferResult; function normalizeForwardResult(result, value) { return result === undefined ? [] : Array.isArray(result) ? result.map(transferResult => normalizeTransferResult(transferResult, value)) : [normalizeTransferResult(result, value)]; } exports.normalizeForwardResult = normalizeForwardResult; function normalizeRedirectResult(result, value) { const redirect = normalizeForwardResult(typeof result === 'object' && 'redirect' in result ? result.redirect : result, value); return redirect.length === 0 ? { remain: value, redirect } : typeof result === 'object' && 'remain' in result ? { remain: result.remain, redirect } : { redirect }; } exports.normalizeRedirectResult = normalizeRedirectResult; }); unwrapExports(utils); var utils_1 = utils.recordFromArray; var utils_2 = utils.mapFromArray; var utils_3 = utils.createAutoChecklist; var utils_4 = utils.partition; var utils_5 = utils.isInt; var utils_6 = utils.comparePrimitive; var utils_7 = utils.normalizeDefaultResult; var utils_8 = utils.normalizeValidateResult; var utils_9 = utils.normalizeDeprecatedResult; var utils_10 = utils.normalizeTransferResult; var utils_11 = utils.normalizeForwardResult; var utils_12 = utils.normalizeRedirectResult; var choice = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class ChoiceSchema extends schema.Schema { constructor(parameters) { super(parameters); this._choices = utils.mapFromArray(parameters.choices.map(choice => choice && typeof choice === 'object' ? choice : { value: choice }), 'value'); } expected({ descriptor }) { const choiceValues = Array.from(this._choices.keys()).map(value => this._choices.get(value)).filter(choiceInfo => !choiceInfo.deprecated).map(choiceInfo => choiceInfo.value).sort(utils.comparePrimitive).map(descriptor.value); const head = choiceValues.slice(0, -2); const tail = choiceValues.slice(-2); return head.concat(tail.join(' or ')).join(', '); } validate(value) { return this._choices.has(value); } deprecated(value) { const choiceInfo = this._choices.get(value); return choiceInfo && choiceInfo.deprecated ? { value } : false; } forward(value) { const choiceInfo = this._choices.get(value); return choiceInfo ? choiceInfo.forward : undefined; } redirect(value) { const choiceInfo = this._choices.get(value); return choiceInfo ? choiceInfo.redirect : undefined; } } exports.ChoiceSchema = ChoiceSchema; }); unwrapExports(choice); var choice_1 = choice.ChoiceSchema; var number = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class NumberSchema extends schema.Schema { expected() { return 'a number'; } validate(value, _utils) { return typeof value === 'number'; } } exports.NumberSchema = NumberSchema; }); unwrapExports(number); var number_1 = number.NumberSchema; var integer = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class IntegerSchema extends number.NumberSchema { expected() { return 'an integer'; } validate(value, utils$1) { return utils$1.normalizeValidateResult(super.validate(value, utils$1), value) === true && utils.isInt(value); } } exports.IntegerSchema = IntegerSchema; }); unwrapExports(integer); var integer_1 = integer.IntegerSchema; var string = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); class StringSchema extends schema.Schema { expected() { return 'a string'; } validate(value) { return typeof value === 'string'; } } exports.StringSchema = StringSchema; }); unwrapExports(string); var string_1 = string.StringSchema; var schemas = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(alias, exports); tslib_1.__exportStar(any, exports); tslib_1.__exportStar(array, exports); tslib_1.__exportStar(boolean_1, exports); tslib_1.__exportStar(choice, exports); tslib_1.__exportStar(integer, exports); tslib_1.__exportStar(number, exports); tslib_1.__exportStar(string, exports); }); unwrapExports(schemas); var defaults = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultDescriptor = api.apiDescriptor; exports.defaultUnknownHandler = leven_1.levenUnknownHandler; exports.defaultInvalidHandler = invalid.commonInvalidHandler; exports.defaultDeprecatedHandler = common.commonDeprecatedHandler; }); unwrapExports(defaults); var defaults_1 = defaults.defaultDescriptor; var defaults_2 = defaults.defaultUnknownHandler; var defaults_3 = defaults.defaultInvalidHandler; var defaults_4 = defaults.defaultDeprecatedHandler; var normalize = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.normalize = (options, schemas, opts) => new Normalizer(schemas, opts).normalize(options); class Normalizer { constructor(schemas, opts) { // istanbul ignore next const { logger = console, descriptor = defaults.defaultDescriptor, unknown = defaults.defaultUnknownHandler, invalid = defaults.defaultInvalidHandler, deprecated = defaults.defaultDeprecatedHandler } = opts || {}; this._utils = { descriptor, logger: /* istanbul ignore next */ logger || { warn: () => {} }, schemas: utils.recordFromArray(schemas, 'name'), normalizeDefaultResult: utils.normalizeDefaultResult, normalizeDeprecatedResult: utils.normalizeDeprecatedResult, normalizeForwardResult: utils.normalizeForwardResult, normalizeRedirectResult: utils.normalizeRedirectResult, normalizeValidateResult: utils.normalizeValidateResult }; this._unknownHandler = unknown; this._invalidHandler = invalid; this._deprecatedHandler = deprecated; this.cleanHistory(); } cleanHistory() { this._hasDeprecationWarned = utils.createAutoChecklist(); } normalize(options) { const normalized = {}; const restOptionsArray = [options]; const applyNormalization = () => { while (restOptionsArray.length !== 0) { const currentOptions = restOptionsArray.shift(); const transferredOptionsArray = this._applyNormalization(currentOptions, normalized); restOptionsArray.push(...transferredOptionsArray); } }; applyNormalization(); for (const key of Object.keys(this._utils.schemas)) { const schema = this._utils.schemas[key]; if (!(key in normalized)) { const defaultResult = utils.normalizeDefaultResult(schema.default(this._utils)); if ('value' in defaultResult) { restOptionsArray.push({ [key]: defaultResult.value }); } } } applyNormalization(); for (const key of Object.keys(this._utils.schemas)) { const schema = this._utils.schemas[key]; if (key in normalized) { normalized[key] = schema.postprocess(normalized[key], this._utils); } } return normalized; } _applyNormalization(options, normalized) { const transferredOptionsArray = []; const [knownOptionNames, unknownOptionNames] = utils.partition(Object.keys(options), key => key in this._utils.schemas); for (const key of knownOptionNames) { const schema = this._utils.schemas[key]; const value = schema.preprocess(options[key], this._utils); const validateResult = utils.normalizeValidateResult(schema.validate(value, this._utils), value); if (validateResult !== true) { const { value: invalidValue } = validateResult; const errorMessageOrError = this._invalidHandler(key, invalidValue, this._utils); throw typeof errorMessageOrError === 'string' ? new Error(errorMessageOrError) : /* istanbul ignore next*/ errorMessageOrError; } const appendTransferredOptions = ({ from, to }) => { transferredOptionsArray.push(typeof to === 'string' ? { [to]: from } : { [to.key]: to.value }); }; const warnDeprecated = ({ value: currentValue, redirectTo }) => { const deprecatedResult = utils.normalizeDeprecatedResult(schema.deprecated(currentValue, this._utils), value, /* doNotNormalizeTrue */ true); if (deprecatedResult === false) { return; } if (deprecatedResult === true) { if (!this._hasDeprecationWarned(key)) { this._utils.logger.warn(this._deprecatedHandler(key, redirectTo, this._utils)); } } else { for (const { value: deprecatedValue } of deprecatedResult) { const pair = { key, value: deprecatedValue }; if (!this._hasDeprecationWarned(pair)) { const redirectToPair = typeof redirectTo === 'string' ? { key: redirectTo, value: deprecatedValue } : redirectTo; this._utils.logger.warn(this._deprecatedHandler(pair, redirectToPair, this._utils)); } } } }; const forwardResult = utils.normalizeForwardResult(schema.forward(value, this._utils), value); forwardResult.forEach(appendTransferredOptions); const redirectResult = utils.normalizeRedirectResult(schema.redirect(value, this._utils), value); redirectResult.redirect.forEach(appendTransferredOptions); if ('remain' in redirectResult) { const remainingValue = redirectResult.remain; normalized[key] = key in normalized ? schema.overlap(normalized[key], remainingValue, this._utils) : remainingValue; warnDeprecated({ value: remainingValue }); } for (const { from, to } of redirectResult.redirect) { warnDeprecated({ value: from, redirectTo: to }); } } for (const key of unknownOptionNames) { const value = options[key]; const unknownResult = this._unknownHandler(key, value, this._utils); if (unknownResult) { for (const unknownKey of Object.keys(unknownResult)) { const unknownOption = { [unknownKey]: unknownResult[unknownKey] }; if (unknownKey in this._utils.schemas) { transferredOptionsArray.push(unknownOption); } else { Object.assign(normalized, unknownOption); } } } } return transferredOptionsArray; } } exports.Normalizer = Normalizer; }); unwrapExports(normalize); var normalize_1 = normalize.normalize; var normalize_2 = normalize.Normalizer; var lib = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); tslib_1.__exportStar(descriptors, exports); tslib_1.__exportStar(handlers, exports); tslib_1.__exportStar(schemas, exports); tslib_1.__exportStar(normalize, exports); tslib_1.__exportStar(schema, exports); }); unwrapExports(lib); const array$1 = []; const charCodeCache$1 = []; const leven$1 = (left, right) => { if (left === right) { return 0; } const swap = left; // Swapping the strings if `a` is longer than `b` so we know which one is the // shortest & which one is the longest if (left.length > right.length) { left = right; right = swap; } let leftLength = left.length; let rightLength = right.length; // Performing suffix trimming: // We can linearly drop suffix common to both strings since they // don't increase distance at all // Note: `~-` is the bitwise way to perform a `- 1` operation while (leftLength > 0 && left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength)) { leftLength--; rightLength--; } // Performing prefix trimming // We can linearly drop prefix common to both strings since they // don't increase distance at all let start = 0; while (start < leftLength && left.charCodeAt(start) === right.charCodeAt(start)) { start++; } leftLength -= start; rightLength -= start; if (leftLength === 0) { return rightLength; } let bCharCode; let result; let temp; let temp2; let i = 0; let j = 0; while (i < leftLength) { charCodeCache$1[i] = left.charCodeAt(start + i); array$1[i] = ++i; } while (j < rightLength) { bCharCode = right.charCodeAt(start + j); temp = j++; result = j; for (i = 0; i < leftLength; i++) { temp2 = bCharCode === charCodeCache$1[i] ? temp : temp + 1; temp = array$1[i]; // eslint-disable-next-line no-multi-assign result = array$1[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2; } } return result; }; var leven_1$1 = leven$1; // TODO: Remove this for the next major release var default_1 = leven$1; leven_1$1.default = default_1; var colorName$1 = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; /* MIT license */ /* eslint-disable no-mixed-operators */ // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) const reverseKeywords = {}; for (const key of Object.keys(colorName$1)) { reverseKeywords[colorName$1[key]] = key; } const convert$1 = { rgb: { channels: 3, labels: 'rgb' }, hsl: { channels: 3, labels: 'hsl' }, hsv: { channels: 3, labels: 'hsv' }, hwb: { channels: 3, labels: 'hwb' }, cmyk: { channels: 4, labels: 'cmyk' }, xyz: { channels: 3, labels: 'xyz' }, lab: { channels: 3, labels: 'lab' }, lch: { channels: 3, labels: 'lch' }, hex: { channels: 1, labels: ['hex'] }, keyword: { channels: 1, labels: ['keyword'] }, ansi16: { channels: 1, labels: ['ansi16'] }, ansi256: { channels: 1, labels: ['ansi256'] }, hcg: { channels: 3, labels: ['h', 'c', 'g'] }, apple: { channels: 3, labels: ['r16', 'g16', 'b16'] }, gray: { channels: 1, labels: ['gray'] } }; var conversions$1 = convert$1; // Hide .channels and .labels properties for (const model of Object.keys(convert$1)) { if (!('channels' in convert$1[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert$1[model])) { throw new Error('missing channel labels property: ' + model); } if (convert$1[model].labels.length !== convert$1[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } const { channels, labels } = convert$1[model]; delete convert$1[model].channels; delete convert$1[model].labels; Object.defineProperty(convert$1[model], 'channels', { value: channels }); Object.defineProperty(convert$1[model], 'labels', { value: labels }); } convert$1.rgb.hsl = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const min = Math.min(r, g, b); const max = Math.max(r, g, b); const delta = max - min; let h; let s; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } const l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert$1.rgb.hsv = function (rgb) { let rdif; let gdif; let bdif; let h; let s; const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const v = Math.max(r, g, b); const diff = v - Math.min(r, g, b); const diffc = function diffc(c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = 0; s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = 1 / 3 + rdif - bdif; } else if (b === v) { h = 2 / 3 + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [h * 360, s * 100, v * 100]; }; convert$1.rgb.hwb = function (rgb) { const r = rgb[0]; const g = rgb[1]; let b = rgb[2]; const h = convert$1.rgb.hsl(rgb)[0]; const w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert$1.rgb.cmyk = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const k = Math.min(1 - r, 1 - g, 1 - b); const c = (1 - r - k) / (1 - k) || 0; const m = (1 - g - k) / (1 - k) || 0; const y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; function comparativeDistance(x, y) { /* See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance */ return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2; } convert$1.rgb.keyword = function (rgb) { const reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } let currentClosestDistance = Infinity; let currentClosestKeyword; for (const keyword of Object.keys(colorName$1)) { const value = colorName$1[keyword]; // Compute comparative distance const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } return currentClosestKeyword; }; convert$1.keyword.rgb = function (keyword) { return colorName$1[keyword]; }; convert$1.rgb.xyz = function (rgb) { let r = rgb[0] / 255; let g = rgb[1] / 255; let b = rgb[2] / 255; // Assume sRGB r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92; g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92; b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92; const x = r * 0.4124 + g * 0.3576 + b * 0.1805; const y = r * 0.2126 + g * 0.7152 + b * 0.0722; const z = r * 0.0193 + g * 0.1192 + b * 0.9505; return [x * 100, y * 100, z * 100]; }; convert$1.rgb.lab = function (rgb) { const xyz = convert$1.rgb.xyz(rgb); let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116; y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116; z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116; const l = 116 * y - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert$1.hsl.rgb = function (hsl) { const h = hsl[0] / 360; const s = hsl[1] / 100; const l = hsl[2] / 100; let t2; let t3; let val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } const t1 = 2 * l - t2; const rgb = [0, 0, 0]; for (let i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert$1.hsl.hsv = function (hsl) { const h = hsl[0]; let s = hsl[1] / 100; let l = hsl[2] / 100; let smin = s; const lmin = Math.max(l, 0.01); l *= 2; s *= l <= 1 ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; const v = (l + s) / 2; const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); return [h, sv * 100, v * 100]; }; convert$1.hsv.rgb = function (hsv) { const h = hsv[0] / 60; const s = hsv[1] / 100; let v = hsv[2] / 100; const hi = Math.floor(h) % 6; const f = h - Math.floor(h); const p = 255 * v * (1 - s); const q = 255 * v * (1 - s * f); const t = 255 * v * (1 - s * (1 - f)); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert$1.hsv.hsl = function (hsv) { const h = hsv[0]; const s = hsv[1] / 100; const v = hsv[2] / 100; const vmin = Math.max(v, 0.01); let sl; let l; l = (2 - s) * v; const lmin = (2 - s) * vmin; sl = s * vmin; sl /= lmin <= 1 ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert$1.hwb.rgb = function (hwb) { const h = hwb[0] / 360; let wh = hwb[1] / 100; let bl = hwb[2] / 100; const ratio = wh + bl; let f; // Wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } const i = Math.floor(6 * h); const v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } const n = wh + f * (v - wh); // Linear interpolation let r; let g; let b; /* eslint-disable max-statements-per-line,no-multi-spaces */ switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } /* eslint-enable max-statements-per-line,no-multi-spaces */ return [r * 255, g * 255, b * 255]; }; convert$1.cmyk.rgb = function (cmyk) { const c = cmyk[0] / 100; const m = cmyk[1] / 100; const y = cmyk[2] / 100; const k = cmyk[3] / 100; const r = 1 - Math.min(1, c * (1 - k) + k); const g = 1 - Math.min(1, m * (1 - k) + k); const b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert$1.xyz.rgb = function (xyz) { const x = xyz[0] / 100; const y = xyz[1] / 100; const z = xyz[2] / 100; let r; let g; let b; r = x * 3.2406 + y * -1.5372 + z * -0.4986; g = x * -0.9689 + y * 1.8758 + z * 0.0415; b = x * 0.0557 + y * -0.2040 + z * 1.0570; // Assume sRGB r = r > 0.0031308 ? 1.055 * r ** (1.0 / 2.4) - 0.055 : r * 12.92; g = g > 0.0031308 ? 1.055 * g ** (1.0 / 2.4) - 0.055 : g * 12.92; b = b > 0.0031308 ? 1.055 * b ** (1.0 / 2.4) - 0.055 : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert$1.xyz.lab = function (xyz) { let x = xyz[0]; let y = xyz[1]; let z = xyz[2]; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116; y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116; z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116; const l = 116 * y - 16; const a = 500 * (x - y); const b = 200 * (y - z); return [l, a, b]; }; convert$1.lab.xyz = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let x; let y; let z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; const y2 = y ** 3; const x2 = x ** 3; const z2 = z ** 3; y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert$1.lab.lch = function (lab) { const l = lab[0]; const a = lab[1]; const b = lab[2]; let h; const hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } const c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert$1.lch.lab = function (lch) { const l = lch[0]; const c = lch[1]; const h = lch[2]; const hr = h / 360 * 2 * Math.PI; const a = c * Math.cos(hr); const b = c * Math.sin(hr); return [l, a, b]; }; convert$1.rgb.ansi16 = function (args, saturation = null) { const [r, g, b] = args; let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert$1.hsv.ansi16 = function (args) { // Optimization here; we already know the value and don't need to get // it converted for us. return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]); }; convert$1.rgb.ansi256 = function (args) { const r = args[0]; const g = args[1]; const b = args[2]; // We use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round((r - 8) / 247 * 24) + 232; } const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); return ansi; }; convert$1.ansi16.rgb = function (args) { let color = args % 10; // Handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } const mult = (~~(args > 50) + 1) * 0.5; const r = (color & 1) * mult * 255; const g = (color >> 1 & 1) * mult * 255; const b = (color >> 2 & 1) * mult * 255; return [r, g, b]; }; convert$1.ansi256.rgb = function (args) { // Handle greyscale if (args >= 232) { const c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; let rem; const r = Math.floor(args / 36) / 5 * 255; const g = Math.floor((rem = args % 36) / 6) / 5 * 255; const b = rem % 6 / 5 * 255; return [r, g, b]; }; convert$1.rgb.hex = function (args) { const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert$1.hex.rgb = function (args) { const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } let colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(char => { return char + char; }).join(''); } const integer = parseInt(colorString, 16); const r = integer >> 16 & 0xFF; const g = integer >> 8 & 0xFF; const b = integer & 0xFF; return [r, g, b]; }; convert$1.rgb.hcg = function (rgb) { const r = rgb[0] / 255; const g = rgb[1] / 255; const b = rgb[2] / 255; const max = Math.max(Math.max(r, g), b); const min = Math.min(Math.min(r, g), b); const chroma = max - min; let grayscale; let hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = (g - b) / chroma % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert$1.hsl.hcg = function (hsl) { const s = hsl[1] / 100; const l = hsl[2] / 100; const c = l < 0.5 ? 2.0 * s * l : 2.0 * s * (1.0 - l); let f = 0; if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert$1.hsv.hcg = function (hsv) { const s = hsv[1] / 100; const v = hsv[2] / 100; const c = s * v; let f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert$1.hcg.rgb = function (hcg) { const h = hcg[0] / 360; const c = hcg[1] / 100; const g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } const pure = [0, 0, 0]; const hi = h % 1 * 6; const v = hi % 1; const w = 1 - v; let mg = 0; /* eslint-disable max-statements-per-line */ switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } /* eslint-enable max-statements-per-line */ mg = (1.0 - c) * g; return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255]; }; convert$1.hcg.hsv = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); let f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert$1.hcg.hsl = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const l = g * (1.0 - c) + 0.5 * c; let s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert$1.hcg.hwb = function (hcg) { const c = hcg[1] / 100; const g = hcg[2] / 100; const v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert$1.hwb.hcg = function (hwb) { const w = hwb[1] / 100; const b = hwb[2] / 100; const v = 1 - b; const c = v - w; let g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert$1.apple.rgb = function (apple) { return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; }; convert$1.rgb.apple = function (rgb) { return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; }; convert$1.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert$1.gray.hsl = function (args) { return [0, 0, args[0]]; }; convert$1.gray.hsv = convert$1.gray.hsl; convert$1.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert$1.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert$1.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert$1.gray.hex = function (gray) { const val = Math.round(gray[0] / 100 * 255) & 0xFF; const integer = (val << 16) + (val << 8) + val; const string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert$1.rgb.gray = function (rgb) { const val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; /* This function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph$1() { const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 const models = Object.keys(conversions$1); for (let len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS$1(fromModel) { const graph = buildGraph$1(); const queue = [fromModel]; // Unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { const current = queue.pop(); const adjacents = Object.keys(conversions$1[current]); for (let len = adjacents.length, i = 0; i < len; i++) { const adjacent = adjacents[i]; const node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link$1(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion$1(toModel, graph) { const path = [graph[toModel].parent, toModel]; let fn = conversions$1[graph[toModel].parent][toModel]; let cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link$1(conversions$1[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } var route$1 = function route(fromModel) { const graph = deriveBFS$1(fromModel); const conversion = {}; const models = Object.keys(graph); for (let len = models.length, i = 0; i < len; i++) { const toModel = models[i]; const node = graph[toModel]; if (node.parent === null) { // No possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion$1(toModel, graph); } return conversion; }; const convert$2 = {}; const models$1 = Object.keys(conversions$1); function wrapRaw$1(fn) { const wrappedFn = function wrappedFn(...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } return fn(args); }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded$1(fn) { const wrappedFn = function wrappedFn(...args) { const arg0 = args[0]; if (arg0 === undefined || arg0 === null) { return arg0; } if (arg0.length > 1) { args = arg0; } const result = fn(args); // We're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (let len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // Preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models$1.forEach(fromModel => { convert$2[fromModel] = {}; Object.defineProperty(convert$2[fromModel], 'channels', { value: conversions$1[fromModel].channels }); Object.defineProperty(convert$2[fromModel], 'labels', { value: conversions$1[fromModel].labels }); const routes = route$1(fromModel); const routeModels = Object.keys(routes); routeModels.forEach(toModel => { const fn = routes[toModel]; convert$2[fromModel][toModel] = wrapRounded$1(fn); convert$2[fromModel][toModel].raw = wrapRaw$1(fn); }); }); var colorConvert$1 = convert$2; var ansiStyles$1 = createCommonjsModule(function (module) { const wrapAnsi16 = (fn, offset) => (...args) => { const code = fn(...args); return "\x1B[".concat(code + offset, "m"); }; const wrapAnsi256 = (fn, offset) => (...args) => { const code = fn(...args); return "\x1B[".concat(38 + offset, ";5;").concat(code, "m"); }; const wrapAnsi16m = (fn, offset) => (...args) => { const rgb = fn(...args); return "\x1B[".concat(38 + offset, ";2;").concat(rgb[0], ";").concat(rgb[1], ";").concat(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 = colorConvert$1; } 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: "\x1B[".concat(style[0], "m"), close: "\x1B[".concat(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 }); }); var tty = { isatty() { return false; } }; var hasFlag$1 = (flag, argv = process.argv) => { const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--'; const position = argv.indexOf(prefix + flag); const terminatorPosition = argv.indexOf('--'); return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); }; const { env: env$2 } = process; let forceColor$1; if (hasFlag$1('no-color') || hasFlag$1('no-colors') || hasFlag$1('color=false') || hasFlag$1('color=never')) { forceColor$1 = 0; } else if (hasFlag$1('color') || hasFlag$1('colors') || hasFlag$1('color=true') || hasFlag$1('color=always')) { forceColor$1 = 1; } if ('FORCE_COLOR' in env$2) { if (env$2.FORCE_COLOR === 'true') { forceColor$1 = 1; } else if (env$2.FORCE_COLOR === 'false') { forceColor$1 = 0; } else { forceColor$1 = env$2.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$2.FORCE_COLOR, 10), 3); } } function translateLevel$1(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor$1(haveStream, streamIsTTY) { if (forceColor$1 === 0) { return 0; } if (hasFlag$1('color=16m') || hasFlag$1('color=full') || hasFlag$1('color=truecolor')) { return 3; } if (hasFlag$1('color=256')) { return 2; } if (haveStream && !streamIsTTY && forceColor$1 === undefined) { return 0; } const min = forceColor$1 || 0; if (env$2.TERM === 'dumb') { return min; } if (process.platform === 'win32') { // Windows 10 build 10586 is the first Windows release that supports 256 colors. // Windows 10 build 14931 is the first release that supports 16m/TrueColor. const osRelease = require$$0$1.release().split('.'); if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env$2) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env$2) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0; } if ('GITHUB_ACTIONS' in env$2) { return 1; } if (env$2.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env$2) { const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env$2.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env$2.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) { return 1; } if ('COLORTERM' in env$2) { return 1; } return min; } function getSupportLevel$1(stream) { const level = supportsColor$1(stream, stream && stream.isTTY); return translateLevel$1(level); } var supportsColor_1$1 = { supportsColor: getSupportLevel$1, stdout: translateLevel$1(supportsColor$1(true, tty.isatty(1))), stderr: translateLevel$1(supportsColor$1(true, tty.isatty(2))) }; const stringReplaceAll = (string, substring, replacer) => { let index = string.indexOf(substring); if (index === -1) { return string; } const substringLength = substring.length; let endIndex = 0; let returnValue = ''; do { returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; endIndex = index + substringLength; index = string.indexOf(substring, endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { let endIndex = 0; let returnValue = ''; do { const gotCR = string[index - 1] === '\r'; returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; endIndex = index + 1; index = string.indexOf('\n', endIndex); } while (index !== -1); returnValue += string.substr(endIndex); return returnValue; }; var util = { stringReplaceAll, stringEncaseCRLFWithFirstIndex }; const TEMPLATE_REGEX$1 = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; const ESCAPES$1 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]); function unescape$1(c) { const u = c[0] === 'u'; const bracket = c[1] === '{'; if (u && !bracket && c.length === 5 || c[0] === 'x' && c.length === 3) { return String.fromCharCode(parseInt(c.slice(1), 16)); } if (u && bracket) { return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); } return ESCAPES$1.get(c) || c; } function parseArguments$1(name, arguments_) { const results = []; const chunks = arguments_.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { const number = Number(chunk); if (!Number.isNaN(number)) { results.push(number); } else if (matches = chunk.match(STRING_REGEX$1)) { results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$1(escape) : character)); } else { throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')")); } } return results; } function parseStyle$1(style) { STYLE_REGEX$1.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX$1.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments$1(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle$1(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const [styleName, styles] of Object.entries(enabled)) { if (!Array.isArray(styles)) { continue; } if (!(styleName in current)) { throw new Error("Unknown Chalk style: ".concat(styleName)); } current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; } return current; } var templates$1 = (chalk, temporary) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => { if (escapeCharacter) { chunk.push(unescape$1(escapeCharacter)); } else if (style) { const string = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string)); styles.push({ inverse, styles: parseStyle$1(style) }); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle$1(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(character); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMessage = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)"); throw new Error(errMessage); } return chunks.join(''); }; const { stdout: stdoutColor, stderr: stderrColor } = supportsColor_1$1; const { stringReplaceAll: stringReplaceAll$1, stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1 } = util; // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; const styles = Object.create(null); const applyOptions = (object, options = {}) => { if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { throw new Error('The `level` option should be an integer from 0 to 3'); } // Detect level if not set manually const colorLevel = stdoutColor ? stdoutColor.level : 0; object.level = options.level === undefined ? colorLevel : options.level; }; class ChalkClass { constructor(options) { // eslint-disable-next-line no-constructor-return return chalkFactory(options); } } const chalkFactory = options => { const chalk = {}; applyOptions(chalk, options); chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = () => { throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); }; chalk.template.Instance = ChalkClass; return chalk.template; }; function Chalk(options) { return chalkFactory(options); } for (const [styleName, style] of Object.entries(ansiStyles$1)) { styles[styleName] = { get() { const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); Object.defineProperty(this, styleName, { value: builder }); return builder; } }; } styles.visible = { get() { const builder = createBuilder(this, this._styler, true); Object.defineProperty(this, 'visible', { value: builder }); return builder; } }; const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; for (const model of usedModels) { styles[model] = { get() { const { level } = this; return function (...arguments_) { const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } for (const model of usedModels) { const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const { level } = this; return function (...arguments_) { const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler); return createBuilder(this, styler, this._isEmpty); }; } }; } const proto = Object.defineProperties(() => {}, Object.assign({}, styles, { level: { enumerable: true, get() { return this._generator.level; }, set(level) { this._generator.level = level; } } })); const createStyler = (open, close, parent) => { let openAll; let closeAll; if (parent === undefined) { openAll = open; closeAll = close; } else { openAll = parent.openAll + open; closeAll = close + parent.closeAll; } return { open, close, openAll, closeAll, parent }; }; const createBuilder = (self, _styler, _isEmpty) => { const builder = (...arguments_) => { // Single argument is hot path, implicit coercion is faster than anything // eslint-disable-next-line no-implicit-coercion return applyStyle(builder, arguments_.length === 1 ? '' + arguments_[0] : arguments_.join(' ')); }; // We alter the prototype because we must return a function, but there is // no way to create a function with a different prototype Object.setPrototypeOf(builder, proto); builder._generator = self; builder._styler = _styler; builder._isEmpty = _isEmpty; return builder; }; const applyStyle = (self, string) => { if (self.level <= 0 || !string) { return self._isEmpty ? '' : string; } let styler = self._styler; if (styler === undefined) { return string; } const { openAll, closeAll } = styler; if (string.indexOf('\u001B') !== -1) { while (styler !== undefined) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. string = stringReplaceAll$1(string, styler.close, styler.open); styler = styler.parent; } } // We can move both next actions out of loop, because remaining actions in loop won't have // any/visible effect on parts we add here. Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 const lfIndex = string.indexOf('\n'); if (lfIndex !== -1) { string = stringEncaseCRLFWithFirstIndex$1(string, closeAll, openAll, lfIndex); } return openAll + string + closeAll; }; let template; const chalkTag = (chalk, ...strings) => { const [firstString] = strings; if (!Array.isArray(firstString)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return strings.join(' '); } const arguments_ = strings.slice(1); const parts = [firstString.raw[0]]; for (let i = 1; i < firstString.length; i++) { parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i])); } if (template === undefined) { template = templates$1; } return template(chalk, parts.join('')); }; Object.defineProperties(Chalk.prototype, styles); const chalk$1 = Chalk(); // eslint-disable-line new-cap chalk$1.supportsColor = stdoutColor; chalk$1.stderr = Chalk({ level: stderrColor ? stderrColor.level : 0 }); // eslint-disable-line new-cap chalk$1.stderr.supportsColor = stderrColor; var source = chalk$1; const cliDescriptor = { key: _key => _key.length === 1 ? "-".concat(_key) : "--".concat(_key), value: _value => lib.apiDescriptor.value(_value), pair: ({ key, value }) => value === false ? "--no-".concat(key) : value === true ? cliDescriptor.key(key) : value === "" ? "".concat(cliDescriptor.key(key), " without an argument") : "".concat(cliDescriptor.key(key), "=").concat(value) }; class FlagSchema extends lib.ChoiceSchema { constructor({ name, flags }) { super({ name, choices: flags }); this._flags = flags.slice().sort(); } preprocess(value, utils) { if (typeof value === "string" && value.length !== 0 && !this._flags.includes(value)) { const suggestion = this._flags.find(flag => leven_1$1(flag, value) < 3); if (suggestion) { utils.logger.warn(["Unknown flag ".concat(source.yellow(utils.descriptor.value(value)), ","), "did you mean ".concat(source.blue(utils.descriptor.value(suggestion)), "?")].join(" ")); return suggestion; } } return value; } expected() { return "a flag"; } } let hasDeprecationWarned; function normalizeOptions(options, optionInfos, { logger, isCLI = false, passThrough = false } = {}) { const unknown = !passThrough ? lib.levenUnknownHandler : Array.isArray(passThrough) ? (key, value) => !passThrough.includes(key) ? undefined : { [key]: value } : (key, value) => ({ [key]: value }); const descriptor = isCLI ? cliDescriptor : lib.apiDescriptor; const schemas = optionInfosToSchemas(optionInfos, { isCLI }); const normalizer = new lib.Normalizer(schemas, { logger, unknown, descriptor }); const shouldSuppressDuplicateDeprecationWarnings = logger !== false; if (shouldSuppressDuplicateDeprecationWarnings && hasDeprecationWarned) { normalizer._hasDeprecationWarned = hasDeprecationWarned; } const normalized = normalizer.normalize(options); if (shouldSuppressDuplicateDeprecationWarnings) { hasDeprecationWarned = normalizer._hasDeprecationWarned; } return normalized; } function optionInfosToSchemas(optionInfos, { isCLI }) { const schemas = []; if (isCLI) { schemas.push(lib.AnySchema.create({ name: "_" })); } for (const optionInfo of optionInfos) { schemas.push(optionInfoToSchema(optionInfo, { isCLI, optionInfos })); if (optionInfo.alias && isCLI) { schemas.push(lib.AliasSchema.create({ name: optionInfo.alias, sourceName: optionInfo.name })); } } return schemas; } function optionInfoToSchema(optionInfo, { isCLI, optionInfos }) { let SchemaConstructor; const parameters = { name: optionInfo.name }; const handlers = {}; switch (optionInfo.type) { case "int": SchemaConstructor = lib.IntegerSchema; if (isCLI) { parameters.preprocess = value => Number(value); } break; case "string": SchemaConstructor = lib.StringSchema; break; case "choice": SchemaConstructor = lib.ChoiceSchema; parameters.choices = optionInfo.choices.map(choiceInfo => typeof choiceInfo === "object" && choiceInfo.redirect ? Object.assign({}, choiceInfo, { redirect: { to: { key: optionInfo.name, value: choiceInfo.redirect } } }) : choiceInfo); break; case "boolean": SchemaConstructor = lib.BooleanSchema; break; case "flag": SchemaConstructor = FlagSchema; parameters.flags = optionInfos.map(optionInfo => [].concat(optionInfo.alias || [], optionInfo.description ? optionInfo.name : [], optionInfo.oppositeDescription ? "no-".concat(optionInfo.name) : [])).reduce((a, b) => a.concat(b), []); break; case "path": SchemaConstructor = lib.StringSchema; break; default: throw new Error("Unexpected type ".concat(optionInfo.type)); } if (optionInfo.exception) { parameters.validate = (value, schema, utils) => { return optionInfo.exception(value) || schema.validate(value, utils); }; } else { parameters.validate = (value, schema, utils) => { return value === undefined || schema.validate(value, utils); }; } if (optionInfo.redirect) { handlers.redirect = value => !value ? undefined : { to: { key: optionInfo.redirect.option, value: optionInfo.redirect.value } }; } if (optionInfo.deprecated) { handlers.deprecated = true; } // allow CLI overriding, e.g., prettier package.json --tab-width 1 --tab-width 2 if (isCLI && !optionInfo.array) { const originalPreprocess = parameters.preprocess || (x => x); parameters.preprocess = (value, schema, utils) => schema.preprocess(originalPreprocess(Array.isArray(value) ? value[value.length - 1] : value), utils); } return optionInfo.array ? lib.ArraySchema.create(Object.assign({}, isCLI ? { preprocess: v => [].concat(v) } : {}, {}, handlers, { valueSchema: SchemaConstructor.create(parameters) })) : SchemaConstructor.create(Object.assign({}, parameters, {}, handlers)); } function normalizeApiOptions(options, optionInfos, opts) { return normalizeOptions(options, optionInfos, opts); } function normalizeCliOptions(options, optionInfos, opts) { return normalizeOptions(options, optionInfos, Object.assign({ isCLI: true }, opts)); } var optionsNormalizer = { normalizeApiOptions, normalizeCliOptions }; var getLast = arr => arr[arr.length - 1]; function locStart(node, opts) { opts = opts || {}; // Handle nodes with decorators. They should start at the first decorator if (!opts.ignoreDecorators && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0) { return locStart(node.declaration.decorators[0]); } if (!opts.ignoreDecorators && node.decorators && node.decorators.length > 0) { return locStart(node.decorators[0]); } if (node.__location) { return node.__location.startOffset; } if (node.range) { return node.range[0]; } if (typeof node.start === "number") { return node.start; } if (node.loc) { return node.loc.start; } return null; } function locEnd(node) { const endNode = node.nodes && getLast(node.nodes); if (endNode && node.source && !node.source.end) { node = endNode; } if (node.__location) { return node.__location.endOffset; } const loc = node.range ? node.range[1] : typeof node.end === "number" ? node.end : null; if (node.typeAnnotation) { return Math.max(loc, locEnd(node.typeAnnotation)); } if (node.loc && !loc) { return node.loc.end; } return loc; } function composeLoc(startNode, endNodeOrLength = startNode) { const length = typeof endNodeOrLength === "number" ? endNodeOrLength : -1; const start = locStart(startNode); const end = length !== -1 ? start + length : locEnd(endNodeOrLength); const startLoc = startNode.loc.start; return { start, end, range: [start, end], loc: { start: startLoc, end: length !== -1 ? { line: startLoc.line, column: startLoc.column + length } : endNodeOrLength.loc.end } }; } var loc = { locStart, locEnd, composeLoc }; var jsTokens = createCommonjsModule(function (module, exports) { // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell // License: MIT. (See LICENSE.) Object.defineProperty(exports, "__esModule", { value: true }); // This regex comes from regex.coffee, and is inserted here by generate-index.js // (run `npm run build`). exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g; exports.matchToToken = function (match) { var token = { type: "invalid", value: match[0], closed: undefined }; if (match[1]) token.type = "string", token.closed = !!(match[3] || match[4]);else if (match[5]) token.type = "comment";else if (match[6]) token.type = "comment", token.closed = !!match[7];else if (match[8]) token.type = "regex";else if (match[9]) token.type = "number";else if (match[10]) token.type = "name";else if (match[11]) token.type = "punctuator";else if (match[12]) token.type = "whitespace"; return token; }; }); unwrapExports(jsTokens); var jsTokens_1 = jsTokens.matchToToken; var ast = createCommonjsModule(function (module) { /* Copyright (C) 2013 Yusuke Suzuki Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function () { function isExpression(node) { if (node == null) { return false; } switch (node.type) { case 'ArrayExpression': case 'AssignmentExpression': case 'BinaryExpression': case 'CallExpression': case 'ConditionalExpression': case 'FunctionExpression': case 'Identifier': case 'Literal': case 'LogicalExpression': case 'MemberExpression': case 'NewExpression': case 'ObjectExpression': case 'SequenceExpression': case 'ThisExpression': case 'UnaryExpression': case 'UpdateExpression': return true; } return false; } function isIterationStatement(node) { if (node == null) { return false; } switch (node.type) { case 'DoWhileStatement': case 'ForInStatement': case 'ForStatement': case 'WhileStatement': return true; } return false; } function isStatement(node) { if (node == null) { return false; } switch (node.type) { case 'BlockStatement': case 'BreakStatement': case 'ContinueStatement': case 'DebuggerStatement': case 'DoWhileStatement': case 'EmptyStatement': case 'ExpressionStatement': case 'ForInStatement': case 'ForStatement': case 'IfStatement': case 'LabeledStatement': case 'ReturnStatement': case 'SwitchStatement': case 'ThrowStatement': case 'TryStatement': case 'VariableDeclaration': case 'WhileStatement': case 'WithStatement': return true; } return false; } function isSourceElement(node) { return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; } function trailingStatement(node) { switch (node.type) { case 'IfStatement': if (node.alternate != null) { return node.alternate; } return node.consequent; case 'LabeledStatement': case 'ForStatement': case 'ForInStatement': case 'WhileStatement': case 'WithStatement': return node.body; } return null; } function isProblematicIfStatement(node) { var current; if (node.type !== 'IfStatement') { return false; } if (node.alternate == null) { return false; } current = node.consequent; do { if (current.type === 'IfStatement') { if (current.alternate == null) { return true; } } current = trailingStatement(current); } while (current); return false; } module.exports = { isExpression: isExpression, isStatement: isStatement, isIterationStatement: isIterationStatement, isSourceElement: isSourceElement, isProblematicIfStatement: isProblematicIfStatement, trailingStatement: trailingStatement }; })(); /* vim: set sw=4 ts=4 et tw=80 : */ }); var ast_1 = ast.isExpression; var ast_2 = ast.isStatement; var ast_3 = ast.isIterationStatement; var ast_4 = ast.isSourceElement; var ast_5 = ast.isProblematicIfStatement; var ast_6 = ast.trailingStatement; var code = createCommonjsModule(function (module) { /* Copyright (C) 2013-2014 Yusuke Suzuki Copyright (C) 2014 Ivan Nikulin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function () { var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`. ES5Regex = { // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart: NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/, // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart: NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/ }; ES6Regex = { // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart: NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart: NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ }; function isDecimalDigit(ch) { return 0x30 <= ch && ch <= 0x39; // 0..9 } function isHexDigit(ch) { return 0x30 <= ch && ch <= 0x39 || // 0..9 0x61 <= ch && ch <= 0x66 || // a..f 0x41 <= ch && ch <= 0x46; // A..F } function isOctalDigit(ch) { return ch >= 0x30 && ch <= 0x37; // 0..7 } // 7.2 White Space NON_ASCII_WHITESPACES = [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF]; function isWhiteSpace(ch) { return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0; } // 7.3 Line Terminators function isLineTerminator(ch) { return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029; } // 7.6 Identifier Names and Identifiers function fromCodePoint(cp) { if (cp <= 0xFFFF) { return String.fromCharCode(cp); } var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00); return cu1 + cu2; } IDENTIFIER_START = new Array(0x80); for (ch = 0; ch < 0x80; ++ch) { IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z ch >= 0x41 && ch <= 0x5A || // A..Z ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) } IDENTIFIER_PART = new Array(0x80); for (ch = 0; ch < 0x80; ++ch) { IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z ch >= 0x41 && ch <= 0x5A || // A..Z ch >= 0x30 && ch <= 0x39 || // 0..9 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) } function isIdentifierStartES5(ch) { return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); } function isIdentifierPartES5(ch) { return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); } function isIdentifierStartES6(ch) { return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); } function isIdentifierPartES6(ch) { return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); } module.exports = { isDecimalDigit: isDecimalDigit, isHexDigit: isHexDigit, isOctalDigit: isOctalDigit, isWhiteSpace: isWhiteSpace, isLineTerminator: isLineTerminator, isIdentifierStartES5: isIdentifierStartES5, isIdentifierPartES5: isIdentifierPartES5, isIdentifierStartES6: isIdentifierStartES6, isIdentifierPartES6: isIdentifierPartES6 }; })(); /* vim: set sw=4 ts=4 et tw=80 : */ }); var code_1 = code.isDecimalDigit; var code_2 = code.isHexDigit; var code_3 = code.isOctalDigit; var code_4 = code.isWhiteSpace; var code_5 = code.isLineTerminator; var code_6 = code.isIdentifierStartES5; var code_7 = code.isIdentifierPartES5; var code_8 = code.isIdentifierStartES6; var code_9 = code.isIdentifierPartES6; var keyword = createCommonjsModule(function (module) { /* Copyright (C) 2013 Yusuke Suzuki Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function () { var code$1 = code; function isStrictModeReservedWordES6(id) { switch (id) { case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'let': return true; default: return false; } } function isKeywordES5(id, strict) { // yield should not be treated as keyword under non-strict mode. if (!strict && id === 'yield') { return false; } return isKeywordES6(id, strict); } function isKeywordES6(id, strict) { if (strict && isStrictModeReservedWordES6(id)) { return true; } switch (id.length) { case 2: return id === 'if' || id === 'in' || id === 'do'; case 3: return id === 'var' || id === 'for' || id === 'new' || id === 'try'; case 4: return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum'; case 5: return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super'; case 6: return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import'; case 7: return id === 'default' || id === 'finally' || id === 'extends'; case 8: return id === 'function' || id === 'continue' || id === 'debugger'; case 10: return id === 'instanceof'; default: return false; } } function isReservedWordES5(id, strict) { return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); } function isReservedWordES6(id, strict) { return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); } function isRestrictedWord(id) { return id === 'eval' || id === 'arguments'; } function isIdentifierNameES5(id) { var i, iz, ch; if (id.length === 0) { return false; } ch = id.charCodeAt(0); if (!code$1.isIdentifierStartES5(ch)) { return false; } for (i = 1, iz = id.length; i < iz; ++i) { ch = id.charCodeAt(i); if (!code$1.isIdentifierPartES5(ch)) { return false; } } return true; } function decodeUtf16(lead, trail) { return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; } function isIdentifierNameES6(id) { var i, iz, ch, lowCh, check; if (id.length === 0) { return false; } check = code$1.isIdentifierStartES6; for (i = 0, iz = id.length; i < iz; ++i) { ch = id.charCodeAt(i); if (0xD800 <= ch && ch <= 0xDBFF) { ++i; if (i >= iz) { return false; } lowCh = id.charCodeAt(i); if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { return false; } ch = decodeUtf16(ch, lowCh); } if (!check(ch)) { return false; } check = code$1.isIdentifierPartES6; } return true; } function isIdentifierES5(id, strict) { return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); } function isIdentifierES6(id, strict) { return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); } module.exports = { isKeywordES5: isKeywordES5, isKeywordES6: isKeywordES6, isReservedWordES5: isReservedWordES5, isReservedWordES6: isReservedWordES6, isRestrictedWord: isRestrictedWord, isIdentifierNameES5: isIdentifierNameES5, isIdentifierNameES6: isIdentifierNameES6, isIdentifierES5: isIdentifierES5, isIdentifierES6: isIdentifierES6 }; })(); /* vim: set sw=4 ts=4 et tw=80 : */ }); var keyword_1 = keyword.isKeywordES5; var keyword_2 = keyword.isKeywordES6; var keyword_3 = keyword.isReservedWordES5; var keyword_4 = keyword.isReservedWordES6; var keyword_5 = keyword.isRestrictedWord; var keyword_6 = keyword.isIdentifierNameES5; var keyword_7 = keyword.isIdentifierNameES6; var keyword_8 = keyword.isIdentifierES5; var keyword_9 = keyword.isIdentifierES6; var utils$1 = createCommonjsModule(function (module, exports) { /* Copyright (C) 2013 Yusuke Suzuki Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function () { exports.ast = ast; exports.code = code; exports.keyword = keyword; })(); /* vim: set sw=4 ts=4 et tw=80 : */ }); var utils_1$1 = utils$1.ast; var utils_2$1 = utils$1.code; var utils_3$1 = utils$1.keyword; var matchOperatorsRe$1 = /[|\\{}()[\]^$+*?.]/g; var escapeStringRegexp$1 = function escapeStringRegexp(str) { if (typeof str !== 'string') { throw new TypeError('Expected a string'); } return str.replace(matchOperatorsRe$1, '\\$&'); }; var colorName$2 = { "aliceblue": [240, 248, 255], "antiquewhite": [250, 235, 215], "aqua": [0, 255, 255], "aquamarine": [127, 255, 212], "azure": [240, 255, 255], "beige": [245, 245, 220], "bisque": [255, 228, 196], "black": [0, 0, 0], "blanchedalmond": [255, 235, 205], "blue": [0, 0, 255], "blueviolet": [138, 43, 226], "brown": [165, 42, 42], "burlywood": [222, 184, 135], "cadetblue": [95, 158, 160], "chartreuse": [127, 255, 0], "chocolate": [210, 105, 30], "coral": [255, 127, 80], "cornflowerblue": [100, 149, 237], "cornsilk": [255, 248, 220], "crimson": [220, 20, 60], "cyan": [0, 255, 255], "darkblue": [0, 0, 139], "darkcyan": [0, 139, 139], "darkgoldenrod": [184, 134, 11], "darkgray": [169, 169, 169], "darkgreen": [0, 100, 0], "darkgrey": [169, 169, 169], "darkkhaki": [189, 183, 107], "darkmagenta": [139, 0, 139], "darkolivegreen": [85, 107, 47], "darkorange": [255, 140, 0], "darkorchid": [153, 50, 204], "darkred": [139, 0, 0], "darksalmon": [233, 150, 122], "darkseagreen": [143, 188, 143], "darkslateblue": [72, 61, 139], "darkslategray": [47, 79, 79], "darkslategrey": [47, 79, 79], "darkturquoise": [0, 206, 209], "darkviolet": [148, 0, 211], "deeppink": [255, 20, 147], "deepskyblue": [0, 191, 255], "dimgray": [105, 105, 105], "dimgrey": [105, 105, 105], "dodgerblue": [30, 144, 255], "firebrick": [178, 34, 34], "floralwhite": [255, 250, 240], "forestgreen": [34, 139, 34], "fuchsia": [255, 0, 255], "gainsboro": [220, 220, 220], "ghostwhite": [248, 248, 255], "gold": [255, 215, 0], "goldenrod": [218, 165, 32], "gray": [128, 128, 128], "green": [0, 128, 0], "greenyellow": [173, 255, 47], "grey": [128, 128, 128], "honeydew": [240, 255, 240], "hotpink": [255, 105, 180], "indianred": [205, 92, 92], "indigo": [75, 0, 130], "ivory": [255, 255, 240], "khaki": [240, 230, 140], "lavender": [230, 230, 250], "lavenderblush": [255, 240, 245], "lawngreen": [124, 252, 0], "lemonchiffon": [255, 250, 205], "lightblue": [173, 216, 230], "lightcoral": [240, 128, 128], "lightcyan": [224, 255, 255], "lightgoldenrodyellow": [250, 250, 210], "lightgray": [211, 211, 211], "lightgreen": [144, 238, 144], "lightgrey": [211, 211, 211], "lightpink": [255, 182, 193], "lightsalmon": [255, 160, 122], "lightseagreen": [32, 178, 170], "lightskyblue": [135, 206, 250], "lightslategray": [119, 136, 153], "lightslategrey": [119, 136, 153], "lightsteelblue": [176, 196, 222], "lightyellow": [255, 255, 224], "lime": [0, 255, 0], "limegreen": [50, 205, 50], "linen": [250, 240, 230], "magenta": [255, 0, 255], "maroon": [128, 0, 0], "mediumaquamarine": [102, 205, 170], "mediumblue": [0, 0, 205], "mediumorchid": [186, 85, 211], "mediumpurple": [147, 112, 219], "mediumseagreen": [60, 179, 113], "mediumslateblue": [123, 104, 238], "mediumspringgreen": [0, 250, 154], "mediumturquoise": [72, 209, 204], "mediumvioletred": [199, 21, 133], "midnightblue": [25, 25, 112], "mintcream": [245, 255, 250], "mistyrose": [255, 228, 225], "moccasin": [255, 228, 181], "navajowhite": [255, 222, 173], "navy": [0, 0, 128], "oldlace": [253, 245, 230], "olive": [128, 128, 0], "olivedrab": [107, 142, 35], "orange": [255, 165, 0], "orangered": [255, 69, 0], "orchid": [218, 112, 214], "palegoldenrod": [238, 232, 170], "palegreen": [152, 251, 152], "paleturquoise": [175, 238, 238], "palevioletred": [219, 112, 147], "papayawhip": [255, 239, 213], "peachpuff": [255, 218, 185], "peru": [205, 133, 63], "pink": [255, 192, 203], "plum": [221, 160, 221], "powderblue": [176, 224, 230], "purple": [128, 0, 128], "rebeccapurple": [102, 51, 153], "red": [255, 0, 0], "rosybrown": [188, 143, 143], "royalblue": [65, 105, 225], "saddlebrown": [139, 69, 19], "salmon": [250, 128, 114], "sandybrown": [244, 164, 96], "seagreen": [46, 139, 87], "seashell": [255, 245, 238], "sienna": [160, 82, 45], "silver": [192, 192, 192], "skyblue": [135, 206, 235], "slateblue": [106, 90, 205], "slategray": [112, 128, 144], "slategrey": [112, 128, 144], "snow": [255, 250, 250], "springgreen": [0, 255, 127], "steelblue": [70, 130, 180], "tan": [210, 180, 140], "teal": [0, 128, 128], "thistle": [216, 191, 216], "tomato": [255, 99, 71], "turquoise": [64, 224, 208], "violet": [238, 130, 238], "wheat": [245, 222, 179], "white": [255, 255, 255], "whitesmoke": [245, 245, 245], "yellow": [255, 255, 0], "yellowgreen": [154, 205, 50] }; var conversions$2 = createCommonjsModule(function (module) { /* MIT license */ // NOTE: conversions should only return primitive values (i.e. arrays, or // values that give correct `typeof` results). // do not use box values types (i.e. Number(), String(), etc.) var reverseKeywords = {}; for (var key in colorName$2) { if (colorName$2.hasOwnProperty(key)) { reverseKeywords[colorName$2[key]] = key; } } var convert = module.exports = { rgb: { channels: 3, labels: 'rgb' }, hsl: { channels: 3, labels: 'hsl' }, hsv: { channels: 3, labels: 'hsv' }, hwb: { channels: 3, labels: 'hwb' }, cmyk: { channels: 4, labels: 'cmyk' }, xyz: { channels: 3, labels: 'xyz' }, lab: { channels: 3, labels: 'lab' }, lch: { channels: 3, labels: 'lch' }, hex: { channels: 1, labels: ['hex'] }, keyword: { channels: 1, labels: ['keyword'] }, ansi16: { channels: 1, labels: ['ansi16'] }, ansi256: { channels: 1, labels: ['ansi256'] }, hcg: { channels: 3, labels: ['h', 'c', 'g'] }, apple: { channels: 3, labels: ['r16', 'g16', 'b16'] }, gray: { channels: 1, labels: ['gray'] } }; // hide .channels and .labels properties for (var model in convert) { if (convert.hasOwnProperty(model)) { if (!('channels' in convert[model])) { throw new Error('missing channels property: ' + model); } if (!('labels' in convert[model])) { throw new Error('missing channel labels property: ' + model); } if (convert[model].labels.length !== convert[model].channels) { throw new Error('channel and label counts mismatch: ' + model); } var channels = convert[model].channels; var labels = convert[model].labels; delete convert[model].channels; delete convert[model].labels; Object.defineProperty(convert[model], 'channels', { value: channels }); Object.defineProperty(convert[model], 'labels', { value: labels }); } } convert.rgb.hsl = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var min = Math.min(r, g, b); var max = Math.max(r, g, b); var delta = max - min; var h; var s; var l; if (max === min) { h = 0; } else if (r === max) { h = (g - b) / delta; } else if (g === max) { h = 2 + (b - r) / delta; } else if (b === max) { h = 4 + (r - g) / delta; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } l = (min + max) / 2; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return [h, s * 100, l * 100]; }; convert.rgb.hsv = function (rgb) { var rdif; var gdif; var bdif; var h; var s; var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var v = Math.max(r, g, b); var diff = v - Math.min(r, g, b); var diffc = function diffc(c) { return (v - c) / 6 / diff + 1 / 2; }; if (diff === 0) { h = s = 0; } else { s = diff / v; rdif = diffc(r); gdif = diffc(g); bdif = diffc(b); if (r === v) { h = bdif - gdif; } else if (g === v) { h = 1 / 3 + rdif - bdif; } else if (b === v) { h = 2 / 3 + gdif - rdif; } if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } } return [h * 360, s * 100, v * 100]; }; convert.rgb.hwb = function (rgb) { var r = rgb[0]; var g = rgb[1]; var b = rgb[2]; var h = convert.rgb.hsl(rgb)[0]; var w = 1 / 255 * Math.min(r, Math.min(g, b)); b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); return [h, w * 100, b * 100]; }; convert.rgb.cmyk = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var c; var m; var y; var k; k = Math.min(1 - r, 1 - g, 1 - b); c = (1 - r - k) / (1 - k) || 0; m = (1 - g - k) / (1 - k) || 0; y = (1 - b - k) / (1 - k) || 0; return [c * 100, m * 100, y * 100, k * 100]; }; /** * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance * */ function comparativeDistance(x, y) { return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2); } convert.rgb.keyword = function (rgb) { var reversed = reverseKeywords[rgb]; if (reversed) { return reversed; } var currentClosestDistance = Infinity; var currentClosestKeyword; for (var keyword in colorName$2) { if (colorName$2.hasOwnProperty(keyword)) { var value = colorName$2[keyword]; // Compute comparative distance var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest if (distance < currentClosestDistance) { currentClosestDistance = distance; currentClosestKeyword = keyword; } } } return currentClosestKeyword; }; convert.keyword.rgb = function (keyword) { return colorName$2[keyword]; }; convert.rgb.xyz = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; // assume sRGB r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; var x = r * 0.4124 + g * 0.3576 + b * 0.1805; var y = r * 0.2126 + g * 0.7152 + b * 0.0722; var z = r * 0.0193 + g * 0.1192 + b * 0.9505; return [x * 100, y * 100, z * 100]; }; convert.rgb.lab = function (rgb) { var xyz = convert.rgb.xyz(rgb); var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; l = 116 * y - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.hsl.rgb = function (hsl) { var h = hsl[0] / 360; var s = hsl[1] / 100; var l = hsl[2] / 100; var t1; var t2; var t3; var rgb; var val; if (s === 0) { val = l * 255; return [val, val, val]; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } t1 = 2 * l - t2; rgb = [0, 0, 0]; for (var i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return rgb; }; convert.hsl.hsv = function (hsl) { var h = hsl[0]; var s = hsl[1] / 100; var l = hsl[2] / 100; var smin = s; var lmin = Math.max(l, 0.01); var sv; var v; l *= 2; s *= l <= 1 ? l : 2 - l; smin *= lmin <= 1 ? lmin : 2 - lmin; v = (l + s) / 2; sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); return [h, sv * 100, v * 100]; }; convert.hsv.rgb = function (hsv) { var h = hsv[0] / 60; var s = hsv[1] / 100; var v = hsv[2] / 100; var hi = Math.floor(h) % 6; var f = h - Math.floor(h); var p = 255 * v * (1 - s); var q = 255 * v * (1 - s * f); var t = 255 * v * (1 - s * (1 - f)); v *= 255; switch (hi) { case 0: return [v, t, p]; case 1: return [q, v, p]; case 2: return [p, v, t]; case 3: return [p, q, v]; case 4: return [t, p, v]; case 5: return [v, p, q]; } }; convert.hsv.hsl = function (hsv) { var h = hsv[0]; var s = hsv[1] / 100; var v = hsv[2] / 100; var vmin = Math.max(v, 0.01); var lmin; var sl; var l; l = (2 - s) * v; lmin = (2 - s) * vmin; sl = s * vmin; sl /= lmin <= 1 ? lmin : 2 - lmin; sl = sl || 0; l /= 2; return [h, sl * 100, l * 100]; }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb convert.hwb.rgb = function (hwb) { var h = hwb[0] / 360; var wh = hwb[1] / 100; var bl = hwb[2] / 100; var ratio = wh + bl; var i; var v; var f; var n; // wh + bl cant be > 1 if (ratio > 1) { wh /= ratio; bl /= ratio; } i = Math.floor(6 * h); v = 1 - bl; f = 6 * h - i; if ((i & 0x01) !== 0) { f = 1 - f; } n = wh + f * (v - wh); // linear interpolation var r; var g; var b; switch (i) { default: case 6: case 0: r = v; g = n; b = wh; break; case 1: r = n; g = v; b = wh; break; case 2: r = wh; g = v; b = n; break; case 3: r = wh; g = n; b = v; break; case 4: r = n; g = wh; b = v; break; case 5: r = v; g = wh; b = n; break; } return [r * 255, g * 255, b * 255]; }; convert.cmyk.rgb = function (cmyk) { var c = cmyk[0] / 100; var m = cmyk[1] / 100; var y = cmyk[2] / 100; var k = cmyk[3] / 100; var r; var g; var b; r = 1 - Math.min(1, c * (1 - k) + k); g = 1 - Math.min(1, m * (1 - k) + k); b = 1 - Math.min(1, y * (1 - k) + k); return [r * 255, g * 255, b * 255]; }; convert.xyz.rgb = function (xyz) { var x = xyz[0] / 100; var y = xyz[1] / 100; var z = xyz[2] / 100; var r; var g; var b; r = x * 3.2406 + y * -1.5372 + z * -0.4986; g = x * -0.9689 + y * 1.8758 + z * 0.0415; b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92; g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92; b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92; r = Math.min(Math.max(0, r), 1); g = Math.min(Math.max(0, g), 1); b = Math.min(Math.max(0, b), 1); return [r * 255, g * 255, b * 255]; }; convert.xyz.lab = function (xyz) { var x = xyz[0]; var y = xyz[1]; var z = xyz[2]; var l; var a; var b; x /= 95.047; y /= 100; z /= 108.883; x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; l = 116 * y - 16; a = 500 * (x - y); b = 200 * (y - z); return [l, a, b]; }; convert.lab.xyz = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var x; var y; var z; y = (l + 16) / 116; x = a / 500 + y; z = y - b / 200; var y2 = Math.pow(y, 3); var x2 = Math.pow(x, 3); var z2 = Math.pow(z, 3); y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; x *= 95.047; y *= 100; z *= 108.883; return [x, y, z]; }; convert.lab.lch = function (lab) { var l = lab[0]; var a = lab[1]; var b = lab[2]; var hr; var h; var c; hr = Math.atan2(b, a); h = hr * 360 / 2 / Math.PI; if (h < 0) { h += 360; } c = Math.sqrt(a * a + b * b); return [l, c, h]; }; convert.lch.lab = function (lch) { var l = lch[0]; var c = lch[1]; var h = lch[2]; var a; var b; var hr; hr = h / 360 * 2 * Math.PI; a = c * Math.cos(hr); b = c * Math.sin(hr); return [l, a, b]; }; convert.rgb.ansi16 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization value = Math.round(value / 50); if (value === 0) { return 30; } var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); if (value === 2) { ansi += 60; } return ansi; }; convert.hsv.ansi16 = function (args) { // optimization here; we already know the value and don't need to get // it converted for us. return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); }; convert.rgb.ansi256 = function (args) { var r = args[0]; var g = args[1]; var b = args[2]; // we use the extended greyscale palette here, with the exception of // black and white. normal palette only has 4 greyscale shades. if (r === g && g === b) { if (r < 8) { return 16; } if (r > 248) { return 231; } return Math.round((r - 8) / 247 * 24) + 232; } var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); return ansi; }; convert.ansi16.rgb = function (args) { var color = args % 10; // handle greyscale if (color === 0 || color === 7) { if (args > 50) { color += 3.5; } color = color / 10.5 * 255; return [color, color, color]; } var mult = (~~(args > 50) + 1) * 0.5; var r = (color & 1) * mult * 255; var g = (color >> 1 & 1) * mult * 255; var b = (color >> 2 & 1) * mult * 255; return [r, g, b]; }; convert.ansi256.rgb = function (args) { // handle greyscale if (args >= 232) { var c = (args - 232) * 10 + 8; return [c, c, c]; } args -= 16; var rem; var r = Math.floor(args / 36) / 5 * 255; var g = Math.floor((rem = args % 36) / 6) / 5 * 255; var b = rem % 6 / 5 * 255; return [r, g, b]; }; convert.rgb.hex = function (args) { var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.hex.rgb = function (args) { var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); if (!match) { return [0, 0, 0]; } var colorString = match[0]; if (match[0].length === 3) { colorString = colorString.split('').map(function (char) { return char + char; }).join(''); } var integer = parseInt(colorString, 16); var r = integer >> 16 & 0xFF; var g = integer >> 8 & 0xFF; var b = integer & 0xFF; return [r, g, b]; }; convert.rgb.hcg = function (rgb) { var r = rgb[0] / 255; var g = rgb[1] / 255; var b = rgb[2] / 255; var max = Math.max(Math.max(r, g), b); var min = Math.min(Math.min(r, g), b); var chroma = max - min; var grayscale; var hue; if (chroma < 1) { grayscale = min / (1 - chroma); } else { grayscale = 0; } if (chroma <= 0) { hue = 0; } else if (max === r) { hue = (g - b) / chroma % 6; } else if (max === g) { hue = 2 + (b - r) / chroma; } else { hue = 4 + (r - g) / chroma + 4; } hue /= 6; hue %= 1; return [hue * 360, chroma * 100, grayscale * 100]; }; convert.hsl.hcg = function (hsl) { var s = hsl[1] / 100; var l = hsl[2] / 100; var c = 1; var f = 0; if (l < 0.5) { c = 2.0 * s * l; } else { c = 2.0 * s * (1.0 - l); } if (c < 1.0) { f = (l - 0.5 * c) / (1.0 - c); } return [hsl[0], c * 100, f * 100]; }; convert.hsv.hcg = function (hsv) { var s = hsv[1] / 100; var v = hsv[2] / 100; var c = s * v; var f = 0; if (c < 1.0) { f = (v - c) / (1 - c); } return [hsv[0], c * 100, f * 100]; }; convert.hcg.rgb = function (hcg) { var h = hcg[0] / 360; var c = hcg[1] / 100; var g = hcg[2] / 100; if (c === 0.0) { return [g * 255, g * 255, g * 255]; } var pure = [0, 0, 0]; var hi = h % 1 * 6; var v = hi % 1; var w = 1 - v; var mg = 0; switch (Math.floor(hi)) { case 0: pure[0] = 1; pure[1] = v; pure[2] = 0; break; case 1: pure[0] = w; pure[1] = 1; pure[2] = 0; break; case 2: pure[0] = 0; pure[1] = 1; pure[2] = v; break; case 3: pure[0] = 0; pure[1] = w; pure[2] = 1; break; case 4: pure[0] = v; pure[1] = 0; pure[2] = 1; break; default: pure[0] = 1; pure[1] = 0; pure[2] = w; } mg = (1.0 - c) * g; return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255]; }; convert.hcg.hsv = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); var f = 0; if (v > 0.0) { f = c / v; } return [hcg[0], f * 100, v * 100]; }; convert.hcg.hsl = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var l = g * (1.0 - c) + 0.5 * c; var s = 0; if (l > 0.0 && l < 0.5) { s = c / (2 * l); } else if (l >= 0.5 && l < 1.0) { s = c / (2 * (1 - l)); } return [hcg[0], s * 100, l * 100]; }; convert.hcg.hwb = function (hcg) { var c = hcg[1] / 100; var g = hcg[2] / 100; var v = c + g * (1.0 - c); return [hcg[0], (v - c) * 100, (1 - v) * 100]; }; convert.hwb.hcg = function (hwb) { var w = hwb[1] / 100; var b = hwb[2] / 100; var v = 1 - b; var c = v - w; var g = 0; if (c < 1) { g = (v - c) / (1 - c); } return [hwb[0], c * 100, g * 100]; }; convert.apple.rgb = function (apple) { return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; }; convert.rgb.apple = function (rgb) { return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; }; convert.gray.rgb = function (args) { return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; }; convert.gray.hsl = convert.gray.hsv = function (args) { return [0, 0, args[0]]; }; convert.gray.hwb = function (gray) { return [0, 100, gray[0]]; }; convert.gray.cmyk = function (gray) { return [0, 0, 0, gray[0]]; }; convert.gray.lab = function (gray) { return [gray[0], 0, 0]; }; convert.gray.hex = function (gray) { var val = Math.round(gray[0] / 100 * 255) & 0xFF; var integer = (val << 16) + (val << 8) + val; var string = integer.toString(16).toUpperCase(); return '000000'.substring(string.length) + string; }; convert.rgb.gray = function (rgb) { var val = (rgb[0] + rgb[1] + rgb[2]) / 3; return [val / 255 * 100]; }; }); var conversions_1$1 = conversions$2.rgb; var conversions_2$1 = conversions$2.hsl; var conversions_3$1 = conversions$2.hsv; var conversions_4$1 = conversions$2.hwb; var conversions_5$1 = conversions$2.cmyk; var conversions_6$1 = conversions$2.xyz; var conversions_7$1 = conversions$2.lab; var conversions_8$1 = conversions$2.lch; var conversions_9$1 = conversions$2.hex; var conversions_10$1 = conversions$2.keyword; var conversions_11$1 = conversions$2.ansi16; var conversions_12$1 = conversions$2.ansi256; var conversions_13$1 = conversions$2.hcg; var conversions_14$1 = conversions$2.apple; var conversions_15$1 = conversions$2.gray; /* this function routes a model to all other models. all functions that are routed have a property `.conversion` attached to the returned synthetic function. This property is an array of strings, each with the steps in between the 'from' and 'to' color models (inclusive). conversions that are not possible simply are not included. */ function buildGraph$2() { var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 var models = Object.keys(conversions$2); for (var len = models.length, i = 0; i < len; i++) { graph[models[i]] = { // http://jsperf.com/1-vs-infinity // micro-opt, but this is simple. distance: -1, parent: null }; } return graph; } // https://en.wikipedia.org/wiki/Breadth-first_search function deriveBFS$2(fromModel) { var graph = buildGraph$2(); var queue = [fromModel]; // unshift -> queue -> pop graph[fromModel].distance = 0; while (queue.length) { var current = queue.pop(); var adjacents = Object.keys(conversions$2[current]); for (var len = adjacents.length, i = 0; i < len; i++) { var adjacent = adjacents[i]; var node = graph[adjacent]; if (node.distance === -1) { node.distance = graph[current].distance + 1; node.parent = current; queue.unshift(adjacent); } } } return graph; } function link$2(from, to) { return function (args) { return to(from(args)); }; } function wrapConversion$2(toModel, graph) { var path = [graph[toModel].parent, toModel]; var fn = conversions$2[graph[toModel].parent][toModel]; var cur = graph[toModel].parent; while (graph[cur].parent) { path.unshift(graph[cur].parent); fn = link$2(conversions$2[graph[cur].parent][cur], fn); cur = graph[cur].parent; } fn.conversion = path; return fn; } var route$2 = function route(fromModel) { var graph = deriveBFS$2(fromModel); var conversion = {}; var models = Object.keys(graph); for (var len = models.length, i = 0; i < len; i++) { var toModel = models[i]; var node = graph[toModel]; if (node.parent === null) { // no possible conversion, or this node is the source model. continue; } conversion[toModel] = wrapConversion$2(toModel, graph); } return conversion; }; var convert$3 = {}; var models$2 = Object.keys(conversions$2); function wrapRaw$2(fn) { var wrappedFn = function wrappedFn(args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } return fn(args); }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } function wrapRounded$2(fn) { var wrappedFn = function wrappedFn(args) { if (args === undefined || args === null) { return args; } if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } var result = fn(args); // we're assuming the result is an array here. // see notice in conversions.js; don't use box types // in conversion functions. if (typeof result === 'object') { for (var len = result.length, i = 0; i < len; i++) { result[i] = Math.round(result[i]); } } return result; }; // preserve .conversion property if there is one if ('conversion' in fn) { wrappedFn.conversion = fn.conversion; } return wrappedFn; } models$2.forEach(function (fromModel) { convert$3[fromModel] = {}; Object.defineProperty(convert$3[fromModel], 'channels', { value: conversions$2[fromModel].channels }); Object.defineProperty(convert$3[fromModel], 'labels', { value: conversions$2[fromModel].labels }); var routes = route$2(fromModel); var routeModels = Object.keys(routes); routeModels.forEach(function (toModel) { var fn = routes[toModel]; convert$3[fromModel][toModel] = wrapRounded$2(fn); convert$3[fromModel][toModel].raw = wrapRaw$2(fn); }); }); var colorConvert$2 = convert$3; var ansiStyles$2 = createCommonjsModule(function (module) { const wrapAnsi16 = (fn, offset) => function () { const code = fn.apply(colorConvert$2, arguments); return "\x1B[".concat(code + offset, "m"); }; const wrapAnsi256 = (fn, offset) => function () { const code = fn.apply(colorConvert$2, arguments); return "\x1B[".concat(38 + offset, ";5;").concat(code, "m"); }; const wrapAnsi16m = (fn, offset) => function () { const rgb = fn.apply(colorConvert$2, arguments); return "\x1B[".concat(38 + offset, ";2;").concat(rgb[0], ";").concat(rgb[1], ";").concat(rgb[2], "m"); }; 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], gray: [90, 39], // Bright color 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] } }; // Fix humans styles.color.grey = styles.color.gray; for (const groupName of Object.keys(styles)) { const group = styles[groupName]; for (const styleName of Object.keys(group)) { const style = group[styleName]; styles[styleName] = { open: "\x1B[".concat(style[0], "m"), close: "\x1B[".concat(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 }); } const ansi2ansi = n => n; const rgb2rgb = (r, g, b) => [r, g, b]; styles.color.close = '\u001B[39m'; styles.bgColor.close = '\u001B[49m'; styles.color.ansi = { ansi: wrapAnsi16(ansi2ansi, 0) }; styles.color.ansi256 = { ansi256: wrapAnsi256(ansi2ansi, 0) }; styles.color.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 0) }; styles.bgColor.ansi = { ansi: wrapAnsi16(ansi2ansi, 10) }; styles.bgColor.ansi256 = { ansi256: wrapAnsi256(ansi2ansi, 10) }; styles.bgColor.ansi16m = { rgb: wrapAnsi16m(rgb2rgb, 10) }; for (let key of Object.keys(colorConvert$2)) { if (typeof colorConvert$2[key] !== 'object') { continue; } const suite = colorConvert$2[key]; if (key === 'ansi16') { key = 'ansi'; } if ('ansi16' in suite) { styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); } if ('ansi256' in suite) { styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); } if ('rgb' in suite) { styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); } } return styles; } // Make the export immutable Object.defineProperty(module, 'exports', { enumerable: true, get: assembleStyles }); }); const env$3 = process.env; let forceColor$2; if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { forceColor$2 = false; } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { forceColor$2 = true; } if ('FORCE_COLOR' in env$3) { forceColor$2 = env$3.FORCE_COLOR.length === 0 || parseInt(env$3.FORCE_COLOR, 10) !== 0; } function translateLevel$2(level) { if (level === 0) { return false; } return { level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; } function supportsColor$2(stream) { if (forceColor$2 === false) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (stream && !stream.isTTY && forceColor$2 !== true) { return 0; } const min = forceColor$2 ? 1 : 0; if (process.platform === 'win32') { // Node.js 7.5.0 is the first version of Node.js to include a patch to // libuv that enables 256 color output on Windows. Anything earlier and it // won't work. However, here we target Node.js 8 at minimum as it is an LTS // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows // release that supports 256 colors. Windows 10 build 14931 is the first release // that supports 16m/TrueColor. const osRelease = require$$0$1.release().split('.'); if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { return Number(osRelease[2]) >= 14931 ? 3 : 2; } return 1; } if ('CI' in env$3) { if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$3) || env$3.CI_NAME === 'codeship') { return 1; } return min; } if ('TEAMCITY_VERSION' in env$3) { return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$3.TEAMCITY_VERSION) ? 1 : 0; } if (env$3.COLORTERM === 'truecolor') { return 3; } if ('TERM_PROGRAM' in env$3) { const version = parseInt((env$3.TERM_PROGRAM_VERSION || '').split('.')[0], 10); switch (env$3.TERM_PROGRAM) { case 'iTerm.app': return version >= 3 ? 3 : 2; case 'Apple_Terminal': return 2; // No default } } if (/-256(color)?$/i.test(env$3.TERM)) { return 2; } if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$3.TERM)) { return 1; } if ('COLORTERM' in env$3) { return 1; } if (env$3.TERM === 'dumb') { return min; } return min; } function getSupportLevel$2(stream) { const level = supportsColor$2(stream); return translateLevel$2(level); } var supportsColor_1$2 = { supportsColor: getSupportLevel$2, stdout: getSupportLevel$2(process.stdout), stderr: getSupportLevel$2(process.stderr) }; const TEMPLATE_REGEX$2 = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; const STYLE_REGEX$2 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; const STRING_REGEX$2 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; const ESCAPE_REGEX$2 = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; const ESCAPES$2 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]); function unescape$2(c) { if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) { return String.fromCharCode(parseInt(c.slice(1), 16)); } return ESCAPES$2.get(c) || c; } function parseArguments$2(name, args) { const results = []; const chunks = args.trim().split(/\s*,\s*/g); let matches; for (const chunk of chunks) { if (!isNaN(chunk)) { results.push(Number(chunk)); } else if (matches = chunk.match(STRING_REGEX$2)) { results.push(matches[2].replace(ESCAPE_REGEX$2, (m, escape, chr) => escape ? unescape$2(escape) : chr)); } else { throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')")); } } return results; } function parseStyle$2(style) { STYLE_REGEX$2.lastIndex = 0; const results = []; let matches; while ((matches = STYLE_REGEX$2.exec(style)) !== null) { const name = matches[1]; if (matches[2]) { const args = parseArguments$2(name, matches[2]); results.push([name].concat(args)); } else { results.push([name]); } } return results; } function buildStyle$2(chalk, styles) { const enabled = {}; for (const layer of styles) { for (const style of layer.styles) { enabled[style[0]] = layer.inverse ? null : style.slice(1); } } let current = chalk; for (const styleName of Object.keys(enabled)) { if (Array.isArray(enabled[styleName])) { if (!(styleName in current)) { throw new Error("Unknown Chalk style: ".concat(styleName)); } if (enabled[styleName].length > 0) { current = current[styleName].apply(current, enabled[styleName]); } else { current = current[styleName]; } } } return current; } var templates$2 = (chalk, tmp) => { const styles = []; const chunks = []; let chunk = []; // eslint-disable-next-line max-params tmp.replace(TEMPLATE_REGEX$2, (m, escapeChar, inverse, style, close, chr) => { if (escapeChar) { chunk.push(unescape$2(escapeChar)); } else if (style) { const str = chunk.join(''); chunk = []; chunks.push(styles.length === 0 ? str : buildStyle$2(chalk, styles)(str)); styles.push({ inverse, styles: parseStyle$2(style) }); } else if (close) { if (styles.length === 0) { throw new Error('Found extraneous } in Chalk template literal'); } chunks.push(buildStyle$2(chalk, styles)(chunk.join(''))); chunk = []; styles.pop(); } else { chunk.push(chr); } }); chunks.push(chunk.join('')); if (styles.length > 0) { const errMsg = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)"); throw new Error(errMsg); } return chunks.join(''); }; var chalk$2 = createCommonjsModule(function (module) { const stdoutColor = supportsColor_1$2.stdout; const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such const skipModels = new Set(['gray']); const styles = Object.create(null); function applyOptions(obj, options) { options = options || {}; // Detect level if not set manually const scLevel = stdoutColor ? stdoutColor.level : 0; obj.level = options.level === undefined ? scLevel : options.level; obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; } function Chalk(options) { // We check for this.template here since calling `chalk.constructor()` // by itself will have a `this` of a previously constructed chalk object if (!this || !(this instanceof Chalk) || this.template) { const chalk = {}; applyOptions(chalk, options); chalk.template = function () { const args = [].slice.call(arguments); return chalkTag.apply(null, [chalk.template].concat(args)); }; Object.setPrototypeOf(chalk, Chalk.prototype); Object.setPrototypeOf(chalk.template, chalk); chalk.template.constructor = Chalk; return chalk.template; } applyOptions(this, options); } // Use bright blue on Windows as the normal blue color is illegible if (isSimpleWindowsTerm) { ansiStyles$2.blue.open = '\u001B[94m'; } for (const key of Object.keys(ansiStyles$2)) { ansiStyles$2[key].closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2[key].close), 'g'); styles[key] = { get() { const codes = ansiStyles$2[key]; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); } }; } styles.visible = { get() { return build.call(this, this._styles || [], true, 'visible'); } }; ansiStyles$2.color.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2.color.close), 'g'); for (const model of Object.keys(ansiStyles$2.color.ansi)) { if (skipModels.has(model)) { continue; } styles[model] = { get() { const level = this.level; return function () { const open = ansiStyles$2.color[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles$2.color.close, closeRe: ansiStyles$2.color.closeRe }; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); }; } }; } ansiStyles$2.bgColor.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2.bgColor.close), 'g'); for (const model of Object.keys(ansiStyles$2.bgColor.ansi)) { if (skipModels.has(model)) { continue; } const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); styles[bgModel] = { get() { const level = this.level; return function () { const open = ansiStyles$2.bgColor[levelMapping[level]][model].apply(null, arguments); const codes = { open, close: ansiStyles$2.bgColor.close, closeRe: ansiStyles$2.bgColor.closeRe }; return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); }; } }; } const proto = Object.defineProperties(() => {}, styles); function build(_styles, _empty, key) { const builder = function builder() { return applyStyle.apply(builder, arguments); }; builder._styles = _styles; builder._empty = _empty; const self = this; Object.defineProperty(builder, 'level', { enumerable: true, get() { return self.level; }, set(level) { self.level = level; } }); Object.defineProperty(builder, 'enabled', { enumerable: true, get() { return self.enabled; }, set(enabled) { self.enabled = enabled; } }); // See below for fix regarding invisible grey/dim combination on Windows builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is // no way to create a function with a different prototype builder.__proto__ = proto; // eslint-disable-line no-proto return builder; } function applyStyle() { // Support varags, but simply cast to string in case there's only one arg const args = arguments; const argsLen = args.length; let str = String(arguments[0]); if (argsLen === 0) { return ''; } if (argsLen > 1) { // Don't slice `arguments`, it prevents V8 optimizations for (let a = 1; a < argsLen; a++) { str += ' ' + args[a]; } } if (!this.enabled || this.level <= 0 || !str) { return this._empty ? '' : str; } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, // see https://github.com/chalk/chalk/issues/58 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. const originalDim = ansiStyles$2.dim.open; if (isSimpleWindowsTerm && this.hasGrey) { ansiStyles$2.dim.open = ''; } for (const code of this._styles.slice().reverse()) { // Replace any instances already present with a re-opening code // otherwise only the part of the string until said closing code // will be colored, and the rest will simply be 'plain'. str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen // after next line to fix a bleed issue on macOS // https://github.com/chalk/chalk/pull/92 str = str.replace(/\r?\n/g, "".concat(code.close, "$&").concat(code.open)); } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue ansiStyles$2.dim.open = originalDim; return str; } function chalkTag(chalk, strings) { if (!Array.isArray(strings)) { // If chalk() was called by itself or with a string, // return the string itself as a string. return [].slice.call(arguments, 1).join(' '); } const args = [].slice.call(arguments, 2); const parts = [strings.raw[0]]; for (let i = 1; i < strings.length; i++) { parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); parts.push(String(strings.raw[i])); } return templates$2(chalk, parts.join('')); } Object.defineProperties(Chalk.prototype, styles); module.exports = Chalk(); // eslint-disable-line new-cap module.exports.supportsColor = stdoutColor; module.exports.default = module.exports; // For TypeScript }); var chalk_1$1 = chalk$2.supportsColor; var lib$1 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.shouldHighlight = shouldHighlight; exports.getChalk = getChalk; exports.default = highlight; var _jsTokens = _interopRequireWildcard(jsTokens); var _esutils = _interopRequireDefault(utils$1); var _chalk = _interopRequireDefault(chalk$2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function getDefs(chalk) { return { keyword: chalk.cyan, capitalized: chalk.yellow, jsx_tag: chalk.yellow, punctuator: chalk.yellow, number: chalk.magenta, string: chalk.green, regex: chalk.magenta, comment: chalk.grey, invalid: chalk.white.bgRed.bold }; } const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; const JSX_TAG = /^[a-z][\w-]*$/i; const BRACKET = /^[()[\]{}]$/; function getTokenType(match) { const [offset, text] = match.slice(-2); const token = (0, _jsTokens.matchToToken)(match); if (token.type === "name") { if (_esutils.default.keyword.isReservedWordES6(token.value)) { return "keyword"; } if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == " colorize(str)).join("\n"); } else { return args[0]; } }); } function shouldHighlight(options) { return _chalk.default.supportsColor || options.forceColor; } function getChalk(options) { let chalk = _chalk.default; if (options.forceColor) { chalk = new _chalk.default.constructor({ enabled: true, level: 1 }); } return chalk; } function highlight(code, options = {}) { if (shouldHighlight(options)) { const chalk = getChalk(options); const defs = getDefs(chalk); return highlightTokens(defs, code); } else { return code; } } }); unwrapExports(lib$1); var lib_1 = lib$1.shouldHighlight; var lib_2 = lib$1.getChalk; var lib$2 = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, "__esModule", { value: true }); exports.codeFrameColumns = codeFrameColumns; exports.default = _default; var _highlight = _interopRequireWildcard(lib$1); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } let deprecationWarningShown = false; function getDefs(chalk) { return { gutter: chalk.grey, marker: chalk.red.bold, message: chalk.red.bold }; } const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; function getMarkerLines(loc, source, opts) { const startLoc = Object.assign({ column: 0, line: -1 }, loc.start); const endLoc = Object.assign({}, startLoc, {}, loc.end); const { linesAbove = 2, linesBelow = 3 } = opts || {}; const startLine = startLoc.line; const startColumn = startLoc.column; const endLine = endLoc.line; const endColumn = endLoc.column; let start = Math.max(startLine - (linesAbove + 1), 0); let end = Math.min(source.length, endLine + linesBelow); if (startLine === -1) { start = 0; } if (endLine === -1) { end = source.length; } const lineDiff = endLine - startLine; const markerLines = {}; if (lineDiff) { for (let i = 0; i <= lineDiff; i++) { const lineNumber = i + startLine; if (!startColumn) { markerLines[lineNumber] = true; } else if (i === 0) { const sourceLength = source[lineNumber - 1].length; markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; } else if (i === lineDiff) { markerLines[lineNumber] = [0, endColumn]; } else { const sourceLength = source[lineNumber - i].length; markerLines[lineNumber] = [0, sourceLength]; } } } else { if (startColumn === endColumn) { if (startColumn) { markerLines[startLine] = [startColumn, 0]; } else { markerLines[startLine] = true; } } else { markerLines[startLine] = [startColumn, endColumn - startColumn]; } } return { start, end, markerLines }; } function codeFrameColumns(rawLines, loc, opts = {}) { const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts); const chalk = (0, _highlight.getChalk)(opts); const defs = getDefs(chalk); const maybeHighlight = (chalkFn, string) => { return highlighted ? chalkFn(string) : string; }; const lines = rawLines.split(NEWLINE); const { start, end, markerLines } = getMarkerLines(loc, lines, opts); const hasColumns = loc.start && typeof loc.start.column === "number"; const numberMaxWidth = String(end).length; const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => { const number = start + 1 + index; const paddedNumber = " ".concat(number).slice(-numberMaxWidth); const gutter = " ".concat(paddedNumber, " | "); const hasMarker = markerLines[number]; const lastMarkerLine = !markerLines[number + 1]; if (hasMarker) { let markerLine = ""; if (Array.isArray(hasMarker)) { const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); const numberOfMarkers = hasMarker[1] || 1; markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); if (lastMarkerLine && opts.message) { markerLine += " " + maybeHighlight(defs.message, opts.message); } } return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); } else { return " ".concat(maybeHighlight(defs.gutter, gutter)).concat(line); } }).join("\n"); if (opts.message && !hasColumns) { frame = "".concat(" ".repeat(numberMaxWidth + 1)).concat(opts.message, "\n").concat(frame); } if (highlighted) { return chalk.reset(frame); } else { return frame; } } function _default(rawLines, lineNumber, colNumber, opts = {}) { if (!deprecationWarningShown) { deprecationWarningShown = true; const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; if (process.emitWarning) { process.emitWarning(message, "DeprecationWarning"); } else { const deprecationError = new Error(message); deprecationError.name = "DeprecationWarning"; console.warn(new Error(message)); } } colNumber = Math.max(colNumber, 0); const location = { start: { column: colNumber, line: lineNumber } }; return codeFrameColumns(rawLines, location, opts); } }); unwrapExports(lib$2); var lib_1$1 = lib$2.codeFrameColumns; const { ConfigError: ConfigError$1 } = errors; const { locStart: locStart$1, locEnd: locEnd$1 } = loc; // Use defineProperties()/getOwnPropertyDescriptor() to prevent // triggering the parsers getters. const ownNames = Object.getOwnPropertyNames; const ownDescriptor = Object.getOwnPropertyDescriptor; function getParsers(options) { const parsers = {}; for (const plugin of options.plugins) { if (!plugin.parsers) { continue; } for (const name of ownNames(plugin.parsers)) { Object.defineProperty(parsers, name, ownDescriptor(plugin.parsers, name)); } } return parsers; } function resolveParser(opts, parsers) { parsers = parsers || getParsers(opts); if (typeof opts.parser === "function") { // Custom parser API always works with JavaScript. return { parse: opts.parser, astFormat: "estree", locStart: locStart$1, locEnd: locEnd$1 }; } if (typeof opts.parser === "string") { if (Object.prototype.hasOwnProperty.call(parsers, opts.parser)) { return parsers[opts.parser]; } /* istanbul ignore next */ { throw new ConfigError$1("Couldn't resolve parser \"".concat(opts.parser, "\". Parsers must be explicitly added to the standalone bundle.")); } } } function parse(text, opts) { const parsers = getParsers(opts); // Create a new object {parserName: parseFn}. Uses defineProperty() to only call // the parsers getters when actually calling the parser `parse` function. const parsersForCustomParserApi = Object.keys(parsers).reduce((object, parserName) => Object.defineProperty(object, parserName, { enumerable: true, get() { return parsers[parserName].parse; } }), {}); const parser = resolveParser(opts, parsers); try { if (parser.preprocess) { text = parser.preprocess(text, opts); } return { text, ast: parser.parse(text, parsersForCustomParserApi, opts) }; } catch (error) { const { loc } = error; if (loc) { const codeFrame = lib$2; error.codeFrame = codeFrame.codeFrameColumns(text, loc, { highlightCode: true }); error.message += "\n" + error.codeFrame; throw error; } /* istanbul ignore next */ throw error.stack; } } var parser = { parse, resolveParser }; const { UndefinedParserError: UndefinedParserError$1 } = errors; const { getSupportInfo: getSupportInfo$1 } = support; const { resolveParser: resolveParser$1 } = parser; const hiddenDefaults = { astFormat: "estree", printer: {}, originalText: undefined, locStart: null, locEnd: null }; // Copy options and fill in default values. function normalize$1(options, opts) { opts = opts || {}; const rawOptions = Object.assign({}, options); const supportOptions = getSupportInfo$1({ plugins: options.plugins, showUnreleased: true, showDeprecated: true }).options; const defaults = Object.assign({}, hiddenDefaults, {}, fromPairs_1(supportOptions.filter(optionInfo => optionInfo.default !== undefined).map(option => [option.name, option.default]))); if (!rawOptions.parser) { if (!rawOptions.filepath) { const logger = opts.logger || console; logger.warn("No parser and no filepath given, using 'babel' the parser now " + "but this will throw an error in the future. " + "Please specify a parser or a filepath so one can be inferred."); rawOptions.parser = "babel"; } else { rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins); if (!rawOptions.parser) { throw new UndefinedParserError$1("No parser could be inferred for file: ".concat(rawOptions.filepath)); } } } const parser = resolveParser$1(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(x => x.name === "parser")], { passThrough: true, logger: false })); rawOptions.astFormat = parser.astFormat; rawOptions.locEnd = parser.locEnd; rawOptions.locStart = parser.locStart; const plugin = getPlugin(rawOptions); rawOptions.printer = plugin.printers[rawOptions.astFormat]; const pluginDefaults = supportOptions.filter(optionInfo => optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name] !== undefined).reduce((reduced, optionInfo) => Object.assign(reduced, { [optionInfo.name]: optionInfo.pluginDefaults[plugin.name] }), {}); const mixedDefaults = Object.assign({}, defaults, {}, pluginDefaults); Object.keys(mixedDefaults).forEach(k => { if (rawOptions[k] == null) { rawOptions[k] = mixedDefaults[k]; } }); if (rawOptions.parser === "json") { rawOptions.trailingComma = "none"; } return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({ passThrough: Object.keys(hiddenDefaults) }, opts)); } function getPlugin(options) { const { astFormat } = options; if (!astFormat) { throw new Error("getPlugin() requires astFormat to be set"); } const printerPlugin = options.plugins.find(plugin => plugin.printers && plugin.printers[astFormat]); if (!printerPlugin) { throw new Error("Couldn't find plugin for AST format \"".concat(astFormat, "\"")); } return printerPlugin; } function getInterpreter(filepath) { if (typeof filepath !== "string") { return ""; } let fd; try { fd = fs.openSync(filepath, "r"); } catch (err) { // istanbul ignore next return ""; } try { const liner = new readlines(fd); const firstLine = liner.next().toString("utf8"); // #!/bin/env node, #!/usr/bin/env node const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/); if (m1) { return m1[1]; } // #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node const m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/); if (m2) { return m2[1]; } return ""; } catch (err) { // There are some weird cases where paths are missing, causing Jest // failures. It's unclear what these correspond to in the real world. return ""; } finally { try { // There are some weird cases where paths are missing, causing Jest // failures. It's unclear what these correspond to in the real world. fs.closeSync(fd); } catch (err) {// nop } } } function inferParser(filepath, plugins) { const filename = path.basename(filepath).toLowerCase(); const languages = getSupportInfo$1({ plugins }).languages.filter(language => language.since !== null); // If the file has no extension, we can try to infer the language from the // interpreter in the shebang line, if any; but since this requires FS access, // do it last. let language = languages.find(language => language.extensions && language.extensions.some(extension => filename.endsWith(extension)) || language.filenames && language.filenames.find(name => name.toLowerCase() === filename)); if (!language && !filename.includes(".")) { const interpreter = getInterpreter(filepath); language = languages.find(language => language.interpreters && language.interpreters.includes(interpreter)); } return language && language.parsers[0]; } var options$1 = { normalize: normalize$1, hiddenDefaults, inferParser }; function massageAST(ast, options, parent) { if (Array.isArray(ast)) { return ast.map(e => massageAST(e, options, parent)).filter(Boolean); } if (!ast || typeof ast !== "object") { return ast; } const newObj = {}; for (const key of Object.keys(ast)) { if (typeof ast[key] !== "function") { newObj[key] = massageAST(ast[key], options, ast); } } if (options.printer.massageAstNode) { const result = options.printer.massageAstNode(ast, newObj, parent); if (result === null) { return undefined; } if (result) { return result; } } return newObj; } var massageAst = massageAST; function assert() {} assert.ok = function () {}; assert.strictEqual = function () {}; /** * @param {Doc[]} parts * @returns Doc */ function concat(parts) { // access the internals of a document directly. // if(parts.length === 1) { // // If it's a single document, no need to concat it. // return parts[0]; // } return { type: "concat", parts }; } /** * @param {Doc} contents * @returns Doc */ function indent(contents) { return { type: "indent", contents }; } /** * @param {number} n * @param {Doc} contents * @returns Doc */ function align(n, contents) { return { type: "align", contents, n }; } /** * @param {Doc} contents * @param {object} [opts] - TBD ??? * @returns Doc */ function group(contents, opts) { opts = opts || {}; return { type: "group", id: opts.id, contents, break: !!opts.shouldBreak, expandedStates: opts.expandedStates }; } /** * @param {Doc} contents * @returns Doc */ function dedentToRoot(contents) { return align(-Infinity, contents); } /** * @param {Doc} contents * @returns Doc */ function markAsRoot(contents) { // @ts-ignore - TBD ???: return align({ type: "root" }, contents); } /** * @param {Doc} contents * @returns Doc */ function dedent(contents) { return align(-1, contents); } /** * @param {Doc[]} states * @param {object} [opts] - TBD ??? * @returns Doc */ function conditionalGroup(states, opts) { return group(states[0], Object.assign({}, opts, { expandedStates: states })); } /** * @param {Doc[]} parts * @returns Doc */ function fill(parts) { return { type: "fill", parts }; } /** * @param {Doc} [breakContents] * @param {Doc} [flatContents] * @param {object} [opts] - TBD ??? * @returns Doc */ function ifBreak(breakContents, flatContents, opts) { opts = opts || {}; return { type: "if-break", breakContents, flatContents, groupId: opts.groupId }; } /** * @param {Doc} contents * @returns Doc */ function lineSuffix(contents) { return { type: "line-suffix", contents }; } const lineSuffixBoundary = { type: "line-suffix-boundary" }; const breakParent = { type: "break-parent" }; const trim = { type: "trim" }; const line = { type: "line" }; const softline = { type: "line", soft: true }; const hardline = concat([{ type: "line", hard: true }, breakParent]); const literalline = concat([{ type: "line", hard: true, literal: true }, breakParent]); const cursor = { type: "cursor", placeholder: Symbol("cursor") }; /** * @param {Doc} sep * @param {Doc[]} arr * @returns Doc */ function join(sep, arr) { const res = []; for (let i = 0; i < arr.length; i++) { if (i !== 0) { res.push(sep); } res.push(arr[i]); } return concat(res); } /** * @param {Doc} doc * @param {number} size * @param {number} tabWidth */ function addAlignmentToDoc(doc, size, tabWidth) { let aligned = doc; if (size > 0) { // Use indent to add tabs for all the levels of tabs we need for (let i = 0; i < Math.floor(size / tabWidth); ++i) { aligned = indent(aligned); } // Use align for all the spaces that are needed aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current // indentation, so we use -Infinity to reset the indentation to 0 aligned = align(-Infinity, aligned); } return aligned; } var docBuilders = { concat, join, line, softline, hardline, literalline, group, conditionalGroup, fill, lineSuffix, lineSuffixBoundary, cursor, breakParent, ifBreak, trim, indent, align, addAlignmentToDoc, markAsRoot, dedentToRoot, dedent }; var ansiRegex = ({ onlyFirst = false } = {}) => { const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|'); return new RegExp(pattern, onlyFirst ? undefined : 'g'); }; var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; /* eslint-disable yoda */ const isFullwidthCodePoint = codePoint => { if (Number.isNaN(codePoint)) { return false; } // Code points are derived from: // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt if (codePoint >= 0x1100 && (codePoint <= 0x115F || // Hangul Jamo codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET // CJK Radicals Supplement .. Enclosed CJK Letters and Months 0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A 0x3250 <= codePoint && codePoint <= 0x4DBF || // CJK Unified Ideographs .. Yi Radicals 0x4E00 <= codePoint && codePoint <= 0xA4C6 || // Hangul Jamo Extended-A 0xA960 <= codePoint && codePoint <= 0xA97C || // Hangul Syllables 0xAC00 <= codePoint && codePoint <= 0xD7A3 || // CJK Compatibility Ideographs 0xF900 <= codePoint && codePoint <= 0xFAFF || // Vertical Forms 0xFE10 <= codePoint && codePoint <= 0xFE19 || // CJK Compatibility Forms .. Small Form Variants 0xFE30 <= codePoint && codePoint <= 0xFE6B || // Halfwidth and Fullwidth Forms 0xFF01 <= codePoint && codePoint <= 0xFF60 || 0xFFE0 <= codePoint && codePoint <= 0xFFE6 || // Kana Supplement 0x1B000 <= codePoint && codePoint <= 0x1B001 || // Enclosed Ideographic Supplement 0x1F200 <= codePoint && codePoint <= 0x1F251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane 0x20000 <= codePoint && codePoint <= 0x3FFFD)) { return true; } return false; }; var isFullwidthCodePoint_1 = isFullwidthCodePoint; var default_1$1 = isFullwidthCodePoint; isFullwidthCodePoint_1.default = default_1$1; var emojiRegex = function emojiRegex() { // https://mths.be/emoji return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; }; const stringWidth = string => { string = string.replace(emojiRegex(), ' '); if (typeof string !== 'string' || string.length === 0) { return 0; } string = stripAnsi(string); let width = 0; for (let i = 0; i < string.length; i++) { const code = string.codePointAt(i); // Ignore control characters if (code <= 0x1F || code >= 0x7F && code <= 0x9F) { continue; } // Ignore combining characters if (code >= 0x300 && code <= 0x36F) { continue; } // Surrogates if (code > 0xFFFF) { i++; } width += isFullwidthCodePoint_1(code) ? 2 : 1; } return width; }; var stringWidth_1 = stringWidth; // TODO: remove this in the next major version var default_1$2 = stringWidth; stringWidth_1.default = default_1$2; const matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g; var escapeStringRegexp$2 = string => { if (typeof string !== 'string') { throw new TypeError('Expected a string'); } return string.replace(matchOperatorsRegex, '\\$&'); }; const notAsciiRegex = /[^\x20-\x7F]/; function getPenultimate(arr) { if (arr.length > 1) { return arr[arr.length - 2]; } return null; } /** * @typedef {{backwards?: boolean}} SkipOptions */ /** * @param {string | RegExp} chars * @returns {(text: string, index: number | false, opts?: SkipOptions) => number | false} */ function skip(chars) { return (text, index, opts) => { const backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having // to check for failures (did someone say monads?). if (index === false) { return false; } const { length } = text; let cursor = index; while (cursor >= 0 && cursor < length) { const c = text.charAt(cursor); if (chars instanceof RegExp) { if (!chars.test(c)) { return cursor; } } else if (!chars.includes(c)) { return cursor; } backwards ? cursor-- : cursor++; } if (cursor === -1 || cursor === length) { // If we reached the beginning or end of the file, return the // out-of-bounds cursor. It's up to the caller to handle this // correctly. We don't want to indicate `false` though if it // actually skipped valid characters. return cursor; } return false; }; } /** * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} */ const skipWhitespace = skip(/\s/); /** * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} */ const skipSpaces = skip(" \t"); /** * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} */ const skipToLineEnd = skip(",; \t"); /** * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} */ const skipEverythingButNewLine = skip(/[^\r\n]/); /** * @param {string} text * @param {number | false} index * @returns {number | false} */ function skipInlineComment(text, index) { if (index === false) { return false; } if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") { for (let i = index + 2; i < text.length; ++i) { if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") { return i + 2; } } } return index; } /** * @param {string} text * @param {number | false} index * @returns {number | false} */ function skipTrailingComment(text, index) { if (index === false) { return false; } if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") { return skipEverythingButNewLine(text, index); } return index; } // This one doesn't use the above helper function because it wants to // test \r\n in order and `skip` doesn't support ordering and we only // want to skip one newline. It's simple to implement. /** * @param {string} text * @param {number | false} index * @param {SkipOptions=} opts * @returns {number | false} */ function skipNewline(text, index, opts) { const backwards = opts && opts.backwards; if (index === false) { return false; } const atIndex = text.charAt(index); if (backwards) { if (text.charAt(index - 1) === "\r" && atIndex === "\n") { return index - 2; } if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") { return index - 1; } } else { if (atIndex === "\r" && text.charAt(index + 1) === "\n") { return index + 2; } if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") { return index + 1; } } return index; } /** * @param {string} text * @param {number} index * @param {SkipOptions=} opts * @returns {boolean} */ function hasNewline(text, index, opts) { opts = opts || {}; const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts); const idx2 = skipNewline(text, idx, opts); return idx !== idx2; } /** * @param {string} text * @param {number} start * @param {number} end * @returns {boolean} */ function hasNewlineInRange(text, start, end) { for (let i = start; i < end; ++i) { if (text.charAt(i) === "\n") { return true; } } return false; } // Note: this function doesn't ignore leading comments unlike isNextLineEmpty /** * @template N * @param {string} text * @param {N} node * @param {(node: N) => number} locStart */ function isPreviousLineEmpty(text, node, locStart) { /** @type {number | false} */ let idx = locStart(node) - 1; idx = skipSpaces(text, idx, { backwards: true }); idx = skipNewline(text, idx, { backwards: true }); idx = skipSpaces(text, idx, { backwards: true }); const idx2 = skipNewline(text, idx, { backwards: true }); return idx !== idx2; } /** * @param {string} text * @param {number} index * @returns {boolean} */ function isNextLineEmptyAfterIndex(text, index) { /** @type {number | false} */ let oldIdx = null; /** @type {number | false} */ let idx = index; while (idx !== oldIdx) { // We need to skip all the potential trailing inline comments oldIdx = idx; idx = skipToLineEnd(text, idx); idx = skipInlineComment(text, idx); idx = skipSpaces(text, idx); } idx = skipTrailingComment(text, idx); idx = skipNewline(text, idx); return idx !== false && hasNewline(text, idx); } /** * @template N * @param {string} text * @param {N} node * @param {(node: N) => number} locEnd * @returns {boolean} */ function isNextLineEmpty(text, node, locEnd) { return isNextLineEmptyAfterIndex(text, locEnd(node)); } /** * @param {string} text * @param {number} idx * @returns {number | false} */ function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) { /** @type {number | false} */ let oldIdx = null; /** @type {number | false} */ let nextIdx = idx; while (nextIdx !== oldIdx) { oldIdx = nextIdx; nextIdx = skipSpaces(text, nextIdx); nextIdx = skipInlineComment(text, nextIdx); nextIdx = skipTrailingComment(text, nextIdx); nextIdx = skipNewline(text, nextIdx); } return nextIdx; } /** * @template N * @param {string} text * @param {N} node * @param {(node: N) => number} locEnd * @returns {number | false} */ function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) { return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node)); } /** * @template N * @param {string} text * @param {N} node * @param {(node: N) => number} locEnd * @returns {string} */ function getNextNonSpaceNonCommentCharacter(text, node, locEnd) { return text.charAt( // @ts-ignore => TBD: can return false, should we define a fallback? getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd)); } /** * @param {string} text * @param {number} index * @param {SkipOptions=} opts * @returns {boolean} */ function hasSpaces(text, index, opts) { opts = opts || {}; const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts); return idx !== index; } /** * @param {{range?: [number, number], start?: number}} node * @param {number} index */ function setLocStart(node, index) { if (node.range) { node.range[0] = index; } else { node.start = index; } } /** * @param {{range?: [number, number], end?: number}} node * @param {number} index */ function setLocEnd(node, index) { if (node.range) { node.range[1] = index; } else { node.end = index; } } const PRECEDENCE = {}; [["|>"], ["??"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach((tier, i) => { tier.forEach(op => { PRECEDENCE[op] = i; }); }); function getPrecedence(op) { return PRECEDENCE[op]; } const equalityOperators = { "==": true, "!=": true, "===": true, "!==": true }; const multiplicativeOperators = { "*": true, "/": true, "%": true }; const bitshiftOperators = { ">>": true, ">>>": true, "<<": true }; function shouldFlatten(parentOp, nodeOp) { if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) { return false; } // ** is right-associative // x ** y ** z --> x ** (y ** z) if (parentOp === "**") { return false; } // x == y == z --> (x == y) == z if (equalityOperators[parentOp] && equalityOperators[nodeOp]) { return false; } // x * y % z --> (x * y) % z if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) { return false; } // x * y / z --> (x * y) / z // x / y * z --> (x / y) * z if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) { return false; } // x << y << z --> (x << y) << z if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) { return false; } return true; } function isBitwiseOperator(operator) { return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&"; } // Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr // holds) `function`, `class`, or `do {}`. Will be overzealous if there's // already necessary grouping parentheses. function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) { node = getLeftMost(node); switch (node.type) { case "FunctionExpression": case "ClassExpression": case "DoExpression": return forbidFunctionClassAndDoExpr; case "ObjectExpression": return true; case "MemberExpression": case "OptionalMemberExpression": return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr); case "TaggedTemplateExpression": if (node.tag.type === "FunctionExpression") { // IIFEs are always already parenthesized return false; } return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr); case "CallExpression": case "OptionalCallExpression": if (node.callee.type === "FunctionExpression") { // IIFEs are always already parenthesized return false; } return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr); case "ConditionalExpression": return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr); case "UpdateExpression": return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr); case "BindExpression": return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr); case "SequenceExpression": return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr); case "TSAsExpression": return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr); default: return false; } } function getLeftMost(node) { if (node.left) { return getLeftMost(node.left); } return node; } /** * @param {string} value * @param {number} tabWidth * @param {number=} startIndex * @returns {number} */ function getAlignmentSize(value, tabWidth, startIndex) { startIndex = startIndex || 0; let size = 0; for (let i = startIndex; i < value.length; ++i) { if (value[i] === "\t") { // Tabs behave in a way that they are aligned to the nearest // multiple of tabWidth: // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4 // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ... size = size + tabWidth - size % tabWidth; } else { size++; } } return size; } /** * @param {string} value * @param {number} tabWidth * @returns {number} */ function getIndentSize(value, tabWidth) { const lastNewlineIndex = value.lastIndexOf("\n"); if (lastNewlineIndex === -1) { return 0; } return getAlignmentSize( // All the leading whitespaces value.slice(lastNewlineIndex + 1).match(/^[ \t]*/)[0], tabWidth); } /** * @typedef {'"' | "'"} Quote */ /** * * @param {string} raw * @param {Quote} preferredQuote * @returns {Quote} */ function getPreferredQuote(raw, preferredQuote) { // `rawContent` is the string exactly like it appeared in the input source // code, without its enclosing quotes. const rawContent = raw.slice(1, -1); /** @type {{ quote: '"', regex: RegExp }} */ const double = { quote: '"', regex: /"/g }; /** @type {{ quote: "'", regex: RegExp }} */ const single = { quote: "'", regex: /'/g }; const preferred = preferredQuote === "'" ? single : double; const alternate = preferred === single ? double : single; let result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing // the string, we might want to enclose with the alternate quote instead, to // minimize the number of escaped quotes. if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) { const numPreferredQuotes = (rawContent.match(preferred.regex) || []).length; const numAlternateQuotes = (rawContent.match(alternate.regex) || []).length; result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote; } return result; } function printString(raw, options, isDirectiveLiteral) { // `rawContent` is the string exactly like it appeared in the input source // code, without its enclosing quotes. const rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap // the quotes on a DirectiveLiteral. const canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'"); /** @type {Quote} */ const enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't // change the escape sequences they use. // See https://github.com/prettier/prettier/issues/1555 // and https://tc39.github.io/ecma262/#directive-prologue if (isDirectiveLiteral) { if (canChangeDirectiveQuotes) { return enclosingQuote + rawContent + enclosingQuote; } return raw; } // It might sound unnecessary to use `makeString` even if the string already // is enclosed with `enclosingQuote`, but it isn't. The string could contain // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes // sure that we consistently output the minimum amount of escaped quotes. return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.embeddedInHtml)); } /** * @param {string} rawContent * @param {Quote} enclosingQuote * @param {boolean=} unescapeUnnecessaryEscapes * @returns {string} */ function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) { const otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double). const regex = /\\([\s\S])|(['"])/g; // Escape and unescape single and double quotes as needed to be able to // enclose `rawContent` with `enclosingQuote`. const newContent = rawContent.replace(regex, (match, escaped, quote) => { // If we matched an escape, and the escaped character is a quote of the // other type than we intend to enclose the string with, there's no need for // it to be escaped, so return it _without_ the backslash. if (escaped === otherQuote) { return escaped; } // If we matched an unescaped quote and it is of the _same_ type as we // intend to enclose the string with, it must be escaped, so return it with // a backslash. if (quote === enclosingQuote) { return "\\" + quote; } if (quote) { return quote; } // Unescape any unnecessarily escaped character. // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27 return unescapeUnnecessaryEscapes && /^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(escaped) ? escaped : "\\" + escaped; }); return enclosingQuote + newContent + enclosingQuote; } function printNumber(rawNumber) { return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation. .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0). .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit. .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes. .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot. .replace(/\.(?=e|$)/, ""); } /** * @param {string} str * @param {string} target * @returns {number} */ function getMaxContinuousCount(str, target) { const results = str.match(new RegExp("(".concat(escapeStringRegexp$2(target), ")+"), "g")); if (results === null) { return 0; } return results.reduce((maxCount, result) => Math.max(maxCount, result.length / target.length), 0); } function getMinNotPresentContinuousCount(str, target) { const matches = str.match(new RegExp("(".concat(escapeStringRegexp$2(target), ")+"), "g")); if (matches === null) { return 0; } const countPresent = new Map(); let max = 0; for (const match of matches) { const count = match.length / target.length; countPresent.set(count, true); if (count > max) { max = count; } } for (let i = 1; i < max; i++) { if (!countPresent.get(i)) { return i; } } return max + 1; } /** * @param {string} text * @returns {number} */ function getStringWidth(text) { if (!text) { return 0; } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width` if (!notAsciiRegex.test(text)) { return text.length; } return stringWidth_1(text); } function hasIgnoreComment(path) { const node = path.getValue(); return hasNodeIgnoreComment(node); } function hasNodeIgnoreComment(node) { return node && (node.comments && node.comments.length > 0 && node.comments.some(comment => isNodeIgnoreComment(comment) && !comment.unignore) || node.prettierIgnore); } function isNodeIgnoreComment(comment) { return comment.value.trim() === "prettier-ignore"; } function addCommentHelper(node, comment) { const comments = node.comments || (node.comments = []); comments.push(comment); comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment // We already "print" it via the raw text, we don't need to re-print it as a // comment if (node.type === "JSXText") { comment.printed = true; } } function addLeadingComment(node, comment) { comment.leading = true; comment.trailing = false; addCommentHelper(node, comment); } function addDanglingComment(node, comment) { comment.leading = false; comment.trailing = false; addCommentHelper(node, comment); } function addTrailingComment(node, comment) { comment.leading = false; comment.trailing = true; addCommentHelper(node, comment); } function isWithinParentArrayProperty(path, propertyName) { const node = path.getValue(); const parent = path.getParentNode(); if (parent == null) { return false; } if (!Array.isArray(parent[propertyName])) { return false; } const key = path.getName(); return parent[propertyName][key] === node; } function replaceEndOfLineWith(text, replacement) { const parts = []; for (const part of text.split("\n")) { if (parts.length !== 0) { parts.push(replacement); } parts.push(part); } return parts; } var util$1 = { replaceEndOfLineWith, getStringWidth, getMaxContinuousCount, getMinNotPresentContinuousCount, getPrecedence, shouldFlatten, isBitwiseOperator, getPenultimate, getLast, getNextNonSpaceNonCommentCharacterIndexWithStartIndex, getNextNonSpaceNonCommentCharacterIndex, getNextNonSpaceNonCommentCharacter, skip, skipWhitespace, skipSpaces, skipToLineEnd, skipEverythingButNewLine, skipInlineComment, skipTrailingComment, skipNewline, isNextLineEmptyAfterIndex, isNextLineEmpty, isPreviousLineEmpty, hasNewline, hasNewlineInRange, hasSpaces, setLocStart, setLocEnd, startsWithNoLookaheadToken, getAlignmentSize, getIndentSize, getPreferredQuote, printString, printNumber, hasIgnoreComment, hasNodeIgnoreComment, isNodeIgnoreComment, makeString, addLeadingComment, addDanglingComment, addTrailingComment, isWithinParentArrayProperty }; function guessEndOfLine(text) { const index = text.indexOf("\r"); if (index >= 0) { return text.charAt(index + 1) === "\n" ? "crlf" : "cr"; } return "lf"; } function convertEndOfLineToChars(value) { switch (value) { case "cr": return "\r"; case "crlf": return "\r\n"; default: return "\n"; } } var endOfLine = { guessEndOfLine, convertEndOfLineToChars }; const { getStringWidth: getStringWidth$1 } = util$1; const { convertEndOfLineToChars: convertEndOfLineToChars$1 } = endOfLine; const { concat: concat$1, fill: fill$1, cursor: cursor$1 } = docBuilders; /** @type {Record} */ let groupModeMap; const MODE_BREAK = 1; const MODE_FLAT = 2; function rootIndent() { return { value: "", length: 0, queue: [] }; } function makeIndent(ind, options) { return generateInd(ind, { type: "indent" }, options); } function makeAlign(ind, n, options) { return n === -Infinity ? ind.root || rootIndent() : n < 0 ? generateInd(ind, { type: "dedent" }, options) : !n ? ind : n.type === "root" ? Object.assign({}, ind, { root: ind }) : typeof n === "string" ? generateInd(ind, { type: "stringAlign", n }, options) : generateInd(ind, { type: "numberAlign", n }, options); } function generateInd(ind, newPart, options) { const queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart); let value = ""; let length = 0; let lastTabs = 0; let lastSpaces = 0; for (const part of queue) { switch (part.type) { case "indent": flush(); if (options.useTabs) { addTabs(1); } else { addSpaces(options.tabWidth); } break; case "stringAlign": flush(); value += part.n; length += part.n.length; break; case "numberAlign": lastTabs += 1; lastSpaces += part.n; break; /* istanbul ignore next */ default: throw new Error("Unexpected type '".concat(part.type, "'")); } } flushSpaces(); return Object.assign({}, ind, { value, length, queue }); function addTabs(count) { value += "\t".repeat(count); length += options.tabWidth * count; } function addSpaces(count) { value += " ".repeat(count); length += count; } function flush() { if (options.useTabs) { flushTabs(); } else { flushSpaces(); } } function flushTabs() { if (lastTabs > 0) { addTabs(lastTabs); } resetLast(); } function flushSpaces() { if (lastSpaces > 0) { addSpaces(lastSpaces); } resetLast(); } function resetLast() { lastTabs = 0; lastSpaces = 0; } } function trim$1(out) { if (out.length === 0) { return 0; } let trimCount = 0; // Trim whitespace at the end of line while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[ \t]*$/)) { trimCount += out.pop().length; } if (out.length && typeof out[out.length - 1] === "string") { const trimmed = out[out.length - 1].replace(/[ \t]*$/, ""); trimCount += out[out.length - 1].length - trimmed.length; out[out.length - 1] = trimmed; } return trimCount; } function fits(next, restCommands, width, options, mustBeFlat) { let restIdx = restCommands.length; const cmds = [next]; // `out` is only used for width counting because `trim` requires to look // backwards for space characters. const out = []; while (width >= 0) { if (cmds.length === 0) { if (restIdx === 0) { return true; } cmds.push(restCommands[restIdx - 1]); restIdx--; continue; } const [ind, mode, doc] = cmds.pop(); if (typeof doc === "string") { out.push(doc); width -= getStringWidth$1(doc); } else { switch (doc.type) { case "concat": for (let i = doc.parts.length - 1; i >= 0; i--) { cmds.push([ind, mode, doc.parts[i]]); } break; case "indent": cmds.push([makeIndent(ind, options), mode, doc.contents]); break; case "align": cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]); break; case "trim": width += trim$1(out); break; case "group": if (mustBeFlat && doc.break) { return false; } cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]); if (doc.id) { groupModeMap[doc.id] = cmds[cmds.length - 1][1]; } break; case "fill": for (let i = doc.parts.length - 1; i >= 0; i--) { cmds.push([ind, mode, doc.parts[i]]); } break; case "if-break": { const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode; if (groupMode === MODE_BREAK) { if (doc.breakContents) { cmds.push([ind, mode, doc.breakContents]); } } if (groupMode === MODE_FLAT) { if (doc.flatContents) { cmds.push([ind, mode, doc.flatContents]); } } break; } case "line": switch (mode) { // fallthrough case MODE_FLAT: if (!doc.hard) { if (!doc.soft) { out.push(" "); width -= 1; } break; } return true; case MODE_BREAK: return true; } break; } } } return false; } function printDocToString(doc, options) { groupModeMap = {}; const width = options.printWidth; const newLine = convertEndOfLineToChars$1(options.endOfLine); let pos = 0; // cmds is basically a stack. We've turned a recursive call into a // while loop which is much faster. The while loop below adds new // cmds to the array instead of recursively calling `print`. const cmds = [[rootIndent(), MODE_BREAK, doc]]; const out = []; let shouldRemeasure = false; let lineSuffix = []; while (cmds.length !== 0) { const [ind, mode, doc] = cmds.pop(); if (typeof doc === "string") { const formatted = newLine !== "\n" && doc.includes("\n") ? doc.replace(/\n/g, newLine) : doc; out.push(formatted); pos += getStringWidth$1(formatted); } else { switch (doc.type) { case "cursor": out.push(cursor$1.placeholder); break; case "concat": for (let i = doc.parts.length - 1; i >= 0; i--) { cmds.push([ind, mode, doc.parts[i]]); } break; case "indent": cmds.push([makeIndent(ind, options), mode, doc.contents]); break; case "align": cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]); break; case "trim": pos -= trim$1(out); break; case "group": switch (mode) { case MODE_FLAT: if (!shouldRemeasure) { cmds.push([ind, doc.break ? MODE_BREAK : MODE_FLAT, doc.contents]); break; } // fallthrough case MODE_BREAK: { shouldRemeasure = false; const next = [ind, MODE_FLAT, doc.contents]; const rem = width - pos; if (!doc.break && fits(next, cmds, rem, options)) { cmds.push(next); } else { // Expanded states are a rare case where a document // can manually provide multiple representations of // itself. It provides an array of documents // going from the least expanded (most flattened) // representation first to the most expanded. If a // group has these, we need to manually go through // these states and find the first one that fits. if (doc.expandedStates) { const mostExpanded = doc.expandedStates[doc.expandedStates.length - 1]; if (doc.break) { cmds.push([ind, MODE_BREAK, mostExpanded]); break; } else { for (let i = 1; i < doc.expandedStates.length + 1; i++) { if (i >= doc.expandedStates.length) { cmds.push([ind, MODE_BREAK, mostExpanded]); break; } else { const state = doc.expandedStates[i]; const cmd = [ind, MODE_FLAT, state]; if (fits(cmd, cmds, rem, options)) { cmds.push(cmd); break; } } } } } else { cmds.push([ind, MODE_BREAK, doc.contents]); } } break; } } if (doc.id) { groupModeMap[doc.id] = cmds[cmds.length - 1][1]; } break; // Fills each line with as much code as possible before moving to a new // line with the same indentation. // // Expects doc.parts to be an array of alternating content and // whitespace. The whitespace contains the linebreaks. // // For example: // ["I", line, "love", line, "monkeys"] // or // [{ type: group, ... }, softline, { type: group, ... }] // // It uses this parts structure to handle three main layout cases: // * The first two content items fit on the same line without // breaking // -> output the first content item and the whitespace "flat". // * Only the first content item fits on the line without breaking // -> output the first content item "flat" and the whitespace with // "break". // * Neither content item fits on the line without breaking // -> output the first content item and the whitespace with "break". case "fill": { const rem = width - pos; const { parts } = doc; if (parts.length === 0) { break; } const [content, whitespace] = parts; const contentFlatCmd = [ind, MODE_FLAT, content]; const contentBreakCmd = [ind, MODE_BREAK, content]; const contentFits = fits(contentFlatCmd, [], rem, options, true); if (parts.length === 1) { if (contentFits) { cmds.push(contentFlatCmd); } else { cmds.push(contentBreakCmd); } break; } const whitespaceFlatCmd = [ind, MODE_FLAT, whitespace]; const whitespaceBreakCmd = [ind, MODE_BREAK, whitespace]; if (parts.length === 2) { if (contentFits) { cmds.push(whitespaceFlatCmd); cmds.push(contentFlatCmd); } else { cmds.push(whitespaceBreakCmd); cmds.push(contentBreakCmd); } break; } // At this point we've handled the first pair (context, separator) // and will create a new fill doc for the rest of the content. // Ideally we wouldn't mutate the array here but copying all the // elements to a new array would make this algorithm quadratic, // which is unusable for large arrays (e.g. large texts in JSX). parts.splice(0, 2); const remainingCmd = [ind, mode, fill$1(parts)]; const secondContent = parts[0]; const firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$1([content, whitespace, secondContent])]; const firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], rem, options, true); if (firstAndSecondContentFits) { cmds.push(remainingCmd); cmds.push(whitespaceFlatCmd); cmds.push(contentFlatCmd); } else if (contentFits) { cmds.push(remainingCmd); cmds.push(whitespaceBreakCmd); cmds.push(contentFlatCmd); } else { cmds.push(remainingCmd); cmds.push(whitespaceBreakCmd); cmds.push(contentBreakCmd); } break; } case "if-break": { const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode; if (groupMode === MODE_BREAK) { if (doc.breakContents) { cmds.push([ind, mode, doc.breakContents]); } } if (groupMode === MODE_FLAT) { if (doc.flatContents) { cmds.push([ind, mode, doc.flatContents]); } } break; } case "line-suffix": lineSuffix.push([ind, mode, doc.contents]); break; case "line-suffix-boundary": if (lineSuffix.length > 0) { cmds.push([ind, mode, { type: "line", hard: true }]); } break; case "line": switch (mode) { case MODE_FLAT: if (!doc.hard) { if (!doc.soft) { out.push(" "); pos += 1; } break; } else { // This line was forced into the output even if we // were in flattened mode, so we need to tell the next // group that no matter what, it needs to remeasure // because the previous measurement didn't accurately // capture the entire expression (this is necessary // for nested groups) shouldRemeasure = true; } // fallthrough case MODE_BREAK: if (lineSuffix.length) { cmds.push([ind, mode, doc]); cmds.push(...lineSuffix.reverse()); lineSuffix = []; break; } if (doc.literal) { if (ind.root) { out.push(newLine, ind.root.value); pos = ind.root.length; } else { out.push(newLine); pos = 0; } } else { pos -= trim$1(out); out.push(newLine + ind.value); pos = ind.length; } break; } break; } } } const cursorPlaceholderIndex = out.indexOf(cursor$1.placeholder); if (cursorPlaceholderIndex !== -1) { const otherCursorPlaceholderIndex = out.indexOf(cursor$1.placeholder, cursorPlaceholderIndex + 1); const beforeCursor = out.slice(0, cursorPlaceholderIndex).join(""); const aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join(""); const afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join(""); return { formatted: beforeCursor + aroundCursor + afterCursor, cursorNodeStart: beforeCursor.length, cursorNodeText: aroundCursor }; } return { formatted: out.join("") }; } var docPrinter = { printDocToString }; const traverseDocOnExitStackMarker = {}; function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) { const docsStack = [doc]; while (docsStack.length !== 0) { const doc = docsStack.pop(); if (doc === traverseDocOnExitStackMarker) { onExit(docsStack.pop()); continue; } let shouldRecurse = true; if (onEnter) { if (onEnter(doc) === false) { shouldRecurse = false; } } if (onExit) { docsStack.push(doc); docsStack.push(traverseDocOnExitStackMarker); } if (shouldRecurse) { // When there are multiple parts to process, // the parts need to be pushed onto the stack in reverse order, // so that they are processed in the original order // when the stack is popped. if (doc.type === "concat" || doc.type === "fill") { for (let ic = doc.parts.length, i = ic - 1; i >= 0; --i) { docsStack.push(doc.parts[i]); } } else if (doc.type === "if-break") { if (doc.flatContents) { docsStack.push(doc.flatContents); } if (doc.breakContents) { docsStack.push(doc.breakContents); } } else if (doc.type === "group" && doc.expandedStates) { if (shouldTraverseConditionalGroups) { for (let ic = doc.expandedStates.length, i = ic - 1; i >= 0; --i) { docsStack.push(doc.expandedStates[i]); } } else { docsStack.push(doc.contents); } } else if (doc.contents) { docsStack.push(doc.contents); } } } } function mapDoc(doc, cb) { if (doc.type === "concat" || doc.type === "fill") { const parts = doc.parts.map(part => mapDoc(part, cb)); return cb(Object.assign({}, doc, { parts })); } else if (doc.type === "if-break") { const breakContents = doc.breakContents && mapDoc(doc.breakContents, cb); const flatContents = doc.flatContents && mapDoc(doc.flatContents, cb); return cb(Object.assign({}, doc, { breakContents, flatContents })); } else if (doc.contents) { const contents = mapDoc(doc.contents, cb); return cb(Object.assign({}, doc, { contents })); } return cb(doc); } function findInDoc(doc, fn, defaultValue) { let result = defaultValue; let hasStopped = false; function findInDocOnEnterFn(doc) { const maybeResult = fn(doc); if (maybeResult !== undefined) { hasStopped = true; result = maybeResult; } if (hasStopped) { return false; } } traverseDoc(doc, findInDocOnEnterFn); return result; } function isEmpty(n) { return typeof n === "string" && n.length === 0; } function isLineNextFn(doc) { if (typeof doc === "string") { return false; } if (doc.type === "line") { return true; } } function isLineNext(doc) { return findInDoc(doc, isLineNextFn, false); } function willBreakFn(doc) { if (doc.type === "group" && doc.break) { return true; } if (doc.type === "line" && doc.hard) { return true; } if (doc.type === "break-parent") { return true; } } function willBreak(doc) { return findInDoc(doc, willBreakFn, false); } function breakParentGroup(groupStack) { if (groupStack.length > 0) { const parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because // the user is expected to manually handle what breaks. if (!parentGroup.expandedStates) { parentGroup.break = true; } } return null; } function propagateBreaks(doc) { const alreadyVisitedSet = new Set(); const groupStack = []; function propagateBreaksOnEnterFn(doc) { if (doc.type === "break-parent") { breakParentGroup(groupStack); } if (doc.type === "group") { groupStack.push(doc); if (alreadyVisitedSet.has(doc)) { return false; } alreadyVisitedSet.add(doc); } } function propagateBreaksOnExitFn(doc) { if (doc.type === "group") { const group = groupStack.pop(); if (group.break) { breakParentGroup(groupStack); } } } traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn, /* shouldTraverseConditionalGroups */ true); } function removeLinesFn(doc) { // Force this doc into flat mode by statically converting all // lines into spaces (or soft lines into nothing). Hard lines // should still output because there's too great of a chance // of breaking existing assumptions otherwise. if (doc.type === "line" && !doc.hard) { return doc.soft ? "" : " "; } else if (doc.type === "if-break") { return doc.flatContents || ""; } return doc; } function removeLines(doc) { return mapDoc(doc, removeLinesFn); } function stripTrailingHardline(doc) { // HACK remove ending hardline, original PR: #1984 if (doc.type === "concat" && doc.parts.length !== 0) { const lastPart = doc.parts[doc.parts.length - 1]; if (lastPart.type === "concat") { if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") { return { type: "concat", parts: doc.parts.slice(0, -1) }; } return { type: "concat", parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart)) }; } } return doc; } var docUtils = { isEmpty, willBreak, isLineNext, traverseDoc, findInDoc, mapDoc, propagateBreaks, removeLines, stripTrailingHardline }; function flattenDoc(doc) { if (doc.type === "concat") { const res = []; for (let i = 0; i < doc.parts.length; ++i) { const doc2 = doc.parts[i]; if (typeof doc2 !== "string" && doc2.type === "concat") { res.push(...flattenDoc(doc2).parts); } else { const flattened = flattenDoc(doc2); if (flattened !== "") { res.push(flattened); } } } return Object.assign({}, doc, { parts: res }); } else if (doc.type === "if-break") { return Object.assign({}, doc, { breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null, flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null }); } else if (doc.type === "group") { return Object.assign({}, doc, { contents: flattenDoc(doc.contents), expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates }); } else if (doc.contents) { return Object.assign({}, doc, { contents: flattenDoc(doc.contents) }); } return doc; } function printDoc(doc) { if (typeof doc === "string") { return JSON.stringify(doc); } if (doc.type === "line") { if (doc.literal) { return "literalline"; } if (doc.hard) { return "hardline"; } if (doc.soft) { return "softline"; } return "line"; } if (doc.type === "break-parent") { return "breakParent"; } if (doc.type === "trim") { return "trim"; } if (doc.type === "concat") { return "[" + doc.parts.map(printDoc).join(", ") + "]"; } if (doc.type === "indent") { return "indent(" + printDoc(doc.contents) + ")"; } if (doc.type === "align") { return doc.n === -Infinity ? "dedentToRoot(" + printDoc(doc.contents) + ")" : doc.n < 0 ? "dedent(" + printDoc(doc.contents) + ")" : doc.n.type === "root" ? "markAsRoot(" + printDoc(doc.contents) + ")" : "align(" + JSON.stringify(doc.n) + ", " + printDoc(doc.contents) + ")"; } if (doc.type === "if-break") { return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")"; } if (doc.type === "group") { if (doc.expandedStates) { return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])"; } return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")"; } if (doc.type === "fill") { return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")"; } if (doc.type === "line-suffix") { return "lineSuffix(" + printDoc(doc.contents) + ")"; } if (doc.type === "line-suffix-boundary") { return "lineSuffixBoundary"; } throw new Error("Unknown doc type " + doc.type); } var docDebug = { printDocToDebug(doc) { return printDoc(flattenDoc(doc)); } }; var document = { builders: docBuilders, printer: docPrinter, utils: docUtils, debug: docDebug }; const { getMaxContinuousCount: getMaxContinuousCount$1, getStringWidth: getStringWidth$2, getAlignmentSize: getAlignmentSize$1, getIndentSize: getIndentSize$1, skip: skip$1, skipWhitespace: skipWhitespace$1, skipSpaces: skipSpaces$1, skipNewline: skipNewline$1, skipToLineEnd: skipToLineEnd$1, skipEverythingButNewLine: skipEverythingButNewLine$1, skipInlineComment: skipInlineComment$1, skipTrailingComment: skipTrailingComment$1, hasNewline: hasNewline$1, hasNewlineInRange: hasNewlineInRange$1, hasSpaces: hasSpaces$1, isNextLineEmpty: isNextLineEmpty$1, isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1, isPreviousLineEmpty: isPreviousLineEmpty$1, getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1, makeString: makeString$1, addLeadingComment: addLeadingComment$1, addDanglingComment: addDanglingComment$1, addTrailingComment: addTrailingComment$1 } = util$1; var utilShared = { getMaxContinuousCount: getMaxContinuousCount$1, getStringWidth: getStringWidth$2, getAlignmentSize: getAlignmentSize$1, getIndentSize: getIndentSize$1, skip: skip$1, skipWhitespace: skipWhitespace$1, skipSpaces: skipSpaces$1, skipNewline: skipNewline$1, skipToLineEnd: skipToLineEnd$1, skipEverythingButNewLine: skipEverythingButNewLine$1, skipInlineComment: skipInlineComment$1, skipTrailingComment: skipTrailingComment$1, hasNewline: hasNewline$1, hasNewlineInRange: hasNewlineInRange$1, hasSpaces: hasSpaces$1, isNextLineEmpty: isNextLineEmpty$1, isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1, isPreviousLineEmpty: isPreviousLineEmpty$1, getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1, makeString: makeString$1, addLeadingComment: addLeadingComment$1, addDanglingComment: addDanglingComment$1, addTrailingComment: addTrailingComment$1 }; const { concat: concat$2, line: line$1, hardline: hardline$1, breakParent: breakParent$1, indent: indent$1, lineSuffix: lineSuffix$1, join: join$1, cursor: cursor$2 } = document.builders; const { hasNewline: hasNewline$2, skipNewline: skipNewline$2, isPreviousLineEmpty: isPreviousLineEmpty$2 } = util$1; const { addLeadingComment: addLeadingComment$2, addDanglingComment: addDanglingComment$2, addTrailingComment: addTrailingComment$2 } = utilShared; const childNodesCacheKey = Symbol("child-nodes"); function getSortedChildNodes(node, options, resultArray) { if (!node) { return; } const { printer, locStart, locEnd } = options; if (resultArray) { if (printer.canAttachComment && printer.canAttachComment(node)) { // This reverse insertion sort almost always takes constant // time because we almost always (maybe always?) append the // nodes in order anyway. let i; for (i = resultArray.length - 1; i >= 0; --i) { if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) { break; } } resultArray.splice(i + 1, 0, node); return; } } else if (node[childNodesCacheKey]) { return node[childNodesCacheKey]; } const childNodes = printer.getCommentChildNodes && printer.getCommentChildNodes(node, options) || typeof node === "object" && Object.keys(node).filter(n => n !== "enclosingNode" && n !== "precedingNode" && n !== "followingNode").map(n => node[n]); if (!childNodes) { return; } if (!resultArray) { Object.defineProperty(node, childNodesCacheKey, { value: resultArray = [], enumerable: false }); } childNodes.forEach(childNode => { getSortedChildNodes(childNode, options, resultArray); }); return resultArray; } // As efficiently as possible, decorate the comment object with // .precedingNode, .enclosingNode, and/or .followingNode properties, at // least one of which is guaranteed to be defined. function decorateComment(node, comment, options) { const { locStart, locEnd } = options; const childNodes = getSortedChildNodes(node, options); let precedingNode; let followingNode; // Time to dust off the old binary search robes and wizard hat. let left = 0; let right = childNodes.length; while (left < right) { const middle = left + right >> 1; const child = childNodes[middle]; if (locStart(child) - locStart(comment) <= 0 && locEnd(comment) - locEnd(child) <= 0) { // The comment is completely contained by this child node. comment.enclosingNode = child; decorateComment(child, comment, options); return; // Abandon the binary search at this level. } if (locEnd(child) - locStart(comment) <= 0) { // This child node falls completely before the comment. // Because we will never consider this node or any nodes // before it again, this node must be the closest preceding // node we have encountered so far. precedingNode = child; left = middle + 1; continue; } if (locEnd(comment) - locStart(child) <= 0) { // This child node falls completely after the comment. // Because we will never consider this node or any nodes after // it again, this node must be the closest following node we // have encountered so far. followingNode = child; right = middle; continue; } /* istanbul ignore next */ throw new Error("Comment location overlaps with node location"); } // We don't want comments inside of different expressions inside of the same // template literal to move to another expression. if (comment.enclosingNode && comment.enclosingNode.type === "TemplateLiteral") { const { quasis } = comment.enclosingNode; const commentIndex = findExpressionIndexForComment(quasis, comment, options); if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) { precedingNode = null; } if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) { followingNode = null; } } if (precedingNode) { comment.precedingNode = precedingNode; } if (followingNode) { comment.followingNode = followingNode; } } function attach(comments, ast, text, options) { if (!Array.isArray(comments)) { return; } const tiesToBreak = []; const { locStart, locEnd } = options; comments.forEach((comment, i) => { if (options.parser === "json" || options.parser === "json5" || options.parser === "__js_expression" || options.parser === "__vue_expression") { if (locStart(comment) - locStart(ast) <= 0) { addLeadingComment$2(ast, comment); return; } if (locEnd(comment) - locEnd(ast) >= 0) { addTrailingComment$2(ast, comment); return; } } decorateComment(ast, comment, options); const { precedingNode, enclosingNode, followingNode } = comment; const pluginHandleOwnLineComment = options.printer.handleComments && options.printer.handleComments.ownLine ? options.printer.handleComments.ownLine : () => false; const pluginHandleEndOfLineComment = options.printer.handleComments && options.printer.handleComments.endOfLine ? options.printer.handleComments.endOfLine : () => false; const pluginHandleRemainingComment = options.printer.handleComments && options.printer.handleComments.remaining ? options.printer.handleComments.remaining : () => false; const isLastComment = comments.length - 1 === i; if (hasNewline$2(text, locStart(comment), { backwards: true })) { // If a comment exists on its own line, prefer a leading comment. // We also need to check if it's the first line of the file. if (pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)) ; else if (followingNode) { // Always a leading comment. addLeadingComment$2(followingNode, comment); } else if (precedingNode) { addTrailingComment$2(precedingNode, comment); } else if (enclosingNode) { addDanglingComment$2(enclosingNode, comment); } else { // There are no nodes, let's attach it to the root of the ast /* istanbul ignore next */ addDanglingComment$2(ast, comment); } } else if (hasNewline$2(text, locEnd(comment))) { if (pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode) { // There is content before this comment on the same line, but // none after it, so prefer a trailing comment of the previous node. addTrailingComment$2(precedingNode, comment); } else if (followingNode) { addLeadingComment$2(followingNode, comment); } else if (enclosingNode) { addDanglingComment$2(enclosingNode, comment); } else { // There are no nodes, let's attach it to the root of the ast /* istanbul ignore next */ addDanglingComment$2(ast, comment); } } else { if (pluginHandleRemainingComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode && followingNode) { // Otherwise, text exists both before and after the comment on // the same line. If there is both a preceding and following // node, use a tie-breaking algorithm to determine if it should // be attached to the next or previous node. In the last case, // simply attach the right node; const tieCount = tiesToBreak.length; if (tieCount > 0) { const lastTie = tiesToBreak[tieCount - 1]; if (lastTie.followingNode !== comment.followingNode) { breakTies(tiesToBreak, text, options); } } tiesToBreak.push(comment); } else if (precedingNode) { addTrailingComment$2(precedingNode, comment); } else if (followingNode) { addLeadingComment$2(followingNode, comment); } else if (enclosingNode) { addDanglingComment$2(enclosingNode, comment); } else { // There are no nodes, let's attach it to the root of the ast /* istanbul ignore next */ addDanglingComment$2(ast, comment); } } }); breakTies(tiesToBreak, text, options); comments.forEach(comment => { // These node references were useful for breaking ties, but we // don't need them anymore, and they create cycles in the AST that // may lead to infinite recursion if we don't delete them here. delete comment.precedingNode; delete comment.enclosingNode; delete comment.followingNode; }); } function breakTies(tiesToBreak, text, options) { const tieCount = tiesToBreak.length; if (tieCount === 0) { return; } const { precedingNode, followingNode, enclosingNode } = tiesToBreak[0]; const gapRegExp = options.printer.getGapRegex && options.printer.getGapRegex(enclosingNode) || /^[\s(]*$/; let gapEndPos = options.locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps // between the tied comments. In order to qualify as leading, a // comment must be separated from followingNode by an unbroken series of // gaps (or other comments). Gaps should only contain whitespace or open // parentheses. let indexOfFirstLeadingComment; for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) { const comment = tiesToBreak[indexOfFirstLeadingComment - 1]; assert.strictEqual(comment.precedingNode, precedingNode); assert.strictEqual(comment.followingNode, followingNode); const gap = text.slice(options.locEnd(comment), gapEndPos); if (gapRegExp.test(gap)) { gapEndPos = options.locStart(comment); } else { // The gap string contained something other than whitespace or open // parentheses. break; } } tiesToBreak.forEach((comment, i) => { if (i < indexOfFirstLeadingComment) { addTrailingComment$2(precedingNode, comment); } else { addLeadingComment$2(followingNode, comment); } }); tiesToBreak.length = 0; } function printComment(commentPath, options) { const comment = commentPath.getValue(); comment.printed = true; return options.printer.printComment(commentPath, options); } function findExpressionIndexForComment(quasis, comment, options) { const startPos = options.locStart(comment) - 1; for (let i = 1; i < quasis.length; ++i) { if (startPos < getQuasiRange(quasis[i]).start) { return i - 1; } } // We haven't found it, it probably means that some of the locations are off. // Let's just return the first one. /* istanbul ignore next */ return 0; } function getQuasiRange(expr) { if (expr.start !== undefined) { // Babel return { start: expr.start, end: expr.end }; } // Flow return { start: expr.range[0], end: expr.range[1] }; } function printLeadingComment(commentPath, print, options) { const comment = commentPath.getValue(); const contents = printComment(commentPath, options); if (!contents) { return ""; } const isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // Leading block comments should see if they need to stay on the // same line or not. if (isBlock) { const lineBreak = hasNewline$2(options.originalText, options.locEnd(comment)) ? hasNewline$2(options.originalText, options.locStart(comment), { backwards: true }) ? hardline$1 : line$1 : " "; return concat$2([contents, lineBreak]); } return concat$2([contents, hardline$1]); } function printTrailingComment(commentPath, print, options) { const comment = commentPath.getValue(); const contents = printComment(commentPath, options); if (!contents) { return ""; } const isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // We don't want the line to break // when the parentParentNode is a ClassDeclaration/-Expression // And the parentNode is in the superClass property const parentNode = commentPath.getNode(1); const parentParentNode = commentPath.getNode(2); const isParentSuperClass = parentParentNode && (parentParentNode.type === "ClassDeclaration" || parentParentNode.type === "ClassExpression") && parentParentNode.superClass === parentNode; if (hasNewline$2(options.originalText, options.locStart(comment), { backwards: true })) { // This allows comments at the end of nested structures: // { // x: 1, // y: 2 // // A comment // } // Those kinds of comments are almost always leading comments, but // here it doesn't go "outside" the block and turns it into a // trailing comment for `2`. We can simulate the above by checking // if this a comment on its own line; normal trailing comments are // always at the end of another expression. const isLineBeforeEmpty = isPreviousLineEmpty$2(options.originalText, comment, options.locStart); return lineSuffix$1(concat$2([hardline$1, isLineBeforeEmpty ? hardline$1 : "", contents])); } else if (isBlock || isParentSuperClass) { // Trailing block comments never need a newline return concat$2([" ", contents]); } return concat$2([lineSuffix$1(concat$2([" ", contents])), !isBlock ? breakParent$1 : ""]); } function printDanglingComments(path, options, sameIndent, filter) { const parts = []; const node = path.getValue(); if (!node || !node.comments) { return ""; } path.each(commentPath => { const comment = commentPath.getValue(); if (comment && !comment.leading && !comment.trailing && (!filter || filter(comment))) { parts.push(printComment(commentPath, options)); } }, "comments"); if (parts.length === 0) { return ""; } if (sameIndent) { return join$1(hardline$1, parts); } return indent$1(concat$2([hardline$1, join$1(hardline$1, parts)])); } function prependCursorPlaceholder(path, options, printed) { if (path.getNode() === options.cursorNode && path.getValue()) { return concat$2([cursor$2, printed, cursor$2]); } return printed; } function printComments(path, print, options, needsSemi) { const value = path.getValue(); const printed = print(path); const comments = value && value.comments; if (!comments || comments.length === 0) { return prependCursorPlaceholder(path, options, printed); } const leadingParts = []; const trailingParts = [needsSemi ? ";" : "", printed]; path.each(commentPath => { const comment = commentPath.getValue(); const { leading, trailing } = comment; if (leading) { const contents = printLeadingComment(commentPath, print, options); if (!contents) { return; } leadingParts.push(contents); const text = options.originalText; const index = skipNewline$2(text, options.locEnd(comment)); if (index !== false && hasNewline$2(text, index)) { leadingParts.push(hardline$1); } } else if (trailing) { trailingParts.push(printTrailingComment(commentPath, print, options)); } }, "comments"); return prependCursorPlaceholder(path, options, concat$2(leadingParts.concat(trailingParts))); } var comments = { attach, printComments, printDanglingComments, getSortedChildNodes }; function getNodeHelper(path, count) { const stackIndex = getNodeStackIndexHelper(path.stack, count); return stackIndex === -1 ? null : path.stack[stackIndex]; } function getNodeStackIndexHelper(stack, count) { for (let i = stack.length - 1; i >= 0; i -= 2) { const value = stack[i]; if (value && !Array.isArray(value) && --count < 0) { return i; } } return -1; } class FastPath { constructor(value) { this.stack = [value]; } // The name of the current property is always the penultimate element of // this.stack, and always a String. getName() { const { stack } = this; const { length } = stack; if (length > 1) { return stack[length - 2]; } // Since the name is always a string, null is a safe sentinel value to // return if we do not know the name of the (root) value. /* istanbul ignore next */ return null; } // The value of the current property is always the final element of // this.stack. getValue() { return getLast(this.stack); } getNode(count = 0) { return getNodeHelper(this, count); } getParentNode(count = 0) { return getNodeHelper(this, count + 1); } // Temporarily push properties named by string arguments given after the // callback function onto this.stack, then call the callback with a // reference to this (modified) FastPath object. Note that the stack will // be restored to its original state after the callback is finished, so it // is probably a mistake to retain a reference to the path. call(callback, ...names) { const { stack } = this; const { length } = stack; let value = getLast(stack); for (const name of names) { value = value[name]; stack.push(name, value); } const result = callback(this); stack.length = length; return result; } callParent(callback, count = 0) { const stackIndex = getNodeStackIndexHelper(this.stack, count + 1); const parentValues = this.stack.splice(stackIndex + 1); const result = callback(this); this.stack.push(...parentValues); return result; } // Similar to FastPath.prototype.call, except that the value obtained by // accessing this.getValue()[name1][name2]... should be array-like. The // callback will be called with a reference to this path object for each // element of the array. each(callback, ...names) { const { stack } = this; const { length } = stack; let value = getLast(stack); for (const name of names) { value = value[name]; stack.push(name, value); } for (let i = 0; i < value.length; ++i) { if (i in value) { stack.push(i, value[i]); // If the callback needs to know the value of i, call // path.getName(), assuming path is the parameter name. callback(this); stack.length -= 2; } } stack.length = length; } // Similar to FastPath.prototype.each, except that the results of the // callback function invocations are stored in an array and returned at // the end of the iteration. map(callback, ...names) { const { stack } = this; const { length } = stack; let value = getLast(stack); for (const name of names) { value = value[name]; stack.push(name, value); } const result = new Array(value.length); for (let i = 0; i < value.length; ++i) { if (i in value) { stack.push(i, value[i]); result[i] = callback(this, i); stack.length -= 2; } } stack.length = length; return result; } /** * @param {...( * | ((node: any, name: string | null, number: number | null) => boolean) * | undefined * )} predicates */ match(...predicates) { let stackPointer = this.stack.length - 1; let name = null; let node = this.stack[stackPointer--]; for (const predicate of predicates) { if (node === undefined) { return false; } // skip index/array let number = null; if (typeof name === "number") { number = name; name = this.stack[stackPointer--]; node = this.stack[stackPointer--]; } if (predicate && !predicate(node, name, number)) { return false; } name = this.stack[stackPointer--]; node = this.stack[stackPointer--]; } return true; } } var fastPath = FastPath; const { normalize: normalize$2 } = options$1; function printSubtree(path, print, options, printAstToDoc) { if (options.printer.embed) { return options.printer.embed(path, print, (text, partialNextOptions) => textToDoc(text, partialNextOptions, options, printAstToDoc), options); } } function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc) { const nextOptions = normalize$2(Object.assign({}, parentOptions, {}, partialNextOptions, { parentParser: parentOptions.parser, embeddedInHtml: !!(parentOptions.embeddedInHtml || parentOptions.parser === "html" || parentOptions.parser === "vue" || parentOptions.parser === "angular" || parentOptions.parser === "lwc"), originalText: text }), { passThrough: true }); const result = parser.parse(text, nextOptions); const { ast } = result; text = result.text; const astComments = ast.comments; delete ast.comments; comments.attach(astComments, ast, text, nextOptions); return printAstToDoc(ast, nextOptions); } var multiparser = { printSubtree }; const doc = document; const docBuilders$1 = doc.builders; const { concat: concat$3, hardline: hardline$2, addAlignmentToDoc: addAlignmentToDoc$1 } = docBuilders$1; const docUtils$1 = doc.utils; /** * Takes an abstract syntax tree (AST) and recursively converts it to a * document (series of printing primitives). * * This is done by descending down the AST recursively. The recursion * involves two functions that call each other: * * 1. printGenerically(), which is defined as an inner function here. * It basically takes care of node caching. * 2. callPluginPrintFunction(), which checks for some options, and * ultimately calls the print() function provided by the plugin. * * The plugin function will call printGenerically() again for child nodes * of the current node, which will do its housekeeping, then call the * plugin function again, and so on. * * All the while, these functions pass a "path" variable around, which * is a stack-like data structure (FastPath) that maintains the current * state of the recursion. It is called "path", because it represents * the path to the current node through the Abstract Syntax Tree. */ function printAstToDoc(ast, options, alignmentSize = 0) { const { printer } = options; if (printer.preprocess) { ast = printer.preprocess(ast, options); } const cache = new Map(); function printGenerically(path, args) { const node = path.getValue(); const shouldCache = node && typeof node === "object" && args === undefined; if (shouldCache && cache.has(node)) { return cache.get(node); } // We let JSXElement print its comments itself because it adds () around // UnionTypeAnnotation has to align the child without the comments let res; if (printer.willPrintOwnComments && printer.willPrintOwnComments(path, options)) { res = callPluginPrintFunction(path, options, printGenerically, args); } else { // printComments will call the plugin print function and check for // comments to print res = comments.printComments(path, p => callPluginPrintFunction(p, options, printGenerically, args), options, args && args.needsSemi); } if (shouldCache) { cache.set(node, res); } return res; } let doc = printGenerically(new fastPath(ast)); if (alignmentSize > 0) { // Add a hardline to make the indents take effect // It should be removed in index.js format() doc = addAlignmentToDoc$1(concat$3([hardline$2, doc]), alignmentSize, options.tabWidth); } docUtils$1.propagateBreaks(doc); return doc; } function callPluginPrintFunction(path, options, printPath, args) { assert.ok(path instanceof fastPath); const node = path.getValue(); const { printer } = options; // Escape hatch if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path)) { return options.originalText.slice(options.locStart(node), options.locEnd(node)); } if (node) { try { // Potentially switch to a different parser const sub = multiparser.printSubtree(path, printPath, options, printAstToDoc); if (sub) { return sub; } } catch (error) { /* istanbul ignore if */ if (commonjsGlobal.PRETTIER_DEBUG) { throw error; } // Continue with current parser } } return printer.print(path, options, printPath, args); } var astToDoc = printAstToDoc; function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) { let resultStartNode = startNodeAndParents.node; let resultEndNode = endNodeAndParents.node; if (resultStartNode === resultEndNode) { return { startNode: resultStartNode, endNode: resultEndNode }; } for (const endParent of endNodeAndParents.parentNodes) { if (endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node)) { resultEndNode = endParent; } else { break; } } for (const startParent of startNodeAndParents.parentNodes) { if (startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node)) { resultStartNode = startParent; } else { break; } } return { startNode: resultStartNode, endNode: resultEndNode }; } function findNodeAtOffset(node, offset, options, predicate, parentNodes) { predicate = predicate || (() => true); parentNodes = parentNodes || []; const start = options.locStart(node, options.locStart); const end = options.locEnd(node, options.locEnd); if (start <= offset && offset <= end) { for (const childNode of comments.getSortedChildNodes(node, options)) { const childResult = findNodeAtOffset(childNode, offset, options, predicate, [node].concat(parentNodes)); if (childResult) { return childResult; } } if (predicate(node)) { return { node, parentNodes }; } } } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 function isSourceElement(opts, node) { if (node == null) { return false; } // JS and JS like to avoid repetitions const jsSourceElements = ["FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015 "ImportDeclaration", // Module "ExportDefaultDeclaration", // Module "ExportNamedDeclaration", // Module "ExportAllDeclaration", // Module "TypeAlias", // Flow "InterfaceDeclaration", // Flow, TypeScript "TypeAliasDeclaration", // TypeScript "ExportAssignment", // TypeScript "ExportDeclaration" // TypeScript ]; const jsonSourceElements = ["ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"]; const graphqlSourceElements = ["OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition"]; switch (opts.parser) { case "flow": case "babel": case "babel-flow": case "babel-ts": case "typescript": return jsSourceElements.includes(node.type); case "json": return jsonSourceElements.includes(node.type); case "graphql": return graphqlSourceElements.includes(node.kind); case "vue": return node.tag !== "root"; } return false; } function calculateRange(text, opts, ast) { // Contract the range so that it has non-whitespace characters at its endpoints. // This ensures we can format a range that doesn't end on a node. const rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd); const startNonWhitespace = Math.max(opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart); let endNonWhitespace; for (endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace) { if (text[endNonWhitespace - 1].match(/\S/)) { break; } } const startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace, opts, node => isSourceElement(opts, node)); const endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace, opts, node => isSourceElement(opts, node)); if (!startNodeAndParents || !endNodeAndParents) { return { rangeStart: 0, rangeEnd: 0 }; } const siblingAncestors = findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts); const { startNode, endNode } = siblingAncestors; const rangeStart = Math.min(opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart)); const rangeEnd = Math.max(opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd)); return { rangeStart, rangeEnd }; } var rangeUtil = { calculateRange, findNodeAtOffset }; var diff = getCjsExportFromNamespace(index_es6); const normalizeOptions$1 = options$1.normalize; const { guessEndOfLine: guessEndOfLine$1, convertEndOfLineToChars: convertEndOfLineToChars$2 } = endOfLine; const { printer: { printDocToString: printDocToString$1 }, debug: { printDocToDebug } } = document; const BOM = "\uFEFF"; const CURSOR = Symbol("cursor"); const PLACEHOLDERS = { cursorOffset: "<<>>", rangeStart: "<<>>", rangeEnd: "<<>>" }; function ensureAllCommentsPrinted(astComments) { if (!astComments) { return; } for (let i = 0; i < astComments.length; ++i) { if (util$1.isNodeIgnoreComment(astComments[i])) { // If there's a prettier-ignore, we're not printing that sub-tree so we // don't know if the comments was printed or not. return; } } astComments.forEach(comment => { if (!comment.printed) { throw new Error('Comment "' + comment.value.trim() + '" was not printed. Please report this error!'); } delete comment.printed; }); } function attachComments(text, ast, opts) { const astComments = ast.comments; if (astComments) { delete ast.comments; comments.attach(astComments, ast, text, opts); } ast.tokens = []; opts.originalText = opts.parser === "yaml" ? text : text.trimEnd(); return astComments; } function coreFormat(text, opts, addAlignmentSize) { if (!text || !text.trim().length) { return { formatted: "", cursorOffset: 0 }; } addAlignmentSize = addAlignmentSize || 0; const parsed = parser.parse(text, opts); const { ast } = parsed; text = parsed.text; if (opts.cursorOffset >= 0) { const nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts); if (nodeResult && nodeResult.node) { opts.cursorNode = nodeResult.node; } } const astComments = attachComments(text, ast, opts); const doc = astToDoc(ast, opts, addAlignmentSize); const result = printDocToString$1(doc, opts); ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline if (addAlignmentSize > 0) { const trimmed = result.formatted.trim(); if (result.cursorNodeStart !== undefined) { result.cursorNodeStart -= result.formatted.indexOf(trimmed); } result.formatted = trimmed + convertEndOfLineToChars$2(opts.endOfLine); } if (opts.cursorOffset >= 0) { let oldCursorNodeStart; let oldCursorNodeText; let cursorOffsetRelativeToOldCursorNode; let newCursorNodeStart; let newCursorNodeText; if (opts.cursorNode && result.cursorNodeText) { oldCursorNodeStart = opts.locStart(opts.cursorNode); oldCursorNodeText = text.slice(oldCursorNodeStart, opts.locEnd(opts.cursorNode)); cursorOffsetRelativeToOldCursorNode = opts.cursorOffset - oldCursorNodeStart; newCursorNodeStart = result.cursorNodeStart; newCursorNodeText = result.cursorNodeText; } else { oldCursorNodeStart = 0; oldCursorNodeText = text; cursorOffsetRelativeToOldCursorNode = opts.cursorOffset; newCursorNodeStart = 0; newCursorNodeText = result.formatted; } if (oldCursorNodeText === newCursorNodeText) { return { formatted: result.formatted, cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode }; } // diff old and new cursor node texts, with a special cursor // symbol inserted to find out where it moves to const oldCursorNodeCharArray = oldCursorNodeText.split(""); oldCursorNodeCharArray.splice(cursorOffsetRelativeToOldCursorNode, 0, CURSOR); const newCursorNodeCharArray = newCursorNodeText.split(""); const cursorNodeDiff = diff.diffArrays(oldCursorNodeCharArray, newCursorNodeCharArray); let cursorOffset = newCursorNodeStart; for (const entry of cursorNodeDiff) { if (entry.removed) { if (entry.value.includes(CURSOR)) { break; } } else { cursorOffset += entry.count; } } return { formatted: result.formatted, cursorOffset }; } return { formatted: result.formatted }; } function formatRange(text, opts) { const parsed = parser.parse(text, opts); const { ast } = parsed; text = parsed.text; const range = rangeUtil.calculateRange(text, opts, ast); const { rangeStart, rangeEnd } = range; const rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line. // This is so we can detect indentation correctly and restore it. // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0 const rangeStart2 = Math.min(rangeStart, text.lastIndexOf("\n", rangeStart) + 1); const indentString = text.slice(rangeStart2, rangeStart); const alignmentSize = util$1.getAlignmentSize(indentString, opts.tabWidth); const rangeResult = coreFormat(rangeString, Object.assign({}, opts, { rangeStart: 0, rangeEnd: Infinity, // track the cursor offset only if it's within our range cursorOffset: opts.cursorOffset >= rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart : -1 }), alignmentSize); // Since the range contracts to avoid trailing whitespace, // we need to remove the newline that was inserted by the `format` call. const rangeTrimmed = rangeResult.formatted.trimEnd(); const rangeLeft = text.slice(0, rangeStart); const rangeRight = text.slice(rangeEnd); let { cursorOffset } = opts; if (opts.cursorOffset >= rangeEnd) { // handle the case where the cursor was past the end of the range cursorOffset = opts.cursorOffset - rangeEnd + (rangeStart + rangeTrimmed.length); } else if (rangeResult.cursorOffset !== undefined) { // handle the case where the cursor was in the range cursorOffset = rangeResult.cursorOffset + rangeStart; } // keep the cursor as it was if it was before the start of the range let formatted; if (opts.endOfLine === "lf") { formatted = rangeLeft + rangeTrimmed + rangeRight; } else { const eol = convertEndOfLineToChars$2(opts.endOfLine); if (cursorOffset >= 0) { const parts = [rangeLeft, rangeTrimmed, rangeRight]; let partIndex = 0; let partOffset = cursorOffset; while (partIndex < parts.length) { const part = parts[partIndex]; if (partOffset < part.length) { parts[partIndex] = parts[partIndex].slice(0, partOffset) + PLACEHOLDERS.cursorOffset + parts[partIndex].slice(partOffset); break; } partIndex++; partOffset -= part.length; } const [newRangeLeft, newRangeTrimmed, newRangeRight] = parts; formatted = (newRangeLeft.replace(/\n/g, eol) + newRangeTrimmed + newRangeRight.replace(/\n/g, eol)).replace(PLACEHOLDERS.cursorOffset, (_, index) => { cursorOffset = index; return ""; }); } else { formatted = rangeLeft.replace(/\n/g, eol) + rangeTrimmed + rangeRight.replace(/\n/g, eol); } } return { formatted, cursorOffset }; } function format(text, opts) { const selectedParser = parser.resolveParser(opts); const hasPragma = !selectedParser.hasPragma || selectedParser.hasPragma(text); if (opts.requirePragma && !hasPragma) { return { formatted: text }; } if (opts.endOfLine === "auto") { opts.endOfLine = guessEndOfLine$1(text); } const hasCursor = opts.cursorOffset >= 0; const hasRangeStart = opts.rangeStart > 0; const hasRangeEnd = opts.rangeEnd < text.length; // get rid of CR/CRLF parsing if (text.includes("\r")) { const offsetKeys = [hasCursor && "cursorOffset", hasRangeStart && "rangeStart", hasRangeEnd && "rangeEnd"].filter(Boolean).sort((aKey, bKey) => opts[aKey] - opts[bKey]); for (let i = offsetKeys.length - 1; i >= 0; i--) { const key = offsetKeys[i]; text = text.slice(0, opts[key]) + PLACEHOLDERS[key] + text.slice(opts[key]); } text = text.replace(/\r\n?/g, "\n"); for (let i = 0; i < offsetKeys.length; i++) { const key = offsetKeys[i]; text = text.replace(PLACEHOLDERS[key], (_, index) => { opts[key] = index; return ""; }); } } const hasUnicodeBOM = text.charAt(0) === BOM; if (hasUnicodeBOM) { text = text.slice(1); if (hasCursor) { opts.cursorOffset++; } if (hasRangeStart) { opts.rangeStart++; } if (hasRangeEnd) { opts.rangeEnd++; } } if (!hasCursor) { opts.cursorOffset = -1; } if (opts.rangeStart < 0) { opts.rangeStart = 0; } if (opts.rangeEnd > text.length) { opts.rangeEnd = text.length; } const result = hasRangeStart || hasRangeEnd ? formatRange(text, opts) : coreFormat(opts.insertPragma && opts.printer.insertPragma && !hasPragma ? opts.printer.insertPragma(text) : text, opts); if (hasUnicodeBOM) { result.formatted = BOM + result.formatted; if (hasCursor) { result.cursorOffset++; } } return result; } var core = { formatWithCursor(text, opts) { opts = normalizeOptions$1(opts); return format(text, opts); }, parse(text, opts, massage) { opts = normalizeOptions$1(opts); if (text.includes("\r")) { text = text.replace(/\r\n?/g, "\n"); } const parsed = parser.parse(text, opts); if (massage) { parsed.ast = massageAst(parsed.ast, opts); } return parsed; }, formatAST(ast, opts) { opts = normalizeOptions$1(opts); const doc = astToDoc(ast, opts); return printDocToString$1(doc, opts); }, // Doesn't handle shebang for now formatDoc(doc, opts) { const debug = printDocToDebug(doc); opts = normalizeOptions$1(Object.assign({}, opts, { parser: "babel" })); return format(debug, opts).formatted; }, printToDoc(text, opts) { opts = normalizeOptions$1(opts); const parsed = parser.parse(text, opts); const { ast } = parsed; text = parsed.text; attachComments(text, ast, opts); return astToDoc(ast, opts); }, printDocToString(doc, opts) { return printDocToString$1(doc, normalizeOptions$1(opts)); } }; function clean(ast, newObj, parent) { ["raw", // front-matter "raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(name => { delete newObj[name]; }); if (ast.type === "yaml") { delete newObj.value; } // --insert-pragma if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0 && ( // first non-front-matter comment parent.nodes[0] === ast || (parent.nodes[0].type === "yaml" || parent.nodes[0].type === "toml") && parent.nodes[1] === ast)) { /** * something * * @format */ delete newObj.text; // standalone pragma if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) { return null; } } if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") { delete newObj.value; } if (ast.type === "css-rule") { delete newObj.params; } if (ast.type === "selector-combinator") { newObj.value = newObj.value.replace(/\s+/g, " "); } if (ast.type === "media-feature") { newObj.value = newObj.value.replace(/ /g, ""); } if (ast.type === "value-word" && (ast.isColor && ast.isHex || ["initial", "inherit", "unset", "revert"].includes(newObj.value.replace().toLowerCase())) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || ast.type === "selector-pseudo") { newObj.value = newObj.value.toLowerCase(); } if (ast.type === "css-decl") { newObj.prop = newObj.prop.toLowerCase(); } if (ast.type === "css-atrule" || ast.type === "css-import") { newObj.name = newObj.name.toLowerCase(); } if (ast.type === "value-number") { newObj.unit = newObj.unit.toLowerCase(); } if ((ast.type === "media-feature" || ast.type === "media-keyword" || ast.type === "media-type" || ast.type === "media-unknown" || ast.type === "media-url" || ast.type === "media-value" || ast.type === "selector-attribute" || ast.type === "selector-string" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "value-string") && newObj.value) { newObj.value = cleanCSSStrings(newObj.value); } if (ast.type === "selector-attribute") { newObj.attribute = newObj.attribute.trim(); if (newObj.namespace) { if (typeof newObj.namespace === "string") { newObj.namespace = newObj.namespace.trim(); if (newObj.namespace.length === 0) { newObj.namespace = true; } } } if (newObj.value) { newObj.value = newObj.value.trim().replace(/^['"]|['"]$/g, ""); delete newObj.quoted; } } if ((ast.type === "media-value" || ast.type === "media-type" || ast.type === "value-number" || ast.type === "selector-root-invalid" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "selector-tag") && newObj.value) { newObj.value = newObj.value.replace(/([\d.eE+-]+)([a-zA-Z]*)/g, (match, numStr, unit) => { const num = Number(numStr); return isNaN(num) ? match : num + unit.toLowerCase(); }); } if (ast.type === "selector-tag") { const lowercasedValue = ast.value.toLowerCase(); if (["from", "to"].includes(lowercasedValue)) { newObj.value = lowercasedValue; } } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func` if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") { delete newObj.value; } // Workaround for SCSS nested properties if (ast.type === "selector-unknown") { delete newObj.value; } } function cleanCSSStrings(value) { return value.replace(/'/g, '"').replace(/\\([^a-fA-F\d])/g, "$1"); } var clean_1 = clean; const { builders: { hardline: hardline$3, literalline: literalline$1, concat: concat$4, markAsRoot: markAsRoot$1 }, utils: { mapDoc: mapDoc$1 } } = document; function embed(path, print, textToDoc /*, options */ ) { const node = path.getValue(); if (node.type === "yaml") { return markAsRoot$1(concat$4(["---", hardline$3, node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, { parser: "yaml" })) : "", "---", hardline$3])); } return null; function replaceNewlinesWithLiterallines(doc) { return mapDoc$1(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$4(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$1)) : currentDoc); } } var embed_1 = embed; const detectNewline = string => { if (typeof string !== 'string') { throw new TypeError('Expected a string'); } const newlines = string.match(/(?:\r?\n)/g) || []; if (newlines.length === 0) { return; } const crlf = newlines.filter(newline => newline === '\r\n').length; const lf = newlines.length - crlf; return crlf > lf ? '\r\n' : '\n'; }; var detectNewline_1 = detectNewline; var graceful = string => typeof string === 'string' && detectNewline(string) || '\n'; detectNewline_1.graceful = graceful; var build = createCommonjsModule(function (module, exports) { Object.defineProperty(exports, '__esModule', { value: true }); exports.extract = extract; exports.strip = strip; exports.parse = parse; exports.parseWithComments = parseWithComments; exports.print = print; function _os() { const data = require$$0$1; _os = function _os() { return data; }; return data; } function _detectNewline() { const data = _interopRequireDefault(detectNewline_1); _detectNewline = function _detectNewline() { return data; }; return data; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ const commentEndRe = /\*\/$/; const commentStartRe = /^\/\*\*/; const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/; const lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g; const ltrimNewlineRe = /^(\r?\n)+/; const multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g; const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g; const stringStartRe = /(\r?\n|^) *\* ?/g; function extract(contents) { const match = contents.match(docblockRe); return match ? match[0].trimLeft() : ''; } function strip(contents) { const match = contents.match(docblockRe); return match && match[0] ? contents.substring(match[0].length) : contents; } function parse(docblock) { return parseWithComments(docblock).pragmas; } function parseWithComments(docblock) { const line = (0, _detectNewline().default)(docblock) || _os().EOL; docblock = docblock.replace(commentStartRe, '').replace(commentEndRe, '').replace(stringStartRe, '$1'); // Normalize multi-line directives let prev = ''; while (prev !== docblock) { prev = docblock; docblock = docblock.replace(multilineRe, "".concat(line, "$1 $2").concat(line)); } docblock = docblock.replace(ltrimNewlineRe, '').trimRight(); const result = Object.create(null); const comments = docblock.replace(propertyRe, '').replace(ltrimNewlineRe, '').trimRight(); let match; while (match = propertyRe.exec(docblock)) { // strip linecomments from pragmas const nextPragma = match[2].replace(lineCommentRe, ''); if (typeof result[match[1]] === 'string' || Array.isArray(result[match[1]])) { result[match[1]] = [].concat(result[match[1]], nextPragma); } else { result[match[1]] = nextPragma; } } return { comments, pragmas: result }; } function print({ comments = '', pragmas = {} }) { const line = (0, _detectNewline().default)(comments) || _os().EOL; const head = '/**'; const start = ' *'; const tail = ' */'; const keys = Object.keys(pragmas); const printedObject = keys.map(key => printKeyValues(key, pragmas[key])).reduce((arr, next) => arr.concat(next), []).map(keyValue => start + ' ' + keyValue + line).join(''); if (!comments) { if (keys.length === 0) { return ''; } if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) { const value = pragmas[keys[0]]; return "".concat(head, " ").concat(printKeyValues(keys[0], value)[0]).concat(tail); } } const printedComments = comments.split(line).map(textLine => "".concat(start, " ").concat(textLine)).join(line) + line; return head + line + (comments ? printedComments : '') + (comments && keys.length ? start + line : '') + printedObject + tail; } function printKeyValues(key, valueOrArray) { return [].concat(valueOrArray).map(value => "@".concat(key, " ").concat(value).trim()); } }); unwrapExports(build); var build_1 = build.extract; var build_2 = build.strip; var build_3 = build.parse; var build_4 = build.parseWithComments; var build_5 = build.print; function hasPragma(text) { const pragmas = Object.keys(build.parse(build.extract(text))); return pragmas.includes("prettier") || pragmas.includes("format"); } function insertPragma(text) { const parsedDocblock = build.parseWithComments(build.extract(text)); const pragmas = Object.assign({ format: "" }, parsedDocblock.pragmas); const newDocblock = build.print({ pragmas, comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines }).replace(/(\r\n|\r)/g, "\n"); // normalise newlines (mitigate use of os.EOL by jest-docblock) const strippedText = build.strip(text); const separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n"; return newDocblock + separatingNewlines + strippedText; } var pragma = { hasPragma, insertPragma }; const DELIMITER_MAP = { "---": "yaml", "+++": "toml" }; function parse$1(text) { const delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp$2).join("|"); const match = text.match( // trailing spaces after delimiters are allowed new RegExp("^(".concat(delimiterRegex, ")[^\\n\\S]*\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)"))); if (match === null) { return { frontMatter: null, content: text }; } const [raw, delimiter, value] = match; return { frontMatter: { type: DELIMITER_MAP[delimiter], value, raw: raw.replace(/\n$/, "") }, content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length) }; } var frontMatter = parse$1; function hasPragma$1(text) { return pragma.hasPragma(frontMatter(text).content); } function insertPragma$1(text) { const { frontMatter: frontMatter$1, content } = frontMatter(text); return (frontMatter$1 ? frontMatter$1.raw + "\n\n" : "") + pragma.insertPragma(content); } var pragma$1 = { hasPragma: hasPragma$1, insertPragma: insertPragma$1 }; var lineColumnToIndex = function lineColumnToIndex(lineColumn, text) { let index = 0; for (let i = 0; i < lineColumn.line - 1; ++i) { index = text.indexOf("\n", index) + 1; if (index === -1) { return -1; } } return index + lineColumn.column; }; const { getLast: getLast$1, skipEverythingButNewLine: skipEverythingButNewLine$2 } = util$1; function calculateLocStart(node, text) { if (node.source) { return lineColumnToIndex(node.source.start, text) - 1; } return null; } function calculateLocEnd(node, text) { if (node.type === "css-comment" && node.inline) { return skipEverythingButNewLine$2(text, node.source.startOffset); } const endNode = node.nodes && getLast$1(node.nodes); if (endNode && node.source && !node.source.end) { node = endNode; } if (node.source && node.source.end) { return lineColumnToIndex(node.source.end, text); } return null; } function calculateLoc(node, text) { if (node && typeof node === "object") { if (node.source) { node.source.startOffset = calculateLocStart(node, text); node.source.endOffset = calculateLocEnd(node, text); } for (const key in node) { calculateLoc(node[key], text); } } } /** * Workaround for a bug: quotes in inline comments corrupt loc data of subsequent nodes. * This function replaces the quotes with U+FFFE and U+FFFF. Later, when the comments are printed, * their content is extracted from the original text or restored by replacing the placeholder * characters back with quotes. * - https://github.com/prettier/prettier/issues/7780 * - https://github.com/shellscape/postcss-less/issues/145 * - About noncharacters (U+FFFE and U+FFFF): http://www.unicode.org/faq/private_use.html#nonchar1 * @param text {string} */ function replaceQuotesInInlineComments(text) { /** @typedef { 'initial' | 'single-quotes' | 'double-quotes' | 'url' | 'comment-block' | 'comment-inline' } State */ /** @type {State} */ let state = "initial"; /** @type {State} */ let stateToReturnFromQuotes = "initial"; let inlineCommentStartIndex; let inlineCommentContainsQuotes = false; const inlineCommentsToReplace = []; for (let i = 0; i < text.length; i++) { const c = text[i]; switch (state) { case "initial": if (c === "'") { state = "single-quotes"; continue; } if (c === '"') { state = "double-quotes"; continue; } if ((c === "u" || c === "U") && text.slice(i, i + 4).toLowerCase() === "url(") { state = "url"; i += 3; continue; } if (c === "*" && text[i - 1] === "/") { state = "comment-block"; continue; } if (c === "/" && text[i - 1] === "/") { state = "comment-inline"; inlineCommentStartIndex = i - 1; continue; } continue; case "single-quotes": if (c === "'" && text[i - 1] !== "\\") { state = stateToReturnFromQuotes; stateToReturnFromQuotes = "initial"; } if (c === "\n" || c === "\r") { return text; // invalid input } continue; case "double-quotes": if (c === '"' && text[i - 1] !== "\\") { state = stateToReturnFromQuotes; stateToReturnFromQuotes = "initial"; } if (c === "\n" || c === "\r") { return text; // invalid input } continue; case "url": if (c === ")") { state = "initial"; } if (c === "\n" || c === "\r") { return text; // invalid input } if (c === "'") { state = "single-quotes"; stateToReturnFromQuotes = "url"; continue; } if (c === '"') { state = "double-quotes"; stateToReturnFromQuotes = "url"; continue; } continue; case "comment-block": if (c === "/" && text[i - 1] === "*") { state = "initial"; } continue; case "comment-inline": if (c === '"' || c === "'") { inlineCommentContainsQuotes = true; } if (c === "\n" || c === "\r") { if (inlineCommentContainsQuotes) { inlineCommentsToReplace.push([inlineCommentStartIndex, i]); } state = "initial"; inlineCommentContainsQuotes = false; } continue; } } for (const [start, end] of inlineCommentsToReplace) { text = text.slice(0, start) + text.slice(start, end).replace(/'/g, "\ufffe").replace(/"/g, "\uffff") + text.slice(end); } return text; } function restoreQuotesInInlineComments(text) { return text.replace(/\ufffe/g, "'").replace(/\uffff/g, '"'); } var loc$1 = { calculateLoc, replaceQuotesInInlineComments, restoreQuotesInInlineComments }; const colorAdjusterFunctions = ["red", "green", "blue", "alpha", "a", "rgb", "hue", "h", "saturation", "s", "lightness", "l", "whiteness", "w", "blackness", "b", "tint", "shade", "blend", "blenda", "contrast", "hsl", "hsla", "hwb", "hwba"]; function getAncestorCounter(path, typeOrTypes) { const types = [].concat(typeOrTypes); let counter = -1; let ancestorNode; while (ancestorNode = path.getParentNode(++counter)) { if (types.includes(ancestorNode.type)) { return counter; } } return -1; } function getAncestorNode(path, typeOrTypes) { const counter = getAncestorCounter(path, typeOrTypes); return counter === -1 ? null : path.getParentNode(counter); } function getPropOfDeclNode(path) { const declAncestorNode = getAncestorNode(path, "css-decl"); return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase(); } function isSCSS(parser, text) { const hasExplicitParserChoice = parser === "less" || parser === "scss"; const IS_POSSIBLY_SCSS = /(\w\s*:\s*[^}:]+|#){|@import[^\n]+(?:url|,)/; return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text); } function isWideKeywords(value) { return ["initial", "inherit", "unset", "revert"].includes(value.toLowerCase()); } function isKeyframeAtRuleKeywords(path, value) { const atRuleAncestorNode = getAncestorNode(path, "css-atrule"); return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].includes(value.toLowerCase()); } function maybeToLowerCase(value) { return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase(); } function insideValueFunctionNode(path, functionName) { const funcAncestorNode = getAncestorNode(path, "value-func"); return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName; } function insideICSSRuleNode(path) { const ruleAncestorNode = getAncestorNode(path, "css-rule"); return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export")); } function insideAtRuleNode(path, atRuleNameOrAtRuleNames) { const atRuleNames = [].concat(atRuleNameOrAtRuleNames); const atRuleAncestorNode = getAncestorNode(path, "css-atrule"); return atRuleAncestorNode && atRuleNames.includes(atRuleAncestorNode.name.toLowerCase()); } function insideURLFunctionInImportAtRuleNode(path) { const node = path.getValue(); const atRuleAncestorNode = getAncestorNode(path, "css-atrule"); return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2; } function isURLFunctionNode(node) { return node.type === "value-func" && node.value.toLowerCase() === "url"; } function isLastNode(path, node) { const parentNode = path.getParentNode(); if (!parentNode) { return false; } const { nodes } = parentNode; return nodes && nodes.indexOf(node) === nodes.length - 1; } function isDetachedRulesetDeclarationNode(node) { // If a Less file ends up being parsed with the SCSS parser, Less // variable declarations will be parsed as atrules with names ending // with a colon, so keep the original case then. if (!node.selector) { return false; } return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value); } function isForKeywordNode(node) { return node.type === "value-word" && ["from", "through", "end"].includes(node.value); } function isIfElseKeywordNode(node) { return node.type === "value-word" && ["and", "or", "not"].includes(node.value); } function isEachKeywordNode(node) { return node.type === "value-word" && node.value === "in"; } function isMultiplicationNode(node) { return node.type === "value-operator" && node.value === "*"; } function isDivisionNode(node) { return node.type === "value-operator" && node.value === "/"; } function isAdditionNode(node) { return node.type === "value-operator" && node.value === "+"; } function isSubtractionNode(node) { return node.type === "value-operator" && node.value === "-"; } function isModuloNode(node) { return node.type === "value-operator" && node.value === "%"; } function isMathOperatorNode(node) { return isMultiplicationNode(node) || isDivisionNode(node) || isAdditionNode(node) || isSubtractionNode(node) || isModuloNode(node); } function isEqualityOperatorNode(node) { return node.type === "value-word" && ["==", "!="].includes(node.value); } function isRelationalOperatorNode(node) { return node.type === "value-word" && ["<", ">", "<=", ">="].includes(node.value); } function isSCSSControlDirectiveNode(node) { return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].includes(node.name); } function isSCSSNestedPropertyNode(node) { if (!node.selector) { return false; } return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":"); } function isDetachedRulesetCallNode(node) { return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params); } function isTemplatePlaceholderNode(node) { return node.name.startsWith("prettier-placeholder"); } function isTemplatePropNode(node) { return node.prop.startsWith("@prettier-placeholder"); } function isPostcssSimpleVarNode(currentNode, nextNode) { return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before; } function hasComposesNode(node) { return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes"; } function hasParensAroundNode(node) { return node.value && node.value.group && node.value.group.group && node.value.group.group.type === "value-paren_group" && node.value.group.group.open !== null && node.value.group.group.close !== null; } function hasEmptyRawBefore(node) { return node.raws && node.raws.before === ""; } function isKeyValuePairNode(node) { return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon"; } function isKeyValuePairInParenGroupNode(node) { return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode(node.groups[0]); } function isSCSSMapItemNode(path) { const node = path.getValue(); // Ignore empty item (i.e. `$key: ()`) if (node.groups.length === 0) { return false; } const parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`) if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) { return false; } const declNode = getAncestorNode(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`) if (declNode && declNode.prop && declNode.prop.startsWith("$")) { return true; } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`) if (isKeyValuePairInParenGroupNode(parentParentNode)) { return true; } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`) if (parentParentNode.type === "value-func") { return true; } return false; } function isInlineValueCommentNode(node) { return node.type === "value-comment" && node.inline; } function isHashNode(node) { return node.type === "value-word" && node.value === "#"; } function isLeftCurlyBraceNode(node) { return node.type === "value-word" && node.value === "{"; } function isRightCurlyBraceNode(node) { return node.type === "value-word" && node.value === "}"; } function isWordNode(node) { return ["value-word", "value-atword"].includes(node.type); } function isColonNode(node) { return node.type === "value-colon"; } function isMediaAndSupportsKeywords(node) { return node.value && ["not", "and", "or"].includes(node.value.toLowerCase()); } function isColorAdjusterFuncNode(node) { if (node.type !== "value-func") { return false; } return colorAdjusterFunctions.includes(node.value.toLowerCase()); } // TODO: only check `less` when we don't use `less` to parse `css` function isLessParser(options) { return options.parser === "css" || options.parser === "less"; } function lastLineHasInlineComment(text) { return /\/\//.test(text.split(/[\r\n]/).pop()); } var utils$2 = { getAncestorCounter, getAncestorNode, getPropOfDeclNode, maybeToLowerCase, insideValueFunctionNode, insideICSSRuleNode, insideAtRuleNode, insideURLFunctionInImportAtRuleNode, isKeyframeAtRuleKeywords, isWideKeywords, isSCSS, isLastNode, isLessParser, isSCSSControlDirectiveNode, isDetachedRulesetDeclarationNode, isRelationalOperatorNode, isEqualityOperatorNode, isMultiplicationNode, isDivisionNode, isAdditionNode, isSubtractionNode, isModuloNode, isMathOperatorNode, isEachKeywordNode, isForKeywordNode, isURLFunctionNode, isIfElseKeywordNode, hasComposesNode, hasParensAroundNode, hasEmptyRawBefore, isSCSSNestedPropertyNode, isDetachedRulesetCallNode, isTemplatePlaceholderNode, isTemplatePropNode, isPostcssSimpleVarNode, isKeyValuePairNode, isKeyValuePairInParenGroupNode, isSCSSMapItemNode, isInlineValueCommentNode, isHashNode, isLeftCurlyBraceNode, isRightCurlyBraceNode, isWordNode, isColonNode, isMediaAndSupportsKeywords, isColorAdjusterFuncNode, lastLineHasInlineComment }; const { insertPragma: insertPragma$2 } = pragma$1; const { printNumber: printNumber$1, printString: printString$1, hasIgnoreComment: hasIgnoreComment$1, hasNewline: hasNewline$3 } = util$1; const { isNextLineEmpty: isNextLineEmpty$2 } = utilShared; const { restoreQuotesInInlineComments: restoreQuotesInInlineComments$1 } = loc$1; const { builders: { concat: concat$5, join: join$2, line: line$2, hardline: hardline$4, softline: softline$1, group: group$1, fill: fill$2, indent: indent$2, dedent: dedent$1, ifBreak: ifBreak$1 }, utils: { removeLines: removeLines$1 } } = document; const { getAncestorNode: getAncestorNode$1, getPropOfDeclNode: getPropOfDeclNode$1, maybeToLowerCase: maybeToLowerCase$1, insideValueFunctionNode: insideValueFunctionNode$1, insideICSSRuleNode: insideICSSRuleNode$1, insideAtRuleNode: insideAtRuleNode$1, insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1, isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1, isWideKeywords: isWideKeywords$1, isSCSS: isSCSS$1, isLastNode: isLastNode$1, isLessParser: isLessParser$1, isSCSSControlDirectiveNode: isSCSSControlDirectiveNode$1, isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode$1, isRelationalOperatorNode: isRelationalOperatorNode$1, isEqualityOperatorNode: isEqualityOperatorNode$1, isMultiplicationNode: isMultiplicationNode$1, isDivisionNode: isDivisionNode$1, isAdditionNode: isAdditionNode$1, isSubtractionNode: isSubtractionNode$1, isMathOperatorNode: isMathOperatorNode$1, isEachKeywordNode: isEachKeywordNode$1, isForKeywordNode: isForKeywordNode$1, isURLFunctionNode: isURLFunctionNode$1, isIfElseKeywordNode: isIfElseKeywordNode$1, hasComposesNode: hasComposesNode$1, hasParensAroundNode: hasParensAroundNode$1, hasEmptyRawBefore: hasEmptyRawBefore$1, isKeyValuePairNode: isKeyValuePairNode$1, isDetachedRulesetCallNode: isDetachedRulesetCallNode$1, isTemplatePlaceholderNode: isTemplatePlaceholderNode$1, isTemplatePropNode: isTemplatePropNode$1, isPostcssSimpleVarNode: isPostcssSimpleVarNode$1, isSCSSMapItemNode: isSCSSMapItemNode$1, isInlineValueCommentNode: isInlineValueCommentNode$1, isHashNode: isHashNode$1, isLeftCurlyBraceNode: isLeftCurlyBraceNode$1, isRightCurlyBraceNode: isRightCurlyBraceNode$1, isWordNode: isWordNode$1, isColonNode: isColonNode$1, isMediaAndSupportsKeywords: isMediaAndSupportsKeywords$1, isColorAdjusterFuncNode: isColorAdjusterFuncNode$1, lastLineHasInlineComment: lastLineHasInlineComment$1 } = utils$2; function shouldPrintComma(options) { switch (options.trailingComma) { case "all": case "es5": return true; case "none": default: return false; } } function genericPrint(path, options, print) { const node = path.getValue(); /* istanbul ignore if */ if (!node) { return ""; } if (typeof node === "string") { return node; } switch (node.type) { case "yaml": case "toml": return concat$5([node.raw, hardline$4]); case "css-root": { const nodes = printNodeSequence(path, options, print); if (nodes.parts.length) { return concat$5([nodes, options.__isHTMLStyleAttribute ? "" : hardline$4]); } return nodes; } case "css-comment": { const isInlineComment = node.inline || node.raws.inline; const text = options.originalText.slice(options.locStart(node), options.locEnd(node)); return isInlineComment ? text.trimEnd() : text; } case "css-rule": { return concat$5([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$5([node.selector && node.selector.type === "selector-unknown" && lastLineHasInlineComment$1(node.selector.value) ? line$2 : " ", "{", node.nodes.length > 0 ? indent$2(concat$5([hardline$4, printNodeSequence(path, options, print)])) : "", hardline$4, "}", isDetachedRulesetDeclarationNode$1(node) ? ";" : ""]) : ";"]); } case "css-decl": { const parentNode = path.getParentNode(); return concat$5([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode$1(path) ? node.prop : maybeToLowerCase$1(node.prop), node.raws.between.trim() === ":" ? ":" : node.raws.between.trim(), node.extend ? "" : " ", hasComposesNode$1(node) ? removeLines$1(path.call(print, "value")) : path.call(print, "value"), node.raws.important ? node.raws.important.replace(/\s*!\s*important/i, " !important") : node.important ? " !important" : "", node.raws.scssDefault ? node.raws.scssDefault.replace(/\s*!default/i, " !default") : node.scssDefault ? " !default" : "", node.raws.scssGlobal ? node.raws.scssGlobal.replace(/\s*!global/i, " !global") : node.scssGlobal ? " !global" : "", node.nodes ? concat$5([" {", indent$2(concat$5([softline$1, printNodeSequence(path, options, print)])), softline$1, "}"]) : isTemplatePropNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : ";"]); } case "css-atrule": { const parentNode = path.getParentNode(); const isTemplatePlaceholderNodeWithoutSemiColon = isTemplatePlaceholderNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";"; if (isLessParser$1(options)) { if (node.mixin) { return concat$5([path.call(print, "selector"), node.important ? " !important" : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); } if (node.function) { return concat$5([node.name, concat$5([path.call(print, "params")]), isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); } if (node.variable) { return concat$5(["@", node.name, ": ", node.value ? concat$5([path.call(print, "value")]) : "", node.raws.between.trim() ? node.raws.between.trim() + " " : "", node.nodes ? concat$5(["{", indent$2(concat$5([node.nodes.length > 0 ? softline$1 : "", printNodeSequence(path, options, print)])), softline$1, "}"]) : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); } } return concat$5(["@", // If a Less file ends up being parsed with the SCSS parser, Less // variable declarations will be parsed as at-rules with names ending // with a colon, so keep the original case then. isDetachedRulesetCallNode$1(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase$1(node.name), node.params ? concat$5([isDetachedRulesetCallNode$1(node) ? "" : isTemplatePlaceholderNode$1(node) ? node.raws.afterName === "" ? "" : node.name.endsWith(":") ? " " : /^\s*\n\s*\n/.test(node.raws.afterName) ? concat$5([hardline$4, hardline$4]) : /^\s*\n/.test(node.raws.afterName) ? hardline$4 : " " : " ", path.call(print, "params")]) : "", node.selector ? indent$2(concat$5([" ", path.call(print, "selector")])) : "", node.value ? group$1(concat$5([" ", path.call(print, "value"), isSCSSControlDirectiveNode$1(node) ? hasParensAroundNode$1(node) ? " " : line$2 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$5([isSCSSControlDirectiveNode$1(node) ? "" : " ", "{", indent$2(concat$5([node.nodes.length > 0 ? softline$1 : "", printNodeSequence(path, options, print)])), softline$1, "}"]) : isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); } // postcss-media-query-parser case "media-query-list": { const parts = []; path.each(childPath => { const node = childPath.getValue(); if (node.type === "media-query" && node.value === "") { return; } parts.push(childPath.call(print)); }, "nodes"); return group$1(indent$2(join$2(line$2, parts))); } case "media-query": { return concat$5([join$2(" ", path.map(print, "nodes")), isLastNode$1(path, node) ? "" : ","]); } case "media-type": { return adjustNumbers(adjustStrings(node.value, options)); } case "media-feature-expression": { if (!node.nodes) { return node.value; } return concat$5(["(", concat$5(path.map(print, "nodes")), ")"]); } case "media-feature": { return maybeToLowerCase$1(adjustStrings(node.value.replace(/ +/g, " "), options)); } case "media-colon": { return concat$5([node.value, " "]); } case "media-value": { return adjustNumbers(adjustStrings(node.value, options)); } case "media-keyword": { return adjustStrings(node.value, options); } case "media-url": { return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options); } case "media-unknown": { return node.value; } // postcss-selector-parser case "selector-root": { return group$1(concat$5([insideAtRuleNode$1(path, "custom-selector") ? concat$5([getAncestorNode$1(path, "css-atrule").customSelector, line$2]) : "", join$2(concat$5([",", insideAtRuleNode$1(path, ["extend", "custom-selector", "nest"]) ? line$2 : hardline$4]), path.map(print, "nodes"))])); } case "selector-selector": { return group$1(indent$2(concat$5(path.map(print, "nodes")))); } case "selector-comment": { return node.value; } case "selector-string": { return adjustStrings(node.value, options); } case "selector-tag": { const parentNode = path.getParentNode(); const index = parentNode && parentNode.nodes.indexOf(node); const prevNode = index && parentNode.nodes[index - 1]; return concat$5([node.namespace ? concat$5([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isKeyframeAtRuleKeywords$1(path, node.value) ? node.value.toLowerCase() : node.value)]); } case "selector-id": { return concat$5(["#", node.value]); } case "selector-class": { return concat$5([".", adjustNumbers(adjustStrings(node.value, options))]); } case "selector-attribute": { return concat$5(["[", node.namespace ? concat$5([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.attribute.trim(), node.operator ? node.operator : "", node.value ? quoteAttributeValue(adjustStrings(node.value.trim(), options), options) : "", node.insensitive ? " i" : "", "]"]); } case "selector-combinator": { if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") { const parentNode = path.getParentNode(); const leading = parentNode.type === "selector-selector" && parentNode.nodes[0] === node ? "" : line$2; return concat$5([leading, node.value, isLastNode$1(path, node) ? "" : " "]); } const leading = node.value.trim().startsWith("(") ? line$2 : ""; const value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$2; return concat$5([leading, value]); } case "selector-universal": { return concat$5([node.namespace ? concat$5([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]); } case "selector-pseudo": { return concat$5([maybeToLowerCase$1(node.value), node.nodes && node.nodes.length > 0 ? concat$5(["(", join$2(", ", path.map(print, "nodes")), ")"]) : ""]); } case "selector-nesting": { return node.value; } case "selector-unknown": { const ruleAncestorNode = getAncestorNode$1(path, "css-rule"); // Nested SCSS property if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) { return adjustNumbers(adjustStrings(maybeToLowerCase$1(node.value), options)); } // originalText has to be used for Less, see replaceQuotesInInlineComments in loc.js const parentNode = path.getParentNode(); if (parentNode.raws && parentNode.raws.selector) { const start = options.locStart(parentNode); const end = start + parentNode.raws.selector.length; return options.originalText.slice(start, end).trim(); } return node.value; } // postcss-values-parser case "value-value": case "value-root": { return path.call(print, "group"); } case "value-comment": { return concat$5([node.inline ? "//" : "/*", // see replaceQuotesInInlineComments in loc.js // value-* nodes don't have correct location data, so we have to rely on placeholder characters. restoreQuotesInInlineComments$1(node.value), node.inline ? "" : "*/"]); } case "value-comma_group": { const parentNode = path.getParentNode(); const parentParentNode = path.getParentNode(1); const declAncestorProp = getPropOfDeclNode$1(path); const isGridValue = declAncestorProp && parentNode.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template")); const atRuleAncestorNode = getAncestorNode$1(path, "css-atrule"); const isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode$1(atRuleAncestorNode); const printed = path.map(print, "groups"); const parts = []; const insideURLFunction = insideValueFunctionNode$1(path, "url"); let insideSCSSInterpolationInString = false; let didBreak = false; for (let i = 0; i < node.groups.length; ++i) { parts.push(printed[i]); const iPrevNode = node.groups[i - 1]; const iNode = node.groups[i]; const iNextNode = node.groups[i + 1]; const iNextNextNode = node.groups[i + 2]; if (insideURLFunction) { if (iNextNode && isAdditionNode$1(iNextNode) || isAdditionNode$1(iNode)) { parts.push(" "); } continue; } // Ignore after latest node (i.e. before semicolon) if (!iNextNode) { continue; } // styled.div` background: var(--${one}); ` if (!iPrevNode && iNode.value === "--" && iNextNode.type === "value-atword") { continue; } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`) const isStartSCSSInterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{"); const isEndingSCSSInterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}"); if (isStartSCSSInterpolationInString || isEndingSCSSInterpolationInString) { insideSCSSInterpolationInString = !insideSCSSInterpolationInString; continue; } if (insideSCSSInterpolationInString) { continue; } // Ignore colon (i.e. `:`) if (isColonNode$1(iNode) || isColonNode$1(iNextNode)) { continue; } // Ignore `@` in Less (i.e. `@@var;`) if (iNode.type === "value-atword" && iNode.value === "") { continue; } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`) if (iNode.value === "~") { continue; } // Ignore escape `\` if (iNode.value && iNode.value.includes("\\") && iNextNode && iNextNode.type !== "value-comment") { continue; } // Ignore escaped `/` if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") { continue; } // Ignore `\` (i.e. `$variable: \@small;`) if (iNode.value === "\\") { continue; } // Ignore `$$` (i.e. `background-color: $$(style)Color;`) if (isPostcssSimpleVarNode$1(iNode, iNextNode)) { continue; } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`) if (isHashNode$1(iNode) || isLeftCurlyBraceNode$1(iNode) || isRightCurlyBraceNode$1(iNextNode) || isLeftCurlyBraceNode$1(iNextNode) && hasEmptyRawBefore$1(iNextNode) || isRightCurlyBraceNode$1(iNode) && hasEmptyRawBefore$1(iNextNode)) { continue; } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`) if (iNode.value === "--" && isHashNode$1(iNextNode)) { continue; } // Formatting math operations const isMathOperator = isMathOperatorNode$1(iNode); const isNextMathOperator = isMathOperatorNode$1(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`) // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`) if ((isMathOperator && isHashNode$1(iNextNode) || isNextMathOperator && isRightCurlyBraceNode$1(iNode)) && hasEmptyRawBefore$1(iNextNode)) { continue; } // Print spaces before and after addition and subtraction math operators as is in `calc` function // due to the fact that it is not valid syntax // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`) if (insideValueFunctionNode$1(path, "calc") && (isAdditionNode$1(iNode) || isAdditionNode$1(iNextNode) || isSubtractionNode$1(iNode) || isSubtractionNode$1(iNextNode)) && hasEmptyRawBefore$1(iNextNode)) { continue; } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`) // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is. const isColorAdjusterNode = (isAdditionNode$1(iNode) || isSubtractionNode$1(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode$1(parentParentNode) && !hasEmptyRawBefore$1(iNextNode); const requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode$1(iNextNextNode) || iNode.type === "value-func" || isWordNode$1(iNode); const requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode$1(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode$1(iPrevNode); // Formatting `/`, `+`, `-` sign if (!(isMultiplicationNode$1(iNextNode) || isMultiplicationNode$1(iNode)) && !insideValueFunctionNode$1(path, "calc") && !isColorAdjusterNode && (isDivisionNode$1(iNextNode) && !requireSpaceBeforeOperator || isDivisionNode$1(iNode) && !requireSpaceAfterOperator || isAdditionNode$1(iNextNode) && !requireSpaceBeforeOperator || isAdditionNode$1(iNode) && !requireSpaceAfterOperator || isSubtractionNode$1(iNextNode) || isSubtractionNode$1(iNode)) && (hasEmptyRawBefore$1(iNextNode) || isMathOperator && (!iPrevNode || iPrevNode && isMathOperatorNode$1(iPrevNode)))) { continue; } // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`) if (isInlineValueCommentNode$1(iNode)) { parts.push(hardline$4); continue; } // Handle keywords in SCSS control directive if (isControlDirective && (isEqualityOperatorNode$1(iNextNode) || isRelationalOperatorNode$1(iNextNode) || isIfElseKeywordNode$1(iNextNode) || isEachKeywordNode$1(iNode) || isForKeywordNode$1(iNode))) { parts.push(" "); continue; } // At-rule `namespace` should be in one line if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") { parts.push(" "); continue; } // Formatting `grid` property if (isGridValue) { if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) { parts.push(hardline$4); didBreak = true; } else { parts.push(" "); } continue; } // Add `space` before next math operation // Note: `grip` property have `/` delimiter and it is not math operation, so // `grid` property handles above if (isNextMathOperator) { parts.push(" "); continue; } // Be default all values go through `line` parts.push(line$2); } if (didBreak) { parts.unshift(hardline$4); } if (isControlDirective) { return group$1(indent$2(concat$5(parts))); } // Indent is not needed for import url when url is very long // and node has two groups // when type is value-comma_group // example @import url("verylongurl") projection,tv if (insideURLFunctionInImportAtRuleNode$1(path)) { return group$1(fill$2(parts)); } return group$1(indent$2(fill$2(parts))); } case "value-paren_group": { const parentNode = path.getParentNode(); if (parentNode && isURLFunctionNode$1(parentNode) && (node.groups.length === 1 || node.groups.length > 0 && node.groups[0].type === "value-comma_group" && node.groups[0].groups.length > 0 && node.groups[0].groups[0].type === "value-word" && node.groups[0].groups[0].value.startsWith("data:"))) { return concat$5([node.open ? path.call(print, "open") : "", join$2(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]); } if (!node.open) { const printed = path.map(print, "groups"); const res = []; for (let i = 0; i < printed.length; i++) { if (i !== 0) { res.push(concat$5([",", line$2])); } res.push(printed[i]); } return group$1(indent$2(fill$2(res))); } const isSCSSMapItem = isSCSSMapItemNode$1(path); const lastItem = node.groups[node.groups.length - 1]; const isLastItemComment = lastItem && lastItem.type === "value-comment"; return group$1(concat$5([node.open ? path.call(print, "open") : "", indent$2(concat$5([softline$1, join$2(concat$5([",", line$2]), path.map(childPath => { const node = childPath.getValue(); const printed = print(childPath); // Key/Value pair in open paren already indented if (isKeyValuePairNode$1(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") { printed.contents.contents.parts[1] = group$1(printed.contents.contents.parts[1]); return group$1(dedent$1(printed)); } return printed; }, "groups"))])), ifBreak$1(!isLastItemComment && isSCSS$1(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma(options) ? "," : ""), softline$1, node.close ? path.call(print, "close") : ""]), { shouldBreak: isSCSSMapItem }); } case "value-func": { return concat$5([node.value, insideAtRuleNode$1(path, "supports") && isMediaAndSupportsKeywords$1(node) ? " " : "", path.call(print, "group")]); } case "value-paren": { return node.value; } case "value-number": { return concat$5([printCssNumber(node.value), maybeToLowerCase$1(node.unit)]); } case "value-operator": { return node.value; } case "value-word": { if (node.isColor && node.isHex || isWideKeywords$1(node.value)) { return node.value.toLowerCase(); } return node.value; } case "value-colon": { return concat$5([node.value, // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`) insideValueFunctionNode$1(path, "url") ? "" : line$2]); } case "value-comma": { return concat$5([node.value, " "]); } case "value-string": { return printString$1(node.raws.quote + node.value + node.raws.quote, options); } case "value-atword": { return concat$5(["@", node.value]); } case "value-unicode-range": { return node.value; } case "value-unknown": { return node.value; } default: /* istanbul ignore next */ throw new Error("Unknown postcss type ".concat(JSON.stringify(node.type))); } } function printNodeSequence(path, options, print) { const node = path.getValue(); const parts = []; let i = 0; path.map(pathChild => { const prevNode = node.nodes[i - 1]; if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") { const childNode = pathChild.getValue(); parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode))); } else { parts.push(pathChild.call(print)); } if (i !== node.nodes.length - 1) { if (node.nodes[i + 1].type === "css-comment" && !hasNewline$3(options.originalText, options.locStart(node.nodes[i + 1]), { backwards: true }) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml" || node.nodes[i + 1].type === "css-atrule" && node.nodes[i + 1].name === "else" && node.nodes[i].type !== "css-comment") { parts.push(" "); } else { parts.push(options.__isHTMLStyleAttribute ? line$2 : hardline$4); if (isNextLineEmpty$2(options.originalText, pathChild.getValue(), options.locEnd) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml") { parts.push(hardline$4); } } } i++; }, "nodes"); return concat$5(parts); } const STRING_REGEX$3 = /(['"])(?:(?!\1)[^\\]|\\[\s\S])*\1/g; const NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g; const STANDARD_UNIT_REGEX = /[a-zA-Z]+/g; const WORD_PART_REGEX = /[$@]?[a-zA-Z_\u0080-\uFFFF][\w\-\u0080-\uFFFF]*/g; const ADJUST_NUMBERS_REGEX = new RegExp(STRING_REGEX$3.source + "|" + "(".concat(WORD_PART_REGEX.source, ")?") + "(".concat(NUMBER_REGEX.source, ")") + "(".concat(STANDARD_UNIT_REGEX.source, ")?"), "g"); function adjustStrings(value, options) { return value.replace(STRING_REGEX$3, match => printString$1(match, options)); } function quoteAttributeValue(value, options) { const quote = options.singleQuote ? "'" : '"'; return value.includes('"') || value.includes("'") ? value : quote + value + quote; } function adjustNumbers(value) { return value.replace(ADJUST_NUMBERS_REGEX, (match, quote, wordPart, number, unit) => !wordPart && number ? printCssNumber(number) + maybeToLowerCase$1(unit || "") : match); } function printCssNumber(rawNumber) { return printNumber$1(rawNumber) // Remove trailing `.0`. .replace(/\.0(?=$|e)/, ""); } var printerPostcss = { print: genericPrint, embed: embed_1, insertPragma: insertPragma$2, hasPrettierIgnore: hasIgnoreComment$1, massageAstNode: clean_1 }; const CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js var commonOptions = { bracketSpacing: { since: "0.0.0", category: CATEGORY_COMMON, type: "boolean", default: true, description: "Print spaces between brackets.", oppositeDescription: "Do not print spaces between brackets." }, singleQuote: { since: "0.0.0", category: CATEGORY_COMMON, type: "boolean", default: false, description: "Use single quotes instead of double quotes." }, proseWrap: { since: "1.8.2", category: CATEGORY_COMMON, type: "choice", default: [{ since: "1.8.2", value: true }, { since: "1.9.0", value: "preserve" }], description: "How to wrap prose.", choices: [{ since: "1.9.0", value: "always", description: "Wrap prose if it exceeds the print width." }, { since: "1.9.0", value: "never", description: "Do not wrap prose." }, { since: "1.9.0", value: "preserve", description: "Wrap prose as-is." }] } }; var options$2 = { singleQuote: commonOptions.singleQuote }; var createLanguage = function createLanguage(linguistData, override) { const { languageId } = linguistData, rest = _objectWithoutPropertiesLoose(linguistData, ["languageId"]); return Object.assign({ linguistLanguageId: languageId }, rest, {}, override(linguistData)); }; var name$1 = "CSS"; var type = "markup"; var tmScope = "source.css"; var aceMode = "css"; var codemirrorMode = "css"; var codemirrorMimeType = "text/css"; var color = "#563d7c"; var extensions = [ ".css" ]; var languageId = 50; var CSS = { name: name$1, type: type, tmScope: tmScope, aceMode: aceMode, codemirrorMode: codemirrorMode, codemirrorMimeType: codemirrorMimeType, color: color, extensions: extensions, languageId: languageId }; var CSS$1 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name$1, type: type, tmScope: tmScope, aceMode: aceMode, codemirrorMode: codemirrorMode, codemirrorMimeType: codemirrorMimeType, color: color, extensions: extensions, languageId: languageId, 'default': CSS }); var name$2 = "PostCSS"; var type$1 = "markup"; var tmScope$1 = "source.postcss"; var group$2 = "CSS"; var extensions$1 = [ ".pcss", ".postcss" ]; var aceMode$1 = "text"; var languageId$1 = 262764437; var PostCSS = { name: name$2, type: type$1, tmScope: tmScope$1, group: group$2, extensions: extensions$1, aceMode: aceMode$1, languageId: languageId$1 }; var PostCSS$1 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name$2, type: type$1, tmScope: tmScope$1, group: group$2, extensions: extensions$1, aceMode: aceMode$1, languageId: languageId$1, 'default': PostCSS }); var name$3 = "Less"; var type$2 = "markup"; var group$3 = "CSS"; var extensions$2 = [ ".less" ]; var tmScope$2 = "source.css.less"; var aceMode$2 = "less"; var codemirrorMode$1 = "css"; var codemirrorMimeType$1 = "text/css"; var languageId$2 = 198; var Less = { name: name$3, type: type$2, group: group$3, extensions: extensions$2, tmScope: tmScope$2, aceMode: aceMode$2, codemirrorMode: codemirrorMode$1, codemirrorMimeType: codemirrorMimeType$1, languageId: languageId$2 }; var Less$1 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name$3, type: type$2, group: group$3, extensions: extensions$2, tmScope: tmScope$2, aceMode: aceMode$2, codemirrorMode: codemirrorMode$1, codemirrorMimeType: codemirrorMimeType$1, languageId: languageId$2, 'default': Less }); var name$4 = "SCSS"; var type$3 = "markup"; var tmScope$3 = "source.css.scss"; var group$4 = "CSS"; var aceMode$3 = "scss"; var codemirrorMode$2 = "css"; var codemirrorMimeType$2 = "text/x-scss"; var extensions$3 = [ ".scss" ]; var languageId$3 = 329; var SCSS = { name: name$4, type: type$3, tmScope: tmScope$3, group: group$4, aceMode: aceMode$3, codemirrorMode: codemirrorMode$2, codemirrorMimeType: codemirrorMimeType$2, extensions: extensions$3, languageId: languageId$3 }; var SCSS$1 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name$4, type: type$3, tmScope: tmScope$3, group: group$4, aceMode: aceMode$3, codemirrorMode: codemirrorMode$2, codemirrorMimeType: codemirrorMimeType$2, extensions: extensions$3, languageId: languageId$3, 'default': SCSS }); var require$$0$2 = getCjsExportFromNamespace(CSS$1); var require$$1 = getCjsExportFromNamespace(PostCSS$1); var require$$2 = getCjsExportFromNamespace(Less$1); var require$$3 = getCjsExportFromNamespace(SCSS$1); const languages = [createLanguage(require$$0$2, () => ({ since: "1.4.0", parsers: ["css"], vscodeLanguageIds: ["css"] })), createLanguage(require$$1, () => ({ since: "1.4.0", parsers: ["css"], vscodeLanguageIds: ["postcss"] })), createLanguage(require$$2, () => ({ since: "1.4.0", parsers: ["less"], vscodeLanguageIds: ["less"] })), createLanguage(require$$3, () => ({ since: "1.4.0", parsers: ["scss"], vscodeLanguageIds: ["scss"] }))]; const printers = { postcss: printerPostcss }; var languageCss = { languages, options: options$2, printers }; function hasPragma$2(text) { return /^\s*#[^\n\S]*@(format|prettier)\s*(\n|$)/.test(text); } function insertPragma$3(text) { return "# @format\n\n" + text; } var pragma$2 = { hasPragma: hasPragma$2, insertPragma: insertPragma$3 }; const { concat: concat$6, join: join$3, hardline: hardline$5, line: line$3, softline: softline$2, group: group$5, indent: indent$3, ifBreak: ifBreak$2 } = document.builders; const { hasIgnoreComment: hasIgnoreComment$2 } = util$1; const { isNextLineEmpty: isNextLineEmpty$3 } = utilShared; const { insertPragma: insertPragma$4 } = pragma$2; function genericPrint$1(path, options, print) { const n = path.getValue(); if (!n) { return ""; } if (typeof n === "string") { return n; } switch (n.kind) { case "Document": { const parts = []; path.map((pathChild, index) => { parts.push(concat$6([pathChild.call(print)])); if (index !== n.definitions.length - 1) { parts.push(hardline$5); if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), options.locEnd)) { parts.push(hardline$5); } } }, "definitions"); return concat$6([concat$6(parts), hardline$5]); } case "OperationDefinition": { const hasOperation = options.originalText[options.locStart(n)] !== "{"; const hasName = !!n.name; return concat$6([hasOperation ? n.operation : "", hasOperation && hasName ? concat$6([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "variableDefinitions"))])), softline$2, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]); } case "FragmentDefinition": { return concat$6(["fragment ", path.call(print, "name"), n.variableDefinitions && n.variableDefinitions.length ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "variableDefinitions"))])), softline$2, ")"])) : "", " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]); } case "SelectionSet": { return concat$6(["{", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(selectionsPath => printSequence(selectionsPath, options, print), "selections"))])), hardline$5, "}"]); } case "Field": { return group$5(concat$6([n.alias ? concat$6([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")])); } case "Name": { return n.value; } case "StringValue": { if (n.block) { return concat$6(['"""', hardline$5, join$3(hardline$5, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$5, '"""']); } return concat$6(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']); } case "IntValue": case "FloatValue": case "EnumValue": { return n.value; } case "BooleanValue": { return n.value ? "true" : "false"; } case "NullValue": { return "null"; } case "Variable": { return concat$6(["$", path.call(print, "name")]); } case "ListValue": { return group$5(concat$6(["[", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "values"))])), softline$2, "]"])); } case "ObjectValue": { return group$5(concat$6(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "fields"))])), softline$2, ifBreak$2("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"])); } case "ObjectField": case "Argument": { return concat$6([path.call(print, "name"), ": ", path.call(print, "value")]); } case "Directive": { return concat$6(["@", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : ""]); } case "NamedType": { return path.call(print, "name"); } case "VariableDefinition": { return concat$6([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$6([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]); } case "TypeExtensionDefinition": { return concat$6(["extend ", path.call(print, "definition")]); } case "ObjectTypeExtension": case "ObjectTypeDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$6([" implements ", concat$6(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$5, "}"]) : ""]); } case "FieldDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]); } case "DirectiveDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : "", n.repeatable ? " repeatable" : "", concat$6([" on ", join$3(" | ", path.map(print, "locations"))])]); } case "EnumTypeExtension": case "EnumTypeDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(valuesPath => printSequence(valuesPath, options, print), "values"))])), hardline$5, "}"]) : ""]); } case "EnumValueDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", path.call(print, "name"), printDirectives(path, print, n)]); } case "InputValueDefinition": { return concat$6([path.call(print, "description"), n.description ? n.description.block ? hardline$5 : line$3 : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$6([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]); } case "InputObjectTypeExtension": case "InputObjectTypeDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$5, "}"]) : ""]); } case "SchemaDefinition": { return concat$6(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(opsPath => printSequence(opsPath, options, print), "operationTypes"))])) : "", hardline$5, "}"]); } case "OperationTypeDefinition": { return concat$6([path.call(print, "operation"), ": ", path.call(print, "type")]); } case "InterfaceTypeExtension": case "InterfaceTypeDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$5, "}"]) : ""]); } case "FragmentSpread": { return concat$6(["...", path.call(print, "name"), printDirectives(path, print, n)]); } case "InlineFragment": { return concat$6(["...", n.typeCondition ? concat$6([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]); } case "UnionTypeExtension": case "UnionTypeDefinition": { return group$5(concat$6([path.call(print, "description"), n.description ? hardline$5 : "", group$5(concat$6([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$6([" =", ifBreak$2("", " "), indent$3(concat$6([ifBreak$2(concat$6([line$3, " "])), join$3(concat$6([line$3, "| "]), path.map(print, "types"))]))]) : ""]))])); } case "ScalarTypeExtension": case "ScalarTypeDefinition": { return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]); } case "NonNullType": { return concat$6([path.call(print, "type"), "!"]); } case "ListType": { return concat$6(["[", path.call(print, "type"), "]"]); } default: /* istanbul ignore next */ throw new Error("unknown graphql type: " + JSON.stringify(n.kind)); } } function printDirectives(path, print, n) { if (n.directives.length === 0) { return ""; } return concat$6([" ", group$5(indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", " "), softline$2]), path.map(print, "directives"))])))]); } function printSequence(sequencePath, options, print) { const count = sequencePath.getValue().length; return sequencePath.map((path, i) => { const printed = print(path); if (isNextLineEmpty$3(options.originalText, path.getValue(), options.locEnd) && i < count - 1) { return concat$6([printed, hardline$5]); } return printed; }); } function canAttachComment(node) { return node.kind && node.kind !== "Comment"; } function printComment$1(commentPath) { const comment = commentPath.getValue(); if (comment.kind === "Comment") { return "#" + comment.value.trimEnd(); } throw new Error("Not a comment: " + JSON.stringify(comment)); } function determineInterfaceSeparatorBetween(first, second, options) { const textBetween = options.originalText.slice(first.loc.end, second.loc.start).replace(/#.*/g, "").trim(); return textBetween === "," ? ", " : " & "; } function printInterfaces(path, options, print) { const node = path.getNode(); const parts = []; const { interfaces } = node; const printed = path.map(node => print(node), "interfaces"); for (let index = 0; index < interfaces.length; index++) { const interfaceNode = interfaces[index]; if (index > 0) { parts.push(determineInterfaceSeparatorBetween(interfaces[index - 1], interfaceNode, options)); } parts.push(printed[index]); } return parts; } function clean$1(node, newNode /*, parent*/ ) { delete newNode.loc; delete newNode.comments; } var printerGraphql = { print: genericPrint$1, massageAstNode: clean$1, hasPrettierIgnore: hasIgnoreComment$2, insertPragma: insertPragma$4, printComment: printComment$1, canAttachComment }; var options$3 = { bracketSpacing: commonOptions.bracketSpacing }; var name$5 = "GraphQL"; var type$4 = "data"; var extensions$4 = [ ".graphql", ".gql", ".graphqls" ]; var tmScope$4 = "source.graphql"; var aceMode$4 = "text"; var languageId$4 = 139; var GraphQL = { name: name$5, type: type$4, extensions: extensions$4, tmScope: tmScope$4, aceMode: aceMode$4, languageId: languageId$4 }; var GraphQL$1 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name$5, type: type$4, extensions: extensions$4, tmScope: tmScope$4, aceMode: aceMode$4, languageId: languageId$4, 'default': GraphQL }); var require$$0$3 = getCjsExportFromNamespace(GraphQL$1); const languages$1 = [createLanguage(require$$0$3, () => ({ since: "1.5.0", parsers: ["graphql"], vscodeLanguageIds: ["graphql"] }))]; const printers$1 = { graphql: printerGraphql }; var languageGraphql = { languages: languages$1, options: options$3, printers: printers$1 }; var clean$2 = function clean(ast, newNode) { delete newNode.loc; delete newNode.selfClosing; // (Glimmer/HTML) ignore TextNode whitespace if (ast.type === "TextNode") { const trimmed = ast.chars.trim(); if (!trimmed) { return null; } newNode.chars = trimmed; } }; function isUppercase(string) { return string.toUpperCase() === string; } function isGlimmerComponent(node) { return isNodeOfSomeType(node, ["ElementNode"]) && typeof node.tag === "string" && (isUppercase(node.tag[0]) || node.tag.includes(".")); } function isWhitespaceNode(node) { return isNodeOfSomeType(node, ["TextNode"]) && !/\S/.test(node.chars); } function isNodeOfSomeType(node, types) { return node && types.some(type => node.type === type); } function isParentOfSomeType(path, types) { const parentNode = path.getParentNode(0); return isNodeOfSomeType(parentNode, types); } function isPreviousNodeOfSomeType(path, types) { const previousNode = getPreviousNode(path); return isNodeOfSomeType(previousNode, types); } function isNextNodeOfSomeType(path, types) { const nextNode = getNextNode(path); return isNodeOfSomeType(nextNode, types); } function getSiblingNode(path, offset) { const node = path.getValue(); const parentNode = path.getParentNode(0) || {}; const children = parentNode.children || parentNode.body || []; const index = children.indexOf(node); return index !== -1 && children[index + offset]; } function getPreviousNode(path, lookBack = 1) { return getSiblingNode(path, -lookBack); } function getNextNode(path) { return getSiblingNode(path, 1); } function isPrettierIgnoreNode(node) { return isNodeOfSomeType(node, ["MustacheCommentStatement"]) && typeof node.value === "string" && node.value.trim() === "prettier-ignore"; } function hasPrettierIgnore(path) { const node = path.getValue(); const previousPreviousNode = getPreviousNode(path, 2); return isPrettierIgnoreNode(node) || isPrettierIgnoreNode(previousPreviousNode); } var utils$3 = { getNextNode, getPreviousNode, hasPrettierIgnore, isGlimmerComponent, isNextNodeOfSomeType, isNodeOfSomeType, isParentOfSomeType, isPreviousNodeOfSomeType, isWhitespaceNode }; const { concat: concat$7, join: join$4, softline: softline$3, hardline: hardline$6, line: line$4, group: group$6, indent: indent$4, ifBreak: ifBreak$3 } = document.builders; const { getNextNode: getNextNode$1, getPreviousNode: getPreviousNode$1, hasPrettierIgnore: hasPrettierIgnore$1, isGlimmerComponent: isGlimmerComponent$1, isNextNodeOfSomeType: isNextNodeOfSomeType$1, isParentOfSomeType: isParentOfSomeType$1, isPreviousNodeOfSomeType: isPreviousNodeOfSomeType$1, isWhitespaceNode: isWhitespaceNode$1 } = utils$3; // http://w3c.github.io/html/single-page.html#void-elements const voidTags = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]; // Formatter based on @glimmerjs/syntax's built-in test formatter: // https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts function print(path, options, print) { const n = path.getValue(); /* istanbul ignore if*/ if (!n) { return ""; } if (hasPrettierIgnore$1(path)) { const startOffset = locationToOffset(options.originalText, n.loc.start.line - 1, n.loc.start.column); const endOffset = locationToOffset(options.originalText, n.loc.end.line - 1, n.loc.end.column); const ignoredText = options.originalText.slice(startOffset, endOffset); return ignoredText; } switch (n.type) { case "Block": case "Program": case "Template": { return group$6(concat$7(path.map(print, "body"))); } case "ElementNode": { const hasChildren = n.children.length > 0; const hasNonWhitespaceChildren = n.children.some(n => !isWhitespaceNode$1(n)); const isVoid = isGlimmerComponent$1(n) && (!hasChildren || !hasNonWhitespaceChildren) || voidTags.includes(n.tag); const closeTagForNoBreak = isVoid ? concat$7([" />", softline$3]) : ">"; const closeTagForBreak = isVoid ? "/>" : ">"; const printParams = (path, print) => indent$4(concat$7([n.attributes.length ? line$4 : "", join$4(line$4, path.map(print, "attributes")), n.modifiers.length ? line$4 : "", join$4(line$4, path.map(print, "modifiers")), n.comments.length ? line$4 : "", join$4(line$4, path.map(print, "comments"))])); const nextNode = getNextNode$1(path); return concat$7([group$6(concat$7(["<", n.tag, printParams(path, print), n.blockParams.length ? " as |".concat(n.blockParams.join(" "), "|") : "", ifBreak$3(softline$3, ""), ifBreak$3(closeTagForBreak, closeTagForNoBreak)])), !isVoid ? group$6(concat$7([hasNonWhitespaceChildren ? indent$4(printChildren(path, options, print)) : "", ifBreak$3(hasChildren ? hardline$6 : "", ""), concat$7([""])])) : "", nextNode && nextNode.type === "ElementNode" ? hardline$6 : ""]); } case "BlockStatement": { const pp = path.getParentNode(1); const isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if"; const hasElseIf = n.inverse && n.inverse.body.length === 1 && n.inverse.body[0].type === "BlockStatement" && n.inverse.body[0].path.parts[0] === "if"; const indentElse = hasElseIf ? a => a : indent$4; const inverseElseStatement = (n.inverseStrip.open ? "{{~" : "{{") + "else" + (n.inverseStrip.close ? "~}}" : "}}"); if (n.inverse) { return concat$7([isElseIf ? concat$7([n.openStrip.open ? "{{~else " : "{{else ", printPathParams(path, print), n.openStrip.close ? "~}}" : "}}"]) : printOpenBlock(path, print, n.openStrip), indent$4(concat$7([hardline$6, path.call(print, "program")])), n.inverse && !hasElseIf ? concat$7([hardline$6, inverseElseStatement]) : "", n.inverse ? indentElse(concat$7([hardline$6, path.call(print, "inverse")])) : "", isElseIf ? "" : concat$7([hardline$6, printCloseBlock(path, print, n.closeStrip)])]); } else if (isElseIf) { return concat$7([concat$7([n.openStrip.open ? "{{~else" : "{{else ", printPathParams(path, print), n.openStrip.close ? "~}}" : "}}"]), indent$4(concat$7([hardline$6, path.call(print, "program")]))]); } const hasNonWhitespaceChildren = n.program.body.some(n => !isWhitespaceNode$1(n)); return concat$7([printOpenBlock(path, print, n.openStrip), group$6(concat$7([indent$4(concat$7([softline$3, path.call(print, "program")])), hasNonWhitespaceChildren ? hardline$6 : softline$3, printCloseBlock(path, print, n.closeStrip)]))]); } case "ElementModifierStatement": { return group$6(concat$7(["{{", printPathParams(path, print), softline$3, "}}"])); } case "MustacheStatement": { const isEscaped = n.escaped === false; const { open: openStrip, close: closeStrip } = n.strip; const opening = (isEscaped ? "{{{" : "{{") + (openStrip ? "~" : ""); const closing = (closeStrip ? "~" : "") + (isEscaped ? "}}}" : "}}"); const leading = isParentOfSomeType$1(path, ["AttrNode", "ConcatStatement", "ElementNode"]) ? [opening, indent$4(softline$3)] : [opening]; return group$6(concat$7([...leading, printPathParams(path, print), softline$3, closing])); } case "SubExpression": { const params = printParams(path, print); const printedParams = params.length > 0 ? indent$4(concat$7([line$4, group$6(join$4(line$4, params))])) : ""; return group$6(concat$7(["(", printPath(path, print), printedParams, softline$3, ")"])); } case "AttrNode": { const isText = n.value.type === "TextNode"; const isEmptyText = isText && n.value.chars === ""; // If the text is empty and the value's loc start and end columns are the // same, there is no value for this AttrNode and it should be printed // without the `=""`. Example: `` -> `` const isEmptyValue = isEmptyText && n.value.loc.start.column === n.value.loc.end.column; if (isEmptyValue) { return concat$7([n.name]); } const value = path.call(print, "value"); const quotedValue = isText ? printStringLiteral(value.parts.join(), options) : value; return concat$7([n.name, "=", quotedValue]); } case "ConcatStatement": { return concat$7(['"', concat$7(path.map(partPath => print(partPath), "parts").filter(a => a !== "")), '"']); } case "Hash": { return concat$7([join$4(line$4, path.map(print, "pairs"))]); } case "HashPair": { return concat$7([n.key, "=", path.call(print, "value")]); } case "TextNode": { const maxLineBreaksToPreserve = 2; const isFirstElement = !getPreviousNode$1(path); const isLastElement = !getNextNode$1(path); const isWhitespaceOnly = !/\S/.test(n.chars); const lineBreaksCount = countNewLines(n.chars); const hasBlockParent = path.getParentNode(0).type === "Block"; const hasElementParent = path.getParentNode(0).type === "ElementNode"; const hasTemplateParent = path.getParentNode(0).type === "Template"; let leadingLineBreaksCount = countLeadingNewLines(n.chars); let trailingLineBreaksCount = countTrailingNewLines(n.chars); if ((isFirstElement || isLastElement) && isWhitespaceOnly && (hasBlockParent || hasElementParent || hasTemplateParent)) { return ""; } if (isWhitespaceOnly && lineBreaksCount) { leadingLineBreaksCount = Math.min(lineBreaksCount, maxLineBreaksToPreserve); trailingLineBreaksCount = 0; } else { if (isNextNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) { trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1); } if (isPreviousNodeOfSomeType$1(path, ["ElementNode"]) || isPreviousNodeOfSomeType$1(path, ["BlockStatement"])) { leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1); } } let leadingSpace = ""; let trailingSpace = ""; // preserve a space inside of an attribute node where whitespace present, // when next to mustache statement. const inAttrNode = path.stack.includes("attributes"); if (inAttrNode) { const parentNode = path.getParentNode(0); const isConcat = parentNode.type === "ConcatStatement"; if (isConcat) { const { parts } = parentNode; const partIndex = parts.indexOf(n); if (partIndex > 0) { const partType = parts[partIndex - 1].type; const isMustache = partType === "MustacheStatement"; if (isMustache) { leadingSpace = " "; } } if (partIndex < parts.length - 1) { const partType = parts[partIndex + 1].type; const isMustache = partType === "MustacheStatement"; if (isMustache) { trailingSpace = " "; } } } } else { if (trailingLineBreaksCount === 0 && isNextNodeOfSomeType$1(path, ["MustacheStatement"])) { trailingSpace = " "; } if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) { leadingSpace = " "; } if (isFirstElement) { leadingLineBreaksCount = 0; leadingSpace = ""; } if (isLastElement) { trailingLineBreaksCount = 0; trailingSpace = ""; } } return concat$7([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), n.chars.replace(/^[\s ]+/g, leadingSpace).replace(/[\s ]+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)].filter(Boolean)); } case "MustacheCommentStatement": { const dashes = n.value.includes("}}") ? "--" : ""; return concat$7(["{{!", dashes, n.value, dashes, "}}"]); } case "PathExpression": { return n.original; } case "BooleanLiteral": { return String(n.value); } case "CommentStatement": { return concat$7([""]); } case "StringLiteral": { return printStringLiteral(n.value, options); } case "NumberLiteral": { return String(n.value); } case "UndefinedLiteral": { return "undefined"; } case "NullLiteral": { return "null"; } /* istanbul ignore next */ default: throw new Error("unknown glimmer type: " + JSON.stringify(n.type)); } } function printChildren(path, options, print) { return concat$7(path.map((childPath, childIndex) => { const childNode = path.getValue(); const isFirstNode = childIndex === 0; const isLastNode = childIndex === path.getParentNode(0).children.length - 1; const isLastNodeInMultiNodeList = isLastNode && !isFirstNode; const isWhitespace = isWhitespaceNode$1(childNode); if (isWhitespace && isLastNodeInMultiNodeList) { return print(childPath, options, print); } else if (isFirstNode) { return concat$7([softline$3, print(childPath, options, print)]); } return print(childPath, options, print); }, "children")); } /** * Prints a string literal with the correct surrounding quotes based on * `options.singleQuote` and the number of escaped quotes contained in * the string literal. This function is the glimmer equivalent of `printString` * in `common/util`, but has differences because of the way escaped characters * are treated in hbs string literals. * @param {string} stringLiteral - the string literal value * @param {object} options - the prettier options object */ function printStringLiteral(stringLiteral, options) { const double = { quote: '"', regex: /"/g }; const single = { quote: "'", regex: /'/g }; const preferred = options.singleQuote ? single : double; const alternate = preferred === single ? double : single; let shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for // enclosing the string, we might want to enclose with the alternate quote // instead, to minimize the number of escaped quotes. if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) { const numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length; const numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length; shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes; } const enclosingQuote = shouldUseAlternateQuote ? alternate : preferred; const escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, "\\".concat(enclosingQuote.quote)); return concat$7([enclosingQuote.quote, escapedStringLiteral, enclosingQuote.quote]); } function printPath(path, print) { return path.call(print, "path"); } function printParams(path, print) { const node = path.getValue(); let parts = []; if (node.params.length > 0) { parts = parts.concat(path.map(print, "params")); } if (node.hash && node.hash.pairs.length > 0) { parts.push(path.call(print, "hash")); } return parts; } function printPathParams(path, print) { const printedPath = printPath(path, print); const printedParams = printParams(path, print); const parts = [printedPath, ...printedParams]; return indent$4(group$6(join$4(line$4, parts))); } function printBlockParams(path) { const block = path.getValue(); if (!block.program || !block.program.blockParams.length) { return ""; } return concat$7([" as |", block.program.blockParams.join(" "), "|"]); } function printOpenBlock(path, print, { open: isOpenStrip = false, close: isCloseStrip = false } = {}) { return group$6(concat$7([isOpenStrip ? "{{~#" : "{{#", printPathParams(path, print), printBlockParams(path), softline$3, isCloseStrip ? "~}}" : "}}"])); } function printCloseBlock(path, print, { open: isOpenStrip = false, close: isCloseStrip = false } = {}) { return concat$7([isOpenStrip ? "{{~/" : "{{/", path.call(print, "path"), isCloseStrip ? "~}}" : "}}"]); } function countNewLines(string) { /* istanbul ignore next */ string = typeof string === "string" ? string : ""; return string.split("\n").length - 1; } function countLeadingNewLines(string) { /* istanbul ignore next */ string = typeof string === "string" ? string : ""; const newLines = (string.match(/^([^\S\r\n]*[\r\n])+/g) || [])[0] || ""; return countNewLines(newLines); } function countTrailingNewLines(string) { /* istanbul ignore next */ string = typeof string === "string" ? string : ""; const newLines = (string.match(/([\r\n][^\S\r\n]*)+$/g) || [])[0] || ""; return countNewLines(newLines); } function generateHardlines(number = 0, max = 0) { return new Array(Math.min(number, max)).fill(hardline$6); } /* istanbul ignore next https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/compiler/lib/location.ts#L5-L29 */ function locationToOffset(source, line, column) { let seenLines = 0; let seenChars = 0; // eslint-disable-next-line no-constant-condition while (true) { if (seenChars === source.length) { return null; } let nextLine = source.indexOf("\n", seenChars); if (nextLine === -1) { nextLine = source.length; } if (seenLines === line) { if (seenChars + column > nextLine) { return null; } return seenChars + column; } else if (nextLine === -1) { return null; } seenLines += 1; seenChars = nextLine + 1; } } var printerGlimmer = { print, massageAstNode: clean$2 }; var name$6 = "Handlebars"; var type$5 = "markup"; var group$7 = "HTML"; var aliases = [ "hbs", "htmlbars" ]; var extensions$5 = [ ".handlebars", ".hbs" ]; var tmScope$5 = "text.html.handlebars"; var aceMode$5 = "handlebars"; var languageId$5 = 155; var Handlebars = { name: name$6, type: type$5, group: group$7, aliases: aliases, extensions: extensions$5, tmScope: tmScope$5, aceMode: aceMode$5, languageId: languageId$5 }; var Handlebars$1 = /*#__PURE__*/Object.freeze({ __proto__: null, name: name$6, type: type$5, group: group$7, aliases: aliases, extensions: extensions$5, tmScope: tmScope$5, aceMode: aceMode$5, languageId: languageId$5, 'default': Handlebars }); var require$$0$4 = getCjsExportFromNamespace(Handlebars$1); const languages$2 = [createLanguage(require$$0$4, () => ({ since: null, // unreleased parsers: ["glimmer"], vscodeLanguageIds: ["handlebars"] }))]; const printers$2 = { glimmer: printerGlimmer }; var languageHandlebars = { languages: languages$2, printers: printers$2 }; var clean$3 = function clean(ast, newNode) { delete newNode.sourceSpan; delete newNode.startSourceSpan; delete newNode.endSourceSpan; delete newNode.nameSpan; delete newNode.valueSpan; if (ast.type === "text" || ast.type === "comment") { return null; } // may be formatted by multiparser if (ast.type === "yaml" || ast.type === "toml") { return null; } if (ast.type === "attribute") { delete newNode.value; } if (ast.type === "docType") { delete newNode.value; } }; var json = { "CSS_DISPLAY_TAGS": { "area": "none", "base": "none", "basefont": "none", "datalist": "none", "head": "none", "link": "none", "meta": "none", "noembed": "none", "noframes": "none", "param": "none", "rp": "none", "script": "block", "source": "block", "style": "none", "template": "inline", "track": "block", "title": "none", "html": "block", "body": "block", "address": "block", "blockquote": "block", "center": "block", "div": "block", "figure": "block", "figcaption": "block", "footer": "block", "form": "block", "header": "block", "hr": "block", "legend": "block", "listing": "block", "main": "block", "p": "block", "plaintext": "block", "pre": "block", "xmp": "block", "slot": "contents", "ruby": "ruby", "rt": "ruby-text", "article": "block", "aside": "block", "h1": "block", "h2": "block", "h3": "block", "h4": "block", "h5": "block", "h6": "block", "hgroup": "block", "nav": "block", "section": "block", "dir": "block", "dd": "block", "dl": "block", "dt": "block", "ol": "block", "ul": "block", "li": "list-item", "table": "table", "caption": "table-caption", "colgroup": "table-column-group", "col": "table-column", "thead": "table-header-group", "tbody": "table-row-group", "tfoot": "table-footer-group", "tr": "table-row", "td": "table-cell", "th": "table-cell", "fieldset": "block", "button": "inline-block", "video": "inline-block", "audio": "inline-block" }, "CSS_DISPLAY_DEFAULT": "inline", "CSS_WHITE_SPACE_TAGS": { "listing": "pre", "plaintext": "pre", "pre": "pre", "xmp": "pre", "nobr": "nowrap", "table": "initial", "textarea": "pre-wrap" }, "CSS_WHITE_SPACE_DEFAULT": "normal" }; var index = [ "a", "abbr", "acronym", "address", "applet", "area", "article", "aside", "audio", "b", "base", "basefont", "bdi", "bdo", "bgsound", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "command", "content", "data", "datalist", "dd", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "element", "em", "embed", "fieldset", "figcaption", "figure", "font", "footer", "form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", "i", "iframe", "image", "img", "input", "ins", "isindex", "kbd", "keygen", "label", "legend", "li", "link", "listing", "main", "map", "mark", "marquee", "math", "menu", "menuitem", "meta", "meter", "multicol", "nav", "nextid", "nobr", "noembed", "noframes", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "picture", "plaintext", "pre", "progress", "q", "rb", "rbc", "rp", "rt", "rtc", "ruby", "s", "samp", "script", "section", "select", "shadow", "slot", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "svg", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "tt", "u", "ul", "var", "video", "wbr", "xmp" ]; var htmlTagNames = /*#__PURE__*/Object.freeze({ __proto__: null, 'default': index }); var a = [ "accesskey", "charset", "coords", "download", "href", "hreflang", "name", "ping", "referrerpolicy", "rel", "rev", "shape", "tabindex", "target", "type" ]; var abbr = [ "title" ]; var applet = [ "align", "alt", "archive", "code", "codebase", "height", "hspace", "name", "object", "vspace", "width" ]; var area = [ "accesskey", "alt", "coords", "download", "href", "hreflang", "nohref", "ping", "referrerpolicy", "rel", "shape", "tabindex", "target", "type" ]; var audio = [ "autoplay", "controls", "crossorigin", "loop", "muted", "preload", "src" ]; var base = [ "href", "target" ]; var basefont = [ "color", "face", "size" ]; var bdo = [ "dir" ]; var blockquote = [ "cite" ]; var body = [ "alink", "background", "bgcolor", "link", "text", "vlink" ]; var br = [ "clear" ]; var button = [ "accesskey", "autofocus", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "name", "tabindex", "type", "value" ]; var canvas = [ "height", "width" ]; var caption = [ "align" ]; var col = [ "align", "char", "charoff", "span", "valign", "width" ]; var colgroup = [ "align", "char", "charoff", "span", "valign", "width" ]; var data = [ "value" ]; var del = [ "cite", "datetime" ]; var details = [ "open" ]; var dfn = [ "title" ]; var dialog = [ "open" ]; var dir = [ "compact" ]; var div = [ "align" ]; var dl = [ "compact" ]; var embed$1 = [ "height", "src", "type", "width" ]; var fieldset = [ "disabled", "form", "name" ]; var font = [ "color", "face", "size" ]; var form = [ "accept", "accept-charset", "action", "autocomplete", "enctype", "method", "name", "novalidate", "target" ]; var frame = [ "frameborder", "longdesc", "marginheight", "marginwidth", "name", "noresize", "scrolling", "src" ]; var frameset = [ "cols", "rows" ]; var h1 = [ "align" ]; var h2 = [ "align" ]; var h3 = [ "align" ]; var h4 = [ "align" ]; var h5 = [ "align" ]; var h6 = [ "align" ]; var head = [ "profile" ]; var hr = [ "align", "noshade", "size", "width" ]; var html = [ "manifest", "version" ]; var iframe = [ "align", "allow", "allowfullscreen", "allowpaymentrequest", "allowusermedia", "frameborder", "height", "longdesc", "marginheight", "marginwidth", "name", "referrerpolicy", "sandbox", "scrolling", "src", "srcdoc", "width" ]; var img = [ "align", "alt", "border", "crossorigin", "decoding", "height", "hspace", "ismap", "longdesc", "name", "referrerpolicy", "sizes", "src", "srcset", "usemap", "vspace", "width" ]; var input = [ "accept", "accesskey", "align", "alt", "autocomplete", "autofocus", "checked", "dirname", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "height", "ismap", "list", "max", "maxlength", "min", "minlength", "multiple", "name", "pattern", "placeholder", "readonly", "required", "size", "src", "step", "tabindex", "title", "type", "usemap", "value", "width" ]; var ins = [ "cite", "datetime" ]; var isindex = [ "prompt" ]; var label = [ "accesskey", "for", "form" ]; var legend = [ "accesskey", "align" ]; var li = [ "type", "value" ]; var link$3 = [ "as", "charset", "color", "crossorigin", "href", "hreflang", "imagesizes", "imagesrcset", "integrity", "media", "nonce", "referrerpolicy", "rel", "rev", "sizes", "target", "title", "type" ]; var map = [ "name" ]; var menu = [ "compact" ]; var meta = [ "charset", "content", "http-equiv", "name", "scheme" ]; var meter = [ "high", "low", "max", "min", "optimum", "value" ]; var object = [ "align", "archive", "border", "classid", "codebase", "codetype", "data", "declare", "form", "height", "hspace", "name", "standby", "tabindex", "type", "typemustmatch", "usemap", "vspace", "width" ]; var ol = [ "compact", "reversed", "start", "type" ]; var optgroup = [ "disabled", "label" ]; var option = [ "disabled", "label", "selected", "value" ]; var output = [ "for", "form", "name" ]; var p = [ "align" ]; var param = [ "name", "type", "value", "valuetype" ]; var pre = [ "width" ]; var progress = [ "max", "value" ]; var q = [ "cite" ]; var script = [ "async", "charset", "crossorigin", "defer", "integrity", "language", "nomodule", "nonce", "referrerpolicy", "src", "type" ]; var select = [ "autocomplete", "autofocus", "disabled", "form", "multiple", "name", "required", "size", "tabindex" ]; var slot = [ "name" ]; var source$1 = [ "media", "sizes", "src", "srcset", "type" ]; var style = [ "media", "nonce", "title", "type" ]; var table = [ "align", "bgcolor", "border", "cellpadding", "cellspacing", "frame", "rules", "summary", "width" ]; var tbody = [ "align", "char", "charoff", "valign" ]; var td = [ "abbr", "align", "axis", "bgcolor", "char", "charoff", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign", "width" ]; var textarea = [ "accesskey", "autocomplete", "autofocus", "cols", "dirname", "disabled", "form", "maxlength", "minlength", "name", "placeholder", "readonly", "required", "rows", "tabindex", "wrap" ]; var tfoot = [ "align", "char", "charoff", "valign" ]; var th = [ "abbr", "align", "axis", "bgcolor", "char", "charoff", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign", "width" ]; var thead = [ "align", "char", "charoff", "valign" ]; var time = [ "datetime" ]; var tr = [ "align", "bgcolor", "char", "charoff", "valign" ]; var track = [ "default", "kind", "label", "src", "srclang" ]; var ul = [ "compact", "type" ]; var video = [ "autoplay", "controls", "crossorigin", "height", "loop", "muted", "playsinline", "poster", "preload", "src", "width" ]; var index$1 = { "*": [ "accesskey", "autocapitalize", "autofocus", "class", "contenteditable", "dir", "draggable", "enterkeyhint", "hidden", "id", "inputmode", "is", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "nonce", "slot", "spellcheck", "style", "tabindex", "title", "translate" ], a: a, abbr: abbr, applet: applet, area: area, audio: audio, base: base, basefont: basefont, bdo: bdo, blockquote: blockquote, body: body, br: br, button: button, canvas: canvas, caption: caption, col: col, colgroup: colgroup, data: data, del: del, details: details, dfn: dfn, dialog: dialog, dir: dir, div: div, dl: dl, embed: embed$1, fieldset: fieldset, font: font, form: form, frame: frame, frameset: frameset, h1: h1, h2: h2, h3: h3, h4: h4, h5: h5, h6: h6, head: head, hr: hr, html: html, iframe: iframe, img: img, input: input, ins: ins, isindex: isindex, label: label, legend: legend, li: li, link: link$3, map: map, menu: menu, meta: meta, meter: meter, object: object, ol: ol, optgroup: optgroup, option: option, output: output, p: p, param: param, pre: pre, progress: progress, q: q, script: script, select: select, slot: slot, source: source$1, style: style, table: table, tbody: tbody, td: td, textarea: textarea, tfoot: tfoot, th: th, thead: thead, time: time, tr: tr, track: track, ul: ul, video: video }; var htmlElementAttributes = /*#__PURE__*/Object.freeze({ __proto__: null, a: a, abbr: abbr, applet: applet, area: area, audio: audio, base: base, basefont: basefont, bdo: bdo, blockquote: blockquote, body: body, br: br, button: button, canvas: canvas, caption: caption, col: col, colgroup: colgroup, data: data, del: del, details: details, dfn: dfn, dialog: dialog, dir: dir, div: div, dl: dl, embed: embed$1, fieldset: fieldset, font: font, form: form, frame: frame, frameset: frameset, h1: h1, h2: h2, h3: h3, h4: h4, h5: h5, h6: h6, head: head, hr: hr, html: html, iframe: iframe, img: img, input: input, ins: ins, isindex: isindex, label: label, legend: legend, li: li, link: link$3, map: map, menu: menu, meta: meta, meter: meter, object: object, ol: ol, optgroup: optgroup, option: option, output: output, p: p, param: param, pre: pre, progress: progress, q: q, script: script, select: select, slot: slot, source: source$1, style: style, table: table, tbody: tbody, td: td, textarea: textarea, tfoot: tfoot, th: th, thead: thead, time: time, tr: tr, track: track, ul: ul, video: video, 'default': index$1 }); var htmlTagNames$1 = getCjsExportFromNamespace(htmlTagNames); var htmlElementAttributes$1 = getCjsExportFromNamespace(htmlElementAttributes); const { CSS_DISPLAY_TAGS, CSS_DISPLAY_DEFAULT, CSS_WHITE_SPACE_TAGS, CSS_WHITE_SPACE_DEFAULT } = json; const HTML_TAGS = arrayToMap(htmlTagNames$1); const HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes$1, arrayToMap); function arrayToMap(array) { const map = Object.create(null); for (const value of array) { map[value] = true; } return map; } function mapObject(object, fn) { const newObject = Object.create(null); for (const key of Object.keys(object)) { newObject[key] = fn(object[key], key); } return newObject; } function shouldPreserveContent(node, options) { if (!node.endSourceSpan) { return false; } if (node.type === "element" && node.fullName === "template" && node.attrMap.lang && node.attrMap.lang !== "html") { return true; } // unterminated node in ie conditional comment // e.g. if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) { return true; } // incomplete html in ie conditional comment // e.g. if (node.type === "ieConditionalComment" && !node.complete) { return true; } // top-level elements (excluding