4 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6 var fs$3 = _interopDefault(require('fs'));
7 var path$2 = _interopDefault(require('path'));
8 var os$1 = _interopDefault(require('os'));
9 var tty$1 = _interopDefault(require('tty'));
10 var assert$1 = _interopDefault(require('assert'));
11 var util$4 = _interopDefault(require('util'));
12 var stream$6 = _interopDefault(require('stream'));
13 var events$1 = _interopDefault(require('events'));
14 var readline$1 = _interopDefault(require('readline'));
16 var semverCompare = function cmp(a, b) {
17 var pa = a.split('.');
18 var pb = b.split('.');
20 for (var i = 0; i < 3; i++) {
21 var na = Number(pa[i]);
22 var nb = Number(pb[i]);
23 if (na > nb) return 1;
24 if (nb > na) return -1;
25 if (!isNaN(na) && isNaN(nb)) return 1;
26 if (isNaN(na) && !isNaN(nb)) return -1;
32 var pleaseUpgradeNode = function pleaseUpgradeNode(pkg, opts) {
33 var opts = opts || {};
34 var requiredVersion = pkg.engines.node.replace('>=', '');
35 var currentVersion = process.version.replace('v', '');
37 if (semverCompare(currentVersion, requiredVersion) === -1) {
39 console.error(opts.message(requiredVersion));
41 console.error(pkg.name + ' requires at least version ' + requiredVersion + ' of Node, please upgrade');
44 if (opts.hasOwnProperty('exitCode')) {
45 process.exit(opts.exitCode);
52 var name = "prettier";
53 var version = "2.0.5";
54 var description = "Prettier is an opinionated code formatter";
55 var bin = "./bin/prettier.js";
56 var repository = "prettier/prettier";
57 var homepage = "https://prettier.io";
58 var author = "James Long";
60 var main = "./index.js";
65 "@angular/compiler": "9.0.5",
66 "@babel/code-frame": "7.8.0",
67 "@babel/parser": "7.9.4",
68 "@glimmer/syntax": "0.50.0",
69 "@iarna/toml": "2.2.3",
70 "@typescript-eslint/typescript-estree": "2.26.0",
71 "angular-estree-parser": "1.3.0",
72 "angular-html-parser": "1.4.0",
75 "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540",
81 editorconfig: "0.15.3",
82 "editorconfig-to-prettier": "0.1.1",
83 "escape-string-regexp": "2.0.0",
86 "find-parent-dir": "0.3.0",
87 "find-project-root": "1.1.1",
88 "flow-parser": "0.122.0",
89 "get-stream": "5.1.0",
92 "html-element-attributes": "2.2.1",
93 "html-styles": "1.0.0",
94 "html-tag-names": "1.1.5",
96 "jest-docblock": "25.2.6",
97 "json-stable-stringify": "1.0.1",
99 "lines-and-columns": "1.1.6",
100 "linguist-languages": "7.9.0",
105 "n-readlines": "1.0.0",
106 "please-upgrade-node": "3.2.0",
107 "postcss-less": "3.1.4",
108 "postcss-media-query-parser": "0.2.3",
109 "postcss-scss": "2.0.0",
110 "postcss-selector-parser": "2.2.3",
111 "postcss-values-parser": "2.0.1",
112 "regexp-util": "1.2.2",
113 "remark-math": "1.0.6",
114 "remark-parse": "5.0.0",
118 "string-width": "4.2.0",
120 "unicode-regex": "3.0.0",
123 "yaml-unist-parser": "1.1.1"
125 var devDependencies = {
126 "@babel/core": "7.9.0",
127 "@babel/preset-env": "7.9.0",
128 "@rollup/plugin-alias": "3.0.1",
129 "@rollup/plugin-commonjs": "11.0.2",
130 "@rollup/plugin-json": "4.0.2",
131 "@rollup/plugin-node-resolve": "7.1.1",
132 "@rollup/plugin-replace": "2.3.1",
133 "babel-loader": "8.1.0",
135 "builtin-modules": "3.1.0",
137 "cross-env": "7.0.2",
140 "eslint-config-prettier": "6.10.1",
141 "eslint-formatter-friendly": "7.0.0",
142 "eslint-plugin-import": "2.20.2",
143 "eslint-plugin-prettier": "3.1.2",
144 "eslint-plugin-react": "7.19.0",
145 "eslint-plugin-unicorn": "18.0.1",
148 "jest-snapshot-serializer-ansi": "1.0.0",
149 "jest-snapshot-serializer-raw": "1.1.0",
150 "jest-watch-typeahead": "0.5.0",
154 "rollup-plugin-babel": "4.4.0",
155 "rollup-plugin-node-globals": "1.4.0",
156 "rollup-plugin-terser": "5.3.0",
158 "snapshot-diff": "0.7.0",
159 "strip-ansi": "6.0.0",
160 "synchronous-promise": "2.0.10",
162 "terser-webpack-plugin": "2.3.5",
166 prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1",
167 "prepare-release": "yarn && yarn build && yarn test:dist",
169 "test:dist": "cross-env NODE_ENV=production jest",
170 "test:dist-standalone": "cross-env NODE_ENV=production TEST_STANDALONE=1 jest tests/",
171 "test:integration": "jest tests_integration",
172 "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",
173 "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",
174 "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",
175 "lint:typecheck": "tsc",
176 "lint:eslint": "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly",
177 "lint:changelog": "node ./scripts/lint-changelog.js",
178 "lint:prettier": "prettier \"**/*.{md,json,yml,html,css}\" --check",
179 "lint:dist": "eslint --no-eslintrc --no-ignore --env=es6,browser --parser-options=ecmaVersion:2016 \"dist/!(bin-prettier|index|third-party).js\"",
180 "lint:spellcheck": "cspell {bin,scripts,src,website}/**/*.js {docs,website/blog,changelog_unreleased}/**/*.md",
181 "lint:deps": "node ./scripts/check-deps.js",
182 build: "node --max-old-space-size=3072 ./scripts/build/build.js",
183 "build-docs": "node ./scripts/build-docs.js"
188 description: description,
190 repository: repository,
196 dependencies: dependencies,
197 devDependencies: devDependencies,
201 var _package$1 = /*#__PURE__*/Object.freeze({
205 description: description,
207 repository: repository,
213 dependencies: dependencies,
214 devDependencies: devDependencies,
222 diff: function diff(oldString, newString) {
223 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
224 var callback = options.callback;
226 if (typeof options === 'function') {
231 this.options = options;
234 function done(value) {
236 setTimeout(function () {
237 callback(undefined, value);
243 } // Allow subclasses to massage the input prior to running
246 oldString = this.castInput(oldString);
247 newString = this.castInput(newString);
248 oldString = this.removeEmpty(this.tokenize(oldString));
249 newString = this.removeEmpty(this.tokenize(newString));
250 var newLen = newString.length,
251 oldLen = oldString.length;
253 var maxEditLength = newLen + oldLen;
257 }]; // Seed editLength = 0, i.e. the content starts with the same values
259 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
261 if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
262 // Identity per the equality and tokenizer
264 value: this.join(newString),
265 count: newString.length
267 } // Main worker method. checks all permutations of a given edit length for acceptance.
270 function execEditLength() {
271 for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
272 var basePath = void 0;
274 var addPath = bestPath[diagonalPath - 1],
275 removePath = bestPath[diagonalPath + 1],
276 _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
279 // No one else is going to attempt to use this value, clear it
280 bestPath[diagonalPath - 1] = undefined;
283 var canAdd = addPath && addPath.newPos + 1 < newLen,
284 canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
286 if (!canAdd && !canRemove) {
287 // If this path is a terminal then prune
288 bestPath[diagonalPath] = undefined;
290 } // Select the diagonal that we want to branch from. We select the prior
291 // path whose position in the new string is the farthest from the origin
292 // and does not pass the bounds of the diff graph
295 if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
296 basePath = clonePath(removePath);
297 self.pushComponent(basePath.components, undefined, true);
299 basePath = addPath; // No need to clone, we've pulled it from the list
302 self.pushComponent(basePath.components, true, undefined);
305 _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
307 if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
308 return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
310 // Otherwise track this path as a potential candidate and continue.
311 bestPath[diagonalPath] = basePath;
316 } // Performs the length of edit iteration. Is a bit fugly as this has to support the
317 // sync and async mode which is never fun. Loops over execEditLength until a value
323 setTimeout(function () {
324 // This should not happen, but we want to be safe.
326 /* istanbul ignore next */
327 if (editLength > maxEditLength) {
331 if (!execEditLength()) {
337 while (editLength <= maxEditLength) {
338 var ret = execEditLength();
346 pushComponent: function pushComponent(components, added, removed) {
347 var last = components[components.length - 1];
349 if (last && last.added === added && last.removed === removed) {
350 // We need to clone here as the component clone operation is just
351 // as shallow array clone
352 components[components.length - 1] = {
353 count: last.count + 1,
365 extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
366 var newLen = newString.length,
367 oldLen = oldString.length,
368 newPos = basePath.newPos,
369 oldPos = newPos - diagonalPath,
372 while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
379 basePath.components.push({
384 basePath.newPos = newPos;
387 equals: function equals(left, right) {
388 if (this.options.comparator) {
389 return this.options.comparator(left, right);
391 return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
394 removeEmpty: function removeEmpty(array) {
397 for (var i = 0; i < array.length; i++) {
405 castInput: function castInput(value) {
408 tokenize: function tokenize(value) {
409 return value.split('');
411 join: function join(chars) {
412 return chars.join('');
416 function buildValues(diff, components, newString, oldString, useLongestToken) {
417 var componentPos = 0,
418 componentLen = components.length,
422 for (; componentPos < componentLen; componentPos++) {
423 var component = components[componentPos];
425 if (!component.removed) {
426 if (!component.added && useLongestToken) {
427 var value = newString.slice(newPos, newPos + component.count);
428 value = value.map(function (value, i) {
429 var oldValue = oldString[oldPos + i];
430 return oldValue.length > value.length ? oldValue : value;
432 component.value = diff.join(value);
434 component.value = diff.join(newString.slice(newPos, newPos + component.count));
437 newPos += component.count; // Common case
439 if (!component.added) {
440 oldPos += component.count;
443 component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
444 oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
445 // The diffing algorithm is tied to add then remove output and this is the simplest
446 // route to get the desired output with minimal overhead.
448 if (componentPos && components[componentPos - 1].added) {
449 var tmp = components[componentPos - 1];
450 components[componentPos - 1] = components[componentPos];
451 components[componentPos] = tmp;
454 } // Special case handle for when one terminal is ignored (i.e. whitespace).
455 // For this case we merge the terminal into the prior string and drop the change.
456 // This is only available for string mode.
459 var lastComponent = components[componentLen - 1];
461 if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
462 components[componentLen - 2].value += lastComponent.value;
469 function clonePath(path) {
472 components: path.components.slice(0)
476 var characterDiff = new Diff();
478 function diffChars(oldStr, newStr, options) {
479 return characterDiff.diff(oldStr, newStr, options);
482 function generateOptions(options, defaults) {
483 if (typeof options === 'function') {
484 defaults.callback = options;
485 } else if (options) {
486 for (var name in options) {
487 /* istanbul ignore else */
488 if (options.hasOwnProperty(name)) {
489 defaults[name] = options[name];
496 // Ranges and exceptions:
497 // Latin-1 Supplement, 0080–00FF
498 // - U+00D7 × Multiplication sign
499 // - U+00F7 ÷ Division sign
500 // Latin Extended-A, 0100–017F
501 // Latin Extended-B, 0180–024F
502 // IPA Extensions, 0250–02AF
503 // Spacing Modifier Letters, 02B0–02FF
504 // - U+02C7 ˇ ˇ Caron
505 // - U+02D8 ˘ ˘ Breve
506 // - U+02D9 ˙ ˙ Dot Above
507 // - U+02DA ˚ ˚ Ring Above
508 // - U+02DB ˛ ˛ Ogonek
509 // - U+02DC ˜ ˜ Small Tilde
510 // - U+02DD ˝ ˝ Double Acute Accent
511 // Latin Extended Additional, 1E00–1EFF
514 var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
515 var reWhitespace = /\S/;
516 var wordDiff = new Diff();
518 wordDiff.equals = function (left, right) {
519 if (this.options.ignoreCase) {
520 left = left.toLowerCase();
521 right = right.toLowerCase();
524 return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
527 wordDiff.tokenize = function (value) {
528 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.
530 for (var i = 0; i < tokens.length - 1; i++) {
531 // If we have an empty string in the next field and we have only word chars before and after, merge
532 if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
533 tokens[i] += tokens[i + 2];
534 tokens.splice(i + 1, 2);
542 function diffWords(oldStr, newStr, options) {
543 options = generateOptions(options, {
544 ignoreWhitespace: true
546 return wordDiff.diff(oldStr, newStr, options);
549 function diffWordsWithSpace(oldStr, newStr, options) {
550 return wordDiff.diff(oldStr, newStr, options);
553 var lineDiff = new Diff();
555 lineDiff.tokenize = function (value) {
557 linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
559 if (!linesAndNewlines[linesAndNewlines.length - 1]) {
560 linesAndNewlines.pop();
561 } // Merge the content and line separators into single tokens
564 for (var i = 0; i < linesAndNewlines.length; i++) {
565 var line = linesAndNewlines[i];
567 if (i % 2 && !this.options.newlineIsToken) {
568 retLines[retLines.length - 1] += line;
570 if (this.options.ignoreWhitespace) {
581 function diffLines(oldStr, newStr, callback) {
582 return lineDiff.diff(oldStr, newStr, callback);
585 function diffTrimmedLines(oldStr, newStr, callback) {
586 var options = generateOptions(callback, {
587 ignoreWhitespace: true
589 return lineDiff.diff(oldStr, newStr, options);
592 var sentenceDiff = new Diff();
594 sentenceDiff.tokenize = function (value) {
595 return value.split(/(\S.+?[.!?])(?=\s+|$)/);
598 function diffSentences(oldStr, newStr, callback) {
599 return sentenceDiff.diff(oldStr, newStr, callback);
602 var cssDiff = new Diff();
604 cssDiff.tokenize = function (value) {
605 return value.split(/([{}:;,]|\s+)/);
608 function diffCss(oldStr, newStr, callback) {
609 return cssDiff.diff(oldStr, newStr, callback);
612 function _typeof(obj) {
613 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
614 _typeof = function (obj) {
618 _typeof = function (obj) {
619 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
626 function _toConsumableArray(arr) {
627 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
630 function _arrayWithoutHoles(arr) {
631 if (Array.isArray(arr)) {
632 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
638 function _iterableToArray(iter) {
639 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
642 function _nonIterableSpread() {
643 throw new TypeError("Invalid attempt to spread non-iterable instance");
646 var objectPrototypeToString = Object.prototype.toString;
647 var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
648 // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
650 jsonDiff.useLongestToken = true;
651 jsonDiff.tokenize = lineDiff.tokenize;
653 jsonDiff.castInput = function (value) {
654 var _this$options = this.options,
655 undefinedReplacement = _this$options.undefinedReplacement,
656 _this$options$stringi = _this$options.stringifyReplacer,
657 stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
658 return typeof v === 'undefined' ? undefinedReplacement : v;
659 } : _this$options$stringi;
660 return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
663 jsonDiff.equals = function (left, right) {
664 return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
667 function diffJson(oldObj, newObj, options) {
668 return jsonDiff.diff(oldObj, newObj, options);
669 } // This function handles the presence of circular references by bailing out when encountering an
670 // object that is already on the "stack" of items being processed. Accepts an optional replacer
673 function canonicalize(obj, stack, replacementStack, replacer, key) {
675 replacementStack = replacementStack || [];
678 obj = replacer(key, obj);
683 for (i = 0; i < stack.length; i += 1) {
684 if (stack[i] === obj) {
685 return replacementStack[i];
689 var canonicalizedObj;
691 if ('[object Array]' === objectPrototypeToString.call(obj)) {
693 canonicalizedObj = new Array(obj.length);
694 replacementStack.push(canonicalizedObj);
696 for (i = 0; i < obj.length; i += 1) {
697 canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
701 replacementStack.pop();
702 return canonicalizedObj;
705 if (obj && obj.toJSON) {
709 if (_typeof(obj) === 'object' && obj !== null) {
711 canonicalizedObj = {};
712 replacementStack.push(canonicalizedObj);
718 /* istanbul ignore else */
719 if (obj.hasOwnProperty(_key)) {
720 sortedKeys.push(_key);
726 for (i = 0; i < sortedKeys.length; i += 1) {
727 _key = sortedKeys[i];
728 canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
732 replacementStack.pop();
734 canonicalizedObj = obj;
737 return canonicalizedObj;
740 var arrayDiff = new Diff();
742 arrayDiff.tokenize = function (value) {
743 return value.slice();
746 arrayDiff.join = arrayDiff.removeEmpty = function (value) {
750 function diffArrays(oldArr, newArr, callback) {
751 return arrayDiff.diff(oldArr, newArr, callback);
754 function parsePatch(uniDiff) {
755 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
756 var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
757 delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
761 function parseIndex() {
763 list.push(index); // Parse diff metadata
765 while (i < diffstr.length) {
766 var line = diffstr[i]; // File header found, end parsing diff metadata
768 if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
773 var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
776 index.index = header[1];
780 } // Parse file headers if they are defined. Unified diff requires them, but
781 // there's no technical issues to have an isolated hunk without file header
784 parseFileHeader(index);
785 parseFileHeader(index); // Parse hunks
789 while (i < diffstr.length) {
790 var _line = diffstr[i];
792 if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
794 } else if (/^@@/.test(_line)) {
795 index.hunks.push(parseHunk());
796 } else if (_line && options.strict) {
797 // Ignore unexpected content unless in strict mode
798 throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
803 } // Parses the --- and +++ headers, if none are found, no lines
807 function parseFileHeader(index) {
808 var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
811 var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
812 var data = fileHeader[2].split('\t', 2);
813 var fileName = data[0].replace(/\\\\/g, '\\');
815 if (/^".*"$/.test(fileName)) {
816 fileName = fileName.substr(1, fileName.length - 2);
819 index[keyPrefix + 'FileName'] = fileName;
820 index[keyPrefix + 'Header'] = (data[1] || '').trim();
824 // This assumes that we are at the start of a hunk.
827 function parseHunk() {
828 var chunkHeaderIndex = i,
829 chunkHeaderLine = diffstr[i++],
830 chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
832 oldStart: +chunkHeader[1],
833 oldLines: +chunkHeader[2] || 1,
834 newStart: +chunkHeader[3],
835 newLines: +chunkHeader[4] || 1,
842 for (; i < diffstr.length; i++) {
843 // Lines starting with '---' could be mistaken for the "remove line" operation
844 // But they could be the header for the next file. Therefore prune such cases out.
845 if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
849 var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
851 if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
852 hunk.lines.push(diffstr[i]);
853 hunk.linedelimiters.push(delimiters[i] || '\n');
855 if (operation === '+') {
857 } else if (operation === '-') {
859 } else if (operation === ' ') {
866 } // Handle the empty block count case
869 if (!addCount && hunk.newLines === 1) {
873 if (!removeCount && hunk.oldLines === 1) {
875 } // Perform optional sanity checking
878 if (options.strict) {
879 if (addCount !== hunk.newLines) {
880 throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
883 if (removeCount !== hunk.oldLines) {
884 throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
891 while (i < diffstr.length) {
896 } // Iterator that traverses in the range of [min, max], stepping
897 // by distance from a given start position. I.e. for [0, 4], with
898 // start of 2, this will iterate 2, 3, 1, 4, 0.
901 function distanceIterator(start, minLine, maxLine) {
902 var wantForward = true,
903 backwardExhausted = false,
904 forwardExhausted = false,
906 return function iterator() {
907 if (wantForward && !forwardExhausted) {
908 if (backwardExhausted) {
912 } // Check if trying to fit beyond text length, and if not, check it fits
913 // after offset location (or desired location on first iteration)
916 if (start + localOffset <= maxLine) {
920 forwardExhausted = true;
923 if (!backwardExhausted) {
924 if (!forwardExhausted) {
926 } // Check if trying to fit before text beginning, and if not, check it fits
927 // before offset location
930 if (minLine <= start - localOffset) {
931 return -localOffset++;
934 backwardExhausted = true;
936 } // We tried to fit hunk before text beginning and beyond text length, then
937 // hunk can't fit on the text. Return undefined
942 function applyPatch(source, uniDiff) {
943 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
945 if (typeof uniDiff === 'string') {
946 uniDiff = parsePatch(uniDiff);
949 if (Array.isArray(uniDiff)) {
950 if (uniDiff.length > 1) {
951 throw new Error('applyPatch only works with a single input.');
954 uniDiff = uniDiff[0];
955 } // Apply the diff to the input
958 var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
959 delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
960 hunks = uniDiff.hunks,
961 compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
962 return line === patchContent;
965 fuzzFactor = options.fuzzFactor || 0,
971 * Checks if the hunk exactly fits on the provided location
975 function hunkFits(hunk, toPos) {
976 for (var j = 0; j < hunk.lines.length; j++) {
977 var line = hunk.lines[j],
978 operation = line.length > 0 ? line[0] : ' ',
979 content = line.length > 0 ? line.substr(1) : line;
981 if (operation === ' ' || operation === '-') {
982 // Context sanity check
983 if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
986 if (errorCount > fuzzFactor) {
996 } // Search best fit offsets for each hunk based on the previous ones
999 for (var i = 0; i < hunks.length; i++) {
1000 var hunk = hunks[i],
1001 maxLine = lines.length - hunk.oldLines,
1003 toPos = offset + hunk.oldStart - 1;
1004 var iterator = distanceIterator(toPos, minLine, maxLine);
1006 for (; localOffset !== undefined; localOffset = iterator()) {
1007 if (hunkFits(hunk, toPos + localOffset)) {
1008 hunk.offset = offset += localOffset;
1013 if (localOffset === undefined) {
1015 } // Set lower text limit to end of the current hunk, so next ones don't try
1016 // to fit over already patched text
1019 minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
1020 } // Apply patch hunks
1025 for (var _i = 0; _i < hunks.length; _i++) {
1026 var _hunk = hunks[_i],
1027 _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
1029 diffOffset += _hunk.newLines - _hunk.oldLines;
1032 // Creating a new file
1036 for (var j = 0; j < _hunk.lines.length; j++) {
1037 var line = _hunk.lines[j],
1038 operation = line.length > 0 ? line[0] : ' ',
1039 content = line.length > 0 ? line.substr(1) : line,
1040 delimiter = _hunk.linedelimiters[j];
1042 if (operation === ' ') {
1044 } else if (operation === '-') {
1045 lines.splice(_toPos, 1);
1046 delimiters.splice(_toPos, 1);
1047 /* istanbul ignore else */
1048 } else if (operation === '+') {
1049 lines.splice(_toPos, 0, content);
1050 delimiters.splice(_toPos, 0, delimiter);
1052 } else if (operation === '\\') {
1053 var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
1055 if (previousOperation === '+') {
1057 } else if (previousOperation === '-') {
1062 } // Handle EOFNL insertion/removal
1066 while (!lines[lines.length - 1]) {
1070 } else if (addEOFNL) {
1072 delimiters.push('\n');
1075 for (var _k = 0; _k < lines.length - 1; _k++) {
1076 lines[_k] = lines[_k] + delimiters[_k];
1079 return lines.join('');
1080 } // Wrapper that supports multiple file patches via callbacks.
1083 function applyPatches(uniDiff, options) {
1084 if (typeof uniDiff === 'string') {
1085 uniDiff = parsePatch(uniDiff);
1088 var currentIndex = 0;
1090 function processIndex() {
1091 var index = uniDiff[currentIndex++];
1094 return options.complete();
1097 options.loadFile(index, function (err, data) {
1099 return options.complete(err);
1102 var updatedContent = applyPatch(data, index, options);
1103 options.patched(index, updatedContent, function (err) {
1105 return options.complete(err);
1116 function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1121 if (typeof options.context === 'undefined') {
1122 options.context = 4;
1125 var diff = diffLines(oldStr, newStr, options);
1129 }); // Append an empty value to make cleanup easier
1131 function contextLines(lines) {
1132 return lines.map(function (entry) {
1138 var oldRangeStart = 0,
1144 var _loop = function _loop(i) {
1145 var current = diff[i],
1146 lines = current.lines || current.value.replace(/\n$/, '').split('\n');
1147 current.lines = lines;
1149 if (current.added || current.removed) {
1150 var _curRange; // If we have previous context, start with that
1153 if (!oldRangeStart) {
1154 var prev = diff[i - 1];
1155 oldRangeStart = oldLine;
1156 newRangeStart = newLine;
1159 curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
1160 oldRangeStart -= curRange.length;
1161 newRangeStart -= curRange.length;
1163 } // Output our changes
1166 (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
1167 return (current.added ? '+' : '-') + entry;
1168 }))); // Track the updated file position
1171 if (current.added) {
1172 newLine += lines.length;
1174 oldLine += lines.length;
1177 // Identical context lines. Track line changes
1178 if (oldRangeStart) {
1179 // Close out any changes that have been output (or join overlapping)
1180 if (lines.length <= options.context * 2 && i < diff.length - 2) {
1181 var _curRange2; // Overlapping
1184 (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
1186 var _curRange3; // end the range and output
1189 var contextSize = Math.min(lines.length, options.context);
1191 (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
1194 oldStart: oldRangeStart,
1195 oldLines: oldLine - oldRangeStart + contextSize,
1196 newStart: newRangeStart,
1197 newLines: newLine - newRangeStart + contextSize,
1201 if (i >= diff.length - 2 && lines.length <= options.context) {
1202 // EOF is inside this hunk
1203 var oldEOFNewline = /\n$/.test(oldStr);
1204 var newEOFNewline = /\n$/.test(newStr);
1205 var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
1207 if (!oldEOFNewline && noNlBeforeAdds) {
1208 // special case: old has no eol and no trailing context; no-nl can end up before adds
1209 curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
1212 if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
1213 curRange.push('\\ No newline at end of file');
1224 oldLine += lines.length;
1225 newLine += lines.length;
1229 for (var i = 0; i < diff.length; i++) {
1234 oldFileName: oldFileName,
1235 newFileName: newFileName,
1236 oldHeader: oldHeader,
1237 newHeader: newHeader,
1242 function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1243 var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
1246 if (oldFileName == newFileName) {
1247 ret.push('Index: ' + oldFileName);
1250 ret.push('===================================================================');
1251 ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
1252 ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
1254 for (var i = 0; i < diff.hunks.length; i++) {
1255 var hunk = diff.hunks[i];
1256 ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
1257 ret.push.apply(ret, hunk.lines);
1260 return ret.join('\n') + '\n';
1263 function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
1264 return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
1267 function arrayEqual(a, b) {
1268 if (a.length !== b.length) {
1272 return arrayStartsWith(a, b);
1275 function arrayStartsWith(array, start) {
1276 if (start.length > array.length) {
1280 for (var i = 0; i < start.length; i++) {
1281 if (start[i] !== array[i]) {
1289 function calcLineCount(hunk) {
1290 var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
1291 oldLines = _calcOldNewLineCount.oldLines,
1292 newLines = _calcOldNewLineCount.newLines;
1294 if (oldLines !== undefined) {
1295 hunk.oldLines = oldLines;
1297 delete hunk.oldLines;
1300 if (newLines !== undefined) {
1301 hunk.newLines = newLines;
1303 delete hunk.newLines;
1307 function merge(mine, theirs, base) {
1308 mine = loadPatch(mine, base);
1309 theirs = loadPatch(theirs, base);
1310 var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
1311 // Leaving sanity checks on this to the API consumer that may know more about the
1312 // meaning in their own context.
1314 if (mine.index || theirs.index) {
1315 ret.index = mine.index || theirs.index;
1318 if (mine.newFileName || theirs.newFileName) {
1319 if (!fileNameChanged(mine)) {
1320 // No header or no change in ours, use theirs (and ours if theirs does not exist)
1321 ret.oldFileName = theirs.oldFileName || mine.oldFileName;
1322 ret.newFileName = theirs.newFileName || mine.newFileName;
1323 ret.oldHeader = theirs.oldHeader || mine.oldHeader;
1324 ret.newHeader = theirs.newHeader || mine.newHeader;
1325 } else if (!fileNameChanged(theirs)) {
1326 // No header or no change in theirs, use ours
1327 ret.oldFileName = mine.oldFileName;
1328 ret.newFileName = mine.newFileName;
1329 ret.oldHeader = mine.oldHeader;
1330 ret.newHeader = mine.newHeader;
1332 // Both changed... figure it out
1333 ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
1334 ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
1335 ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
1336 ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
1346 while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
1347 var mineCurrent = mine.hunks[mineIndex] || {
1350 theirsCurrent = theirs.hunks[theirsIndex] || {
1354 if (hunkBefore(mineCurrent, theirsCurrent)) {
1355 // This patch does not overlap with any of the others, yay.
1356 ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
1358 theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
1359 } else if (hunkBefore(theirsCurrent, mineCurrent)) {
1360 // This patch does not overlap with any of the others, yay.
1361 ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
1363 mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
1365 // Overlap, merge as best we can
1367 oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
1369 newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
1373 mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
1376 ret.hunks.push(mergedHunk);
1383 function loadPatch(param, base) {
1384 if (typeof param === 'string') {
1385 if (/^@@/m.test(param) || /^Index:/m.test(param)) {
1386 return parsePatch(param)[0];
1390 throw new Error('Must provide a base reference or pass in a patch');
1393 return structuredPatch(undefined, undefined, base, param);
1399 function fileNameChanged(patch) {
1400 return patch.newFileName && patch.newFileName !== patch.oldFileName;
1403 function selectField(index, mine, theirs) {
1404 if (mine === theirs) {
1407 index.conflict = true;
1415 function hunkBefore(test, check) {
1416 return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
1419 function cloneHunk(hunk, offset) {
1421 oldStart: hunk.oldStart,
1422 oldLines: hunk.oldLines,
1423 newStart: hunk.newStart + offset,
1424 newLines: hunk.newLines,
1429 function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
1430 // This will generally result in a conflicted hunk, but there are cases where the context
1431 // is the only overlap where we can successfully merge the content here.
1438 offset: theirOffset,
1441 }; // Handle any leading content
1443 insertLeading(hunk, mine, their);
1444 insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
1446 while (mine.index < mine.lines.length && their.index < their.lines.length) {
1447 var mineCurrent = mine.lines[mine.index],
1448 theirCurrent = their.lines[their.index];
1450 if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
1451 // Both modified ...
1452 mutualChange(hunk, mine, their);
1453 } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
1454 var _hunk$lines; // Mine inserted
1457 (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
1458 } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
1459 var _hunk$lines2; // Theirs inserted
1462 (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
1463 } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
1464 // Mine removed or edited
1465 removal(hunk, mine, their);
1466 } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
1467 // Their removed or edited
1468 removal(hunk, their, mine, true);
1469 } else if (mineCurrent === theirCurrent) {
1471 hunk.lines.push(mineCurrent);
1476 conflict(hunk, collectChange(mine), collectChange(their));
1478 } // Now push anything that may be remaining
1481 insertTrailing(hunk, mine);
1482 insertTrailing(hunk, their);
1483 calcLineCount(hunk);
1486 function mutualChange(hunk, mine, their) {
1487 var myChanges = collectChange(mine),
1488 theirChanges = collectChange(their);
1490 if (allRemoves(myChanges) && allRemoves(theirChanges)) {
1491 // Special case for remove changes that are supersets of one another
1492 if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
1495 (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
1498 } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
1501 (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
1505 } else if (arrayEqual(myChanges, theirChanges)) {
1508 (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
1513 conflict(hunk, myChanges, theirChanges);
1516 function removal(hunk, mine, their, swap) {
1517 var myChanges = collectChange(mine),
1518 theirChanges = collectContext(their, myChanges);
1520 if (theirChanges.merged) {
1523 (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
1525 conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
1529 function conflict(hunk, mine, their) {
1530 hunk.conflict = true;
1538 function insertLeading(hunk, insert, their) {
1539 while (insert.offset < their.offset && insert.index < insert.lines.length) {
1540 var line = insert.lines[insert.index++];
1541 hunk.lines.push(line);
1546 function insertTrailing(hunk, insert) {
1547 while (insert.index < insert.lines.length) {
1548 var line = insert.lines[insert.index++];
1549 hunk.lines.push(line);
1553 function collectChange(state) {
1555 operation = state.lines[state.index][0];
1557 while (state.index < state.lines.length) {
1558 var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
1560 if (operation === '-' && line[0] === '+') {
1564 if (operation === line[0]) {
1575 function collectContext(state, matchChanges) {
1579 contextChanges = false,
1582 while (matchIndex < matchChanges.length && state.index < state.lines.length) {
1583 var change = state.lines[state.index],
1584 match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
1586 if (match[0] === '+') {
1590 contextChanges = contextChanges || change[0] !== ' ';
1592 matchIndex++; // Consume any additions in the other block as a conflict to attempt
1593 // to pull in the remaining context after this
1595 if (change[0] === '+') {
1598 while (change[0] === '+') {
1599 changes.push(change);
1600 change = state.lines[++state.index];
1604 if (match.substr(1) === change.substr(1)) {
1605 changes.push(change);
1612 if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
1620 while (matchIndex < matchChanges.length) {
1621 merged.push(matchChanges[matchIndex++]);
1630 function allRemoves(changes) {
1631 return changes.reduce(function (prev, change) {
1632 return prev && change[0] === '-';
1636 function skipRemoveSuperset(state, removeChanges, delta) {
1637 for (var i = 0; i < delta; i++) {
1638 var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
1640 if (state.lines[state.index + i] !== ' ' + changeContent) {
1645 state.index += delta;
1649 function calcOldNewLineCount(lines) {
1652 lines.forEach(function (line) {
1653 if (typeof line !== 'string') {
1654 var myCount = calcOldNewLineCount(line.mine);
1655 var theirCount = calcOldNewLineCount(line.theirs);
1657 if (oldLines !== undefined) {
1658 if (myCount.oldLines === theirCount.oldLines) {
1659 oldLines += myCount.oldLines;
1661 oldLines = undefined;
1665 if (newLines !== undefined) {
1666 if (myCount.newLines === theirCount.newLines) {
1667 newLines += myCount.newLines;
1669 newLines = undefined;
1673 if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
1677 if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
1686 } // See: http://code.google.com/p/google-diff-match-patch/wiki/API
1689 function convertChangesToDMP(changes) {
1694 for (var i = 0; i < changes.length; i++) {
1695 change = changes[i];
1699 } else if (change.removed) {
1705 ret.push([operation, change.value]);
1711 function convertChangesToXML(changes) {
1714 for (var i = 0; i < changes.length; i++) {
1715 var change = changes[i];
1719 } else if (change.removed) {
1723 ret.push(escapeHTML(change.value));
1727 } else if (change.removed) {
1732 return ret.join('');
1735 function escapeHTML(s) {
1737 n = n.replace(/&/g, '&');
1738 n = n.replace(/</g, '<');
1739 n = n.replace(/>/g, '>');
1740 n = n.replace(/"/g, '"');
1744 var index_es6 = /*#__PURE__*/Object.freeze({
1747 diffChars: diffChars,
1748 diffWords: diffWords,
1749 diffWordsWithSpace: diffWordsWithSpace,
1750 diffLines: diffLines,
1751 diffTrimmedLines: diffTrimmedLines,
1752 diffSentences: diffSentences,
1755 diffArrays: diffArrays,
1756 structuredPatch: structuredPatch,
1757 createTwoFilesPatch: createTwoFilesPatch,
1758 createPatch: createPatch,
1759 applyPatch: applyPatch,
1760 applyPatches: applyPatches,
1761 parsePatch: parsePatch,
1763 convertChangesToDMP: convertChangesToDMP,
1764 convertChangesToXML: convertChangesToXML,
1765 canonicalize: canonicalize
1774 constructor(file, options) {
1775 options = options || {};
1776 if (!options.readChunk) options.readChunk = 1024;
1778 if (!options.newLineCharacter) {
1779 options.newLineCharacter = 0x0a; //linux line ending
1781 options.newLineCharacter = options.newLineCharacter.charCodeAt(0);
1784 if (typeof file === 'number') {
1787 this.fd = fs$3.openSync(file, 'r');
1790 this.options = options;
1791 this.newLineCharacter = options.newLineCharacter;
1795 _searchInBuffer(buffer, hexNeedle) {
1798 for (let i = 0; i <= buffer.length; i++) {
1799 let b_byte = buffer[i];
1801 if (b_byte === hexNeedle) {
1811 this.eofReached = false;
1812 this.linesCache = [];
1813 this.fdPosition = 0;
1817 fs$3.closeSync(this.fd);
1821 _extractLines(buffer) {
1824 let bufferPosition = 0;
1825 let lastNewLineBufferPosition = 0;
1828 let bufferPositionValue = buffer[bufferPosition++];
1830 if (bufferPositionValue === this.newLineCharacter) {
1831 line = buffer.slice(lastNewLineBufferPosition, bufferPosition);
1833 lastNewLineBufferPosition = bufferPosition;
1834 } else if (!bufferPositionValue) {
1839 let leftovers = buffer.slice(lastNewLineBufferPosition, bufferPosition);
1841 if (leftovers.length) {
1842 lines.push(leftovers);
1848 _readChunk(lineLeftovers) {
1849 let totalBytesRead = 0;
1854 const readBuffer = new Buffer(this.options.readChunk);
1855 bytesRead = fs$3.readSync(this.fd, readBuffer, 0, this.options.readChunk, this.fdPosition);
1856 totalBytesRead = totalBytesRead + bytesRead;
1857 this.fdPosition = this.fdPosition + bytesRead;
1858 buffers.push(readBuffer);
1859 } while (bytesRead && this._searchInBuffer(buffers[buffers.length - 1], this.options.newLineCharacter) === -1);
1861 let bufferData = Buffer.concat(buffers);
1863 if (bytesRead < this.options.readChunk) {
1864 this.eofReached = true;
1865 bufferData = bufferData.slice(0, totalBytesRead);
1868 if (totalBytesRead) {
1869 this.linesCache = this._extractLines(bufferData);
1871 if (lineLeftovers) {
1872 this.linesCache[0] = Buffer.concat([lineLeftovers, this.linesCache[0]]);
1876 return totalBytesRead;
1880 if (!this.fd) return false;
1883 if (this.eofReached && this.linesCache.length === 0) {
1889 if (!this.linesCache.length) {
1890 bytesRead = this._readChunk();
1893 if (this.linesCache.length) {
1894 line = this.linesCache.shift();
1895 const lastLineCharacter = line[line.length - 1];
1897 if (lastLineCharacter !== 0x0a) {
1898 bytesRead = this._readChunk(line);
1901 line = this.linesCache.shift();
1906 if (this.eofReached && this.linesCache.length === 0) {
1910 if (line && line[line.length - 1] === this.newLineCharacter) {
1911 line = line.slice(0, line.length - 1);
1919 var readlines = LineByLine;
1922 * The inverse of `_.toPairs`; this method returns an object composed
1923 * from key-value `pairs`.
1929 * @param {Array} pairs The key-value pairs.
1930 * @returns {Object} Returns the new object.
1933 * _.fromPairs([['a', 1], ['b', 2]]);
1934 * // => { 'a': 1, 'b': 2 }
1936 function fromPairs(pairs) {
1938 length = pairs == null ? 0 : pairs.length,
1941 while (++index < length) {
1942 var pair = pairs[index];
1943 result[pair[0]] = pair[1];
1949 var fromPairs_1 = fromPairs;
1951 class ConfigError extends Error {}
1953 class DebugError extends Error {}
1955 class UndefinedParserError extends Error {}
1960 UndefinedParserError
1963 function _objectWithoutPropertiesLoose(source, excluded) {
1964 if (source == null) return {};
1966 var sourceKeys = Object.keys(source);
1969 for (i = 0; i < sourceKeys.length; i++) {
1970 key = sourceKeys[i];
1971 if (excluded.indexOf(key) >= 0) continue;
1972 target[key] = source[key];
1978 const debug = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error('SEMVER', ...args) : () => {};
1979 var debug_1 = debug;
1981 // Note: this is the semver.org version of the spec that it implements
1982 // Not necessarily the package version of this code.
1983 const SEMVER_SPEC_VERSION = '2.0.0';
1984 const MAX_LENGTH = 256;
1985 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
1986 /* istanbul ignore next */
1987 9007199254740991; // Max safe segment length for coercion.
1989 const MAX_SAFE_COMPONENT_LENGTH = 16;
1991 SEMVER_SPEC_VERSION,
1994 MAX_SAFE_COMPONENT_LENGTH
1997 function unwrapExports (x) {
1998 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
2001 function createCommonjsModule(fn, module) {
2002 return module = { exports: {} }, fn(module, module.exports), module.exports;
2005 function getCjsExportFromNamespace (n) {
2006 return n && n['default'] || n;
2009 var re_1 = createCommonjsModule(function (module, exports) {
2011 MAX_SAFE_COMPONENT_LENGTH
2013 exports = module.exports = {}; // The actual regexps go on exports.re
2015 const re = exports.re = [];
2016 const src = exports.src = [];
2017 const t = exports.t = {};
2020 const createToken = (name, value, isGlobal) => {
2022 debug_1(index, value);
2025 re[index] = new RegExp(value, isGlobal ? 'g' : undefined);
2026 }; // The following Regular Expressions can be used for tokenizing,
2027 // validating, and parsing SemVer version strings.
2028 // ## Numeric Identifier
2029 // A single `0`, or a non-zero digit followed by zero or more digits.
2032 createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*');
2033 createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); // ## Non-numeric Identifier
2034 // Zero or more digits, followed by a letter or hyphen, and then zero or
2035 // more letters, digits, or hyphens.
2037 createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); // ## Main Version
2038 // Three dot-separated numeric identifiers.
2040 createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`);
2041 createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); // ## Pre-release Version Identifier
2042 // A numeric identifier, or a non-numeric identifier.
2044 createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`);
2045 createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`); // ## Pre-release Version
2046 // Hyphen, followed by one or more dot-separated pre-release version
2049 createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
2050 createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); // ## Build Metadata Identifier
2051 // Any combination of digits, letters, or hyphens.
2053 createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); // ## Build Metadata
2054 // Plus sign, followed by one or more period-separated build metadata
2057 createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); // ## Full Version String
2058 // A main version, followed optionally by a pre-release version and
2060 // Note that the only major, minor, patch, and pre-release sections of
2061 // the version string are capturing groups. The build metadata is not a
2062 // capturing group, because it should not ever be used in version
2065 createToken('FULLPLAIN', `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
2066 createToken('FULL', `^${src[t.FULLPLAIN]}$`); // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
2067 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
2068 // common in the npm registry.
2070 createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
2071 createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`);
2072 createToken('GTLT', '((?:<|>)?=?)'); // Something like "2.*" or "1.2.x".
2073 // Note that "x.x" is a valid xRange identifer, meaning "any version"
2074 // Only the first item is strictly required.
2076 createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
2077 createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
2078 createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?` + `)?)?`);
2079 createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?` + `)?)?`);
2080 createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
2081 createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); // Coercion.
2082 // Extract anything that could conceivably be a part of a valid semver
2084 createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`);
2085 createToken('COERCERTL', src[t.COERCE], true); // Tilde ranges.
2086 // Meaning is "reasonably at or greater than"
2088 createToken('LONETILDE', '(?:~>?)');
2089 createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true);
2090 exports.tildeTrimReplace = '$1~';
2091 createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
2092 createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); // Caret ranges.
2093 // Meaning is "at least and backwards compatible with"
2095 createToken('LONECARET', '(?:\\^)');
2096 createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true);
2097 exports.caretTrimReplace = '$1^';
2098 createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
2099 createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); // A simple gt/lt/eq thing, or just "" to indicate "any version"
2101 createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
2102 createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); // An expression to strip any whitespace between the gtlt and the thing
2103 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
2105 createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
2106 exports.comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
2107 // Note that these all use the loose form, because they'll be
2108 // checked against either the strict or loose comparator form
2111 createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`);
2112 createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`); // Star ranges basically just allow anything at all.
2114 createToken('STAR', '(<|>)?=?\\s*\\*');
2117 var re_3 = re_1.src;
2119 var re_5 = re_1.tildeTrimReplace;
2120 var re_6 = re_1.caretTrimReplace;
2121 var re_7 = re_1.comparatorTrimReplace;
2123 const numeric = /^[0-9]+$/;
2125 const compareIdentifiers = (a, b) => {
2126 const anum = numeric.test(a);
2127 const bnum = numeric.test(b);
2134 return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
2137 const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
2145 MAX_LENGTH: MAX_LENGTH$1,
2146 MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1
2153 compareIdentifiers: compareIdentifiers$1
2157 constructor(version, options) {
2158 if (!options || typeof options !== 'object') {
2161 includePrerelease: false
2165 if (version instanceof SemVer) {
2166 if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
2169 version = version.version;
2171 } else if (typeof version !== 'string') {
2172 throw new TypeError(`Invalid Version: ${version}`);
2175 if (version.length > MAX_LENGTH$1) {
2176 throw new TypeError(`version is longer than ${MAX_LENGTH$1} characters`);
2179 debug_1('SemVer', version, options);
2180 this.options = options;
2181 this.loose = !!options.loose; // this isn't actually relevant for versions, but keep it so that we
2182 // don't run into trouble passing this.options around.
2184 this.includePrerelease = !!options.includePrerelease;
2185 const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
2188 throw new TypeError(`Invalid Version: ${version}`);
2191 this.raw = version; // these are actually numbers
2197 if (this.major > MAX_SAFE_INTEGER$1 || this.major < 0) {
2198 throw new TypeError('Invalid major version');
2201 if (this.minor > MAX_SAFE_INTEGER$1 || this.minor < 0) {
2202 throw new TypeError('Invalid minor version');
2205 if (this.patch > MAX_SAFE_INTEGER$1 || this.patch < 0) {
2206 throw new TypeError('Invalid patch version');
2207 } // numberify any prerelease numeric ids
2211 this.prerelease = [];
2213 this.prerelease = m[4].split('.').map(id => {
2214 if (/^[0-9]+$/.test(id)) {
2217 if (num >= 0 && num < MAX_SAFE_INTEGER$1) {
2226 this.build = m[5] ? m[5].split('.') : [];
2231 this.version = `${this.major}.${this.minor}.${this.patch}`;
2233 if (this.prerelease.length) {
2234 this.version += `-${this.prerelease.join('.')}`;
2237 return this.version;
2241 return this.version;
2245 debug_1('SemVer.compare', this.version, this.options, other);
2247 if (!(other instanceof SemVer)) {
2248 if (typeof other === 'string' && other === this.version) {
2252 other = new SemVer(other, this.options);
2255 if (other.version === this.version) {
2259 return this.compareMain(other) || this.comparePre(other);
2262 compareMain(other) {
2263 if (!(other instanceof SemVer)) {
2264 other = new SemVer(other, this.options);
2267 return compareIdentifiers$1(this.major, other.major) || compareIdentifiers$1(this.minor, other.minor) || compareIdentifiers$1(this.patch, other.patch);
2271 if (!(other instanceof SemVer)) {
2272 other = new SemVer(other, this.options);
2273 } // NOT having a prerelease is > having one
2276 if (this.prerelease.length && !other.prerelease.length) {
2278 } else if (!this.prerelease.length && other.prerelease.length) {
2280 } else if (!this.prerelease.length && !other.prerelease.length) {
2287 const a = this.prerelease[i];
2288 const b = other.prerelease[i];
2289 debug_1('prerelease compare', i, a, b);
2291 if (a === undefined && b === undefined) {
2293 } else if (b === undefined) {
2295 } else if (a === undefined) {
2297 } else if (a === b) {
2300 return compareIdentifiers$1(a, b);
2305 compareBuild(other) {
2306 if (!(other instanceof SemVer)) {
2307 other = new SemVer(other, this.options);
2313 const a = this.build[i];
2314 const b = other.build[i];
2315 debug_1('prerelease compare', i, a, b);
2317 if (a === undefined && b === undefined) {
2319 } else if (b === undefined) {
2321 } else if (a === undefined) {
2323 } else if (a === b) {
2326 return compareIdentifiers$1(a, b);
2329 } // preminor will bump the version up to the next minor release, and immediately
2330 // down to pre-release. premajor and prepatch work the same way.
2333 inc(release, identifier) {
2336 this.prerelease.length = 0;
2340 this.inc('pre', identifier);
2344 this.prerelease.length = 0;
2347 this.inc('pre', identifier);
2351 // If this is already a prerelease, it will bump to the next version
2352 // drop any prereleases that might already exist, since they are not
2353 // relevant at this point.
2354 this.prerelease.length = 0;
2355 this.inc('patch', identifier);
2356 this.inc('pre', identifier);
2358 // If the input is a non-prerelease version, this acts the same as
2362 if (this.prerelease.length === 0) {
2363 this.inc('patch', identifier);
2366 this.inc('pre', identifier);
2370 // If this is a pre-major version, bump up to the same major version.
2371 // Otherwise increment major.
2372 // 1.0.0-5 bumps to 1.0.0
2373 // 1.1.0 bumps to 2.0.0
2374 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
2380 this.prerelease = [];
2384 // If this is a pre-minor version, bump up to the same minor version.
2385 // Otherwise increment minor.
2386 // 1.2.0-5 bumps to 1.2.0
2387 // 1.2.1 bumps to 1.3.0
2388 if (this.patch !== 0 || this.prerelease.length === 0) {
2393 this.prerelease = [];
2397 // If this is not a pre-release version, it will increment the patch.
2398 // If it is a pre-release it will bump up to the same patch version.
2399 // 1.2.0-5 patches to 1.2.0
2400 // 1.2.0 patches to 1.2.1
2401 if (this.prerelease.length === 0) {
2405 this.prerelease = [];
2407 // This probably shouldn't be used publicly.
2408 // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
2411 if (this.prerelease.length === 0) {
2412 this.prerelease = [0];
2414 let i = this.prerelease.length;
2417 if (typeof this.prerelease[i] === 'number') {
2418 this.prerelease[i]++;
2424 // didn't increment anything
2425 this.prerelease.push(0);
2430 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
2431 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
2432 if (this.prerelease[0] === identifier) {
2433 if (isNaN(this.prerelease[1])) {
2434 this.prerelease = [identifier, 0];
2437 this.prerelease = [identifier, 0];
2444 throw new Error(`invalid increment argument: ${release}`);
2448 this.raw = this.version;
2454 var semver = SemVer;
2456 const compare = (a, b, loose) => new semver(a, loose).compare(new semver(b, loose));
2458 var compare_1 = compare;
2460 const lt = (a, b, loose) => compare_1(a, b, loose) < 0;
2464 const gte = (a, b, loose) => compare_1(a, b, loose) >= 0;
2468 var arrayify = (object, keyName) => Object.entries(object).map(([key, value]) => Object.assign({
2472 var dedent_1 = createCommonjsModule(function (module) {
2474 function dedent(strings) {
2477 if (typeof strings === "string") {
2478 // dedent can be used as a plain function
2482 } // first, perform interpolation
2487 for (var i = 0; i < raw.length; i++) {
2488 result += raw[i]. // join lines when there is a suppressed newline
2489 replace(/\\\n[ \t]*/g, ""). // handle escaped backticks
2490 replace(/\\`/g, "`");
2492 if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) {
2493 result += arguments.length <= i + 1 ? undefined : arguments[i + 1];
2495 } // now strip indentation
2498 var lines = result.split("\n");
2500 lines.forEach(function (l) {
2501 var m = l.match(/^(\s+)\S+/);
2504 var indent = m[1].length;
2507 // this is the first indented line
2510 mindent = Math.min(mindent, indent);
2515 if (mindent !== null) {
2516 result = lines.map(function (l) {
2517 return l[0] === " " ? l.slice(mindent) : l;
2519 } // dedent eats leading and trailing whitespace too
2522 result = result.trim(); // handle escaped newlines at the end to ensure they don't get stripped too
2524 return result.replace(/\\n/g, "\n");
2528 module.exports = dedent;
2532 const CATEGORY_CONFIG = "Config";
2533 const CATEGORY_EDITOR = "Editor";
2534 const CATEGORY_FORMAT = "Format";
2535 const CATEGORY_OTHER = "Other";
2536 const CATEGORY_OUTPUT = "Output";
2537 const CATEGORY_GLOBAL = "Global";
2538 const CATEGORY_SPECIAL = "Special";
2540 * @typedef {Object} OptionInfo
2541 * @property {string} [since] - available since version
2542 * @property {string} category
2543 * @property {'int' | 'boolean' | 'choice' | 'path'} type
2544 * @property {boolean} [array] - indicate it's an array of the specified type
2545 * @property {OptionValueInfo} [default]
2546 * @property {OptionRangeInfo} [range] - for type int
2547 * @property {string} description
2548 * @property {string} [deprecated] - deprecated since version
2549 * @property {OptionRedirectInfo} [redirect] - redirect deprecated option
2550 * @property {(value: any) => boolean} [exception]
2551 * @property {OptionChoiceInfo[]} [choices] - for type choice
2552 * @property {string} [cliName]
2553 * @property {string} [cliCategory]
2554 * @property {string} [cliDescription]
2556 * @typedef {number | boolean | string} OptionValue
2557 * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo
2559 * @typedef {Object} OptionRedirectInfo
2560 * @property {string} option
2561 * @property {OptionValue} value
2563 * @typedef {Object} OptionRangeInfo
2564 * @property {number} start - recommended range start
2565 * @property {number} end - recommended range end
2566 * @property {number} step - recommended range step
2568 * @typedef {Object} OptionChoiceInfo
2569 * @property {boolean | string} value - boolean for the option that is originally boolean type
2570 * @property {string} description
2571 * @property {string} [since] - undefined if available since the first version of the option
2572 * @property {string} [deprecated] - deprecated since version
2573 * @property {OptionValueInfo} [redirect] - redirect deprecated value
2576 /** @type {{ [name: string]: OptionInfo }} */
2581 category: CATEGORY_SPECIAL,
2589 description: dedent_1`
2590 Print (to stderr) where a cursor at the given position would move to after formatting.
2591 This option cannot be used with --range-start and --range-end.
2593 cliCategory: CATEGORY_EDITOR
2597 category: CATEGORY_GLOBAL,
2606 description: "Which end of line characters to apply.",
2609 description: "Line Feed only (\\n), common on Linux and macOS as well as inside git repos"
2612 description: "Carriage Return + Line Feed characters (\\r\\n), common on Windows"
2615 description: "Carriage Return character only (\\r), used very rarely"
2618 description: dedent_1`
2620 (mixed values within one file are normalised by looking at what's used after the first line)
2626 category: CATEGORY_SPECIAL,
2628 description: "Specify the input filepath. This will be used to do parser inference.",
2629 cliName: "stdin-filepath",
2630 cliCategory: CATEGORY_OTHER,
2631 cliDescription: "Path to the file to pretend that stdin comes from."
2635 category: CATEGORY_SPECIAL,
2638 description: "Insert @format pragma into file's first docblock comment.",
2639 cliCategory: CATEGORY_OTHER
2643 category: CATEGORY_GLOBAL,
2652 description: "Which parser to use.",
2653 exception: value => typeof value === "string" || typeof value === "function",
2660 description: "JavaScript"
2662 value: "babel-flow",
2668 description: "TypeScript"
2670 value: "typescript",
2672 description: "TypeScript"
2692 description: "JSON5"
2694 value: "json-stringify",
2696 description: "JSON.stringify"
2700 description: "GraphQL"
2704 description: "Markdown"
2720 description: "Handlebars"
2728 description: "Angular"
2732 description: "Lightning Web Components"
2742 category: CATEGORY_GLOBAL,
2743 description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.",
2744 exception: value => typeof value === "string" || typeof value === "object",
2746 cliCategory: CATEGORY_CONFIG
2755 category: CATEGORY_GLOBAL,
2756 description: dedent_1`
2757 Custom directory that contains prettier plugins in node_modules subdirectory.
2758 Overrides default behavior when plugins are searched relatively to the location of Prettier.
2759 Multiple values are accepted.
2761 exception: value => typeof value === "string" || typeof value === "object",
2762 cliName: "plugin-search-dir",
2763 cliCategory: CATEGORY_CONFIG
2767 category: CATEGORY_GLOBAL,
2770 description: "The line length where Prettier will try wrap.",
2779 category: CATEGORY_SPECIAL,
2787 description: dedent_1`
2788 Format code ending at a given character offset (exclusive).
2789 The range will extend forwards to the end of the selected statement.
2790 This option cannot be used with --cursor-offset.
2792 cliCategory: CATEGORY_EDITOR
2796 category: CATEGORY_SPECIAL,
2804 description: dedent_1`
2805 Format code starting at a given character offset.
2806 The range will extend backwards to the start of the first line containing the selected statement.
2807 This option cannot be used with --cursor-offset.
2809 cliCategory: CATEGORY_EDITOR
2813 category: CATEGORY_SPECIAL,
2816 description: dedent_1`
2817 Require either '@prettier' or '@format' to be present in the file's first docblock comment
2818 in order for it to be formatted.
2820 cliCategory: CATEGORY_OTHER
2824 category: CATEGORY_GLOBAL,
2826 description: "Number of spaces per indentation level.",
2835 category: CATEGORY_GLOBAL,
2838 description: "Indent with tabs instead of spaces."
2852 var require$$1 = getCjsExportFromNamespace(_package$1);
2859 const currentVersion = require$$1.version;
2860 const coreOptions$1 = coreOptions.options;
2862 * Strings in `plugins` and `pluginSearchDirs` are handled by a wrapped version
2863 * of this function created by `withPlugins`. Don't pass them here directly.
2864 * @param {object} param0
2865 * @param {(string | object)[]=} param0.plugins Strings are resolved by `withPlugins`.
2866 * @param {string[]=} param0.pluginSearchDirs Added by `withPlugins`.
2867 * @param {boolean=} param0.showUnreleased
2868 * @param {boolean=} param0.showDeprecated
2869 * @param {boolean=} param0.showInternal
2872 function getSupportInfo({
2874 showUnreleased = false,
2875 showDeprecated = false,
2876 showInternal = false
2878 // pre-release version is smaller than the normal version in semver,
2879 // we need to treat it as the normal one so as to test new features.
2880 const version = currentVersion.split("-", 1)[0];
2881 const options = arrayify(Object.assign({}, ...plugins.map(({
2883 }) => 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 => {
2884 option = Object.assign({}, option);
2886 if (Array.isArray(option.default)) {
2887 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;
2890 if (Array.isArray(option.choices)) {
2891 option.choices = option.choices.filter(option => filterSince(option) && filterDeprecated(option));
2894 const filteredPlugins = plugins.filter(plugin => plugin.defaultOptions && plugin.defaultOptions[option.name] !== undefined);
2895 const pluginDefaults = filteredPlugins.reduce((reduced, plugin) => {
2896 reduced[plugin.name] = plugin.defaultOptions[option.name];
2899 return Object.assign({}, option, {
2903 const languages = plugins.reduce((all, plugin) => all.concat(plugin.languages || []), []).filter(filterSince);
2909 function filterSince(object) {
2910 return showUnreleased || !("since" in object) || object.since && semver$1.gte(version, object.since);
2913 function filterDeprecated(object) {
2914 return showDeprecated || !("deprecated" in object) || object.deprecated && semver$1.lt(version, object.deprecated);
2917 function mapInternal(object) {
2922 const newObject = _objectWithoutPropertiesLoose(object, ["cliName", "cliCategory", "cliDescription"]);
2932 /*! *****************************************************************************
\r
2933 Copyright (c) Microsoft Corporation. All rights reserved.
\r
2934 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
\r
2935 this file except in compliance with the License. You may obtain a copy of the
\r
2936 License at http://www.apache.org/licenses/LICENSE-2.0
\r
2938 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
\r
2939 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
\r
2940 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
\r
2941 MERCHANTABLITY OR NON-INFRINGEMENT.
\r
2943 See the Apache Version 2.0 License for specific language governing permissions
\r
2944 and limitations under the License.
\r
2945 ***************************************************************************** */
2947 /* global Reflect, Promise */
2948 var extendStatics = function (d, b) {
2949 extendStatics = Object.setPrototypeOf || {
2951 } instanceof Array && function (d, b) {
2953 } || function (d, b) {
2954 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
2957 return extendStatics(d, b);
2960 function __extends(d, b) {
2961 extendStatics(d, b);
2964 this.constructor = d;
2967 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
2969 var __assign = function () {
2970 __assign = Object.assign || function __assign(t) {
2971 for (var s, i = 1, n = arguments.length; i < n; i++) {
2974 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
2980 return __assign.apply(this, arguments);
2982 function __rest(s, e) {
2985 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
2987 if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
2988 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
2992 function __decorate(decorators, target, key, desc) {
2993 var c = arguments.length,
2994 r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
2996 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;
2997 return c > 3 && r && Object.defineProperty(target, key, r), r;
2999 function __param(paramIndex, decorator) {
3000 return function (target, key) {
3001 decorator(target, key, paramIndex);
3004 function __metadata(metadataKey, metadataValue) {
3005 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
3007 function __awaiter(thisArg, _arguments, P, generator) {
3008 return new (P || (P = Promise))(function (resolve, reject) {
3009 function fulfilled(value) {
3011 step(generator.next(value));
3017 function rejected(value) {
3019 step(generator["throw"](value));
3025 function step(result) {
3026 result.done ? resolve(result.value) : new P(function (resolve) {
3027 resolve(result.value);
3028 }).then(fulfilled, rejected);
3031 step((generator = generator.apply(thisArg, _arguments || [])).next());
3034 function __generator(thisArg, body) {
3038 if (t[0] & 1) throw t[1];
3052 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
3057 return function (v) {
3058 return step([n, v]);
3063 if (f) throw new TypeError("Generator is already executing.");
3066 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;
3067 if (y = 0, t) op = [op[0] & 2, t.value];
3096 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
3101 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
3106 if (op[0] === 6 && _.label < t[1]) {
3112 if (t && _.label < t[2]) {
3120 if (t[2]) _.ops.pop();
3127 op = body.call(thisArg, _);
3135 if (op[0] & 5) throw op[1];
3137 value: op[0] ? op[1] : void 0,
3142 function __exportStar(m, exports) {
3143 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
3145 function __values(o) {
3146 var m = typeof Symbol === "function" && o[Symbol.iterator],
3148 if (m) return m.call(o);
3151 if (o && i >= o.length) o = void 0;
3159 function __read(o, n) {
3160 var m = typeof Symbol === "function" && o[Symbol.iterator];
3168 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
3175 if (r && !r.done && (m = i["return"])) m.call(i);
3177 if (e) throw e.error;
3183 function __spread() {
3184 for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
3188 function __spreadArrays() {
3189 for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
3191 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];
3195 function __await(v) {
3196 return this instanceof __await ? (this.v = v, this) : new __await(v);
3198 function __asyncGenerator(thisArg, _arguments, generator) {
3199 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
3200 var g = generator.apply(thisArg, _arguments || []),
3203 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
3208 if (g[n]) i[n] = function (v) {
3209 return new Promise(function (a, b) {
3210 q.push([n, v, a, b]) > 1 || resume(n, v);
3215 function resume(n, v) {
3224 r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
3227 function fulfill(value) {
3228 resume("next", value);
3231 function reject(value) {
3232 resume("throw", value);
3235 function settle(f, v) {
3236 if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
3239 function __asyncDelegator(o) {
3241 return i = {}, verb("next"), verb("throw", function (e) {
3243 }), verb("return"), i[Symbol.iterator] = function () {
3247 function verb(n, f) {
3248 i[n] = o[n] ? function (v) {
3250 value: __await(o[n](v)),
3251 done: n === "return"
3256 function __asyncValues(o) {
3257 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
3258 var m = o[Symbol.asyncIterator],
3260 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 () {
3265 i[n] = o[n] && function (v) {
3266 return new Promise(function (resolve, reject) {
3267 v = o[n](v), settle(resolve, reject, v.done, v.value);
3272 function settle(resolve, reject, d, v) {
3273 Promise.resolve(v).then(function (v) {
3281 function __makeTemplateObject(cooked, raw) {
3282 if (Object.defineProperty) {
3283 Object.defineProperty(cooked, "raw", {
3292 function __importStar(mod) {
3293 if (mod && mod.__esModule) return mod;
3295 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
3296 result.default = mod;
3299 function __importDefault(mod) {
3300 return mod && mod.__esModule ? mod : {
3305 var tslib_es6 = /*#__PURE__*/Object.freeze({
3307 __extends: __extends,
3308 get __assign () { return __assign; },
3310 __decorate: __decorate,
3312 __metadata: __metadata,
3313 __awaiter: __awaiter,
3314 __generator: __generator,
3315 __exportStar: __exportStar,
3319 __spreadArrays: __spreadArrays,
3321 __asyncGenerator: __asyncGenerator,
3322 __asyncDelegator: __asyncDelegator,
3323 __asyncValues: __asyncValues,
3324 __makeTemplateObject: __makeTemplateObject,
3325 __importStar: __importStar,
3326 __importDefault: __importDefault
3329 var api = createCommonjsModule(function (module, exports) {
3331 Object.defineProperty(exports, "__esModule", {
3334 exports.apiDescriptor = {
3335 key: key => /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(key) ? key : JSON.stringify(key),
3338 if (value === null || typeof value !== 'object') {
3339 return JSON.stringify(value);
3342 if (Array.isArray(value)) {
3343 return `[${value.map(subValue => exports.apiDescriptor.value(subValue)).join(', ')}]`;
3346 const keys = Object.keys(value);
3347 return keys.length === 0 ? '{}' : `{ ${keys.map(key => `${exports.apiDescriptor.key(key)}: ${exports.apiDescriptor.value(value[key])}`).join(', ')} }`;
3353 }) => exports.apiDescriptor.value({
3359 var api_1 = api.apiDescriptor;
3361 var tslib_1 = getCjsExportFromNamespace(tslib_es6);
3363 var descriptors = createCommonjsModule(function (module, exports) {
3365 Object.defineProperty(exports, "__esModule", {
3369 tslib_1.__exportStar(api, exports);
3371 unwrapExports(descriptors);
3373 var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
3375 var escapeStringRegexp = function (str) {
3376 if (typeof str !== 'string') {
3377 throw new TypeError('Expected a string');
3380 return str.replace(matchOperatorsRe, '\\$&');
3384 "aliceblue": [240, 248, 255],
3385 "antiquewhite": [250, 235, 215],
3386 "aqua": [0, 255, 255],
3387 "aquamarine": [127, 255, 212],
3388 "azure": [240, 255, 255],
3389 "beige": [245, 245, 220],
3390 "bisque": [255, 228, 196],
3392 "blanchedalmond": [255, 235, 205],
3393 "blue": [0, 0, 255],
3394 "blueviolet": [138, 43, 226],
3395 "brown": [165, 42, 42],
3396 "burlywood": [222, 184, 135],
3397 "cadetblue": [95, 158, 160],
3398 "chartreuse": [127, 255, 0],
3399 "chocolate": [210, 105, 30],
3400 "coral": [255, 127, 80],
3401 "cornflowerblue": [100, 149, 237],
3402 "cornsilk": [255, 248, 220],
3403 "crimson": [220, 20, 60],
3404 "cyan": [0, 255, 255],
3405 "darkblue": [0, 0, 139],
3406 "darkcyan": [0, 139, 139],
3407 "darkgoldenrod": [184, 134, 11],
3408 "darkgray": [169, 169, 169],
3409 "darkgreen": [0, 100, 0],
3410 "darkgrey": [169, 169, 169],
3411 "darkkhaki": [189, 183, 107],
3412 "darkmagenta": [139, 0, 139],
3413 "darkolivegreen": [85, 107, 47],
3414 "darkorange": [255, 140, 0],
3415 "darkorchid": [153, 50, 204],
3416 "darkred": [139, 0, 0],
3417 "darksalmon": [233, 150, 122],
3418 "darkseagreen": [143, 188, 143],
3419 "darkslateblue": [72, 61, 139],
3420 "darkslategray": [47, 79, 79],
3421 "darkslategrey": [47, 79, 79],
3422 "darkturquoise": [0, 206, 209],
3423 "darkviolet": [148, 0, 211],
3424 "deeppink": [255, 20, 147],
3425 "deepskyblue": [0, 191, 255],
3426 "dimgray": [105, 105, 105],
3427 "dimgrey": [105, 105, 105],
3428 "dodgerblue": [30, 144, 255],
3429 "firebrick": [178, 34, 34],
3430 "floralwhite": [255, 250, 240],
3431 "forestgreen": [34, 139, 34],
3432 "fuchsia": [255, 0, 255],
3433 "gainsboro": [220, 220, 220],
3434 "ghostwhite": [248, 248, 255],
3435 "gold": [255, 215, 0],
3436 "goldenrod": [218, 165, 32],
3437 "gray": [128, 128, 128],
3438 "green": [0, 128, 0],
3439 "greenyellow": [173, 255, 47],
3440 "grey": [128, 128, 128],
3441 "honeydew": [240, 255, 240],
3442 "hotpink": [255, 105, 180],
3443 "indianred": [205, 92, 92],
3444 "indigo": [75, 0, 130],
3445 "ivory": [255, 255, 240],
3446 "khaki": [240, 230, 140],
3447 "lavender": [230, 230, 250],
3448 "lavenderblush": [255, 240, 245],
3449 "lawngreen": [124, 252, 0],
3450 "lemonchiffon": [255, 250, 205],
3451 "lightblue": [173, 216, 230],
3452 "lightcoral": [240, 128, 128],
3453 "lightcyan": [224, 255, 255],
3454 "lightgoldenrodyellow": [250, 250, 210],
3455 "lightgray": [211, 211, 211],
3456 "lightgreen": [144, 238, 144],
3457 "lightgrey": [211, 211, 211],
3458 "lightpink": [255, 182, 193],
3459 "lightsalmon": [255, 160, 122],
3460 "lightseagreen": [32, 178, 170],
3461 "lightskyblue": [135, 206, 250],
3462 "lightslategray": [119, 136, 153],
3463 "lightslategrey": [119, 136, 153],
3464 "lightsteelblue": [176, 196, 222],
3465 "lightyellow": [255, 255, 224],
3466 "lime": [0, 255, 0],
3467 "limegreen": [50, 205, 50],
3468 "linen": [250, 240, 230],
3469 "magenta": [255, 0, 255],
3470 "maroon": [128, 0, 0],
3471 "mediumaquamarine": [102, 205, 170],
3472 "mediumblue": [0, 0, 205],
3473 "mediumorchid": [186, 85, 211],
3474 "mediumpurple": [147, 112, 219],
3475 "mediumseagreen": [60, 179, 113],
3476 "mediumslateblue": [123, 104, 238],
3477 "mediumspringgreen": [0, 250, 154],
3478 "mediumturquoise": [72, 209, 204],
3479 "mediumvioletred": [199, 21, 133],
3480 "midnightblue": [25, 25, 112],
3481 "mintcream": [245, 255, 250],
3482 "mistyrose": [255, 228, 225],
3483 "moccasin": [255, 228, 181],
3484 "navajowhite": [255, 222, 173],
3485 "navy": [0, 0, 128],
3486 "oldlace": [253, 245, 230],
3487 "olive": [128, 128, 0],
3488 "olivedrab": [107, 142, 35],
3489 "orange": [255, 165, 0],
3490 "orangered": [255, 69, 0],
3491 "orchid": [218, 112, 214],
3492 "palegoldenrod": [238, 232, 170],
3493 "palegreen": [152, 251, 152],
3494 "paleturquoise": [175, 238, 238],
3495 "palevioletred": [219, 112, 147],
3496 "papayawhip": [255, 239, 213],
3497 "peachpuff": [255, 218, 185],
3498 "peru": [205, 133, 63],
3499 "pink": [255, 192, 203],
3500 "plum": [221, 160, 221],
3501 "powderblue": [176, 224, 230],
3502 "purple": [128, 0, 128],
3503 "rebeccapurple": [102, 51, 153],
3505 "rosybrown": [188, 143, 143],
3506 "royalblue": [65, 105, 225],
3507 "saddlebrown": [139, 69, 19],
3508 "salmon": [250, 128, 114],
3509 "sandybrown": [244, 164, 96],
3510 "seagreen": [46, 139, 87],
3511 "seashell": [255, 245, 238],
3512 "sienna": [160, 82, 45],
3513 "silver": [192, 192, 192],
3514 "skyblue": [135, 206, 235],
3515 "slateblue": [106, 90, 205],
3516 "slategray": [112, 128, 144],
3517 "slategrey": [112, 128, 144],
3518 "snow": [255, 250, 250],
3519 "springgreen": [0, 255, 127],
3520 "steelblue": [70, 130, 180],
3521 "tan": [210, 180, 140],
3522 "teal": [0, 128, 128],
3523 "thistle": [216, 191, 216],
3524 "tomato": [255, 99, 71],
3525 "turquoise": [64, 224, 208],
3526 "violet": [238, 130, 238],
3527 "wheat": [245, 222, 179],
3528 "white": [255, 255, 255],
3529 "whitesmoke": [245, 245, 245],
3530 "yellow": [255, 255, 0],
3531 "yellowgreen": [154, 205, 50]
3534 var conversions = createCommonjsModule(function (module) {
3536 // NOTE: conversions should only return primitive values (i.e. arrays, or
3537 // values that give correct `typeof` results).
3538 // do not use box values types (i.e. Number(), String(), etc.)
3539 var reverseKeywords = {};
3541 for (var key in colorName) {
3542 if (colorName.hasOwnProperty(key)) {
3543 reverseKeywords[colorName[key]] = key;
3547 var convert = module.exports = {
3598 labels: ['h', 'c', 'g']
3602 labels: ['r16', 'g16', 'b16']
3608 }; // hide .channels and .labels properties
3610 for (var model in convert) {
3611 if (convert.hasOwnProperty(model)) {
3612 if (!('channels' in convert[model])) {
3613 throw new Error('missing channels property: ' + model);
3616 if (!('labels' in convert[model])) {
3617 throw new Error('missing channel labels property: ' + model);
3620 if (convert[model].labels.length !== convert[model].channels) {
3621 throw new Error('channel and label counts mismatch: ' + model);
3624 var channels = convert[model].channels;
3625 var labels = convert[model].labels;
3626 delete convert[model].channels;
3627 delete convert[model].labels;
3628 Object.defineProperty(convert[model], 'channels', {
3631 Object.defineProperty(convert[model], 'labels', {
3637 convert.rgb.hsl = function (rgb) {
3638 var r = rgb[0] / 255;
3639 var g = rgb[1] / 255;
3640 var b = rgb[2] / 255;
3641 var min = Math.min(r, g, b);
3642 var max = Math.max(r, g, b);
3643 var delta = max - min;
3650 } else if (r === max) {
3651 h = (g - b) / delta;
3652 } else if (g === max) {
3653 h = 2 + (b - r) / delta;
3654 } else if (b === max) {
3655 h = 4 + (r - g) / delta;
3658 h = Math.min(h * 60, 360);
3664 l = (min + max) / 2;
3668 } else if (l <= 0.5) {
3669 s = delta / (max + min);
3671 s = delta / (2 - max - min);
3674 return [h, s * 100, l * 100];
3677 convert.rgb.hsv = function (rgb) {
3683 var r = rgb[0] / 255;
3684 var g = rgb[1] / 255;
3685 var b = rgb[2] / 255;
3686 var v = Math.max(r, g, b);
3687 var diff = v - Math.min(r, g, b);
3689 var diffc = function (c) {
3690 return (v - c) / 6 / diff + 1 / 2;
3703 } else if (g === v) {
3704 h = 1 / 3 + rdif - bdif;
3705 } else if (b === v) {
3706 h = 2 / 3 + gdif - rdif;
3716 return [h * 360, s * 100, v * 100];
3719 convert.rgb.hwb = function (rgb) {
3723 var h = convert.rgb.hsl(rgb)[0];
3724 var w = 1 / 255 * Math.min(r, Math.min(g, b));
3725 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
3726 return [h, w * 100, b * 100];
3729 convert.rgb.cmyk = function (rgb) {
3730 var r = rgb[0] / 255;
3731 var g = rgb[1] / 255;
3732 var b = rgb[2] / 255;
3737 k = Math.min(1 - r, 1 - g, 1 - b);
3738 c = (1 - r - k) / (1 - k) || 0;
3739 m = (1 - g - k) / (1 - k) || 0;
3740 y = (1 - b - k) / (1 - k) || 0;
3741 return [c * 100, m * 100, y * 100, k * 100];
3744 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
3748 function comparativeDistance(x, y) {
3749 return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
3752 convert.rgb.keyword = function (rgb) {
3753 var reversed = reverseKeywords[rgb];
3759 var currentClosestDistance = Infinity;
3760 var currentClosestKeyword;
3762 for (var keyword in colorName) {
3763 if (colorName.hasOwnProperty(keyword)) {
3764 var value = colorName[keyword]; // Compute comparative distance
3766 var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
3768 if (distance < currentClosestDistance) {
3769 currentClosestDistance = distance;
3770 currentClosestKeyword = keyword;
3775 return currentClosestKeyword;
3778 convert.keyword.rgb = function (keyword) {
3779 return colorName[keyword];
3782 convert.rgb.xyz = function (rgb) {
3783 var r = rgb[0] / 255;
3784 var g = rgb[1] / 255;
3785 var b = rgb[2] / 255; // assume sRGB
3787 r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
3788 g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
3789 b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
3790 var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
3791 var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
3792 var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
3793 return [x * 100, y * 100, z * 100];
3796 convert.rgb.lab = function (rgb) {
3797 var xyz = convert.rgb.xyz(rgb);
3807 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
3808 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
3809 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
3816 convert.hsl.rgb = function (hsl) {
3817 var h = hsl[0] / 360;
3818 var s = hsl[1] / 100;
3819 var l = hsl[2] / 100;
3828 return [val, val, val];
3840 for (var i = 0; i < 3; i++) {
3841 t3 = h + 1 / 3 * -(i - 1);
3852 val = t1 + (t2 - t1) * 6 * t3;
3853 } else if (2 * t3 < 1) {
3855 } else if (3 * t3 < 2) {
3856 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
3867 convert.hsl.hsv = function (hsl) {
3869 var s = hsl[1] / 100;
3870 var l = hsl[2] / 100;
3872 var lmin = Math.max(l, 0.01);
3876 s *= l <= 1 ? l : 2 - l;
3877 smin *= lmin <= 1 ? lmin : 2 - lmin;
3879 sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
3880 return [h, sv * 100, v * 100];
3883 convert.hsv.rgb = function (hsv) {
3884 var h = hsv[0] / 60;
3885 var s = hsv[1] / 100;
3886 var v = hsv[2] / 100;
3887 var hi = Math.floor(h) % 6;
3888 var f = h - Math.floor(h);
3889 var p = 255 * v * (1 - s);
3890 var q = 255 * v * (1 - s * f);
3891 var t = 255 * v * (1 - s * (1 - f));
3915 convert.hsv.hsl = function (hsv) {
3917 var s = hsv[1] / 100;
3918 var v = hsv[2] / 100;
3919 var vmin = Math.max(v, 0.01);
3924 lmin = (2 - s) * vmin;
3926 sl /= lmin <= 1 ? lmin : 2 - lmin;
3929 return [h, sl * 100, l * 100];
3930 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
3933 convert.hwb.rgb = function (hwb) {
3934 var h = hwb[0] / 360;
3935 var wh = hwb[1] / 100;
3936 var bl = hwb[2] / 100;
3937 var ratio = wh + bl;
3941 var n; // wh + bl cant be > 1
3948 i = Math.floor(6 * h);
3952 if ((i & 0x01) !== 0) {
3956 n = wh + f * (v - wh); // linear interpolation
4002 return [r * 255, g * 255, b * 255];
4005 convert.cmyk.rgb = function (cmyk) {
4006 var c = cmyk[0] / 100;
4007 var m = cmyk[1] / 100;
4008 var y = cmyk[2] / 100;
4009 var k = cmyk[3] / 100;
4013 r = 1 - Math.min(1, c * (1 - k) + k);
4014 g = 1 - Math.min(1, m * (1 - k) + k);
4015 b = 1 - Math.min(1, y * (1 - k) + k);
4016 return [r * 255, g * 255, b * 255];
4019 convert.xyz.rgb = function (xyz) {
4020 var x = xyz[0] / 100;
4021 var y = xyz[1] / 100;
4022 var z = xyz[2] / 100;
4026 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
4027 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
4028 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
4030 r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
4031 g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
4032 b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
4033 r = Math.min(Math.max(0, r), 1);
4034 g = Math.min(Math.max(0, g), 1);
4035 b = Math.min(Math.max(0, b), 1);
4036 return [r * 255, g * 255, b * 255];
4039 convert.xyz.lab = function (xyz) {
4049 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
4050 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
4051 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
4058 convert.lab.xyz = function (lab) {
4068 var y2 = Math.pow(y, 3);
4069 var x2 = Math.pow(x, 3);
4070 var z2 = Math.pow(z, 3);
4071 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
4072 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
4073 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
4080 convert.lab.lch = function (lab) {
4087 hr = Math.atan2(b, a);
4088 h = hr * 360 / 2 / Math.PI;
4094 c = Math.sqrt(a * a + b * b);
4098 convert.lch.lab = function (lch) {
4105 hr = h / 360 * 2 * Math.PI;
4106 a = c * Math.cos(hr);
4107 b = c * Math.sin(hr);
4111 convert.rgb.ansi16 = function (args) {
4115 var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
4117 value = Math.round(value / 50);
4123 var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
4132 convert.hsv.ansi16 = function (args) {
4133 // optimization here; we already know the value and don't need to get
4134 // it converted for us.
4135 return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
4138 convert.rgb.ansi256 = function (args) {
4141 var b = args[2]; // we use the extended greyscale palette here, with the exception of
4142 // black and white. normal palette only has 4 greyscale shades.
4144 if (r === g && g === b) {
4153 return Math.round((r - 8) / 247 * 24) + 232;
4156 var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
4160 convert.ansi16.rgb = function (args) {
4161 var color = args % 10; // handle greyscale
4163 if (color === 0 || color === 7) {
4168 color = color / 10.5 * 255;
4169 return [color, color, color];
4172 var mult = (~~(args > 50) + 1) * 0.5;
4173 var r = (color & 1) * mult * 255;
4174 var g = (color >> 1 & 1) * mult * 255;
4175 var b = (color >> 2 & 1) * mult * 255;
4179 convert.ansi256.rgb = function (args) {
4182 var c = (args - 232) * 10 + 8;
4188 var r = Math.floor(args / 36) / 5 * 255;
4189 var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
4190 var b = rem % 6 / 5 * 255;
4194 convert.rgb.hex = function (args) {
4195 var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
4196 var string = integer.toString(16).toUpperCase();
4197 return '000000'.substring(string.length) + string;
4200 convert.hex.rgb = function (args) {
4201 var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
4207 var colorString = match[0];
4209 if (match[0].length === 3) {
4210 colorString = colorString.split('').map(function (char) {
4215 var integer = parseInt(colorString, 16);
4216 var r = integer >> 16 & 0xFF;
4217 var g = integer >> 8 & 0xFF;
4218 var b = integer & 0xFF;
4222 convert.rgb.hcg = function (rgb) {
4223 var r = rgb[0] / 255;
4224 var g = rgb[1] / 255;
4225 var b = rgb[2] / 255;
4226 var max = Math.max(Math.max(r, g), b);
4227 var min = Math.min(Math.min(r, g), b);
4228 var chroma = max - min;
4233 grayscale = min / (1 - chroma);
4240 } else if (max === r) {
4241 hue = (g - b) / chroma % 6;
4242 } else if (max === g) {
4243 hue = 2 + (b - r) / chroma;
4245 hue = 4 + (r - g) / chroma + 4;
4250 return [hue * 360, chroma * 100, grayscale * 100];
4253 convert.hsl.hcg = function (hsl) {
4254 var s = hsl[1] / 100;
4255 var l = hsl[2] / 100;
4262 c = 2.0 * s * (1.0 - l);
4266 f = (l - 0.5 * c) / (1.0 - c);
4269 return [hsl[0], c * 100, f * 100];
4272 convert.hsv.hcg = function (hsv) {
4273 var s = hsv[1] / 100;
4274 var v = hsv[2] / 100;
4279 f = (v - c) / (1 - c);
4282 return [hsv[0], c * 100, f * 100];
4285 convert.hcg.rgb = function (hcg) {
4286 var h = hcg[0] / 360;
4287 var c = hcg[1] / 100;
4288 var g = hcg[2] / 100;
4291 return [g * 255, g * 255, g * 255];
4294 var pure = [0, 0, 0];
4300 switch (Math.floor(hi)) {
4338 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
4341 convert.hcg.hsv = function (hcg) {
4342 var c = hcg[1] / 100;
4343 var g = hcg[2] / 100;
4344 var v = c + g * (1.0 - c);
4351 return [hcg[0], f * 100, v * 100];
4354 convert.hcg.hsl = function (hcg) {
4355 var c = hcg[1] / 100;
4356 var g = hcg[2] / 100;
4357 var l = g * (1.0 - c) + 0.5 * c;
4360 if (l > 0.0 && l < 0.5) {
4362 } else if (l >= 0.5 && l < 1.0) {
4363 s = c / (2 * (1 - l));
4366 return [hcg[0], s * 100, l * 100];
4369 convert.hcg.hwb = function (hcg) {
4370 var c = hcg[1] / 100;
4371 var g = hcg[2] / 100;
4372 var v = c + g * (1.0 - c);
4373 return [hcg[0], (v - c) * 100, (1 - v) * 100];
4376 convert.hwb.hcg = function (hwb) {
4377 var w = hwb[1] / 100;
4378 var b = hwb[2] / 100;
4384 g = (v - c) / (1 - c);
4387 return [hwb[0], c * 100, g * 100];
4390 convert.apple.rgb = function (apple) {
4391 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
4394 convert.rgb.apple = function (rgb) {
4395 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
4398 convert.gray.rgb = function (args) {
4399 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
4402 convert.gray.hsl = convert.gray.hsv = function (args) {
4403 return [0, 0, args[0]];
4406 convert.gray.hwb = function (gray) {
4407 return [0, 100, gray[0]];
4410 convert.gray.cmyk = function (gray) {
4411 return [0, 0, 0, gray[0]];
4414 convert.gray.lab = function (gray) {
4415 return [gray[0], 0, 0];
4418 convert.gray.hex = function (gray) {
4419 var val = Math.round(gray[0] / 100 * 255) & 0xFF;
4420 var integer = (val << 16) + (val << 8) + val;
4421 var string = integer.toString(16).toUpperCase();
4422 return '000000'.substring(string.length) + string;
4425 convert.rgb.gray = function (rgb) {
4426 var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
4427 return [val / 255 * 100];
4430 var conversions_1 = conversions.rgb;
4431 var conversions_2 = conversions.hsl;
4432 var conversions_3 = conversions.hsv;
4433 var conversions_4 = conversions.hwb;
4434 var conversions_5 = conversions.cmyk;
4435 var conversions_6 = conversions.xyz;
4436 var conversions_7 = conversions.lab;
4437 var conversions_8 = conversions.lch;
4438 var conversions_9 = conversions.hex;
4439 var conversions_10 = conversions.keyword;
4440 var conversions_11 = conversions.ansi16;
4441 var conversions_12 = conversions.ansi256;
4442 var conversions_13 = conversions.hcg;
4443 var conversions_14 = conversions.apple;
4444 var conversions_15 = conversions.gray;
4447 this function routes a model to all other models.
4449 all functions that are routed have a property `.conversion` attached
4450 to the returned synthetic function. This property is an array
4451 of strings, each with the steps in between the 'from' and 'to'
4452 color models (inclusive).
4454 conversions that are not possible simply are not included.
4457 function buildGraph() {
4458 var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
4460 var models = Object.keys(conversions);
4462 for (var len = models.length, i = 0; i < len; i++) {
4463 graph[models[i]] = {
4464 // http://jsperf.com/1-vs-infinity
4465 // micro-opt, but this is simple.
4472 } // https://en.wikipedia.org/wiki/Breadth-first_search
4475 function deriveBFS(fromModel) {
4476 var graph = buildGraph();
4477 var queue = [fromModel]; // unshift -> queue -> pop
4479 graph[fromModel].distance = 0;
4481 while (queue.length) {
4482 var current = queue.pop();
4483 var adjacents = Object.keys(conversions[current]);
4485 for (var len = adjacents.length, i = 0; i < len; i++) {
4486 var adjacent = adjacents[i];
4487 var node = graph[adjacent];
4489 if (node.distance === -1) {
4490 node.distance = graph[current].distance + 1;
4491 node.parent = current;
4492 queue.unshift(adjacent);
4500 function link(from, to) {
4501 return function (args) {
4502 return to(from(args));
4506 function wrapConversion(toModel, graph) {
4507 var path = [graph[toModel].parent, toModel];
4508 var fn = conversions[graph[toModel].parent][toModel];
4509 var cur = graph[toModel].parent;
4511 while (graph[cur].parent) {
4512 path.unshift(graph[cur].parent);
4513 fn = link(conversions[graph[cur].parent][cur], fn);
4514 cur = graph[cur].parent;
4517 fn.conversion = path;
4521 var route = function (fromModel) {
4522 var graph = deriveBFS(fromModel);
4523 var conversion = {};
4524 var models = Object.keys(graph);
4526 for (var len = models.length, i = 0; i < len; i++) {
4527 var toModel = models[i];
4528 var node = graph[toModel];
4530 if (node.parent === null) {
4531 // no possible conversion, or this node is the source model.
4535 conversion[toModel] = wrapConversion(toModel, graph);
4542 var models = Object.keys(conversions);
4544 function wrapRaw(fn) {
4545 var wrappedFn = function (args) {
4546 if (args === undefined || args === null) {
4550 if (arguments.length > 1) {
4551 args = Array.prototype.slice.call(arguments);
4555 }; // preserve .conversion property if there is one
4558 if ('conversion' in fn) {
4559 wrappedFn.conversion = fn.conversion;
4565 function wrapRounded(fn) {
4566 var wrappedFn = function (args) {
4567 if (args === undefined || args === null) {
4571 if (arguments.length > 1) {
4572 args = Array.prototype.slice.call(arguments);
4575 var result = fn(args); // we're assuming the result is an array here.
4576 // see notice in conversions.js; don't use box types
4577 // in conversion functions.
4579 if (typeof result === 'object') {
4580 for (var len = result.length, i = 0; i < len; i++) {
4581 result[i] = Math.round(result[i]);
4586 }; // preserve .conversion property if there is one
4589 if ('conversion' in fn) {
4590 wrappedFn.conversion = fn.conversion;
4596 models.forEach(function (fromModel) {
4597 convert[fromModel] = {};
4598 Object.defineProperty(convert[fromModel], 'channels', {
4599 value: conversions[fromModel].channels
4601 Object.defineProperty(convert[fromModel], 'labels', {
4602 value: conversions[fromModel].labels
4604 var routes = route(fromModel);
4605 var routeModels = Object.keys(routes);
4606 routeModels.forEach(function (toModel) {
4607 var fn = routes[toModel];
4608 convert[fromModel][toModel] = wrapRounded(fn);
4609 convert[fromModel][toModel].raw = wrapRaw(fn);
4612 var colorConvert = convert;
4614 var ansiStyles = createCommonjsModule(function (module) {
4616 const wrapAnsi16 = (fn, offset) => function () {
4617 const code = fn.apply(colorConvert, arguments);
4618 return `\u001B[${code + offset}m`;
4621 const wrapAnsi256 = (fn, offset) => function () {
4622 const code = fn.apply(colorConvert, arguments);
4623 return `\u001B[${38 + offset};5;${code}m`;
4626 const wrapAnsi16m = (fn, offset) => function () {
4627 const rgb = fn.apply(colorConvert, arguments);
4628 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
4631 function assembleStyles() {
4632 const codes = new Map();
4636 // 21 isn't widely supported and 22 does the same thing
4643 strikethrough: [9, 29]
4656 redBright: [91, 39],
4657 greenBright: [92, 39],
4658 yellowBright: [93, 39],
4659 blueBright: [94, 39],
4660 magentaBright: [95, 39],
4661 cyanBright: [96, 39],
4662 whiteBright: [97, 39]
4670 bgMagenta: [45, 49],
4674 bgBlackBright: [100, 49],
4675 bgRedBright: [101, 49],
4676 bgGreenBright: [102, 49],
4677 bgYellowBright: [103, 49],
4678 bgBlueBright: [104, 49],
4679 bgMagentaBright: [105, 49],
4680 bgCyanBright: [106, 49],
4681 bgWhiteBright: [107, 49]
4685 styles.color.grey = styles.color.gray;
4687 for (const groupName of Object.keys(styles)) {
4688 const group = styles[groupName];
4690 for (const styleName of Object.keys(group)) {
4691 const style = group[styleName];
4692 styles[styleName] = {
4693 open: `\u001B[${style[0]}m`,
4694 close: `\u001B[${style[1]}m`
4696 group[styleName] = styles[styleName];
4697 codes.set(style[0], style[1]);
4700 Object.defineProperty(styles, groupName, {
4704 Object.defineProperty(styles, 'codes', {
4710 const ansi2ansi = n => n;
4712 const rgb2rgb = (r, g, b) => [r, g, b];
4714 styles.color.close = '\u001B[39m';
4715 styles.bgColor.close = '\u001B[49m';
4716 styles.color.ansi = {
4717 ansi: wrapAnsi16(ansi2ansi, 0)
4719 styles.color.ansi256 = {
4720 ansi256: wrapAnsi256(ansi2ansi, 0)
4722 styles.color.ansi16m = {
4723 rgb: wrapAnsi16m(rgb2rgb, 0)
4725 styles.bgColor.ansi = {
4726 ansi: wrapAnsi16(ansi2ansi, 10)
4728 styles.bgColor.ansi256 = {
4729 ansi256: wrapAnsi256(ansi2ansi, 10)
4731 styles.bgColor.ansi16m = {
4732 rgb: wrapAnsi16m(rgb2rgb, 10)
4735 for (let key of Object.keys(colorConvert)) {
4736 if (typeof colorConvert[key] !== 'object') {
4740 const suite = colorConvert[key];
4742 if (key === 'ansi16') {
4746 if ('ansi16' in suite) {
4747 styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
4748 styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
4751 if ('ansi256' in suite) {
4752 styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
4753 styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
4756 if ('rgb' in suite) {
4757 styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
4758 styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
4763 } // Make the export immutable
4766 Object.defineProperty(module, 'exports', {
4772 var hasFlag = (flag, argv) => {
4773 argv = argv || process.argv;
4774 const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
4775 const pos = argv.indexOf(prefix + flag);
4776 const terminatorPos = argv.indexOf('--');
4777 return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
4780 const env = process.env;
4783 if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
4785 } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
4789 if ('FORCE_COLOR' in env) {
4790 forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
4793 function translateLevel(level) {
4806 function supportsColor(stream) {
4807 if (forceColor === false) {
4811 if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
4815 if (hasFlag('color=256')) {
4819 if (stream && !stream.isTTY && forceColor !== true) {
4823 const min = forceColor ? 1 : 0;
4825 if (process.platform === 'win32') {
4826 // Node.js 7.5.0 is the first version of Node.js to include a patch to
4827 // libuv that enables 256 color output on Windows. Anything earlier and it
4828 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
4829 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
4830 // release that supports 256 colors. Windows 10 build 14931 is the first release
4831 // that supports 16m/TrueColor.
4832 const osRelease = os$1.release().split('.');
4834 if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
4835 return Number(osRelease[2]) >= 14931 ? 3 : 2;
4842 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
4849 if ('TEAMCITY_VERSION' in env) {
4850 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
4853 if (env.COLORTERM === 'truecolor') {
4857 if ('TERM_PROGRAM' in env) {
4858 const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
4860 switch (env.TERM_PROGRAM) {
4862 return version >= 3 ? 3 : 2;
4864 case 'Apple_Terminal':
4870 if (/-256(color)?$/i.test(env.TERM)) {
4874 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
4878 if ('COLORTERM' in env) {
4882 if (env.TERM === 'dumb') {
4889 function getSupportLevel(stream) {
4890 const level = supportsColor(stream);
4891 return translateLevel(level);
4894 var supportsColor_1 = {
4895 supportsColor: getSupportLevel,
4896 stdout: getSupportLevel(process.stdout),
4897 stderr: getSupportLevel(process.stderr)
4900 const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
4901 const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
4902 const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
4903 const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
4904 const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
4906 function unescape(c) {
4907 if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
4908 return String.fromCharCode(parseInt(c.slice(1), 16));
4911 return ESCAPES.get(c) || c;
4914 function parseArguments(name, args) {
4916 const chunks = args.trim().split(/\s*,\s*/g);
4919 for (const chunk of chunks) {
4920 if (!isNaN(chunk)) {
4921 results.push(Number(chunk));
4922 } else if (matches = chunk.match(STRING_REGEX)) {
4923 results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
4925 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
4932 function parseStyle(style) {
4933 STYLE_REGEX.lastIndex = 0;
4937 while ((matches = STYLE_REGEX.exec(style)) !== null) {
4938 const name = matches[1];
4941 const args = parseArguments(name, matches[2]);
4942 results.push([name].concat(args));
4944 results.push([name]);
4951 function buildStyle(chalk, styles) {
4954 for (const layer of styles) {
4955 for (const style of layer.styles) {
4956 enabled[style[0]] = layer.inverse ? null : style.slice(1);
4960 let current = chalk;
4962 for (const styleName of Object.keys(enabled)) {
4963 if (Array.isArray(enabled[styleName])) {
4964 if (!(styleName in current)) {
4965 throw new Error(`Unknown Chalk style: ${styleName}`);
4968 if (enabled[styleName].length > 0) {
4969 current = current[styleName].apply(current, enabled[styleName]);
4971 current = current[styleName];
4979 var templates = (chalk, tmp) => {
4982 let chunk = []; // eslint-disable-next-line max-params
4984 tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
4986 chunk.push(unescape(escapeChar));
4988 const str = chunk.join('');
4990 chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
4993 styles: parseStyle(style)
4996 if (styles.length === 0) {
4997 throw new Error('Found extraneous } in Chalk template literal');
5000 chunks.push(buildStyle(chalk, styles)(chunk.join('')));
5007 chunks.push(chunk.join(''));
5009 if (styles.length > 0) {
5010 const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
5011 throw new Error(errMsg);
5014 return chunks.join('');
5017 var chalk = createCommonjsModule(function (module) {
5019 const stdoutColor = supportsColor_1.stdout;
5020 const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
5022 const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
5024 const skipModels = new Set(['gray']);
5025 const styles = Object.create(null);
5027 function applyOptions(obj, options) {
5028 options = options || {}; // Detect level if not set manually
5030 const scLevel = stdoutColor ? stdoutColor.level : 0;
5031 obj.level = options.level === undefined ? scLevel : options.level;
5032 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
5035 function Chalk(options) {
5036 // We check for this.template here since calling `chalk.constructor()`
5037 // by itself will have a `this` of a previously constructed chalk object
5038 if (!this || !(this instanceof Chalk) || this.template) {
5040 applyOptions(chalk, options);
5042 chalk.template = function () {
5043 const args = [].slice.call(arguments);
5044 return chalkTag.apply(null, [chalk.template].concat(args));
5047 Object.setPrototypeOf(chalk, Chalk.prototype);
5048 Object.setPrototypeOf(chalk.template, chalk);
5049 chalk.template.constructor = Chalk;
5050 return chalk.template;
5053 applyOptions(this, options);
5054 } // Use bright blue on Windows as the normal blue color is illegible
5057 if (isSimpleWindowsTerm) {
5058 ansiStyles.blue.open = '\u001B[94m';
5061 for (const key of Object.keys(ansiStyles)) {
5062 ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
5065 const codes = ansiStyles[key];
5066 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
5074 return build.call(this, this._styles || [], true, 'visible');
5078 ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
5080 for (const model of Object.keys(ansiStyles.color.ansi)) {
5081 if (skipModels.has(model)) {
5087 const level = this.level;
5088 return function () {
5089 const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
5092 close: ansiStyles.color.close,
5093 closeRe: ansiStyles.color.closeRe
5095 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
5102 ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
5104 for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
5105 if (skipModels.has(model)) {
5109 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
5112 const level = this.level;
5113 return function () {
5114 const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
5117 close: ansiStyles.bgColor.close,
5118 closeRe: ansiStyles.bgColor.closeRe
5120 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
5127 const proto = Object.defineProperties(() => {}, styles);
5129 function build(_styles, _empty, key) {
5130 const builder = function () {
5131 return applyStyle.apply(builder, arguments);
5134 builder._styles = _styles;
5135 builder._empty = _empty;
5137 Object.defineProperty(builder, 'level', {
5149 Object.defineProperty(builder, 'enabled', {
5153 return self.enabled;
5157 self.enabled = enabled;
5160 }); // See below for fix regarding invisible grey/dim combination on Windows
5162 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
5163 // no way to create a function with a different prototype
5165 builder.__proto__ = proto; // eslint-disable-line no-proto
5170 function applyStyle() {
5171 // Support varags, but simply cast to string in case there's only one arg
5172 const args = arguments;
5173 const argsLen = args.length;
5174 let str = String(arguments[0]);
5176 if (argsLen === 0) {
5181 // Don't slice `arguments`, it prevents V8 optimizations
5182 for (let a = 1; a < argsLen; a++) {
5183 str += ' ' + args[a];
5187 if (!this.enabled || this.level <= 0 || !str) {
5188 return this._empty ? '' : str;
5189 } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
5190 // see https://github.com/chalk/chalk/issues/58
5191 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
5194 const originalDim = ansiStyles.dim.open;
5196 if (isSimpleWindowsTerm && this.hasGrey) {
5197 ansiStyles.dim.open = '';
5200 for (const code of this._styles.slice().reverse()) {
5201 // Replace any instances already present with a re-opening code
5202 // otherwise only the part of the string until said closing code
5203 // will be colored, and the rest will simply be 'plain'.
5204 str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
5205 // after next line to fix a bleed issue on macOS
5206 // https://github.com/chalk/chalk/pull/92
5208 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
5209 } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
5212 ansiStyles.dim.open = originalDim;
5216 function chalkTag(chalk, strings) {
5217 if (!Array.isArray(strings)) {
5218 // If chalk() was called by itself or with a string,
5219 // return the string itself as a string.
5220 return [].slice.call(arguments, 1).join(' ');
5223 const args = [].slice.call(arguments, 2);
5224 const parts = [strings.raw[0]];
5226 for (let i = 1; i < strings.length; i++) {
5227 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
5228 parts.push(String(strings.raw[i]));
5231 return templates(chalk, parts.join(''));
5234 Object.defineProperties(Chalk.prototype, styles);
5235 module.exports = Chalk(); // eslint-disable-line new-cap
5237 module.exports.supportsColor = stdoutColor;
5238 module.exports.default = module.exports; // For TypeScript
5240 var chalk_1 = chalk.supportsColor;
5242 var common = createCommonjsModule(function (module, exports) {
5244 Object.defineProperty(exports, "__esModule", {
5248 exports.commonDeprecatedHandler = (keyOrPair, redirectTo, {
5251 const messages = [`${chalk.default.yellow(typeof keyOrPair === 'string' ? descriptor.key(keyOrPair) : descriptor.pair(keyOrPair))} is deprecated`];
5254 messages.push(`we now treat it as ${chalk.default.blue(typeof redirectTo === 'string' ? descriptor.key(redirectTo) : descriptor.pair(redirectTo))}`);
5257 return messages.join('; ') + '.';
5260 unwrapExports(common);
5261 var common_1 = common.commonDeprecatedHandler;
5263 var deprecated = createCommonjsModule(function (module, exports) {
5265 Object.defineProperty(exports, "__esModule", {
5269 tslib_1.__exportStar(common, exports);
5271 unwrapExports(deprecated);
5273 var common$1 = createCommonjsModule(function (module, exports) {
5275 Object.defineProperty(exports, "__esModule", {
5279 exports.commonInvalidHandler = (key, value, utils) => [`Invalid ${chalk.default.red(utils.descriptor.key(key))} value.`, `Expected ${chalk.default.blue(utils.schemas[key].expected(utils))},`, `but received ${chalk.default.red(utils.descriptor.value(value))}.`].join(' ');
5281 unwrapExports(common$1);
5282 var common_1$1 = common$1.commonInvalidHandler;
5284 var invalid = createCommonjsModule(function (module, exports) {
5286 Object.defineProperty(exports, "__esModule", {
5290 tslib_1.__exportStar(common$1, exports);
5292 unwrapExports(invalid);
5294 /* eslint-disable no-nested-ternary */
5297 var charCodeCache = [];
5299 var leven = function (a, b) {
5304 var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the
5305 // shortest & which one is the longest
5307 if (a.length > b.length) {
5312 var aLen = a.length;
5313 var bLen = b.length;
5321 } // Performing suffix trimming:
5322 // We can linearly drop suffix common to both strings since they
5323 // don't increase distance at all
5324 // Note: `~-` is the bitwise way to perform a `- 1` operation
5327 while (aLen > 0 && a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen)) {
5334 } // Performing prefix trimming
5335 // We can linearly drop prefix common to both strings since they
5336 // don't increase distance at all
5341 while (start < aLen && a.charCodeAt(start) === b.charCodeAt(start)) {
5360 charCodeCache[start + i] = a.charCodeAt(start + i);
5365 bCharCode = b.charCodeAt(start + j);
5369 for (i = 0; i < aLen; i++) {
5370 tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1;
5372 ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2;
5379 var leven_1 = createCommonjsModule(function (module, exports) {
5381 Object.defineProperty(exports, "__esModule", {
5385 exports.levenUnknownHandler = (key, value, {
5390 const messages = [`Ignored unknown option ${chalk.default.yellow(descriptor.pair({
5394 const suggestion = Object.keys(schemas).sort().find(knownKey => leven(key, knownKey) < 3);
5397 messages.push(`Did you mean ${chalk.default.blue(descriptor.key(suggestion))}?`);
5400 logger.warn(messages.join(' '));
5403 unwrapExports(leven_1);
5404 var leven_2 = leven_1.levenUnknownHandler;
5406 var unknown = createCommonjsModule(function (module, exports) {
5408 Object.defineProperty(exports, "__esModule", {
5412 tslib_1.__exportStar(leven_1, exports);
5414 unwrapExports(unknown);
5416 var handlers = createCommonjsModule(function (module, exports) {
5418 Object.defineProperty(exports, "__esModule", {
5422 tslib_1.__exportStar(deprecated, exports);
5424 tslib_1.__exportStar(invalid, exports);
5426 tslib_1.__exportStar(unknown, exports);
5428 unwrapExports(handlers);
5430 var schema = createCommonjsModule(function (module, exports) {
5432 Object.defineProperty(exports, "__esModule", {
5435 const HANDLER_KEYS = ['default', 'expected', 'validate', 'deprecated', 'forward', 'redirect', 'overlap', 'preprocess', 'postprocess'];
5437 function createSchema(SchemaConstructor, parameters) {
5438 const schema = new SchemaConstructor(parameters);
5439 const subSchema = Object.create(schema);
5441 for (const handlerKey of HANDLER_KEYS) {
5442 if (handlerKey in parameters) {
5443 subSchema[handlerKey] = normalizeHandler(parameters[handlerKey], schema, Schema.prototype[handlerKey].length);
5450 exports.createSchema = createSchema;
5453 constructor(parameters) {
5454 this.name = parameters.name;
5457 static create(parameters) {
5458 // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/5863
5459 return createSchema(this, parameters);
5464 } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
5469 } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
5472 validate(_value, _utils) {
5476 deprecated(_value, _utils) {
5480 forward(_value, _utils) {
5484 redirect(_value, _utils) {
5488 overlap(currentValue, _newValue, _utils) {
5489 return currentValue;
5492 preprocess(value, _utils) {
5496 postprocess(value, _utils) {
5502 exports.Schema = Schema;
5504 function normalizeHandler(handler, superSchema, handlerArgumentsLength) {
5505 return typeof handler === 'function' ? (...args) => handler(...args.slice(0, handlerArgumentsLength - 1), superSchema, ...args.slice(handlerArgumentsLength - 1)) : () => handler;
5508 unwrapExports(schema);
5509 var schema_1 = schema.createSchema;
5510 var schema_2 = schema.Schema;
5512 var alias = createCommonjsModule(function (module, exports) {
5514 Object.defineProperty(exports, "__esModule", {
5518 class AliasSchema extends schema.Schema {
5519 constructor(parameters) {
5521 this._sourceName = parameters.sourceName;
5525 return utils.schemas[this._sourceName].expected(utils);
5528 validate(value, utils) {
5529 return utils.schemas[this._sourceName].validate(value, utils);
5532 redirect(_value, _utils) {
5533 return this._sourceName;
5538 exports.AliasSchema = AliasSchema;
5540 unwrapExports(alias);
5541 var alias_1 = alias.AliasSchema;
5543 var any = createCommonjsModule(function (module, exports) {
5545 Object.defineProperty(exports, "__esModule", {
5549 class AnySchema extends schema.Schema {
5560 exports.AnySchema = AnySchema;
5563 var any_1 = any.AnySchema;
5565 var array = createCommonjsModule(function (module, exports) {
5567 Object.defineProperty(exports, "__esModule", {
5571 class ArraySchema extends schema.Schema {
5575 name = valueSchema.name
5577 handlers = tslib_1.__rest(_a, ["valueSchema", "name"]);
5579 super(Object.assign({}, handlers, {
5582 this._valueSchema = valueSchema;
5586 return `an array of ${this._valueSchema.expected(utils)}`;
5589 validate(value, utils) {
5590 if (!Array.isArray(value)) {
5594 const invalidValues = [];
5596 for (const subValue of value) {
5597 const subValidateResult = utils.normalizeValidateResult(this._valueSchema.validate(subValue, utils), subValue);
5599 if (subValidateResult !== true) {
5600 invalidValues.push(subValidateResult.value);
5604 return invalidValues.length === 0 ? true : {
5605 value: invalidValues
5609 deprecated(value, utils) {
5610 const deprecatedResult = [];
5612 for (const subValue of value) {
5613 const subDeprecatedResult = utils.normalizeDeprecatedResult(this._valueSchema.deprecated(subValue, utils), subValue);
5615 if (subDeprecatedResult !== false) {
5616 deprecatedResult.push(...subDeprecatedResult.map(({
5617 value: deprecatedValue
5619 value: [deprecatedValue]
5624 return deprecatedResult;
5627 forward(value, utils) {
5628 const forwardResult = [];
5630 for (const subValue of value) {
5631 const subForwardResult = utils.normalizeForwardResult(this._valueSchema.forward(subValue, utils), subValue);
5632 forwardResult.push(...subForwardResult.map(wrapTransferResult));
5635 return forwardResult;
5638 redirect(value, utils) {
5640 const redirect = [];
5642 for (const subValue of value) {
5643 const subRedirectResult = utils.normalizeRedirectResult(this._valueSchema.redirect(subValue, utils), subValue);
5645 if ('remain' in subRedirectResult) {
5646 remain.push(subRedirectResult.remain);
5649 redirect.push(...subRedirectResult.redirect.map(wrapTransferResult));
5652 return remain.length === 0 ? {
5660 overlap(currentValue, newValue) {
5661 return currentValue.concat(newValue);
5666 exports.ArraySchema = ArraySchema;
5668 function wrapTransferResult({
5678 unwrapExports(array);
5679 var array_1 = array.ArraySchema;
5681 var boolean_1 = createCommonjsModule(function (module, exports) {
5683 Object.defineProperty(exports, "__esModule", {
5687 class BooleanSchema extends schema.Schema {
5689 return 'true or false';
5693 return typeof value === 'boolean';
5698 exports.BooleanSchema = BooleanSchema;
5700 unwrapExports(boolean_1);
5701 var boolean_2 = boolean_1.BooleanSchema;
5703 var utils = createCommonjsModule(function (module, exports) {
5705 Object.defineProperty(exports, "__esModule", {
5709 function recordFromArray(array, mainKey) {
5710 const record = Object.create(null);
5712 for (const value of array) {
5713 const key = value[mainKey]; // istanbul ignore next
5716 throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`);
5720 record[key] = value;
5726 exports.recordFromArray = recordFromArray;
5728 function mapFromArray(array, mainKey) {
5729 const map = new Map();
5731 for (const value of array) {
5732 const key = value[mainKey]; // istanbul ignore next
5735 throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`);
5738 map.set(key, value);
5744 exports.mapFromArray = mapFromArray;
5746 function createAutoChecklist() {
5747 const map = Object.create(null);
5749 const idString = JSON.stringify(id);
5751 if (map[idString]) {
5755 map[idString] = true;
5760 exports.createAutoChecklist = createAutoChecklist;
5762 function partition(array, predicate) {
5763 const trueArray = [];
5764 const falseArray = [];
5766 for (const value of array) {
5767 if (predicate(value)) {
5768 trueArray.push(value);
5770 falseArray.push(value);
5774 return [trueArray, falseArray];
5777 exports.partition = partition;
5779 function isInt(value) {
5780 return value === Math.floor(value);
5783 exports.isInt = isInt;
5785 function comparePrimitive(a, b) {
5790 const typeofA = typeof a;
5791 const typeofB = typeof b;
5792 const orders = ['undefined', 'object', 'boolean', 'number', 'string'];
5794 if (typeofA !== typeofB) {
5795 return orders.indexOf(typeofA) - orders.indexOf(typeofB);
5798 if (typeofA !== 'string') {
5799 return Number(a) - Number(b);
5802 return a.localeCompare(b);
5805 exports.comparePrimitive = comparePrimitive;
5807 function normalizeDefaultResult(result) {
5808 return result === undefined ? {} : result;
5811 exports.normalizeDefaultResult = normalizeDefaultResult;
5813 function normalizeValidateResult(result, value) {
5814 return result === true ? true : result === false ? {
5819 exports.normalizeValidateResult = normalizeValidateResult;
5821 function normalizeDeprecatedResult(result, value, doNotNormalizeTrue = false) {
5822 return result === false ? false : result === true ? doNotNormalizeTrue ? true : [{
5824 }] : 'value' in result ? [result] : result.length === 0 ? false : result;
5827 exports.normalizeDeprecatedResult = normalizeDeprecatedResult;
5829 function normalizeTransferResult(result, value) {
5830 return typeof result === 'string' || 'key' in result ? {
5833 } : 'from' in result ? {
5842 exports.normalizeTransferResult = normalizeTransferResult;
5844 function normalizeForwardResult(result, value) {
5845 return result === undefined ? [] : Array.isArray(result) ? result.map(transferResult => normalizeTransferResult(transferResult, value)) : [normalizeTransferResult(result, value)];
5848 exports.normalizeForwardResult = normalizeForwardResult;
5850 function normalizeRedirectResult(result, value) {
5851 const redirect = normalizeForwardResult(typeof result === 'object' && 'redirect' in result ? result.redirect : result, value);
5852 return redirect.length === 0 ? {
5855 } : typeof result === 'object' && 'remain' in result ? {
5856 remain: result.remain,
5863 exports.normalizeRedirectResult = normalizeRedirectResult;
5865 unwrapExports(utils);
5866 var utils_1 = utils.recordFromArray;
5867 var utils_2 = utils.mapFromArray;
5868 var utils_3 = utils.createAutoChecklist;
5869 var utils_4 = utils.partition;
5870 var utils_5 = utils.isInt;
5871 var utils_6 = utils.comparePrimitive;
5872 var utils_7 = utils.normalizeDefaultResult;
5873 var utils_8 = utils.normalizeValidateResult;
5874 var utils_9 = utils.normalizeDeprecatedResult;
5875 var utils_10 = utils.normalizeTransferResult;
5876 var utils_11 = utils.normalizeForwardResult;
5877 var utils_12 = utils.normalizeRedirectResult;
5879 var choice = createCommonjsModule(function (module, exports) {
5881 Object.defineProperty(exports, "__esModule", {
5885 class ChoiceSchema extends schema.Schema {
5886 constructor(parameters) {
5888 this._choices = utils.mapFromArray(parameters.choices.map(choice => choice && typeof choice === 'object' ? choice : {
5896 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);
5897 const head = choiceValues.slice(0, -2);
5898 const tail = choiceValues.slice(-2);
5899 return head.concat(tail.join(' or ')).join(', ');
5903 return this._choices.has(value);
5907 const choiceInfo = this._choices.get(value);
5909 return choiceInfo && choiceInfo.deprecated ? {
5915 const choiceInfo = this._choices.get(value);
5917 return choiceInfo ? choiceInfo.forward : undefined;
5921 const choiceInfo = this._choices.get(value);
5923 return choiceInfo ? choiceInfo.redirect : undefined;
5928 exports.ChoiceSchema = ChoiceSchema;
5930 unwrapExports(choice);
5931 var choice_1 = choice.ChoiceSchema;
5933 var number = createCommonjsModule(function (module, exports) {
5935 Object.defineProperty(exports, "__esModule", {
5939 class NumberSchema extends schema.Schema {
5944 validate(value, _utils) {
5945 return typeof value === 'number';
5950 exports.NumberSchema = NumberSchema;
5952 unwrapExports(number);
5953 var number_1 = number.NumberSchema;
5955 var integer = createCommonjsModule(function (module, exports) {
5957 Object.defineProperty(exports, "__esModule", {
5961 class IntegerSchema extends number.NumberSchema {
5963 return 'an integer';
5966 validate(value, utils$1) {
5967 return utils$1.normalizeValidateResult(super.validate(value, utils$1), value) === true && utils.isInt(value);
5972 exports.IntegerSchema = IntegerSchema;
5974 unwrapExports(integer);
5975 var integer_1 = integer.IntegerSchema;
5977 var string = createCommonjsModule(function (module, exports) {
5979 Object.defineProperty(exports, "__esModule", {
5983 class StringSchema extends schema.Schema {
5989 return typeof value === 'string';
5994 exports.StringSchema = StringSchema;
5996 unwrapExports(string);
5997 var string_1 = string.StringSchema;
5999 var schemas = createCommonjsModule(function (module, exports) {
6001 Object.defineProperty(exports, "__esModule", {
6005 tslib_1.__exportStar(alias, exports);
6007 tslib_1.__exportStar(any, exports);
6009 tslib_1.__exportStar(array, exports);
6011 tslib_1.__exportStar(boolean_1, exports);
6013 tslib_1.__exportStar(choice, exports);
6015 tslib_1.__exportStar(integer, exports);
6017 tslib_1.__exportStar(number, exports);
6019 tslib_1.__exportStar(string, exports);
6021 unwrapExports(schemas);
6023 var defaults = createCommonjsModule(function (module, exports) {
6025 Object.defineProperty(exports, "__esModule", {
6028 exports.defaultDescriptor = api.apiDescriptor;
6029 exports.defaultUnknownHandler = leven_1.levenUnknownHandler;
6030 exports.defaultInvalidHandler = invalid.commonInvalidHandler;
6031 exports.defaultDeprecatedHandler = common.commonDeprecatedHandler;
6033 unwrapExports(defaults);
6034 var defaults_1 = defaults.defaultDescriptor;
6035 var defaults_2 = defaults.defaultUnknownHandler;
6036 var defaults_3 = defaults.defaultInvalidHandler;
6037 var defaults_4 = defaults.defaultDeprecatedHandler;
6039 var normalize = createCommonjsModule(function (module, exports) {
6041 Object.defineProperty(exports, "__esModule", {
6045 exports.normalize = (options, schemas, opts) => new Normalizer(schemas, opts).normalize(options);
6048 constructor(schemas, opts) {
6049 // istanbul ignore next
6052 descriptor = defaults.defaultDescriptor,
6053 unknown = defaults.defaultUnknownHandler,
6054 invalid = defaults.defaultInvalidHandler,
6055 deprecated = defaults.defaultDeprecatedHandler
6060 /* istanbul ignore next */
6064 schemas: utils.recordFromArray(schemas, 'name'),
6065 normalizeDefaultResult: utils.normalizeDefaultResult,
6066 normalizeDeprecatedResult: utils.normalizeDeprecatedResult,
6067 normalizeForwardResult: utils.normalizeForwardResult,
6068 normalizeRedirectResult: utils.normalizeRedirectResult,
6069 normalizeValidateResult: utils.normalizeValidateResult
6071 this._unknownHandler = unknown;
6072 this._invalidHandler = invalid;
6073 this._deprecatedHandler = deprecated;
6074 this.cleanHistory();
6078 this._hasDeprecationWarned = utils.createAutoChecklist();
6081 normalize(options) {
6082 const normalized = {};
6083 const restOptionsArray = [options];
6085 const applyNormalization = () => {
6086 while (restOptionsArray.length !== 0) {
6087 const currentOptions = restOptionsArray.shift();
6089 const transferredOptionsArray = this._applyNormalization(currentOptions, normalized);
6091 restOptionsArray.push(...transferredOptionsArray);
6095 applyNormalization();
6097 for (const key of Object.keys(this._utils.schemas)) {
6098 const schema = this._utils.schemas[key];
6100 if (!(key in normalized)) {
6101 const defaultResult = utils.normalizeDefaultResult(schema.default(this._utils));
6103 if ('value' in defaultResult) {
6104 restOptionsArray.push({
6105 [key]: defaultResult.value
6111 applyNormalization();
6113 for (const key of Object.keys(this._utils.schemas)) {
6114 const schema = this._utils.schemas[key];
6116 if (key in normalized) {
6117 normalized[key] = schema.postprocess(normalized[key], this._utils);
6124 _applyNormalization(options, normalized) {
6125 const transferredOptionsArray = [];
6126 const [knownOptionNames, unknownOptionNames] = utils.partition(Object.keys(options), key => key in this._utils.schemas);
6128 for (const key of knownOptionNames) {
6129 const schema = this._utils.schemas[key];
6130 const value = schema.preprocess(options[key], this._utils);
6131 const validateResult = utils.normalizeValidateResult(schema.validate(value, this._utils), value);
6133 if (validateResult !== true) {
6138 const errorMessageOrError = this._invalidHandler(key, invalidValue, this._utils);
6140 throw typeof errorMessageOrError === 'string' ? new Error(errorMessageOrError) :
6141 /* istanbul ignore next*/
6142 errorMessageOrError;
6145 const appendTransferredOptions = ({
6149 transferredOptionsArray.push(typeof to === 'string' ? {
6156 const warnDeprecated = ({
6157 value: currentValue,
6160 const deprecatedResult = utils.normalizeDeprecatedResult(schema.deprecated(currentValue, this._utils), value,
6161 /* doNotNormalizeTrue */
6164 if (deprecatedResult === false) {
6168 if (deprecatedResult === true) {
6169 if (!this._hasDeprecationWarned(key)) {
6170 this._utils.logger.warn(this._deprecatedHandler(key, redirectTo, this._utils));
6174 value: deprecatedValue
6175 } of deprecatedResult) {
6178 value: deprecatedValue
6181 if (!this._hasDeprecationWarned(pair)) {
6182 const redirectToPair = typeof redirectTo === 'string' ? {
6184 value: deprecatedValue
6187 this._utils.logger.warn(this._deprecatedHandler(pair, redirectToPair, this._utils));
6193 const forwardResult = utils.normalizeForwardResult(schema.forward(value, this._utils), value);
6194 forwardResult.forEach(appendTransferredOptions);
6195 const redirectResult = utils.normalizeRedirectResult(schema.redirect(value, this._utils), value);
6196 redirectResult.redirect.forEach(appendTransferredOptions);
6198 if ('remain' in redirectResult) {
6199 const remainingValue = redirectResult.remain;
6200 normalized[key] = key in normalized ? schema.overlap(normalized[key], remainingValue, this._utils) : remainingValue;
6202 value: remainingValue
6209 } of redirectResult.redirect) {
6217 for (const key of unknownOptionNames) {
6218 const value = options[key];
6220 const unknownResult = this._unknownHandler(key, value, this._utils);
6222 if (unknownResult) {
6223 for (const unknownKey of Object.keys(unknownResult)) {
6224 const unknownOption = {
6225 [unknownKey]: unknownResult[unknownKey]
6228 if (unknownKey in this._utils.schemas) {
6229 transferredOptionsArray.push(unknownOption);
6231 Object.assign(normalized, unknownOption);
6237 return transferredOptionsArray;
6242 exports.Normalizer = Normalizer;
6244 unwrapExports(normalize);
6245 var normalize_1 = normalize.normalize;
6246 var normalize_2 = normalize.Normalizer;
6248 var lib = createCommonjsModule(function (module, exports) {
6250 Object.defineProperty(exports, "__esModule", {
6254 tslib_1.__exportStar(descriptors, exports);
6256 tslib_1.__exportStar(handlers, exports);
6258 tslib_1.__exportStar(schemas, exports);
6260 tslib_1.__exportStar(normalize, exports);
6262 tslib_1.__exportStar(schema, exports);
6267 const charCodeCache$1 = [];
6269 const leven$1 = (left, right) => {
6270 if (left === right) {
6274 const swap = left; // Swapping the strings if `a` is longer than `b` so we know which one is the
6275 // shortest & which one is the longest
6277 if (left.length > right.length) {
6282 let leftLength = left.length;
6283 let rightLength = right.length; // Performing suffix trimming:
6284 // We can linearly drop suffix common to both strings since they
6285 // don't increase distance at all
6286 // Note: `~-` is the bitwise way to perform a `- 1` operation
6288 while (leftLength > 0 && left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength)) {
6291 } // Performing prefix trimming
6292 // We can linearly drop prefix common to both strings since they
6293 // don't increase distance at all
6298 while (start < leftLength && left.charCodeAt(start) === right.charCodeAt(start)) {
6302 leftLength -= start;
6303 rightLength -= start;
6305 if (leftLength === 0) {
6316 while (i < leftLength) {
6317 charCodeCache$1[i] = left.charCodeAt(start + i);
6321 while (j < rightLength) {
6322 bCharCode = right.charCodeAt(start + j);
6326 for (i = 0; i < leftLength; i++) {
6327 temp2 = bCharCode === charCodeCache$1[i] ? temp : temp + 1;
6328 temp = array$1[i]; // eslint-disable-next-line no-multi-assign
6330 result = array$1[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2;
6337 var leven_1$1 = leven$1; // TODO: Remove this for the next major release
6339 var default_1 = leven$1;
6340 leven_1$1.default = default_1;
6343 "aliceblue": [240, 248, 255],
6344 "antiquewhite": [250, 235, 215],
6345 "aqua": [0, 255, 255],
6346 "aquamarine": [127, 255, 212],
6347 "azure": [240, 255, 255],
6348 "beige": [245, 245, 220],
6349 "bisque": [255, 228, 196],
6351 "blanchedalmond": [255, 235, 205],
6352 "blue": [0, 0, 255],
6353 "blueviolet": [138, 43, 226],
6354 "brown": [165, 42, 42],
6355 "burlywood": [222, 184, 135],
6356 "cadetblue": [95, 158, 160],
6357 "chartreuse": [127, 255, 0],
6358 "chocolate": [210, 105, 30],
6359 "coral": [255, 127, 80],
6360 "cornflowerblue": [100, 149, 237],
6361 "cornsilk": [255, 248, 220],
6362 "crimson": [220, 20, 60],
6363 "cyan": [0, 255, 255],
6364 "darkblue": [0, 0, 139],
6365 "darkcyan": [0, 139, 139],
6366 "darkgoldenrod": [184, 134, 11],
6367 "darkgray": [169, 169, 169],
6368 "darkgreen": [0, 100, 0],
6369 "darkgrey": [169, 169, 169],
6370 "darkkhaki": [189, 183, 107],
6371 "darkmagenta": [139, 0, 139],
6372 "darkolivegreen": [85, 107, 47],
6373 "darkorange": [255, 140, 0],
6374 "darkorchid": [153, 50, 204],
6375 "darkred": [139, 0, 0],
6376 "darksalmon": [233, 150, 122],
6377 "darkseagreen": [143, 188, 143],
6378 "darkslateblue": [72, 61, 139],
6379 "darkslategray": [47, 79, 79],
6380 "darkslategrey": [47, 79, 79],
6381 "darkturquoise": [0, 206, 209],
6382 "darkviolet": [148, 0, 211],
6383 "deeppink": [255, 20, 147],
6384 "deepskyblue": [0, 191, 255],
6385 "dimgray": [105, 105, 105],
6386 "dimgrey": [105, 105, 105],
6387 "dodgerblue": [30, 144, 255],
6388 "firebrick": [178, 34, 34],
6389 "floralwhite": [255, 250, 240],
6390 "forestgreen": [34, 139, 34],
6391 "fuchsia": [255, 0, 255],
6392 "gainsboro": [220, 220, 220],
6393 "ghostwhite": [248, 248, 255],
6394 "gold": [255, 215, 0],
6395 "goldenrod": [218, 165, 32],
6396 "gray": [128, 128, 128],
6397 "green": [0, 128, 0],
6398 "greenyellow": [173, 255, 47],
6399 "grey": [128, 128, 128],
6400 "honeydew": [240, 255, 240],
6401 "hotpink": [255, 105, 180],
6402 "indianred": [205, 92, 92],
6403 "indigo": [75, 0, 130],
6404 "ivory": [255, 255, 240],
6405 "khaki": [240, 230, 140],
6406 "lavender": [230, 230, 250],
6407 "lavenderblush": [255, 240, 245],
6408 "lawngreen": [124, 252, 0],
6409 "lemonchiffon": [255, 250, 205],
6410 "lightblue": [173, 216, 230],
6411 "lightcoral": [240, 128, 128],
6412 "lightcyan": [224, 255, 255],
6413 "lightgoldenrodyellow": [250, 250, 210],
6414 "lightgray": [211, 211, 211],
6415 "lightgreen": [144, 238, 144],
6416 "lightgrey": [211, 211, 211],
6417 "lightpink": [255, 182, 193],
6418 "lightsalmon": [255, 160, 122],
6419 "lightseagreen": [32, 178, 170],
6420 "lightskyblue": [135, 206, 250],
6421 "lightslategray": [119, 136, 153],
6422 "lightslategrey": [119, 136, 153],
6423 "lightsteelblue": [176, 196, 222],
6424 "lightyellow": [255, 255, 224],
6425 "lime": [0, 255, 0],
6426 "limegreen": [50, 205, 50],
6427 "linen": [250, 240, 230],
6428 "magenta": [255, 0, 255],
6429 "maroon": [128, 0, 0],
6430 "mediumaquamarine": [102, 205, 170],
6431 "mediumblue": [0, 0, 205],
6432 "mediumorchid": [186, 85, 211],
6433 "mediumpurple": [147, 112, 219],
6434 "mediumseagreen": [60, 179, 113],
6435 "mediumslateblue": [123, 104, 238],
6436 "mediumspringgreen": [0, 250, 154],
6437 "mediumturquoise": [72, 209, 204],
6438 "mediumvioletred": [199, 21, 133],
6439 "midnightblue": [25, 25, 112],
6440 "mintcream": [245, 255, 250],
6441 "mistyrose": [255, 228, 225],
6442 "moccasin": [255, 228, 181],
6443 "navajowhite": [255, 222, 173],
6444 "navy": [0, 0, 128],
6445 "oldlace": [253, 245, 230],
6446 "olive": [128, 128, 0],
6447 "olivedrab": [107, 142, 35],
6448 "orange": [255, 165, 0],
6449 "orangered": [255, 69, 0],
6450 "orchid": [218, 112, 214],
6451 "palegoldenrod": [238, 232, 170],
6452 "palegreen": [152, 251, 152],
6453 "paleturquoise": [175, 238, 238],
6454 "palevioletred": [219, 112, 147],
6455 "papayawhip": [255, 239, 213],
6456 "peachpuff": [255, 218, 185],
6457 "peru": [205, 133, 63],
6458 "pink": [255, 192, 203],
6459 "plum": [221, 160, 221],
6460 "powderblue": [176, 224, 230],
6461 "purple": [128, 0, 128],
6462 "rebeccapurple": [102, 51, 153],
6464 "rosybrown": [188, 143, 143],
6465 "royalblue": [65, 105, 225],
6466 "saddlebrown": [139, 69, 19],
6467 "salmon": [250, 128, 114],
6468 "sandybrown": [244, 164, 96],
6469 "seagreen": [46, 139, 87],
6470 "seashell": [255, 245, 238],
6471 "sienna": [160, 82, 45],
6472 "silver": [192, 192, 192],
6473 "skyblue": [135, 206, 235],
6474 "slateblue": [106, 90, 205],
6475 "slategray": [112, 128, 144],
6476 "slategrey": [112, 128, 144],
6477 "snow": [255, 250, 250],
6478 "springgreen": [0, 255, 127],
6479 "steelblue": [70, 130, 180],
6480 "tan": [210, 180, 140],
6481 "teal": [0, 128, 128],
6482 "thistle": [216, 191, 216],
6483 "tomato": [255, 99, 71],
6484 "turquoise": [64, 224, 208],
6485 "violet": [238, 130, 238],
6486 "wheat": [245, 222, 179],
6487 "white": [255, 255, 255],
6488 "whitesmoke": [245, 245, 245],
6489 "yellow": [255, 255, 0],
6490 "yellowgreen": [154, 205, 50]
6495 /* eslint-disable no-mixed-operators */
6496 // NOTE: conversions should only return primitive values (i.e. arrays, or
6497 // values that give correct `typeof` results).
6498 // do not use box values types (i.e. Number(), String(), etc.)
6500 const reverseKeywords = {};
6502 for (const key of Object.keys(colorName$1)) {
6503 reverseKeywords[colorName$1[key]] = key;
6557 labels: ['h', 'c', 'g']
6561 labels: ['r16', 'g16', 'b16']
6568 var conversions$1 = convert$1; // Hide .channels and .labels properties
6570 for (const model of Object.keys(convert$1)) {
6571 if (!('channels' in convert$1[model])) {
6572 throw new Error('missing channels property: ' + model);
6575 if (!('labels' in convert$1[model])) {
6576 throw new Error('missing channel labels property: ' + model);
6579 if (convert$1[model].labels.length !== convert$1[model].channels) {
6580 throw new Error('channel and label counts mismatch: ' + model);
6586 } = convert$1[model];
6587 delete convert$1[model].channels;
6588 delete convert$1[model].labels;
6589 Object.defineProperty(convert$1[model], 'channels', {
6592 Object.defineProperty(convert$1[model], 'labels', {
6597 convert$1.rgb.hsl = function (rgb) {
6598 const r = rgb[0] / 255;
6599 const g = rgb[1] / 255;
6600 const b = rgb[2] / 255;
6601 const min = Math.min(r, g, b);
6602 const max = Math.max(r, g, b);
6603 const delta = max - min;
6609 } else if (r === max) {
6610 h = (g - b) / delta;
6611 } else if (g === max) {
6612 h = 2 + (b - r) / delta;
6613 } else if (b === max) {
6614 h = 4 + (r - g) / delta;
6617 h = Math.min(h * 60, 360);
6623 const l = (min + max) / 2;
6627 } else if (l <= 0.5) {
6628 s = delta / (max + min);
6630 s = delta / (2 - max - min);
6633 return [h, s * 100, l * 100];
6636 convert$1.rgb.hsv = function (rgb) {
6642 const r = rgb[0] / 255;
6643 const g = rgb[1] / 255;
6644 const b = rgb[2] / 255;
6645 const v = Math.max(r, g, b);
6646 const diff = v - Math.min(r, g, b);
6648 const diffc = function (c) {
6649 return (v - c) / 6 / diff + 1 / 2;
6663 } else if (g === v) {
6664 h = 1 / 3 + rdif - bdif;
6665 } else if (b === v) {
6666 h = 2 / 3 + gdif - rdif;
6676 return [h * 360, s * 100, v * 100];
6679 convert$1.rgb.hwb = function (rgb) {
6683 const h = convert$1.rgb.hsl(rgb)[0];
6684 const w = 1 / 255 * Math.min(r, Math.min(g, b));
6685 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
6686 return [h, w * 100, b * 100];
6689 convert$1.rgb.cmyk = function (rgb) {
6690 const r = rgb[0] / 255;
6691 const g = rgb[1] / 255;
6692 const b = rgb[2] / 255;
6693 const k = Math.min(1 - r, 1 - g, 1 - b);
6694 const c = (1 - r - k) / (1 - k) || 0;
6695 const m = (1 - g - k) / (1 - k) || 0;
6696 const y = (1 - b - k) / (1 - k) || 0;
6697 return [c * 100, m * 100, y * 100, k * 100];
6700 function comparativeDistance(x, y) {
6702 See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
6704 return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2;
6707 convert$1.rgb.keyword = function (rgb) {
6708 const reversed = reverseKeywords[rgb];
6714 let currentClosestDistance = Infinity;
6715 let currentClosestKeyword;
6717 for (const keyword of Object.keys(colorName$1)) {
6718 const value = colorName$1[keyword]; // Compute comparative distance
6720 const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
6722 if (distance < currentClosestDistance) {
6723 currentClosestDistance = distance;
6724 currentClosestKeyword = keyword;
6728 return currentClosestKeyword;
6731 convert$1.keyword.rgb = function (keyword) {
6732 return colorName$1[keyword];
6735 convert$1.rgb.xyz = function (rgb) {
6736 let r = rgb[0] / 255;
6737 let g = rgb[1] / 255;
6738 let b = rgb[2] / 255; // Assume sRGB
6740 r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92;
6741 g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92;
6742 b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92;
6743 const x = r * 0.4124 + g * 0.3576 + b * 0.1805;
6744 const y = r * 0.2126 + g * 0.7152 + b * 0.0722;
6745 const z = r * 0.0193 + g * 0.1192 + b * 0.9505;
6746 return [x * 100, y * 100, z * 100];
6749 convert$1.rgb.lab = function (rgb) {
6750 const xyz = convert$1.rgb.xyz(rgb);
6757 x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
6758 y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
6759 z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
6760 const l = 116 * y - 16;
6761 const a = 500 * (x - y);
6762 const b = 200 * (y - z);
6766 convert$1.hsl.rgb = function (hsl) {
6767 const h = hsl[0] / 360;
6768 const s = hsl[1] / 100;
6769 const l = hsl[2] / 100;
6776 return [val, val, val];
6785 const t1 = 2 * l - t2;
6786 const rgb = [0, 0, 0];
6788 for (let i = 0; i < 3; i++) {
6789 t3 = h + 1 / 3 * -(i - 1);
6800 val = t1 + (t2 - t1) * 6 * t3;
6801 } else if (2 * t3 < 1) {
6803 } else if (3 * t3 < 2) {
6804 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
6815 convert$1.hsl.hsv = function (hsl) {
6817 let s = hsl[1] / 100;
6818 let l = hsl[2] / 100;
6820 const lmin = Math.max(l, 0.01);
6822 s *= l <= 1 ? l : 2 - l;
6823 smin *= lmin <= 1 ? lmin : 2 - lmin;
6824 const v = (l + s) / 2;
6825 const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
6826 return [h, sv * 100, v * 100];
6829 convert$1.hsv.rgb = function (hsv) {
6830 const h = hsv[0] / 60;
6831 const s = hsv[1] / 100;
6832 let v = hsv[2] / 100;
6833 const hi = Math.floor(h) % 6;
6834 const f = h - Math.floor(h);
6835 const p = 255 * v * (1 - s);
6836 const q = 255 * v * (1 - s * f);
6837 const t = 255 * v * (1 - s * (1 - f));
6861 convert$1.hsv.hsl = function (hsv) {
6863 const s = hsv[1] / 100;
6864 const v = hsv[2] / 100;
6865 const vmin = Math.max(v, 0.01);
6869 const lmin = (2 - s) * vmin;
6871 sl /= lmin <= 1 ? lmin : 2 - lmin;
6874 return [h, sl * 100, l * 100];
6875 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
6878 convert$1.hwb.rgb = function (hwb) {
6879 const h = hwb[0] / 360;
6880 let wh = hwb[1] / 100;
6881 let bl = hwb[2] / 100;
6882 const ratio = wh + bl;
6883 let f; // Wh + bl cant be > 1
6890 const i = Math.floor(6 * h);
6894 if ((i & 0x01) !== 0) {
6898 const n = wh + f * (v - wh); // Linear interpolation
6903 /* eslint-disable max-statements-per-line,no-multi-spaces */
6944 /* eslint-enable max-statements-per-line,no-multi-spaces */
6947 return [r * 255, g * 255, b * 255];
6950 convert$1.cmyk.rgb = function (cmyk) {
6951 const c = cmyk[0] / 100;
6952 const m = cmyk[1] / 100;
6953 const y = cmyk[2] / 100;
6954 const k = cmyk[3] / 100;
6955 const r = 1 - Math.min(1, c * (1 - k) + k);
6956 const g = 1 - Math.min(1, m * (1 - k) + k);
6957 const b = 1 - Math.min(1, y * (1 - k) + k);
6958 return [r * 255, g * 255, b * 255];
6961 convert$1.xyz.rgb = function (xyz) {
6962 const x = xyz[0] / 100;
6963 const y = xyz[1] / 100;
6964 const z = xyz[2] / 100;
6968 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
6969 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
6970 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // Assume sRGB
6972 r = r > 0.0031308 ? 1.055 * r ** (1.0 / 2.4) - 0.055 : r * 12.92;
6973 g = g > 0.0031308 ? 1.055 * g ** (1.0 / 2.4) - 0.055 : g * 12.92;
6974 b = b > 0.0031308 ? 1.055 * b ** (1.0 / 2.4) - 0.055 : b * 12.92;
6975 r = Math.min(Math.max(0, r), 1);
6976 g = Math.min(Math.max(0, g), 1);
6977 b = Math.min(Math.max(0, b), 1);
6978 return [r * 255, g * 255, b * 255];
6981 convert$1.xyz.lab = function (xyz) {
6988 x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
6989 y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
6990 z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
6991 const l = 116 * y - 16;
6992 const a = 500 * (x - y);
6993 const b = 200 * (y - z);
6997 convert$1.lab.xyz = function (lab) {
7010 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
7011 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
7012 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
7019 convert$1.lab.lch = function (lab) {
7024 const hr = Math.atan2(b, a);
7025 h = hr * 360 / 2 / Math.PI;
7031 const c = Math.sqrt(a * a + b * b);
7035 convert$1.lch.lab = function (lch) {
7039 const hr = h / 360 * 2 * Math.PI;
7040 const a = c * Math.cos(hr);
7041 const b = c * Math.sin(hr);
7045 convert$1.rgb.ansi16 = function (args, saturation = null) {
7046 const [r, g, b] = args;
7047 let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
7049 value = Math.round(value / 50);
7055 let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
7064 convert$1.hsv.ansi16 = function (args) {
7065 // Optimization here; we already know the value and don't need to get
7066 // it converted for us.
7067 return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
7070 convert$1.rgb.ansi256 = function (args) {
7073 const b = args[2]; // We use the extended greyscale palette here, with the exception of
7074 // black and white. normal palette only has 4 greyscale shades.
7076 if (r === g && g === b) {
7085 return Math.round((r - 8) / 247 * 24) + 232;
7088 const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
7092 convert$1.ansi16.rgb = function (args) {
7093 let color = args % 10; // Handle greyscale
7095 if (color === 0 || color === 7) {
7100 color = color / 10.5 * 255;
7101 return [color, color, color];
7104 const mult = (~~(args > 50) + 1) * 0.5;
7105 const r = (color & 1) * mult * 255;
7106 const g = (color >> 1 & 1) * mult * 255;
7107 const b = (color >> 2 & 1) * mult * 255;
7111 convert$1.ansi256.rgb = function (args) {
7114 const c = (args - 232) * 10 + 8;
7120 const r = Math.floor(args / 36) / 5 * 255;
7121 const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
7122 const b = rem % 6 / 5 * 255;
7126 convert$1.rgb.hex = function (args) {
7127 const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
7128 const string = integer.toString(16).toUpperCase();
7129 return '000000'.substring(string.length) + string;
7132 convert$1.hex.rgb = function (args) {
7133 const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
7139 let colorString = match[0];
7141 if (match[0].length === 3) {
7142 colorString = colorString.split('').map(char => {
7147 const integer = parseInt(colorString, 16);
7148 const r = integer >> 16 & 0xFF;
7149 const g = integer >> 8 & 0xFF;
7150 const b = integer & 0xFF;
7154 convert$1.rgb.hcg = function (rgb) {
7155 const r = rgb[0] / 255;
7156 const g = rgb[1] / 255;
7157 const b = rgb[2] / 255;
7158 const max = Math.max(Math.max(r, g), b);
7159 const min = Math.min(Math.min(r, g), b);
7160 const chroma = max - min;
7165 grayscale = min / (1 - chroma);
7172 } else if (max === r) {
7173 hue = (g - b) / chroma % 6;
7174 } else if (max === g) {
7175 hue = 2 + (b - r) / chroma;
7177 hue = 4 + (r - g) / chroma;
7182 return [hue * 360, chroma * 100, grayscale * 100];
7185 convert$1.hsl.hcg = function (hsl) {
7186 const s = hsl[1] / 100;
7187 const l = hsl[2] / 100;
7188 const c = l < 0.5 ? 2.0 * s * l : 2.0 * s * (1.0 - l);
7192 f = (l - 0.5 * c) / (1.0 - c);
7195 return [hsl[0], c * 100, f * 100];
7198 convert$1.hsv.hcg = function (hsv) {
7199 const s = hsv[1] / 100;
7200 const v = hsv[2] / 100;
7205 f = (v - c) / (1 - c);
7208 return [hsv[0], c * 100, f * 100];
7211 convert$1.hcg.rgb = function (hcg) {
7212 const h = hcg[0] / 360;
7213 const c = hcg[1] / 100;
7214 const g = hcg[2] / 100;
7217 return [g * 255, g * 255, g * 255];
7220 const pure = [0, 0, 0];
7221 const hi = h % 1 * 6;
7225 /* eslint-disable max-statements-per-line */
7227 switch (Math.floor(hi)) {
7263 /* eslint-enable max-statements-per-line */
7267 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
7270 convert$1.hcg.hsv = function (hcg) {
7271 const c = hcg[1] / 100;
7272 const g = hcg[2] / 100;
7273 const v = c + g * (1.0 - c);
7280 return [hcg[0], f * 100, v * 100];
7283 convert$1.hcg.hsl = function (hcg) {
7284 const c = hcg[1] / 100;
7285 const g = hcg[2] / 100;
7286 const l = g * (1.0 - c) + 0.5 * c;
7289 if (l > 0.0 && l < 0.5) {
7291 } else if (l >= 0.5 && l < 1.0) {
7292 s = c / (2 * (1 - l));
7295 return [hcg[0], s * 100, l * 100];
7298 convert$1.hcg.hwb = function (hcg) {
7299 const c = hcg[1] / 100;
7300 const g = hcg[2] / 100;
7301 const v = c + g * (1.0 - c);
7302 return [hcg[0], (v - c) * 100, (1 - v) * 100];
7305 convert$1.hwb.hcg = function (hwb) {
7306 const w = hwb[1] / 100;
7307 const b = hwb[2] / 100;
7313 g = (v - c) / (1 - c);
7316 return [hwb[0], c * 100, g * 100];
7319 convert$1.apple.rgb = function (apple) {
7320 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
7323 convert$1.rgb.apple = function (rgb) {
7324 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
7327 convert$1.gray.rgb = function (args) {
7328 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
7331 convert$1.gray.hsl = function (args) {
7332 return [0, 0, args[0]];
7335 convert$1.gray.hsv = convert$1.gray.hsl;
7337 convert$1.gray.hwb = function (gray) {
7338 return [0, 100, gray[0]];
7341 convert$1.gray.cmyk = function (gray) {
7342 return [0, 0, 0, gray[0]];
7345 convert$1.gray.lab = function (gray) {
7346 return [gray[0], 0, 0];
7349 convert$1.gray.hex = function (gray) {
7350 const val = Math.round(gray[0] / 100 * 255) & 0xFF;
7351 const integer = (val << 16) + (val << 8) + val;
7352 const string = integer.toString(16).toUpperCase();
7353 return '000000'.substring(string.length) + string;
7356 convert$1.rgb.gray = function (rgb) {
7357 const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
7358 return [val / 255 * 100];
7362 This function routes a model to all other models.
7364 all functions that are routed have a property `.conversion` attached
7365 to the returned synthetic function. This property is an array
7366 of strings, each with the steps in between the 'from' and 'to'
7367 color models (inclusive).
7369 conversions that are not possible simply are not included.
7372 function buildGraph$1() {
7373 const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
7375 const models = Object.keys(conversions$1);
7377 for (let len = models.length, i = 0; i < len; i++) {
7378 graph[models[i]] = {
7379 // http://jsperf.com/1-vs-infinity
7380 // micro-opt, but this is simple.
7387 } // https://en.wikipedia.org/wiki/Breadth-first_search
7390 function deriveBFS$1(fromModel) {
7391 const graph = buildGraph$1();
7392 const queue = [fromModel]; // Unshift -> queue -> pop
7394 graph[fromModel].distance = 0;
7396 while (queue.length) {
7397 const current = queue.pop();
7398 const adjacents = Object.keys(conversions$1[current]);
7400 for (let len = adjacents.length, i = 0; i < len; i++) {
7401 const adjacent = adjacents[i];
7402 const node = graph[adjacent];
7404 if (node.distance === -1) {
7405 node.distance = graph[current].distance + 1;
7406 node.parent = current;
7407 queue.unshift(adjacent);
7415 function link$1(from, to) {
7416 return function (args) {
7417 return to(from(args));
7421 function wrapConversion$1(toModel, graph) {
7422 const path = [graph[toModel].parent, toModel];
7423 let fn = conversions$1[graph[toModel].parent][toModel];
7424 let cur = graph[toModel].parent;
7426 while (graph[cur].parent) {
7427 path.unshift(graph[cur].parent);
7428 fn = link$1(conversions$1[graph[cur].parent][cur], fn);
7429 cur = graph[cur].parent;
7432 fn.conversion = path;
7436 var route$1 = function (fromModel) {
7437 const graph = deriveBFS$1(fromModel);
7438 const conversion = {};
7439 const models = Object.keys(graph);
7441 for (let len = models.length, i = 0; i < len; i++) {
7442 const toModel = models[i];
7443 const node = graph[toModel];
7445 if (node.parent === null) {
7446 // No possible conversion, or this node is the source model.
7450 conversion[toModel] = wrapConversion$1(toModel, graph);
7456 const convert$2 = {};
7457 const models$1 = Object.keys(conversions$1);
7459 function wrapRaw$1(fn) {
7460 const wrappedFn = function (...args) {
7461 const arg0 = args[0];
7463 if (arg0 === undefined || arg0 === null) {
7467 if (arg0.length > 1) {
7472 }; // Preserve .conversion property if there is one
7475 if ('conversion' in fn) {
7476 wrappedFn.conversion = fn.conversion;
7482 function wrapRounded$1(fn) {
7483 const wrappedFn = function (...args) {
7484 const arg0 = args[0];
7486 if (arg0 === undefined || arg0 === null) {
7490 if (arg0.length > 1) {
7494 const result = fn(args); // We're assuming the result is an array here.
7495 // see notice in conversions.js; don't use box types
7496 // in conversion functions.
7498 if (typeof result === 'object') {
7499 for (let len = result.length, i = 0; i < len; i++) {
7500 result[i] = Math.round(result[i]);
7505 }; // Preserve .conversion property if there is one
7508 if ('conversion' in fn) {
7509 wrappedFn.conversion = fn.conversion;
7515 models$1.forEach(fromModel => {
7516 convert$2[fromModel] = {};
7517 Object.defineProperty(convert$2[fromModel], 'channels', {
7518 value: conversions$1[fromModel].channels
7520 Object.defineProperty(convert$2[fromModel], 'labels', {
7521 value: conversions$1[fromModel].labels
7523 const routes = route$1(fromModel);
7524 const routeModels = Object.keys(routes);
7525 routeModels.forEach(toModel => {
7526 const fn = routes[toModel];
7527 convert$2[fromModel][toModel] = wrapRounded$1(fn);
7528 convert$2[fromModel][toModel].raw = wrapRaw$1(fn);
7531 var colorConvert$1 = convert$2;
7533 var ansiStyles$1 = createCommonjsModule(function (module) {
7535 const wrapAnsi16 = (fn, offset) => (...args) => {
7536 const code = fn(...args);
7537 return `\u001B[${code + offset}m`;
7540 const wrapAnsi256 = (fn, offset) => (...args) => {
7541 const code = fn(...args);
7542 return `\u001B[${38 + offset};5;${code}m`;
7545 const wrapAnsi16m = (fn, offset) => (...args) => {
7546 const rgb = fn(...args);
7547 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
7550 const ansi2ansi = n => n;
7552 const rgb2rgb = (r, g, b) => [r, g, b];
7554 const setLazyProperty = (object, property, get) => {
7555 Object.defineProperty(object, property, {
7557 const value = get();
7558 Object.defineProperty(object, property, {
7569 /** @type {typeof import('color-convert')} */
7574 const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
7575 if (colorConvert === undefined) {
7576 colorConvert = colorConvert$1;
7579 const offset = isBackground ? 10 : 0;
7582 for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
7583 const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
7585 if (sourceSpace === targetSpace) {
7586 styles[name] = wrap(identity, offset);
7587 } else if (typeof suite === 'object') {
7588 styles[name] = wrap(suite[targetSpace], offset);
7595 function assembleStyles() {
7596 const codes = new Map();
7600 // 21 isn't widely supported and 22 does the same thing
7607 strikethrough: [9, 29]
7619 blackBright: [90, 39],
7620 redBright: [91, 39],
7621 greenBright: [92, 39],
7622 yellowBright: [93, 39],
7623 blueBright: [94, 39],
7624 magentaBright: [95, 39],
7625 cyanBright: [96, 39],
7626 whiteBright: [97, 39]
7634 bgMagenta: [45, 49],
7638 bgBlackBright: [100, 49],
7639 bgRedBright: [101, 49],
7640 bgGreenBright: [102, 49],
7641 bgYellowBright: [103, 49],
7642 bgBlueBright: [104, 49],
7643 bgMagentaBright: [105, 49],
7644 bgCyanBright: [106, 49],
7645 bgWhiteBright: [107, 49]
7647 }; // Alias bright black as gray (and grey)
7649 styles.color.gray = styles.color.blackBright;
7650 styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
7651 styles.color.grey = styles.color.blackBright;
7652 styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
7654 for (const [groupName, group] of Object.entries(styles)) {
7655 for (const [styleName, style] of Object.entries(group)) {
7656 styles[styleName] = {
7657 open: `\u001B[${style[0]}m`,
7658 close: `\u001B[${style[1]}m`
7660 group[styleName] = styles[styleName];
7661 codes.set(style[0], style[1]);
7664 Object.defineProperty(styles, groupName, {
7670 Object.defineProperty(styles, 'codes', {
7674 styles.color.close = '\u001B[39m';
7675 styles.bgColor.close = '\u001B[49m';
7676 setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
7677 setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
7678 setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
7679 setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
7680 setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
7681 setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
7683 } // Make the export immutable
7686 Object.defineProperty(module, 'exports', {
7692 var hasFlag$1 = (flag, argv = process.argv) => {
7693 const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
7694 const position = argv.indexOf(prefix + flag);
7695 const terminatorPosition = argv.indexOf('--');
7696 return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
7704 if (hasFlag$1('no-color') || hasFlag$1('no-colors') || hasFlag$1('color=false') || hasFlag$1('color=never')) {
7706 } else if (hasFlag$1('color') || hasFlag$1('colors') || hasFlag$1('color=true') || hasFlag$1('color=always')) {
7710 if ('FORCE_COLOR' in env$1) {
7711 if (env$1.FORCE_COLOR === 'true') {
7713 } else if (env$1.FORCE_COLOR === 'false') {
7716 forceColor$1 = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3);
7720 function translateLevel$1(level) {
7733 function supportsColor$1(haveStream, streamIsTTY) {
7734 if (forceColor$1 === 0) {
7738 if (hasFlag$1('color=16m') || hasFlag$1('color=full') || hasFlag$1('color=truecolor')) {
7742 if (hasFlag$1('color=256')) {
7746 if (haveStream && !streamIsTTY && forceColor$1 === undefined) {
7750 const min = forceColor$1 || 0;
7752 if (env$1.TERM === 'dumb') {
7756 if (process.platform === 'win32') {
7757 // Windows 10 build 10586 is the first Windows release that supports 256 colors.
7758 // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
7759 const osRelease = os$1.release().split('.');
7761 if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
7762 return Number(osRelease[2]) >= 14931 ? 3 : 2;
7768 if ('CI' in env$1) {
7769 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') {
7776 if ('TEAMCITY_VERSION' in env$1) {
7777 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
7780 if ('GITHUB_ACTIONS' in env$1) {
7784 if (env$1.COLORTERM === 'truecolor') {
7788 if ('TERM_PROGRAM' in env$1) {
7789 const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
7791 switch (env$1.TERM_PROGRAM) {
7793 return version >= 3 ? 3 : 2;
7795 case 'Apple_Terminal':
7801 if (/-256(color)?$/i.test(env$1.TERM)) {
7805 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
7809 if ('COLORTERM' in env$1) {
7816 function getSupportLevel$1(stream) {
7817 const level = supportsColor$1(stream, stream && stream.isTTY);
7818 return translateLevel$1(level);
7821 var supportsColor_1$1 = {
7822 supportsColor: getSupportLevel$1,
7823 stdout: translateLevel$1(supportsColor$1(true, tty$1.isatty(1))),
7824 stderr: translateLevel$1(supportsColor$1(true, tty$1.isatty(2)))
7827 const stringReplaceAll = (string, substring, replacer) => {
7828 let index = string.indexOf(substring);
7834 const substringLength = substring.length;
7836 let returnValue = '';
7839 returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
7840 endIndex = index + substringLength;
7841 index = string.indexOf(substring, endIndex);
7842 } while (index !== -1);
7844 returnValue += string.substr(endIndex);
7848 const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
7850 let returnValue = '';
7853 const gotCR = string[index - 1] === '\r';
7854 returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
7855 endIndex = index + 1;
7856 index = string.indexOf('\n', endIndex);
7857 } while (index !== -1);
7859 returnValue += string.substr(endIndex);
7865 stringEncaseCRLFWithFirstIndex
7868 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;
7869 const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
7870 const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
7871 const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
7872 const ESCAPES$1 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
7874 function unescape$1(c) {
7875 const u = c[0] === 'u';
7876 const bracket = c[1] === '{';
7878 if (u && !bracket && c.length === 5 || c[0] === 'x' && c.length === 3) {
7879 return String.fromCharCode(parseInt(c.slice(1), 16));
7883 return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
7886 return ESCAPES$1.get(c) || c;
7889 function parseArguments$1(name, arguments_) {
7891 const chunks = arguments_.trim().split(/\s*,\s*/g);
7894 for (const chunk of chunks) {
7895 const number = Number(chunk);
7897 if (!Number.isNaN(number)) {
7898 results.push(number);
7899 } else if (matches = chunk.match(STRING_REGEX$1)) {
7900 results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$1(escape) : character));
7902 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
7909 function parseStyle$1(style) {
7910 STYLE_REGEX$1.lastIndex = 0;
7914 while ((matches = STYLE_REGEX$1.exec(style)) !== null) {
7915 const name = matches[1];
7918 const args = parseArguments$1(name, matches[2]);
7919 results.push([name].concat(args));
7921 results.push([name]);
7928 function buildStyle$1(chalk, styles) {
7931 for (const layer of styles) {
7932 for (const style of layer.styles) {
7933 enabled[style[0]] = layer.inverse ? null : style.slice(1);
7937 let current = chalk;
7939 for (const [styleName, styles] of Object.entries(enabled)) {
7940 if (!Array.isArray(styles)) {
7944 if (!(styleName in current)) {
7945 throw new Error(`Unknown Chalk style: ${styleName}`);
7948 current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
7954 var templates$1 = (chalk, temporary) => {
7957 let chunk = []; // eslint-disable-next-line max-params
7959 temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => {
7960 if (escapeCharacter) {
7961 chunk.push(unescape$1(escapeCharacter));
7963 const string = chunk.join('');
7965 chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string));
7968 styles: parseStyle$1(style)
7971 if (styles.length === 0) {
7972 throw new Error('Found extraneous } in Chalk template literal');
7975 chunks.push(buildStyle$1(chalk, styles)(chunk.join('')));
7979 chunk.push(character);
7982 chunks.push(chunk.join(''));
7984 if (styles.length > 0) {
7985 const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
7986 throw new Error(errMessage);
7989 return chunks.join('');
7993 stdout: stdoutColor,
7995 } = supportsColor_1$1;
7997 stringReplaceAll: stringReplaceAll$1,
7998 stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
7999 } = util; // `supportsColor.level` → `ansiStyles.color[name]` mapping
8001 const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
8002 const styles = Object.create(null);
8004 const applyOptions = (object, options = {}) => {
8005 if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
8006 throw new Error('The `level` option should be an integer from 0 to 3');
8007 } // Detect level if not set manually
8010 const colorLevel = stdoutColor ? stdoutColor.level : 0;
8011 object.level = options.level === undefined ? colorLevel : options.level;
8015 constructor(options) {
8016 // eslint-disable-next-line no-constructor-return
8017 return chalkFactory(options);
8022 const chalkFactory = options => {
8024 applyOptions(chalk, options);
8026 chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
8028 Object.setPrototypeOf(chalk, Chalk.prototype);
8029 Object.setPrototypeOf(chalk.template, chalk);
8031 chalk.template.constructor = () => {
8032 throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
8035 chalk.template.Instance = ChalkClass;
8036 return chalk.template;
8039 function Chalk(options) {
8040 return chalkFactory(options);
8043 for (const [styleName, style] of Object.entries(ansiStyles$1)) {
8044 styles[styleName] = {
8046 const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
8047 Object.defineProperty(this, styleName, {
8058 const builder = createBuilder(this, this._styler, true);
8059 Object.defineProperty(this, 'visible', {
8066 const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
8068 for (const model of usedModels) {
8074 return function (...arguments_) {
8075 const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler);
8076 return createBuilder(this, styler, this._isEmpty);
8083 for (const model of usedModels) {
8084 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
8090 return function (...arguments_) {
8091 const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler);
8092 return createBuilder(this, styler, this._isEmpty);
8099 const proto = Object.defineProperties(() => {}, Object.assign({}, styles, {
8104 return this._generator.level;
8108 this._generator.level = level;
8114 const createStyler = (open, close, parent) => {
8118 if (parent === undefined) {
8122 openAll = parent.openAll + open;
8123 closeAll = close + parent.closeAll;
8135 const createBuilder = (self, _styler, _isEmpty) => {
8136 const builder = (...arguments_) => {
8137 // Single argument is hot path, implicit coercion is faster than anything
8138 // eslint-disable-next-line no-implicit-coercion
8139 return applyStyle(builder, arguments_.length === 1 ? '' + arguments_[0] : arguments_.join(' '));
8140 }; // We alter the prototype because we must return a function, but there is
8141 // no way to create a function with a different prototype
8144 Object.setPrototypeOf(builder, proto);
8145 builder._generator = self;
8146 builder._styler = _styler;
8147 builder._isEmpty = _isEmpty;
8151 const applyStyle = (self, string) => {
8152 if (self.level <= 0 || !string) {
8153 return self._isEmpty ? '' : string;
8156 let styler = self._styler;
8158 if (styler === undefined) {
8167 if (string.indexOf('\u001B') !== -1) {
8168 while (styler !== undefined) {
8169 // Replace any instances already present with a re-opening code
8170 // otherwise only the part of the string until said closing code
8171 // will be colored, and the rest will simply be 'plain'.
8172 string = stringReplaceAll$1(string, styler.close, styler.open);
8173 styler = styler.parent;
8175 } // We can move both next actions out of loop, because remaining actions in loop won't have
8176 // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
8177 // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
8180 const lfIndex = string.indexOf('\n');
8182 if (lfIndex !== -1) {
8183 string = stringEncaseCRLFWithFirstIndex$1(string, closeAll, openAll, lfIndex);
8186 return openAll + string + closeAll;
8191 const chalkTag = (chalk, ...strings) => {
8192 const [firstString] = strings;
8194 if (!Array.isArray(firstString)) {
8195 // If chalk() was called by itself or with a string,
8196 // return the string itself as a string.
8197 return strings.join(' ');
8200 const arguments_ = strings.slice(1);
8201 const parts = [firstString.raw[0]];
8203 for (let i = 1; i < firstString.length; i++) {
8204 parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]));
8207 if (template === undefined) {
8208 template = templates$1;
8211 return template(chalk, parts.join(''));
8214 Object.defineProperties(Chalk.prototype, styles);
8215 const chalk$1 = Chalk(); // eslint-disable-line new-cap
8217 chalk$1.supportsColor = stdoutColor;
8218 chalk$1.stderr = Chalk({
8219 level: stderrColor ? stderrColor.level : 0
8220 }); // eslint-disable-line new-cap
8222 chalk$1.stderr.supportsColor = stderrColor;
8223 var source = chalk$1;
8225 const cliDescriptor = {
8226 key: key => key.length === 1 ? `-${key}` : `--${key}`,
8227 value: value => lib.apiDescriptor.value(value),
8231 }) => value === false ? `--no-${key}` : value === true ? cliDescriptor.key(key) : value === "" ? `${cliDescriptor.key(key)} without an argument` : `${cliDescriptor.key(key)}=${value}`
8234 class FlagSchema extends lib.ChoiceSchema {
8243 this._flags = flags.slice().sort();
8246 preprocess(value, utils) {
8247 if (typeof value === "string" && value.length !== 0 && !this._flags.includes(value)) {
8248 const suggestion = this._flags.find(flag => leven_1$1(flag, value) < 3);
8251 utils.logger.warn([`Unknown flag ${source.yellow(utils.descriptor.value(value))},`, `did you mean ${source.blue(utils.descriptor.value(suggestion))}?`].join(" "));
8265 let hasDeprecationWarned;
8267 function normalizeOptions(options, optionInfos, {
8272 const unknown = !passThrough ? lib.levenUnknownHandler : Array.isArray(passThrough) ? (key, value) => !passThrough.includes(key) ? undefined : {
8274 } : (key, value) => ({
8277 const descriptor = isCLI ? cliDescriptor : lib.apiDescriptor;
8278 const schemas = optionInfosToSchemas(optionInfos, {
8281 const normalizer = new lib.Normalizer(schemas, {
8286 const shouldSuppressDuplicateDeprecationWarnings = logger !== false;
8288 if (shouldSuppressDuplicateDeprecationWarnings && hasDeprecationWarned) {
8289 normalizer._hasDeprecationWarned = hasDeprecationWarned;
8292 const normalized = normalizer.normalize(options);
8294 if (shouldSuppressDuplicateDeprecationWarnings) {
8295 hasDeprecationWarned = normalizer._hasDeprecationWarned;
8301 function optionInfosToSchemas(optionInfos, {
8307 schemas.push(lib.AnySchema.create({
8312 for (const optionInfo of optionInfos) {
8313 schemas.push(optionInfoToSchema(optionInfo, {
8318 if (optionInfo.alias && isCLI) {
8319 schemas.push(lib.AliasSchema.create({
8320 name: optionInfo.alias,
8321 sourceName: optionInfo.name
8329 function optionInfoToSchema(optionInfo, {
8333 let SchemaConstructor;
8334 const parameters = {
8335 name: optionInfo.name
8337 const handlers = {};
8339 switch (optionInfo.type) {
8341 SchemaConstructor = lib.IntegerSchema;
8344 parameters.preprocess = value => Number(value);
8350 SchemaConstructor = lib.StringSchema;
8354 SchemaConstructor = lib.ChoiceSchema;
8355 parameters.choices = optionInfo.choices.map(choiceInfo => typeof choiceInfo === "object" && choiceInfo.redirect ? Object.assign({}, choiceInfo, {
8358 key: optionInfo.name,
8359 value: choiceInfo.redirect
8366 SchemaConstructor = lib.BooleanSchema;
8370 SchemaConstructor = FlagSchema;
8371 parameters.flags = optionInfos.map(optionInfo => [].concat(optionInfo.alias || [], optionInfo.description ? optionInfo.name : [], optionInfo.oppositeDescription ? `no-${optionInfo.name}` : [])).reduce((a, b) => a.concat(b), []);
8375 SchemaConstructor = lib.StringSchema;
8379 throw new Error(`Unexpected type ${optionInfo.type}`);
8382 if (optionInfo.exception) {
8383 parameters.validate = (value, schema, utils) => {
8384 return optionInfo.exception(value) || schema.validate(value, utils);
8387 parameters.validate = (value, schema, utils) => {
8388 return value === undefined || schema.validate(value, utils);
8392 if (optionInfo.redirect) {
8393 handlers.redirect = value => !value ? undefined : {
8395 key: optionInfo.redirect.option,
8396 value: optionInfo.redirect.value
8401 if (optionInfo.deprecated) {
8402 handlers.deprecated = true;
8403 } // allow CLI overriding, e.g., prettier package.json --tab-width 1 --tab-width 2
8406 if (isCLI && !optionInfo.array) {
8407 const originalPreprocess = parameters.preprocess || (x => x);
8409 parameters.preprocess = (value, schema, utils) => schema.preprocess(originalPreprocess(Array.isArray(value) ? value[value.length - 1] : value), utils);
8412 return optionInfo.array ? lib.ArraySchema.create(Object.assign({}, isCLI ? {
8413 preprocess: v => [].concat(v)
8414 } : {}, {}, handlers, {
8415 valueSchema: SchemaConstructor.create(parameters)
8416 })) : SchemaConstructor.create(Object.assign({}, parameters, {}, handlers));
8419 function normalizeApiOptions(options, optionInfos, opts) {
8420 return normalizeOptions(options, optionInfos, opts);
8423 function normalizeCliOptions(options, optionInfos, opts) {
8424 return normalizeOptions(options, optionInfos, Object.assign({
8429 var optionsNormalizer = {
8430 normalizeApiOptions,
8434 var getLast = arr => arr[arr.length - 1];
8436 function locStart(node, opts) {
8437 opts = opts || {}; // Handle nodes with decorators. They should start at the first decorator
8439 if (!opts.ignoreDecorators && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0) {
8440 return locStart(node.declaration.decorators[0]);
8443 if (!opts.ignoreDecorators && node.decorators && node.decorators.length > 0) {
8444 return locStart(node.decorators[0]);
8447 if (node.__location) {
8448 return node.__location.startOffset;
8452 return node.range[0];
8455 if (typeof node.start === "number") {
8460 return node.loc.start;
8466 function locEnd(node) {
8467 const endNode = node.nodes && getLast(node.nodes);
8469 if (endNode && node.source && !node.source.end) {
8473 if (node.__location) {
8474 return node.__location.endOffset;
8477 const loc = node.range ? node.range[1] : typeof node.end === "number" ? node.end : null;
8479 if (node.typeAnnotation) {
8480 return Math.max(loc, locEnd(node.typeAnnotation));
8483 if (node.loc && !loc) {
8484 return node.loc.end;
8490 function composeLoc(startNode, endNodeOrLength = startNode) {
8491 const length = typeof endNodeOrLength === "number" ? endNodeOrLength : -1;
8492 const start = locStart(startNode);
8493 const end = length !== -1 ? start + length : locEnd(endNodeOrLength);
8494 const startLoc = startNode.loc.start;
8498 range: [start, end],
8501 end: length !== -1 ? {
8502 line: startLoc.line,
8503 column: startLoc.column + length
8504 } : endNodeOrLength.loc.end
8515 var jsTokens = createCommonjsModule(function (module, exports) {
8516 // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell
8517 // License: MIT. (See LICENSE.)
8518 Object.defineProperty(exports, "__esModule", {
8520 }); // This regex comes from regex.coffee, and is inserted here by generate-index.js
8521 // (run `npm run build`).
8523 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;
8525 exports.matchToToken = function (match) {
8531 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";
8535 unwrapExports(jsTokens);
8536 var jsTokens_1 = jsTokens.matchToToken;
8538 var ast = createCommonjsModule(function (module) {
8540 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
8542 Redistribution and use in source and binary forms, with or without
8543 modification, are permitted provided that the following conditions are met:
8545 * Redistributions of source code must retain the above copyright
8546 notice, this list of conditions and the following disclaimer.
8547 * Redistributions in binary form must reproduce the above copyright
8548 notice, this list of conditions and the following disclaimer in the
8549 documentation and/or other materials provided with the distribution.
8551 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
8552 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
8553 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
8554 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
8555 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
8556 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
8557 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
8558 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8559 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8560 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8564 function isExpression(node) {
8569 switch (node.type) {
8570 case 'ArrayExpression':
8571 case 'AssignmentExpression':
8572 case 'BinaryExpression':
8573 case 'CallExpression':
8574 case 'ConditionalExpression':
8575 case 'FunctionExpression':
8578 case 'LogicalExpression':
8579 case 'MemberExpression':
8580 case 'NewExpression':
8581 case 'ObjectExpression':
8582 case 'SequenceExpression':
8583 case 'ThisExpression':
8584 case 'UnaryExpression':
8585 case 'UpdateExpression':
8592 function isIterationStatement(node) {
8597 switch (node.type) {
8598 case 'DoWhileStatement':
8599 case 'ForInStatement':
8600 case 'ForStatement':
8601 case 'WhileStatement':
8608 function isStatement(node) {
8613 switch (node.type) {
8614 case 'BlockStatement':
8615 case 'BreakStatement':
8616 case 'ContinueStatement':
8617 case 'DebuggerStatement':
8618 case 'DoWhileStatement':
8619 case 'EmptyStatement':
8620 case 'ExpressionStatement':
8621 case 'ForInStatement':
8622 case 'ForStatement':
8624 case 'LabeledStatement':
8625 case 'ReturnStatement':
8626 case 'SwitchStatement':
8627 case 'ThrowStatement':
8628 case 'TryStatement':
8629 case 'VariableDeclaration':
8630 case 'WhileStatement':
8631 case 'WithStatement':
8638 function isSourceElement(node) {
8639 return isStatement(node) || node != null && node.type === 'FunctionDeclaration';
8642 function trailingStatement(node) {
8643 switch (node.type) {
8645 if (node.alternate != null) {
8646 return node.alternate;
8649 return node.consequent;
8651 case 'LabeledStatement':
8652 case 'ForStatement':
8653 case 'ForInStatement':
8654 case 'WhileStatement':
8655 case 'WithStatement':
8662 function isProblematicIfStatement(node) {
8665 if (node.type !== 'IfStatement') {
8669 if (node.alternate == null) {
8673 current = node.consequent;
8676 if (current.type === 'IfStatement') {
8677 if (current.alternate == null) {
8682 current = trailingStatement(current);
8689 isExpression: isExpression,
8690 isStatement: isStatement,
8691 isIterationStatement: isIterationStatement,
8692 isSourceElement: isSourceElement,
8693 isProblematicIfStatement: isProblematicIfStatement,
8694 trailingStatement: trailingStatement
8697 /* vim: set sw=4 ts=4 et tw=80 : */
8700 var ast_1 = ast.isExpression;
8701 var ast_2 = ast.isStatement;
8702 var ast_3 = ast.isIterationStatement;
8703 var ast_4 = ast.isSourceElement;
8704 var ast_5 = ast.isProblematicIfStatement;
8705 var ast_6 = ast.trailingStatement;
8707 var code = createCommonjsModule(function (module) {
8709 Copyright (C) 2013-2014 Yusuke Suzuki <utatane.tea@gmail.com>
8710 Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
8712 Redistribution and use in source and binary forms, with or without
8713 modification, are permitted provided that the following conditions are met:
8715 * Redistributions of source code must retain the above copyright
8716 notice, this list of conditions and the following disclaimer.
8717 * Redistributions in binary form must reproduce the above copyright
8718 notice, this list of conditions and the following disclaimer in the
8719 documentation and/or other materials provided with the distribution.
8721 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
8722 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
8723 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
8724 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
8725 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
8726 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
8727 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
8728 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8729 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8730 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8734 var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`.
8737 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart:
8738 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]/,
8739 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart:
8740 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]/
8743 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart:
8744 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]/,
8745 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart:
8746 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]/
8749 function isDecimalDigit(ch) {
8750 return 0x30 <= ch && ch <= 0x39; // 0..9
8753 function isHexDigit(ch) {
8754 return 0x30 <= ch && ch <= 0x39 || // 0..9
8755 0x61 <= ch && ch <= 0x66 || // a..f
8756 0x41 <= ch && ch <= 0x46; // A..F
8759 function isOctalDigit(ch) {
8760 return ch >= 0x30 && ch <= 0x37; // 0..7
8761 } // 7.2 White Space
8764 NON_ASCII_WHITESPACES = [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF];
8766 function isWhiteSpace(ch) {
8767 return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
8768 } // 7.3 Line Terminators
8771 function isLineTerminator(ch) {
8772 return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;
8773 } // 7.6 Identifier Names and Identifiers
8776 function fromCodePoint(cp) {
8778 return String.fromCharCode(cp);
8781 var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800);
8782 var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00);
8786 IDENTIFIER_START = new Array(0x80);
8788 for (ch = 0; ch < 0x80; ++ch) {
8789 IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
8790 ch >= 0x41 && ch <= 0x5A || // A..Z
8791 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
8794 IDENTIFIER_PART = new Array(0x80);
8796 for (ch = 0; ch < 0x80; ++ch) {
8797 IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
8798 ch >= 0x41 && ch <= 0x5A || // A..Z
8799 ch >= 0x30 && ch <= 0x39 || // 0..9
8800 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
8803 function isIdentifierStartES5(ch) {
8804 return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
8807 function isIdentifierPartES5(ch) {
8808 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
8811 function isIdentifierStartES6(ch) {
8812 return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
8815 function isIdentifierPartES6(ch) {
8816 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
8820 isDecimalDigit: isDecimalDigit,
8821 isHexDigit: isHexDigit,
8822 isOctalDigit: isOctalDigit,
8823 isWhiteSpace: isWhiteSpace,
8824 isLineTerminator: isLineTerminator,
8825 isIdentifierStartES5: isIdentifierStartES5,
8826 isIdentifierPartES5: isIdentifierPartES5,
8827 isIdentifierStartES6: isIdentifierStartES6,
8828 isIdentifierPartES6: isIdentifierPartES6
8831 /* vim: set sw=4 ts=4 et tw=80 : */
8834 var code_1 = code.isDecimalDigit;
8835 var code_2 = code.isHexDigit;
8836 var code_3 = code.isOctalDigit;
8837 var code_4 = code.isWhiteSpace;
8838 var code_5 = code.isLineTerminator;
8839 var code_6 = code.isIdentifierStartES5;
8840 var code_7 = code.isIdentifierPartES5;
8841 var code_8 = code.isIdentifierStartES6;
8842 var code_9 = code.isIdentifierPartES6;
8844 var keyword = createCommonjsModule(function (module) {
8846 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
8848 Redistribution and use in source and binary forms, with or without
8849 modification, are permitted provided that the following conditions are met:
8851 * Redistributions of source code must retain the above copyright
8852 notice, this list of conditions and the following disclaimer.
8853 * Redistributions in binary form must reproduce the above copyright
8854 notice, this list of conditions and the following disclaimer in the
8855 documentation and/or other materials provided with the distribution.
8857 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
8858 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
8859 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
8860 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
8861 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
8862 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
8863 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
8864 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8865 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8866 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8872 function isStrictModeReservedWordES6(id) {
8889 function isKeywordES5(id, strict) {
8890 // yield should not be treated as keyword under non-strict mode.
8891 if (!strict && id === 'yield') {
8895 return isKeywordES6(id, strict);
8898 function isKeywordES6(id, strict) {
8899 if (strict && isStrictModeReservedWordES6(id)) {
8903 switch (id.length) {
8905 return id === 'if' || id === 'in' || id === 'do';
8908 return id === 'var' || id === 'for' || id === 'new' || id === 'try';
8911 return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum';
8914 return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super';
8917 return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import';
8920 return id === 'default' || id === 'finally' || id === 'extends';
8923 return id === 'function' || id === 'continue' || id === 'debugger';
8926 return id === 'instanceof';
8933 function isReservedWordES5(id, strict) {
8934 return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict);
8937 function isReservedWordES6(id, strict) {
8938 return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict);
8941 function isRestrictedWord(id) {
8942 return id === 'eval' || id === 'arguments';
8945 function isIdentifierNameES5(id) {
8948 if (id.length === 0) {
8952 ch = id.charCodeAt(0);
8954 if (!code$1.isIdentifierStartES5(ch)) {
8958 for (i = 1, iz = id.length; i < iz; ++i) {
8959 ch = id.charCodeAt(i);
8961 if (!code$1.isIdentifierPartES5(ch)) {
8969 function decodeUtf16(lead, trail) {
8970 return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
8973 function isIdentifierNameES6(id) {
8974 var i, iz, ch, lowCh, check;
8976 if (id.length === 0) {
8980 check = code$1.isIdentifierStartES6;
8982 for (i = 0, iz = id.length; i < iz; ++i) {
8983 ch = id.charCodeAt(i);
8985 if (0xD800 <= ch && ch <= 0xDBFF) {
8992 lowCh = id.charCodeAt(i);
8994 if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) {
8998 ch = decodeUtf16(ch, lowCh);
9005 check = code$1.isIdentifierPartES6;
9011 function isIdentifierES5(id, strict) {
9012 return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
9015 function isIdentifierES6(id, strict) {
9016 return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
9020 isKeywordES5: isKeywordES5,
9021 isKeywordES6: isKeywordES6,
9022 isReservedWordES5: isReservedWordES5,
9023 isReservedWordES6: isReservedWordES6,
9024 isRestrictedWord: isRestrictedWord,
9025 isIdentifierNameES5: isIdentifierNameES5,
9026 isIdentifierNameES6: isIdentifierNameES6,
9027 isIdentifierES5: isIdentifierES5,
9028 isIdentifierES6: isIdentifierES6
9031 /* vim: set sw=4 ts=4 et tw=80 : */
9034 var keyword_1 = keyword.isKeywordES5;
9035 var keyword_2 = keyword.isKeywordES6;
9036 var keyword_3 = keyword.isReservedWordES5;
9037 var keyword_4 = keyword.isReservedWordES6;
9038 var keyword_5 = keyword.isRestrictedWord;
9039 var keyword_6 = keyword.isIdentifierNameES5;
9040 var keyword_7 = keyword.isIdentifierNameES6;
9041 var keyword_8 = keyword.isIdentifierES5;
9042 var keyword_9 = keyword.isIdentifierES6;
9044 var utils$1 = createCommonjsModule(function (module, exports) {
9046 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
9048 Redistribution and use in source and binary forms, with or without
9049 modification, are permitted provided that the following conditions are met:
9051 * Redistributions of source code must retain the above copyright
9052 notice, this list of conditions and the following disclaimer.
9053 * Redistributions in binary form must reproduce the above copyright
9054 notice, this list of conditions and the following disclaimer in the
9055 documentation and/or other materials provided with the distribution.
9057 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
9058 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
9059 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
9060 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
9061 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
9062 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
9063 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
9064 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9065 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
9066 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9071 exports.code = code;
9072 exports.keyword = keyword;
9074 /* vim: set sw=4 ts=4 et tw=80 : */
9077 var utils_1$1 = utils$1.ast;
9078 var utils_2$1 = utils$1.code;
9079 var utils_3$1 = utils$1.keyword;
9081 var matchOperatorsRe$1 = /[|\\{}()[\]^$+*?.]/g;
9083 var escapeStringRegexp$1 = function (str) {
9084 if (typeof str !== 'string') {
9085 throw new TypeError('Expected a string');
9088 return str.replace(matchOperatorsRe$1, '\\$&');
9092 "aliceblue": [240, 248, 255],
9093 "antiquewhite": [250, 235, 215],
9094 "aqua": [0, 255, 255],
9095 "aquamarine": [127, 255, 212],
9096 "azure": [240, 255, 255],
9097 "beige": [245, 245, 220],
9098 "bisque": [255, 228, 196],
9100 "blanchedalmond": [255, 235, 205],
9101 "blue": [0, 0, 255],
9102 "blueviolet": [138, 43, 226],
9103 "brown": [165, 42, 42],
9104 "burlywood": [222, 184, 135],
9105 "cadetblue": [95, 158, 160],
9106 "chartreuse": [127, 255, 0],
9107 "chocolate": [210, 105, 30],
9108 "coral": [255, 127, 80],
9109 "cornflowerblue": [100, 149, 237],
9110 "cornsilk": [255, 248, 220],
9111 "crimson": [220, 20, 60],
9112 "cyan": [0, 255, 255],
9113 "darkblue": [0, 0, 139],
9114 "darkcyan": [0, 139, 139],
9115 "darkgoldenrod": [184, 134, 11],
9116 "darkgray": [169, 169, 169],
9117 "darkgreen": [0, 100, 0],
9118 "darkgrey": [169, 169, 169],
9119 "darkkhaki": [189, 183, 107],
9120 "darkmagenta": [139, 0, 139],
9121 "darkolivegreen": [85, 107, 47],
9122 "darkorange": [255, 140, 0],
9123 "darkorchid": [153, 50, 204],
9124 "darkred": [139, 0, 0],
9125 "darksalmon": [233, 150, 122],
9126 "darkseagreen": [143, 188, 143],
9127 "darkslateblue": [72, 61, 139],
9128 "darkslategray": [47, 79, 79],
9129 "darkslategrey": [47, 79, 79],
9130 "darkturquoise": [0, 206, 209],
9131 "darkviolet": [148, 0, 211],
9132 "deeppink": [255, 20, 147],
9133 "deepskyblue": [0, 191, 255],
9134 "dimgray": [105, 105, 105],
9135 "dimgrey": [105, 105, 105],
9136 "dodgerblue": [30, 144, 255],
9137 "firebrick": [178, 34, 34],
9138 "floralwhite": [255, 250, 240],
9139 "forestgreen": [34, 139, 34],
9140 "fuchsia": [255, 0, 255],
9141 "gainsboro": [220, 220, 220],
9142 "ghostwhite": [248, 248, 255],
9143 "gold": [255, 215, 0],
9144 "goldenrod": [218, 165, 32],
9145 "gray": [128, 128, 128],
9146 "green": [0, 128, 0],
9147 "greenyellow": [173, 255, 47],
9148 "grey": [128, 128, 128],
9149 "honeydew": [240, 255, 240],
9150 "hotpink": [255, 105, 180],
9151 "indianred": [205, 92, 92],
9152 "indigo": [75, 0, 130],
9153 "ivory": [255, 255, 240],
9154 "khaki": [240, 230, 140],
9155 "lavender": [230, 230, 250],
9156 "lavenderblush": [255, 240, 245],
9157 "lawngreen": [124, 252, 0],
9158 "lemonchiffon": [255, 250, 205],
9159 "lightblue": [173, 216, 230],
9160 "lightcoral": [240, 128, 128],
9161 "lightcyan": [224, 255, 255],
9162 "lightgoldenrodyellow": [250, 250, 210],
9163 "lightgray": [211, 211, 211],
9164 "lightgreen": [144, 238, 144],
9165 "lightgrey": [211, 211, 211],
9166 "lightpink": [255, 182, 193],
9167 "lightsalmon": [255, 160, 122],
9168 "lightseagreen": [32, 178, 170],
9169 "lightskyblue": [135, 206, 250],
9170 "lightslategray": [119, 136, 153],
9171 "lightslategrey": [119, 136, 153],
9172 "lightsteelblue": [176, 196, 222],
9173 "lightyellow": [255, 255, 224],
9174 "lime": [0, 255, 0],
9175 "limegreen": [50, 205, 50],
9176 "linen": [250, 240, 230],
9177 "magenta": [255, 0, 255],
9178 "maroon": [128, 0, 0],
9179 "mediumaquamarine": [102, 205, 170],
9180 "mediumblue": [0, 0, 205],
9181 "mediumorchid": [186, 85, 211],
9182 "mediumpurple": [147, 112, 219],
9183 "mediumseagreen": [60, 179, 113],
9184 "mediumslateblue": [123, 104, 238],
9185 "mediumspringgreen": [0, 250, 154],
9186 "mediumturquoise": [72, 209, 204],
9187 "mediumvioletred": [199, 21, 133],
9188 "midnightblue": [25, 25, 112],
9189 "mintcream": [245, 255, 250],
9190 "mistyrose": [255, 228, 225],
9191 "moccasin": [255, 228, 181],
9192 "navajowhite": [255, 222, 173],
9193 "navy": [0, 0, 128],
9194 "oldlace": [253, 245, 230],
9195 "olive": [128, 128, 0],
9196 "olivedrab": [107, 142, 35],
9197 "orange": [255, 165, 0],
9198 "orangered": [255, 69, 0],
9199 "orchid": [218, 112, 214],
9200 "palegoldenrod": [238, 232, 170],
9201 "palegreen": [152, 251, 152],
9202 "paleturquoise": [175, 238, 238],
9203 "palevioletred": [219, 112, 147],
9204 "papayawhip": [255, 239, 213],
9205 "peachpuff": [255, 218, 185],
9206 "peru": [205, 133, 63],
9207 "pink": [255, 192, 203],
9208 "plum": [221, 160, 221],
9209 "powderblue": [176, 224, 230],
9210 "purple": [128, 0, 128],
9211 "rebeccapurple": [102, 51, 153],
9213 "rosybrown": [188, 143, 143],
9214 "royalblue": [65, 105, 225],
9215 "saddlebrown": [139, 69, 19],
9216 "salmon": [250, 128, 114],
9217 "sandybrown": [244, 164, 96],
9218 "seagreen": [46, 139, 87],
9219 "seashell": [255, 245, 238],
9220 "sienna": [160, 82, 45],
9221 "silver": [192, 192, 192],
9222 "skyblue": [135, 206, 235],
9223 "slateblue": [106, 90, 205],
9224 "slategray": [112, 128, 144],
9225 "slategrey": [112, 128, 144],
9226 "snow": [255, 250, 250],
9227 "springgreen": [0, 255, 127],
9228 "steelblue": [70, 130, 180],
9229 "tan": [210, 180, 140],
9230 "teal": [0, 128, 128],
9231 "thistle": [216, 191, 216],
9232 "tomato": [255, 99, 71],
9233 "turquoise": [64, 224, 208],
9234 "violet": [238, 130, 238],
9235 "wheat": [245, 222, 179],
9236 "white": [255, 255, 255],
9237 "whitesmoke": [245, 245, 245],
9238 "yellow": [255, 255, 0],
9239 "yellowgreen": [154, 205, 50]
9242 var conversions$2 = createCommonjsModule(function (module) {
9244 // NOTE: conversions should only return primitive values (i.e. arrays, or
9245 // values that give correct `typeof` results).
9246 // do not use box values types (i.e. Number(), String(), etc.)
9247 var reverseKeywords = {};
9249 for (var key in colorName$2) {
9250 if (colorName$2.hasOwnProperty(key)) {
9251 reverseKeywords[colorName$2[key]] = key;
9255 var convert = module.exports = {
9306 labels: ['h', 'c', 'g']
9310 labels: ['r16', 'g16', 'b16']
9316 }; // hide .channels and .labels properties
9318 for (var model in convert) {
9319 if (convert.hasOwnProperty(model)) {
9320 if (!('channels' in convert[model])) {
9321 throw new Error('missing channels property: ' + model);
9324 if (!('labels' in convert[model])) {
9325 throw new Error('missing channel labels property: ' + model);
9328 if (convert[model].labels.length !== convert[model].channels) {
9329 throw new Error('channel and label counts mismatch: ' + model);
9332 var channels = convert[model].channels;
9333 var labels = convert[model].labels;
9334 delete convert[model].channels;
9335 delete convert[model].labels;
9336 Object.defineProperty(convert[model], 'channels', {
9339 Object.defineProperty(convert[model], 'labels', {
9345 convert.rgb.hsl = function (rgb) {
9346 var r = rgb[0] / 255;
9347 var g = rgb[1] / 255;
9348 var b = rgb[2] / 255;
9349 var min = Math.min(r, g, b);
9350 var max = Math.max(r, g, b);
9351 var delta = max - min;
9358 } else if (r === max) {
9359 h = (g - b) / delta;
9360 } else if (g === max) {
9361 h = 2 + (b - r) / delta;
9362 } else if (b === max) {
9363 h = 4 + (r - g) / delta;
9366 h = Math.min(h * 60, 360);
9372 l = (min + max) / 2;
9376 } else if (l <= 0.5) {
9377 s = delta / (max + min);
9379 s = delta / (2 - max - min);
9382 return [h, s * 100, l * 100];
9385 convert.rgb.hsv = function (rgb) {
9391 var r = rgb[0] / 255;
9392 var g = rgb[1] / 255;
9393 var b = rgb[2] / 255;
9394 var v = Math.max(r, g, b);
9395 var diff = v - Math.min(r, g, b);
9397 var diffc = function (c) {
9398 return (v - c) / 6 / diff + 1 / 2;
9411 } else if (g === v) {
9412 h = 1 / 3 + rdif - bdif;
9413 } else if (b === v) {
9414 h = 2 / 3 + gdif - rdif;
9424 return [h * 360, s * 100, v * 100];
9427 convert.rgb.hwb = function (rgb) {
9431 var h = convert.rgb.hsl(rgb)[0];
9432 var w = 1 / 255 * Math.min(r, Math.min(g, b));
9433 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
9434 return [h, w * 100, b * 100];
9437 convert.rgb.cmyk = function (rgb) {
9438 var r = rgb[0] / 255;
9439 var g = rgb[1] / 255;
9440 var b = rgb[2] / 255;
9445 k = Math.min(1 - r, 1 - g, 1 - b);
9446 c = (1 - r - k) / (1 - k) || 0;
9447 m = (1 - g - k) / (1 - k) || 0;
9448 y = (1 - b - k) / (1 - k) || 0;
9449 return [c * 100, m * 100, y * 100, k * 100];
9452 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
9456 function comparativeDistance(x, y) {
9457 return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
9460 convert.rgb.keyword = function (rgb) {
9461 var reversed = reverseKeywords[rgb];
9467 var currentClosestDistance = Infinity;
9468 var currentClosestKeyword;
9470 for (var keyword in colorName$2) {
9471 if (colorName$2.hasOwnProperty(keyword)) {
9472 var value = colorName$2[keyword]; // Compute comparative distance
9474 var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
9476 if (distance < currentClosestDistance) {
9477 currentClosestDistance = distance;
9478 currentClosestKeyword = keyword;
9483 return currentClosestKeyword;
9486 convert.keyword.rgb = function (keyword) {
9487 return colorName$2[keyword];
9490 convert.rgb.xyz = function (rgb) {
9491 var r = rgb[0] / 255;
9492 var g = rgb[1] / 255;
9493 var b = rgb[2] / 255; // assume sRGB
9495 r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
9496 g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
9497 b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
9498 var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
9499 var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
9500 var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
9501 return [x * 100, y * 100, z * 100];
9504 convert.rgb.lab = function (rgb) {
9505 var xyz = convert.rgb.xyz(rgb);
9515 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
9516 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
9517 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
9524 convert.hsl.rgb = function (hsl) {
9525 var h = hsl[0] / 360;
9526 var s = hsl[1] / 100;
9527 var l = hsl[2] / 100;
9536 return [val, val, val];
9548 for (var i = 0; i < 3; i++) {
9549 t3 = h + 1 / 3 * -(i - 1);
9560 val = t1 + (t2 - t1) * 6 * t3;
9561 } else if (2 * t3 < 1) {
9563 } else if (3 * t3 < 2) {
9564 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
9575 convert.hsl.hsv = function (hsl) {
9577 var s = hsl[1] / 100;
9578 var l = hsl[2] / 100;
9580 var lmin = Math.max(l, 0.01);
9584 s *= l <= 1 ? l : 2 - l;
9585 smin *= lmin <= 1 ? lmin : 2 - lmin;
9587 sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
9588 return [h, sv * 100, v * 100];
9591 convert.hsv.rgb = function (hsv) {
9592 var h = hsv[0] / 60;
9593 var s = hsv[1] / 100;
9594 var v = hsv[2] / 100;
9595 var hi = Math.floor(h) % 6;
9596 var f = h - Math.floor(h);
9597 var p = 255 * v * (1 - s);
9598 var q = 255 * v * (1 - s * f);
9599 var t = 255 * v * (1 - s * (1 - f));
9623 convert.hsv.hsl = function (hsv) {
9625 var s = hsv[1] / 100;
9626 var v = hsv[2] / 100;
9627 var vmin = Math.max(v, 0.01);
9632 lmin = (2 - s) * vmin;
9634 sl /= lmin <= 1 ? lmin : 2 - lmin;
9637 return [h, sl * 100, l * 100];
9638 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
9641 convert.hwb.rgb = function (hwb) {
9642 var h = hwb[0] / 360;
9643 var wh = hwb[1] / 100;
9644 var bl = hwb[2] / 100;
9645 var ratio = wh + bl;
9649 var n; // wh + bl cant be > 1
9656 i = Math.floor(6 * h);
9660 if ((i & 0x01) !== 0) {
9664 n = wh + f * (v - wh); // linear interpolation
9710 return [r * 255, g * 255, b * 255];
9713 convert.cmyk.rgb = function (cmyk) {
9714 var c = cmyk[0] / 100;
9715 var m = cmyk[1] / 100;
9716 var y = cmyk[2] / 100;
9717 var k = cmyk[3] / 100;
9721 r = 1 - Math.min(1, c * (1 - k) + k);
9722 g = 1 - Math.min(1, m * (1 - k) + k);
9723 b = 1 - Math.min(1, y * (1 - k) + k);
9724 return [r * 255, g * 255, b * 255];
9727 convert.xyz.rgb = function (xyz) {
9728 var x = xyz[0] / 100;
9729 var y = xyz[1] / 100;
9730 var z = xyz[2] / 100;
9734 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
9735 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
9736 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
9738 r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
9739 g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
9740 b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
9741 r = Math.min(Math.max(0, r), 1);
9742 g = Math.min(Math.max(0, g), 1);
9743 b = Math.min(Math.max(0, b), 1);
9744 return [r * 255, g * 255, b * 255];
9747 convert.xyz.lab = function (xyz) {
9757 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
9758 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
9759 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
9766 convert.lab.xyz = function (lab) {
9776 var y2 = Math.pow(y, 3);
9777 var x2 = Math.pow(x, 3);
9778 var z2 = Math.pow(z, 3);
9779 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
9780 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
9781 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
9788 convert.lab.lch = function (lab) {
9795 hr = Math.atan2(b, a);
9796 h = hr * 360 / 2 / Math.PI;
9802 c = Math.sqrt(a * a + b * b);
9806 convert.lch.lab = function (lch) {
9813 hr = h / 360 * 2 * Math.PI;
9814 a = c * Math.cos(hr);
9815 b = c * Math.sin(hr);
9819 convert.rgb.ansi16 = function (args) {
9823 var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
9825 value = Math.round(value / 50);
9831 var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
9840 convert.hsv.ansi16 = function (args) {
9841 // optimization here; we already know the value and don't need to get
9842 // it converted for us.
9843 return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
9846 convert.rgb.ansi256 = function (args) {
9849 var b = args[2]; // we use the extended greyscale palette here, with the exception of
9850 // black and white. normal palette only has 4 greyscale shades.
9852 if (r === g && g === b) {
9861 return Math.round((r - 8) / 247 * 24) + 232;
9864 var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
9868 convert.ansi16.rgb = function (args) {
9869 var color = args % 10; // handle greyscale
9871 if (color === 0 || color === 7) {
9876 color = color / 10.5 * 255;
9877 return [color, color, color];
9880 var mult = (~~(args > 50) + 1) * 0.5;
9881 var r = (color & 1) * mult * 255;
9882 var g = (color >> 1 & 1) * mult * 255;
9883 var b = (color >> 2 & 1) * mult * 255;
9887 convert.ansi256.rgb = function (args) {
9890 var c = (args - 232) * 10 + 8;
9896 var r = Math.floor(args / 36) / 5 * 255;
9897 var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
9898 var b = rem % 6 / 5 * 255;
9902 convert.rgb.hex = function (args) {
9903 var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
9904 var string = integer.toString(16).toUpperCase();
9905 return '000000'.substring(string.length) + string;
9908 convert.hex.rgb = function (args) {
9909 var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
9915 var colorString = match[0];
9917 if (match[0].length === 3) {
9918 colorString = colorString.split('').map(function (char) {
9923 var integer = parseInt(colorString, 16);
9924 var r = integer >> 16 & 0xFF;
9925 var g = integer >> 8 & 0xFF;
9926 var b = integer & 0xFF;
9930 convert.rgb.hcg = function (rgb) {
9931 var r = rgb[0] / 255;
9932 var g = rgb[1] / 255;
9933 var b = rgb[2] / 255;
9934 var max = Math.max(Math.max(r, g), b);
9935 var min = Math.min(Math.min(r, g), b);
9936 var chroma = max - min;
9941 grayscale = min / (1 - chroma);
9948 } else if (max === r) {
9949 hue = (g - b) / chroma % 6;
9950 } else if (max === g) {
9951 hue = 2 + (b - r) / chroma;
9953 hue = 4 + (r - g) / chroma + 4;
9958 return [hue * 360, chroma * 100, grayscale * 100];
9961 convert.hsl.hcg = function (hsl) {
9962 var s = hsl[1] / 100;
9963 var l = hsl[2] / 100;
9970 c = 2.0 * s * (1.0 - l);
9974 f = (l - 0.5 * c) / (1.0 - c);
9977 return [hsl[0], c * 100, f * 100];
9980 convert.hsv.hcg = function (hsv) {
9981 var s = hsv[1] / 100;
9982 var v = hsv[2] / 100;
9987 f = (v - c) / (1 - c);
9990 return [hsv[0], c * 100, f * 100];
9993 convert.hcg.rgb = function (hcg) {
9994 var h = hcg[0] / 360;
9995 var c = hcg[1] / 100;
9996 var g = hcg[2] / 100;
9999 return [g * 255, g * 255, g * 255];
10002 var pure = [0, 0, 0];
10003 var hi = h % 1 * 6;
10008 switch (Math.floor(hi)) {
10045 mg = (1.0 - c) * g;
10046 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
10049 convert.hcg.hsv = function (hcg) {
10050 var c = hcg[1] / 100;
10051 var g = hcg[2] / 100;
10052 var v = c + g * (1.0 - c);
10059 return [hcg[0], f * 100, v * 100];
10062 convert.hcg.hsl = function (hcg) {
10063 var c = hcg[1] / 100;
10064 var g = hcg[2] / 100;
10065 var l = g * (1.0 - c) + 0.5 * c;
10068 if (l > 0.0 && l < 0.5) {
10070 } else if (l >= 0.5 && l < 1.0) {
10071 s = c / (2 * (1 - l));
10074 return [hcg[0], s * 100, l * 100];
10077 convert.hcg.hwb = function (hcg) {
10078 var c = hcg[1] / 100;
10079 var g = hcg[2] / 100;
10080 var v = c + g * (1.0 - c);
10081 return [hcg[0], (v - c) * 100, (1 - v) * 100];
10084 convert.hwb.hcg = function (hwb) {
10085 var w = hwb[1] / 100;
10086 var b = hwb[2] / 100;
10092 g = (v - c) / (1 - c);
10095 return [hwb[0], c * 100, g * 100];
10098 convert.apple.rgb = function (apple) {
10099 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
10102 convert.rgb.apple = function (rgb) {
10103 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
10106 convert.gray.rgb = function (args) {
10107 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
10110 convert.gray.hsl = convert.gray.hsv = function (args) {
10111 return [0, 0, args[0]];
10114 convert.gray.hwb = function (gray) {
10115 return [0, 100, gray[0]];
10118 convert.gray.cmyk = function (gray) {
10119 return [0, 0, 0, gray[0]];
10122 convert.gray.lab = function (gray) {
10123 return [gray[0], 0, 0];
10126 convert.gray.hex = function (gray) {
10127 var val = Math.round(gray[0] / 100 * 255) & 0xFF;
10128 var integer = (val << 16) + (val << 8) + val;
10129 var string = integer.toString(16).toUpperCase();
10130 return '000000'.substring(string.length) + string;
10133 convert.rgb.gray = function (rgb) {
10134 var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
10135 return [val / 255 * 100];
10138 var conversions_1$1 = conversions$2.rgb;
10139 var conversions_2$1 = conversions$2.hsl;
10140 var conversions_3$1 = conversions$2.hsv;
10141 var conversions_4$1 = conversions$2.hwb;
10142 var conversions_5$1 = conversions$2.cmyk;
10143 var conversions_6$1 = conversions$2.xyz;
10144 var conversions_7$1 = conversions$2.lab;
10145 var conversions_8$1 = conversions$2.lch;
10146 var conversions_9$1 = conversions$2.hex;
10147 var conversions_10$1 = conversions$2.keyword;
10148 var conversions_11$1 = conversions$2.ansi16;
10149 var conversions_12$1 = conversions$2.ansi256;
10150 var conversions_13$1 = conversions$2.hcg;
10151 var conversions_14$1 = conversions$2.apple;
10152 var conversions_15$1 = conversions$2.gray;
10155 this function routes a model to all other models.
10157 all functions that are routed have a property `.conversion` attached
10158 to the returned synthetic function. This property is an array
10159 of strings, each with the steps in between the 'from' and 'to'
10160 color models (inclusive).
10162 conversions that are not possible simply are not included.
10165 function buildGraph$2() {
10166 var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
10168 var models = Object.keys(conversions$2);
10170 for (var len = models.length, i = 0; i < len; i++) {
10171 graph[models[i]] = {
10172 // http://jsperf.com/1-vs-infinity
10173 // micro-opt, but this is simple.
10180 } // https://en.wikipedia.org/wiki/Breadth-first_search
10183 function deriveBFS$2(fromModel) {
10184 var graph = buildGraph$2();
10185 var queue = [fromModel]; // unshift -> queue -> pop
10187 graph[fromModel].distance = 0;
10189 while (queue.length) {
10190 var current = queue.pop();
10191 var adjacents = Object.keys(conversions$2[current]);
10193 for (var len = adjacents.length, i = 0; i < len; i++) {
10194 var adjacent = adjacents[i];
10195 var node = graph[adjacent];
10197 if (node.distance === -1) {
10198 node.distance = graph[current].distance + 1;
10199 node.parent = current;
10200 queue.unshift(adjacent);
10208 function link$2(from, to) {
10209 return function (args) {
10210 return to(from(args));
10214 function wrapConversion$2(toModel, graph) {
10215 var path = [graph[toModel].parent, toModel];
10216 var fn = conversions$2[graph[toModel].parent][toModel];
10217 var cur = graph[toModel].parent;
10219 while (graph[cur].parent) {
10220 path.unshift(graph[cur].parent);
10221 fn = link$2(conversions$2[graph[cur].parent][cur], fn);
10222 cur = graph[cur].parent;
10225 fn.conversion = path;
10229 var route$2 = function (fromModel) {
10230 var graph = deriveBFS$2(fromModel);
10231 var conversion = {};
10232 var models = Object.keys(graph);
10234 for (var len = models.length, i = 0; i < len; i++) {
10235 var toModel = models[i];
10236 var node = graph[toModel];
10238 if (node.parent === null) {
10239 // no possible conversion, or this node is the source model.
10243 conversion[toModel] = wrapConversion$2(toModel, graph);
10249 var convert$3 = {};
10250 var models$2 = Object.keys(conversions$2);
10252 function wrapRaw$2(fn) {
10253 var wrappedFn = function (args) {
10254 if (args === undefined || args === null) {
10258 if (arguments.length > 1) {
10259 args = Array.prototype.slice.call(arguments);
10263 }; // preserve .conversion property if there is one
10266 if ('conversion' in fn) {
10267 wrappedFn.conversion = fn.conversion;
10273 function wrapRounded$2(fn) {
10274 var wrappedFn = function (args) {
10275 if (args === undefined || args === null) {
10279 if (arguments.length > 1) {
10280 args = Array.prototype.slice.call(arguments);
10283 var result = fn(args); // we're assuming the result is an array here.
10284 // see notice in conversions.js; don't use box types
10285 // in conversion functions.
10287 if (typeof result === 'object') {
10288 for (var len = result.length, i = 0; i < len; i++) {
10289 result[i] = Math.round(result[i]);
10294 }; // preserve .conversion property if there is one
10297 if ('conversion' in fn) {
10298 wrappedFn.conversion = fn.conversion;
10304 models$2.forEach(function (fromModel) {
10305 convert$3[fromModel] = {};
10306 Object.defineProperty(convert$3[fromModel], 'channels', {
10307 value: conversions$2[fromModel].channels
10309 Object.defineProperty(convert$3[fromModel], 'labels', {
10310 value: conversions$2[fromModel].labels
10312 var routes = route$2(fromModel);
10313 var routeModels = Object.keys(routes);
10314 routeModels.forEach(function (toModel) {
10315 var fn = routes[toModel];
10316 convert$3[fromModel][toModel] = wrapRounded$2(fn);
10317 convert$3[fromModel][toModel].raw = wrapRaw$2(fn);
10320 var colorConvert$2 = convert$3;
10322 var ansiStyles$2 = createCommonjsModule(function (module) {
10324 const wrapAnsi16 = (fn, offset) => function () {
10325 const code = fn.apply(colorConvert$2, arguments);
10326 return `\u001B[${code + offset}m`;
10329 const wrapAnsi256 = (fn, offset) => function () {
10330 const code = fn.apply(colorConvert$2, arguments);
10331 return `\u001B[${38 + offset};5;${code}m`;
10334 const wrapAnsi16m = (fn, offset) => function () {
10335 const rgb = fn.apply(colorConvert$2, arguments);
10336 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
10339 function assembleStyles() {
10340 const codes = new Map();
10344 // 21 isn't widely supported and 22 does the same thing
10348 underline: [4, 24],
10351 strikethrough: [9, 29]
10364 redBright: [91, 39],
10365 greenBright: [92, 39],
10366 yellowBright: [93, 39],
10367 blueBright: [94, 39],
10368 magentaBright: [95, 39],
10369 cyanBright: [96, 39],
10370 whiteBright: [97, 39]
10376 bgYellow: [43, 49],
10378 bgMagenta: [45, 49],
10382 bgBlackBright: [100, 49],
10383 bgRedBright: [101, 49],
10384 bgGreenBright: [102, 49],
10385 bgYellowBright: [103, 49],
10386 bgBlueBright: [104, 49],
10387 bgMagentaBright: [105, 49],
10388 bgCyanBright: [106, 49],
10389 bgWhiteBright: [107, 49]
10393 styles.color.grey = styles.color.gray;
10395 for (const groupName of Object.keys(styles)) {
10396 const group = styles[groupName];
10398 for (const styleName of Object.keys(group)) {
10399 const style = group[styleName];
10400 styles[styleName] = {
10401 open: `\u001B[${style[0]}m`,
10402 close: `\u001B[${style[1]}m`
10404 group[styleName] = styles[styleName];
10405 codes.set(style[0], style[1]);
10408 Object.defineProperty(styles, groupName, {
10412 Object.defineProperty(styles, 'codes', {
10418 const ansi2ansi = n => n;
10420 const rgb2rgb = (r, g, b) => [r, g, b];
10422 styles.color.close = '\u001B[39m';
10423 styles.bgColor.close = '\u001B[49m';
10424 styles.color.ansi = {
10425 ansi: wrapAnsi16(ansi2ansi, 0)
10427 styles.color.ansi256 = {
10428 ansi256: wrapAnsi256(ansi2ansi, 0)
10430 styles.color.ansi16m = {
10431 rgb: wrapAnsi16m(rgb2rgb, 0)
10433 styles.bgColor.ansi = {
10434 ansi: wrapAnsi16(ansi2ansi, 10)
10436 styles.bgColor.ansi256 = {
10437 ansi256: wrapAnsi256(ansi2ansi, 10)
10439 styles.bgColor.ansi16m = {
10440 rgb: wrapAnsi16m(rgb2rgb, 10)
10443 for (let key of Object.keys(colorConvert$2)) {
10444 if (typeof colorConvert$2[key] !== 'object') {
10448 const suite = colorConvert$2[key];
10450 if (key === 'ansi16') {
10454 if ('ansi16' in suite) {
10455 styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
10456 styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
10459 if ('ansi256' in suite) {
10460 styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
10461 styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
10464 if ('rgb' in suite) {
10465 styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
10466 styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
10471 } // Make the export immutable
10474 Object.defineProperty(module, 'exports', {
10476 get: assembleStyles
10480 const env$2 = process.env;
10483 if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
10484 forceColor$2 = false;
10485 } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
10486 forceColor$2 = true;
10489 if ('FORCE_COLOR' in env$2) {
10490 forceColor$2 = env$2.FORCE_COLOR.length === 0 || parseInt(env$2.FORCE_COLOR, 10) !== 0;
10493 function translateLevel$2(level) {
10501 has256: level >= 2,
10506 function supportsColor$2(stream) {
10507 if (forceColor$2 === false) {
10511 if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
10515 if (hasFlag('color=256')) {
10519 if (stream && !stream.isTTY && forceColor$2 !== true) {
10523 const min = forceColor$2 ? 1 : 0;
10525 if (process.platform === 'win32') {
10526 // Node.js 7.5.0 is the first version of Node.js to include a patch to
10527 // libuv that enables 256 color output on Windows. Anything earlier and it
10528 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
10529 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
10530 // release that supports 256 colors. Windows 10 build 14931 is the first release
10531 // that supports 16m/TrueColor.
10532 const osRelease = os$1.release().split('.');
10534 if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
10535 return Number(osRelease[2]) >= 14931 ? 3 : 2;
10541 if ('CI' in env$2) {
10542 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') {
10549 if ('TEAMCITY_VERSION' in env$2) {
10550 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0;
10553 if (env$2.COLORTERM === 'truecolor') {
10557 if ('TERM_PROGRAM' in env$2) {
10558 const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
10560 switch (env$2.TERM_PROGRAM) {
10562 return version >= 3 ? 3 : 2;
10564 case 'Apple_Terminal':
10570 if (/-256(color)?$/i.test(env$2.TERM)) {
10574 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) {
10578 if ('COLORTERM' in env$2) {
10582 if (env$2.TERM === 'dumb') {
10589 function getSupportLevel$2(stream) {
10590 const level = supportsColor$2(stream);
10591 return translateLevel$2(level);
10594 var supportsColor_1$2 = {
10595 supportsColor: getSupportLevel$2,
10596 stdout: getSupportLevel$2(process.stdout),
10597 stderr: getSupportLevel$2(process.stderr)
10600 const TEMPLATE_REGEX$2 = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
10601 const STYLE_REGEX$2 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
10602 const STRING_REGEX$2 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
10603 const ESCAPE_REGEX$2 = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
10604 const ESCAPES$2 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
10606 function unescape$2(c) {
10607 if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
10608 return String.fromCharCode(parseInt(c.slice(1), 16));
10611 return ESCAPES$2.get(c) || c;
10614 function parseArguments$2(name, args) {
10615 const results = [];
10616 const chunks = args.trim().split(/\s*,\s*/g);
10619 for (const chunk of chunks) {
10620 if (!isNaN(chunk)) {
10621 results.push(Number(chunk));
10622 } else if (matches = chunk.match(STRING_REGEX$2)) {
10623 results.push(matches[2].replace(ESCAPE_REGEX$2, (m, escape, chr) => escape ? unescape$2(escape) : chr));
10625 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
10632 function parseStyle$2(style) {
10633 STYLE_REGEX$2.lastIndex = 0;
10634 const results = [];
10637 while ((matches = STYLE_REGEX$2.exec(style)) !== null) {
10638 const name = matches[1];
10641 const args = parseArguments$2(name, matches[2]);
10642 results.push([name].concat(args));
10644 results.push([name]);
10651 function buildStyle$2(chalk, styles) {
10652 const enabled = {};
10654 for (const layer of styles) {
10655 for (const style of layer.styles) {
10656 enabled[style[0]] = layer.inverse ? null : style.slice(1);
10660 let current = chalk;
10662 for (const styleName of Object.keys(enabled)) {
10663 if (Array.isArray(enabled[styleName])) {
10664 if (!(styleName in current)) {
10665 throw new Error(`Unknown Chalk style: ${styleName}`);
10668 if (enabled[styleName].length > 0) {
10669 current = current[styleName].apply(current, enabled[styleName]);
10671 current = current[styleName];
10679 var templates$2 = (chalk, tmp) => {
10682 let chunk = []; // eslint-disable-next-line max-params
10684 tmp.replace(TEMPLATE_REGEX$2, (m, escapeChar, inverse, style, close, chr) => {
10686 chunk.push(unescape$2(escapeChar));
10687 } else if (style) {
10688 const str = chunk.join('');
10690 chunks.push(styles.length === 0 ? str : buildStyle$2(chalk, styles)(str));
10693 styles: parseStyle$2(style)
10695 } else if (close) {
10696 if (styles.length === 0) {
10697 throw new Error('Found extraneous } in Chalk template literal');
10700 chunks.push(buildStyle$2(chalk, styles)(chunk.join('')));
10707 chunks.push(chunk.join(''));
10709 if (styles.length > 0) {
10710 const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
10711 throw new Error(errMsg);
10714 return chunks.join('');
10717 var chalk$2 = createCommonjsModule(function (module) {
10719 const stdoutColor = supportsColor_1$2.stdout;
10720 const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
10722 const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
10724 const skipModels = new Set(['gray']);
10725 const styles = Object.create(null);
10727 function applyOptions(obj, options) {
10728 options = options || {}; // Detect level if not set manually
10730 const scLevel = stdoutColor ? stdoutColor.level : 0;
10731 obj.level = options.level === undefined ? scLevel : options.level;
10732 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
10735 function Chalk(options) {
10736 // We check for this.template here since calling `chalk.constructor()`
10737 // by itself will have a `this` of a previously constructed chalk object
10738 if (!this || !(this instanceof Chalk) || this.template) {
10740 applyOptions(chalk, options);
10742 chalk.template = function () {
10743 const args = [].slice.call(arguments);
10744 return chalkTag.apply(null, [chalk.template].concat(args));
10747 Object.setPrototypeOf(chalk, Chalk.prototype);
10748 Object.setPrototypeOf(chalk.template, chalk);
10749 chalk.template.constructor = Chalk;
10750 return chalk.template;
10753 applyOptions(this, options);
10754 } // Use bright blue on Windows as the normal blue color is illegible
10757 if (isSimpleWindowsTerm) {
10758 ansiStyles$2.blue.open = '\u001B[94m';
10761 for (const key of Object.keys(ansiStyles$2)) {
10762 ansiStyles$2[key].closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2[key].close), 'g');
10765 const codes = ansiStyles$2[key];
10766 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
10774 return build.call(this, this._styles || [], true, 'visible');
10778 ansiStyles$2.color.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2.color.close), 'g');
10780 for (const model of Object.keys(ansiStyles$2.color.ansi)) {
10781 if (skipModels.has(model)) {
10787 const level = this.level;
10788 return function () {
10789 const open = ansiStyles$2.color[levelMapping[level]][model].apply(null, arguments);
10792 close: ansiStyles$2.color.close,
10793 closeRe: ansiStyles$2.color.closeRe
10795 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
10802 ansiStyles$2.bgColor.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2.bgColor.close), 'g');
10804 for (const model of Object.keys(ansiStyles$2.bgColor.ansi)) {
10805 if (skipModels.has(model)) {
10809 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
10810 styles[bgModel] = {
10812 const level = this.level;
10813 return function () {
10814 const open = ansiStyles$2.bgColor[levelMapping[level]][model].apply(null, arguments);
10817 close: ansiStyles$2.bgColor.close,
10818 closeRe: ansiStyles$2.bgColor.closeRe
10820 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
10827 const proto = Object.defineProperties(() => {}, styles);
10829 function build(_styles, _empty, key) {
10830 const builder = function () {
10831 return applyStyle.apply(builder, arguments);
10834 builder._styles = _styles;
10835 builder._empty = _empty;
10837 Object.defineProperty(builder, 'level', {
10845 self.level = level;
10849 Object.defineProperty(builder, 'enabled', {
10853 return self.enabled;
10857 self.enabled = enabled;
10860 }); // See below for fix regarding invisible grey/dim combination on Windows
10862 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
10863 // no way to create a function with a different prototype
10865 builder.__proto__ = proto; // eslint-disable-line no-proto
10870 function applyStyle() {
10871 // Support varags, but simply cast to string in case there's only one arg
10872 const args = arguments;
10873 const argsLen = args.length;
10874 let str = String(arguments[0]);
10876 if (argsLen === 0) {
10881 // Don't slice `arguments`, it prevents V8 optimizations
10882 for (let a = 1; a < argsLen; a++) {
10883 str += ' ' + args[a];
10887 if (!this.enabled || this.level <= 0 || !str) {
10888 return this._empty ? '' : str;
10889 } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
10890 // see https://github.com/chalk/chalk/issues/58
10891 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
10894 const originalDim = ansiStyles$2.dim.open;
10896 if (isSimpleWindowsTerm && this.hasGrey) {
10897 ansiStyles$2.dim.open = '';
10900 for (const code of this._styles.slice().reverse()) {
10901 // Replace any instances already present with a re-opening code
10902 // otherwise only the part of the string until said closing code
10903 // will be colored, and the rest will simply be 'plain'.
10904 str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
10905 // after next line to fix a bleed issue on macOS
10906 // https://github.com/chalk/chalk/pull/92
10908 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
10909 } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
10912 ansiStyles$2.dim.open = originalDim;
10916 function chalkTag(chalk, strings) {
10917 if (!Array.isArray(strings)) {
10918 // If chalk() was called by itself or with a string,
10919 // return the string itself as a string.
10920 return [].slice.call(arguments, 1).join(' ');
10923 const args = [].slice.call(arguments, 2);
10924 const parts = [strings.raw[0]];
10926 for (let i = 1; i < strings.length; i++) {
10927 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
10928 parts.push(String(strings.raw[i]));
10931 return templates$2(chalk, parts.join(''));
10934 Object.defineProperties(Chalk.prototype, styles);
10935 module.exports = Chalk(); // eslint-disable-line new-cap
10937 module.exports.supportsColor = stdoutColor;
10938 module.exports.default = module.exports; // For TypeScript
10940 var chalk_1$1 = chalk$2.supportsColor;
10942 var lib$1 = createCommonjsModule(function (module, exports) {
10944 Object.defineProperty(exports, "__esModule", {
10947 exports.shouldHighlight = shouldHighlight;
10948 exports.getChalk = getChalk;
10949 exports.default = highlight;
10951 var _jsTokens = _interopRequireWildcard(jsTokens);
10953 var _esutils = _interopRequireDefault(utils$1);
10955 var _chalk = _interopRequireDefault(chalk$2);
10957 function _interopRequireDefault(obj) {
10958 return obj && obj.__esModule ? obj : {
10963 function _getRequireWildcardCache() {
10964 if (typeof WeakMap !== "function") return null;
10965 var cache = new WeakMap();
10967 _getRequireWildcardCache = function () {
10974 function _interopRequireWildcard(obj) {
10975 if (obj && obj.__esModule) {
10979 if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
10985 var cache = _getRequireWildcardCache();
10987 if (cache && cache.has(obj)) {
10988 return cache.get(obj);
10992 var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
10994 for (var key in obj) {
10995 if (Object.prototype.hasOwnProperty.call(obj, key)) {
10996 var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
10998 if (desc && (desc.get || desc.set)) {
10999 Object.defineProperty(newObj, key, desc);
11001 newObj[key] = obj[key];
11006 newObj.default = obj;
11009 cache.set(obj, newObj);
11015 function getDefs(chalk) {
11017 keyword: chalk.cyan,
11018 capitalized: chalk.yellow,
11019 jsx_tag: chalk.yellow,
11020 punctuator: chalk.yellow,
11021 number: chalk.magenta,
11022 string: chalk.green,
11023 regex: chalk.magenta,
11024 comment: chalk.grey,
11025 invalid: chalk.white.bgRed.bold
11029 const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
11030 const JSX_TAG = /^[a-z][\w-]*$/i;
11031 const BRACKET = /^[()[\]{}]$/;
11033 function getTokenType(match) {
11034 const [offset, text] = match.slice(-2);
11035 const token = (0, _jsTokens.matchToToken)(match);
11037 if (token.type === "name") {
11038 if (_esutils.default.keyword.isReservedWordES6(token.value)) {
11042 if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
11046 if (token.value[0] !== token.value[0].toLowerCase()) {
11047 return "capitalized";
11051 if (token.type === "punctuator" && BRACKET.test(token.value)) {
11055 if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
11056 return "punctuator";
11062 function highlightTokens(defs, text) {
11063 return text.replace(_jsTokens.default, function (...args) {
11064 const type = getTokenType(args);
11065 const colorize = defs[type];
11068 return args[0].split(NEWLINE).map(str => colorize(str)).join("\n");
11075 function shouldHighlight(options) {
11076 return _chalk.default.supportsColor || options.forceColor;
11079 function getChalk(options) {
11080 let chalk = _chalk.default;
11082 if (options.forceColor) {
11083 chalk = new _chalk.default.constructor({
11092 function highlight(code, options = {}) {
11093 if (shouldHighlight(options)) {
11094 const chalk = getChalk(options);
11095 const defs = getDefs(chalk);
11096 return highlightTokens(defs, code);
11102 unwrapExports(lib$1);
11103 var lib_1 = lib$1.shouldHighlight;
11104 var lib_2 = lib$1.getChalk;
11106 var lib$2 = createCommonjsModule(function (module, exports) {
11108 Object.defineProperty(exports, "__esModule", {
11111 exports.codeFrameColumns = codeFrameColumns;
11112 exports.default = _default;
11114 var _highlight = _interopRequireWildcard(lib$1);
11116 function _getRequireWildcardCache() {
11117 if (typeof WeakMap !== "function") return null;
11118 var cache = new WeakMap();
11120 _getRequireWildcardCache = function () {
11127 function _interopRequireWildcard(obj) {
11128 if (obj && obj.__esModule) {
11132 if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
11138 var cache = _getRequireWildcardCache();
11140 if (cache && cache.has(obj)) {
11141 return cache.get(obj);
11145 var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
11147 for (var key in obj) {
11148 if (Object.prototype.hasOwnProperty.call(obj, key)) {
11149 var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
11151 if (desc && (desc.get || desc.set)) {
11152 Object.defineProperty(newObj, key, desc);
11154 newObj[key] = obj[key];
11159 newObj.default = obj;
11162 cache.set(obj, newObj);
11168 let deprecationWarningShown = false;
11170 function getDefs(chalk) {
11172 gutter: chalk.grey,
11173 marker: chalk.red.bold,
11174 message: chalk.red.bold
11178 const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
11180 function getMarkerLines(loc, source, opts) {
11181 const startLoc = Object.assign({
11185 const endLoc = Object.assign({}, startLoc, {}, loc.end);
11190 const startLine = startLoc.line;
11191 const startColumn = startLoc.column;
11192 const endLine = endLoc.line;
11193 const endColumn = endLoc.column;
11194 let start = Math.max(startLine - (linesAbove + 1), 0);
11195 let end = Math.min(source.length, endLine + linesBelow);
11197 if (startLine === -1) {
11201 if (endLine === -1) {
11202 end = source.length;
11205 const lineDiff = endLine - startLine;
11206 const markerLines = {};
11209 for (let i = 0; i <= lineDiff; i++) {
11210 const lineNumber = i + startLine;
11212 if (!startColumn) {
11213 markerLines[lineNumber] = true;
11214 } else if (i === 0) {
11215 const sourceLength = source[lineNumber - 1].length;
11216 markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
11217 } else if (i === lineDiff) {
11218 markerLines[lineNumber] = [0, endColumn];
11220 const sourceLength = source[lineNumber - i].length;
11221 markerLines[lineNumber] = [0, sourceLength];
11225 if (startColumn === endColumn) {
11227 markerLines[startLine] = [startColumn, 0];
11229 markerLines[startLine] = true;
11232 markerLines[startLine] = [startColumn, endColumn - startColumn];
11243 function codeFrameColumns(rawLines, loc, opts = {}) {
11244 const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts);
11245 const chalk = (0, _highlight.getChalk)(opts);
11246 const defs = getDefs(chalk);
11248 const maybeHighlight = (chalkFn, string) => {
11249 return highlighted ? chalkFn(string) : string;
11252 const lines = rawLines.split(NEWLINE);
11257 } = getMarkerLines(loc, lines, opts);
11258 const hasColumns = loc.start && typeof loc.start.column === "number";
11259 const numberMaxWidth = String(end).length;
11260 const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines;
11261 let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => {
11262 const number = start + 1 + index;
11263 const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
11264 const gutter = ` ${paddedNumber} | `;
11265 const hasMarker = markerLines[number];
11266 const lastMarkerLine = !markerLines[number + 1];
11269 let markerLine = "";
11271 if (Array.isArray(hasMarker)) {
11272 const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
11273 const numberOfMarkers = hasMarker[1] || 1;
11274 markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
11276 if (lastMarkerLine && opts.message) {
11277 markerLine += " " + maybeHighlight(defs.message, opts.message);
11281 return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
11283 return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;
11287 if (opts.message && !hasColumns) {
11288 frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
11292 return chalk.reset(frame);
11298 function _default(rawLines, lineNumber, colNumber, opts = {}) {
11299 if (!deprecationWarningShown) {
11300 deprecationWarningShown = true;
11301 const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
11303 if (process.emitWarning) {
11304 process.emitWarning(message, "DeprecationWarning");
11306 const deprecationError = new Error(message);
11307 deprecationError.name = "DeprecationWarning";
11308 console.warn(new Error(message));
11312 colNumber = Math.max(colNumber, 0);
11319 return codeFrameColumns(rawLines, location, opts);
11322 unwrapExports(lib$2);
11323 var lib_1$1 = lib$2.codeFrameColumns;
11326 ConfigError: ConfigError$1
11329 locStart: locStart$1,
11331 } = loc; // Use defineProperties()/getOwnPropertyDescriptor() to prevent
11332 // triggering the parsers getters.
11334 const ownNames = Object.getOwnPropertyNames;
11335 const ownDescriptor = Object.getOwnPropertyDescriptor;
11337 function getParsers(options) {
11338 const parsers = {};
11340 for (const plugin of options.plugins) {
11341 if (!plugin.parsers) {
11345 for (const name of ownNames(plugin.parsers)) {
11346 Object.defineProperty(parsers, name, ownDescriptor(plugin.parsers, name));
11353 function resolveParser(opts, parsers) {
11354 parsers = parsers || getParsers(opts);
11356 if (typeof opts.parser === "function") {
11357 // Custom parser API always works with JavaScript.
11359 parse: opts.parser,
11360 astFormat: "estree",
11361 locStart: locStart$1,
11366 if (typeof opts.parser === "string") {
11367 if (Object.prototype.hasOwnProperty.call(parsers, opts.parser)) {
11368 return parsers[opts.parser];
11370 /* istanbul ignore next */
11376 parse: require(path$2.resolve(process.cwd(), opts.parser)),
11377 astFormat: "estree",
11378 locStart: locStart$1,
11382 /* istanbul ignore next */
11383 throw new ConfigError$1(`Couldn't resolve parser "${opts.parser}"`);
11389 function parse(text, opts) {
11390 const parsers = getParsers(opts); // Create a new object {parserName: parseFn}. Uses defineProperty() to only call
11391 // the parsers getters when actually calling the parser `parse` function.
11393 const parsersForCustomParserApi = Object.keys(parsers).reduce((object, parserName) => Object.defineProperty(object, parserName, {
11397 return parsers[parserName].parse;
11401 const parser = resolveParser(opts, parsers);
11404 if (parser.preprocess) {
11405 text = parser.preprocess(text, opts);
11410 ast: parser.parse(text, parsersForCustomParserApi, opts)
11418 const codeFrame = lib$2;
11419 error.codeFrame = codeFrame.codeFrameColumns(text, loc, {
11420 highlightCode: true
11422 error.message += "\n" + error.codeFrame;
11425 /* istanbul ignore next */
11438 UndefinedParserError: UndefinedParserError$1
11441 getSupportInfo: getSupportInfo$1
11444 resolveParser: resolveParser$1
11446 const hiddenDefaults = {
11447 astFormat: "estree",
11449 originalText: undefined,
11452 }; // Copy options and fill in default values.
11454 function normalize$1(options, opts) {
11456 const rawOptions = Object.assign({}, options);
11457 const supportOptions = getSupportInfo$1({
11458 plugins: options.plugins,
11459 showUnreleased: true,
11460 showDeprecated: true
11462 const defaults = Object.assign({}, hiddenDefaults, {}, fromPairs_1(supportOptions.filter(optionInfo => optionInfo.default !== undefined).map(option => [option.name, option.default])));
11464 if (!rawOptions.parser) {
11465 if (!rawOptions.filepath) {
11466 const logger = opts.logger || console;
11467 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.");
11468 rawOptions.parser = "babel";
11470 rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins);
11472 if (!rawOptions.parser) {
11473 throw new UndefinedParserError$1(`No parser could be inferred for file: ${rawOptions.filepath}`);
11478 const parser = resolveParser$1(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(x => x.name === "parser")], {
11482 rawOptions.astFormat = parser.astFormat;
11483 rawOptions.locEnd = parser.locEnd;
11484 rawOptions.locStart = parser.locStart;
11485 const plugin = getPlugin(rawOptions);
11486 rawOptions.printer = plugin.printers[rawOptions.astFormat];
11487 const pluginDefaults = supportOptions.filter(optionInfo => optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name] !== undefined).reduce((reduced, optionInfo) => Object.assign(reduced, {
11488 [optionInfo.name]: optionInfo.pluginDefaults[plugin.name]
11490 const mixedDefaults = Object.assign({}, defaults, {}, pluginDefaults);
11491 Object.keys(mixedDefaults).forEach(k => {
11492 if (rawOptions[k] == null) {
11493 rawOptions[k] = mixedDefaults[k];
11497 if (rawOptions.parser === "json") {
11498 rawOptions.trailingComma = "none";
11501 return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({
11502 passThrough: Object.keys(hiddenDefaults)
11506 function getPlugin(options) {
11512 throw new Error("getPlugin() requires astFormat to be set");
11515 const printerPlugin = options.plugins.find(plugin => plugin.printers && plugin.printers[astFormat]);
11517 if (!printerPlugin) {
11518 throw new Error(`Couldn't find plugin for AST format "${astFormat}"`);
11521 return printerPlugin;
11524 function getInterpreter(filepath) {
11525 if (typeof filepath !== "string") {
11532 fd = fs$3.openSync(filepath, "r");
11534 // istanbul ignore next
11539 const liner = new readlines(fd);
11540 const firstLine = liner.next().toString("utf8"); // #!/bin/env node, #!/usr/bin/env node
11542 const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/);
11546 } // #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node
11549 const m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/);
11557 // There are some weird cases where paths are missing, causing Jest
11558 // failures. It's unclear what these correspond to in the real world.
11562 // There are some weird cases where paths are missing, causing Jest
11563 // failures. It's unclear what these correspond to in the real world.
11564 fs$3.closeSync(fd);
11565 } catch (err) {// nop
11570 function inferParser(filepath, plugins) {
11571 const filename = path$2.basename(filepath).toLowerCase();
11572 const languages = getSupportInfo$1({
11574 }).languages.filter(language => language.since !== null); // If the file has no extension, we can try to infer the language from the
11575 // interpreter in the shebang line, if any; but since this requires FS access,
11578 let language = languages.find(language => language.extensions && language.extensions.some(extension => filename.endsWith(extension)) || language.filenames && language.filenames.find(name => name.toLowerCase() === filename));
11580 if (!language && !filename.includes(".")) {
11581 const interpreter = getInterpreter(filepath);
11582 language = languages.find(language => language.interpreters && language.interpreters.includes(interpreter));
11585 return language && language.parsers[0];
11589 normalize: normalize$1,
11594 function massageAST(ast, options, parent) {
11595 if (Array.isArray(ast)) {
11596 return ast.map(e => massageAST(e, options, parent)).filter(Boolean);
11599 if (!ast || typeof ast !== "object") {
11605 for (const key of Object.keys(ast)) {
11606 if (typeof ast[key] !== "function") {
11607 newObj[key] = massageAST(ast[key], options, ast);
11611 if (options.printer.massageAstNode) {
11612 const result = options.printer.massageAstNode(ast, newObj, parent);
11614 if (result === null) {
11626 var massageAst = massageAST;
11629 * @param {Doc[]} parts
11634 function concat(parts) {
11635 // access the internals of a document directly.
11636 // if(parts.length === 1) {
11637 // // If it's a single document, no need to concat it.
11638 // return parts[0];
11648 * @param {Doc} contents
11653 function indent(contents) {
11661 * @param {number} n
11662 * @param {Doc} contents
11667 function align(n, contents) {
11676 * @param {Doc} contents
11677 * @param {object} [opts] - TBD ???
11682 function group(contents, opts) {
11689 break: !!opts.shouldBreak,
11690 expandedStates: opts.expandedStates
11694 * @param {Doc} contents
11699 function dedentToRoot(contents) {
11700 return align(-Infinity, contents);
11703 * @param {Doc} contents
11708 function markAsRoot(contents) {
11709 // @ts-ignore - TBD ???:
11715 * @param {Doc} contents
11720 function dedent(contents) {
11721 return align(-1, contents);
11724 * @param {Doc[]} states
11725 * @param {object} [opts] - TBD ???
11730 function conditionalGroup(states, opts) {
11731 return group(states[0], Object.assign({}, opts, {
11732 expandedStates: states
11736 * @param {Doc[]} parts
11741 function fill(parts) {
11749 * @param {Doc} [breakContents]
11750 * @param {Doc} [flatContents]
11751 * @param {object} [opts] - TBD ???
11756 function ifBreak(breakContents, flatContents, opts) {
11763 groupId: opts.groupId
11767 * @param {Doc} contents
11772 function lineSuffix(contents) {
11775 type: "line-suffix",
11780 const lineSuffixBoundary = {
11781 type: "line-suffix-boundary"
11783 const breakParent = {
11784 type: "break-parent"
11796 const hardline = concat([{
11800 const literalline = concat([{
11807 placeholder: Symbol("cursor")
11811 * @param {Doc[]} arr
11815 function join(sep, arr) {
11818 for (let i = 0; i < arr.length; i++) {
11826 return concat(res);
11830 * @param {number} size
11831 * @param {number} tabWidth
11835 function addAlignmentToDoc(doc, size, tabWidth) {
11839 // Use indent to add tabs for all the levels of tabs we need
11840 for (let i = 0; i < Math.floor(size / tabWidth); ++i) {
11841 aligned = indent(aligned);
11842 } // Use align for all the spaces that are needed
11845 aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current
11846 // indentation, so we use -Infinity to reset the indentation to 0
11848 aligned = align(-Infinity, aligned);
11854 var docBuilders = {
11865 lineSuffixBoundary,
11881 const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|');
11882 return new RegExp(pattern, onlyFirst ? undefined : 'g');
11885 var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
11887 /* eslint-disable yoda */
11889 const isFullwidthCodePoint = codePoint => {
11890 if (Number.isNaN(codePoint)) {
11892 } // Code points are derived from:
11893 // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
11896 if (codePoint >= 0x1100 && (codePoint <= 0x115F || // Hangul Jamo
11897 codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET
11898 codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET
11899 // CJK Radicals Supplement .. Enclosed CJK Letters and Months
11900 0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
11901 0x3250 <= codePoint && codePoint <= 0x4DBF || // CJK Unified Ideographs .. Yi Radicals
11902 0x4E00 <= codePoint && codePoint <= 0xA4C6 || // Hangul Jamo Extended-A
11903 0xA960 <= codePoint && codePoint <= 0xA97C || // Hangul Syllables
11904 0xAC00 <= codePoint && codePoint <= 0xD7A3 || // CJK Compatibility Ideographs
11905 0xF900 <= codePoint && codePoint <= 0xFAFF || // Vertical Forms
11906 0xFE10 <= codePoint && codePoint <= 0xFE19 || // CJK Compatibility Forms .. Small Form Variants
11907 0xFE30 <= codePoint && codePoint <= 0xFE6B || // Halfwidth and Fullwidth Forms
11908 0xFF01 <= codePoint && codePoint <= 0xFF60 || 0xFFE0 <= codePoint && codePoint <= 0xFFE6 || // Kana Supplement
11909 0x1B000 <= codePoint && codePoint <= 0x1B001 || // Enclosed Ideographic Supplement
11910 0x1F200 <= codePoint && codePoint <= 0x1F251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
11911 0x20000 <= codePoint && codePoint <= 0x3FFFD)) {
11918 var isFullwidthCodePoint_1 = isFullwidthCodePoint;
11919 var default_1$1 = isFullwidthCodePoint;
11920 isFullwidthCodePoint_1.default = default_1$1;
11922 var emojiRegex = function () {
11923 // https://mths.be/emoji
11924 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;
11927 const stringWidth = string => {
11928 string = string.replace(emojiRegex(), ' ');
11930 if (typeof string !== 'string' || string.length === 0) {
11934 string = stripAnsi(string);
11937 for (let i = 0; i < string.length; i++) {
11938 const code = string.codePointAt(i); // Ignore control characters
11940 if (code <= 0x1F || code >= 0x7F && code <= 0x9F) {
11942 } // Ignore combining characters
11945 if (code >= 0x300 && code <= 0x36F) {
11950 if (code > 0xFFFF) {
11954 width += isFullwidthCodePoint_1(code) ? 2 : 1;
11960 var stringWidth_1 = stringWidth; // TODO: remove this in the next major version
11962 var default_1$2 = stringWidth;
11963 stringWidth_1.default = default_1$2;
11965 const matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g;
11967 var escapeStringRegexp$2 = string => {
11968 if (typeof string !== 'string') {
11969 throw new TypeError('Expected a string');
11972 return string.replace(matchOperatorsRegex, '\\$&');
11975 const notAsciiRegex = /[^\x20-\x7F]/;
11977 function getPenultimate(arr) {
11978 if (arr.length > 1) {
11979 return arr[arr.length - 2];
11985 * @typedef {{backwards?: boolean}} SkipOptions
11989 * @param {string | RegExp} chars
11990 * @returns {(text: string, index: number | false, opts?: SkipOptions) => number | false}
11994 function skip(chars) {
11995 return (text, index, opts) => {
11996 const backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having
11997 // to check for failures (did someone say monads?).
11999 if (index === false) {
12006 let cursor = index;
12008 while (cursor >= 0 && cursor < length) {
12009 const c = text.charAt(cursor);
12011 if (chars instanceof RegExp) {
12012 if (!chars.test(c)) {
12015 } else if (!chars.includes(c)) {
12019 backwards ? cursor-- : cursor++;
12022 if (cursor === -1 || cursor === length) {
12023 // If we reached the beginning or end of the file, return the
12024 // out-of-bounds cursor. It's up to the caller to handle this
12025 // correctly. We don't want to indicate `false` though if it
12026 // actually skipped valid characters.
12034 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
12038 const skipWhitespace = skip(/\s/);
12040 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
12043 const skipSpaces = skip(" \t");
12045 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
12048 const skipToLineEnd = skip(",; \t");
12050 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
12053 const skipEverythingButNewLine = skip(/[^\r\n]/);
12055 * @param {string} text
12056 * @param {number | false} index
12057 * @returns {number | false}
12060 function skipInlineComment(text, index) {
12061 if (index === false) {
12065 if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") {
12066 for (let i = index + 2; i < text.length; ++i) {
12067 if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") {
12076 * @param {string} text
12077 * @param {number | false} index
12078 * @returns {number | false}
12082 function skipTrailingComment(text, index) {
12083 if (index === false) {
12087 if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") {
12088 return skipEverythingButNewLine(text, index);
12092 } // This one doesn't use the above helper function because it wants to
12093 // test \r\n in order and `skip` doesn't support ordering and we only
12094 // want to skip one newline. It's simple to implement.
12097 * @param {string} text
12098 * @param {number | false} index
12099 * @param {SkipOptions=} opts
12100 * @returns {number | false}
12104 function skipNewline(text, index, opts) {
12105 const backwards = opts && opts.backwards;
12107 if (index === false) {
12111 const atIndex = text.charAt(index);
12114 if (text.charAt(index - 1) === "\r" && atIndex === "\n") {
12118 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
12122 if (atIndex === "\r" && text.charAt(index + 1) === "\n") {
12126 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
12134 * @param {string} text
12135 * @param {number} index
12136 * @param {SkipOptions=} opts
12137 * @returns {boolean}
12141 function hasNewline(text, index, opts) {
12143 const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
12144 const idx2 = skipNewline(text, idx, opts);
12145 return idx !== idx2;
12148 * @param {string} text
12149 * @param {number} start
12150 * @param {number} end
12151 * @returns {boolean}
12155 function hasNewlineInRange(text, start, end) {
12156 for (let i = start; i < end; ++i) {
12157 if (text.charAt(i) === "\n") {
12163 } // Note: this function doesn't ignore leading comments unlike isNextLineEmpty
12167 * @param {string} text
12169 * @param {(node: N) => number} locStart
12173 function isPreviousLineEmpty(text, node, locStart) {
12174 /** @type {number | false} */
12175 let idx = locStart(node) - 1;
12176 idx = skipSpaces(text, idx, {
12179 idx = skipNewline(text, idx, {
12182 idx = skipSpaces(text, idx, {
12185 const idx2 = skipNewline(text, idx, {
12188 return idx !== idx2;
12191 * @param {string} text
12192 * @param {number} index
12193 * @returns {boolean}
12197 function isNextLineEmptyAfterIndex(text, index) {
12198 /** @type {number | false} */
12200 /** @type {number | false} */
12204 while (idx !== oldIdx) {
12205 // We need to skip all the potential trailing inline comments
12207 idx = skipToLineEnd(text, idx);
12208 idx = skipInlineComment(text, idx);
12209 idx = skipSpaces(text, idx);
12212 idx = skipTrailingComment(text, idx);
12213 idx = skipNewline(text, idx);
12214 return idx !== false && hasNewline(text, idx);
12218 * @param {string} text
12220 * @param {(node: N) => number} locEnd
12221 * @returns {boolean}
12225 function isNextLineEmpty(text, node, locEnd) {
12226 return isNextLineEmptyAfterIndex(text, locEnd(node));
12229 * @param {string} text
12230 * @param {number} idx
12231 * @returns {number | false}
12235 function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) {
12236 /** @type {number | false} */
12238 /** @type {number | false} */
12242 while (nextIdx !== oldIdx) {
12244 nextIdx = skipSpaces(text, nextIdx);
12245 nextIdx = skipInlineComment(text, nextIdx);
12246 nextIdx = skipTrailingComment(text, nextIdx);
12247 nextIdx = skipNewline(text, nextIdx);
12254 * @param {string} text
12256 * @param {(node: N) => number} locEnd
12257 * @returns {number | false}
12261 function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) {
12262 return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node));
12266 * @param {string} text
12268 * @param {(node: N) => number} locEnd
12269 * @returns {string}
12273 function getNextNonSpaceNonCommentCharacter(text, node, locEnd) {
12274 return text.charAt( // @ts-ignore => TBD: can return false, should we define a fallback?
12275 getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd));
12278 * @param {string} text
12279 * @param {number} index
12280 * @param {SkipOptions=} opts
12281 * @returns {boolean}
12285 function hasSpaces(text, index, opts) {
12287 const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
12288 return idx !== index;
12291 * @param {{range?: [number, number], start?: number}} node
12292 * @param {number} index
12296 function setLocStart(node, index) {
12298 node.range[0] = index;
12300 node.start = index;
12304 * @param {{range?: [number, number], end?: number}} node
12305 * @param {number} index
12309 function setLocEnd(node, index) {
12311 node.range[1] = index;
12317 const PRECEDENCE = {};
12318 [["|>"], ["??"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach((tier, i) => {
12319 tier.forEach(op => {
12320 PRECEDENCE[op] = i;
12324 function getPrecedence(op) {
12325 return PRECEDENCE[op];
12328 const equalityOperators = {
12334 const multiplicativeOperators = {
12339 const bitshiftOperators = {
12345 function shouldFlatten(parentOp, nodeOp) {
12346 if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) {
12348 } // ** is right-associative
12349 // x ** y ** z --> x ** (y ** z)
12352 if (parentOp === "**") {
12354 } // x == y == z --> (x == y) == z
12357 if (equalityOperators[parentOp] && equalityOperators[nodeOp]) {
12359 } // x * y % z --> (x * y) % z
12362 if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) {
12364 } // x * y / z --> (x * y) / z
12365 // x / y * z --> (x / y) * z
12368 if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) {
12370 } // x << y << z --> (x << y) << z
12373 if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) {
12380 function isBitwiseOperator(operator) {
12381 return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&";
12382 } // Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr
12383 // holds) `function`, `class`, or `do {}`. Will be overzealous if there's
12384 // already necessary grouping parentheses.
12387 function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) {
12388 node = getLeftMost(node);
12390 switch (node.type) {
12391 case "FunctionExpression":
12392 case "ClassExpression":
12393 case "DoExpression":
12394 return forbidFunctionClassAndDoExpr;
12396 case "ObjectExpression":
12399 case "MemberExpression":
12400 case "OptionalMemberExpression":
12401 return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
12403 case "TaggedTemplateExpression":
12404 if (node.tag.type === "FunctionExpression") {
12405 // IIFEs are always already parenthesized
12409 return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr);
12411 case "CallExpression":
12412 case "OptionalCallExpression":
12413 if (node.callee.type === "FunctionExpression") {
12414 // IIFEs are always already parenthesized
12418 return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr);
12420 case "ConditionalExpression":
12421 return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr);
12423 case "UpdateExpression":
12424 return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr);
12426 case "BindExpression":
12427 return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
12429 case "SequenceExpression":
12430 return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr);
12432 case "TSAsExpression":
12433 return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr);
12440 function getLeftMost(node) {
12442 return getLeftMost(node.left);
12448 * @param {string} value
12449 * @param {number} tabWidth
12450 * @param {number=} startIndex
12451 * @returns {number}
12455 function getAlignmentSize(value, tabWidth, startIndex) {
12456 startIndex = startIndex || 0;
12459 for (let i = startIndex; i < value.length; ++i) {
12460 if (value[i] === "\t") {
12461 // Tabs behave in a way that they are aligned to the nearest
12462 // multiple of tabWidth:
12463 // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4
12464 // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ...
12465 size = size + tabWidth - size % tabWidth;
12474 * @param {string} value
12475 * @param {number} tabWidth
12476 * @returns {number}
12480 function getIndentSize(value, tabWidth) {
12481 const lastNewlineIndex = value.lastIndexOf("\n");
12483 if (lastNewlineIndex === -1) {
12487 return getAlignmentSize( // All the leading whitespaces
12488 value.slice(lastNewlineIndex + 1).match(/^[ \t]*/)[0], tabWidth);
12491 * @typedef {'"' | "'"} Quote
12496 * @param {string} raw
12497 * @param {Quote} preferredQuote
12502 function getPreferredQuote(raw, preferredQuote) {
12503 // `rawContent` is the string exactly like it appeared in the input source
12504 // code, without its enclosing quotes.
12505 const rawContent = raw.slice(1, -1);
12506 /** @type {{ quote: '"', regex: RegExp }} */
12512 /** @type {{ quote: "'", regex: RegExp }} */
12518 const preferred = preferredQuote === "'" ? single : double;
12519 const alternate = preferred === single ? double : single;
12520 let result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing
12521 // the string, we might want to enclose with the alternate quote instead, to
12522 // minimize the number of escaped quotes.
12524 if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) {
12525 const numPreferredQuotes = (rawContent.match(preferred.regex) || []).length;
12526 const numAlternateQuotes = (rawContent.match(alternate.regex) || []).length;
12527 result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote;
12533 function printString(raw, options, isDirectiveLiteral) {
12534 // `rawContent` is the string exactly like it appeared in the input source
12535 // code, without its enclosing quotes.
12536 const rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap
12537 // the quotes on a DirectiveLiteral.
12539 const canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'");
12540 /** @type {Quote} */
12542 const enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't
12543 // change the escape sequences they use.
12544 // See https://github.com/prettier/prettier/issues/1555
12545 // and https://tc39.github.io/ecma262/#directive-prologue
12547 if (isDirectiveLiteral) {
12548 if (canChangeDirectiveQuotes) {
12549 return enclosingQuote + rawContent + enclosingQuote;
12553 } // It might sound unnecessary to use `makeString` even if the string already
12554 // is enclosed with `enclosingQuote`, but it isn't. The string could contain
12555 // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes
12556 // sure that we consistently output the minimum amount of escaped quotes.
12559 return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.embeddedInHtml));
12562 * @param {string} rawContent
12563 * @param {Quote} enclosingQuote
12564 * @param {boolean=} unescapeUnnecessaryEscapes
12565 * @returns {string}
12569 function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) {
12570 const otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double).
12572 const regex = /\\([\s\S])|(['"])/g; // Escape and unescape single and double quotes as needed to be able to
12573 // enclose `rawContent` with `enclosingQuote`.
12575 const newContent = rawContent.replace(regex, (match, escaped, quote) => {
12576 // If we matched an escape, and the escaped character is a quote of the
12577 // other type than we intend to enclose the string with, there's no need for
12578 // it to be escaped, so return it _without_ the backslash.
12579 if (escaped === otherQuote) {
12581 } // If we matched an unescaped quote and it is of the _same_ type as we
12582 // intend to enclose the string with, it must be escaped, so return it with
12586 if (quote === enclosingQuote) {
12587 return "\\" + quote;
12592 } // Unescape any unnecessarily escaped character.
12593 // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27
12596 return unescapeUnnecessaryEscapes && /^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(escaped) ? escaped : "\\" + escaped;
12598 return enclosingQuote + newContent + enclosingQuote;
12601 function printNumber(rawNumber) {
12602 return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation.
12603 .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0).
12604 .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit.
12605 .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes.
12606 .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot.
12607 .replace(/\.(?=e|$)/, "");
12610 * @param {string} str
12611 * @param {string} target
12612 * @returns {number}
12616 function getMaxContinuousCount(str, target) {
12617 const results = str.match(new RegExp(`(${escapeStringRegexp$2(target)})+`, "g"));
12619 if (results === null) {
12623 return results.reduce((maxCount, result) => Math.max(maxCount, result.length / target.length), 0);
12626 function getMinNotPresentContinuousCount(str, target) {
12627 const matches = str.match(new RegExp(`(${escapeStringRegexp$2(target)})+`, "g"));
12629 if (matches === null) {
12633 const countPresent = new Map();
12636 for (const match of matches) {
12637 const count = match.length / target.length;
12638 countPresent.set(count, true);
12645 for (let i = 1; i < max; i++) {
12646 if (!countPresent.get(i)) {
12654 * @param {string} text
12655 * @returns {number}
12659 function getStringWidth(text) {
12662 } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width`
12665 if (!notAsciiRegex.test(text)) {
12666 return text.length;
12669 return stringWidth_1(text);
12672 function hasIgnoreComment(path) {
12673 const node = path.getValue();
12674 return hasNodeIgnoreComment(node);
12677 function hasNodeIgnoreComment(node) {
12678 return node && (node.comments && node.comments.length > 0 && node.comments.some(comment => isNodeIgnoreComment(comment) && !comment.unignore) || node.prettierIgnore);
12681 function isNodeIgnoreComment(comment) {
12682 return comment.value.trim() === "prettier-ignore";
12685 function addCommentHelper(node, comment) {
12686 const comments = node.comments || (node.comments = []);
12687 comments.push(comment);
12688 comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment
12689 // We already "print" it via the raw text, we don't need to re-print it as a
12692 if (node.type === "JSXText") {
12693 comment.printed = true;
12697 function addLeadingComment(node, comment) {
12698 comment.leading = true;
12699 comment.trailing = false;
12700 addCommentHelper(node, comment);
12703 function addDanglingComment(node, comment) {
12704 comment.leading = false;
12705 comment.trailing = false;
12706 addCommentHelper(node, comment);
12709 function addTrailingComment(node, comment) {
12710 comment.leading = false;
12711 comment.trailing = true;
12712 addCommentHelper(node, comment);
12715 function isWithinParentArrayProperty(path, propertyName) {
12716 const node = path.getValue();
12717 const parent = path.getParentNode();
12719 if (parent == null) {
12723 if (!Array.isArray(parent[propertyName])) {
12727 const key = path.getName();
12728 return parent[propertyName][key] === node;
12731 function replaceEndOfLineWith(text, replacement) {
12734 for (const part of text.split("\n")) {
12735 if (parts.length !== 0) {
12736 parts.push(replacement);
12746 replaceEndOfLineWith,
12748 getMaxContinuousCount,
12749 getMinNotPresentContinuousCount,
12755 getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
12756 getNextNonSpaceNonCommentCharacterIndex,
12757 getNextNonSpaceNonCommentCharacter,
12762 skipEverythingButNewLine,
12764 skipTrailingComment,
12766 isNextLineEmptyAfterIndex,
12768 isPreviousLineEmpty,
12774 startsWithNoLookaheadToken,
12781 hasNodeIgnoreComment,
12782 isNodeIgnoreComment,
12785 addDanglingComment,
12786 addTrailingComment,
12787 isWithinParentArrayProperty
12790 function guessEndOfLine(text) {
12791 const index = text.indexOf("\r");
12794 return text.charAt(index + 1) === "\n" ? "crlf" : "cr";
12800 function convertEndOfLineToChars(value) {
12815 convertEndOfLineToChars
12819 getStringWidth: getStringWidth$1
12822 convertEndOfLineToChars: convertEndOfLineToChars$1
12829 /** @type {Record<symbol, typeof MODE_BREAK | typeof MODE_FLAT>} */
12832 const MODE_BREAK = 1;
12833 const MODE_FLAT = 2;
12835 function rootIndent() {
12843 function makeIndent(ind, options) {
12844 return generateInd(ind, {
12849 function makeAlign(ind, n, options) {
12850 return n === -Infinity ? ind.root || rootIndent() : n < 0 ? generateInd(ind, {
12852 }, options) : !n ? ind : n.type === "root" ? Object.assign({}, ind, {
12854 }) : typeof n === "string" ? generateInd(ind, {
12855 type: "stringAlign",
12857 }, options) : generateInd(ind, {
12858 type: "numberAlign",
12863 function generateInd(ind, newPart, options) {
12864 const queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart);
12868 let lastSpaces = 0;
12870 for (const part of queue) {
12871 switch (part.type) {
12875 if (options.useTabs) {
12878 addSpaces(options.tabWidth);
12883 case "stringAlign":
12886 length += part.n.length;
12889 case "numberAlign":
12891 lastSpaces += part.n;
12894 /* istanbul ignore next */
12897 throw new Error(`Unexpected type '${part.type}'`);
12902 return Object.assign({}, ind, {
12908 function addTabs(count) {
12909 value += "\t".repeat(count);
12910 length += options.tabWidth * count;
12913 function addSpaces(count) {
12914 value += " ".repeat(count);
12919 if (options.useTabs) {
12926 function flushTabs() {
12927 if (lastTabs > 0) {
12934 function flushSpaces() {
12935 if (lastSpaces > 0) {
12936 addSpaces(lastSpaces);
12942 function resetLast() {
12948 function trim$1(out) {
12949 if (out.length === 0) {
12953 let trimCount = 0; // Trim whitespace at the end of line
12955 while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[ \t]*$/)) {
12956 trimCount += out.pop().length;
12959 if (out.length && typeof out[out.length - 1] === "string") {
12960 const trimmed = out[out.length - 1].replace(/[ \t]*$/, "");
12961 trimCount += out[out.length - 1].length - trimmed.length;
12962 out[out.length - 1] = trimmed;
12968 function fits(next, restCommands, width, options, mustBeFlat) {
12969 let restIdx = restCommands.length;
12970 const cmds = [next]; // `out` is only used for width counting because `trim` requires to look
12971 // backwards for space characters.
12975 while (width >= 0) {
12976 if (cmds.length === 0) {
12977 if (restIdx === 0) {
12981 cmds.push(restCommands[restIdx - 1]);
12986 const [ind, mode, doc] = cmds.pop();
12988 if (typeof doc === "string") {
12990 width -= getStringWidth$1(doc);
12992 switch (doc.type) {
12994 for (let i = doc.parts.length - 1; i >= 0; i--) {
12995 cmds.push([ind, mode, doc.parts[i]]);
13001 cmds.push([makeIndent(ind, options), mode, doc.contents]);
13005 cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
13009 width += trim$1(out);
13013 if (mustBeFlat && doc.break) {
13017 cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]);
13020 groupModeMap[doc.id] = cmds[cmds.length - 1][1];
13026 for (let i = doc.parts.length - 1; i >= 0; i--) {
13027 cmds.push([ind, mode, doc.parts[i]]);
13034 const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
13036 if (groupMode === MODE_BREAK) {
13037 if (doc.breakContents) {
13038 cmds.push([ind, mode, doc.breakContents]);
13042 if (groupMode === MODE_FLAT) {
13043 if (doc.flatContents) {
13044 cmds.push([ind, mode, doc.flatContents]);
13078 function printDocToString(doc, options) {
13080 const width = options.printWidth;
13081 const newLine = convertEndOfLineToChars$1(options.endOfLine);
13082 let pos = 0; // cmds is basically a stack. We've turned a recursive call into a
13083 // while loop which is much faster. The while loop below adds new
13084 // cmds to the array instead of recursively calling `print`.
13086 const cmds = [[rootIndent(), MODE_BREAK, doc]];
13088 let shouldRemeasure = false;
13089 let lineSuffix = [];
13091 while (cmds.length !== 0) {
13092 const [ind, mode, doc] = cmds.pop();
13094 if (typeof doc === "string") {
13095 const formatted = newLine !== "\n" && doc.includes("\n") ? doc.replace(/\n/g, newLine) : doc;
13096 out.push(formatted);
13097 pos += getStringWidth$1(formatted);
13099 switch (doc.type) {
13101 out.push(cursor$1.placeholder);
13105 for (let i = doc.parts.length - 1; i >= 0; i--) {
13106 cmds.push([ind, mode, doc.parts[i]]);
13112 cmds.push([makeIndent(ind, options), mode, doc.contents]);
13116 cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
13120 pos -= trim$1(out);
13126 if (!shouldRemeasure) {
13127 cmds.push([ind, doc.break ? MODE_BREAK : MODE_FLAT, doc.contents]);
13135 shouldRemeasure = false;
13136 const next = [ind, MODE_FLAT, doc.contents];
13137 const rem = width - pos;
13139 if (!doc.break && fits(next, cmds, rem, options)) {
13142 // Expanded states are a rare case where a document
13143 // can manually provide multiple representations of
13144 // itself. It provides an array of documents
13145 // going from the least expanded (most flattened)
13146 // representation first to the most expanded. If a
13147 // group has these, we need to manually go through
13148 // these states and find the first one that fits.
13149 if (doc.expandedStates) {
13150 const mostExpanded = doc.expandedStates[doc.expandedStates.length - 1];
13153 cmds.push([ind, MODE_BREAK, mostExpanded]);
13156 for (let i = 1; i < doc.expandedStates.length + 1; i++) {
13157 if (i >= doc.expandedStates.length) {
13158 cmds.push([ind, MODE_BREAK, mostExpanded]);
13161 const state = doc.expandedStates[i];
13162 const cmd = [ind, MODE_FLAT, state];
13164 if (fits(cmd, cmds, rem, options)) {
13172 cmds.push([ind, MODE_BREAK, doc.contents]);
13181 groupModeMap[doc.id] = cmds[cmds.length - 1][1];
13185 // Fills each line with as much code as possible before moving to a new
13186 // line with the same indentation.
13188 // Expects doc.parts to be an array of alternating content and
13189 // whitespace. The whitespace contains the linebreaks.
13192 // ["I", line, "love", line, "monkeys"]
13194 // [{ type: group, ... }, softline, { type: group, ... }]
13196 // It uses this parts structure to handle three main layout cases:
13197 // * The first two content items fit on the same line without
13199 // -> output the first content item and the whitespace "flat".
13200 // * Only the first content item fits on the line without breaking
13201 // -> output the first content item "flat" and the whitespace with
13203 // * Neither content item fits on the line without breaking
13204 // -> output the first content item and the whitespace with "break".
13208 const rem = width - pos;
13213 if (parts.length === 0) {
13217 const [content, whitespace] = parts;
13218 const contentFlatCmd = [ind, MODE_FLAT, content];
13219 const contentBreakCmd = [ind, MODE_BREAK, content];
13220 const contentFits = fits(contentFlatCmd, [], rem, options, true);
13222 if (parts.length === 1) {
13224 cmds.push(contentFlatCmd);
13226 cmds.push(contentBreakCmd);
13232 const whitespaceFlatCmd = [ind, MODE_FLAT, whitespace];
13233 const whitespaceBreakCmd = [ind, MODE_BREAK, whitespace];
13235 if (parts.length === 2) {
13237 cmds.push(whitespaceFlatCmd);
13238 cmds.push(contentFlatCmd);
13240 cmds.push(whitespaceBreakCmd);
13241 cmds.push(contentBreakCmd);
13245 } // At this point we've handled the first pair (context, separator)
13246 // and will create a new fill doc for the rest of the content.
13247 // Ideally we wouldn't mutate the array here but copying all the
13248 // elements to a new array would make this algorithm quadratic,
13249 // which is unusable for large arrays (e.g. large texts in JSX).
13252 parts.splice(0, 2);
13253 const remainingCmd = [ind, mode, fill$1(parts)];
13254 const secondContent = parts[0];
13255 const firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$1([content, whitespace, secondContent])];
13256 const firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], rem, options, true);
13258 if (firstAndSecondContentFits) {
13259 cmds.push(remainingCmd);
13260 cmds.push(whitespaceFlatCmd);
13261 cmds.push(contentFlatCmd);
13262 } else if (contentFits) {
13263 cmds.push(remainingCmd);
13264 cmds.push(whitespaceBreakCmd);
13265 cmds.push(contentFlatCmd);
13267 cmds.push(remainingCmd);
13268 cmds.push(whitespaceBreakCmd);
13269 cmds.push(contentBreakCmd);
13277 const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
13279 if (groupMode === MODE_BREAK) {
13280 if (doc.breakContents) {
13281 cmds.push([ind, mode, doc.breakContents]);
13285 if (groupMode === MODE_FLAT) {
13286 if (doc.flatContents) {
13287 cmds.push([ind, mode, doc.flatContents]);
13294 case "line-suffix":
13295 lineSuffix.push([ind, mode, doc.contents]);
13298 case "line-suffix-boundary":
13299 if (lineSuffix.length > 0) {
13300 cmds.push([ind, mode, {
13319 // This line was forced into the output even if we
13320 // were in flattened mode, so we need to tell the next
13321 // group that no matter what, it needs to remeasure
13322 // because the previous measurement didn't accurately
13323 // capture the entire expression (this is necessary
13324 // for nested groups)
13325 shouldRemeasure = true;
13331 if (lineSuffix.length) {
13332 cmds.push([ind, mode, doc]);
13333 cmds.push(...lineSuffix.reverse());
13340 out.push(newLine, ind.root.value);
13341 pos = ind.root.length;
13347 pos -= trim$1(out);
13348 out.push(newLine + ind.value);
13360 const cursorPlaceholderIndex = out.indexOf(cursor$1.placeholder);
13362 if (cursorPlaceholderIndex !== -1) {
13363 const otherCursorPlaceholderIndex = out.indexOf(cursor$1.placeholder, cursorPlaceholderIndex + 1);
13364 const beforeCursor = out.slice(0, cursorPlaceholderIndex).join("");
13365 const aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join("");
13366 const afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join("");
13368 formatted: beforeCursor + aroundCursor + afterCursor,
13369 cursorNodeStart: beforeCursor.length,
13370 cursorNodeText: aroundCursor
13375 formatted: out.join("")
13383 const traverseDocOnExitStackMarker = {};
13385 function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) {
13386 const docsStack = [doc];
13388 while (docsStack.length !== 0) {
13389 const doc = docsStack.pop();
13391 if (doc === traverseDocOnExitStackMarker) {
13392 onExit(docsStack.pop());
13396 let shouldRecurse = true;
13399 if (onEnter(doc) === false) {
13400 shouldRecurse = false;
13405 docsStack.push(doc);
13406 docsStack.push(traverseDocOnExitStackMarker);
13409 if (shouldRecurse) {
13410 // When there are multiple parts to process,
13411 // the parts need to be pushed onto the stack in reverse order,
13412 // so that they are processed in the original order
13413 // when the stack is popped.
13414 if (doc.type === "concat" || doc.type === "fill") {
13415 for (let ic = doc.parts.length, i = ic - 1; i >= 0; --i) {
13416 docsStack.push(doc.parts[i]);
13418 } else if (doc.type === "if-break") {
13419 if (doc.flatContents) {
13420 docsStack.push(doc.flatContents);
13423 if (doc.breakContents) {
13424 docsStack.push(doc.breakContents);
13426 } else if (doc.type === "group" && doc.expandedStates) {
13427 if (shouldTraverseConditionalGroups) {
13428 for (let ic = doc.expandedStates.length, i = ic - 1; i >= 0; --i) {
13429 docsStack.push(doc.expandedStates[i]);
13432 docsStack.push(doc.contents);
13434 } else if (doc.contents) {
13435 docsStack.push(doc.contents);
13441 function mapDoc(doc, cb) {
13442 if (doc.type === "concat" || doc.type === "fill") {
13443 const parts = doc.parts.map(part => mapDoc(part, cb));
13444 return cb(Object.assign({}, doc, {
13447 } else if (doc.type === "if-break") {
13448 const breakContents = doc.breakContents && mapDoc(doc.breakContents, cb);
13449 const flatContents = doc.flatContents && mapDoc(doc.flatContents, cb);
13450 return cb(Object.assign({}, doc, {
13454 } else if (doc.contents) {
13455 const contents = mapDoc(doc.contents, cb);
13456 return cb(Object.assign({}, doc, {
13464 function findInDoc(doc, fn, defaultValue) {
13465 let result = defaultValue;
13466 let hasStopped = false;
13468 function findInDocOnEnterFn(doc) {
13469 const maybeResult = fn(doc);
13471 if (maybeResult !== undefined) {
13473 result = maybeResult;
13481 traverseDoc(doc, findInDocOnEnterFn);
13485 function isEmpty(n) {
13486 return typeof n === "string" && n.length === 0;
13489 function isLineNextFn(doc) {
13490 if (typeof doc === "string") {
13494 if (doc.type === "line") {
13499 function isLineNext(doc) {
13500 return findInDoc(doc, isLineNextFn, false);
13503 function willBreakFn(doc) {
13504 if (doc.type === "group" && doc.break) {
13508 if (doc.type === "line" && doc.hard) {
13512 if (doc.type === "break-parent") {
13517 function willBreak(doc) {
13518 return findInDoc(doc, willBreakFn, false);
13521 function breakParentGroup(groupStack) {
13522 if (groupStack.length > 0) {
13523 const parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because
13524 // the user is expected to manually handle what breaks.
13526 if (!parentGroup.expandedStates) {
13527 parentGroup.break = true;
13534 function propagateBreaks(doc) {
13535 const alreadyVisitedSet = new Set();
13536 const groupStack = [];
13538 function propagateBreaksOnEnterFn(doc) {
13539 if (doc.type === "break-parent") {
13540 breakParentGroup(groupStack);
13543 if (doc.type === "group") {
13544 groupStack.push(doc);
13546 if (alreadyVisitedSet.has(doc)) {
13550 alreadyVisitedSet.add(doc);
13554 function propagateBreaksOnExitFn(doc) {
13555 if (doc.type === "group") {
13556 const group = groupStack.pop();
13559 breakParentGroup(groupStack);
13564 traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn,
13565 /* shouldTraverseConditionalGroups */
13569 function removeLinesFn(doc) {
13570 // Force this doc into flat mode by statically converting all
13571 // lines into spaces (or soft lines into nothing). Hard lines
13572 // should still output because there's too great of a chance
13573 // of breaking existing assumptions otherwise.
13574 if (doc.type === "line" && !doc.hard) {
13575 return doc.soft ? "" : " ";
13576 } else if (doc.type === "if-break") {
13577 return doc.flatContents || "";
13583 function removeLines(doc) {
13584 return mapDoc(doc, removeLinesFn);
13587 function stripTrailingHardline(doc) {
13588 // HACK remove ending hardline, original PR: #1984
13589 if (doc.type === "concat" && doc.parts.length !== 0) {
13590 const lastPart = doc.parts[doc.parts.length - 1];
13592 if (lastPart.type === "concat") {
13593 if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") {
13596 parts: doc.parts.slice(0, -1)
13602 parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart))
13619 stripTrailingHardline
13622 function flattenDoc(doc) {
13623 if (doc.type === "concat") {
13626 for (let i = 0; i < doc.parts.length; ++i) {
13627 const doc2 = doc.parts[i];
13629 if (typeof doc2 !== "string" && doc2.type === "concat") {
13630 res.push(...flattenDoc(doc2).parts);
13632 const flattened = flattenDoc(doc2);
13634 if (flattened !== "") {
13635 res.push(flattened);
13640 return Object.assign({}, doc, {
13643 } else if (doc.type === "if-break") {
13644 return Object.assign({}, doc, {
13645 breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null,
13646 flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null
13648 } else if (doc.type === "group") {
13649 return Object.assign({}, doc, {
13650 contents: flattenDoc(doc.contents),
13651 expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates
13653 } else if (doc.contents) {
13654 return Object.assign({}, doc, {
13655 contents: flattenDoc(doc.contents)
13662 function printDoc(doc) {
13663 if (typeof doc === "string") {
13664 return JSON.stringify(doc);
13667 if (doc.type === "line") {
13669 return "literalline";
13683 if (doc.type === "break-parent") {
13684 return "breakParent";
13687 if (doc.type === "trim") {
13691 if (doc.type === "concat") {
13692 return "[" + doc.parts.map(printDoc).join(", ") + "]";
13695 if (doc.type === "indent") {
13696 return "indent(" + printDoc(doc.contents) + ")";
13699 if (doc.type === "align") {
13700 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) + ")";
13703 if (doc.type === "if-break") {
13704 return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")";
13707 if (doc.type === "group") {
13708 if (doc.expandedStates) {
13709 return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])";
13712 return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")";
13715 if (doc.type === "fill") {
13716 return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")";
13719 if (doc.type === "line-suffix") {
13720 return "lineSuffix(" + printDoc(doc.contents) + ")";
13723 if (doc.type === "line-suffix-boundary") {
13724 return "lineSuffixBoundary";
13727 throw new Error("Unknown doc type " + doc.type);
13731 printDocToDebug(doc) {
13732 return printDoc(flattenDoc(doc));
13738 builders: docBuilders,
13739 printer: docPrinter,
13745 getMaxContinuousCount: getMaxContinuousCount$1,
13746 getStringWidth: getStringWidth$2,
13747 getAlignmentSize: getAlignmentSize$1,
13748 getIndentSize: getIndentSize$1,
13750 skipWhitespace: skipWhitespace$1,
13751 skipSpaces: skipSpaces$1,
13752 skipNewline: skipNewline$1,
13753 skipToLineEnd: skipToLineEnd$1,
13754 skipEverythingButNewLine: skipEverythingButNewLine$1,
13755 skipInlineComment: skipInlineComment$1,
13756 skipTrailingComment: skipTrailingComment$1,
13757 hasNewline: hasNewline$1,
13758 hasNewlineInRange: hasNewlineInRange$1,
13759 hasSpaces: hasSpaces$1,
13760 isNextLineEmpty: isNextLineEmpty$1,
13761 isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1,
13762 isPreviousLineEmpty: isPreviousLineEmpty$1,
13763 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1,
13764 makeString: makeString$1,
13765 addLeadingComment: addLeadingComment$1,
13766 addDanglingComment: addDanglingComment$1,
13767 addTrailingComment: addTrailingComment$1
13770 getMaxContinuousCount: getMaxContinuousCount$1,
13771 getStringWidth: getStringWidth$2,
13772 getAlignmentSize: getAlignmentSize$1,
13773 getIndentSize: getIndentSize$1,
13775 skipWhitespace: skipWhitespace$1,
13776 skipSpaces: skipSpaces$1,
13777 skipNewline: skipNewline$1,
13778 skipToLineEnd: skipToLineEnd$1,
13779 skipEverythingButNewLine: skipEverythingButNewLine$1,
13780 skipInlineComment: skipInlineComment$1,
13781 skipTrailingComment: skipTrailingComment$1,
13782 hasNewline: hasNewline$1,
13783 hasNewlineInRange: hasNewlineInRange$1,
13784 hasSpaces: hasSpaces$1,
13785 isNextLineEmpty: isNextLineEmpty$1,
13786 isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1,
13787 isPreviousLineEmpty: isPreviousLineEmpty$1,
13788 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1,
13789 makeString: makeString$1,
13790 addLeadingComment: addLeadingComment$1,
13791 addDanglingComment: addDanglingComment$1,
13792 addTrailingComment: addTrailingComment$1
13798 hardline: hardline$1,
13799 breakParent: breakParent$1,
13801 lineSuffix: lineSuffix$1,
13804 } = document.builders;
13806 hasNewline: hasNewline$2,
13807 skipNewline: skipNewline$2,
13808 isPreviousLineEmpty: isPreviousLineEmpty$2
13811 addLeadingComment: addLeadingComment$2,
13812 addDanglingComment: addDanglingComment$2,
13813 addTrailingComment: addTrailingComment$2
13815 const childNodesCacheKey = Symbol("child-nodes");
13817 function getSortedChildNodes(node, options, resultArray) {
13829 if (printer.canAttachComment && printer.canAttachComment(node)) {
13830 // This reverse insertion sort almost always takes constant
13831 // time because we almost always (maybe always?) append the
13832 // nodes in order anyway.
13835 for (i = resultArray.length - 1; i >= 0; --i) {
13836 if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) {
13841 resultArray.splice(i + 1, 0, node);
13844 } else if (node[childNodesCacheKey]) {
13845 return node[childNodesCacheKey];
13848 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]);
13854 if (!resultArray) {
13855 Object.defineProperty(node, childNodesCacheKey, {
13856 value: resultArray = [],
13861 childNodes.forEach(childNode => {
13862 getSortedChildNodes(childNode, options, resultArray);
13864 return resultArray;
13865 } // As efficiently as possible, decorate the comment object with
13866 // .precedingNode, .enclosingNode, and/or .followingNode properties, at
13867 // least one of which is guaranteed to be defined.
13870 function decorateComment(node, comment, options) {
13875 const childNodes = getSortedChildNodes(node, options);
13877 let followingNode; // Time to dust off the old binary search robes and wizard hat.
13880 let right = childNodes.length;
13882 while (left < right) {
13883 const middle = left + right >> 1;
13884 const child = childNodes[middle];
13886 if (locStart(child) - locStart(comment) <= 0 && locEnd(comment) - locEnd(child) <= 0) {
13887 // The comment is completely contained by this child node.
13888 comment.enclosingNode = child;
13889 decorateComment(child, comment, options);
13890 return; // Abandon the binary search at this level.
13893 if (locEnd(child) - locStart(comment) <= 0) {
13894 // This child node falls completely before the comment.
13895 // Because we will never consider this node or any nodes
13896 // before it again, this node must be the closest preceding
13897 // node we have encountered so far.
13898 precedingNode = child;
13903 if (locEnd(comment) - locStart(child) <= 0) {
13904 // This child node falls completely after the comment.
13905 // Because we will never consider this node or any nodes after
13906 // it again, this node must be the closest following node we
13907 // have encountered so far.
13908 followingNode = child;
13912 /* istanbul ignore next */
13915 throw new Error("Comment location overlaps with node location");
13916 } // We don't want comments inside of different expressions inside of the same
13917 // template literal to move to another expression.
13920 if (comment.enclosingNode && comment.enclosingNode.type === "TemplateLiteral") {
13923 } = comment.enclosingNode;
13924 const commentIndex = findExpressionIndexForComment(quasis, comment, options);
13926 if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) {
13927 precedingNode = null;
13930 if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) {
13931 followingNode = null;
13935 if (precedingNode) {
13936 comment.precedingNode = precedingNode;
13939 if (followingNode) {
13940 comment.followingNode = followingNode;
13944 function attach(comments, ast, text, options) {
13945 if (!Array.isArray(comments)) {
13949 const tiesToBreak = [];
13954 comments.forEach((comment, i) => {
13955 if (options.parser === "json" || options.parser === "json5" || options.parser === "__js_expression" || options.parser === "__vue_expression") {
13956 if (locStart(comment) - locStart(ast) <= 0) {
13957 addLeadingComment$2(ast, comment);
13961 if (locEnd(comment) - locEnd(ast) >= 0) {
13962 addTrailingComment$2(ast, comment);
13967 decorateComment(ast, comment, options);
13973 const pluginHandleOwnLineComment = options.printer.handleComments && options.printer.handleComments.ownLine ? options.printer.handleComments.ownLine : () => false;
13974 const pluginHandleEndOfLineComment = options.printer.handleComments && options.printer.handleComments.endOfLine ? options.printer.handleComments.endOfLine : () => false;
13975 const pluginHandleRemainingComment = options.printer.handleComments && options.printer.handleComments.remaining ? options.printer.handleComments.remaining : () => false;
13976 const isLastComment = comments.length - 1 === i;
13978 if (hasNewline$2(text, locStart(comment), {
13981 // If a comment exists on its own line, prefer a leading comment.
13982 // We also need to check if it's the first line of the file.
13983 if (pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)) ; else if (followingNode) {
13984 // Always a leading comment.
13985 addLeadingComment$2(followingNode, comment);
13986 } else if (precedingNode) {
13987 addTrailingComment$2(precedingNode, comment);
13988 } else if (enclosingNode) {
13989 addDanglingComment$2(enclosingNode, comment);
13991 // There are no nodes, let's attach it to the root of the ast
13993 /* istanbul ignore next */
13994 addDanglingComment$2(ast, comment);
13996 } else if (hasNewline$2(text, locEnd(comment))) {
13997 if (pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode) {
13998 // There is content before this comment on the same line, but
13999 // none after it, so prefer a trailing comment of the previous node.
14000 addTrailingComment$2(precedingNode, comment);
14001 } else if (followingNode) {
14002 addLeadingComment$2(followingNode, comment);
14003 } else if (enclosingNode) {
14004 addDanglingComment$2(enclosingNode, comment);
14006 // There are no nodes, let's attach it to the root of the ast
14008 /* istanbul ignore next */
14009 addDanglingComment$2(ast, comment);
14012 if (pluginHandleRemainingComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode && followingNode) {
14013 // Otherwise, text exists both before and after the comment on
14014 // the same line. If there is both a preceding and following
14015 // node, use a tie-breaking algorithm to determine if it should
14016 // be attached to the next or previous node. In the last case,
14017 // simply attach the right node;
14018 const tieCount = tiesToBreak.length;
14020 if (tieCount > 0) {
14021 const lastTie = tiesToBreak[tieCount - 1];
14023 if (lastTie.followingNode !== comment.followingNode) {
14024 breakTies(tiesToBreak, text, options);
14028 tiesToBreak.push(comment);
14029 } else if (precedingNode) {
14030 addTrailingComment$2(precedingNode, comment);
14031 } else if (followingNode) {
14032 addLeadingComment$2(followingNode, comment);
14033 } else if (enclosingNode) {
14034 addDanglingComment$2(enclosingNode, comment);
14036 // There are no nodes, let's attach it to the root of the ast
14038 /* istanbul ignore next */
14039 addDanglingComment$2(ast, comment);
14043 breakTies(tiesToBreak, text, options);
14044 comments.forEach(comment => {
14045 // These node references were useful for breaking ties, but we
14046 // don't need them anymore, and they create cycles in the AST that
14047 // may lead to infinite recursion if we don't delete them here.
14048 delete comment.precedingNode;
14049 delete comment.enclosingNode;
14050 delete comment.followingNode;
14054 function breakTies(tiesToBreak, text, options) {
14055 const tieCount = tiesToBreak.length;
14057 if (tieCount === 0) {
14065 } = tiesToBreak[0];
14066 const gapRegExp = options.printer.getGapRegex && options.printer.getGapRegex(enclosingNode) || /^[\s(]*$/;
14067 let gapEndPos = options.locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps
14068 // between the tied comments. In order to qualify as leading, a
14069 // comment must be separated from followingNode by an unbroken series of
14070 // gaps (or other comments). Gaps should only contain whitespace or open
14073 let indexOfFirstLeadingComment;
14075 for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) {
14076 const comment = tiesToBreak[indexOfFirstLeadingComment - 1];
14077 assert$1.strictEqual(comment.precedingNode, precedingNode);
14078 assert$1.strictEqual(comment.followingNode, followingNode);
14079 const gap = text.slice(options.locEnd(comment), gapEndPos);
14081 if (gapRegExp.test(gap)) {
14082 gapEndPos = options.locStart(comment);
14084 // The gap string contained something other than whitespace or open
14090 tiesToBreak.forEach((comment, i) => {
14091 if (i < indexOfFirstLeadingComment) {
14092 addTrailingComment$2(precedingNode, comment);
14094 addLeadingComment$2(followingNode, comment);
14097 tiesToBreak.length = 0;
14100 function printComment(commentPath, options) {
14101 const comment = commentPath.getValue();
14102 comment.printed = true;
14103 return options.printer.printComment(commentPath, options);
14106 function findExpressionIndexForComment(quasis, comment, options) {
14107 const startPos = options.locStart(comment) - 1;
14109 for (let i = 1; i < quasis.length; ++i) {
14110 if (startPos < getQuasiRange(quasis[i]).start) {
14113 } // We haven't found it, it probably means that some of the locations are off.
14114 // Let's just return the first one.
14116 /* istanbul ignore next */
14122 function getQuasiRange(expr) {
14123 if (expr.start !== undefined) {
14133 start: expr.range[0],
14138 function printLeadingComment(commentPath, print, options) {
14139 const comment = commentPath.getValue();
14140 const contents = printComment(commentPath, options);
14146 const isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // Leading block comments should see if they need to stay on the
14147 // same line or not.
14150 const lineBreak = hasNewline$2(options.originalText, options.locEnd(comment)) ? hasNewline$2(options.originalText, options.locStart(comment), {
14152 }) ? hardline$1 : line$1 : " ";
14153 return concat$2([contents, lineBreak]);
14156 return concat$2([contents, hardline$1]);
14159 function printTrailingComment(commentPath, print, options) {
14160 const comment = commentPath.getValue();
14161 const contents = printComment(commentPath, options);
14167 const isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // We don't want the line to break
14168 // when the parentParentNode is a ClassDeclaration/-Expression
14169 // And the parentNode is in the superClass property
14171 const parentNode = commentPath.getNode(1);
14172 const parentParentNode = commentPath.getNode(2);
14173 const isParentSuperClass = parentParentNode && (parentParentNode.type === "ClassDeclaration" || parentParentNode.type === "ClassExpression") && parentParentNode.superClass === parentNode;
14175 if (hasNewline$2(options.originalText, options.locStart(comment), {
14178 // This allows comments at the end of nested structures:
14184 // Those kinds of comments are almost always leading comments, but
14185 // here it doesn't go "outside" the block and turns it into a
14186 // trailing comment for `2`. We can simulate the above by checking
14187 // if this a comment on its own line; normal trailing comments are
14188 // always at the end of another expression.
14189 const isLineBeforeEmpty = isPreviousLineEmpty$2(options.originalText, comment, options.locStart);
14190 return lineSuffix$1(concat$2([hardline$1, isLineBeforeEmpty ? hardline$1 : "", contents]));
14191 } else if (isBlock || isParentSuperClass) {
14192 // Trailing block comments never need a newline
14193 return concat$2([" ", contents]);
14196 return concat$2([lineSuffix$1(concat$2([" ", contents])), !isBlock ? breakParent$1 : ""]);
14199 function printDanglingComments(path, options, sameIndent, filter) {
14201 const node = path.getValue();
14203 if (!node || !node.comments) {
14207 path.each(commentPath => {
14208 const comment = commentPath.getValue();
14210 if (comment && !comment.leading && !comment.trailing && (!filter || filter(comment))) {
14211 parts.push(printComment(commentPath, options));
14215 if (parts.length === 0) {
14220 return join$1(hardline$1, parts);
14223 return indent$1(concat$2([hardline$1, join$1(hardline$1, parts)]));
14226 function prependCursorPlaceholder(path, options, printed) {
14227 if (path.getNode() === options.cursorNode && path.getValue()) {
14228 return concat$2([cursor$2, printed, cursor$2]);
14234 function printComments(path, print, options, needsSemi) {
14235 const value = path.getValue();
14236 const printed = print(path);
14237 const comments = value && value.comments;
14239 if (!comments || comments.length === 0) {
14240 return prependCursorPlaceholder(path, options, printed);
14243 const leadingParts = [];
14244 const trailingParts = [needsSemi ? ";" : "", printed];
14245 path.each(commentPath => {
14246 const comment = commentPath.getValue();
14253 const contents = printLeadingComment(commentPath, print, options);
14259 leadingParts.push(contents);
14260 const text = options.originalText;
14261 const index = skipNewline$2(text, options.locEnd(comment));
14263 if (index !== false && hasNewline$2(text, index)) {
14264 leadingParts.push(hardline$1);
14266 } else if (trailing) {
14267 trailingParts.push(printTrailingComment(commentPath, print, options));
14270 return prependCursorPlaceholder(path, options, concat$2(leadingParts.concat(trailingParts)));
14276 printDanglingComments,
14277 getSortedChildNodes
14280 function getNodeHelper(path, count) {
14281 const stackIndex = getNodeStackIndexHelper(path.stack, count);
14282 return stackIndex === -1 ? null : path.stack[stackIndex];
14285 function getNodeStackIndexHelper(stack, count) {
14286 for (let i = stack.length - 1; i >= 0; i -= 2) {
14287 const value = stack[i];
14289 if (value && !Array.isArray(value) && --count < 0) {
14298 constructor(value) {
14299 this.stack = [value];
14300 } // The name of the current property is always the penultimate element of
14301 // this.stack, and always a String.
14313 return stack[length - 2];
14314 } // Since the name is always a string, null is a safe sentinel value to
14315 // return if we do not know the name of the (root) value.
14317 /* istanbul ignore next */
14321 } // The value of the current property is always the final element of
14326 return getLast(this.stack);
14329 getNode(count = 0) {
14330 return getNodeHelper(this, count);
14333 getParentNode(count = 0) {
14334 return getNodeHelper(this, count + 1);
14335 } // Temporarily push properties named by string arguments given after the
14336 // callback function onto this.stack, then call the callback with a
14337 // reference to this (modified) FastPath object. Note that the stack will
14338 // be restored to its original state after the callback is finished, so it
14339 // is probably a mistake to retain a reference to the path.
14342 call(callback, ...names) {
14349 let value = getLast(stack);
14351 for (const name of names) {
14352 value = value[name];
14353 stack.push(name, value);
14356 const result = callback(this);
14357 stack.length = length;
14361 callParent(callback, count = 0) {
14362 const stackIndex = getNodeStackIndexHelper(this.stack, count + 1);
14363 const parentValues = this.stack.splice(stackIndex + 1);
14364 const result = callback(this);
14365 this.stack.push(...parentValues);
14367 } // Similar to FastPath.prototype.call, except that the value obtained by
14368 // accessing this.getValue()[name1][name2]... should be array-like. The
14369 // callback will be called with a reference to this path object for each
14370 // element of the array.
14373 each(callback, ...names) {
14380 let value = getLast(stack);
14382 for (const name of names) {
14383 value = value[name];
14384 stack.push(name, value);
14387 for (let i = 0; i < value.length; ++i) {
14389 stack.push(i, value[i]); // If the callback needs to know the value of i, call
14390 // path.getName(), assuming path is the parameter name.
14397 stack.length = length;
14398 } // Similar to FastPath.prototype.each, except that the results of the
14399 // callback function invocations are stored in an array and returned at
14400 // the end of the iteration.
14403 map(callback, ...names) {
14410 let value = getLast(stack);
14412 for (const name of names) {
14413 value = value[name];
14414 stack.push(name, value);
14417 const result = new Array(value.length);
14419 for (let i = 0; i < value.length; ++i) {
14421 stack.push(i, value[i]);
14422 result[i] = callback(this, i);
14427 stack.length = length;
14432 * | ((node: any, name: string | null, number: number | null) => boolean)
14438 match(...predicates) {
14439 let stackPointer = this.stack.length - 1;
14441 let node = this.stack[stackPointer--];
14443 for (const predicate of predicates) {
14444 if (node === undefined) {
14446 } // skip index/array
14451 if (typeof name === "number") {
14453 name = this.stack[stackPointer--];
14454 node = this.stack[stackPointer--];
14457 if (predicate && !predicate(node, name, number)) {
14461 name = this.stack[stackPointer--];
14462 node = this.stack[stackPointer--];
14470 var fastPath = FastPath;
14473 normalize: normalize$2
14476 function printSubtree(path, print, options, printAstToDoc) {
14477 if (options.printer.embed) {
14478 return options.printer.embed(path, print, (text, partialNextOptions) => textToDoc(text, partialNextOptions, options, printAstToDoc), options);
14482 function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc) {
14483 const nextOptions = normalize$2(Object.assign({}, parentOptions, {}, partialNextOptions, {
14484 parentParser: parentOptions.parser,
14485 embeddedInHtml: !!(parentOptions.embeddedInHtml || parentOptions.parser === "html" || parentOptions.parser === "vue" || parentOptions.parser === "angular" || parentOptions.parser === "lwc"),
14490 const result = parser.parse(text, nextOptions);
14494 text = result.text;
14495 const astComments = ast.comments;
14496 delete ast.comments;
14497 comments.attach(astComments, ast, text, nextOptions);
14498 return printAstToDoc(ast, nextOptions);
14501 var multiparser = {
14505 const doc = document;
14506 const docBuilders$1 = doc.builders;
14509 hardline: hardline$2,
14510 addAlignmentToDoc: addAlignmentToDoc$1
14512 const docUtils$1 = doc.utils;
14514 * Takes an abstract syntax tree (AST) and recursively converts it to a
14515 * document (series of printing primitives).
14517 * This is done by descending down the AST recursively. The recursion
14518 * involves two functions that call each other:
14520 * 1. printGenerically(), which is defined as an inner function here.
14521 * It basically takes care of node caching.
14522 * 2. callPluginPrintFunction(), which checks for some options, and
14523 * ultimately calls the print() function provided by the plugin.
14525 * The plugin function will call printGenerically() again for child nodes
14526 * of the current node, which will do its housekeeping, then call the
14527 * plugin function again, and so on.
14529 * All the while, these functions pass a "path" variable around, which
14530 * is a stack-like data structure (FastPath) that maintains the current
14531 * state of the recursion. It is called "path", because it represents
14532 * the path to the current node through the Abstract Syntax Tree.
14535 function printAstToDoc(ast, options, alignmentSize = 0) {
14540 if (printer.preprocess) {
14541 ast = printer.preprocess(ast, options);
14544 const cache = new Map();
14546 function printGenerically(path, args) {
14547 const node = path.getValue();
14548 const shouldCache = node && typeof node === "object" && args === undefined;
14550 if (shouldCache && cache.has(node)) {
14551 return cache.get(node);
14552 } // We let JSXElement print its comments itself because it adds () around
14553 // UnionTypeAnnotation has to align the child without the comments
14558 if (printer.willPrintOwnComments && printer.willPrintOwnComments(path, options)) {
14559 res = callPluginPrintFunction(path, options, printGenerically, args);
14561 // printComments will call the plugin print function and check for
14562 // comments to print
14563 res = comments.printComments(path, p => callPluginPrintFunction(p, options, printGenerically, args), options, args && args.needsSemi);
14567 cache.set(node, res);
14573 let doc = printGenerically(new fastPath(ast));
14575 if (alignmentSize > 0) {
14576 // Add a hardline to make the indents take effect
14577 // It should be removed in index.js format()
14578 doc = addAlignmentToDoc$1(concat$3([hardline$2, doc]), alignmentSize, options.tabWidth);
14581 docUtils$1.propagateBreaks(doc);
14585 function callPluginPrintFunction(path, options, printPath, args) {
14586 assert$1.ok(path instanceof fastPath);
14587 const node = path.getValue();
14590 } = options; // Escape hatch
14592 if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path)) {
14593 return options.originalText.slice(options.locStart(node), options.locEnd(node));
14598 // Potentially switch to a different parser
14599 const sub = multiparser.printSubtree(path, printPath, options, printAstToDoc);
14605 /* istanbul ignore if */
14606 if (process.env.PRETTIER_DEBUG) {
14608 } // Continue with current parser
14613 return printer.print(path, options, printPath, args);
14616 var astToDoc = printAstToDoc;
14618 function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) {
14619 let resultStartNode = startNodeAndParents.node;
14620 let resultEndNode = endNodeAndParents.node;
14622 if (resultStartNode === resultEndNode) {
14624 startNode: resultStartNode,
14625 endNode: resultEndNode
14629 for (const endParent of endNodeAndParents.parentNodes) {
14630 if (endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node)) {
14631 resultEndNode = endParent;
14637 for (const startParent of startNodeAndParents.parentNodes) {
14638 if (startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node)) {
14639 resultStartNode = startParent;
14646 startNode: resultStartNode,
14647 endNode: resultEndNode
14651 function findNodeAtOffset(node, offset, options, predicate, parentNodes) {
14652 predicate = predicate || (() => true);
14654 parentNodes = parentNodes || [];
14655 const start = options.locStart(node, options.locStart);
14656 const end = options.locEnd(node, options.locEnd);
14658 if (start <= offset && offset <= end) {
14659 for (const childNode of comments.getSortedChildNodes(node, options)) {
14660 const childResult = findNodeAtOffset(childNode, offset, options, predicate, [node].concat(parentNodes));
14663 return childResult;
14667 if (predicate(node)) {
14674 } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5
14677 function isSourceElement(opts, node) {
14678 if (node == null) {
14680 } // JS and JS like to avoid repetitions
14683 const jsSourceElements = ["FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015
14684 "ImportDeclaration", // Module
14685 "ExportDefaultDeclaration", // Module
14686 "ExportNamedDeclaration", // Module
14687 "ExportAllDeclaration", // Module
14688 "TypeAlias", // Flow
14689 "InterfaceDeclaration", // Flow, TypeScript
14690 "TypeAliasDeclaration", // TypeScript
14691 "ExportAssignment", // TypeScript
14692 "ExportDeclaration" // TypeScript
14694 const jsonSourceElements = ["ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"];
14695 const graphqlSourceElements = ["OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition"];
14697 switch (opts.parser) {
14703 return jsSourceElements.includes(node.type);
14706 return jsonSourceElements.includes(node.type);
14709 return graphqlSourceElements.includes(node.kind);
14712 return node.tag !== "root";
14718 function calculateRange(text, opts, ast) {
14719 // Contract the range so that it has non-whitespace characters at its endpoints.
14720 // This ensures we can format a range that doesn't end on a node.
14721 const rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd);
14722 const startNonWhitespace = Math.max(opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart);
14723 let endNonWhitespace;
14725 for (endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace) {
14726 if (text[endNonWhitespace - 1].match(/\S/)) {
14731 const startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace, opts, node => isSourceElement(opts, node));
14732 const endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace, opts, node => isSourceElement(opts, node));
14734 if (!startNodeAndParents || !endNodeAndParents) {
14741 const siblingAncestors = findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts);
14745 } = siblingAncestors;
14746 const rangeStart = Math.min(opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart));
14747 const rangeEnd = Math.max(opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd));
14759 var require$$0 = getCjsExportFromNamespace(index_es6);
14761 const normalizeOptions$1 = options$1.normalize;
14763 guessEndOfLine: guessEndOfLine$1,
14764 convertEndOfLineToChars: convertEndOfLineToChars$2
14768 printDocToString: printDocToString$1
14774 const BOM = "\uFEFF";
14775 const CURSOR = Symbol("cursor");
14776 const PLACEHOLDERS = {
14777 cursorOffset: "<<<PRETTIER_CURSOR>>>",
14778 rangeStart: "<<<PRETTIER_RANGE_START>>>",
14779 rangeEnd: "<<<PRETTIER_RANGE_END>>>"
14782 function ensureAllCommentsPrinted(astComments) {
14783 if (!astComments) {
14787 for (let i = 0; i < astComments.length; ++i) {
14788 if (util$1.isNodeIgnoreComment(astComments[i])) {
14789 // If there's a prettier-ignore, we're not printing that sub-tree so we
14790 // don't know if the comments was printed or not.
14795 astComments.forEach(comment => {
14796 if (!comment.printed) {
14797 throw new Error('Comment "' + comment.value.trim() + '" was not printed. Please report this error!');
14800 delete comment.printed;
14804 function attachComments(text, ast, opts) {
14805 const astComments = ast.comments;
14808 delete ast.comments;
14809 comments.attach(astComments, ast, text, opts);
14813 opts.originalText = opts.parser === "yaml" ? text : text.trimEnd();
14814 return astComments;
14817 function coreFormat(text, opts, addAlignmentSize) {
14818 if (!text || !text.trim().length) {
14825 addAlignmentSize = addAlignmentSize || 0;
14826 const parsed = parser.parse(text, opts);
14830 text = parsed.text;
14832 if (opts.cursorOffset >= 0) {
14833 const nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts);
14835 if (nodeResult && nodeResult.node) {
14836 opts.cursorNode = nodeResult.node;
14840 const astComments = attachComments(text, ast, opts);
14841 const doc = astToDoc(ast, opts, addAlignmentSize);
14842 const result = printDocToString$1(doc, opts);
14843 ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline
14845 if (addAlignmentSize > 0) {
14846 const trimmed = result.formatted.trim();
14848 if (result.cursorNodeStart !== undefined) {
14849 result.cursorNodeStart -= result.formatted.indexOf(trimmed);
14852 result.formatted = trimmed + convertEndOfLineToChars$2(opts.endOfLine);
14855 if (opts.cursorOffset >= 0) {
14856 let oldCursorNodeStart;
14857 let oldCursorNodeText;
14858 let cursorOffsetRelativeToOldCursorNode;
14859 let newCursorNodeStart;
14860 let newCursorNodeText;
14862 if (opts.cursorNode && result.cursorNodeText) {
14863 oldCursorNodeStart = opts.locStart(opts.cursorNode);
14864 oldCursorNodeText = text.slice(oldCursorNodeStart, opts.locEnd(opts.cursorNode));
14865 cursorOffsetRelativeToOldCursorNode = opts.cursorOffset - oldCursorNodeStart;
14866 newCursorNodeStart = result.cursorNodeStart;
14867 newCursorNodeText = result.cursorNodeText;
14869 oldCursorNodeStart = 0;
14870 oldCursorNodeText = text;
14871 cursorOffsetRelativeToOldCursorNode = opts.cursorOffset;
14872 newCursorNodeStart = 0;
14873 newCursorNodeText = result.formatted;
14876 if (oldCursorNodeText === newCursorNodeText) {
14878 formatted: result.formatted,
14879 cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode
14881 } // diff old and new cursor node texts, with a special cursor
14882 // symbol inserted to find out where it moves to
14885 const oldCursorNodeCharArray = oldCursorNodeText.split("");
14886 oldCursorNodeCharArray.splice(cursorOffsetRelativeToOldCursorNode, 0, CURSOR);
14887 const newCursorNodeCharArray = newCursorNodeText.split("");
14888 const cursorNodeDiff = require$$0.diffArrays(oldCursorNodeCharArray, newCursorNodeCharArray);
14889 let cursorOffset = newCursorNodeStart;
14891 for (const entry of cursorNodeDiff) {
14892 if (entry.removed) {
14893 if (entry.value.includes(CURSOR)) {
14897 cursorOffset += entry.count;
14902 formatted: result.formatted,
14908 formatted: result.formatted
14912 function formatRange(text, opts) {
14913 const parsed = parser.parse(text, opts);
14917 text = parsed.text;
14918 const range = rangeUtil.calculateRange(text, opts, ast);
14923 const rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line.
14924 // This is so we can detect indentation correctly and restore it.
14925 // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0
14927 const rangeStart2 = Math.min(rangeStart, text.lastIndexOf("\n", rangeStart) + 1);
14928 const indentString = text.slice(rangeStart2, rangeStart);
14929 const alignmentSize = util$1.getAlignmentSize(indentString, opts.tabWidth);
14930 const rangeResult = coreFormat(rangeString, Object.assign({}, opts, {
14932 rangeEnd: Infinity,
14933 // track the cursor offset only if it's within our range
14934 cursorOffset: opts.cursorOffset >= rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart : -1
14935 }), alignmentSize); // Since the range contracts to avoid trailing whitespace,
14936 // we need to remove the newline that was inserted by the `format` call.
14938 const rangeTrimmed = rangeResult.formatted.trimEnd();
14939 const rangeLeft = text.slice(0, rangeStart);
14940 const rangeRight = text.slice(rangeEnd);
14945 if (opts.cursorOffset >= rangeEnd) {
14946 // handle the case where the cursor was past the end of the range
14947 cursorOffset = opts.cursorOffset - rangeEnd + (rangeStart + rangeTrimmed.length);
14948 } else if (rangeResult.cursorOffset !== undefined) {
14949 // handle the case where the cursor was in the range
14950 cursorOffset = rangeResult.cursorOffset + rangeStart;
14951 } // keep the cursor as it was if it was before the start of the range
14956 if (opts.endOfLine === "lf") {
14957 formatted = rangeLeft + rangeTrimmed + rangeRight;
14959 const eol = convertEndOfLineToChars$2(opts.endOfLine);
14961 if (cursorOffset >= 0) {
14962 const parts = [rangeLeft, rangeTrimmed, rangeRight];
14964 let partOffset = cursorOffset;
14966 while (partIndex < parts.length) {
14967 const part = parts[partIndex];
14969 if (partOffset < part.length) {
14970 parts[partIndex] = parts[partIndex].slice(0, partOffset) + PLACEHOLDERS.cursorOffset + parts[partIndex].slice(partOffset);
14975 partOffset -= part.length;
14978 const [newRangeLeft, newRangeTrimmed, newRangeRight] = parts;
14979 formatted = (newRangeLeft.replace(/\n/g, eol) + newRangeTrimmed + newRangeRight.replace(/\n/g, eol)).replace(PLACEHOLDERS.cursorOffset, (_, index) => {
14980 cursorOffset = index;
14984 formatted = rangeLeft.replace(/\n/g, eol) + rangeTrimmed + rangeRight.replace(/\n/g, eol);
14994 function format(text, opts) {
14995 const selectedParser = parser.resolveParser(opts);
14996 const hasPragma = !selectedParser.hasPragma || selectedParser.hasPragma(text);
14998 if (opts.requirePragma && !hasPragma) {
15004 if (opts.endOfLine === "auto") {
15005 opts.endOfLine = guessEndOfLine$1(text);
15008 const hasCursor = opts.cursorOffset >= 0;
15009 const hasRangeStart = opts.rangeStart > 0;
15010 const hasRangeEnd = opts.rangeEnd < text.length; // get rid of CR/CRLF parsing
15012 if (text.includes("\r")) {
15013 const offsetKeys = [hasCursor && "cursorOffset", hasRangeStart && "rangeStart", hasRangeEnd && "rangeEnd"].filter(Boolean).sort((aKey, bKey) => opts[aKey] - opts[bKey]);
15015 for (let i = offsetKeys.length - 1; i >= 0; i--) {
15016 const key = offsetKeys[i];
15017 text = text.slice(0, opts[key]) + PLACEHOLDERS[key] + text.slice(opts[key]);
15020 text = text.replace(/\r\n?/g, "\n");
15022 for (let i = 0; i < offsetKeys.length; i++) {
15023 const key = offsetKeys[i];
15024 text = text.replace(PLACEHOLDERS[key], (_, index) => {
15031 const hasUnicodeBOM = text.charAt(0) === BOM;
15033 if (hasUnicodeBOM) {
15034 text = text.slice(1);
15037 opts.cursorOffset++;
15040 if (hasRangeStart) {
15050 opts.cursorOffset = -1;
15053 if (opts.rangeStart < 0) {
15054 opts.rangeStart = 0;
15057 if (opts.rangeEnd > text.length) {
15058 opts.rangeEnd = text.length;
15061 const result = hasRangeStart || hasRangeEnd ? formatRange(text, opts) : coreFormat(opts.insertPragma && opts.printer.insertPragma && !hasPragma ? opts.printer.insertPragma(text) : text, opts);
15063 if (hasUnicodeBOM) {
15064 result.formatted = BOM + result.formatted;
15067 result.cursorOffset++;
15075 formatWithCursor(text, opts) {
15076 opts = normalizeOptions$1(opts);
15077 return format(text, opts);
15080 parse(text, opts, massage) {
15081 opts = normalizeOptions$1(opts);
15083 if (text.includes("\r")) {
15084 text = text.replace(/\r\n?/g, "\n");
15087 const parsed = parser.parse(text, opts);
15090 parsed.ast = massageAst(parsed.ast, opts);
15096 formatAST(ast, opts) {
15097 opts = normalizeOptions$1(opts);
15098 const doc = astToDoc(ast, opts);
15099 return printDocToString$1(doc, opts);
15102 // Doesn't handle shebang for now
15103 formatDoc(doc, opts) {
15104 const debug = printDocToDebug(doc);
15105 opts = normalizeOptions$1(Object.assign({}, opts, {
15108 return format(debug, opts).formatted;
15111 printToDoc(text, opts) {
15112 opts = normalizeOptions$1(opts);
15113 const parsed = parser.parse(text, opts);
15117 text = parsed.text;
15118 attachComments(text, ast, opts);
15119 return astToDoc(ast, opts);
15122 printDocToString(doc, opts) {
15123 return printDocToString$1(doc, normalizeOptions$1(opts));
15128 // A simple implementation of make-array
15129 function make_array(subject) {
15130 return Array.isArray(subject) ? subject : [subject];
15133 const REGEX_BLANK_LINE = /^\s+$/;
15134 const REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
15135 const REGEX_LEADING_EXCAPED_HASH = /^\\#/;
15137 const KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
15138 /* istanbul ignore next */
15141 const define = (object, key, value) => Object.defineProperty(object, key, {
15145 const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression
15146 // The cases are complicated, see test cases for details
15148 const sanitizeRange = range => range.replace(REGEX_REGEXP_RANGE, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match // Invalid range (out of order) which is ok for gitignore rules but
15149 // fatal for JavaScript regular expression, so eliminate it.
15150 : ''); // > If the pattern ends with a slash,
15151 // > it is removed for the purpose of the following description,
15152 // > but it would only find a match with a directory.
15153 // > In other words, foo/ will match a directory foo and paths underneath it,
15154 // > but will not match a regular file or a symbolic link foo
15155 // > (this is consistent with the way how pathspec works in general in Git).
15156 // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
15157 // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
15158 // you could use option `mark: true` with `glob`
15159 // '`foo/`' should not continue with the '`..`'
15162 const DEFAULT_REPLACER_PREFIX = [// > Trailing spaces are ignored unless they are quoted with backslash ("\")
15166 /\\?\s+$/, match => match.indexOf('\\') === 0 ? ' ' : ''], // replace (\ ) with ' '
15167 [/\\\s/g, () => ' '], // Escape metacharacters
15168 // which is written down by users but means special for regular expressions.
15169 // > There are 12 characters with special meanings:
15170 // > - the backslash \,
15171 // > - the caret ^,
15172 // > - the dollar sign $,
15173 // > - the period or dot .,
15174 // > - the vertical bar or pipe symbol |,
15175 // > - the question mark ?,
15176 // > - the asterisk or star *,
15177 // > - the plus sign +,
15178 // > - the opening parenthesis (,
15179 // > - the closing parenthesis ),
15180 // > - and the opening square bracket [,
15181 // > - the opening curly brace {,
15182 // > These special characters are often called "metacharacters".
15183 [/[\\^$.|*+(){]/g, match => `\\${match}`], [// > [abc] matches any character inside the brackets
15184 // > (in this case a, b, or c);
15185 /\[([^\]/]*)($|\])/g, (match, p1, p2) => p2 === ']' ? `[${sanitizeRange(p1)}]` : `\\${match}`], [// > a question mark (?) matches a single character
15186 /(?!\\)\?/g, () => '[^/]'], // leading slash
15187 [// > A leading slash matches the beginning of the pathname.
15188 // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
15189 // A leading slash matches the beginning of the pathname
15190 /^\//, () => '^'], // replace special metacharacter slash after the leading slash
15191 [/\//g, () => '\\/'], [// > A leading "**" followed by a slash means match in all directories.
15192 // > For example, "**/foo" matches file or directory "foo" anywhere,
15193 // > the same as pattern "foo".
15194 // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
15195 // > under directory "foo".
15196 // Notice that the '*'s have been replaced as '\\*'
15197 /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo'
15198 () => '^(?:.*\\/)?']];
15199 const DEFAULT_REPLACER_SUFFIX = [// starting
15200 [// there will be no leading '/'
15201 // (which has been replaced by section "leading slash")
15202 // If starts with '**', adding a '^' to the regular expression also works
15203 /^(?=[^^])/, function startingReplacer() {
15204 return !/\/(?!$)/.test(this) // > If the pattern does not contain a slash /,
15205 // > Git treats it as a shell glob pattern
15206 // Actually, if there is only a trailing slash,
15207 // git also treats it as a shell glob pattern
15208 ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for
15209 // > consumption by fnmatch(3)
15211 }], // two globstars
15212 [// Use lookahead assertions so that we could match more than one `'/**'`
15213 /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories
15214 // should not use '*', or it will be replaced by the next replacer
15215 // Check if it is not the last `'/**'`
15216 (match, index, str) => index + 6 < str.length // case: /**/
15217 // > A slash followed by two consecutive asterisks then a slash matches
15218 // > zero or more directories.
15219 // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
15221 ? '(?:\\/[^\\/]+)*' // case: /**
15222 // > A trailing `"/**"` matches everything inside.
15223 // #21: everything inside but it should not include the current folder
15224 : '\\/.+'], // intermediate wildcards
15225 [// Never replace escaped '*'
15226 // ignore rule '\*' will match the path '*'
15228 // 'abc.*' -> skip this rule
15229 /(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js'
15230 // '*.js' doesn't match 'abc'
15231 (match, p1) => `${p1}[^\\/]*`], // trailing wildcard
15232 [/(\^|\\\/)?\\\*$/, (match, p1) => {
15233 const prefix = p1 // '\^':
15234 // '/*' does not match ''
15235 // '/*' does not match everything
15237 // 'abc/*' does not match 'abc/'
15238 ? `${p1}[^/]+` // 'a*' matches 'a'
15239 // 'a*' matches 'aa'
15241 return `${prefix}(?=$|\\/$)`;
15243 /\\\\\\/g, () => '\\']];
15244 const POSITIVE_REPLACERS = [...DEFAULT_REPLACER_PREFIX, // 'f'
15256 [// 'js' will not match 'js.'
15257 // 'ab' will not match 'abc'
15258 /(?:[^*/])$/, // 'js*' will not match 'a.js'
15259 // 'js/' will not match 'a.js'
15260 // 'js' will match 'a.js' and 'a.js/'
15261 match => `${match}(?=$|\\/)`], ...DEFAULT_REPLACER_SUFFIX];
15262 const NEGATIVE_REPLACERS = [...DEFAULT_REPLACER_PREFIX, // #24, #38
15263 // The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore)
15264 // A negative pattern without a trailing wildcard should not
15265 // re-include the things inside that directory.
15267 // ['node_modules/*', '!node_modules']
15268 // should ignore `node_modules/a.js`
15269 [/(?:[^*])$/, match => `${match}(?=$|\\/$)`], ...DEFAULT_REPLACER_SUFFIX]; // A simple cache, because an ignore rule only has only one certain meaning
15271 const cache = Object.create(null); // @param {pattern}
15273 const make_regex = (pattern, negative, ignorecase) => {
15274 const r = cache[pattern];
15280 const replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS;
15281 const source = replacers.reduce((prev, current) => prev.replace(current[0], current[1].bind(pattern)), pattern);
15282 return cache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source);
15283 }; // > A blank line matches no files, so it can serve as a separator for readability.
15286 const checkPattern = pattern => pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment.
15287 && pattern.indexOf('#') !== 0;
15289 const createRule = (pattern, ignorecase) => {
15290 const origin = pattern;
15291 let negative = false; // > An optional prefix "!" which negates the pattern;
15293 if (pattern.indexOf('!') === 0) {
15295 pattern = pattern.substr(1);
15298 pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that
15299 // > begin with a literal "!", for example, `"\!important!.txt"`.
15300 .replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that
15301 // > begin with a hash.
15302 .replace(REGEX_LEADING_EXCAPED_HASH, '#');
15303 const regex = make_regex(pattern, negative, ignorecase);
15317 this._ignorecase = ignorecase;
15318 define(this, KEY_IGNORE, true);
15324 this._cache = Object.create(null);
15325 } // @param {Array.<string>|string|Ignore} pattern
15329 this._added = false;
15331 if (typeof pattern === 'string') {
15332 pattern = pattern.split(/\r?\n/g);
15335 make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore,
15336 // making the behavior changed.
15346 addPattern(pattern) {
15347 return this.add(pattern);
15350 _addPattern(pattern) {
15352 if (pattern && pattern[KEY_IGNORE]) {
15353 this._rules = this._rules.concat(pattern._rules);
15354 this._added = true;
15358 if (checkPattern(pattern)) {
15359 const rule = createRule(pattern, this._ignorecase);
15360 this._added = true;
15362 this._rules.push(rule);
15367 return make_array(paths).filter(path => this._filter(path));
15371 return path => this._filter(path);
15375 return !this._filter(path);
15376 } // @returns `Boolean` true if the `path` is NOT ignored
15379 _filter(path, slices) {
15384 if (path in this._cache) {
15385 return this._cache[path];
15390 // ['path', 'to', 'a.js']
15391 slices = path.split(SLASH);
15395 return this._cache[path] = slices.length // > It is not possible to re-include a file if a parent directory of
15396 // > that file is excluded.
15397 // If the path contains a parent directory, check the parent first
15398 ? this._filter(slices.join(SLASH) + SLASH, slices) && this._test(path) // Or only test the path
15399 : this._test(path);
15400 } // @returns {Boolean} true if a file is NOT ignored
15404 // Explicitly define variable type by setting matched to `0`
15407 this._rules.forEach(rule => {
15408 // if matched = true, then we only test negative rules
15409 // if matched = false, then we test non-negative rules
15410 if (!(matched ^ rule.negative)) {
15411 matched = rule.negative ^ rule.regex.test(path);
15419 // --------------------------------------------------------------
15421 /* istanbul ignore if */
15424 if ( // Detect `process` so that it can run in browsers.
15425 typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
15426 const filter = IgnoreBase.prototype._filter;
15427 /* eslint no-control-regex: "off" */
15429 const make_posix = str => /^\\\\\?\\/.test(str) || /[^\x00-\x80]+/.test(str) ? str : str.replace(/\\/g, '/');
15431 IgnoreBase.prototype._filter = function filterWin32(path, slices) {
15432 path = make_posix(path);
15433 return filter.call(this, path, slices);
15437 var ignore = options => new IgnoreBase(options);
15440 * @param {string} filename
15441 * @returns {Promise<null | string>}
15445 function getFileContentOrNull(filename) {
15446 return new Promise((resolve, reject) => {
15447 fs$3.readFile(filename, "utf8", (error, data) => {
15448 if (error && error.code !== "ENOENT") {
15449 reject(createError(filename, error));
15451 resolve(error ? null : data);
15457 * @param {string} filename
15458 * @returns {null | string}
15462 getFileContentOrNull.sync = function (filename) {
15464 return fs$3.readFileSync(filename, "utf8");
15466 if (error && error.code === "ENOENT") {
15470 throw createError(filename, error);
15474 function createError(filename, error) {
15475 return new Error(`Unable to read ${filename}: ${error.message}`);
15478 var getFileContentOrNull_1 = getFileContentOrNull;
15481 * @param {undefined | string} ignorePath
15482 * @param {undefined | boolean} withNodeModules
15486 async function createIgnorer(ignorePath, withNodeModules) {
15487 const ignoreContent = ignorePath ? await getFileContentOrNull_1(path$2.resolve(ignorePath)) : null;
15488 return _createIgnorer(ignoreContent, withNodeModules);
15491 * @param {undefined | string} ignorePath
15492 * @param {undefined | boolean} withNodeModules
15496 createIgnorer.sync = function (ignorePath, withNodeModules) {
15497 const ignoreContent = !ignorePath ? null : getFileContentOrNull_1.sync(path$2.resolve(ignorePath));
15498 return _createIgnorer(ignoreContent, withNodeModules);
15501 * @param {null | string} ignoreContent
15502 * @param {undefined | boolean} withNodeModules
15506 function _createIgnorer(ignoreContent, withNodeModules) {
15507 const ignorer = ignore().add(ignoreContent || "");
15509 if (!withNodeModules) {
15510 ignorer.add("node_modules");
15516 var createIgnorer_1 = createIgnorer;
15518 var thirdParty = require("./third-party");
15520 var concatMap = function (xs, fn) {
15523 for (var i = 0; i < xs.length; i++) {
15524 var x = fn(xs[i], i);
15525 if (isArray(x)) res.push.apply(res, x);else res.push(x);
15531 var isArray = Array.isArray || function (xs) {
15532 return Object.prototype.toString.call(xs) === '[object Array]';
15535 var balancedMatch = balanced;
15537 function balanced(a, b, str) {
15538 if (a instanceof RegExp) a = maybeMatch(a, str);
15539 if (b instanceof RegExp) b = maybeMatch(b, str);
15540 var r = range(a, b, str);
15544 pre: str.slice(0, r[0]),
15545 body: str.slice(r[0] + a.length, r[1]),
15546 post: str.slice(r[1] + b.length)
15550 function maybeMatch(reg, str) {
15551 var m = str.match(reg);
15552 return m ? m[0] : null;
15555 balanced.range = range;
15557 function range(a, b, str) {
15558 var begs, beg, left, right, result;
15559 var ai = str.indexOf(a);
15560 var bi = str.indexOf(b, ai + 1);
15563 if (ai >= 0 && bi > 0) {
15567 while (i >= 0 && !result) {
15570 ai = str.indexOf(a, i + 1);
15571 } else if (begs.length == 1) {
15572 result = [begs.pop(), bi];
15581 bi = str.indexOf(b, i + 1);
15584 i = ai < bi && ai >= 0 ? ai : bi;
15588 result = [left, right];
15595 var braceExpansion = expandTop;
15596 var escSlash = '\0SLASH' + Math.random() + '\0';
15597 var escOpen = '\0OPEN' + Math.random() + '\0';
15598 var escClose = '\0CLOSE' + Math.random() + '\0';
15599 var escComma = '\0COMMA' + Math.random() + '\0';
15600 var escPeriod = '\0PERIOD' + Math.random() + '\0';
15602 function numeric$1(str) {
15603 return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
15606 function escapeBraces(str) {
15607 return str.split('\\\\').join(escSlash).split('\\{').join(escOpen).split('\\}').join(escClose).split('\\,').join(escComma).split('\\.').join(escPeriod);
15610 function unescapeBraces(str) {
15611 return str.split(escSlash).join('\\').split(escOpen).join('{').split(escClose).join('}').split(escComma).join(',').split(escPeriod).join('.');
15612 } // Basically just str.split(","), but handling cases
15613 // where we have nested braced sections, which should be
15614 // treated as individual members, like {a,{b,c},d}
15617 function parseCommaParts(str) {
15618 if (!str) return [''];
15620 var m = balancedMatch('{', '}', str);
15621 if (!m) return str.split(',');
15625 var p = pre.split(',');
15626 p[p.length - 1] += '{' + body + '}';
15627 var postParts = parseCommaParts(post);
15630 p[p.length - 1] += postParts.shift();
15631 p.push.apply(p, postParts);
15634 parts.push.apply(parts, p);
15638 function expandTop(str) {
15639 if (!str) return []; // I don't know why Bash 4.3 does this, but it does.
15640 // Anything starting with {} will have the first two bytes preserved
15641 // but *only* at the top level, so {},a}b will not expand to anything,
15642 // but a{},b}c will be expanded to [a}c,abc].
15643 // One could argue that this is a bug in Bash, but since the goal of
15644 // this module is to match Bash's rules, we escape a leading {}
15646 if (str.substr(0, 2) === '{}') {
15647 str = '\\{\\}' + str.substr(2);
15650 return expand(escapeBraces(str), true).map(unescapeBraces);
15653 function embrace(str) {
15654 return '{' + str + '}';
15657 function isPadded(el) {
15658 return /^-?0\d/.test(el);
15661 function lte(i, y) {
15665 function gte$1(i, y) {
15669 function expand(str, isTop) {
15670 var expansions = [];
15671 var m = balancedMatch('{', '}', str);
15672 if (!m || /\$$/.test(m.pre)) return [str];
15673 var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
15674 var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
15675 var isSequence = isNumericSequence || isAlphaSequence;
15676 var isOptions = m.body.indexOf(',') >= 0;
15678 if (!isSequence && !isOptions) {
15680 if (m.post.match(/,.*\}/)) {
15681 str = m.pre + '{' + m.body + escClose + m.post;
15682 return expand(str);
15691 n = m.body.split(/\.\./);
15693 n = parseCommaParts(m.body);
15695 if (n.length === 1) {
15696 // x{{a,b}}y ==> x{a}y x{b}y
15697 n = expand(n[0], false).map(embrace);
15699 if (n.length === 1) {
15700 var post = m.post.length ? expand(m.post, false) : [''];
15701 return post.map(function (p) {
15702 return m.pre + n[0] + p;
15706 } // at this point, n is the parts, and we know it's not a comma set
15707 // with a single entry.
15708 // no need to expand pre, since it is guaranteed to be free of brace-sets
15712 var post = m.post.length ? expand(m.post, false) : [''];
15716 var x = numeric$1(n[0]);
15717 var y = numeric$1(n[1]);
15718 var width = Math.max(n[0].length, n[1].length);
15719 var incr = n.length == 3 ? Math.abs(numeric$1(n[2])) : 1;
15721 var reverse = y < x;
15728 var pad = n.some(isPadded);
15731 for (var i = x; test(i, y); i += incr) {
15734 if (isAlphaSequence) {
15735 c = String.fromCharCode(i);
15736 if (c === '\\') c = '';
15741 var need = width - c.length;
15744 var z = new Array(need + 1).join('0');
15745 if (i < 0) c = '-' + z + c.slice(1);else c = z + c;
15753 N = concatMap(n, function (el) {
15754 return expand(el, false);
15758 for (var j = 0; j < N.length; j++) {
15759 for (var k = 0; k < post.length; k++) {
15760 var expansion = pre + N[j] + post[k];
15761 if (!isTop || isSequence || expansion) expansions.push(expansion);
15768 var minimatch_1 = minimatch;
15769 minimatch.Minimatch = Minimatch;
15778 var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
15800 }; // any single thing other than /
15801 // don't need to escape / when using new RegExp()
15803 var qmark = '[^/]'; // * => any number of characters
15805 var star = qmark + '*?'; // ** when dots are allowed. Anything goes, except .. and .
15806 // not (^ or / followed by one or two dots followed by $ or /),
15807 // followed by anything, any number of times.
15809 var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; // not a ^ or / followed by a dot,
15810 // followed by anything, any number of times.
15812 var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; // characters that need to be escaped in RegExp.
15814 var reSpecials = charSet('().*{}+?[]^$\\!'); // "abc" -> { a:true, b:true, c:true }
15816 function charSet(s) {
15817 return s.split('').reduce(function (set, c) {
15821 } // normalizes slashes.
15824 var slashSplit = /\/+/;
15825 minimatch.filter = filter;
15827 function filter(pattern, options) {
15828 options = options || {};
15829 return function (p, i, list) {
15830 return minimatch(p, pattern, options);
15834 function ext(a, b) {
15838 Object.keys(b).forEach(function (k) {
15841 Object.keys(a).forEach(function (k) {
15847 minimatch.defaults = function (def) {
15848 if (!def || !Object.keys(def).length) return minimatch;
15849 var orig = minimatch;
15851 var m = function minimatch(p, pattern, options) {
15852 return orig.minimatch(p, pattern, ext(def, options));
15855 m.Minimatch = function Minimatch(pattern, options) {
15856 return new orig.Minimatch(pattern, ext(def, options));
15862 Minimatch.defaults = function (def) {
15863 if (!def || !Object.keys(def).length) return Minimatch;
15864 return minimatch.defaults(def).Minimatch;
15867 function minimatch(p, pattern, options) {
15868 if (typeof pattern !== 'string') {
15869 throw new TypeError('glob pattern string required');
15872 if (!options) options = {}; // shortcut: comments match nothing.
15874 if (!options.nocomment && pattern.charAt(0) === '#') {
15876 } // "" only matches ""
15879 if (pattern.trim() === '') return p === '';
15880 return new Minimatch(pattern, options).match(p);
15883 function Minimatch(pattern, options) {
15884 if (!(this instanceof Minimatch)) {
15885 return new Minimatch(pattern, options);
15888 if (typeof pattern !== 'string') {
15889 throw new TypeError('glob pattern string required');
15892 if (!options) options = {};
15893 pattern = pattern.trim(); // windows support: need to use /, not \
15895 if (path.sep !== '/') {
15896 pattern = pattern.split(path.sep).join('/');
15899 this.options = options;
15901 this.pattern = pattern;
15902 this.regexp = null;
15903 this.negate = false;
15904 this.comment = false;
15905 this.empty = false; // make the set of regexps etc.
15910 Minimatch.prototype.debug = function () {};
15912 Minimatch.prototype.make = make;
15915 // don't do it more than once.
15916 if (this._made) return;
15917 var pattern = this.pattern;
15918 var options = this.options; // empty patterns and comments match nothing.
15920 if (!options.nocomment && pattern.charAt(0) === '#') {
15921 this.comment = true;
15928 } // step 1: figure out negation, etc.
15931 this.parseNegate(); // step 2: expand braces
15933 var set = this.globSet = this.braceExpand();
15934 if (options.debug) this.debug = console.error;
15935 this.debug(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion
15936 // matching patterns.
15937 // These will be regexps, except in the case of "**", which is
15938 // set to the GLOBSTAR object for globstar behavior,
15939 // and will not contain any / characters
15941 set = this.globParts = set.map(function (s) {
15942 return s.split(slashSplit);
15944 this.debug(this.pattern, set); // glob --> regexps
15946 set = set.map(function (s, si, set) {
15947 return s.map(this.parse, this);
15949 this.debug(this.pattern, set); // filter out everything that didn't compile properly.
15951 set = set.filter(function (s) {
15952 return s.indexOf(false) === -1;
15954 this.debug(this.pattern, set);
15958 Minimatch.prototype.parseNegate = parseNegate;
15960 function parseNegate() {
15961 var pattern = this.pattern;
15962 var negate = false;
15963 var options = this.options;
15964 var negateOffset = 0;
15965 if (options.nonegate) return;
15967 for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === '!'; i++) {
15972 if (negateOffset) this.pattern = pattern.substr(negateOffset);
15973 this.negate = negate;
15974 } // Brace expansion:
15975 // a{b,c}d -> abd acd
15976 // a{b,}c -> abc ac
15977 // a{0..3}d -> a0d a1d a2d a3d
15978 // a{b,c{d,e}f}g -> abg acdfg acefg
15979 // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
15981 // Invalid sets are not expanded.
15982 // a{2..}b -> a{2..}b
15986 minimatch.braceExpand = function (pattern, options) {
15987 return braceExpand(pattern, options);
15990 Minimatch.prototype.braceExpand = braceExpand;
15992 function braceExpand(pattern, options) {
15994 if (this instanceof Minimatch) {
15995 options = this.options;
16001 pattern = typeof pattern === 'undefined' ? this.pattern : pattern;
16003 if (typeof pattern === 'undefined') {
16004 throw new TypeError('undefined pattern');
16007 if (options.nobrace || !pattern.match(/\{.*\}/)) {
16008 // shortcut. no need to expand.
16012 return braceExpansion(pattern);
16013 } // parse a component of the expanded set.
16014 // At this point, no pattern may contain "/" in it
16015 // so we're going to return a 2d array, where each entry is the full
16016 // pattern, split on '/', and then turned into a regular expression.
16017 // A regexp is made at the end which joins each array with an
16018 // escaped /, and another full one which joins each regexp with |.
16020 // Following the lead of Bash 4.1, note that "**" only has special meaning
16021 // when it is the *only* thing in a path portion. Otherwise, any series
16022 // of * is equivalent to a single *. Globstar behavior is enabled by
16023 // default, and can be disabled by setting options.noglobstar.
16026 Minimatch.prototype.parse = parse$1;
16029 function parse$1(pattern, isSub) {
16030 if (pattern.length > 1024 * 64) {
16031 throw new TypeError('pattern is too long');
16034 var options = this.options; // shortcuts
16036 if (!options.noglobstar && pattern === '**') return GLOBSTAR;
16037 if (pattern === '') return '';
16039 var hasMagic = !!options.nocase;
16040 var escaping = false; // ? => one single character
16042 var patternListStack = [];
16043 var negativeLists = [];
16045 var inClass = false;
16046 var reClassStart = -1;
16047 var classStart = -1; // . and .. never match anything that doesn't start with .,
16048 // even when options.dot is set.
16050 var patternStart = pattern.charAt(0) === '.' ? '' // anything
16051 // not (start or / followed by . or .. followed by / or end)
16052 : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)';
16055 function clearStateChar() {
16057 // we had some state-tracking character
16058 // that wasn't consumed by this pass.
16059 switch (stateChar) {
16071 re += '\\' + stateChar;
16075 self.debug('clearStateChar %j %j', stateChar, re);
16080 for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
16081 this.debug('%s\t%s %s %j', pattern, i, re, c); // skip over any that are escaped.
16083 if (escaping && reSpecials[c]) {
16091 // completely not allowed, even escaped.
16092 // Should already be path-split by now.
16099 // the various stateChar values
16100 // for the "extglob" stuff.
16107 this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); // all of those are literals inside a class, except that
16108 // the glob [!a] means [^a] in regexp
16111 this.debug(' in class');
16112 if (c === '!' && i === classStart + 1) c = '^';
16115 } // if we already have a stateChar, then it means
16116 // that there was something like ** or +? in there.
16117 // Handle the stateChar, then proceed with this one.
16120 self.debug('call clearStateChar %j', stateChar);
16122 stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
16123 // just clear the statechar *now*, rather than even diving into
16124 // the patternList stuff.
16126 if (options.noext) clearStateChar();
16140 patternListStack.push({
16143 reStart: re.length,
16144 open: plTypes[stateChar].open,
16145 close: plTypes[stateChar].close
16146 }); // negation is (?:(?!js)[^/]*)
16148 re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
16149 this.debug('plType %j %j', stateChar, re);
16154 if (inClass || !patternListStack.length) {
16161 var pl = patternListStack.pop(); // negation is (?:(?!js)[^/]*)
16162 // The others are (?:<pattern>)<type>
16166 if (pl.type === '!') {
16167 negativeLists.push(pl);
16170 pl.reEnd = re.length;
16174 if (inClass || !patternListStack.length || escaping) {
16183 // these are mostly the same in regexp and glob
16186 // swallow any state-tracking char before the [
16196 reClassStart = re.length;
16201 // a right bracket shall lose its special
16202 // meaning and represent itself in
16203 // a bracket expression if it occurs
16204 // first in the list. -- POSIX.2 2.8.3.2
16205 if (i === classStart + 1 || !inClass) {
16209 } // handle the case where we left a class open.
16210 // "[z-a]" is valid, equivalent to "\[z-a\]"
16214 // split where the last [ was, make sure we don't have
16215 // an invalid re. if so, re-walk the contents of the
16216 // would-be class to re-translate any characters that
16217 // were passed through as-is
16218 // TODO: It would probably be faster to determine this
16219 // without a try/catch and a new RegExp, but it's tricky
16220 // to do safely. For now, this is safe and works.
16221 var cs = pattern.substring(classStart + 1, i);
16224 RegExp('[' + cs + ']');
16226 // not a valid class!
16227 var sp = this.parse(cs, SUBPARSE);
16228 re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
16229 hasMagic = hasMagic || sp[1];
16233 } // finish up the class.
16242 // swallow any state char that wasn't consumed
16248 } else if (reSpecials[c] && !(c === '^' && inClass)) {
16256 // handle the case where we left a class open.
16257 // "[abc" is valid, equivalent to "\[abc"
16261 // split where the last [ was, and escape it
16262 // this is a huge pita. We now have to re-walk
16263 // the contents of the would-be class to re-translate
16264 // any characters that were passed through as-is
16265 cs = pattern.substr(classStart + 1);
16266 sp = this.parse(cs, SUBPARSE);
16267 re = re.substr(0, reClassStart) + '\\[' + sp[0];
16268 hasMagic = hasMagic || sp[1];
16269 } // handle the case where we had a +( thing at the *end*
16271 // each pattern list stack adds 3 chars, and we need to go through
16272 // and escape any | chars that were passed through as-is for the regexp.
16273 // Go through and escape them, taking care not to double-escape any
16274 // | chars that were already escaped.
16277 for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
16278 var tail = re.slice(pl.reStart + pl.open.length);
16279 this.debug('setting tail', re, pl); // maybe some even number of \, then maybe 1 \, followed by a |
16281 tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
16283 // the | isn't already escaped, so escape it.
16285 } // need to escape all those slashes *again*, without escaping the
16286 // one that we need for escaping the | character. As it works out,
16287 // escaping an even number of slashes can be done by simply repeating
16288 // it exactly after itself. That's why this trick works.
16290 // I am sorry that you have to see this.
16293 return $1 + $1 + $2 + '|';
16295 this.debug('tail=%j\n %s', tail, tail, pl, re);
16296 var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type;
16298 re = re.slice(0, pl.reStart) + t + '\\(' + tail;
16299 } // handle trailing things that only matter at the very end.
16307 } // only need to apply the nodot start if the re starts with
16308 // something that could conceivably capture a dot
16311 var addPatternStart = false;
16313 switch (re.charAt(0)) {
16317 addPatternStart = true;
16318 } // Hack to work around lack of negative lookbehind in JS
16319 // A pattern like: *.!(x).!(y|z) needs to ensure that a name
16320 // like 'a.xyz.yz' doesn't match. So, the first negative
16321 // lookahead, has to look ALL the way ahead, to the end of
16325 for (var n = negativeLists.length - 1; n > -1; n--) {
16326 var nl = negativeLists[n];
16327 var nlBefore = re.slice(0, nl.reStart);
16328 var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
16329 var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
16330 var nlAfter = re.slice(nl.reEnd);
16331 nlLast += nlAfter; // Handle nested stuff like *(*.js|!(*.json)), where open parens
16332 // mean that we should *not* include the ) in the bit that is considered
16333 // "after" the negated section.
16335 var openParensBefore = nlBefore.split('(').length - 1;
16336 var cleanAfter = nlAfter;
16338 for (i = 0; i < openParensBefore; i++) {
16339 cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
16342 nlAfter = cleanAfter;
16345 if (nlAfter === '' && isSub !== SUBPARSE) {
16349 var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
16351 } // if the re is not "" at this point, then we need to make sure
16352 // it doesn't match against an empty path part.
16353 // Otherwise a/* will match a/, which it should not.
16356 if (re !== '' && hasMagic) {
16360 if (addPatternStart) {
16361 re = patternStart + re;
16362 } // parsing just a piece of a larger pattern.
16365 if (isSub === SUBPARSE) {
16366 return [re, hasMagic];
16367 } // skip the regexp for non-magical patterns
16368 // unescape anything in it, though, so that it'll be
16369 // an exact match against a file etc.
16373 return globUnescape(pattern);
16376 var flags = options.nocase ? 'i' : '';
16379 var regExp = new RegExp('^' + re + '$', flags);
16381 // If it was an invalid regular expression, then it can't match
16382 // anything. This trick looks for a character after the end of
16383 // the string, which is of course impossible, except in multi-line
16384 // mode, but it's not a /m regex.
16385 return new RegExp('$.');
16388 regExp._glob = pattern;
16393 minimatch.makeRe = function (pattern, options) {
16394 return new Minimatch(pattern, options || {}).makeRe();
16397 Minimatch.prototype.makeRe = makeRe;
16399 function makeRe() {
16400 if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
16401 // pattern strings, or "**".
16403 // It's better to use .match(). This function shouldn't
16404 // be used, really, but it's pretty convenient sometimes,
16405 // when you just want to work with a regex.
16407 var set = this.set;
16410 this.regexp = false;
16411 return this.regexp;
16414 var options = this.options;
16415 var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
16416 var flags = options.nocase ? 'i' : '';
16417 var re = set.map(function (pattern) {
16418 return pattern.map(function (p) {
16419 return p === GLOBSTAR ? twoStar : typeof p === 'string' ? regExpEscape(p) : p._src;
16421 }).join('|'); // must match entire pattern
16422 // ending in a * or ** will make it less strict.
16424 re = '^(?:' + re + ')$'; // can match anything, as long as it's not this.
16426 if (this.negate) re = '^(?!' + re + ').*$';
16429 this.regexp = new RegExp(re, flags);
16431 this.regexp = false;
16434 return this.regexp;
16437 minimatch.match = function (list, pattern, options) {
16438 options = options || {};
16439 var mm = new Minimatch(pattern, options);
16440 list = list.filter(function (f) {
16441 return mm.match(f);
16444 if (mm.options.nonull && !list.length) {
16445 list.push(pattern);
16451 Minimatch.prototype.match = match;
16453 function match(f, partial) {
16454 this.debug('match', f, this.pattern); // short-circuit in the case of busted things.
16457 if (this.comment) return false;
16458 if (this.empty) return f === '';
16459 if (f === '/' && partial) return true;
16460 var options = this.options; // windows: need to use /, not \
16462 if (path.sep !== '/') {
16463 f = f.split(path.sep).join('/');
16464 } // treat the test path as a set of pathparts.
16467 f = f.split(slashSplit);
16468 this.debug(this.pattern, 'split', f); // just ONE of the pattern sets in this.set needs to match
16469 // in order for it to be valid. If negating, then just one
16470 // match means that we have failed.
16471 // Either way, return on the first hit.
16473 var set = this.set;
16474 this.debug(this.pattern, 'set', set); // Find the basename of the path by looking for the last non-empty segment
16479 for (i = f.length - 1; i >= 0; i--) {
16481 if (filename) break;
16484 for (i = 0; i < set.length; i++) {
16485 var pattern = set[i];
16488 if (options.matchBase && pattern.length === 1) {
16492 var hit = this.matchOne(file, pattern, partial);
16495 if (options.flipNegate) return true;
16496 return !this.negate;
16498 } // didn't get any hits. this is success if it's a negative
16499 // pattern, failure otherwise.
16502 if (options.flipNegate) return false;
16503 return this.negate;
16504 } // set partial to true to test if, for example,
16505 // "/a/b" matches the start of "/*/b/*/d"
16506 // Partial means, if you run out of file before you run
16507 // out of pattern, then that's fine, as long as all
16508 // the parts match.
16511 Minimatch.prototype.matchOne = function (file, pattern, partial) {
16512 var options = this.options;
16513 this.debug('matchOne', {
16518 this.debug('matchOne', file.length, pattern.length);
16520 for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
16521 this.debug('matchOne loop');
16522 var p = pattern[pi];
16524 this.debug(pattern, p, f); // should be impossible.
16525 // some invalid regexp stuff in the set.
16527 if (p === false) return false;
16529 if (p === GLOBSTAR) {
16530 this.debug('GLOBSTAR', [pattern, p, f]); // "**"
16531 // a/**/b/**/c would match the following:
16536 // To do this, take the rest of the pattern after
16537 // the **, and see if it would match the file remainder.
16538 // If so, return success.
16539 // If not, the ** "swallows" a segment, and try again.
16540 // This is recursively awful.
16542 // a/**/b/**/c matching a/b/x/y/z/c
16545 // - matchOne(b/x/y/z/c, b/**/c)
16548 // - matchOne(x/y/z/c, c) -> no
16549 // - matchOne(y/z/c, c) -> no
16550 // - matchOne(z/c, c) -> no
16551 // - matchOne(c, c) yes, hit
16557 this.debug('** at the end'); // a ** at the end will just swallow the rest.
16558 // We have found a match.
16559 // however, it will not swallow /.x, unless
16560 // options.dot is set.
16561 // . and .. are *never* matched by **, for explosively
16562 // exponential reasons.
16564 for (; fi < fl; fi++) {
16565 if (file[fi] === '.' || file[fi] === '..' || !options.dot && file[fi].charAt(0) === '.') return false;
16569 } // ok, let's see if we can swallow whatever we can.
16573 var swallowee = file[fr];
16574 this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); // XXX remove this slice. Just pass the start index.
16576 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
16577 this.debug('globstar found match!', fr, fl, swallowee); // found a match.
16581 // can't swallow "." or ".." ever.
16582 // can only swallow ".foo" when explicitly asked.
16583 if (swallowee === '.' || swallowee === '..' || !options.dot && swallowee.charAt(0) === '.') {
16584 this.debug('dot detected!', file, fr, pattern, pr);
16586 } // ** swallows a segment, and continue.
16589 this.debug('globstar swallow a segment, and continue');
16592 } // no match was found.
16593 // However, in partial mode, we can't say this is necessarily over.
16594 // If there's more *pattern* left, then
16599 this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
16600 if (fr === fl) return true;
16604 } // something other than **
16605 // non-magic patterns just have to match exactly
16606 // patterns with magic have been turned into regexps.
16611 if (typeof p === 'string') {
16612 if (options.nocase) {
16613 hit = f.toLowerCase() === p.toLowerCase();
16618 this.debug('string match', p, f, hit);
16621 this.debug('pattern match', p, f, hit);
16624 if (!hit) return false;
16625 } // Note: ending in / means that we'll get a final ""
16626 // at the end of the pattern. This can only match a
16627 // corresponding "" at the end of the file.
16628 // If the file ends in /, then it can only match a
16629 // a pattern that ends in /, unless the pattern just
16630 // doesn't have any more for it. But, a/b/ should *not*
16631 // match "a/b/*", even though "" matches against the
16632 // [^/]*? pattern, except in partial mode, where it might
16633 // simply not be reached yet.
16634 // However, a/b/ should still satisfy a/*
16635 // now either we fell off the end of the pattern, or we're done.
16638 if (fi === fl && pi === pl) {
16639 // ran out of pattern and filename at the same time.
16642 } else if (fi === fl) {
16643 // ran out of file, but still had pattern left.
16644 // this is ok if we're doing the match as part of
16645 // a glob fs traversal.
16647 } else if (pi === pl) {
16648 // ran out of pattern, still have file left.
16649 // this is only acceptable if we're on the very last
16650 // empty segment of a file with a trailing slash.
16651 // a/* should match a/b/
16652 var emptyFileEnd = fi === fl - 1 && file[fi] === '';
16653 return emptyFileEnd;
16654 } // should be unreachable.
16657 throw new Error('wtf?');
16658 }; // replace stuff like \* with *
16661 function globUnescape(s) {
16662 return s.replace(/\\(.)/g, '$1');
16665 function regExpEscape(s) {
16666 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
16669 const copyProperty = (to, from, property, ignoreNonConfigurable) => {
16670 // `Function#length` should reflect the parameters of `to` not `from` since we keep its body.
16671 // `Function#prototype` is non-writable and non-configurable so can never be modified.
16672 if (property === 'length' || property === 'prototype') {
16676 const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
16677 const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
16679 if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {
16683 Object.defineProperty(to, property, fromDescriptor);
16684 }; // `Object.defineProperty()` throws if the property exists, is not configurable and either:
16685 // - one its descriptors is changed
16686 // - it is non-writable and its value is changed
16689 const canCopyProperty = function (toDescriptor, fromDescriptor) {
16690 return toDescriptor === undefined || toDescriptor.configurable || toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value);
16693 const changePrototype = (to, from) => {
16694 const fromPrototype = Object.getPrototypeOf(from);
16696 if (fromPrototype === Object.getPrototypeOf(to)) {
16700 Object.setPrototypeOf(to, fromPrototype);
16703 const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`;
16705 const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');
16706 const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name'); // We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected.
16707 // We use `bind()` instead of a closure for the same reason.
16708 // Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times.
16710 const changeToString = (to, from, name) => {
16711 const withName = name === '' ? '' : `with ${name.trim()}() `;
16712 const newToString = wrappedToString.bind(null, withName, from.toString()); // Ensure `to.toString.toString` is non-enumerable and has the same `same`
16714 Object.defineProperty(newToString, 'name', toStringName);
16715 Object.defineProperty(to, 'toString', Object.assign({}, toStringDescriptor, {
16720 const mimicFn = (to, from, {
16721 ignoreNonConfigurable = false
16727 for (const property of Reflect.ownKeys(from)) {
16728 copyProperty(to, from, property, ignoreNonConfigurable);
16731 changePrototype(to, from);
16732 changeToString(to, from, name);
16736 var mimicFn_1 = mimicFn;
16738 var pDefer = () => {
16740 ret.promise = new Promise((resolve, reject) => {
16741 ret.resolve = resolve;
16742 ret.reject = reject;
16747 var dist = createCommonjsModule(function (module, exports) {
16749 var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
16750 return new (P || (P = Promise))(function (resolve, reject) {
16751 function fulfilled(value) {
16753 step(generator.next(value));
16759 function rejected(value) {
16761 step(generator["throw"](value));
16767 function step(result) {
16768 result.done ? resolve(result.value) : new P(function (resolve) {
16769 resolve(result.value);
16770 }).then(fulfilled, rejected);
16773 step((generator = generator.apply(thisArg, _arguments || [])).next());
16777 var __importDefault = this && this.__importDefault || function (mod) {
16778 return mod && mod.__esModule ? mod : {
16783 Object.defineProperty(exports, "__esModule", {
16787 const p_defer_1 = __importDefault(pDefer);
16789 function mapAgeCleaner(map, property = 'maxAge') {
16791 let processingTimer;
16792 let processingDeferred;
16794 const cleanup = () => __awaiter(this, void 0, void 0, function* () {
16795 if (processingKey !== undefined) {
16796 // If we are already processing an item, we can safely exit
16800 const setupTimer = item => __awaiter(this, void 0, void 0, function* () {
16801 processingDeferred = p_defer_1.default();
16802 const delay = item[1][property] - Date.now();
16805 // Remove the item immediately if the delay is equal to or below 0
16806 map.delete(item[0]);
16807 processingDeferred.resolve();
16809 } // Keep track of the current processed key
16812 processingKey = item[0];
16813 processingTimer = setTimeout(() => {
16814 // Remove the item when the timeout fires
16815 map.delete(item[0]);
16817 if (processingDeferred) {
16818 processingDeferred.resolve();
16820 }, delay); // tslint:disable-next-line:strict-type-predicates
16822 if (typeof processingTimer.unref === 'function') {
16823 // Don't hold up the process from exiting
16824 processingTimer.unref();
16827 return processingDeferred.promise;
16831 for (const entry of map) {
16832 yield setupTimer(entry);
16834 } catch (_a) {// Do nothing if an error occurs, this means the timer was cleaned up and we should stop processing
16837 processingKey = undefined;
16840 const reset = () => {
16841 processingKey = undefined;
16843 if (processingTimer !== undefined) {
16844 clearTimeout(processingTimer);
16845 processingTimer = undefined;
16848 if (processingDeferred !== undefined) {
16849 // tslint:disable-line:early-exit
16850 processingDeferred.reject(undefined);
16851 processingDeferred = undefined;
16855 const originalSet = map.set.bind(map);
16857 map.set = (key, value) => {
16858 if (map.has(key)) {
16859 // If the key already exist, remove it so we can add it back at the end of the map.
16861 } // Call the original `map.set`
16864 const result = originalSet(key, value); // If we are already processing a key and the key added is the current processed key, stop processing it
16866 if (processingKey && processingKey === key) {
16868 } // Always run the cleanup method in case it wasn't started yet
16871 cleanup(); // tslint:disable-line:no-floating-promises
16876 cleanup(); // tslint:disable-line:no-floating-promises
16881 exports.default = mapAgeCleaner; // Add support for CJS
16883 module.exports = mapAgeCleaner;
16884 module.exports.default = mapAgeCleaner;
16886 unwrapExports(dist);
16888 const cacheStore = new WeakMap();
16891 cacheKey = ([firstArgument]) => firstArgument,
16895 if (typeof maxAge === 'number') {
16899 const memoized = function (...arguments_) {
16900 const key = cacheKey(arguments_);
16902 if (cache.has(key)) {
16903 return cache.get(key).data;
16906 const cacheItem = fn.apply(this, arguments_);
16909 maxAge: maxAge ? Date.now() + maxAge : Infinity
16915 // The below call will throw in some host environments
16916 // See https://github.com/sindresorhus/mimic-fn/issues/10
16917 mimicFn_1(memoized, fn);
16920 cacheStore.set(memoized, cache);
16926 var clear = fn => {
16927 if (!cacheStore.has(fn)) {
16928 throw new Error('Can\'t clear a function that was not memoized!');
16931 const cache = cacheStore.get(fn);
16933 if (typeof cache.clear === 'function') {
16937 mem_1.clear = clear;
16939 var semver$2 = createCommonjsModule(function (module, exports) {
16940 exports = module.exports = SemVer;
16942 /* istanbul ignore next */
16944 if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
16945 debug = function () {
16946 var args = Array.prototype.slice.call(arguments, 0);
16947 args.unshift('SEMVER');
16948 console.log.apply(console, args);
16951 debug = function () {};
16952 } // Note: this is the semver.org version of the spec that it implements
16953 // Not necessarily the package version of this code.
16956 exports.SEMVER_SPEC_VERSION = '2.0.0';
16957 var MAX_LENGTH = 256;
16958 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
16959 /* istanbul ignore next */
16960 9007199254740991; // Max safe segment length for coercion.
16962 var MAX_SAFE_COMPONENT_LENGTH = 16; // The actual regexps go on exports.re
16964 var re = exports.re = [];
16965 var src = exports.src = [];
16966 var R = 0; // The following Regular Expressions can be used for tokenizing,
16967 // validating, and parsing SemVer version strings.
16968 // ## Numeric Identifier
16969 // A single `0`, or a non-zero digit followed by zero or more digits.
16971 var NUMERICIDENTIFIER = R++;
16972 src[NUMERICIDENTIFIER] = '0|[1-9]\\d*';
16973 var NUMERICIDENTIFIERLOOSE = R++;
16974 src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier
16975 // Zero or more digits, followed by a letter or hyphen, and then zero or
16976 // more letters, digits, or hyphens.
16978 var NONNUMERICIDENTIFIER = R++;
16979 src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version
16980 // Three dot-separated numeric identifiers.
16982 var MAINVERSION = R++;
16983 src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')';
16984 var MAINVERSIONLOOSE = R++;
16985 src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier
16986 // A numeric identifier, or a non-numeric identifier.
16988 var PRERELEASEIDENTIFIER = R++;
16989 src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')';
16990 var PRERELEASEIDENTIFIERLOOSE = R++;
16991 src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version
16992 // Hyphen, followed by one or more dot-separated pre-release version
16995 var PRERELEASE = R++;
16996 src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))';
16997 var PRERELEASELOOSE = R++;
16998 src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier
16999 // Any combination of digits, letters, or hyphens.
17001 var BUILDIDENTIFIER = R++;
17002 src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata
17003 // Plus sign, followed by one or more period-separated build metadata
17007 src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; // ## Full Version String
17008 // A main version, followed optionally by a pre-release version and
17010 // Note that the only major, minor, patch, and pre-release sections of
17011 // the version string are capturing groups. The build metadata is not a
17012 // capturing group, because it should not ever be used in version
17016 var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?';
17017 src[FULL] = '^' + FULLPLAIN + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
17018 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
17019 // common in the npm registry.
17021 var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?';
17023 src[LOOSE] = '^' + LOOSEPLAIN + '$';
17025 src[GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x".
17026 // Note that "x.x" is a valid xRange identifer, meaning "any version"
17027 // Only the first item is strictly required.
17029 var XRANGEIDENTIFIERLOOSE = R++;
17030 src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
17031 var XRANGEIDENTIFIER = R++;
17032 src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*';
17033 var XRANGEPLAIN = R++;
17034 src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?';
17035 var XRANGEPLAINLOOSE = R++;
17036 src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?';
17038 src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$';
17039 var XRANGELOOSE = R++;
17040 src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; // Coercion.
17041 // Extract anything that could conceivably be a part of a valid semver
17044 src[COERCE] = '(?:^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])'; // Tilde ranges.
17045 // Meaning is "reasonably at or greater than"
17047 var LONETILDE = R++;
17048 src[LONETILDE] = '(?:~>?)';
17049 var TILDETRIM = R++;
17050 src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+';
17051 re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g');
17052 var tildeTrimReplace = '$1~';
17054 src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$';
17055 var TILDELOOSE = R++;
17056 src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; // Caret ranges.
17057 // Meaning is "at least and backwards compatible with"
17059 var LONECARET = R++;
17060 src[LONECARET] = '(?:\\^)';
17061 var CARETTRIM = R++;
17062 src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+';
17063 re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g');
17064 var caretTrimReplace = '$1^';
17066 src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$';
17067 var CARETLOOSE = R++;
17068 src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version"
17070 var COMPARATORLOOSE = R++;
17071 src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$';
17072 var COMPARATOR = R++;
17073 src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing
17074 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
17076 var COMPARATORTRIM = R++;
17077 src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; // this one has to use the /g flag
17079 re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g');
17080 var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
17081 // Note that these all use the loose form, because they'll be
17082 // checked against either the strict or loose comparator form
17085 var HYPHENRANGE = R++;
17086 src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$';
17087 var HYPHENRANGELOOSE = R++;
17088 src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all.
17091 src[STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects.
17092 // All are flag-free, unless they were created above with a flag.
17094 for (var i = 0; i < R; i++) {
17098 re[i] = new RegExp(src[i]);
17102 exports.parse = parse;
17104 function parse(version, options) {
17105 if (!options || typeof options !== 'object') {
17108 includePrerelease: false
17112 if (version instanceof SemVer) {
17116 if (typeof version !== 'string') {
17120 if (version.length > MAX_LENGTH) {
17124 var r = options.loose ? re[LOOSE] : re[FULL];
17126 if (!r.test(version)) {
17131 return new SemVer(version, options);
17137 exports.valid = valid;
17139 function valid(version, options) {
17140 var v = parse(version, options);
17141 return v ? v.version : null;
17144 exports.clean = clean;
17146 function clean(version, options) {
17147 var s = parse(version.trim().replace(/^[=v]+/, ''), options);
17148 return s ? s.version : null;
17151 exports.SemVer = SemVer;
17153 function SemVer(version, options) {
17154 if (!options || typeof options !== 'object') {
17157 includePrerelease: false
17161 if (version instanceof SemVer) {
17162 if (version.loose === options.loose) {
17165 version = version.version;
17167 } else if (typeof version !== 'string') {
17168 throw new TypeError('Invalid Version: ' + version);
17171 if (version.length > MAX_LENGTH) {
17172 throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters');
17175 if (!(this instanceof SemVer)) {
17176 return new SemVer(version, options);
17179 debug('SemVer', version, options);
17180 this.options = options;
17181 this.loose = !!options.loose;
17182 var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]);
17185 throw new TypeError('Invalid Version: ' + version);
17188 this.raw = version; // these are actually numbers
17190 this.major = +m[1];
17191 this.minor = +m[2];
17192 this.patch = +m[3];
17194 if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
17195 throw new TypeError('Invalid major version');
17198 if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
17199 throw new TypeError('Invalid minor version');
17202 if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
17203 throw new TypeError('Invalid patch version');
17204 } // numberify any prerelease numeric ids
17208 this.prerelease = [];
17210 this.prerelease = m[4].split('.').map(function (id) {
17211 if (/^[0-9]+$/.test(id)) {
17214 if (num >= 0 && num < MAX_SAFE_INTEGER) {
17223 this.build = m[5] ? m[5].split('.') : [];
17227 SemVer.prototype.format = function () {
17228 this.version = this.major + '.' + this.minor + '.' + this.patch;
17230 if (this.prerelease.length) {
17231 this.version += '-' + this.prerelease.join('.');
17234 return this.version;
17237 SemVer.prototype.toString = function () {
17238 return this.version;
17241 SemVer.prototype.compare = function (other) {
17242 debug('SemVer.compare', this.version, this.options, other);
17244 if (!(other instanceof SemVer)) {
17245 other = new SemVer(other, this.options);
17248 return this.compareMain(other) || this.comparePre(other);
17251 SemVer.prototype.compareMain = function (other) {
17252 if (!(other instanceof SemVer)) {
17253 other = new SemVer(other, this.options);
17256 return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
17259 SemVer.prototype.comparePre = function (other) {
17260 if (!(other instanceof SemVer)) {
17261 other = new SemVer(other, this.options);
17262 } // NOT having a prerelease is > having one
17265 if (this.prerelease.length && !other.prerelease.length) {
17267 } else if (!this.prerelease.length && other.prerelease.length) {
17269 } else if (!this.prerelease.length && !other.prerelease.length) {
17276 var a = this.prerelease[i];
17277 var b = other.prerelease[i];
17278 debug('prerelease compare', i, a, b);
17280 if (a === undefined && b === undefined) {
17282 } else if (b === undefined) {
17284 } else if (a === undefined) {
17286 } else if (a === b) {
17289 return compareIdentifiers(a, b);
17292 }; // preminor will bump the version up to the next minor release, and immediately
17293 // down to pre-release. premajor and prepatch work the same way.
17296 SemVer.prototype.inc = function (release, identifier) {
17299 this.prerelease.length = 0;
17303 this.inc('pre', identifier);
17307 this.prerelease.length = 0;
17310 this.inc('pre', identifier);
17314 // If this is already a prerelease, it will bump to the next version
17315 // drop any prereleases that might already exist, since they are not
17316 // relevant at this point.
17317 this.prerelease.length = 0;
17318 this.inc('patch', identifier);
17319 this.inc('pre', identifier);
17321 // If the input is a non-prerelease version, this acts the same as
17325 if (this.prerelease.length === 0) {
17326 this.inc('patch', identifier);
17329 this.inc('pre', identifier);
17333 // If this is a pre-major version, bump up to the same major version.
17334 // Otherwise increment major.
17335 // 1.0.0-5 bumps to 1.0.0
17336 // 1.1.0 bumps to 2.0.0
17337 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
17343 this.prerelease = [];
17347 // If this is a pre-minor version, bump up to the same minor version.
17348 // Otherwise increment minor.
17349 // 1.2.0-5 bumps to 1.2.0
17350 // 1.2.1 bumps to 1.3.0
17351 if (this.patch !== 0 || this.prerelease.length === 0) {
17356 this.prerelease = [];
17360 // If this is not a pre-release version, it will increment the patch.
17361 // If it is a pre-release it will bump up to the same patch version.
17362 // 1.2.0-5 patches to 1.2.0
17363 // 1.2.0 patches to 1.2.1
17364 if (this.prerelease.length === 0) {
17368 this.prerelease = [];
17370 // This probably shouldn't be used publicly.
17371 // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
17374 if (this.prerelease.length === 0) {
17375 this.prerelease = [0];
17377 var i = this.prerelease.length;
17380 if (typeof this.prerelease[i] === 'number') {
17381 this.prerelease[i]++;
17387 // didn't increment anything
17388 this.prerelease.push(0);
17393 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
17394 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
17395 if (this.prerelease[0] === identifier) {
17396 if (isNaN(this.prerelease[1])) {
17397 this.prerelease = [identifier, 0];
17400 this.prerelease = [identifier, 0];
17407 throw new Error('invalid increment argument: ' + release);
17411 this.raw = this.version;
17417 function inc(version, release, loose, identifier) {
17418 if (typeof loose === 'string') {
17419 identifier = loose;
17424 return new SemVer(version, loose).inc(release, identifier).version;
17430 exports.diff = diff;
17432 function diff(version1, version2) {
17433 if (eq(version1, version2)) {
17436 var v1 = parse(version1);
17437 var v2 = parse(version2);
17440 if (v1.prerelease.length || v2.prerelease.length) {
17442 var defaultResult = 'prerelease';
17445 for (var key in v1) {
17446 if (key === 'major' || key === 'minor' || key === 'patch') {
17447 if (v1[key] !== v2[key]) {
17448 return prefix + key;
17453 return defaultResult; // may be undefined
17457 exports.compareIdentifiers = compareIdentifiers;
17458 var numeric = /^[0-9]+$/;
17460 function compareIdentifiers(a, b) {
17461 var anum = numeric.test(a);
17462 var bnum = numeric.test(b);
17464 if (anum && bnum) {
17469 return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
17472 exports.rcompareIdentifiers = rcompareIdentifiers;
17474 function rcompareIdentifiers(a, b) {
17475 return compareIdentifiers(b, a);
17478 exports.major = major;
17480 function major(a, loose) {
17481 return new SemVer(a, loose).major;
17484 exports.minor = minor;
17486 function minor(a, loose) {
17487 return new SemVer(a, loose).minor;
17490 exports.patch = patch;
17492 function patch(a, loose) {
17493 return new SemVer(a, loose).patch;
17496 exports.compare = compare;
17498 function compare(a, b, loose) {
17499 return new SemVer(a, loose).compare(new SemVer(b, loose));
17502 exports.compareLoose = compareLoose;
17504 function compareLoose(a, b) {
17505 return compare(a, b, true);
17508 exports.rcompare = rcompare;
17510 function rcompare(a, b, loose) {
17511 return compare(b, a, loose);
17514 exports.sort = sort;
17516 function sort(list, loose) {
17517 return list.sort(function (a, b) {
17518 return exports.compare(a, b, loose);
17522 exports.rsort = rsort;
17524 function rsort(list, loose) {
17525 return list.sort(function (a, b) {
17526 return exports.rcompare(a, b, loose);
17532 function gt(a, b, loose) {
17533 return compare(a, b, loose) > 0;
17538 function lt(a, b, loose) {
17539 return compare(a, b, loose) < 0;
17544 function eq(a, b, loose) {
17545 return compare(a, b, loose) === 0;
17550 function neq(a, b, loose) {
17551 return compare(a, b, loose) !== 0;
17556 function gte(a, b, loose) {
17557 return compare(a, b, loose) >= 0;
17562 function lte(a, b, loose) {
17563 return compare(a, b, loose) <= 0;
17568 function cmp(a, op, b, loose) {
17571 if (typeof a === 'object') a = a.version;
17572 if (typeof b === 'object') b = b.version;
17576 if (typeof a === 'object') a = a.version;
17577 if (typeof b === 'object') b = b.version;
17583 return eq(a, b, loose);
17586 return neq(a, b, loose);
17589 return gt(a, b, loose);
17592 return gte(a, b, loose);
17595 return lt(a, b, loose);
17598 return lte(a, b, loose);
17601 throw new TypeError('Invalid operator: ' + op);
17605 exports.Comparator = Comparator;
17607 function Comparator(comp, options) {
17608 if (!options || typeof options !== 'object') {
17611 includePrerelease: false
17615 if (comp instanceof Comparator) {
17616 if (comp.loose === !!options.loose) {
17623 if (!(this instanceof Comparator)) {
17624 return new Comparator(comp, options);
17627 debug('comparator', comp, options);
17628 this.options = options;
17629 this.loose = !!options.loose;
17632 if (this.semver === ANY) {
17635 this.value = this.operator + this.semver.version;
17638 debug('comp', this);
17643 Comparator.prototype.parse = function (comp) {
17644 var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
17645 var m = comp.match(r);
17648 throw new TypeError('Invalid comparator: ' + comp);
17651 this.operator = m[1];
17653 if (this.operator === '=') {
17654 this.operator = '';
17655 } // if it literally is just '>' or '' then allow anything.
17661 this.semver = new SemVer(m[2], this.options.loose);
17665 Comparator.prototype.toString = function () {
17669 Comparator.prototype.test = function (version) {
17670 debug('Comparator.test', version, this.options.loose);
17672 if (this.semver === ANY) {
17676 if (typeof version === 'string') {
17677 version = new SemVer(version, this.options);
17680 return cmp(version, this.operator, this.semver, this.options);
17683 Comparator.prototype.intersects = function (comp, options) {
17684 if (!(comp instanceof Comparator)) {
17685 throw new TypeError('a Comparator is required');
17688 if (!options || typeof options !== 'object') {
17691 includePrerelease: false
17697 if (this.operator === '') {
17698 rangeTmp = new Range(comp.value, options);
17699 return satisfies(this.value, rangeTmp, options);
17700 } else if (comp.operator === '') {
17701 rangeTmp = new Range(this.value, options);
17702 return satisfies(comp.semver, rangeTmp, options);
17705 var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>');
17706 var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<');
17707 var sameSemVer = this.semver.version === comp.semver.version;
17708 var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=');
17709 var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<');
17710 var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>');
17711 return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
17714 exports.Range = Range;
17716 function Range(range, options) {
17717 if (!options || typeof options !== 'object') {
17720 includePrerelease: false
17724 if (range instanceof Range) {
17725 if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
17728 return new Range(range.raw, options);
17732 if (range instanceof Comparator) {
17733 return new Range(range.value, options);
17736 if (!(this instanceof Range)) {
17737 return new Range(range, options);
17740 this.options = options;
17741 this.loose = !!options.loose;
17742 this.includePrerelease = !!options.includePrerelease; // First, split based on boolean or ||
17745 this.set = range.split(/\s*\|\|\s*/).map(function (range) {
17746 return this.parseRange(range.trim());
17747 }, this).filter(function (c) {
17748 // throw out any that are not relevant for whatever reason
17752 if (!this.set.length) {
17753 throw new TypeError('Invalid SemVer Range: ' + range);
17759 Range.prototype.format = function () {
17760 this.range = this.set.map(function (comps) {
17761 return comps.join(' ').trim();
17762 }).join('||').trim();
17766 Range.prototype.toString = function () {
17770 Range.prototype.parseRange = function (range) {
17771 var loose = this.options.loose;
17772 range = range.trim(); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
17774 var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];
17775 range = range.replace(hr, hyphenReplace);
17776 debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
17778 range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);
17779 debug('comparator trim', range, re[COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3`
17781 range = range.replace(re[TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3`
17783 range = range.replace(re[CARETTRIM], caretTrimReplace); // normalize spaces
17785 range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and
17786 // ready to be split into comparators.
17788 var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
17789 var set = range.split(' ').map(function (comp) {
17790 return parseComparator(comp, this.options);
17791 }, this).join(' ').split(/\s+/);
17793 if (this.options.loose) {
17794 // in loose mode, throw out any that are not valid comparators
17795 set = set.filter(function (comp) {
17796 return !!comp.match(compRe);
17800 set = set.map(function (comp) {
17801 return new Comparator(comp, this.options);
17806 Range.prototype.intersects = function (range, options) {
17807 if (!(range instanceof Range)) {
17808 throw new TypeError('a Range is required');
17811 return this.set.some(function (thisComparators) {
17812 return thisComparators.every(function (thisComparator) {
17813 return range.set.some(function (rangeComparators) {
17814 return rangeComparators.every(function (rangeComparator) {
17815 return thisComparator.intersects(rangeComparator, options);
17820 }; // Mostly just for testing and legacy API reasons
17823 exports.toComparators = toComparators;
17825 function toComparators(range, options) {
17826 return new Range(range, options).set.map(function (comp) {
17827 return comp.map(function (c) {
17829 }).join(' ').trim().split(' ');
17831 } // comprised of xranges, tildes, stars, and gtlt's at this point.
17832 // already replaced the hyphen ranges
17833 // turn into a set of JUST comparators.
17836 function parseComparator(comp, options) {
17837 debug('comp', comp, options);
17838 comp = replaceCarets(comp, options);
17839 debug('caret', comp);
17840 comp = replaceTildes(comp, options);
17841 debug('tildes', comp);
17842 comp = replaceXRanges(comp, options);
17843 debug('xrange', comp);
17844 comp = replaceStars(comp, options);
17845 debug('stars', comp);
17850 return !id || id.toLowerCase() === 'x' || id === '*';
17851 } // ~, ~> --> * (any, kinda silly)
17852 // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
17853 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
17854 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
17855 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
17856 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
17859 function replaceTildes(comp, options) {
17860 return comp.trim().split(/\s+/).map(function (comp) {
17861 return replaceTilde(comp, options);
17865 function replaceTilde(comp, options) {
17866 var r = options.loose ? re[TILDELOOSE] : re[TILDE];
17867 return comp.replace(r, function (_, M, m, p, pr) {
17868 debug('tilde', comp, _, M, m, p, pr);
17873 } else if (isX(m)) {
17874 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
17875 } else if (isX(p)) {
17876 // ~1.2 == >=1.2.0 <1.3.0
17877 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
17879 debug('replaceTilde pr', pr);
17880 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0';
17882 // ~1.2.3 == >=1.2.3 <1.3.0
17883 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
17886 debug('tilde return', ret);
17889 } // ^ --> * (any, kinda silly)
17890 // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
17891 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
17892 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
17893 // ^1.2.3 --> >=1.2.3 <2.0.0
17894 // ^1.2.0 --> >=1.2.0 <2.0.0
17897 function replaceCarets(comp, options) {
17898 return comp.trim().split(/\s+/).map(function (comp) {
17899 return replaceCaret(comp, options);
17903 function replaceCaret(comp, options) {
17904 debug('caret', comp, options);
17905 var r = options.loose ? re[CARETLOOSE] : re[CARET];
17906 return comp.replace(r, function (_, M, m, p, pr) {
17907 debug('caret', comp, _, M, m, p, pr);
17912 } else if (isX(m)) {
17913 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
17914 } else if (isX(p)) {
17916 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
17918 ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
17921 debug('replaceCaret pr', pr);
17925 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1);
17927 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0';
17930 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0';
17937 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1);
17939 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
17942 ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0';
17946 debug('caret return', ret);
17951 function replaceXRanges(comp, options) {
17952 debug('replaceXRanges', comp, options);
17953 return comp.split(/\s+/).map(function (comp) {
17954 return replaceXRange(comp, options);
17958 function replaceXRange(comp, options) {
17959 comp = comp.trim();
17960 var r = options.loose ? re[XRANGELOOSE] : re[XRANGE];
17961 return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
17962 debug('xRange', comp, ret, gtlt, M, m, p, pr);
17964 var xm = xM || isX(m);
17965 var xp = xm || isX(p);
17968 if (gtlt === '=' && anyX) {
17973 if (gtlt === '>' || gtlt === '<') {
17974 // nothing is allowed
17977 // nothing is forbidden
17980 } else if (gtlt && anyX) {
17981 // we know patch is an x, because we have any x at all.
17982 // replace X with 0
17989 if (gtlt === '>') {
17992 // >1.2.3 => >= 1.2.4
18003 } else if (gtlt === '<=') {
18004 // <=0.7.x is actually <0.8.0, since any 0.7.x should
18005 // pass. Similarly, <=7.x is actually <8.0.0, etc.
18015 ret = gtlt + M + '.' + m + '.' + p;
18017 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
18019 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
18022 debug('xRange return', ret);
18025 } // Because * is AND-ed with everything else in the comparator,
18026 // and '' means "any version", just remove the *s entirely.
18029 function replaceStars(comp, options) {
18030 debug('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets!
18032 return comp.trim().replace(re[STAR], '');
18033 } // This function is passed to string.replace(re[HYPHENRANGE])
18034 // M, m, patch, prerelease, build
18035 // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
18036 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
18037 // 1.2 - 3.4 => >=1.2.0 <3.5.0
18040 function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
18043 } else if (isX(fm)) {
18044 from = '>=' + fM + '.0.0';
18045 } else if (isX(fp)) {
18046 from = '>=' + fM + '.' + fm + '.0';
18048 from = '>=' + from;
18053 } else if (isX(tm)) {
18054 to = '<' + (+tM + 1) + '.0.0';
18055 } else if (isX(tp)) {
18056 to = '<' + tM + '.' + (+tm + 1) + '.0';
18058 to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;
18063 return (from + ' ' + to).trim();
18064 } // if ANY of the sets match ALL of its comparators, then pass
18067 Range.prototype.test = function (version) {
18072 if (typeof version === 'string') {
18073 version = new SemVer(version, this.options);
18076 for (var i = 0; i < this.set.length; i++) {
18077 if (testSet(this.set[i], version, this.options)) {
18085 function testSet(set, version, options) {
18086 for (var i = 0; i < set.length; i++) {
18087 if (!set[i].test(version)) {
18092 if (version.prerelease.length && !options.includePrerelease) {
18093 // Find the set of versions that are allowed to have prereleases
18094 // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
18095 // That should allow `1.2.3-pr.2` to pass.
18096 // However, `1.2.4-alpha.notready` should NOT be allowed,
18097 // even though it's within the range set by the comparators.
18098 for (i = 0; i < set.length; i++) {
18099 debug(set[i].semver);
18101 if (set[i].semver === ANY) {
18105 if (set[i].semver.prerelease.length > 0) {
18106 var allowed = set[i].semver;
18108 if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
18112 } // Version has a -pre, but it's not one of the ones we like.
18121 exports.satisfies = satisfies;
18123 function satisfies(version, range, options) {
18125 range = new Range(range, options);
18130 return range.test(version);
18133 exports.maxSatisfying = maxSatisfying;
18135 function maxSatisfying(versions, range, options) {
18140 var rangeObj = new Range(range, options);
18145 versions.forEach(function (v) {
18146 if (rangeObj.test(v)) {
18147 // satisfies(v, range, options)
18148 if (!max || maxSV.compare(v) === -1) {
18149 // compare(max, v, true)
18151 maxSV = new SemVer(max, options);
18158 exports.minSatisfying = minSatisfying;
18160 function minSatisfying(versions, range, options) {
18165 var rangeObj = new Range(range, options);
18170 versions.forEach(function (v) {
18171 if (rangeObj.test(v)) {
18172 // satisfies(v, range, options)
18173 if (!min || minSV.compare(v) === 1) {
18174 // compare(min, v, true)
18176 minSV = new SemVer(min, options);
18183 exports.minVersion = minVersion;
18185 function minVersion(range, loose) {
18186 range = new Range(range, loose);
18187 var minver = new SemVer('0.0.0');
18189 if (range.test(minver)) {
18193 minver = new SemVer('0.0.0-0');
18195 if (range.test(minver)) {
18201 for (var i = 0; i < range.set.length; ++i) {
18202 var comparators = range.set[i];
18203 comparators.forEach(function (comparator) {
18204 // Clone to avoid manipulating the comparator's semver object.
18205 var compver = new SemVer(comparator.semver.version);
18207 switch (comparator.operator) {
18209 if (compver.prerelease.length === 0) {
18212 compver.prerelease.push(0);
18215 compver.raw = compver.format();
18221 if (!minver || gt(minver, compver)) {
18229 /* Ignore maximum versions */
18232 /* istanbul ignore next */
18235 throw new Error('Unexpected operation: ' + comparator.operator);
18240 if (minver && range.test(minver)) {
18247 exports.validRange = validRange;
18249 function validRange(range, options) {
18251 // Return '*' instead of '' so that truthiness works.
18252 // This will throw if it's invalid anyway
18253 return new Range(range, options).range || '*';
18257 } // Determine if version is less than all the versions possible in the range
18262 function ltr(version, range, options) {
18263 return outside(version, range, '<', options);
18264 } // Determine if version is greater than all the versions possible in the range.
18269 function gtr(version, range, options) {
18270 return outside(version, range, '>', options);
18273 exports.outside = outside;
18275 function outside(version, range, hilo, options) {
18276 version = new SemVer(version, options);
18277 range = new Range(range, options);
18278 var gtfn, ltefn, ltfn, comp, ecomp;
18298 throw new TypeError('Must provide a hilo val of "<" or ">"');
18299 } // If it satisifes the range it is not outside
18302 if (satisfies(version, range, options)) {
18304 } // From now on, variable terms are as if we're in "gtr" mode.
18305 // but note that everything is flipped for the "ltr" function.
18308 for (var i = 0; i < range.set.length; ++i) {
18309 var comparators = range.set[i];
18312 comparators.forEach(function (comparator) {
18313 if (comparator.semver === ANY) {
18314 comparator = new Comparator('>=0.0.0');
18317 high = high || comparator;
18318 low = low || comparator;
18320 if (gtfn(comparator.semver, high.semver, options)) {
18322 } else if (ltfn(comparator.semver, low.semver, options)) {
18325 }); // If the edge version comparator has a operator then our version
18326 // isn't outside it
18328 if (high.operator === comp || high.operator === ecomp) {
18330 } // If the lowest version comparator has an operator and our version
18331 // is less than it then it isn't higher than the range
18334 if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
18336 } else if (low.operator === ecomp && ltfn(version, low.semver)) {
18344 exports.prerelease = prerelease;
18346 function prerelease(version, options) {
18347 var parsed = parse(version, options);
18348 return parsed && parsed.prerelease.length ? parsed.prerelease : null;
18351 exports.intersects = intersects;
18353 function intersects(r1, r2, options) {
18354 r1 = new Range(r1, options);
18355 r2 = new Range(r2, options);
18356 return r1.intersects(r2);
18359 exports.coerce = coerce;
18361 function coerce(version) {
18362 if (version instanceof SemVer) {
18366 if (typeof version !== 'string') {
18370 var match = version.match(re[COERCE]);
18372 if (match == null) {
18376 return parse(match[1] + '.' + (match[2] || '0') + '.' + (match[3] || '0'));
18379 var semver_1 = semver$2.SEMVER_SPEC_VERSION;
18380 var semver_2 = semver$2.re;
18381 var semver_3 = semver$2.src;
18382 var semver_4 = semver$2.parse;
18383 var semver_5 = semver$2.valid;
18384 var semver_6 = semver$2.clean;
18385 var semver_7 = semver$2.SemVer;
18386 var semver_8 = semver$2.inc;
18387 var semver_9 = semver$2.diff;
18388 var semver_10 = semver$2.compareIdentifiers;
18389 var semver_11 = semver$2.rcompareIdentifiers;
18390 var semver_12 = semver$2.major;
18391 var semver_13 = semver$2.minor;
18392 var semver_14 = semver$2.patch;
18393 var semver_15 = semver$2.compare;
18394 var semver_16 = semver$2.compareLoose;
18395 var semver_17 = semver$2.rcompare;
18396 var semver_18 = semver$2.sort;
18397 var semver_19 = semver$2.rsort;
18398 var semver_20 = semver$2.gt;
18399 var semver_21 = semver$2.lt;
18400 var semver_22 = semver$2.eq;
18401 var semver_23 = semver$2.neq;
18402 var semver_24 = semver$2.gte;
18403 var semver_25 = semver$2.lte;
18404 var semver_26 = semver$2.cmp;
18405 var semver_27 = semver$2.Comparator;
18406 var semver_28 = semver$2.Range;
18407 var semver_29 = semver$2.toComparators;
18408 var semver_30 = semver$2.satisfies;
18409 var semver_31 = semver$2.maxSatisfying;
18410 var semver_32 = semver$2.minSatisfying;
18411 var semver_33 = semver$2.minVersion;
18412 var semver_34 = semver$2.validRange;
18413 var semver_35 = semver$2.ltr;
18414 var semver_36 = semver$2.gtr;
18415 var semver_37 = semver$2.outside;
18416 var semver_38 = semver$2.prerelease;
18417 var semver_39 = semver$2.intersects;
18418 var semver_40 = semver$2.coerce;
18420 var hasOwnProperty = Object.prototype.hasOwnProperty;
18421 var pseudomap = PseudoMap;
18423 function PseudoMap(set) {
18424 if (!(this instanceof PseudoMap)) // whyyyyyyy
18425 throw new TypeError("Constructor PseudoMap requires 'new'");
18429 if (set instanceof PseudoMap || typeof Map === 'function' && set instanceof Map) set.forEach(function (value, key) {
18430 this.set(key, value);
18431 }, this);else if (Array.isArray(set)) set.forEach(function (kv) {
18432 this.set(kv[0], kv[1]);
18433 }, this);else throw new TypeError('invalid argument');
18437 PseudoMap.prototype.forEach = function (fn, thisp) {
18438 thisp = thisp || this;
18439 Object.keys(this._data).forEach(function (k) {
18440 if (k !== 'size') fn.call(thisp, this._data[k].value, this._data[k].key);
18444 PseudoMap.prototype.has = function (k) {
18445 return !!find(this._data, k);
18448 PseudoMap.prototype.get = function (k) {
18449 var res = find(this._data, k);
18450 return res && res.value;
18453 PseudoMap.prototype.set = function (k, v) {
18454 set(this._data, k, v);
18457 PseudoMap.prototype.delete = function (k) {
18458 var res = find(this._data, k);
18461 delete this._data[res._index];
18466 PseudoMap.prototype.clear = function () {
18467 var data = Object.create(null);
18469 Object.defineProperty(this, '_data', {
18472 configurable: true,
18477 Object.defineProperty(PseudoMap.prototype, 'size', {
18479 return this._data.size;
18481 set: function (n) {},
18486 PseudoMap.prototype.values = PseudoMap.prototype.keys = PseudoMap.prototype.entries = function () {
18487 throw new Error('iterators are not implemented in this version');
18488 }; // Either identical, or both NaN
18491 function same(a, b) {
18492 return a === b || a !== a && b !== b;
18495 function Entry(k, v, i) {
18501 function find(data, k) {
18502 for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) {
18503 if (same(data[key].key, k)) return data[key];
18507 function set(data, k, v) {
18508 for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) {
18509 if (same(data[key].key, k)) {
18510 data[key].value = v;
18516 data[key] = new Entry(k, v, key);
18519 var map = createCommonjsModule(function (module) {
18520 if (process.env.npm_package_name === 'pseudomap' && process.env.npm_lifecycle_script === 'test') process.env.TEST_PSEUDOMAP = 'true';
18522 if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) {
18523 module.exports = Map;
18525 module.exports = pseudomap;
18529 var yallist = Yallist;
18530 Yallist.Node = Node;
18531 Yallist.create = Yallist;
18533 function Yallist(list) {
18536 if (!(self instanceof Yallist)) {
18537 self = new Yallist();
18544 if (list && typeof list.forEach === 'function') {
18545 list.forEach(function (item) {
18548 } else if (arguments.length > 0) {
18549 for (var i = 0, l = arguments.length; i < l; i++) {
18550 self.push(arguments[i]);
18557 Yallist.prototype.removeNode = function (node) {
18558 if (node.list !== this) {
18559 throw new Error('removing node which does not belong to this list');
18562 var next = node.next;
18563 var prev = node.prev;
18573 if (node === this.head) {
18577 if (node === this.tail) {
18581 node.list.length--;
18587 Yallist.prototype.unshiftNode = function (node) {
18588 if (node === this.head) {
18593 node.list.removeNode(node);
18596 var head = this.head;
18613 Yallist.prototype.pushNode = function (node) {
18614 if (node === this.tail) {
18619 node.list.removeNode(node);
18622 var tail = this.tail;
18639 Yallist.prototype.push = function () {
18640 for (var i = 0, l = arguments.length; i < l; i++) {
18641 push(this, arguments[i]);
18644 return this.length;
18647 Yallist.prototype.unshift = function () {
18648 for (var i = 0, l = arguments.length; i < l; i++) {
18649 unshift(this, arguments[i]);
18652 return this.length;
18655 Yallist.prototype.pop = function () {
18660 var res = this.tail.value;
18661 this.tail = this.tail.prev;
18664 this.tail.next = null;
18673 Yallist.prototype.shift = function () {
18678 var res = this.head.value;
18679 this.head = this.head.next;
18682 this.head.prev = null;
18691 Yallist.prototype.forEach = function (fn, thisp) {
18692 thisp = thisp || this;
18694 for (var walker = this.head, i = 0; walker !== null; i++) {
18695 fn.call(thisp, walker.value, i, this);
18696 walker = walker.next;
18700 Yallist.prototype.forEachReverse = function (fn, thisp) {
18701 thisp = thisp || this;
18703 for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
18704 fn.call(thisp, walker.value, i, this);
18705 walker = walker.prev;
18709 Yallist.prototype.get = function (n) {
18710 for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
18711 // abort out of the list early if we hit a cycle
18712 walker = walker.next;
18715 if (i === n && walker !== null) {
18716 return walker.value;
18720 Yallist.prototype.getReverse = function (n) {
18721 for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
18722 // abort out of the list early if we hit a cycle
18723 walker = walker.prev;
18726 if (i === n && walker !== null) {
18727 return walker.value;
18731 Yallist.prototype.map = function (fn, thisp) {
18732 thisp = thisp || this;
18733 var res = new Yallist();
18735 for (var walker = this.head; walker !== null;) {
18736 res.push(fn.call(thisp, walker.value, this));
18737 walker = walker.next;
18743 Yallist.prototype.mapReverse = function (fn, thisp) {
18744 thisp = thisp || this;
18745 var res = new Yallist();
18747 for (var walker = this.tail; walker !== null;) {
18748 res.push(fn.call(thisp, walker.value, this));
18749 walker = walker.prev;
18755 Yallist.prototype.reduce = function (fn, initial) {
18757 var walker = this.head;
18759 if (arguments.length > 1) {
18761 } else if (this.head) {
18762 walker = this.head.next;
18763 acc = this.head.value;
18765 throw new TypeError('Reduce of empty list with no initial value');
18768 for (var i = 0; walker !== null; i++) {
18769 acc = fn(acc, walker.value, i);
18770 walker = walker.next;
18776 Yallist.prototype.reduceReverse = function (fn, initial) {
18778 var walker = this.tail;
18780 if (arguments.length > 1) {
18782 } else if (this.tail) {
18783 walker = this.tail.prev;
18784 acc = this.tail.value;
18786 throw new TypeError('Reduce of empty list with no initial value');
18789 for (var i = this.length - 1; walker !== null; i--) {
18790 acc = fn(acc, walker.value, i);
18791 walker = walker.prev;
18797 Yallist.prototype.toArray = function () {
18798 var arr = new Array(this.length);
18800 for (var i = 0, walker = this.head; walker !== null; i++) {
18801 arr[i] = walker.value;
18802 walker = walker.next;
18808 Yallist.prototype.toArrayReverse = function () {
18809 var arr = new Array(this.length);
18811 for (var i = 0, walker = this.tail; walker !== null; i++) {
18812 arr[i] = walker.value;
18813 walker = walker.prev;
18819 Yallist.prototype.slice = function (from, to) {
18820 to = to || this.length;
18829 from += this.length;
18832 var ret = new Yallist();
18834 if (to < from || to < 0) {
18842 if (to > this.length) {
18846 for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
18847 walker = walker.next;
18850 for (; walker !== null && i < to; i++, walker = walker.next) {
18851 ret.push(walker.value);
18857 Yallist.prototype.sliceReverse = function (from, to) {
18858 to = to || this.length;
18867 from += this.length;
18870 var ret = new Yallist();
18872 if (to < from || to < 0) {
18880 if (to > this.length) {
18884 for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
18885 walker = walker.prev;
18888 for (; walker !== null && i > from; i--, walker = walker.prev) {
18889 ret.push(walker.value);
18895 Yallist.prototype.reverse = function () {
18896 var head = this.head;
18897 var tail = this.tail;
18899 for (var walker = head; walker !== null; walker = walker.prev) {
18900 var p = walker.prev;
18901 walker.prev = walker.next;
18910 function push(self, item) {
18911 self.tail = new Node(item, self.tail, null, self);
18914 self.head = self.tail;
18920 function unshift(self, item) {
18921 self.head = new Node(item, null, self.head, self);
18924 self.tail = self.head;
18930 function Node(value, prev, next, list) {
18931 if (!(this instanceof Node)) {
18932 return new Node(value, prev, next, list);
18936 this.value = value;
18953 var lruCache = LRUCache; // This will be a proper iterable 'Map' in engines that support it,
18954 // or a fakey-fake PseudoMap in older versions.
18955 // A linked list to keep track of recently-used-ness
18956 // use symbols if possible, otherwise just _props
18958 var hasSymbol = typeof Symbol === 'function' && process.env._nodeLRUCacheForceNoSymbol !== '1';
18962 makeSymbol = function (key) {
18963 return Symbol(key);
18966 makeSymbol = function (key) {
18971 var MAX = makeSymbol('max');
18972 var LENGTH = makeSymbol('length');
18973 var LENGTH_CALCULATOR = makeSymbol('lengthCalculator');
18974 var ALLOW_STALE = makeSymbol('allowStale');
18975 var MAX_AGE = makeSymbol('maxAge');
18976 var DISPOSE = makeSymbol('dispose');
18977 var NO_DISPOSE_ON_SET = makeSymbol('noDisposeOnSet');
18978 var LRU_LIST = makeSymbol('lruList');
18979 var CACHE = makeSymbol('cache');
18981 function naiveLength() {
18983 } // lruList is a yallist where the head is the youngest
18984 // item, and the tail is the oldest. the list contains the Hit
18985 // objects as the entries.
18986 // Each Hit object has a reference to its Yallist.Node. This
18989 // cache is a Map (or PseudoMap) that matches the keys to
18990 // the Yallist.Node object.
18993 function LRUCache(options) {
18994 if (!(this instanceof LRUCache)) {
18995 return new LRUCache(options);
18998 if (typeof options === 'number') {
19008 var max = this[MAX] = options.max; // Kind of weird to have a default max of Infinity, but oh well.
19010 if (!max || !(typeof max === 'number') || max <= 0) {
19011 this[MAX] = Infinity;
19014 var lc = options.length || naiveLength;
19016 if (typeof lc !== 'function') {
19020 this[LENGTH_CALCULATOR] = lc;
19021 this[ALLOW_STALE] = options.stale || false;
19022 this[MAX_AGE] = options.maxAge || 0;
19023 this[DISPOSE] = options.dispose;
19024 this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
19026 } // resize the cache when the max changes.
19029 Object.defineProperty(LRUCache.prototype, 'max', {
19030 set: function (mL) {
19031 if (!mL || !(typeof mL === 'number') || mL <= 0) {
19043 Object.defineProperty(LRUCache.prototype, 'allowStale', {
19044 set: function (allowStale) {
19045 this[ALLOW_STALE] = !!allowStale;
19048 return this[ALLOW_STALE];
19052 Object.defineProperty(LRUCache.prototype, 'maxAge', {
19053 set: function (mA) {
19054 if (!mA || !(typeof mA === 'number') || mA < 0) {
19058 this[MAX_AGE] = mA;
19062 return this[MAX_AGE];
19065 }); // resize the cache when the lengthCalculator changes.
19067 Object.defineProperty(LRUCache.prototype, 'lengthCalculator', {
19068 set: function (lC) {
19069 if (typeof lC !== 'function') {
19073 if (lC !== this[LENGTH_CALCULATOR]) {
19074 this[LENGTH_CALCULATOR] = lC;
19076 this[LRU_LIST].forEach(function (hit) {
19077 hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
19078 this[LENGTH] += hit.length;
19085 return this[LENGTH_CALCULATOR];
19089 Object.defineProperty(LRUCache.prototype, 'length', {
19091 return this[LENGTH];
19095 Object.defineProperty(LRUCache.prototype, 'itemCount', {
19097 return this[LRU_LIST].length;
19102 LRUCache.prototype.rforEach = function (fn, thisp) {
19103 thisp = thisp || this;
19105 for (var walker = this[LRU_LIST].tail; walker !== null;) {
19106 var prev = walker.prev;
19107 forEachStep(this, fn, walker, thisp);
19112 function forEachStep(self, fn, node, thisp) {
19113 var hit = node.value;
19115 if (isStale(self, hit)) {
19118 if (!self[ALLOW_STALE]) {
19124 fn.call(thisp, hit.value, hit.key, self);
19128 LRUCache.prototype.forEach = function (fn, thisp) {
19129 thisp = thisp || this;
19131 for (var walker = this[LRU_LIST].head; walker !== null;) {
19132 var next = walker.next;
19133 forEachStep(this, fn, walker, thisp);
19138 LRUCache.prototype.keys = function () {
19139 return this[LRU_LIST].toArray().map(function (k) {
19144 LRUCache.prototype.values = function () {
19145 return this[LRU_LIST].toArray().map(function (k) {
19150 LRUCache.prototype.reset = function () {
19151 if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) {
19152 this[LRU_LIST].forEach(function (hit) {
19153 this[DISPOSE](hit.key, hit.value);
19157 this[CACHE] = new map(); // hash of items by key
19159 this[LRU_LIST] = new yallist(); // list of items in order of use recency
19161 this[LENGTH] = 0; // length of items in the list
19164 LRUCache.prototype.dump = function () {
19165 return this[LRU_LIST].map(function (hit) {
19166 if (!isStale(this, hit)) {
19170 e: hit.now + (hit.maxAge || 0)
19173 }, this).toArray().filter(function (h) {
19178 LRUCache.prototype.dumpLru = function () {
19179 return this[LRU_LIST];
19181 /* istanbul ignore next */
19184 LRUCache.prototype.inspect = function (n, opts) {
19185 var str = 'LRUCache {';
19186 var extras = false;
19187 var as = this[ALLOW_STALE];
19190 str += '\n allowStale: true';
19194 var max = this[MAX];
19196 if (max && max !== Infinity) {
19201 str += '\n max: ' + util$4.inspect(max, opts);
19205 var maxAge = this[MAX_AGE];
19212 str += '\n maxAge: ' + util$4.inspect(maxAge, opts);
19216 var lc = this[LENGTH_CALCULATOR];
19218 if (lc && lc !== naiveLength) {
19223 str += '\n length: ' + util$4.inspect(this[LENGTH], opts);
19227 var didFirst = false;
19228 this[LRU_LIST].forEach(function (item) {
19240 var key = util$4.inspect(item.key).split('\n').join('\n ');
19245 if (item.maxAge !== maxAge) {
19246 val.maxAge = item.maxAge;
19249 if (lc !== naiveLength) {
19250 val.length = item.length;
19253 if (isStale(this, item)) {
19257 val = util$4.inspect(val, opts).split('\n').join('\n ');
19258 str += key + ' => ' + val;
19261 if (didFirst || extras) {
19269 LRUCache.prototype.set = function (key, value, maxAge) {
19270 maxAge = maxAge || this[MAX_AGE];
19271 var now = maxAge ? Date.now() : 0;
19272 var len = this[LENGTH_CALCULATOR](value, key);
19274 if (this[CACHE].has(key)) {
19275 if (len > this[MAX]) {
19276 del(this, this[CACHE].get(key));
19280 var node = this[CACHE].get(key);
19281 var item = node.value; // dispose of the old one before overwriting
19282 // split out into 2 ifs for better coverage tracking
19284 if (this[DISPOSE]) {
19285 if (!this[NO_DISPOSE_ON_SET]) {
19286 this[DISPOSE](key, item.value);
19291 item.maxAge = maxAge;
19292 item.value = value;
19293 this[LENGTH] += len - item.length;
19300 var hit = new Entry$1(key, value, len, now, maxAge); // oversized objects fall out of cache automatically.
19302 if (hit.length > this[MAX]) {
19303 if (this[DISPOSE]) {
19304 this[DISPOSE](key, value);
19310 this[LENGTH] += hit.length;
19311 this[LRU_LIST].unshift(hit);
19312 this[CACHE].set(key, this[LRU_LIST].head);
19317 LRUCache.prototype.has = function (key) {
19318 if (!this[CACHE].has(key)) return false;
19319 var hit = this[CACHE].get(key).value;
19321 if (isStale(this, hit)) {
19328 LRUCache.prototype.get = function (key) {
19329 return get(this, key, true);
19332 LRUCache.prototype.peek = function (key) {
19333 return get(this, key, false);
19336 LRUCache.prototype.pop = function () {
19337 var node = this[LRU_LIST].tail;
19338 if (!node) return null;
19343 LRUCache.prototype.del = function (key) {
19344 del(this, this[CACHE].get(key));
19347 LRUCache.prototype.load = function (arr) {
19350 var now = Date.now(); // A previous serialized cache has the most recent items first
19352 for (var l = arr.length - 1; l >= 0; l--) {
19354 var expiresAt = hit.e || 0;
19356 if (expiresAt === 0) {
19357 // the item was created without expiration in a non aged cache
19358 this.set(hit.k, hit.v);
19360 var maxAge = expiresAt - now; // dont add already expired items
19363 this.set(hit.k, hit.v, maxAge);
19369 LRUCache.prototype.prune = function () {
19371 this[CACHE].forEach(function (value, key) {
19372 get(self, key, false);
19376 function get(self, key, doUse) {
19377 var node = self[CACHE].get(key);
19380 var hit = node.value;
19382 if (isStale(self, hit)) {
19384 if (!self[ALLOW_STALE]) hit = undefined;
19387 self[LRU_LIST].unshiftNode(node);
19391 if (hit) hit = hit.value;
19397 function isStale(self, hit) {
19398 if (!hit || !hit.maxAge && !self[MAX_AGE]) {
19403 var diff = Date.now() - hit.now;
19406 stale = diff > hit.maxAge;
19408 stale = self[MAX_AGE] && diff > self[MAX_AGE];
19414 function trim$2(self) {
19415 if (self[LENGTH] > self[MAX]) {
19416 for (var walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) {
19417 // We know that we're about to delete this one, and also
19418 // what the next least recently used key will be, so just
19419 // go ahead and set it now.
19420 var prev = walker.prev;
19427 function del(self, node) {
19429 var hit = node.value;
19431 if (self[DISPOSE]) {
19432 self[DISPOSE](hit.key, hit.value);
19435 self[LENGTH] -= hit.length;
19436 self[CACHE].delete(hit.key);
19437 self[LRU_LIST].removeNode(node);
19439 } // classy, since V8 prefers predictable objects.
19442 function Entry$1(key, value, length, now, maxAge) {
19444 this.value = value;
19445 this.length = length;
19447 this.maxAge = maxAge || 0;
19450 var sigmund_1 = sigmund;
19452 function sigmund(subject, maxSessions) {
19453 maxSessions = maxSessions || 10;
19458 function psychoAnalyze(subject, session) {
19459 if (session > maxSessions) return;
19461 if (typeof subject === 'function' || typeof subject === 'undefined') {
19465 if (typeof subject !== 'object' || !subject || subject instanceof RE) {
19466 analysis += subject;
19470 if (notes.indexOf(subject) !== -1 || session === maxSessions) return;
19471 notes.push(subject);
19473 Object.keys(subject).forEach(function (issue, _, __) {
19474 // pseudo-private values. skip those.
19475 if (issue.charAt(0) === '_') return;
19476 var to = typeof subject[issue];
19477 if (to === 'function' || to === 'undefined') return;
19479 psychoAnalyze(subject[issue], session + 1);
19483 psychoAnalyze(subject, 0);
19485 } // vim: set softtabstop=4 shiftwidth=4:
19487 var fnmatch = createCommonjsModule(function (module, exports) {
19488 // Based on minimatch.js by isaacs <https://npmjs.org/package/minimatch>
19489 var platform = typeof process === "object" ? process.platform : "win32";
19490 if (module) module.exports = minimatch;else exports.minimatch = minimatch;
19491 minimatch.Minimatch = Minimatch;
19492 var cache = minimatch.cache = new lruCache({
19495 GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
19496 var qmark = "[^/]" // * => any number of characters
19498 star = qmark + "*?" // ** when dots are allowed. Anything goes, except .. and .
19499 // not (^ or / followed by one or two dots followed by $ or /),
19500 // followed by anything, any number of times.
19502 twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" // not a ^ or / followed by a dot,
19503 // followed by anything, any number of times.
19505 twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" // characters that need to be escaped in RegExp.
19507 reSpecials = charSet("().*{}+?[]^$\\!"); // "abc" -> { a:true, b:true, c:true }
19509 function charSet(s) {
19510 return s.split("").reduce(function (set, c) {
19514 } // normalizes slashes.
19517 var slashSplit = /\/+/;
19518 minimatch.monkeyPatch = monkeyPatch;
19520 function monkeyPatch() {
19521 var desc = Object.getOwnPropertyDescriptor(String.prototype, "match");
19522 var orig = desc.value;
19524 desc.value = function (p) {
19525 if (p instanceof Minimatch) return p.match(this);
19526 return orig.call(this, p);
19529 Object.defineProperty(String.prototype, desc);
19532 minimatch.filter = filter;
19534 function filter(pattern, options) {
19535 options = options || {};
19536 return function (p, i, list) {
19537 return minimatch(p, pattern, options);
19541 function ext(a, b) {
19545 Object.keys(b).forEach(function (k) {
19548 Object.keys(a).forEach(function (k) {
19554 minimatch.defaults = function (def) {
19555 if (!def || !Object.keys(def).length) return minimatch;
19556 var orig = minimatch;
19558 var m = function minimatch(p, pattern, options) {
19559 return orig.minimatch(p, pattern, ext(def, options));
19562 m.Minimatch = function Minimatch(pattern, options) {
19563 return new orig.Minimatch(pattern, ext(def, options));
19569 Minimatch.defaults = function (def) {
19570 if (!def || !Object.keys(def).length) return Minimatch;
19571 return minimatch.defaults(def).Minimatch;
19574 function minimatch(p, pattern, options) {
19575 if (typeof pattern !== "string") {
19576 throw new TypeError("glob pattern string required");
19579 if (!options) options = {}; // shortcut: comments match nothing.
19581 if (!options.nocomment && pattern.charAt(0) === "#") {
19583 } // "" only matches ""
19586 if (pattern.trim() === "") return p === "";
19587 return new Minimatch(pattern, options).match(p);
19590 function Minimatch(pattern, options) {
19591 if (!(this instanceof Minimatch)) {
19592 return new Minimatch(pattern, options, cache);
19595 if (typeof pattern !== "string") {
19596 throw new TypeError("glob pattern string required");
19599 if (!options) options = {}; // windows: need to use /, not \
19600 // On other platforms, \ is a valid (albeit bad) filename char.
19602 if (platform === "win32") {
19603 pattern = pattern.split("\\").join("/");
19605 // these things aren't particularly big, but walking down the string
19606 // and turning it into a regexp can get pretty costly.
19609 var cacheKey = pattern + "\n" + sigmund_1(options);
19610 var cached = minimatch.cache.get(cacheKey);
19611 if (cached) return cached;
19612 minimatch.cache.set(cacheKey, this);
19613 this.options = options;
19615 this.pattern = pattern;
19616 this.regexp = null;
19617 this.negate = false;
19618 this.comment = false;
19619 this.empty = false; // make the set of regexps etc.
19624 Minimatch.prototype.make = make;
19627 // don't do it more than once.
19628 if (this._made) return;
19629 var pattern = this.pattern;
19630 var options = this.options; // empty patterns and comments match nothing.
19632 if (!options.nocomment && pattern.charAt(0) === "#") {
19633 this.comment = true;
19640 } // step 1: figure out negation, etc.
19643 this.parseNegate(); // step 2: expand braces
19645 var set = this.globSet = this.braceExpand();
19646 if (options.debug) console.error(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion
19647 // matching patterns.
19648 // These will be regexps, except in the case of "**", which is
19649 // set to the GLOBSTAR object for globstar behavior,
19650 // and will not contain any / characters
19652 set = this.globParts = set.map(function (s) {
19653 return s.split(slashSplit);
19655 if (options.debug) console.error(this.pattern, set); // glob --> regexps
19657 set = set.map(function (s, si, set) {
19658 return s.map(this.parse, this);
19660 if (options.debug) console.error(this.pattern, set); // filter out everything that didn't compile properly.
19662 set = set.filter(function (s) {
19663 return -1 === s.indexOf(false);
19665 if (options.debug) console.error(this.pattern, set);
19669 Minimatch.prototype.parseNegate = parseNegate;
19671 function parseNegate() {
19672 var pattern = this.pattern,
19674 options = this.options,
19676 if (options.nonegate) return;
19678 for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) {
19683 if (negateOffset) this.pattern = pattern.substr(negateOffset);
19684 this.negate = negate;
19685 } // Brace expansion:
19686 // a{b,c}d -> abd acd
19687 // a{b,}c -> abc ac
19688 // a{0..3}d -> a0d a1d a2d a3d
19689 // a{b,c{d,e}f}g -> abg acdfg acefg
19690 // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
19692 // Invalid sets are not expanded.
19693 // a{2..}b -> a{2..}b
19697 minimatch.braceExpand = function (pattern, options) {
19698 return new Minimatch(pattern, options).braceExpand();
19701 Minimatch.prototype.braceExpand = braceExpand;
19703 function braceExpand(pattern, options) {
19704 options = options || this.options;
19705 pattern = typeof pattern === "undefined" ? this.pattern : pattern;
19707 if (typeof pattern === "undefined") {
19708 throw new Error("undefined pattern");
19711 if (options.nobrace || !pattern.match(/\{.*\}/)) {
19712 // shortcut. no need to expand.
19716 var escaping = false; // examples and comments refer to this crazy pattern:
19717 // a{b,c{d,e},{f,g}h}x{y,z}
19729 // everything before the first \{ is just a prefix.
19730 // So, we pluck that off, and work with the rest,
19731 // and then prepend it to everything we find.
19733 if (pattern.charAt(0) !== "{") {
19734 // console.error(pattern)
19737 for (var i = 0, l = pattern.length; i < l; i++) {
19738 var c = pattern.charAt(i); // console.error(i, c)
19741 escaping = !escaping;
19742 } else if (c === "{" && !escaping) {
19743 prefix = pattern.substr(0, i);
19746 } // actually no sets, all { were escaped.
19749 if (prefix === null) {
19750 // console.error("no sets")
19754 var tail = braceExpand(pattern.substr(i), options);
19755 return tail.map(function (t) {
19758 } // now we have something like:
19759 // {b,c{d,e},{f,g}h}x{y,z}
19760 // walk through the set, expanding each part, until
19761 // the set ends. then, we'll expand the suffix.
19762 // If the set only has a single member, then'll put the {} back
19763 // first, handle numeric sets, since they're easier
19766 var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/);
19769 // console.error("numset", numset[1], numset[2])
19770 var suf = braceExpand(pattern.substr(numset[0].length), options),
19771 start = +numset[1],
19773 inc = start > end ? -1 : 1,
19776 for (var i = start; i != end + inc; i += inc) {
19777 // append all the suffixes
19778 for (var ii = 0, ll = suf.length; ii < ll; ii++) {
19779 set.push(i + suf[ii]);
19784 } // ok, walk through the set
19785 // We hope, somewhat optimistically, that there
19786 // will be a } at the end.
19787 // If the closing brace isn't found, then the pattern is
19788 // interpreted as braceExpand("\\" + pattern) so that
19789 // the leading \{ will be interpreted literally.
19792 var i = 1 // skip the \{
19799 function addMember() {
19802 } // console.error("Entering for")
19805 FOR: for (i = 1, l = pattern.length; i < l; i++) {
19806 var c = pattern.charAt(i); // console.error("", i, c)
19810 member += "\\" + c;
19823 depth--; // if this closes the actual set, then we're done
19826 addMember(); // pluck off the close-brace
19852 // now we've either finished the set, and the suffix is
19853 // pattern.substr(i), or we have *not* closed the set,
19854 // and need to escape the leading brace
19858 // console.error("didn't close", pattern)
19859 return braceExpand("\\" + pattern, options);
19860 } // x{y,z} -> ["xy", "xz"]
19861 // console.error("set", set)
19862 // console.error("suffix", pattern.substr(i))
19865 var suf = braceExpand(pattern.substr(i), options); // ["b", "c{d,e}","{f,g}h"] ->
19866 // [["b"], ["cd", "ce"], ["fh", "gh"]]
19868 var addBraces = set.length === 1; // console.error("set pre-expanded", set)
19870 set = set.map(function (p) {
19871 return braceExpand(p, options);
19872 }); // console.error("set expanded", set)
19873 // [["b"], ["cd", "ce"], ["fh", "gh"]] ->
19874 // ["b", "cd", "ce", "fh", "gh"]
19876 set = set.reduce(function (l, r) {
19877 return l.concat(r);
19881 set = set.map(function (s) {
19882 return "{" + s + "}";
19884 } // now attach the suffixes.
19889 for (var i = 0, l = set.length; i < l; i++) {
19890 for (var ii = 0, ll = suf.length; ii < ll; ii++) {
19891 ret.push(set[i] + suf[ii]);
19896 } // parse a component of the expanded set.
19897 // At this point, no pattern may contain "/" in it
19898 // so we're going to return a 2d array, where each entry is the full
19899 // pattern, split on '/', and then turned into a regular expression.
19900 // A regexp is made at the end which joins each array with an
19901 // escaped /, and another full one which joins each regexp with |.
19903 // Following the lead of Bash 4.1, note that "**" only has special meaning
19904 // when it is the *only* thing in a path portion. Otherwise, any series
19905 // of * is equivalent to a single *. Globstar behavior is enabled by
19906 // default, and can be disabled by setting options.noglobstar.
19909 Minimatch.prototype.parse = parse;
19912 function parse(pattern, isSub) {
19913 var options = this.options; // shortcuts
19915 if (!options.noglobstar && pattern === "**") return GLOBSTAR;
19916 if (pattern === "") return "";
19918 hasMagic = !!options.nocase,
19919 escaping = false // ? => one single character
19921 patternListStack = [],
19926 classStart = -1 // . and .. never match anything that doesn't start with .,
19927 // even when options.dot is set.
19929 patternStart = pattern.charAt(0) === "." ? "" // anything
19930 // not (start or / followed by . or .. followed by / or end)
19931 : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" : "(?!\\.)";
19933 function clearStateChar() {
19935 // we had some state-tracking character
19936 // that wasn't consumed by this pass.
19937 switch (stateChar) {
19949 re += "\\" + stateChar;
19957 for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
19958 if (options.debug) {
19959 console.error("%s\t%s %s %j", pattern, i, re, c);
19960 } // skip over any that are escaped.
19963 if (escaping && reSpecials[c]) {
19971 // completely not allowed, even escaped.
19972 // Should already be path-split by now.
19979 // the various stateChar values
19980 // for the "extglob" stuff.
19987 if (options.debug) {
19988 console.error("%s\t%s %s %j <-- stateChar", pattern, i, re, c);
19989 } // all of those are literals inside a class, except that
19990 // the glob [!a] means [^a] in regexp
19994 if (c === "!" && i === classStart + 1) c = "^";
19997 } // if we already have a stateChar, then it means
19998 // that there was something like ** or +? in there.
19999 // Handle the stateChar, then proceed with this one.
20003 stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
20004 // just clear the statechar *now*, rather than even diving into
20005 // the patternList stuff.
20007 if (options.noext) clearStateChar();
20021 plType = stateChar;
20022 patternListStack.push({
20026 }); // negation is (?:(?!js)[^/]*)
20028 re += stateChar === "!" ? "(?:(?!" : "(?:";
20033 if (inClass || !patternListStack.length) {
20040 plType = patternListStack.pop().type; // negation is (?:(?!js)[^/]*)
20041 // The others are (?:<pattern>)<type>
20052 // the default anyway
20058 if (inClass || !patternListStack.length || escaping) {
20066 // these are mostly the same in regexp and glob
20069 // swallow any state-tracking char before the [
20079 reClassStart = re.length;
20084 // a right bracket shall lose its special
20085 // meaning and represent itself in
20086 // a bracket expression if it occurs
20087 // first in the list. -- POSIX.2 2.8.3.2
20088 if (i === classStart + 1 || !inClass) {
20092 } // finish up the class.
20101 // swallow any state char that wasn't consumed
20107 } else if (reSpecials[c] && !(c === "^" && inClass)) {
20115 // handle the case where we left a class open.
20116 // "[abc" is valid, equivalent to "\[abc"
20120 // split where the last [ was, and escape it
20121 // this is a huge pita. We now have to re-walk
20122 // the contents of the would-be class to re-translate
20123 // any characters that were passed through as-is
20124 var cs = pattern.substr(classStart + 1),
20125 sp = this.parse(cs, SUBPARSE);
20126 re = re.substr(0, reClassStart) + "\\[" + sp[0];
20127 hasMagic = hasMagic || sp[1];
20128 } // handle the case where we had a +( thing at the *end*
20130 // each pattern list stack adds 3 chars, and we need to go through
20131 // and escape any | chars that were passed through as-is for the regexp.
20132 // Go through and escape them, taking care not to double-escape any
20133 // | chars that were already escaped.
20138 while (pl = patternListStack.pop()) {
20139 var tail = re.slice(pl.reStart + 3); // maybe some even number of \, then maybe 1 \, followed by a |
20141 tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {
20143 // the | isn't already escaped, so escape it.
20145 } // need to escape all those slashes *again*, without escaping the
20146 // one that we need for escaping the | character. As it works out,
20147 // escaping an even number of slashes can be done by simply repeating
20148 // it exactly after itself. That's why this trick works.
20150 // I am sorry that you have to see this.
20153 return $1 + $1 + $2 + "|";
20154 }); // console.error("tail=%j\n %s", tail, tail)
20156 var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
20158 re = re.slice(0, pl.reStart) + t + "\\(" + tail;
20159 } // handle trailing things that only matter at the very end.
20167 } // only need to apply the nodot start if the re starts with
20168 // something that could conceivably capture a dot
20171 var addPatternStart = false;
20173 switch (re.charAt(0)) {
20177 addPatternStart = true;
20178 } // if the re is not "" at this point, then we need to make sure
20179 // it doesn't match against an empty path part.
20180 // Otherwise a/* will match a/, which it should not.
20183 if (re !== "" && hasMagic) re = "(?=.)" + re;
20184 if (addPatternStart) re = patternStart + re; // parsing just a piece of a larger pattern.
20186 if (isSub === SUBPARSE) {
20187 return [re, hasMagic];
20188 } // skip the regexp for non-magical patterns
20189 // unescape anything in it, though, so that it'll be
20190 // an exact match against a file etc.
20194 return globUnescape(pattern);
20197 var flags = options.nocase ? "i" : "",
20198 regExp = new RegExp("^" + re + "$", flags);
20199 regExp._glob = pattern;
20204 minimatch.makeRe = function (pattern, options) {
20205 return new Minimatch(pattern, options || {}).makeRe();
20208 Minimatch.prototype.makeRe = makeRe;
20210 function makeRe() {
20211 if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
20212 // pattern strings, or "**".
20214 // It's better to use .match(). This function shouldn't
20215 // be used, really, but it's pretty convenient sometimes,
20216 // when you just want to work with a regex.
20218 var set = this.set;
20219 if (!set.length) return this.regexp = false;
20220 var options = this.options;
20221 var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot,
20222 flags = options.nocase ? "i" : "";
20223 var re = set.map(function (pattern) {
20224 return pattern.map(function (p) {
20225 return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src;
20227 }).join("|"); // must match entire pattern
20228 // ending in a * or ** will make it less strict.
20230 re = "^(?:" + re + ")$"; // can match anything, as long as it's not this.
20232 if (this.negate) re = "^(?!" + re + ").*$";
20235 return this.regexp = new RegExp(re, flags);
20237 return this.regexp = false;
20241 minimatch.match = function (list, pattern, options) {
20242 var mm = new Minimatch(pattern, options);
20243 list = list.filter(function (f) {
20244 return mm.match(f);
20247 if (options.nonull && !list.length) {
20248 list.push(pattern);
20254 Minimatch.prototype.match = match;
20256 function match(f, partial) {
20257 // console.error("match", f, this.pattern)
20258 // short-circuit in the case of busted things.
20260 if (this.comment) return false;
20261 if (this.empty) return f === "";
20262 if (f === "/" && partial) return true;
20263 var options = this.options; // windows: need to use /, not \
20264 // On other platforms, \ is a valid (albeit bad) filename char.
20266 if (platform === "win32") {
20267 f = f.split("\\").join("/");
20268 } // treat the test path as a set of pathparts.
20271 f = f.split(slashSplit);
20273 if (options.debug) {
20274 console.error(this.pattern, "split", f);
20275 } // just ONE of the pattern sets in this.set needs to match
20276 // in order for it to be valid. If negating, then just one
20277 // match means that we have failed.
20278 // Either way, return on the first hit.
20281 var set = this.set; // console.error(this.pattern, "set", set)
20283 for (var i = 0, l = set.length; i < l; i++) {
20284 var pattern = set[i];
20285 var hit = this.matchOne(f, pattern, partial);
20288 if (options.flipNegate) return true;
20289 return !this.negate;
20291 } // didn't get any hits. this is success if it's a negative
20292 // pattern, failure otherwise.
20295 if (options.flipNegate) return false;
20296 return this.negate;
20297 } // set partial to true to test if, for example,
20298 // "/a/b" matches the start of "/*/b/*/d"
20299 // Partial means, if you run out of file before you run
20300 // out of pattern, then that's fine, as long as all
20301 // the parts match.
20304 Minimatch.prototype.matchOne = function (file, pattern, partial) {
20305 var options = this.options;
20307 if (options.debug) {
20308 console.error("matchOne", {
20315 if (options.matchBase && pattern.length === 1) {
20316 file = path$2.basename(file.join("/")).split("/");
20319 if (options.debug) {
20320 console.error("matchOne", file.length, pattern.length);
20323 for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
20324 if (options.debug) {
20325 console.error("matchOne loop");
20328 var p = pattern[pi],
20331 if (options.debug) {
20332 console.error(pattern, p, f);
20333 } // should be impossible.
20334 // some invalid regexp stuff in the set.
20337 if (p === false) return false;
20339 if (p === GLOBSTAR) {
20340 if (options.debug) console.error('GLOBSTAR', [pattern, p, f]); // "**"
20341 // a/**/b/**/c would match the following:
20346 // To do this, take the rest of the pattern after
20347 // the **, and see if it would match the file remainder.
20348 // If so, return success.
20349 // If not, the ** "swallows" a segment, and try again.
20350 // This is recursively awful.
20352 // a/**/b/**/c matching a/b/x/y/z/c
20355 // - matchOne(b/x/y/z/c, b/**/c)
20358 // - matchOne(x/y/z/c, c) -> no
20359 // - matchOne(y/z/c, c) -> no
20360 // - matchOne(z/c, c) -> no
20361 // - matchOne(c, c) yes, hit
20367 if (options.debug) console.error('** at the end'); // a ** at the end will just swallow the rest.
20368 // We have found a match.
20369 // however, it will not swallow /.x, unless
20370 // options.dot is set.
20371 // . and .. are *never* matched by **, for explosively
20372 // exponential reasons.
20374 for (; fi < fl; fi++) {
20375 if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
20379 } // ok, let's see if we can swallow whatever we can.
20382 WHILE: while (fr < fl) {
20383 var swallowee = file[fr];
20385 if (options.debug) {
20386 console.error('\nglobstar while', file, fr, pattern, pr, swallowee);
20387 } // XXX remove this slice. Just pass the start index.
20390 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
20391 if (options.debug) console.error('globstar found match!', fr, fl, swallowee); // found a match.
20395 // can't swallow "." or ".." ever.
20396 // can only swallow ".foo" when explicitly asked.
20397 if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
20398 if (options.debug) console.error("dot detected!", file, fr, pattern, pr);
20400 } // ** swallows a segment, and continue.
20403 if (options.debug) console.error('globstar swallow a segment, and continue');
20406 } // no match was found.
20407 // However, in partial mode, we can't say this is necessarily over.
20408 // If there's more *pattern* left, then
20413 // console.error("\n>>> no match, partial?", file, fr, pattern, pr)
20414 if (fr === fl) return true;
20418 } // something other than **
20419 // non-magic patterns just have to match exactly
20420 // patterns with magic have been turned into regexps.
20425 if (typeof p === "string") {
20426 if (options.nocase) {
20427 hit = f.toLowerCase() === p.toLowerCase();
20432 if (options.debug) {
20433 console.error("string match", p, f, hit);
20438 if (options.debug) {
20439 console.error("pattern match", p, f, hit);
20443 if (!hit) return false;
20444 } // Note: ending in / means that we'll get a final ""
20445 // at the end of the pattern. This can only match a
20446 // corresponding "" at the end of the file.
20447 // If the file ends in /, then it can only match a
20448 // a pattern that ends in /, unless the pattern just
20449 // doesn't have any more for it. But, a/b/ should *not*
20450 // match "a/b/*", even though "" matches against the
20451 // [^/]*? pattern, except in partial mode, where it might
20452 // simply not be reached yet.
20453 // However, a/b/ should still satisfy a/*
20454 // now either we fell off the end of the pattern, or we're done.
20457 if (fi === fl && pi === pl) {
20458 // ran out of pattern and filename at the same time.
20461 } else if (fi === fl) {
20462 // ran out of file, but still had pattern left.
20463 // this is ok if we're doing the match as part of
20464 // a glob fs traversal.
20466 } else if (pi === pl) {
20467 // ran out of pattern, still have file left.
20468 // this is only acceptable if we're on the very last
20469 // empty segment of a file with a trailing slash.
20470 // a/* should match a/b/
20471 var emptyFileEnd = fi === fl - 1 && file[fi] === "";
20472 return emptyFileEnd;
20473 } // should be unreachable.
20476 throw new Error("wtf?");
20477 }; // replace stuff like \* with *
20480 function globUnescape(s) {
20481 return s.replace(/\\(.)/g, "$1");
20484 function regExpEscape(s) {
20485 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
20488 var fnmatch_1 = fnmatch.minimatch;
20490 var ini = createCommonjsModule(function (module, exports) {
20492 var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
20493 return new (P || (P = Promise))(function (resolve, reject) {
20494 function fulfilled(value) {
20496 step(generator.next(value));
20502 function rejected(value) {
20504 step(generator["throw"](value));
20510 function step(result) {
20511 result.done ? resolve(result.value) : new P(function (resolve) {
20512 resolve(result.value);
20513 }).then(fulfilled, rejected);
20516 step((generator = generator.apply(thisArg, _arguments || [])).next());
20520 var __generator = this && this.__generator || function (thisArg, body) {
20523 sent: function () {
20524 if (t[0] & 1) throw t[1];
20538 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
20543 return function (v) {
20544 return step([n, v]);
20548 function step(op) {
20549 if (f) throw new TypeError("Generator is already executing.");
20552 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;
20553 if (y = 0, t) op = [op[0] & 2, t.value];
20582 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
20587 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
20592 if (op[0] === 6 && _.label < t[1]) {
20598 if (t && _.label < t[2]) {
20606 if (t[2]) _.ops.pop();
20613 op = body.call(thisArg, _);
20621 if (op[0] & 5) throw op[1];
20623 value: op[0] ? op[1] : void 0,
20629 var __importStar = this && this.__importStar || function (mod) {
20630 if (mod && mod.__esModule) return mod;
20632 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
20633 result["default"] = mod;
20637 Object.defineProperty(exports, "__esModule", {
20641 var fs = __importStar(fs$3);
20643 * define the possible values:
\r
20644 * section: [section]
\r
20645 * param: key=value
\r
20646 * comment: ;this is a comment
\r
20651 section: /^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$/,
20652 param: /^\s*([\w\.\-\_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$/,
20653 comment: /^\s*[#;].*$/
20656 * Parses an .ini file
\r
20657 * @param file The location of the .ini file
\r
20660 function parse(file) {
20661 return __awaiter(this, void 0, void 0, function () {
20662 return __generator(this, function (_a) {
20665 , new Promise(function (resolve, reject) {
20666 fs.readFile(file, 'utf8', function (err, data) {
20672 resolve(parseString(data));
20679 exports.parse = parse;
20681 function parseSync(file) {
20682 return parseString(fs.readFileSync(file, 'utf8'));
20685 exports.parseSync = parseSync;
20687 function parseString(data) {
20688 var sectionBody = {};
20689 var sectionName = null;
20690 var value = [[sectionName, sectionBody]];
20691 var lines = data.split(/\r\n|\r|\n/);
20692 lines.forEach(function (line) {
20695 if (regex.comment.test(line)) {
20699 if (regex.param.test(line)) {
20700 match = line.match(regex.param);
20701 sectionBody[match[1]] = match[2];
20702 } else if (regex.section.test(line)) {
20703 match = line.match(regex.section);
20704 sectionName = match[1];
20706 value.push([sectionName, sectionBody]);
20712 exports.parseString = parseString;
20714 unwrapExports(ini);
20715 var ini_1 = ini.parse;
20716 var ini_2 = ini.parseSync;
20717 var ini_3 = ini.parseString;
20719 var name$1 = "editorconfig";
20720 var version$1 = "0.15.3";
20721 var description$1 = "EditorConfig File Locator and Interpreter for Node.js";
20726 var main$1 = "src/index.js";
20727 var contributors = [
20728 "Hong Xu (topbug.net)",
20729 "Jed Mao (https://github.com/jedmao/)",
20730 "Trey Hunner (http://treyhunner.com)"
20732 var directories = {
20737 clean: "rimraf dist",
20738 prebuild: "npm run clean",
20740 pretest: "npm run lint && npm run build && npm run copy && cmake .",
20742 "pretest:ci": "npm run pretest",
20743 "test:ci": "ctest -VV --output-on-failure .",
20744 lint: "npm run eclint && npm run tslint",
20745 eclint: "eclint check --indent_size ignore \"src/**\"",
20746 tslint: "tslint --project tsconfig.json --exclude package.json",
20747 copy: "cpy .npmignore LICENSE README.md CHANGELOG.md dist && cpy bin/* dist/bin && cpy src/lib/fnmatch*.* dist/src/lib",
20748 prepub: "npm run lint && npm run build && npm run copy",
20749 pub: "npm publish ./dist"
20751 var repository$1 = {
20753 url: "git://github.com/editorconfig/editorconfig-core-js.git"
20755 var bugs = "https://github.com/editorconfig/editorconfig-core-js/issues";
20756 var author$1 = "EditorConfig Team";
20757 var license$1 = "MIT";
20758 var dependencies$1 = {
20759 commander: "^2.19.0",
20760 "lru-cache": "^4.1.5",
20764 var devDependencies$1 = {
20765 "@types/mocha": "^5.2.6",
20766 "@types/node": "^10.12.29",
20767 "@types/semver": "^5.5.0",
20768 "cpy-cli": "^2.0.0",
20774 typescript: "^3.3.3333"
20778 version: version$1,
20779 description: description$1,
20780 keywords: keywords,
20782 contributors: contributors,
20783 directories: directories,
20784 scripts: scripts$1,
20785 repository: repository$1,
20788 license: license$1,
20789 dependencies: dependencies$1,
20790 devDependencies: devDependencies$1
20793 var _package$3 = /*#__PURE__*/Object.freeze({
20796 version: version$1,
20797 description: description$1,
20798 keywords: keywords,
20800 contributors: contributors,
20801 directories: directories,
20802 scripts: scripts$1,
20803 repository: repository$1,
20806 license: license$1,
20807 dependencies: dependencies$1,
20808 devDependencies: devDependencies$1,
20809 'default': _package$2
20812 var require$$4 = getCjsExportFromNamespace(_package$3);
20814 var src = createCommonjsModule(function (module, exports) {
20816 var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
20817 return new (P || (P = Promise))(function (resolve, reject) {
20818 function fulfilled(value) {
20820 step(generator.next(value));
20826 function rejected(value) {
20828 step(generator["throw"](value));
20834 function step(result) {
20835 result.done ? resolve(result.value) : new P(function (resolve) {
20836 resolve(result.value);
20837 }).then(fulfilled, rejected);
20840 step((generator = generator.apply(thisArg, _arguments || [])).next());
20844 var __generator = this && this.__generator || function (thisArg, body) {
20847 sent: function () {
20848 if (t[0] & 1) throw t[1];
20862 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
20867 return function (v) {
20868 return step([n, v]);
20872 function step(op) {
20873 if (f) throw new TypeError("Generator is already executing.");
20876 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;
20877 if (y = 0, t) op = [op[0] & 2, t.value];
20906 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
20911 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
20916 if (op[0] === 6 && _.label < t[1]) {
20922 if (t && _.label < t[2]) {
20930 if (t[2]) _.ops.pop();
20937 op = body.call(thisArg, _);
20945 if (op[0] & 5) throw op[1];
20947 value: op[0] ? op[1] : void 0,
20953 var __importStar = this && this.__importStar || function (mod) {
20954 if (mod && mod.__esModule) return mod;
20956 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
20957 result["default"] = mod;
20961 var __importDefault = this && this.__importDefault || function (mod) {
20962 return mod && mod.__esModule ? mod : {
20967 Object.defineProperty(exports, "__esModule", {
20971 var fs = __importStar(fs$3);
20973 var path = __importStar(path$2);
20975 var semver = __importStar(semver$2);
20977 var fnmatch_1 = __importDefault(fnmatch);
20979 exports.parseString = ini.parseString;
20981 var package_json_1 = __importDefault(require$$4);
20985 indent_style: true,
20987 insert_final_newline: true,
20988 trim_trailing_whitespace: true,
20992 function fnmatch$1(filepath, glob) {
20993 var matchOptions = {
20998 glob = glob.replace(/\*\*/g, '{*,**/**/**}');
20999 return fnmatch_1.default(filepath, glob, matchOptions);
21002 function getConfigFileNames(filepath, options) {
21006 filepath = path.dirname(filepath);
21007 paths.push(path.join(filepath, options.config));
21008 } while (filepath !== options.root);
21013 function processMatches(matches, version) {
21014 // Set indent_size to 'tab' if indent_size is unspecified and
21015 // indent_style is set to 'tab'.
21016 if ('indent_style' in matches && matches.indent_style === 'tab' && !('indent_size' in matches) && semver.gte(version, '0.10.0')) {
21017 matches.indent_size = 'tab';
21018 } // Set tab_width to indent_size if indent_size is specified and
21019 // tab_width is unspecified
21022 if ('indent_size' in matches && !('tab_width' in matches) && matches.indent_size !== 'tab') {
21023 matches.tab_width = matches.indent_size;
21024 } // Set indent_size to tab_width if indent_size is 'tab'
21027 if ('indent_size' in matches && 'tab_width' in matches && matches.indent_size === 'tab') {
21028 matches.indent_size = matches.tab_width;
21034 function processOptions(options, filepath) {
21035 if (options === void 0) {
21040 config: options.config || '.editorconfig',
21041 version: options.version || package_json_1.default.version,
21042 root: path.resolve(options.root || path.parse(filepath).root)
21046 function buildFullGlob(pathPrefix, glob) {
21047 switch (glob.indexOf('/')) {
21049 glob = '**/' + glob;
21053 glob = glob.substring(1);
21057 return path.join(pathPrefix, glob);
21060 function extendProps(props, options) {
21061 if (props === void 0) {
21065 if (options === void 0) {
21069 for (var key in options) {
21070 if (options.hasOwnProperty(key)) {
21071 var value = options[key];
21072 var key2 = key.toLowerCase();
21073 var value2 = value;
21075 if (knownProps[key2]) {
21076 value2 = value.toLowerCase();
21080 value2 = JSON.parse(value);
21083 if (typeof value === 'undefined' || value === null) {
21084 // null and undefined are values specific to JSON (no special meaning
21085 // in editorconfig) & should just be returned as regular strings.
21086 value2 = String(value);
21089 props[key2] = value2;
21096 function parseFromConfigs(configs, filepath, options) {
21097 return processMatches(configs.reverse().reduce(function (matches, file) {
21098 var pathPrefix = path.dirname(file.name);
21099 file.contents.forEach(function (section) {
21100 var glob = section[0];
21101 var options2 = section[1];
21107 var fullGlob = buildFullGlob(pathPrefix, glob);
21109 if (!fnmatch$1(filepath, fullGlob)) {
21113 matches = extendProps(matches, options2);
21116 }, {}), options.version);
21119 function getConfigsForFiles(files) {
21122 for (var i in files) {
21123 if (files.hasOwnProperty(i)) {
21124 var file = files[i];
21125 var contents = ini.parseString(file.contents);
21131 if ((contents[0][1].root || '').toLowerCase() === 'true') {
21140 function readConfigFiles(filepaths) {
21141 return __awaiter(this, void 0, void 0, function () {
21142 return __generator(this, function (_a) {
21145 , Promise.all(filepaths.map(function (name) {
21146 return new Promise(function (resolve) {
21147 fs.readFile(name, 'utf8', function (err, data) {
21150 contents: err ? '' : data
21159 function readConfigFilesSync(filepaths) {
21162 filepaths.forEach(function (filepath) {
21164 file = fs.readFileSync(filepath, 'utf8');
21177 function opts(filepath, options) {
21178 if (options === void 0) {
21182 var resolvedFilePath = path.resolve(filepath);
21183 return [resolvedFilePath, processOptions(options, resolvedFilePath)];
21186 function parseFromFiles(filepath, files, options) {
21187 if (options === void 0) {
21191 return __awaiter(this, void 0, void 0, function () {
21192 var _a, resolvedFilePath, processedOptions;
21194 return __generator(this, function (_b) {
21195 _a = opts(filepath, options), resolvedFilePath = _a[0], processedOptions = _a[1];
21198 , files.then(getConfigsForFiles).then(function (configs) {
21199 return parseFromConfigs(configs, resolvedFilePath, processedOptions);
21205 exports.parseFromFiles = parseFromFiles;
21207 function parseFromFilesSync(filepath, files, options) {
21208 if (options === void 0) {
21212 var _a = opts(filepath, options),
21213 resolvedFilePath = _a[0],
21214 processedOptions = _a[1];
21216 return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
21219 exports.parseFromFilesSync = parseFromFilesSync;
21221 function parse(_filepath, _options) {
21222 if (_options === void 0) {
21226 return __awaiter(this, void 0, void 0, function () {
21227 var _a, resolvedFilePath, processedOptions, filepaths;
21229 return __generator(this, function (_b) {
21230 _a = opts(_filepath, _options), resolvedFilePath = _a[0], processedOptions = _a[1];
21231 filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
21234 , readConfigFiles(filepaths).then(getConfigsForFiles).then(function (configs) {
21235 return parseFromConfigs(configs, resolvedFilePath, processedOptions);
21241 exports.parse = parse;
21243 function parseSync(_filepath, _options) {
21244 if (_options === void 0) {
21248 var _a = opts(_filepath, _options),
21249 resolvedFilePath = _a[0],
21250 processedOptions = _a[1];
21252 var filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
21253 var files = readConfigFilesSync(filepaths);
21254 return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
21257 exports.parseSync = parseSync;
21259 unwrapExports(src);
21260 var src_1 = src.parseString;
21261 var src_2 = src.parseFromFiles;
21262 var src_3 = src.parseFromFilesSync;
21263 var src_4 = src.parse;
21264 var src_5 = src.parseSync;
21266 var editorconfigToPrettier = editorConfigToPrettier;
21268 function removeUnset(editorConfig) {
21270 const keys = Object.keys(editorConfig);
21272 for (let i = 0; i < keys.length; i++) {
21273 const key = keys[i];
21275 if (editorConfig[key] === "unset") {
21279 result[key] = editorConfig[key];
21285 function editorConfigToPrettier(editorConfig) {
21286 if (!editorConfig) {
21290 editorConfig = removeUnset(editorConfig);
21292 if (Object.keys(editorConfig).length === 0) {
21298 if (editorConfig.indent_style) {
21299 result.useTabs = editorConfig.indent_style === "tab";
21302 if (editorConfig.indent_size === "tab") {
21303 result.useTabs = true;
21306 if (result.useTabs && editorConfig.tab_width) {
21307 result.tabWidth = editorConfig.tab_width;
21308 } else if (editorConfig.indent_style === "space" && editorConfig.indent_size && editorConfig.indent_size !== "tab") {
21309 result.tabWidth = editorConfig.indent_size;
21310 } else if (editorConfig.tab_width !== undefined) {
21311 result.tabWidth = editorConfig.tab_width;
21314 if (editorConfig.max_line_length && editorConfig.max_line_length !== "off") {
21315 result.printWidth = editorConfig.max_line_length;
21318 if (editorConfig.quote_type === "single") {
21319 result.singleQuote = true;
21320 } else if (editorConfig.quote_type === "double") {
21321 result.singleQuote = false;
21324 if (["cr", "crlf", "lf"].indexOf(editorConfig.end_of_line) !== -1) {
21325 result.endOfLine = editorConfig.end_of_line;
21331 function markerExists(files, markers) {
21332 return markers.some(function (marker) {
21333 return files.some(function (file) {
21334 return file === marker;
21339 function traverseFolder(directory, levels, markers) {
21340 var files = fs$3.readdirSync(directory);
21342 if (levels === 0) {
21344 } else if (markerExists(files, markers)) {
21347 return traverseFolder(path$2.resolve(directory, '..'), levels - 1, markers);
21351 var findProjectRoot = function findRoot(dir, opts) {
21352 if (!dir) throw new Error("Directory not defined");
21354 var levels = opts.maxDepth || findRoot.MAX_DEPTH;
21355 var markers = opts.markers || findRoot.MARKERS;
21356 return traverseFolder(dir, levels, markers);
21360 var MARKERS = ['.git', '.hg'];
21361 findProjectRoot.MAX_DEPTH = MAX_DEPTH;
21362 findProjectRoot.MARKERS = MARKERS;
21364 const jsonStringifyMem = fn => mem_1(fn, {
21365 cacheKey: JSON.stringify
21368 const maybeParse = (filePath, parse) => {
21369 // findProjectRoot will throw an error if we pass a nonexistent directory to
21370 // it, which is possible, for example, when the path is given via
21371 // --stdin-filepath. So, first, traverse up until we find an existing
21373 let dirPath = path$2.dirname(path$2.resolve(filePath));
21374 const fsRoot = path$2.parse(dirPath).root;
21376 while (dirPath !== fsRoot && !fs$3.existsSync(dirPath)) {
21377 dirPath = path$2.dirname(dirPath);
21380 const root = findProjectRoot(dirPath);
21381 return filePath && parse(filePath, {
21386 const editorconfigAsyncNoCache = async filePath => {
21387 const editorConfig = await maybeParse(filePath, src.parse);
21388 return editorconfigToPrettier(editorConfig);
21391 const editorconfigAsyncWithCache = jsonStringifyMem(editorconfigAsyncNoCache);
21393 const editorconfigSyncNoCache = filePath => {
21394 return editorconfigToPrettier(maybeParse(filePath, src.parseSync));
21397 const editorconfigSyncWithCache = jsonStringifyMem(editorconfigSyncNoCache);
21399 function getLoadFunction(opts) {
21400 if (!opts.editorconfig) {
21405 return opts.cache ? editorconfigSyncWithCache : editorconfigSyncNoCache;
21408 return opts.cache ? editorconfigAsyncWithCache : editorconfigAsyncNoCache;
21411 function clearCache() {
21412 mem_1.clear(editorconfigSyncWithCache);
21413 mem_1.clear(editorconfigAsyncWithCache);
21416 var resolveConfigEditorconfig = {
21421 const ParserEND = 0x110000;
21423 class ParserError extends Error {
21424 /* istanbul ignore next */
21425 constructor(msg, filename, linenumber) {
21426 super('[ParserError] ' + msg, filename, linenumber);
21427 this.name = 'ParserError';
21428 this.code = 'ParserError';
21429 if (Error.captureStackTrace) Error.captureStackTrace(this, ParserError);
21435 constructor(parser) {
21436 this.parser = parser;
21438 this.returned = null;
21439 this.result = null;
21440 this.resultTable = null;
21441 this.resultArr = null;
21452 this.ctx = this.obj;
21457 this.state = new State(this.parseStart);
21461 /* istanbul ignore next */
21462 if (str.length === 0 || str.length == null) return;
21463 this._buf = String(str);
21468 while (getNext === false || this.nextChar()) {
21469 getNext = this.runOne();
21476 if (this.char === 0x0A) {
21482 this.char = this._buf.codePointAt(this.ii);
21485 return this.haveBuffer();
21489 return this.ii < this._buf.length;
21493 return this.state.parser.call(this, this.state.returned);
21497 this.char = ParserEND;
21501 last = this.state.parser;
21503 } while (this.state.parser !== last);
21512 /* istanbul ignore next */
21513 if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn));
21514 this.state.parser = fn;
21519 return this.runOne();
21522 call(fn, returnWith) {
21523 if (returnWith) this.next(returnWith);
21524 this.stack.push(this.state);
21525 this.state = new State(fn);
21528 callNow(fn, returnWith) {
21529 this.call(fn, returnWith);
21530 return this.runOne();
21534 /* istanbul ignore next */
21535 if (this.stack.length === 0) throw this.error(new ParserError('Stack underflow'));
21536 if (value === undefined) value = this.state.buf;
21537 this.state = this.stack.pop();
21538 this.state.returned = value;
21542 this.return(value);
21543 return this.runOne();
21547 /* istanbul ignore next */
21548 if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer'));
21549 this.state.buf += this._buf[this.ii];
21553 err.line = this.line;
21554 err.col = this.col;
21555 err.pos = this.pos;
21558 /* istanbul ignore next */
21562 throw new ParserError('Must declare a parseStart method');
21567 Parser.END = ParserEND;
21568 Parser.Error = ParserError;
21569 var parser$1 = Parser;
21571 var createDatetime = value => {
21572 const date = new Date(value);
21573 /* istanbul ignore if */
21576 throw new TypeError('Invalid Datetime');
21582 var formatNum = (d, num) => {
21585 while (num.length < d) num = '0' + num;
21590 class FloatingDateTime extends Date {
21591 constructor(value) {
21592 super(value + 'Z');
21593 this.isFloating = true;
21597 const date = `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`;
21598 const time = `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`;
21599 return `${date}T${time}`;
21604 var createDatetimeFloat = value => {
21605 const date = new FloatingDateTime(value);
21606 /* istanbul ignore if */
21609 throw new TypeError('Invalid Datetime');
21615 const DateTime = global.Date;
21617 class Date$1 extends DateTime {
21618 constructor(value) {
21620 this.isDate = true;
21624 return `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`;
21629 var createDate = value => {
21630 const date = new Date$1(value);
21631 /* istanbul ignore if */
21634 throw new TypeError('Invalid Datetime');
21640 class Time extends Date {
21641 constructor(value) {
21642 super(`0000-01-01T${value}Z`);
21643 this.isTime = true;
21647 return `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`;
21652 var createTime = value => {
21653 const date = new Time(value);
21654 /* istanbul ignore if */
21657 throw new TypeError('Invalid Datetime');
21663 /* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */
21666 var tomlParser = makeParserClass(parser$1);
21667 var makeParserClass_1 = makeParserClass;
21669 class TomlError extends Error {
21672 this.name = 'TomlError';
21673 /* istanbul ignore next */
21675 if (Error.captureStackTrace) Error.captureStackTrace(this, TomlError);
21676 this.fromTOML = true;
21677 this.wrapped = null;
21682 TomlError.wrap = err => {
21683 const terr = new TomlError(err.message);
21684 terr.code = err.code;
21685 terr.wrapped = err;
21689 var TomlError_1 = TomlError;
21690 const CTRL_I = 0x09;
21691 const CTRL_J = 0x0A;
21692 const CTRL_M = 0x0D;
21693 const CTRL_CHAR_BOUNDARY = 0x1F; // the last non-character in the latin1 region of unicode, except DEL
21695 const CHAR_SP = 0x20;
21696 const CHAR_QUOT = 0x22;
21697 const CHAR_NUM = 0x23;
21698 const CHAR_APOS = 0x27;
21699 const CHAR_PLUS = 0x2B;
21700 const CHAR_COMMA = 0x2C;
21701 const CHAR_HYPHEN = 0x2D;
21702 const CHAR_PERIOD = 0x2E;
21703 const CHAR_0 = 0x30;
21704 const CHAR_1 = 0x31;
21705 const CHAR_7 = 0x37;
21706 const CHAR_9 = 0x39;
21707 const CHAR_COLON = 0x3A;
21708 const CHAR_EQUALS = 0x3D;
21709 const CHAR_A = 0x41;
21710 const CHAR_E = 0x45;
21711 const CHAR_F = 0x46;
21712 const CHAR_T = 0x54;
21713 const CHAR_U = 0x55;
21714 const CHAR_Z = 0x5A;
21715 const CHAR_LOWBAR = 0x5F;
21716 const CHAR_a = 0x61;
21717 const CHAR_b = 0x62;
21718 const CHAR_e = 0x65;
21719 const CHAR_f = 0x66;
21720 const CHAR_i = 0x69;
21721 const CHAR_l = 0x6C;
21722 const CHAR_n = 0x6E;
21723 const CHAR_o = 0x6F;
21724 const CHAR_r = 0x72;
21725 const CHAR_s = 0x73;
21726 const CHAR_t = 0x74;
21727 const CHAR_u = 0x75;
21728 const CHAR_x = 0x78;
21729 const CHAR_z = 0x7A;
21730 const CHAR_LCUB = 0x7B;
21731 const CHAR_RCUB = 0x7D;
21732 const CHAR_LSQB = 0x5B;
21733 const CHAR_BSOL = 0x5C;
21734 const CHAR_RSQB = 0x5D;
21735 const CHAR_DEL = 0x7F;
21736 const SURROGATE_FIRST = 0xD800;
21737 const SURROGATE_LAST = 0xDFFF;
21739 [CHAR_b]: '\u0008',
21740 [CHAR_t]: '\u0009',
21741 [CHAR_n]: '\u000A',
21742 [CHAR_f]: '\u000C',
21743 [CHAR_r]: '\u000D',
21744 [CHAR_QUOT]: '\u0022',
21745 [CHAR_BSOL]: '\u005C'
21748 function isDigit(cp) {
21749 return cp >= CHAR_0 && cp <= CHAR_9;
21752 function isHexit(cp) {
21753 return cp >= CHAR_A && cp <= CHAR_F || cp >= CHAR_a && cp <= CHAR_f || cp >= CHAR_0 && cp <= CHAR_9;
21756 function isBit(cp) {
21757 return cp === CHAR_1 || cp === CHAR_0;
21760 function isOctit(cp) {
21761 return cp >= CHAR_0 && cp <= CHAR_7;
21764 function isAlphaNumQuoteHyphen(cp) {
21765 return cp >= CHAR_A && cp <= CHAR_Z || cp >= CHAR_a && cp <= CHAR_z || cp >= CHAR_0 && cp <= CHAR_9 || cp === CHAR_APOS || cp === CHAR_QUOT || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN;
21768 function isAlphaNumHyphen(cp) {
21769 return cp >= CHAR_A && cp <= CHAR_Z || cp >= CHAR_a && cp <= CHAR_z || cp >= CHAR_0 && cp <= CHAR_9 || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN;
21772 const _type = Symbol('type');
21774 const _declared = Symbol('declared');
21776 const hasOwnProperty$1 = Object.prototype.hasOwnProperty;
21777 const defineProperty = Object.defineProperty;
21778 const descriptor = {
21779 configurable: true,
21785 function hasKey(obj, key) {
21786 if (hasOwnProperty$1.call(obj, key)) return true;
21787 if (key === '__proto__') defineProperty(obj, '__proto__', descriptor);
21791 const INLINE_TABLE = Symbol('inline-table');
21793 function InlineTable() {
21794 return Object.defineProperties({}, {
21796 value: INLINE_TABLE
21801 function isInlineTable(obj) {
21802 if (obj === null || typeof obj !== 'object') return false;
21803 return obj[_type] === INLINE_TABLE;
21806 const TABLE = Symbol('table');
21809 return Object.defineProperties({}, {
21820 function isTable(obj) {
21821 if (obj === null || typeof obj !== 'object') return false;
21822 return obj[_type] === TABLE;
21825 const _contentType = Symbol('content-type');
21827 const INLINE_LIST = Symbol('inline-list');
21829 function InlineList(type) {
21830 return Object.defineProperties([], {
21840 function isInlineList(obj) {
21841 if (obj === null || typeof obj !== 'object') return false;
21842 return obj[_type] === INLINE_LIST;
21845 const LIST = Symbol('list');
21848 return Object.defineProperties([], {
21855 function isList(obj) {
21856 if (obj === null || typeof obj !== 'object') return false;
21857 return obj[_type] === LIST;
21858 } // in an eval, to let bundlers not slurp in a util proxy
21864 const utilInspect = eval("require('util').inspect");
21865 _custom = utilInspect.custom;
21867 /* eval require not available in transpiled bundle */
21869 /* istanbul ignore next */
21872 const _inspect = _custom || 'inspect';
21874 class BoxedBigInt {
21875 constructor(value) {
21877 this.value = global.BigInt.asIntN(64, value);
21879 /* istanbul ignore next */
21883 Object.defineProperty(this, _type, {
21889 return this.value === null;
21891 /* istanbul ignore next */
21895 return String(this.value);
21897 /* istanbul ignore next */
21901 return `[BigInt: ${this.toString()}]}`;
21910 const INTEGER = Symbol('integer');
21912 function Integer(value) {
21913 let num = Number(value); // -0 is a float thing, not an int thing
21915 if (Object.is(num, -0)) num = 0;
21916 /* istanbul ignore else */
21918 if (global.BigInt && !Number.isSafeInteger(num)) {
21919 return new BoxedBigInt(value);
21921 /* istanbul ignore next */
21922 return Object.defineProperties(new Number(num), {
21924 value: function () {
21925 return isNaN(this);
21932 value: () => `[Integer: ${value}]`
21938 function isInteger(obj) {
21939 if (obj === null || typeof obj !== 'object') return false;
21940 return obj[_type] === INTEGER;
21943 const FLOAT = Symbol('float');
21945 function Float(value) {
21946 /* istanbul ignore next */
21947 return Object.defineProperties(new Number(value), {
21952 value: () => `[Float: ${value}]`
21957 function isFloat(obj) {
21958 if (obj === null || typeof obj !== 'object') return false;
21959 return obj[_type] === FLOAT;
21962 function tomlType(value) {
21963 const type = typeof value;
21965 if (type === 'object') {
21966 /* istanbul ignore if */
21967 if (value === null) return 'null';
21968 if (value instanceof Date) return 'datetime';
21969 /* istanbul ignore else */
21971 if (_type in value) {
21972 switch (value[_type]) {
21974 return 'inline-table';
21977 return 'inline-list';
21979 /* istanbul ignore next */
21984 /* istanbul ignore next */
22001 function makeParserClass(Parser) {
22002 class TOMLParser extends Parser {
22005 this.ctx = this.obj = Table();
22011 return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine();
22015 return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M;
22019 if (this.char === Parser.END) {
22021 } else if (this.char === CHAR_LSQB) {
22022 return this.call(this.parseTableOrList);
22023 } else if (this.char === CHAR_NUM) {
22024 return this.call(this.parseComment);
22025 } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
22027 } else if (isAlphaNumQuoteHyphen(this.char)) {
22028 return this.callNow(this.parseAssignStatement);
22030 throw this.error(new TomlError(`Unknown character "${this.char}"`));
22032 } // HELPER, this strips any whitespace and comments to the end of the line
22033 // then RETURNS. Last state in a production.
22036 parseWhitespaceToEOL() {
22037 if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
22039 } else if (this.char === CHAR_NUM) {
22040 return this.goto(this.parseComment);
22041 } else if (this.char === Parser.END || this.char === CTRL_J) {
22042 return this.return();
22044 throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line'));
22047 /* ASSIGNMENT: key = value */
22050 parseAssignStatement() {
22051 return this.callNow(this.parseAssign, this.recordAssignStatement);
22054 recordAssignStatement(kv) {
22055 let target = this.ctx;
22056 let finalKey = kv.key.pop();
22058 for (let kw of kv.key) {
22059 if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
22060 throw this.error(new TomlError("Can't redefine existing key"));
22063 target = target[kw] = target[kw] || Table();
22066 if (hasKey(target, finalKey)) {
22067 throw this.error(new TomlError("Can't redefine existing key"));
22068 } // unbox our numbers
22071 if (isInteger(kv.value) || isFloat(kv.value)) {
22072 target[finalKey] = kv.value.valueOf();
22074 target[finalKey] = kv.value;
22077 return this.goto(this.parseWhitespaceToEOL);
22079 /* ASSSIGNMENT expression, key = value possibly inside an inline table */
22083 return this.callNow(this.parseKeyword, this.recordAssignKeyword);
22086 recordAssignKeyword(key) {
22087 if (this.state.resultTable) {
22088 this.state.resultTable.push(key);
22090 this.state.resultTable = [key];
22093 return this.goto(this.parseAssignKeywordPreDot);
22096 parseAssignKeywordPreDot() {
22097 if (this.char === CHAR_PERIOD) {
22098 return this.next(this.parseAssignKeywordPostDot);
22099 } else if (this.char !== CHAR_SP && this.char !== CTRL_I) {
22100 return this.goto(this.parseAssignEqual);
22104 parseAssignKeywordPostDot() {
22105 if (this.char !== CHAR_SP && this.char !== CTRL_I) {
22106 return this.callNow(this.parseKeyword, this.recordAssignKeyword);
22110 parseAssignEqual() {
22111 if (this.char === CHAR_EQUALS) {
22112 return this.next(this.parseAssignPreValue);
22114 throw this.error(new TomlError('Invalid character, expected "="'));
22118 parseAssignPreValue() {
22119 if (this.char === CHAR_SP || this.char === CTRL_I) {
22122 return this.callNow(this.parseValue, this.recordAssignValue);
22126 recordAssignValue(value) {
22127 return this.returnNow({
22128 key: this.state.resultTable,
22132 /* COMMENTS: #...eol */
22137 if (this.char === Parser.END || this.char === CTRL_J) {
22138 return this.return();
22140 } while (this.nextChar());
22142 /* TABLES AND LISTS, [foo] and [[foo]] */
22145 parseTableOrList() {
22146 if (this.char === CHAR_LSQB) {
22147 this.next(this.parseList);
22149 return this.goto(this.parseTable);
22152 /* TABLE [foo.bar.baz] */
22156 this.ctx = this.obj;
22157 return this.goto(this.parseTableNext);
22161 if (this.char === CHAR_SP || this.char === CTRL_I) {
22164 return this.callNow(this.parseKeyword, this.parseTableMore);
22168 parseTableMore(keyword) {
22169 if (this.char === CHAR_SP || this.char === CTRL_I) {
22171 } else if (this.char === CHAR_RSQB) {
22172 if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {
22173 throw this.error(new TomlError("Can't redefine existing key"));
22175 this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table();
22176 this.ctx[_declared] = true;
22179 return this.next(this.parseWhitespaceToEOL);
22180 } else if (this.char === CHAR_PERIOD) {
22181 if (!hasKey(this.ctx, keyword)) {
22182 this.ctx = this.ctx[keyword] = Table();
22183 } else if (isTable(this.ctx[keyword])) {
22184 this.ctx = this.ctx[keyword];
22185 } else if (isList(this.ctx[keyword])) {
22186 this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
22188 throw this.error(new TomlError("Can't redefine existing key"));
22191 return this.next(this.parseTableNext);
22193 throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
22196 /* LIST [[a.b.c]] */
22200 this.ctx = this.obj;
22201 return this.goto(this.parseListNext);
22205 if (this.char === CHAR_SP || this.char === CTRL_I) {
22208 return this.callNow(this.parseKeyword, this.parseListMore);
22212 parseListMore(keyword) {
22213 if (this.char === CHAR_SP || this.char === CTRL_I) {
22215 } else if (this.char === CHAR_RSQB) {
22216 if (!hasKey(this.ctx, keyword)) {
22217 this.ctx[keyword] = List();
22220 if (isInlineList(this.ctx[keyword])) {
22221 throw this.error(new TomlError("Can't extend an inline array"));
22222 } else if (isList(this.ctx[keyword])) {
22223 const next = Table();
22224 this.ctx[keyword].push(next);
22227 throw this.error(new TomlError("Can't redefine an existing key"));
22230 return this.next(this.parseListEnd);
22231 } else if (this.char === CHAR_PERIOD) {
22232 if (!hasKey(this.ctx, keyword)) {
22233 this.ctx = this.ctx[keyword] = Table();
22234 } else if (isInlineList(this.ctx[keyword])) {
22235 throw this.error(new TomlError("Can't extend an inline array"));
22236 } else if (isInlineTable(this.ctx[keyword])) {
22237 throw this.error(new TomlError("Can't extend an inline table"));
22238 } else if (isList(this.ctx[keyword])) {
22239 this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
22240 } else if (isTable(this.ctx[keyword])) {
22241 this.ctx = this.ctx[keyword];
22243 throw this.error(new TomlError("Can't redefine an existing key"));
22246 return this.next(this.parseListNext);
22248 throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
22252 parseListEnd(keyword) {
22253 if (this.char === CHAR_RSQB) {
22254 return this.next(this.parseWhitespaceToEOL);
22256 throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
22259 /* VALUE string, number, boolean, inline list, inline object */
22263 if (this.char === Parser.END) {
22264 throw this.error(new TomlError('Key without value'));
22265 } else if (this.char === CHAR_QUOT) {
22266 return this.next(this.parseDoubleString);
22269 if (this.char === CHAR_APOS) {
22270 return this.next(this.parseSingleString);
22271 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
22272 return this.goto(this.parseNumberSign);
22273 } else if (this.char === CHAR_i) {
22274 return this.next(this.parseInf);
22275 } else if (this.char === CHAR_n) {
22276 return this.next(this.parseNan);
22277 } else if (isDigit(this.char)) {
22278 return this.goto(this.parseNumberOrDateTime);
22279 } else if (this.char === CHAR_t || this.char === CHAR_f) {
22280 return this.goto(this.parseBoolean);
22281 } else if (this.char === CHAR_LSQB) {
22282 return this.call(this.parseInlineList, this.recordValue);
22283 } else if (this.char === CHAR_LCUB) {
22284 return this.call(this.parseInlineTable, this.recordValue);
22286 throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table'));
22290 recordValue(value) {
22291 return this.returnNow(value);
22295 if (this.char === CHAR_n) {
22296 return this.next(this.parseInf2);
22298 throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
22303 if (this.char === CHAR_f) {
22304 if (this.state.buf === '-') {
22305 return this.return(-Infinity);
22307 return this.return(Infinity);
22310 throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
22315 if (this.char === CHAR_a) {
22316 return this.next(this.parseNan2);
22318 throw this.error(new TomlError('Unexpected character, expected "nan"'));
22323 if (this.char === CHAR_n) {
22324 return this.return(NaN);
22326 throw this.error(new TomlError('Unexpected character, expected "nan"'));
22329 /* KEYS, barewords or basic, literal, or dotted */
22333 if (this.char === CHAR_QUOT) {
22334 return this.next(this.parseBasicString);
22335 } else if (this.char === CHAR_APOS) {
22336 return this.next(this.parseLiteralString);
22338 return this.goto(this.parseBareKey);
22341 /* KEYS: barewords */
22346 if (this.char === Parser.END) {
22347 throw this.error(new TomlError('Key ended without value'));
22348 } else if (isAlphaNumHyphen(this.char)) {
22350 } else if (this.state.buf.length === 0) {
22351 throw this.error(new TomlError('Empty bare keys are not allowed'));
22353 return this.returnNow();
22355 } while (this.nextChar());
22357 /* STRINGS, single quoted (literal) */
22360 parseSingleString() {
22361 if (this.char === CHAR_APOS) {
22362 return this.next(this.parseLiteralMultiStringMaybe);
22364 return this.goto(this.parseLiteralString);
22368 parseLiteralString() {
22370 if (this.char === CHAR_APOS) {
22371 return this.return();
22372 } else if (this.atEndOfLine()) {
22373 throw this.error(new TomlError('Unterminated string'));
22374 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
22375 throw this.errorControlCharInString();
22379 } while (this.nextChar());
22382 parseLiteralMultiStringMaybe() {
22383 if (this.char === CHAR_APOS) {
22384 return this.next(this.parseLiteralMultiString);
22386 return this.returnNow();
22390 parseLiteralMultiString() {
22391 if (this.char === CTRL_M) {
22393 } else if (this.char === CTRL_J) {
22394 return this.next(this.parseLiteralMultiStringContent);
22396 return this.goto(this.parseLiteralMultiStringContent);
22400 parseLiteralMultiStringContent() {
22402 if (this.char === CHAR_APOS) {
22403 return this.next(this.parseLiteralMultiEnd);
22404 } else if (this.char === Parser.END) {
22405 throw this.error(new TomlError('Unterminated multi-line string'));
22406 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
22407 throw this.errorControlCharInString();
22411 } while (this.nextChar());
22414 parseLiteralMultiEnd() {
22415 if (this.char === CHAR_APOS) {
22416 return this.next(this.parseLiteralMultiEnd2);
22418 this.state.buf += "'";
22419 return this.goto(this.parseLiteralMultiStringContent);
22423 parseLiteralMultiEnd2() {
22424 if (this.char === CHAR_APOS) {
22425 return this.return();
22427 this.state.buf += "''";
22428 return this.goto(this.parseLiteralMultiStringContent);
22431 /* STRINGS double quoted */
22434 parseDoubleString() {
22435 if (this.char === CHAR_QUOT) {
22436 return this.next(this.parseMultiStringMaybe);
22438 return this.goto(this.parseBasicString);
22442 parseBasicString() {
22444 if (this.char === CHAR_BSOL) {
22445 return this.call(this.parseEscape, this.recordEscapeReplacement);
22446 } else if (this.char === CHAR_QUOT) {
22447 return this.return();
22448 } else if (this.atEndOfLine()) {
22449 throw this.error(new TomlError('Unterminated string'));
22450 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
22451 throw this.errorControlCharInString();
22455 } while (this.nextChar());
22458 recordEscapeReplacement(replacement) {
22459 this.state.buf += replacement;
22460 return this.goto(this.parseBasicString);
22463 parseMultiStringMaybe() {
22464 if (this.char === CHAR_QUOT) {
22465 return this.next(this.parseMultiString);
22467 return this.returnNow();
22471 parseMultiString() {
22472 if (this.char === CTRL_M) {
22474 } else if (this.char === CTRL_J) {
22475 return this.next(this.parseMultiStringContent);
22477 return this.goto(this.parseMultiStringContent);
22481 parseMultiStringContent() {
22483 if (this.char === CHAR_BSOL) {
22484 return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement);
22485 } else if (this.char === CHAR_QUOT) {
22486 return this.next(this.parseMultiEnd);
22487 } else if (this.char === Parser.END) {
22488 throw this.error(new TomlError('Unterminated multi-line string'));
22489 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
22490 throw this.errorControlCharInString();
22494 } while (this.nextChar());
22497 errorControlCharInString() {
22498 let displayCode = '\\u00';
22500 if (this.char < 16) {
22501 displayCode += '0';
22504 displayCode += this.char.toString(16);
22505 return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`));
22508 recordMultiEscapeReplacement(replacement) {
22509 this.state.buf += replacement;
22510 return this.goto(this.parseMultiStringContent);
22514 if (this.char === CHAR_QUOT) {
22515 return this.next(this.parseMultiEnd2);
22517 this.state.buf += '"';
22518 return this.goto(this.parseMultiStringContent);
22523 if (this.char === CHAR_QUOT) {
22524 return this.return();
22526 this.state.buf += '""';
22527 return this.goto(this.parseMultiStringContent);
22531 parseMultiEscape() {
22532 if (this.char === CTRL_M || this.char === CTRL_J) {
22533 return this.next(this.parseMultiTrim);
22534 } else if (this.char === CHAR_SP || this.char === CTRL_I) {
22535 return this.next(this.parsePreMultiTrim);
22537 return this.goto(this.parseEscape);
22541 parsePreMultiTrim() {
22542 if (this.char === CHAR_SP || this.char === CTRL_I) {
22544 } else if (this.char === CTRL_M || this.char === CTRL_J) {
22545 return this.next(this.parseMultiTrim);
22547 throw this.error(new TomlError("Can't escape whitespace"));
22552 // explicitly whitespace here, END should follow the same path as chars
22553 if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
22556 return this.returnNow();
22561 if (this.char in escapes) {
22562 return this.return(escapes[this.char]);
22563 } else if (this.char === CHAR_u) {
22564 return this.call(this.parseSmallUnicode, this.parseUnicodeReturn);
22565 } else if (this.char === CHAR_U) {
22566 return this.call(this.parseLargeUnicode, this.parseUnicodeReturn);
22568 throw this.error(new TomlError('Unknown escape character: ' + this.char));
22572 parseUnicodeReturn(char) {
22574 const codePoint = parseInt(char, 16);
22576 if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {
22577 throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved'));
22580 return this.returnNow(String.fromCodePoint(codePoint));
22582 throw this.error(TomlError.wrap(err));
22586 parseSmallUnicode() {
22587 if (!isHexit(this.char)) {
22588 throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'));
22591 if (this.state.buf.length >= 4) return this.return();
22595 parseLargeUnicode() {
22596 if (!isHexit(this.char)) {
22597 throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'));
22600 if (this.state.buf.length >= 8) return this.return();
22606 parseNumberSign() {
22608 return this.next(this.parseMaybeSignedInfOrNan);
22611 parseMaybeSignedInfOrNan() {
22612 if (this.char === CHAR_i) {
22613 return this.next(this.parseInf);
22614 } else if (this.char === CHAR_n) {
22615 return this.next(this.parseNan);
22617 return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart);
22621 parseNumberIntegerStart() {
22622 if (this.char === CHAR_0) {
22624 return this.next(this.parseNumberIntegerExponentOrDecimal);
22626 return this.goto(this.parseNumberInteger);
22630 parseNumberIntegerExponentOrDecimal() {
22631 if (this.char === CHAR_PERIOD) {
22633 return this.call(this.parseNoUnder, this.parseNumberFloat);
22634 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22636 return this.next(this.parseNumberExponentSign);
22638 return this.returnNow(Integer(this.state.buf));
22642 parseNumberInteger() {
22643 if (isDigit(this.char)) {
22645 } else if (this.char === CHAR_LOWBAR) {
22646 return this.call(this.parseNoUnder);
22647 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22649 return this.next(this.parseNumberExponentSign);
22650 } else if (this.char === CHAR_PERIOD) {
22652 return this.call(this.parseNoUnder, this.parseNumberFloat);
22654 const result = Integer(this.state.buf);
22655 /* istanbul ignore if */
22657 if (result.isNaN()) {
22658 throw this.error(new TomlError('Invalid number'));
22660 return this.returnNow(result);
22666 if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) {
22667 throw this.error(new TomlError('Unexpected character, expected digit'));
22668 } else if (this.atEndOfWord()) {
22669 throw this.error(new TomlError('Incomplete number'));
22672 return this.returnNow();
22675 parseNumberFloat() {
22676 if (this.char === CHAR_LOWBAR) {
22677 return this.call(this.parseNoUnder, this.parseNumberFloat);
22678 } else if (isDigit(this.char)) {
22680 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22682 return this.next(this.parseNumberExponentSign);
22684 return this.returnNow(Float(this.state.buf));
22688 parseNumberExponentSign() {
22689 if (isDigit(this.char)) {
22690 return this.goto(this.parseNumberExponent);
22691 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
22693 this.call(this.parseNoUnder, this.parseNumberExponent);
22695 throw this.error(new TomlError('Unexpected character, expected -, + or digit'));
22699 parseNumberExponent() {
22700 if (isDigit(this.char)) {
22702 } else if (this.char === CHAR_LOWBAR) {
22703 return this.call(this.parseNoUnder);
22705 return this.returnNow(Float(this.state.buf));
22708 /* NUMBERS or DATETIMES */
22711 parseNumberOrDateTime() {
22712 if (this.char === CHAR_0) {
22714 return this.next(this.parseNumberBaseOrDateTime);
22716 return this.goto(this.parseNumberOrDateTimeOnly);
22720 parseNumberOrDateTimeOnly() {
22721 // note, if two zeros are in a row then it MUST be a date
22722 if (this.char === CHAR_LOWBAR) {
22723 return this.call(this.parseNoUnder, this.parseNumberInteger);
22724 } else if (isDigit(this.char)) {
22726 if (this.state.buf.length > 4) this.next(this.parseNumberInteger);
22727 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22729 return this.next(this.parseNumberExponentSign);
22730 } else if (this.char === CHAR_PERIOD) {
22732 return this.call(this.parseNoUnder, this.parseNumberFloat);
22733 } else if (this.char === CHAR_HYPHEN) {
22734 return this.goto(this.parseDateTime);
22735 } else if (this.char === CHAR_COLON) {
22736 return this.goto(this.parseOnlyTimeHour);
22738 return this.returnNow(Integer(this.state.buf));
22742 parseDateTimeOnly() {
22743 if (this.state.buf.length < 4) {
22744 if (isDigit(this.char)) {
22745 return this.consume();
22746 } else if (this.char === CHAR_COLON) {
22747 return this.goto(this.parseOnlyTimeHour);
22749 throw this.error(new TomlError('Expected digit while parsing year part of a date'));
22752 if (this.char === CHAR_HYPHEN) {
22753 return this.goto(this.parseDateTime);
22755 throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date'));
22760 parseNumberBaseOrDateTime() {
22761 if (this.char === CHAR_b) {
22763 return this.call(this.parseNoUnder, this.parseIntegerBin);
22764 } else if (this.char === CHAR_o) {
22766 return this.call(this.parseNoUnder, this.parseIntegerOct);
22767 } else if (this.char === CHAR_x) {
22769 return this.call(this.parseNoUnder, this.parseIntegerHex);
22770 } else if (this.char === CHAR_PERIOD) {
22771 return this.goto(this.parseNumberInteger);
22772 } else if (isDigit(this.char)) {
22773 return this.goto(this.parseDateTimeOnly);
22775 return this.returnNow(Integer(this.state.buf));
22779 parseIntegerHex() {
22780 if (isHexit(this.char)) {
22782 } else if (this.char === CHAR_LOWBAR) {
22783 return this.call(this.parseNoUnder);
22785 const result = Integer(this.state.buf);
22786 /* istanbul ignore if */
22788 if (result.isNaN()) {
22789 throw this.error(new TomlError('Invalid number'));
22791 return this.returnNow(result);
22796 parseIntegerOct() {
22797 if (isOctit(this.char)) {
22799 } else if (this.char === CHAR_LOWBAR) {
22800 return this.call(this.parseNoUnder);
22802 const result = Integer(this.state.buf);
22803 /* istanbul ignore if */
22805 if (result.isNaN()) {
22806 throw this.error(new TomlError('Invalid number'));
22808 return this.returnNow(result);
22813 parseIntegerBin() {
22814 if (isBit(this.char)) {
22816 } else if (this.char === CHAR_LOWBAR) {
22817 return this.call(this.parseNoUnder);
22819 const result = Integer(this.state.buf);
22820 /* istanbul ignore if */
22822 if (result.isNaN()) {
22823 throw this.error(new TomlError('Invalid number'));
22825 return this.returnNow(result);
22833 // we enter here having just consumed the year and about to consume the hyphen
22834 if (this.state.buf.length < 4) {
22835 throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters'));
22838 this.state.result = this.state.buf;
22839 this.state.buf = '';
22840 return this.next(this.parseDateMonth);
22844 if (this.char === CHAR_HYPHEN) {
22845 if (this.state.buf.length < 2) {
22846 throw this.error(new TomlError('Months less than 10 must be zero padded to two characters'));
22849 this.state.result += '-' + this.state.buf;
22850 this.state.buf = '';
22851 return this.next(this.parseDateDay);
22852 } else if (isDigit(this.char)) {
22855 throw this.error(new TomlError('Incomplete datetime'));
22860 if (this.char === CHAR_T || this.char === CHAR_SP) {
22861 if (this.state.buf.length < 2) {
22862 throw this.error(new TomlError('Days less than 10 must be zero padded to two characters'));
22865 this.state.result += '-' + this.state.buf;
22866 this.state.buf = '';
22867 return this.next(this.parseStartTimeHour);
22868 } else if (this.atEndOfWord()) {
22869 return this.return(createDate(this.state.result + '-' + this.state.buf));
22870 } else if (isDigit(this.char)) {
22873 throw this.error(new TomlError('Incomplete datetime'));
22877 parseStartTimeHour() {
22878 if (this.atEndOfWord()) {
22879 return this.returnNow(createDate(this.state.result));
22881 return this.goto(this.parseTimeHour);
22886 if (this.char === CHAR_COLON) {
22887 if (this.state.buf.length < 2) {
22888 throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'));
22891 this.state.result += 'T' + this.state.buf;
22892 this.state.buf = '';
22893 return this.next(this.parseTimeMin);
22894 } else if (isDigit(this.char)) {
22897 throw this.error(new TomlError('Incomplete datetime'));
22902 if (this.state.buf.length < 2 && isDigit(this.char)) {
22904 } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
22905 this.state.result += ':' + this.state.buf;
22906 this.state.buf = '';
22907 return this.next(this.parseTimeSec);
22909 throw this.error(new TomlError('Incomplete datetime'));
22914 if (isDigit(this.char)) {
22917 if (this.state.buf.length === 2) {
22918 this.state.result += ':' + this.state.buf;
22919 this.state.buf = '';
22920 return this.next(this.parseTimeZoneOrFraction);
22923 throw this.error(new TomlError('Incomplete datetime'));
22927 parseOnlyTimeHour() {
22928 /* istanbul ignore else */
22929 if (this.char === CHAR_COLON) {
22930 if (this.state.buf.length < 2) {
22931 throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'));
22934 this.state.result = this.state.buf;
22935 this.state.buf = '';
22936 return this.next(this.parseOnlyTimeMin);
22938 throw this.error(new TomlError('Incomplete time'));
22942 parseOnlyTimeMin() {
22943 if (this.state.buf.length < 2 && isDigit(this.char)) {
22945 } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
22946 this.state.result += ':' + this.state.buf;
22947 this.state.buf = '';
22948 return this.next(this.parseOnlyTimeSec);
22950 throw this.error(new TomlError('Incomplete time'));
22954 parseOnlyTimeSec() {
22955 if (isDigit(this.char)) {
22958 if (this.state.buf.length === 2) {
22959 return this.next(this.parseOnlyTimeFractionMaybe);
22962 throw this.error(new TomlError('Incomplete time'));
22966 parseOnlyTimeFractionMaybe() {
22967 this.state.result += ':' + this.state.buf;
22969 if (this.char === CHAR_PERIOD) {
22970 this.state.buf = '';
22971 this.next(this.parseOnlyTimeFraction);
22973 return this.return(createTime(this.state.result));
22977 parseOnlyTimeFraction() {
22978 if (isDigit(this.char)) {
22980 } else if (this.atEndOfWord()) {
22981 if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds'));
22982 return this.returnNow(createTime(this.state.result + '.' + this.state.buf));
22984 throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
22988 parseTimeZoneOrFraction() {
22989 if (this.char === CHAR_PERIOD) {
22991 this.next(this.parseDateTimeFraction);
22992 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
22994 this.next(this.parseTimeZoneHour);
22995 } else if (this.char === CHAR_Z) {
22997 return this.return(createDatetime(this.state.result + this.state.buf));
22998 } else if (this.atEndOfWord()) {
22999 return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf));
23001 throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
23005 parseDateTimeFraction() {
23006 if (isDigit(this.char)) {
23008 } else if (this.state.buf.length === 1) {
23009 throw this.error(new TomlError('Expected digit in milliseconds'));
23010 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
23012 this.next(this.parseTimeZoneHour);
23013 } else if (this.char === CHAR_Z) {
23015 return this.return(createDatetime(this.state.result + this.state.buf));
23016 } else if (this.atEndOfWord()) {
23017 return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf));
23019 throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
23023 parseTimeZoneHour() {
23024 if (isDigit(this.char)) {
23025 this.consume(); // FIXME: No more regexps
23027 if (/\d\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep);
23029 throw this.error(new TomlError('Unexpected character in datetime, expected digit'));
23033 parseTimeZoneSep() {
23034 if (this.char === CHAR_COLON) {
23036 this.next(this.parseTimeZoneMin);
23038 throw this.error(new TomlError('Unexpected character in datetime, expected colon'));
23042 parseTimeZoneMin() {
23043 if (isDigit(this.char)) {
23045 if (/\d\d$/.test(this.state.buf)) return this.return(createDatetime(this.state.result + this.state.buf));
23047 throw this.error(new TomlError('Unexpected character in datetime, expected digit'));
23054 /* istanbul ignore else */
23055 if (this.char === CHAR_t) {
23057 return this.next(this.parseTrue_r);
23058 } else if (this.char === CHAR_f) {
23060 return this.next(this.parseFalse_a);
23065 if (this.char === CHAR_r) {
23067 return this.next(this.parseTrue_u);
23069 throw this.error(new TomlError('Invalid boolean, expected true or false'));
23074 if (this.char === CHAR_u) {
23076 return this.next(this.parseTrue_e);
23078 throw this.error(new TomlError('Invalid boolean, expected true or false'));
23083 if (this.char === CHAR_e) {
23084 return this.return(true);
23086 throw this.error(new TomlError('Invalid boolean, expected true or false'));
23091 if (this.char === CHAR_a) {
23093 return this.next(this.parseFalse_l);
23095 throw this.error(new TomlError('Invalid boolean, expected true or false'));
23100 if (this.char === CHAR_l) {
23102 return this.next(this.parseFalse_s);
23104 throw this.error(new TomlError('Invalid boolean, expected true or false'));
23109 if (this.char === CHAR_s) {
23111 return this.next(this.parseFalse_e);
23113 throw this.error(new TomlError('Invalid boolean, expected true or false'));
23118 if (this.char === CHAR_e) {
23119 return this.return(false);
23121 throw this.error(new TomlError('Invalid boolean, expected true or false'));
23127 parseInlineList() {
23128 if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
23130 } else if (this.char === Parser.END) {
23131 throw this.error(new TomlError('Unterminated inline array'));
23132 } else if (this.char === CHAR_NUM) {
23133 return this.call(this.parseComment);
23134 } else if (this.char === CHAR_RSQB) {
23135 return this.return(this.state.resultArr || InlineList());
23137 return this.callNow(this.parseValue, this.recordInlineListValue);
23141 recordInlineListValue(value) {
23142 if (this.state.resultArr) {
23143 const listType = this.state.resultArr[_contentType];
23144 const valueType = tomlType(value);
23146 if (listType !== valueType) {
23147 throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`));
23150 this.state.resultArr = InlineList(tomlType(value));
23153 if (isFloat(value) || isInteger(value)) {
23154 // unbox now that we've verified they're ok
23155 this.state.resultArr.push(value.valueOf());
23157 this.state.resultArr.push(value);
23160 return this.goto(this.parseInlineListNext);
23163 parseInlineListNext() {
23164 if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
23166 } else if (this.char === CHAR_NUM) {
23167 return this.call(this.parseComment);
23168 } else if (this.char === CHAR_COMMA) {
23169 return this.next(this.parseInlineList);
23170 } else if (this.char === CHAR_RSQB) {
23171 return this.goto(this.parseInlineList);
23173 throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'));
23179 parseInlineTable() {
23180 if (this.char === CHAR_SP || this.char === CTRL_I) {
23182 } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
23183 throw this.error(new TomlError('Unterminated inline array'));
23184 } else if (this.char === CHAR_RCUB) {
23185 return this.return(this.state.resultTable || InlineTable());
23187 if (!this.state.resultTable) this.state.resultTable = InlineTable();
23188 return this.callNow(this.parseAssign, this.recordInlineTableValue);
23192 recordInlineTableValue(kv) {
23193 let target = this.state.resultTable;
23194 let finalKey = kv.key.pop();
23196 for (let kw of kv.key) {
23197 if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
23198 throw this.error(new TomlError("Can't redefine existing key"));
23201 target = target[kw] = target[kw] || Table();
23204 if (hasKey(target, finalKey)) {
23205 throw this.error(new TomlError("Can't redefine existing key"));
23208 if (isInteger(kv.value) || isFloat(kv.value)) {
23209 target[finalKey] = kv.value.valueOf();
23211 target[finalKey] = kv.value;
23214 return this.goto(this.parseInlineTableNext);
23217 parseInlineTableNext() {
23218 if (this.char === CHAR_SP || this.char === CTRL_I) {
23220 } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
23221 throw this.error(new TomlError('Unterminated inline array'));
23222 } else if (this.char === CHAR_COMMA) {
23223 return this.next(this.parseInlineTable);
23224 } else if (this.char === CHAR_RCUB) {
23225 return this.goto(this.parseInlineTable);
23227 throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'));
23235 tomlParser.makeParserClass = makeParserClass_1;
23236 tomlParser.TomlError = TomlError_1;
23238 var parsePrettyError = prettyError;
23240 function prettyError(err, buf) {
23241 /* istanbul ignore if */
23242 if (err.pos == null || err.line == null) return err;
23243 let msg = err.message;
23244 msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\n`;
23245 /* istanbul ignore else */
23247 if (buf && buf.split) {
23248 const lines = buf.split(/\n/);
23249 const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length;
23250 let linePadding = ' ';
23252 while (linePadding.length < lineNumWidth) linePadding += ' ';
23254 for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {
23255 let lineNum = String(ii + 1);
23256 if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum;
23258 if (err.line === ii) {
23259 msg += lineNum + '> ' + lines[ii] + '\n';
23260 msg += linePadding + ' ';
23262 for (let hh = 0; hh < err.col; ++hh) {
23268 msg += lineNum + ': ' + lines[ii] + '\n';
23273 err.message = msg + '\n';
23277 var parseString_1 = parseString;
23279 function parseString(str) {
23280 if (global.Buffer && global.Buffer.isBuffer(str)) {
23281 str = str.toString('utf8');
23284 const parser = new tomlParser();
23288 return parser.finish();
23290 throw parsePrettyError(err, str);
23294 var loadToml = function (filePath, content) {
23296 return parseString_1(content);
23298 error.message = `TOML Error in ${filePath}:\n${error.message}`;
23303 var caller = function () {
23304 // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
23305 var origPrepareStackTrace = Error.prepareStackTrace;
23307 Error.prepareStackTrace = function (_, stack) {
23311 var stack = new Error().stack;
23312 Error.prepareStackTrace = origPrepareStackTrace;
23313 return stack[2].getFileName();
23316 var pathParse = createCommonjsModule(function (module) {
23318 var isWindows = process.platform === 'win32'; // Regex to split a windows path into three parts: [*, device, slash,
23319 // tail] windows-only
23321 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; // Regex to split the tail part of the above into [*, dir, basename, ext]
23323 var splitTailRe = /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
23324 var win32 = {}; // Function to split a filename into [root, dir, basename, ext]
23326 function win32SplitPath(filename) {
23327 // Separate device+slash from tail
23328 var result = splitDeviceRe.exec(filename),
23329 device = (result[1] || '') + (result[2] || ''),
23330 tail = result[3] || ''; // Split the tail into dir, basename and extension
23332 var result2 = splitTailRe.exec(tail),
23334 basename = result2[2],
23336 return [device, dir, basename, ext];
23339 win32.parse = function (pathString) {
23340 if (typeof pathString !== 'string') {
23341 throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
23344 var allParts = win32SplitPath(pathString);
23346 if (!allParts || allParts.length !== 4) {
23347 throw new TypeError("Invalid path '" + pathString + "'");
23352 dir: allParts[0] + allParts[1].slice(0, -1),
23355 name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
23357 }; // Split a filename into [root, dir, basename, ext], unix version
23358 // 'root' is just a slash, or nothing.
23361 var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
23364 function posixSplitPath(filename) {
23365 return splitPathRe.exec(filename).slice(1);
23368 posix.parse = function (pathString) {
23369 if (typeof pathString !== 'string') {
23370 throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
23373 var allParts = posixSplitPath(pathString);
23375 if (!allParts || allParts.length !== 4) {
23376 throw new TypeError("Invalid path '" + pathString + "'");
23379 allParts[1] = allParts[1] || '';
23380 allParts[2] = allParts[2] || '';
23381 allParts[3] = allParts[3] || '';
23384 dir: allParts[0] + allParts[1].slice(0, -1),
23387 name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
23391 if (isWindows) module.exports = win32.parse;else
23393 module.exports = posix.parse;
23394 module.exports.posix = posix.parse;
23395 module.exports.win32 = win32.parse;
23397 var pathParse_1 = pathParse.posix;
23398 var pathParse_2 = pathParse.win32;
23400 var parse$2 = path$2.parse || pathParse;
23402 var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) {
23405 if (/^([A-Za-z]:)/.test(absoluteStart)) {
23407 } else if (/^\\\\/.test(absoluteStart)) {
23411 var paths = [absoluteStart];
23412 var parsed = parse$2(absoluteStart);
23414 while (parsed.dir !== paths[paths.length - 1]) {
23415 paths.push(parsed.dir);
23416 parsed = parse$2(parsed.dir);
23419 return paths.reduce(function (dirs, aPath) {
23420 return dirs.concat(modules.map(function (moduleDir) {
23421 return path$2.resolve(prefix, aPath, moduleDir);
23426 var nodeModulesPaths = function nodeModulesPaths(start, opts, request) {
23427 var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ['node_modules'];
23429 if (opts && typeof opts.paths === 'function') {
23430 return opts.paths(request, start, function () {
23431 return getNodeModulesDirs(start, modules);
23435 var dirs = getNodeModulesDirs(start, modules);
23436 return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
23439 var normalizeOptions$2 = function (x, opts) {
23441 * This file is purposefully a passthrough. It's expected that third-party
23442 * environments will override it at runtime in order to inject special logic
23443 * into `resolve` (by manipulating the options). One such example is the PnP
23444 * code path in Yarn.
23450 var async_hooks = ">= 8";
23451 var buffer_ieee754 = "< 0.9.7";
23453 var child_process = true;
23454 var cluster = true;
23455 var console$1 = true;
23456 var constants$1 = true;
23458 var _debug_agent = ">= 1 && < 8";
23459 var _debugger = "< 8";
23464 var freelist = "< 6";
23466 var _http_agent = ">= 0.11.1";
23467 var _http_client = ">= 0.11.1";
23468 var _http_common = ">= 0.11.1";
23469 var _http_incoming = ">= 0.11.1";
23470 var _http_outgoing = ">= 0.11.1";
23471 var _http_server = ">= 0.11.1";
23473 var http2 = ">= 8.8";
23475 var inspector = ">= 8.0.0";
23476 var _linklist = "< 8";
23477 var module$1 = true;
23481 var perf_hooks = ">= 8.5";
23482 var process$1 = ">= 1";
23483 var punycode = true;
23484 var querystring = true;
23485 var readline = true;
23487 var smalloc = ">= 0.11.5 && < 3";
23488 var _stream_duplex = ">= 0.9.4";
23489 var _stream_transform = ">= 0.9.4";
23490 var _stream_wrap = ">= 1.4.1";
23491 var _stream_passthrough = ">= 0.9.4";
23492 var _stream_readable = ">= 0.9.4";
23493 var _stream_writable = ">= 0.9.4";
23495 var string_decoder = true;
23498 var _tls_common = ">= 0.11.13";
23499 var _tls_legacy = ">= 0.11.3 && < 10";
23500 var _tls_wrap = ">= 0.11.3";
23502 var trace_events = ">= 10";
23508 var wasi = ">= 13.4 && < 13.5";
23509 var worker_threads = ">= 11.7";
23513 async_hooks: async_hooks,
23514 buffer_ieee754: buffer_ieee754,
23516 child_process: child_process,
23518 console: console$1,
23519 constants: constants$1,
23521 _debug_agent: _debug_agent,
23522 _debugger: _debugger,
23527 freelist: freelist,
23533 _http_agent: _http_agent,
23534 _http_client: _http_client,
23535 _http_common: _http_common,
23536 _http_incoming: _http_incoming,
23537 _http_outgoing: _http_outgoing,
23538 _http_server: _http_server,
23542 inspector: inspector,
23543 _linklist: _linklist,
23546 "node-inspect/lib/_inspect": ">= 7.6.0 && < 12",
23547 "node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12",
23548 "node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12",
23551 perf_hooks: perf_hooks,
23552 process: process$1,
23553 punycode: punycode,
23554 querystring: querystring,
23555 readline: readline,
23558 _stream_duplex: _stream_duplex,
23559 _stream_transform: _stream_transform,
23560 _stream_wrap: _stream_wrap,
23561 _stream_passthrough: _stream_passthrough,
23562 _stream_readable: _stream_readable,
23563 _stream_writable: _stream_writable,
23565 string_decoder: string_decoder,
23568 _tls_common: _tls_common,
23569 _tls_legacy: _tls_legacy,
23570 _tls_wrap: _tls_wrap,
23572 trace_events: trace_events,
23576 "v8/tools/arguments": ">= 10 && < 12",
23577 "v8/tools/codemap": [
23581 "v8/tools/consarray": [
23585 "v8/tools/csvparser": [
23589 "v8/tools/logreader": [
23593 "v8/tools/profile_view": [
23597 "v8/tools/splaytree": [
23604 worker_threads: worker_threads,
23608 var core$2 = /*#__PURE__*/Object.freeze({
23611 async_hooks: async_hooks,
23612 buffer_ieee754: buffer_ieee754,
23614 child_process: child_process,
23616 console: console$1,
23617 constants: constants$1,
23619 _debug_agent: _debug_agent,
23620 _debugger: _debugger,
23625 freelist: freelist,
23627 _http_agent: _http_agent,
23628 _http_client: _http_client,
23629 _http_common: _http_common,
23630 _http_incoming: _http_incoming,
23631 _http_outgoing: _http_outgoing,
23632 _http_server: _http_server,
23636 inspector: inspector,
23637 _linklist: _linklist,
23642 perf_hooks: perf_hooks,
23643 process: process$1,
23644 punycode: punycode,
23645 querystring: querystring,
23646 readline: readline,
23649 _stream_duplex: _stream_duplex,
23650 _stream_transform: _stream_transform,
23651 _stream_wrap: _stream_wrap,
23652 _stream_passthrough: _stream_passthrough,
23653 _stream_readable: _stream_readable,
23654 _stream_writable: _stream_writable,
23656 string_decoder: string_decoder,
23659 _tls_common: _tls_common,
23660 _tls_legacy: _tls_legacy,
23661 _tls_wrap: _tls_wrap,
23663 trace_events: trace_events,
23670 worker_threads: worker_threads,
23675 var data = getCjsExportFromNamespace(core$2);
23677 var current = process.versions && process.versions.node && process.versions.node.split('.') || [];
23679 function specifierIncluded(specifier) {
23680 var parts = specifier.split(' ');
23681 var op = parts.length > 1 ? parts[0] : '=';
23682 var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.');
23684 for (var i = 0; i < 3; ++i) {
23685 var cur = Number(current[i] || 0);
23686 var ver = Number(versionParts[i] || 0);
23689 continue; // eslint-disable-line no-restricted-syntax, no-continue
23694 } else if (op === '>=') {
23701 return op === '>=';
23704 function matchesRange(range) {
23705 var specifiers = range.split(/ ?&& ?/);
23707 if (specifiers.length === 0) {
23711 for (var i = 0; i < specifiers.length; ++i) {
23712 if (!specifierIncluded(specifiers[i])) {
23720 function versionIncluded(specifierValue) {
23721 if (typeof specifierValue === 'boolean') {
23722 return specifierValue;
23725 if (specifierValue && typeof specifierValue === 'object') {
23726 for (var i = 0; i < specifierValue.length; ++i) {
23727 if (matchesRange(specifierValue[i])) {
23735 return matchesRange(specifierValue);
23740 for (var mod in data) {
23741 // eslint-disable-line no-restricted-syntax
23742 if (Object.prototype.hasOwnProperty.call(data, mod)) {
23743 core$3[mod] = versionIncluded(data[mod]);
23747 var core_1 = core$3;
23749 var isCore = function isCore(x) {
23750 return Object.prototype.hasOwnProperty.call(core_1, x);
23753 var realpath = fs$3.realpath && typeof fs$3.realpath.native === 'function' ? fs$3.realpath.native : fs$3.realpath;
23755 var defaultIsFile = function isFile(file, cb) {
23756 fs$3.stat(file, function (err, stat) {
23758 return cb(null, stat.isFile() || stat.isFIFO());
23761 if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
23766 var defaultIsDir = function isDirectory(dir, cb) {
23767 fs$3.stat(dir, function (err, stat) {
23769 return cb(null, stat.isDirectory());
23772 if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
23777 var maybeUnwrapSymlink = function maybeUnwrapSymlink(x, opts, cb) {
23778 if (opts && opts.preserveSymlinks === false) {
23779 realpath(x, function (realPathErr, realPath) {
23780 if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr);else cb(null, realPathErr ? x : realPath);
23787 var getPackageCandidates = function getPackageCandidates(x, start, opts) {
23788 var dirs = nodeModulesPaths(start, opts, x);
23790 for (var i = 0; i < dirs.length; i++) {
23791 dirs[i] = path$2.join(dirs[i], x);
23797 var async = function resolve(x, options, callback) {
23799 var opts = options;
23801 if (typeof options === 'function') {
23806 if (typeof x !== 'string') {
23807 var err = new TypeError('Path must be a string.');
23808 return process.nextTick(function () {
23813 opts = normalizeOptions$2(x, opts);
23814 var isFile = opts.isFile || defaultIsFile;
23815 var isDirectory = opts.isDirectory || defaultIsDir;
23816 var readFile = opts.readFile || fs$3.readFile;
23817 var packageIterator = opts.packageIterator;
23818 var extensions = opts.extensions || ['.js'];
23819 var basedir = opts.basedir || path$2.dirname(caller());
23820 var parent = opts.filename || basedir;
23821 opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
23823 var absoluteStart = path$2.resolve(basedir);
23824 maybeUnwrapSymlink(absoluteStart, opts, function (err, realStart) {
23825 if (err) cb(err);else init(realStart);
23829 function init(basedir) {
23830 if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
23831 res = path$2.resolve(basedir, x);
23832 if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';
23834 if (/\/$/.test(x) && res === basedir) {
23835 loadAsDirectory(res, opts.package, onfile);
23836 } else loadAsFile(res, opts.package, onfile);
23837 } else if (isCore(x)) {
23838 return cb(null, x);
23839 } else loadNodeModules(x, basedir, function (err, n, pkg) {
23840 if (err) cb(err);else if (n) {
23841 return maybeUnwrapSymlink(n, opts, function (err, realN) {
23845 cb(null, realN, pkg);
23849 var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
23850 moduleError.code = 'MODULE_NOT_FOUND';
23856 function onfile(err, m, pkg) {
23857 if (err) cb(err);else if (m) cb(null, m, pkg);else loadAsDirectory(res, function (err, d, pkg) {
23858 if (err) cb(err);else if (d) {
23859 maybeUnwrapSymlink(d, opts, function (err, realD) {
23863 cb(null, realD, pkg);
23867 var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
23868 moduleError.code = 'MODULE_NOT_FOUND';
23874 function loadAsFile(x, thePackage, callback) {
23875 var loadAsFilePackage = thePackage;
23878 if (typeof loadAsFilePackage === 'function') {
23879 cb = loadAsFilePackage;
23880 loadAsFilePackage = undefined;
23883 var exts = [''].concat(extensions);
23884 load(exts, x, loadAsFilePackage);
23886 function load(exts, x, loadPackage) {
23887 if (exts.length === 0) return cb(null, undefined, loadPackage);
23888 var file = x + exts[0];
23889 var pkg = loadPackage;
23890 if (pkg) onpkg(null, pkg);else loadpkg(path$2.dirname(file), onpkg);
23892 function onpkg(err, pkg_, dir) {
23894 if (err) return cb(err);
23896 if (dir && pkg && opts.pathFilter) {
23897 var rfile = path$2.relative(dir, file);
23898 var rel = rfile.slice(0, rfile.length - exts[0].length);
23899 var r = opts.pathFilter(pkg, x, rel);
23900 if (r) return load([''].concat(extensions.slice()), path$2.resolve(dir, r), pkg);
23903 isFile(file, onex);
23906 function onex(err, ex) {
23907 if (err) return cb(err);
23908 if (ex) return cb(null, file, pkg);
23909 load(exts.slice(1), x, pkg);
23914 function loadpkg(dir, cb) {
23915 if (dir === '' || dir === '/') return cb(null);
23917 if (process.platform === 'win32' && /^\w:[/\\]*$/.test(dir)) {
23921 if (/[/\\]node_modules[/\\]*$/.test(dir)) return cb(null);
23922 maybeUnwrapSymlink(dir, opts, function (unwrapErr, pkgdir) {
23923 if (unwrapErr) return loadpkg(path$2.dirname(dir), cb);
23924 var pkgfile = path$2.join(pkgdir, 'package.json');
23925 isFile(pkgfile, function (err, ex) {
23926 // on err, ex is false
23927 if (!ex) return loadpkg(path$2.dirname(dir), cb);
23928 readFile(pkgfile, function (err, body) {
23932 var pkg = JSON.parse(body);
23933 } catch (jsonErr) {}
23935 if (pkg && opts.packageFilter) {
23936 pkg = opts.packageFilter(pkg, pkgfile);
23939 cb(null, pkg, dir);
23945 function loadAsDirectory(x, loadAsDirectoryPackage, callback) {
23947 var fpkg = loadAsDirectoryPackage;
23949 if (typeof fpkg === 'function') {
23951 fpkg = opts.package;
23954 maybeUnwrapSymlink(x, opts, function (unwrapErr, pkgdir) {
23955 if (unwrapErr) return cb(unwrapErr);
23956 var pkgfile = path$2.join(pkgdir, 'package.json');
23957 isFile(pkgfile, function (err, ex) {
23958 if (err) return cb(err);
23959 if (!ex) return loadAsFile(path$2.join(x, 'index'), fpkg, cb);
23960 readFile(pkgfile, function (err, body) {
23961 if (err) return cb(err);
23964 var pkg = JSON.parse(body);
23965 } catch (jsonErr) {}
23967 if (pkg && opts.packageFilter) {
23968 pkg = opts.packageFilter(pkg, pkgfile);
23971 if (pkg && pkg.main) {
23972 if (typeof pkg.main !== 'string') {
23973 var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
23974 mainError.code = 'INVALID_PACKAGE_MAIN';
23975 return cb(mainError);
23978 if (pkg.main === '.' || pkg.main === './') {
23979 pkg.main = 'index';
23982 loadAsFile(path$2.resolve(x, pkg.main), pkg, function (err, m, pkg) {
23983 if (err) return cb(err);
23984 if (m) return cb(null, m, pkg);
23985 if (!pkg) return loadAsFile(path$2.join(x, 'index'), pkg, cb);
23986 var dir = path$2.resolve(x, pkg.main);
23987 loadAsDirectory(dir, pkg, function (err, n, pkg) {
23988 if (err) return cb(err);
23989 if (n) return cb(null, n, pkg);
23990 loadAsFile(path$2.join(x, 'index'), pkg, cb);
23996 loadAsFile(path$2.join(x, '/index'), pkg, cb);
24002 function processDirs(cb, dirs) {
24003 if (dirs.length === 0) return cb(null, undefined);
24005 isDirectory(path$2.dirname(dir), isdir);
24007 function isdir(err, isdir) {
24008 if (err) return cb(err);
24009 if (!isdir) return processDirs(cb, dirs.slice(1));
24010 loadAsFile(dir, opts.package, onfile);
24013 function onfile(err, m, pkg) {
24014 if (err) return cb(err);
24015 if (m) return cb(null, m, pkg);
24016 loadAsDirectory(dir, opts.package, ondir);
24019 function ondir(err, n, pkg) {
24020 if (err) return cb(err);
24021 if (n) return cb(null, n, pkg);
24022 processDirs(cb, dirs.slice(1));
24026 function loadNodeModules(x, start, cb) {
24027 var thunk = function () {
24028 return getPackageCandidates(x, start, opts);
24031 processDirs(cb, packageIterator ? packageIterator(x, start, thunk, opts) : thunk());
24035 var realpath$1 = fs$3.realpathSync && typeof fs$3.realpathSync.native === 'function' ? fs$3.realpathSync.native : fs$3.realpathSync;
24037 var defaultIsFile$1 = function isFile(file) {
24039 var stat = fs$3.statSync(file);
24041 if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
24045 return stat.isFile() || stat.isFIFO();
24048 var defaultIsDir$1 = function isDirectory(dir) {
24050 var stat = fs$3.statSync(dir);
24052 if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
24056 return stat.isDirectory();
24059 var maybeUnwrapSymlink$1 = function maybeUnwrapSymlink(x, opts) {
24060 if (opts && opts.preserveSymlinks === false) {
24062 return realpath$1(x);
24063 } catch (realPathErr) {
24064 if (realPathErr.code !== 'ENOENT') {
24073 var getPackageCandidates$1 = function getPackageCandidates(x, start, opts) {
24074 var dirs = nodeModulesPaths(start, opts, x);
24076 for (var i = 0; i < dirs.length; i++) {
24077 dirs[i] = path$2.join(dirs[i], x);
24083 var sync = function resolveSync(x, options) {
24084 if (typeof x !== 'string') {
24085 throw new TypeError('Path must be a string.');
24088 var opts = normalizeOptions$2(x, options);
24089 var isFile = opts.isFile || defaultIsFile$1;
24090 var readFileSync = opts.readFileSync || fs$3.readFileSync;
24091 var isDirectory = opts.isDirectory || defaultIsDir$1;
24092 var packageIterator = opts.packageIterator;
24093 var extensions = opts.extensions || ['.js'];
24094 var basedir = opts.basedir || path$2.dirname(caller());
24095 var parent = opts.filename || basedir;
24096 opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
24098 var absoluteStart = maybeUnwrapSymlink$1(path$2.resolve(basedir), opts);
24100 if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
24101 var res = path$2.resolve(absoluteStart, x);
24102 if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';
24103 var m = loadAsFileSync(res) || loadAsDirectorySync(res);
24104 if (m) return maybeUnwrapSymlink$1(m, opts);
24105 } else if (isCore(x)) {
24108 var n = loadNodeModulesSync(x, absoluteStart);
24109 if (n) return maybeUnwrapSymlink$1(n, opts);
24112 var err = new Error("Cannot find module '" + x + "' from '" + parent + "'");
24113 err.code = 'MODULE_NOT_FOUND';
24116 function loadAsFileSync(x) {
24117 var pkg = loadpkg(path$2.dirname(x));
24119 if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) {
24120 var rfile = path$2.relative(pkg.dir, x);
24121 var r = opts.pathFilter(pkg.pkg, x, rfile);
24124 x = path$2.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign
24132 for (var i = 0; i < extensions.length; i++) {
24133 var file = x + extensions[i];
24135 if (isFile(file)) {
24141 function loadpkg(dir) {
24142 if (dir === '' || dir === '/') return;
24144 if (process.platform === 'win32' && /^\w:[/\\]*$/.test(dir)) {
24148 if (/[/\\]node_modules[/\\]*$/.test(dir)) return;
24149 var pkgfile = path$2.join(maybeUnwrapSymlink$1(dir, opts), 'package.json');
24151 if (!isFile(pkgfile)) {
24152 return loadpkg(path$2.dirname(dir));
24155 var body = readFileSync(pkgfile);
24158 var pkg = JSON.parse(body);
24159 } catch (jsonErr) {}
24161 if (pkg && opts.packageFilter) {
24162 // v2 will pass pkgfile
24163 pkg = opts.packageFilter(pkg,
24165 dir); // eslint-disable-line spaced-comment
24174 function loadAsDirectorySync(x) {
24175 var pkgfile = path$2.join(maybeUnwrapSymlink$1(x, opts), '/package.json');
24177 if (isFile(pkgfile)) {
24179 var body = readFileSync(pkgfile, 'UTF8');
24180 var pkg = JSON.parse(body);
24183 if (pkg && opts.packageFilter) {
24184 // v2 will pass pkgfile
24185 pkg = opts.packageFilter(pkg,
24187 x); // eslint-disable-line spaced-comment
24190 if (pkg && pkg.main) {
24191 if (typeof pkg.main !== 'string') {
24192 var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
24193 mainError.code = 'INVALID_PACKAGE_MAIN';
24197 if (pkg.main === '.' || pkg.main === './') {
24198 pkg.main = 'index';
24202 var m = loadAsFileSync(path$2.resolve(x, pkg.main));
24204 var n = loadAsDirectorySync(path$2.resolve(x, pkg.main));
24210 return loadAsFileSync(path$2.join(x, '/index'));
24213 function loadNodeModulesSync(x, start) {
24214 var thunk = function () {
24215 return getPackageCandidates$1(x, start, opts);
24218 var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk();
24220 for (var i = 0; i < dirs.length; i++) {
24223 if (isDirectory(path$2.dirname(dir))) {
24224 var m = loadAsFileSync(dir);
24226 var n = loadAsDirectorySync(dir);
24233 async.core = core_1;
24234 async.isCore = isCore;
24236 var resolve = async;
24238 // eslint-disable-next-line prefer-destructuring
24241 let resolve$1 = require.resolve; // In the VS Code and Atom extensions `require` is overridden and `require.resolve` doesn't support the 2nd argument.
24243 if (resolve$1.length === 1 || process.env.PRETTIER_FALLBACK_RESOLVE) {
24244 resolve$1 = (id, options) => {
24247 if (options && options.paths && options.paths.length === 1) {
24248 basedir = options.paths[0];
24251 return resolve.sync(id, {
24257 var resolve_1 = resolve$1;
24259 const getExplorerMemoized = mem_1(opts => {
24260 const cosmiconfig = thirdParty["cosmiconfig" + (opts.sync ? "Sync" : "")];
24261 const explorer = cosmiconfig("prettier", {
24263 transform: result => {
24264 if (result && result.config) {
24265 if (typeof result.config === "string") {
24266 const dir = path$2.dirname(result.filepath);
24269 const modulePath = resolve_1(result.config, {
24272 result.config = require(modulePath);
24274 // Original message contains `__filename`, can't pass tests
24275 error.message = `Cannot find module '${result.config}' from '${dir}'`;
24280 if (typeof result.config !== "object") {
24281 throw new Error("Config is only allowed to be an object, " + `but received ${typeof result.config} in "${result.filepath}"`);
24284 delete result.config.$schema;
24289 searchPlaces: ["package.json", ".prettierrc", ".prettierrc.json", ".prettierrc.yaml", ".prettierrc.yml", ".prettierrc.js", "prettier.config.js", ".prettierrc.toml"],
24296 cacheKey: JSON.stringify
24298 /** @param {{ cache: boolean, sync: boolean }} opts */
24300 function getExplorer(opts) {
24301 // Normalize opts before passing to a memoized function
24302 opts = Object.assign({
24306 return getExplorerMemoized(opts);
24309 function _resolveConfig(filePath, opts, sync) {
24310 opts = Object.assign({
24314 cache: !!opts.useCache,
24316 editorconfig: !!opts.editorconfig
24321 } = getExplorer(loadOpts);
24322 const loadEditorConfig = resolveConfigEditorconfig.getLoadFunction(loadOpts);
24323 const arr = [opts.config ? load(opts.config) : search(filePath), loadEditorConfig(filePath)];
24325 const unwrapAndMerge = ([result, editorConfigured]) => {
24326 const merged = Object.assign({}, editorConfigured, {}, mergeOverrides(result, filePath));
24327 ["plugins", "pluginSearchDirs"].forEach(optionName => {
24328 if (Array.isArray(merged[optionName])) {
24329 merged[optionName] = merged[optionName].map(value => typeof value === "string" && value.startsWith(".") // relative path
24330 ? path$2.resolve(path$2.dirname(result.filepath), value) : value);
24334 if (!result && !editorConfigured) {
24341 if (loadOpts.sync) {
24342 return unwrapAndMerge(arr);
24345 return Promise.all(arr).then(unwrapAndMerge);
24348 const resolveConfig = (filePath, opts) => _resolveConfig(filePath, opts, false);
24350 resolveConfig.sync = (filePath, opts) => _resolveConfig(filePath, opts, true);
24352 function clearCache$1() {
24353 mem_1.clear(getExplorerMemoized);
24354 resolveConfigEditorconfig.clearCache();
24357 async function resolveConfigFile(filePath) {
24363 const result = await search(filePath);
24364 return result ? result.filepath : null;
24367 resolveConfigFile.sync = filePath => {
24373 const result = search(filePath);
24374 return result ? result.filepath : null;
24377 function mergeOverrides(configResult, filePath) {
24380 filepath: configPath
24381 } = configResult || {};
24383 const _ref = config || {},
24387 options = _objectWithoutPropertiesLoose(_ref, ["overrides"]);
24389 if (filePath && overrides) {
24390 const relativeFilePath = path$2.relative(path$2.dirname(configPath), filePath);
24392 for (const override of overrides) {
24393 if (pathMatchesGlobs(relativeFilePath, override.files, override.excludeFiles)) {
24394 Object.assign(options, override.options);
24400 } // Based on eslint: https://github.com/eslint/eslint/blob/master/lib/config/config-ops.js
24403 function pathMatchesGlobs(filePath, patterns, excludedPatterns) {
24404 const patternList = [].concat(patterns);
24405 const excludedPatternList = [].concat(excludedPatterns || []);
24410 return patternList.some(pattern => minimatch_1(filePath, pattern, opts)) && !excludedPatternList.some(excludedPattern => minimatch_1(filePath, excludedPattern, opts));
24413 var resolveConfig_1 = {
24416 clearCache: clearCache$1
24420 * @typedef {{ ignorePath?: string, withNodeModules?: boolean, plugins: object }} FileInfoOptions
24421 * @typedef {{ ignored: boolean, inferredParser: string | null }} FileInfoResult
24425 * @param {string} filePath
24426 * @param {FileInfoOptions} opts
24427 * @returns {Promise<FileInfoResult>}
24429 * Please note that prettier.getFileInfo() expects opts.plugins to be an array of paths,
24430 * not an object. A transformation from this array to an object is automatically done
24431 * internally by the method wrapper. See withPlugins() in index.js.
24435 async function getFileInfo(filePath, opts) {
24436 if (typeof filePath !== "string") {
24437 throw new TypeError(`expect \`filePath\` to be a string, got \`${typeof filePath}\``);
24440 const ignorer = await createIgnorer_1(opts.ignorePath, opts.withNodeModules);
24441 return _getFileInfo({
24443 filePath: normalizeFilePath(filePath, opts.ignorePath),
24444 plugins: opts.plugins,
24445 resolveConfig: opts.resolveConfig,
24450 * @param {string} filePath
24451 * @param {FileInfoOptions} opts
24452 * @returns {FileInfoResult}
24456 getFileInfo.sync = function (filePath, opts) {
24457 if (typeof filePath !== "string") {
24458 throw new TypeError(`expect \`filePath\` to be a string, got \`${typeof filePath}\``);
24461 const ignorer = createIgnorer_1.sync(opts.ignorePath, opts.withNodeModules);
24462 return _getFileInfo({
24464 filePath: normalizeFilePath(filePath, opts.ignorePath),
24465 plugins: opts.plugins,
24466 resolveConfig: opts.resolveConfig,
24471 function _getFileInfo({
24475 resolveConfig = false,
24479 ignored: ignorer.ignores(filePath),
24480 inferredParser: options$1.inferParser(filePath, plugins) || null
24483 if (!fileInfo.inferredParser && resolveConfig) {
24485 return resolveConfig_1.resolveConfig(filePath).then(resolvedConfig => {
24486 if (resolvedConfig && resolvedConfig.parser) {
24487 fileInfo.inferredParser = resolvedConfig.parser;
24494 const resolvedConfig = resolveConfig_1.resolveConfig.sync(filePath);
24496 if (resolvedConfig && resolvedConfig.parser) {
24497 fileInfo.inferredParser = resolvedConfig.parser;
24504 function normalizeFilePath(filePath, ignorePath) {
24505 return ignorePath ? path$2.relative(path$2.dirname(ignorePath), filePath) : filePath;
24508 var getFileInfo_1 = getFileInfo;
24511 * Removes all key-value entries from the list cache.
24515 * @memberOf ListCache
24517 function listCacheClear() {
24518 this.__data__ = [];
24522 var _listCacheClear = listCacheClear;
24526 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
24527 * comparison between two values to determine if they are equivalent.
24533 * @param {*} value The value to compare.
24534 * @param {*} other The other value to compare.
24535 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
24538 * var object = { 'a': 1 };
24539 * var other = { 'a': 1 };
24541 * _.eq(object, object);
24544 * _.eq(object, other);
24550 * _.eq('a', Object('a'));
24556 function eq(value, other) {
24557 return value === other || value !== value && other !== other;
24563 * Gets the index at which the `key` is found in `array` of key-value pairs.
24566 * @param {Array} array The array to inspect.
24567 * @param {*} key The key to search for.
24568 * @returns {number} Returns the index of the matched value, else `-1`.
24571 function assocIndexOf(array, key) {
24572 var length = array.length;
24575 if (eq_1(array[length][0], key)) {
24583 var _assocIndexOf = assocIndexOf;
24585 /** Used for built-in method references. */
24587 var arrayProto = Array.prototype;
24588 /** Built-in value references. */
24590 var splice = arrayProto.splice;
24592 * Removes `key` and its value from the list cache.
24596 * @memberOf ListCache
24597 * @param {string} key The key of the value to remove.
24598 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
24601 function listCacheDelete(key) {
24602 var data = this.__data__,
24603 index = _assocIndexOf(data, key);
24609 var lastIndex = data.length - 1;
24611 if (index == lastIndex) {
24614 splice.call(data, index, 1);
24621 var _listCacheDelete = listCacheDelete;
24624 * Gets the list cache value for `key`.
24628 * @memberOf ListCache
24629 * @param {string} key The key of the value to get.
24630 * @returns {*} Returns the entry value.
24633 function listCacheGet(key) {
24634 var data = this.__data__,
24635 index = _assocIndexOf(data, key);
24636 return index < 0 ? undefined : data[index][1];
24639 var _listCacheGet = listCacheGet;
24642 * Checks if a list cache value for `key` exists.
24646 * @memberOf ListCache
24647 * @param {string} key The key of the entry to check.
24648 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
24651 function listCacheHas(key) {
24652 return _assocIndexOf(this.__data__, key) > -1;
24655 var _listCacheHas = listCacheHas;
24658 * Sets the list cache `key` to `value`.
24662 * @memberOf ListCache
24663 * @param {string} key The key of the value to set.
24664 * @param {*} value The value to set.
24665 * @returns {Object} Returns the list cache instance.
24668 function listCacheSet(key, value) {
24669 var data = this.__data__,
24670 index = _assocIndexOf(data, key);
24674 data.push([key, value]);
24676 data[index][1] = value;
24682 var _listCacheSet = listCacheSet;
24685 * Creates an list cache object.
24689 * @param {Array} [entries] The key-value pairs to cache.
24692 function ListCache(entries) {
24694 length = entries == null ? 0 : entries.length;
24697 while (++index < length) {
24698 var entry = entries[index];
24699 this.set(entry[0], entry[1]);
24701 } // Add methods to `ListCache`.
24704 ListCache.prototype.clear = _listCacheClear;
24705 ListCache.prototype['delete'] = _listCacheDelete;
24706 ListCache.prototype.get = _listCacheGet;
24707 ListCache.prototype.has = _listCacheHas;
24708 ListCache.prototype.set = _listCacheSet;
24709 var _ListCache = ListCache;
24712 * Removes all key-value entries from the stack.
24719 function stackClear() {
24720 this.__data__ = new _ListCache();
24724 var _stackClear = stackClear;
24727 * Removes `key` and its value from the stack.
24732 * @param {string} key The key of the value to remove.
24733 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
24735 function stackDelete(key) {
24736 var data = this.__data__,
24737 result = data['delete'](key);
24738 this.size = data.size;
24742 var _stackDelete = stackDelete;
24745 * Gets the stack value for `key`.
24750 * @param {string} key The key of the value to get.
24751 * @returns {*} Returns the entry value.
24753 function stackGet(key) {
24754 return this.__data__.get(key);
24757 var _stackGet = stackGet;
24760 * Checks if a stack value for `key` exists.
24765 * @param {string} key The key of the entry to check.
24766 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
24768 function stackHas(key) {
24769 return this.__data__.has(key);
24772 var _stackHas = stackHas;
24774 /** Detect free variable `global` from Node.js. */
24776 var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
24777 var _freeGlobal = freeGlobal;
24779 /** Detect free variable `self`. */
24781 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
24782 /** Used as a reference to the global object. */
24784 var root = _freeGlobal || freeSelf || Function('return this')();
24787 /** Built-in value references. */
24789 var Symbol$1 = _root.Symbol;
24790 var _Symbol = Symbol$1;
24792 /** Used for built-in method references. */
24794 var objectProto = Object.prototype;
24795 /** Used to check objects for own properties. */
24797 var hasOwnProperty$2 = objectProto.hasOwnProperty;
24799 * Used to resolve the
24800 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
24804 var nativeObjectToString = objectProto.toString;
24805 /** Built-in value references. */
24807 var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
24809 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
24812 * @param {*} value The value to query.
24813 * @returns {string} Returns the raw `toStringTag`.
24816 function getRawTag(value) {
24817 var isOwn = hasOwnProperty$2.call(value, symToStringTag),
24818 tag = value[symToStringTag];
24821 value[symToStringTag] = undefined;
24822 var unmasked = true;
24825 var result = nativeObjectToString.call(value);
24829 value[symToStringTag] = tag;
24831 delete value[symToStringTag];
24838 var _getRawTag = getRawTag;
24840 /** Used for built-in method references. */
24841 var objectProto$1 = Object.prototype;
24843 * Used to resolve the
24844 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
24848 var nativeObjectToString$1 = objectProto$1.toString;
24850 * Converts `value` to a string using `Object.prototype.toString`.
24853 * @param {*} value The value to convert.
24854 * @returns {string} Returns the converted string.
24857 function objectToString(value) {
24858 return nativeObjectToString$1.call(value);
24861 var _objectToString = objectToString;
24863 /** `Object#toString` result references. */
24865 var nullTag = '[object Null]',
24866 undefinedTag = '[object Undefined]';
24867 /** Built-in value references. */
24869 var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
24871 * The base implementation of `getTag` without fallbacks for buggy environments.
24874 * @param {*} value The value to query.
24875 * @returns {string} Returns the `toStringTag`.
24878 function baseGetTag(value) {
24879 if (value == null) {
24880 return value === undefined ? undefinedTag : nullTag;
24883 return symToStringTag$1 && symToStringTag$1 in Object(value) ? _getRawTag(value) : _objectToString(value);
24886 var _baseGetTag = baseGetTag;
24889 * Checks if `value` is the
24890 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
24891 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
24897 * @param {*} value The value to check.
24898 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
24904 * _.isObject([1, 2, 3]);
24907 * _.isObject(_.noop);
24910 * _.isObject(null);
24913 function isObject(value) {
24914 var type = typeof value;
24915 return value != null && (type == 'object' || type == 'function');
24918 var isObject_1 = isObject;
24920 /** `Object#toString` result references. */
24922 var asyncTag = '[object AsyncFunction]',
24923 funcTag = '[object Function]',
24924 genTag = '[object GeneratorFunction]',
24925 proxyTag = '[object Proxy]';
24927 * Checks if `value` is classified as a `Function` object.
24933 * @param {*} value The value to check.
24934 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
24940 * _.isFunction(/abc/);
24944 function isFunction(value) {
24945 if (!isObject_1(value)) {
24947 } // The use of `Object#toString` avoids issues with the `typeof` operator
24948 // in Safari 9 which returns 'object' for typed arrays and other constructors.
24951 var tag = _baseGetTag(value);
24952 return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
24955 var isFunction_1 = isFunction;
24957 /** Used to detect overreaching core-js shims. */
24959 var coreJsData = _root['__core-js_shared__'];
24960 var _coreJsData = coreJsData;
24962 /** Used to detect methods masquerading as native. */
24964 var maskSrcKey = function () {
24965 var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
24966 return uid ? 'Symbol(src)_1.' + uid : '';
24969 * Checks if `func` has its source masked.
24972 * @param {Function} func The function to check.
24973 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
24977 function isMasked(func) {
24978 return !!maskSrcKey && maskSrcKey in func;
24981 var _isMasked = isMasked;
24983 /** Used for built-in method references. */
24984 var funcProto = Function.prototype;
24985 /** Used to resolve the decompiled source of functions. */
24987 var funcToString = funcProto.toString;
24989 * Converts `func` to its source code.
24992 * @param {Function} func The function to convert.
24993 * @returns {string} Returns the source code.
24996 function toSource(func) {
24997 if (func != null) {
24999 return funcToString.call(func);
25010 var _toSource = toSource;
25013 * Used to match `RegExp`
25014 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
25017 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
25018 /** Used to detect host constructors (Safari). */
25020 var reIsHostCtor = /^\[object .+?Constructor\]$/;
25021 /** Used for built-in method references. */
25023 var funcProto$1 = Function.prototype,
25024 objectProto$2 = Object.prototype;
25025 /** Used to resolve the decompiled source of functions. */
25027 var funcToString$1 = funcProto$1.toString;
25028 /** Used to check objects for own properties. */
25030 var hasOwnProperty$3 = objectProto$2.hasOwnProperty;
25031 /** Used to detect if a method is native. */
25033 var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$3).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
25035 * The base implementation of `_.isNative` without bad shim checks.
25038 * @param {*} value The value to check.
25039 * @returns {boolean} Returns `true` if `value` is a native function,
25043 function baseIsNative(value) {
25044 if (!isObject_1(value) || _isMasked(value)) {
25048 var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
25049 return pattern.test(_toSource(value));
25052 var _baseIsNative = baseIsNative;
25055 * Gets the value at `key` of `object`.
25058 * @param {Object} [object] The object to query.
25059 * @param {string} key The key of the property to get.
25060 * @returns {*} Returns the property value.
25062 function getValue(object, key) {
25063 return object == null ? undefined : object[key];
25066 var _getValue = getValue;
25069 * Gets the native function at `key` of `object`.
25072 * @param {Object} object The object to query.
25073 * @param {string} key The key of the method to get.
25074 * @returns {*} Returns the function if it's native, else `undefined`.
25077 function getNative(object, key) {
25078 var value = _getValue(object, key);
25079 return _baseIsNative(value) ? value : undefined;
25082 var _getNative = getNative;
25084 /* Built-in method references that are verified to be native. */
25086 var Map$1 = _getNative(_root, 'Map');
25089 /* Built-in method references that are verified to be native. */
25091 var nativeCreate = _getNative(Object, 'create');
25092 var _nativeCreate = nativeCreate;
25095 * Removes all key-value entries from the hash.
25102 function hashClear() {
25103 this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
25107 var _hashClear = hashClear;
25110 * Removes `key` and its value from the hash.
25115 * @param {Object} hash The hash to modify.
25116 * @param {string} key The key of the value to remove.
25117 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
25119 function hashDelete(key) {
25120 var result = this.has(key) && delete this.__data__[key];
25121 this.size -= result ? 1 : 0;
25125 var _hashDelete = hashDelete;
25127 /** Used to stand-in for `undefined` hash values. */
25129 var HASH_UNDEFINED = '__lodash_hash_undefined__';
25130 /** Used for built-in method references. */
25132 var objectProto$3 = Object.prototype;
25133 /** Used to check objects for own properties. */
25135 var hasOwnProperty$4 = objectProto$3.hasOwnProperty;
25137 * Gets the hash value for `key`.
25142 * @param {string} key The key of the value to get.
25143 * @returns {*} Returns the entry value.
25146 function hashGet(key) {
25147 var data = this.__data__;
25149 if (_nativeCreate) {
25150 var result = data[key];
25151 return result === HASH_UNDEFINED ? undefined : result;
25154 return hasOwnProperty$4.call(data, key) ? data[key] : undefined;
25157 var _hashGet = hashGet;
25159 /** Used for built-in method references. */
25161 var objectProto$4 = Object.prototype;
25162 /** Used to check objects for own properties. */
25164 var hasOwnProperty$5 = objectProto$4.hasOwnProperty;
25166 * Checks if a hash value for `key` exists.
25171 * @param {string} key The key of the entry to check.
25172 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
25175 function hashHas(key) {
25176 var data = this.__data__;
25177 return _nativeCreate ? data[key] !== undefined : hasOwnProperty$5.call(data, key);
25180 var _hashHas = hashHas;
25182 /** Used to stand-in for `undefined` hash values. */
25184 var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
25186 * Sets the hash `key` to `value`.
25191 * @param {string} key The key of the value to set.
25192 * @param {*} value The value to set.
25193 * @returns {Object} Returns the hash instance.
25196 function hashSet(key, value) {
25197 var data = this.__data__;
25198 this.size += this.has(key) ? 0 : 1;
25199 data[key] = _nativeCreate && value === undefined ? HASH_UNDEFINED$1 : value;
25203 var _hashSet = hashSet;
25206 * Creates a hash object.
25210 * @param {Array} [entries] The key-value pairs to cache.
25213 function Hash(entries) {
25215 length = entries == null ? 0 : entries.length;
25218 while (++index < length) {
25219 var entry = entries[index];
25220 this.set(entry[0], entry[1]);
25222 } // Add methods to `Hash`.
25225 Hash.prototype.clear = _hashClear;
25226 Hash.prototype['delete'] = _hashDelete;
25227 Hash.prototype.get = _hashGet;
25228 Hash.prototype.has = _hashHas;
25229 Hash.prototype.set = _hashSet;
25233 * Removes all key-value entries from the map.
25237 * @memberOf MapCache
25240 function mapCacheClear() {
25243 'hash': new _Hash(),
25244 'map': new (_Map || _ListCache)(),
25245 'string': new _Hash()
25249 var _mapCacheClear = mapCacheClear;
25252 * Checks if `value` is suitable for use as unique object key.
25255 * @param {*} value The value to check.
25256 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
25258 function isKeyable(value) {
25259 var type = typeof value;
25260 return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
25263 var _isKeyable = isKeyable;
25266 * Gets the data for `map`.
25269 * @param {Object} map The map to query.
25270 * @param {string} key The reference key.
25271 * @returns {*} Returns the map data.
25274 function getMapData(map, key) {
25275 var data = map.__data__;
25276 return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
25279 var _getMapData = getMapData;
25282 * Removes `key` and its value from the map.
25286 * @memberOf MapCache
25287 * @param {string} key The key of the value to remove.
25288 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
25291 function mapCacheDelete(key) {
25292 var result = _getMapData(this, key)['delete'](key);
25293 this.size -= result ? 1 : 0;
25297 var _mapCacheDelete = mapCacheDelete;
25300 * Gets the map value for `key`.
25304 * @memberOf MapCache
25305 * @param {string} key The key of the value to get.
25306 * @returns {*} Returns the entry value.
25309 function mapCacheGet(key) {
25310 return _getMapData(this, key).get(key);
25313 var _mapCacheGet = mapCacheGet;
25316 * Checks if a map value for `key` exists.
25320 * @memberOf MapCache
25321 * @param {string} key The key of the entry to check.
25322 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
25325 function mapCacheHas(key) {
25326 return _getMapData(this, key).has(key);
25329 var _mapCacheHas = mapCacheHas;
25332 * Sets the map `key` to `value`.
25336 * @memberOf MapCache
25337 * @param {string} key The key of the value to set.
25338 * @param {*} value The value to set.
25339 * @returns {Object} Returns the map cache instance.
25342 function mapCacheSet(key, value) {
25343 var data = _getMapData(this, key),
25345 data.set(key, value);
25346 this.size += data.size == size ? 0 : 1;
25350 var _mapCacheSet = mapCacheSet;
25353 * Creates a map cache object to store key-value pairs.
25357 * @param {Array} [entries] The key-value pairs to cache.
25360 function MapCache(entries) {
25362 length = entries == null ? 0 : entries.length;
25365 while (++index < length) {
25366 var entry = entries[index];
25367 this.set(entry[0], entry[1]);
25369 } // Add methods to `MapCache`.
25372 MapCache.prototype.clear = _mapCacheClear;
25373 MapCache.prototype['delete'] = _mapCacheDelete;
25374 MapCache.prototype.get = _mapCacheGet;
25375 MapCache.prototype.has = _mapCacheHas;
25376 MapCache.prototype.set = _mapCacheSet;
25377 var _MapCache = MapCache;
25379 /** Used as the size to enable large array optimizations. */
25381 var LARGE_ARRAY_SIZE = 200;
25383 * Sets the stack `key` to `value`.
25388 * @param {string} key The key of the value to set.
25389 * @param {*} value The value to set.
25390 * @returns {Object} Returns the stack cache instance.
25393 function stackSet(key, value) {
25394 var data = this.__data__;
25396 if (data instanceof _ListCache) {
25397 var pairs = data.__data__;
25399 if (!_Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
25400 pairs.push([key, value]);
25401 this.size = ++data.size;
25405 data = this.__data__ = new _MapCache(pairs);
25408 data.set(key, value);
25409 this.size = data.size;
25413 var _stackSet = stackSet;
25416 * Creates a stack cache object to store key-value pairs.
25420 * @param {Array} [entries] The key-value pairs to cache.
25423 function Stack(entries) {
25424 var data = this.__data__ = new _ListCache(entries);
25425 this.size = data.size;
25426 } // Add methods to `Stack`.
25429 Stack.prototype.clear = _stackClear;
25430 Stack.prototype['delete'] = _stackDelete;
25431 Stack.prototype.get = _stackGet;
25432 Stack.prototype.has = _stackHas;
25433 Stack.prototype.set = _stackSet;
25434 var _Stack = Stack;
25436 /** Used to stand-in for `undefined` hash values. */
25437 var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
25439 * Adds `value` to the array cache.
25443 * @memberOf SetCache
25445 * @param {*} value The value to cache.
25446 * @returns {Object} Returns the cache instance.
25449 function setCacheAdd(value) {
25450 this.__data__.set(value, HASH_UNDEFINED$2);
25455 var _setCacheAdd = setCacheAdd;
25458 * Checks if `value` is in the array cache.
25462 * @memberOf SetCache
25463 * @param {*} value The value to search for.
25464 * @returns {number} Returns `true` if `value` is found, else `false`.
25466 function setCacheHas(value) {
25467 return this.__data__.has(value);
25470 var _setCacheHas = setCacheHas;
25474 * Creates an array cache object to store unique values.
25478 * @param {Array} [values] The values to cache.
25481 function SetCache(values) {
25483 length = values == null ? 0 : values.length;
25484 this.__data__ = new _MapCache();
25486 while (++index < length) {
25487 this.add(values[index]);
25489 } // Add methods to `SetCache`.
25492 SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
25493 SetCache.prototype.has = _setCacheHas;
25494 var _SetCache = SetCache;
25497 * A specialized version of `_.some` for arrays without support for iteratee
25501 * @param {Array} [array] The array to iterate over.
25502 * @param {Function} predicate The function invoked per iteration.
25503 * @returns {boolean} Returns `true` if any element passes the predicate check,
25506 function arraySome(array, predicate) {
25508 length = array == null ? 0 : array.length;
25510 while (++index < length) {
25511 if (predicate(array[index], index, array)) {
25519 var _arraySome = arraySome;
25522 * Checks if a `cache` value for `key` exists.
25525 * @param {Object} cache The cache to query.
25526 * @param {string} key The key of the entry to check.
25527 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
25529 function cacheHas(cache, key) {
25530 return cache.has(key);
25533 var _cacheHas = cacheHas;
25535 /** Used to compose bitmasks for value comparisons. */
25537 var COMPARE_PARTIAL_FLAG = 1,
25538 COMPARE_UNORDERED_FLAG = 2;
25540 * A specialized version of `baseIsEqualDeep` for arrays with support for
25541 * partial deep comparisons.
25544 * @param {Array} array The array to compare.
25545 * @param {Array} other The other array to compare.
25546 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
25547 * @param {Function} customizer The function to customize comparisons.
25548 * @param {Function} equalFunc The function to determine equivalents of values.
25549 * @param {Object} stack Tracks traversed `array` and `other` objects.
25550 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
25553 function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
25554 var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
25555 arrLength = array.length,
25556 othLength = other.length;
25558 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
25560 } // Assume cyclic values are equal.
25563 var stacked = stack.get(array);
25565 if (stacked && stack.get(other)) {
25566 return stacked == other;
25571 seen = bitmask & COMPARE_UNORDERED_FLAG ? new _SetCache() : undefined;
25572 stack.set(array, other);
25573 stack.set(other, array); // Ignore non-index properties.
25575 while (++index < arrLength) {
25576 var arrValue = array[index],
25577 othValue = other[index];
25580 var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
25583 if (compared !== undefined) {
25590 } // Recursively compare arrays (susceptible to call stack limits).
25594 if (!_arraySome(other, function (othValue, othIndex) {
25595 if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
25596 return seen.push(othIndex);
25602 } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
25608 stack['delete'](array);
25609 stack['delete'](other);
25613 var _equalArrays = equalArrays;
25615 /** Built-in value references. */
25617 var Uint8Array = _root.Uint8Array;
25618 var _Uint8Array = Uint8Array;
25621 * Converts `map` to its key-value pairs.
25624 * @param {Object} map The map to convert.
25625 * @returns {Array} Returns the key-value pairs.
25627 function mapToArray(map) {
25629 result = Array(map.size);
25630 map.forEach(function (value, key) {
25631 result[++index] = [key, value];
25636 var _mapToArray = mapToArray;
25639 * Converts `set` to an array of its values.
25642 * @param {Object} set The set to convert.
25643 * @returns {Array} Returns the values.
25645 function setToArray(set) {
25647 result = Array(set.size);
25648 set.forEach(function (value) {
25649 result[++index] = value;
25654 var _setToArray = setToArray;
25656 /** Used to compose bitmasks for value comparisons. */
25658 var COMPARE_PARTIAL_FLAG$1 = 1,
25659 COMPARE_UNORDERED_FLAG$1 = 2;
25660 /** `Object#toString` result references. */
25662 var boolTag = '[object Boolean]',
25663 dateTag = '[object Date]',
25664 errorTag = '[object Error]',
25665 mapTag = '[object Map]',
25666 numberTag = '[object Number]',
25667 regexpTag = '[object RegExp]',
25668 setTag = '[object Set]',
25669 stringTag = '[object String]',
25670 symbolTag = '[object Symbol]';
25671 var arrayBufferTag = '[object ArrayBuffer]',
25672 dataViewTag = '[object DataView]';
25673 /** Used to convert symbols to primitives and strings. */
25675 var symbolProto = _Symbol ? _Symbol.prototype : undefined,
25676 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
25678 * A specialized version of `baseIsEqualDeep` for comparing objects of
25679 * the same `toStringTag`.
25681 * **Note:** This function only supports comparing values with tags of
25682 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
25685 * @param {Object} object The object to compare.
25686 * @param {Object} other The other object to compare.
25687 * @param {string} tag The `toStringTag` of the objects to compare.
25688 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
25689 * @param {Function} customizer The function to customize comparisons.
25690 * @param {Function} equalFunc The function to determine equivalents of values.
25691 * @param {Object} stack Tracks traversed `object` and `other` objects.
25692 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
25695 function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
25698 if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
25702 object = object.buffer;
25703 other = other.buffer;
25705 case arrayBufferTag:
25706 if (object.byteLength != other.byteLength || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
25715 // Coerce booleans to `1` or `0` and dates to milliseconds.
25716 // Invalid dates are coerced to `NaN`.
25717 return eq_1(+object, +other);
25720 return object.name == other.name && object.message == other.message;
25724 // Coerce regexes to strings and treat strings, primitives and objects,
25725 // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
25726 // for more details.
25727 return object == other + '';
25730 var convert = _mapToArray;
25733 var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;
25734 convert || (convert = _setToArray);
25736 if (object.size != other.size && !isPartial) {
25738 } // Assume cyclic values are equal.
25741 var stacked = stack.get(object);
25744 return stacked == other;
25747 bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits).
25749 stack.set(object, other);
25750 var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
25751 stack['delete'](object);
25755 if (symbolValueOf) {
25756 return symbolValueOf.call(object) == symbolValueOf.call(other);
25764 var _equalByTag = equalByTag;
25767 * Appends the elements of `values` to `array`.
25770 * @param {Array} array The array to modify.
25771 * @param {Array} values The values to append.
25772 * @returns {Array} Returns `array`.
25774 function arrayPush(array, values) {
25776 length = values.length,
25777 offset = array.length;
25779 while (++index < length) {
25780 array[offset + index] = values[index];
25786 var _arrayPush = arrayPush;
25789 * Checks if `value` is classified as an `Array` object.
25795 * @param {*} value The value to check.
25796 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
25799 * _.isArray([1, 2, 3]);
25802 * _.isArray(document.body.children);
25805 * _.isArray('abc');
25808 * _.isArray(_.noop);
25811 var isArray$1 = Array.isArray;
25812 var isArray_1 = isArray$1;
25815 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
25816 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
25817 * symbols of `object`.
25820 * @param {Object} object The object to query.
25821 * @param {Function} keysFunc The function to get the keys of `object`.
25822 * @param {Function} symbolsFunc The function to get the symbols of `object`.
25823 * @returns {Array} Returns the array of property names and symbols.
25826 function baseGetAllKeys(object, keysFunc, symbolsFunc) {
25827 var result = keysFunc(object);
25828 return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
25831 var _baseGetAllKeys = baseGetAllKeys;
25834 * A specialized version of `_.filter` for arrays without support for
25835 * iteratee shorthands.
25838 * @param {Array} [array] The array to iterate over.
25839 * @param {Function} predicate The function invoked per iteration.
25840 * @returns {Array} Returns the new filtered array.
25842 function arrayFilter(array, predicate) {
25844 length = array == null ? 0 : array.length,
25848 while (++index < length) {
25849 var value = array[index];
25851 if (predicate(value, index, array)) {
25852 result[resIndex++] = value;
25859 var _arrayFilter = arrayFilter;
25862 * This method returns a new empty array.
25868 * @returns {Array} Returns the new empty array.
25871 * var arrays = _.times(2, _.stubArray);
25873 * console.log(arrays);
25876 * console.log(arrays[0] === arrays[1]);
25879 function stubArray() {
25883 var stubArray_1 = stubArray;
25885 /** Used for built-in method references. */
25887 var objectProto$5 = Object.prototype;
25888 /** Built-in value references. */
25890 var propertyIsEnumerable = objectProto$5.propertyIsEnumerable;
25891 /* Built-in method references for those with the same name as other `lodash` methods. */
25893 var nativeGetSymbols = Object.getOwnPropertySymbols;
25895 * Creates an array of the own enumerable symbols of `object`.
25898 * @param {Object} object The object to query.
25899 * @returns {Array} Returns the array of symbols.
25902 var getSymbols = !nativeGetSymbols ? stubArray_1 : function (object) {
25903 if (object == null) {
25907 object = Object(object);
25908 return _arrayFilter(nativeGetSymbols(object), function (symbol) {
25909 return propertyIsEnumerable.call(object, symbol);
25912 var _getSymbols = getSymbols;
25915 * The base implementation of `_.times` without support for iteratee shorthands
25916 * or max array length checks.
25919 * @param {number} n The number of times to invoke `iteratee`.
25920 * @param {Function} iteratee The function invoked per iteration.
25921 * @returns {Array} Returns the array of results.
25923 function baseTimes(n, iteratee) {
25927 while (++index < n) {
25928 result[index] = iteratee(index);
25934 var _baseTimes = baseTimes;
25937 * Checks if `value` is object-like. A value is object-like if it's not `null`
25938 * and has a `typeof` result of "object".
25944 * @param {*} value The value to check.
25945 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
25948 * _.isObjectLike({});
25951 * _.isObjectLike([1, 2, 3]);
25954 * _.isObjectLike(_.noop);
25957 * _.isObjectLike(null);
25960 function isObjectLike(value) {
25961 return value != null && typeof value == 'object';
25964 var isObjectLike_1 = isObjectLike;
25966 /** `Object#toString` result references. */
25968 var argsTag = '[object Arguments]';
25970 * The base implementation of `_.isArguments`.
25973 * @param {*} value The value to check.
25974 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
25977 function baseIsArguments(value) {
25978 return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
25981 var _baseIsArguments = baseIsArguments;
25983 /** Used for built-in method references. */
25985 var objectProto$6 = Object.prototype;
25986 /** Used to check objects for own properties. */
25988 var hasOwnProperty$6 = objectProto$6.hasOwnProperty;
25989 /** Built-in value references. */
25991 var propertyIsEnumerable$1 = objectProto$6.propertyIsEnumerable;
25993 * Checks if `value` is likely an `arguments` object.
25999 * @param {*} value The value to check.
26000 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
26004 * _.isArguments(function() { return arguments; }());
26007 * _.isArguments([1, 2, 3]);
26011 var isArguments = _baseIsArguments(function () {
26013 }()) ? _baseIsArguments : function (value) {
26014 return isObjectLike_1(value) && hasOwnProperty$6.call(value, 'callee') && !propertyIsEnumerable$1.call(value, 'callee');
26016 var isArguments_1 = isArguments;
26019 * This method returns `false`.
26025 * @returns {boolean} Returns `false`.
26028 * _.times(2, _.stubFalse);
26029 * // => [false, false]
26031 function stubFalse() {
26035 var stubFalse_1 = stubFalse;
26037 var isBuffer_1 = createCommonjsModule(function (module, exports) {
26038 /** Detect free variable `exports`. */
26039 var freeExports = exports && !exports.nodeType && exports;
26040 /** Detect free variable `module`. */
26042 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
26043 /** Detect the popular CommonJS extension `module.exports`. */
26045 var moduleExports = freeModule && freeModule.exports === freeExports;
26046 /** Built-in value references. */
26048 var Buffer = moduleExports ? _root.Buffer : undefined;
26049 /* Built-in method references for those with the same name as other `lodash` methods. */
26051 var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
26053 * Checks if `value` is a buffer.
26059 * @param {*} value The value to check.
26060 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
26063 * _.isBuffer(new Buffer(2));
26066 * _.isBuffer(new Uint8Array(2));
26070 var isBuffer = nativeIsBuffer || stubFalse_1;
26071 module.exports = isBuffer;
26074 /** Used as references for various `Number` constants. */
26075 var MAX_SAFE_INTEGER$2 = 9007199254740991;
26076 /** Used to detect unsigned integer values. */
26078 var reIsUint = /^(?:0|[1-9]\d*)$/;
26080 * Checks if `value` is a valid array-like index.
26083 * @param {*} value The value to check.
26084 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
26085 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
26088 function isIndex(value, length) {
26089 var type = typeof value;
26090 length = length == null ? MAX_SAFE_INTEGER$2 : length;
26091 return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
26094 var _isIndex = isIndex;
26096 /** Used as references for various `Number` constants. */
26097 var MAX_SAFE_INTEGER$3 = 9007199254740991;
26099 * Checks if `value` is a valid array-like length.
26101 * **Note:** This method is loosely based on
26102 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
26108 * @param {*} value The value to check.
26109 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
26115 * _.isLength(Number.MIN_VALUE);
26118 * _.isLength(Infinity);
26125 function isLength(value) {
26126 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$3;
26129 var isLength_1 = isLength;
26131 /** `Object#toString` result references. */
26133 var argsTag$1 = '[object Arguments]',
26134 arrayTag = '[object Array]',
26135 boolTag$1 = '[object Boolean]',
26136 dateTag$1 = '[object Date]',
26137 errorTag$1 = '[object Error]',
26138 funcTag$1 = '[object Function]',
26139 mapTag$1 = '[object Map]',
26140 numberTag$1 = '[object Number]',
26141 objectTag = '[object Object]',
26142 regexpTag$1 = '[object RegExp]',
26143 setTag$1 = '[object Set]',
26144 stringTag$1 = '[object String]',
26145 weakMapTag = '[object WeakMap]';
26146 var arrayBufferTag$1 = '[object ArrayBuffer]',
26147 dataViewTag$1 = '[object DataView]',
26148 float32Tag = '[object Float32Array]',
26149 float64Tag = '[object Float64Array]',
26150 int8Tag = '[object Int8Array]',
26151 int16Tag = '[object Int16Array]',
26152 int32Tag = '[object Int32Array]',
26153 uint8Tag = '[object Uint8Array]',
26154 uint8ClampedTag = '[object Uint8ClampedArray]',
26155 uint16Tag = '[object Uint16Array]',
26156 uint32Tag = '[object Uint32Array]';
26157 /** Used to identify `toStringTag` values of typed arrays. */
26159 var typedArrayTags = {};
26160 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
26161 typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag$1] = typedArrayTags[boolTag$1] = typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag$1] = typedArrayTags[errorTag$1] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag$1] = typedArrayTags[numberTag$1] = typedArrayTags[objectTag] = typedArrayTags[regexpTag$1] = typedArrayTags[setTag$1] = typedArrayTags[stringTag$1] = typedArrayTags[weakMapTag] = false;
26163 * The base implementation of `_.isTypedArray` without Node.js optimizations.
26166 * @param {*} value The value to check.
26167 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
26170 function baseIsTypedArray(value) {
26171 return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
26174 var _baseIsTypedArray = baseIsTypedArray;
26177 * The base implementation of `_.unary` without support for storing metadata.
26180 * @param {Function} func The function to cap arguments for.
26181 * @returns {Function} Returns the new capped function.
26183 function baseUnary(func) {
26184 return function (value) {
26185 return func(value);
26189 var _baseUnary = baseUnary;
26191 var _nodeUtil = createCommonjsModule(function (module, exports) {
26192 /** Detect free variable `exports`. */
26193 var freeExports = exports && !exports.nodeType && exports;
26194 /** Detect free variable `module`. */
26196 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
26197 /** Detect the popular CommonJS extension `module.exports`. */
26199 var moduleExports = freeModule && freeModule.exports === freeExports;
26200 /** Detect free variable `process` from Node.js. */
26202 var freeProcess = moduleExports && _freeGlobal.process;
26203 /** Used to access faster Node.js helpers. */
26205 var nodeUtil = function () {
26207 // Use `util.types` for Node.js 10+.
26208 var types = freeModule && freeModule.require && freeModule.require('util').types;
26212 } // Legacy `process.binding('util')` for Node.js < 10.
26215 return freeProcess && freeProcess.binding && freeProcess.binding('util');
26219 module.exports = nodeUtil;
26222 /* Node.js helper references. */
26224 var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
26226 * Checks if `value` is classified as a typed array.
26232 * @param {*} value The value to check.
26233 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
26236 * _.isTypedArray(new Uint8Array);
26239 * _.isTypedArray([]);
26243 var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
26244 var isTypedArray_1 = isTypedArray;
26246 /** Used for built-in method references. */
26248 var objectProto$7 = Object.prototype;
26249 /** Used to check objects for own properties. */
26251 var hasOwnProperty$7 = objectProto$7.hasOwnProperty;
26253 * Creates an array of the enumerable property names of the array-like `value`.
26256 * @param {*} value The value to query.
26257 * @param {boolean} inherited Specify returning inherited property names.
26258 * @returns {Array} Returns the array of property names.
26261 function arrayLikeKeys(value, inherited) {
26262 var isArr = isArray_1(value),
26263 isArg = !isArr && isArguments_1(value),
26264 isBuff = !isArr && !isArg && isBuffer_1(value),
26265 isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
26266 skipIndexes = isArr || isArg || isBuff || isType,
26267 result = skipIndexes ? _baseTimes(value.length, String) : [],
26268 length = result.length;
26270 for (var key in value) {
26271 if ((inherited || hasOwnProperty$7.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode.
26272 key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers.
26273 isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays.
26274 isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties.
26275 _isIndex(key, length)))) {
26283 var _arrayLikeKeys = arrayLikeKeys;
26285 /** Used for built-in method references. */
26286 var objectProto$8 = Object.prototype;
26288 * Checks if `value` is likely a prototype object.
26291 * @param {*} value The value to check.
26292 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
26295 function isPrototype(value) {
26296 var Ctor = value && value.constructor,
26297 proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$8;
26298 return value === proto;
26301 var _isPrototype = isPrototype;
26304 * Creates a unary function that invokes `func` with its argument transformed.
26307 * @param {Function} func The function to wrap.
26308 * @param {Function} transform The argument transform.
26309 * @returns {Function} Returns the new function.
26311 function overArg(func, transform) {
26312 return function (arg) {
26313 return func(transform(arg));
26317 var _overArg = overArg;
26319 /* Built-in method references for those with the same name as other `lodash` methods. */
26321 var nativeKeys = _overArg(Object.keys, Object);
26322 var _nativeKeys = nativeKeys;
26324 /** Used for built-in method references. */
26326 var objectProto$9 = Object.prototype;
26327 /** Used to check objects for own properties. */
26329 var hasOwnProperty$8 = objectProto$9.hasOwnProperty;
26331 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
26334 * @param {Object} object The object to query.
26335 * @returns {Array} Returns the array of property names.
26338 function baseKeys(object) {
26339 if (!_isPrototype(object)) {
26340 return _nativeKeys(object);
26345 for (var key in Object(object)) {
26346 if (hasOwnProperty$8.call(object, key) && key != 'constructor') {
26354 var _baseKeys = baseKeys;
26357 * Checks if `value` is array-like. A value is considered array-like if it's
26358 * not a function and has a `value.length` that's an integer greater than or
26359 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
26365 * @param {*} value The value to check.
26366 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
26369 * _.isArrayLike([1, 2, 3]);
26372 * _.isArrayLike(document.body.children);
26375 * _.isArrayLike('abc');
26378 * _.isArrayLike(_.noop);
26382 function isArrayLike(value) {
26383 return value != null && isLength_1(value.length) && !isFunction_1(value);
26386 var isArrayLike_1 = isArrayLike;
26389 * Creates an array of the own enumerable property names of `object`.
26391 * **Note:** Non-object values are coerced to objects. See the
26392 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
26393 * for more details.
26399 * @param {Object} object The object to query.
26400 * @returns {Array} Returns the array of property names.
26408 * Foo.prototype.c = 3;
26411 * // => ['a', 'b'] (iteration order is not guaranteed)
26417 function keys(object) {
26418 return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
26424 * Creates an array of own enumerable property names and symbols of `object`.
26427 * @param {Object} object The object to query.
26428 * @returns {Array} Returns the array of property names and symbols.
26431 function getAllKeys(object) {
26432 return _baseGetAllKeys(object, keys_1, _getSymbols);
26435 var _getAllKeys = getAllKeys;
26437 /** Used to compose bitmasks for value comparisons. */
26439 var COMPARE_PARTIAL_FLAG$2 = 1;
26440 /** Used for built-in method references. */
26442 var objectProto$a = Object.prototype;
26443 /** Used to check objects for own properties. */
26445 var hasOwnProperty$9 = objectProto$a.hasOwnProperty;
26447 * A specialized version of `baseIsEqualDeep` for objects with support for
26448 * partial deep comparisons.
26451 * @param {Object} object The object to compare.
26452 * @param {Object} other The other object to compare.
26453 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
26454 * @param {Function} customizer The function to customize comparisons.
26455 * @param {Function} equalFunc The function to determine equivalents of values.
26456 * @param {Object} stack Tracks traversed `object` and `other` objects.
26457 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
26460 function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
26461 var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,
26462 objProps = _getAllKeys(object),
26463 objLength = objProps.length,
26464 othProps = _getAllKeys(other),
26465 othLength = othProps.length;
26467 if (objLength != othLength && !isPartial) {
26471 var index = objLength;
26474 var key = objProps[index];
26476 if (!(isPartial ? key in other : hasOwnProperty$9.call(other, key))) {
26479 } // Assume cyclic values are equal.
26482 var stacked = stack.get(object);
26484 if (stacked && stack.get(other)) {
26485 return stacked == other;
26489 stack.set(object, other);
26490 stack.set(other, object);
26491 var skipCtor = isPartial;
26493 while (++index < objLength) {
26494 key = objProps[index];
26495 var objValue = object[key],
26496 othValue = other[key];
26499 var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
26500 } // Recursively compare objects (susceptible to call stack limits).
26503 if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
26508 skipCtor || (skipCtor = key == 'constructor');
26511 if (result && !skipCtor) {
26512 var objCtor = object.constructor,
26513 othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal.
26515 if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
26520 stack['delete'](object);
26521 stack['delete'](other);
26525 var _equalObjects = equalObjects;
26527 /* Built-in method references that are verified to be native. */
26529 var DataView = _getNative(_root, 'DataView');
26530 var _DataView = DataView;
26532 /* Built-in method references that are verified to be native. */
26534 var Promise$1 = _getNative(_root, 'Promise');
26535 var _Promise = Promise$1;
26537 /* Built-in method references that are verified to be native. */
26539 var Set$1 = _getNative(_root, 'Set');
26542 /* Built-in method references that are verified to be native. */
26544 var WeakMap$1 = _getNative(_root, 'WeakMap');
26545 var _WeakMap = WeakMap$1;
26547 /** `Object#toString` result references. */
26549 var mapTag$2 = '[object Map]',
26550 objectTag$1 = '[object Object]',
26551 promiseTag = '[object Promise]',
26552 setTag$2 = '[object Set]',
26553 weakMapTag$1 = '[object WeakMap]';
26554 var dataViewTag$2 = '[object DataView]';
26555 /** Used to detect maps, sets, and weakmaps. */
26557 var dataViewCtorString = _toSource(_DataView),
26558 mapCtorString = _toSource(_Map),
26559 promiseCtorString = _toSource(_Promise),
26560 setCtorString = _toSource(_Set),
26561 weakMapCtorString = _toSource(_WeakMap);
26563 * Gets the `toStringTag` of `value`.
26566 * @param {*} value The value to query.
26567 * @returns {string} Returns the `toStringTag`.
26570 var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
26572 if (_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2 || _Map && getTag(new _Map()) != mapTag$2 || _Promise && getTag(_Promise.resolve()) != promiseTag || _Set && getTag(new _Set()) != setTag$2 || _WeakMap && getTag(new _WeakMap()) != weakMapTag$1) {
26573 getTag = function (value) {
26574 var result = _baseGetTag(value),
26575 Ctor = result == objectTag$1 ? value.constructor : undefined,
26576 ctorString = Ctor ? _toSource(Ctor) : '';
26579 switch (ctorString) {
26580 case dataViewCtorString:
26581 return dataViewTag$2;
26583 case mapCtorString:
26586 case promiseCtorString:
26589 case setCtorString:
26592 case weakMapCtorString:
26593 return weakMapTag$1;
26601 var _getTag = getTag;
26603 /** Used to compose bitmasks for value comparisons. */
26605 var COMPARE_PARTIAL_FLAG$3 = 1;
26606 /** `Object#toString` result references. */
26608 var argsTag$2 = '[object Arguments]',
26609 arrayTag$1 = '[object Array]',
26610 objectTag$2 = '[object Object]';
26611 /** Used for built-in method references. */
26613 var objectProto$b = Object.prototype;
26614 /** Used to check objects for own properties. */
26616 var hasOwnProperty$a = objectProto$b.hasOwnProperty;
26618 * A specialized version of `baseIsEqual` for arrays and objects which performs
26619 * deep comparisons and tracks traversed objects enabling objects with circular
26620 * references to be compared.
26623 * @param {Object} object The object to compare.
26624 * @param {Object} other The other object to compare.
26625 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
26626 * @param {Function} customizer The function to customize comparisons.
26627 * @param {Function} equalFunc The function to determine equivalents of values.
26628 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
26629 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
26632 function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
26633 var objIsArr = isArray_1(object),
26634 othIsArr = isArray_1(other),
26635 objTag = objIsArr ? arrayTag$1 : _getTag(object),
26636 othTag = othIsArr ? arrayTag$1 : _getTag(other);
26637 objTag = objTag == argsTag$2 ? objectTag$2 : objTag;
26638 othTag = othTag == argsTag$2 ? objectTag$2 : othTag;
26639 var objIsObj = objTag == objectTag$2,
26640 othIsObj = othTag == objectTag$2,
26641 isSameTag = objTag == othTag;
26643 if (isSameTag && isBuffer_1(object)) {
26644 if (!isBuffer_1(other)) {
26652 if (isSameTag && !objIsObj) {
26653 stack || (stack = new _Stack());
26654 return objIsArr || isTypedArray_1(object) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
26657 if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {
26658 var objIsWrapped = objIsObj && hasOwnProperty$a.call(object, '__wrapped__'),
26659 othIsWrapped = othIsObj && hasOwnProperty$a.call(other, '__wrapped__');
26661 if (objIsWrapped || othIsWrapped) {
26662 var objUnwrapped = objIsWrapped ? object.value() : object,
26663 othUnwrapped = othIsWrapped ? other.value() : other;
26664 stack || (stack = new _Stack());
26665 return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
26673 stack || (stack = new _Stack());
26674 return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
26677 var _baseIsEqualDeep = baseIsEqualDeep;
26680 * The base implementation of `_.isEqual` which supports partial comparisons
26681 * and tracks traversed objects.
26684 * @param {*} value The value to compare.
26685 * @param {*} other The other value to compare.
26686 * @param {boolean} bitmask The bitmask flags.
26687 * 1 - Unordered comparison
26688 * 2 - Partial comparison
26689 * @param {Function} [customizer] The function to customize comparisons.
26690 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
26691 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
26694 function baseIsEqual(value, other, bitmask, customizer, stack) {
26695 if (value === other) {
26699 if (value == null || other == null || !isObjectLike_1(value) && !isObjectLike_1(other)) {
26700 return value !== value && other !== other;
26703 return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
26706 var _baseIsEqual = baseIsEqual;
26708 /** Used to compose bitmasks for value comparisons. */
26710 var COMPARE_PARTIAL_FLAG$4 = 1,
26711 COMPARE_UNORDERED_FLAG$2 = 2;
26713 * The base implementation of `_.isMatch` without support for iteratee shorthands.
26716 * @param {Object} object The object to inspect.
26717 * @param {Object} source The object of property values to match.
26718 * @param {Array} matchData The property names, values, and compare flags to match.
26719 * @param {Function} [customizer] The function to customize comparisons.
26720 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
26723 function baseIsMatch(object, source, matchData, customizer) {
26724 var index = matchData.length,
26726 noCustomizer = !customizer;
26728 if (object == null) {
26732 object = Object(object);
26735 var data = matchData[index];
26737 if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
26742 while (++index < length) {
26743 data = matchData[index];
26745 objValue = object[key],
26746 srcValue = data[1];
26748 if (noCustomizer && data[2]) {
26749 if (objValue === undefined && !(key in object)) {
26753 var stack = new _Stack();
26756 var result = customizer(objValue, srcValue, key, object, source, stack);
26759 if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result)) {
26768 var _baseIsMatch = baseIsMatch;
26771 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
26774 * @param {*} value The value to check.
26775 * @returns {boolean} Returns `true` if `value` if suitable for strict
26776 * equality comparisons, else `false`.
26779 function isStrictComparable(value) {
26780 return value === value && !isObject_1(value);
26783 var _isStrictComparable = isStrictComparable;
26786 * Gets the property names, values, and compare flags of `object`.
26789 * @param {Object} object The object to query.
26790 * @returns {Array} Returns the match data of `object`.
26793 function getMatchData(object) {
26794 var result = keys_1(object),
26795 length = result.length;
26798 var key = result[length],
26799 value = object[key];
26800 result[length] = [key, value, _isStrictComparable(value)];
26806 var _getMatchData = getMatchData;
26809 * A specialized version of `matchesProperty` for source values suitable
26810 * for strict equality comparisons, i.e. `===`.
26813 * @param {string} key The key of the property to get.
26814 * @param {*} srcValue The value to match.
26815 * @returns {Function} Returns the new spec function.
26817 function matchesStrictComparable(key, srcValue) {
26818 return function (object) {
26819 if (object == null) {
26823 return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
26827 var _matchesStrictComparable = matchesStrictComparable;
26830 * The base implementation of `_.matches` which doesn't clone `source`.
26833 * @param {Object} source The object of property values to match.
26834 * @returns {Function} Returns the new spec function.
26837 function baseMatches(source) {
26838 var matchData = _getMatchData(source);
26840 if (matchData.length == 1 && matchData[0][2]) {
26841 return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
26844 return function (object) {
26845 return object === source || _baseIsMatch(object, source, matchData);
26849 var _baseMatches = baseMatches;
26851 /** `Object#toString` result references. */
26853 var symbolTag$1 = '[object Symbol]';
26855 * Checks if `value` is classified as a `Symbol` primitive or object.
26861 * @param {*} value The value to check.
26862 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
26865 * _.isSymbol(Symbol.iterator);
26868 * _.isSymbol('abc');
26872 function isSymbol(value) {
26873 return typeof value == 'symbol' || isObjectLike_1(value) && _baseGetTag(value) == symbolTag$1;
26876 var isSymbol_1 = isSymbol;
26878 /** Used to match property names within property paths. */
26880 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
26881 reIsPlainProp = /^\w*$/;
26883 * Checks if `value` is a property name and not a property path.
26886 * @param {*} value The value to check.
26887 * @param {Object} [object] The object to query keys on.
26888 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
26891 function isKey(value, object) {
26892 if (isArray_1(value)) {
26896 var type = typeof value;
26898 if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) {
26902 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
26905 var _isKey = isKey;
26907 /** Error message constants. */
26909 var FUNC_ERROR_TEXT = 'Expected a function';
26911 * Creates a function that memoizes the result of `func`. If `resolver` is
26912 * provided, it determines the cache key for storing the result based on the
26913 * arguments provided to the memoized function. By default, the first argument
26914 * provided to the memoized function is used as the map cache key. The `func`
26915 * is invoked with the `this` binding of the memoized function.
26917 * **Note:** The cache is exposed as the `cache` property on the memoized
26918 * function. Its creation may be customized by replacing the `_.memoize.Cache`
26919 * constructor with one whose instances implement the
26920 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
26921 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
26926 * @category Function
26927 * @param {Function} func The function to have its output memoized.
26928 * @param {Function} [resolver] The function to resolve the cache key.
26929 * @returns {Function} Returns the new memoized function.
26932 * var object = { 'a': 1, 'b': 2 };
26933 * var other = { 'c': 3, 'd': 4 };
26935 * var values = _.memoize(_.values);
26946 * // Modify the result cache.
26947 * values.cache.set(object, ['a', 'b']);
26951 * // Replace `_.memoize.Cache`.
26952 * _.memoize.Cache = WeakMap;
26955 function memoize(func, resolver) {
26956 if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
26957 throw new TypeError(FUNC_ERROR_TEXT);
26960 var memoized = function () {
26961 var args = arguments,
26962 key = resolver ? resolver.apply(this, args) : args[0],
26963 cache = memoized.cache;
26965 if (cache.has(key)) {
26966 return cache.get(key);
26969 var result = func.apply(this, args);
26970 memoized.cache = cache.set(key, result) || cache;
26974 memoized.cache = new (memoize.Cache || _MapCache)();
26976 } // Expose `MapCache`.
26979 memoize.Cache = _MapCache;
26980 var memoize_1 = memoize;
26982 /** Used as the maximum memoize cache size. */
26984 var MAX_MEMOIZE_SIZE = 500;
26986 * A specialized version of `_.memoize` which clears the memoized function's
26987 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
26990 * @param {Function} func The function to have its output memoized.
26991 * @returns {Function} Returns the new memoized function.
26994 function memoizeCapped(func) {
26995 var result = memoize_1(func, function (key) {
26996 if (cache.size === MAX_MEMOIZE_SIZE) {
27002 var cache = result.cache;
27006 var _memoizeCapped = memoizeCapped;
27008 /** Used to match property names within property paths. */
27010 var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
27011 /** Used to match backslashes in property paths. */
27013 var reEscapeChar = /\\(\\)?/g;
27015 * Converts `string` to a property path array.
27018 * @param {string} string The string to convert.
27019 * @returns {Array} Returns the property path array.
27022 var stringToPath = _memoizeCapped(function (string) {
27025 if (string.charCodeAt(0) === 46
27031 string.replace(rePropName, function (match, number, quote, subString) {
27032 result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
27036 var _stringToPath = stringToPath;
27039 * A specialized version of `_.map` for arrays without support for iteratee
27043 * @param {Array} [array] The array to iterate over.
27044 * @param {Function} iteratee The function invoked per iteration.
27045 * @returns {Array} Returns the new mapped array.
27047 function arrayMap(array, iteratee) {
27049 length = array == null ? 0 : array.length,
27050 result = Array(length);
27052 while (++index < length) {
27053 result[index] = iteratee(array[index], index, array);
27059 var _arrayMap = arrayMap;
27061 /** Used as references for various `Number` constants. */
27063 var INFINITY = 1 / 0;
27064 /** Used to convert symbols to primitives and strings. */
27066 var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
27067 symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined;
27069 * The base implementation of `_.toString` which doesn't convert nullish
27070 * values to empty strings.
27073 * @param {*} value The value to process.
27074 * @returns {string} Returns the string.
27077 function baseToString(value) {
27078 // Exit early for strings to avoid a performance hit in some environments.
27079 if (typeof value == 'string') {
27083 if (isArray_1(value)) {
27084 // Recursively convert values (susceptible to call stack limits).
27085 return _arrayMap(value, baseToString) + '';
27088 if (isSymbol_1(value)) {
27089 return symbolToString ? symbolToString.call(value) : '';
27092 var result = value + '';
27093 return result == '0' && 1 / value == -INFINITY ? '-0' : result;
27096 var _baseToString = baseToString;
27099 * Converts `value` to a string. An empty string is returned for `null`
27100 * and `undefined` values. The sign of `-0` is preserved.
27106 * @param {*} value The value to convert.
27107 * @returns {string} Returns the converted string.
27110 * _.toString(null);
27116 * _.toString([1, 2, 3]);
27120 function toString(value) {
27121 return value == null ? '' : _baseToString(value);
27124 var toString_1 = toString;
27127 * Casts `value` to a path array if it's not one.
27130 * @param {*} value The value to inspect.
27131 * @param {Object} [object] The object to query keys on.
27132 * @returns {Array} Returns the cast property path array.
27135 function castPath(value, object) {
27136 if (isArray_1(value)) {
27140 return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
27143 var _castPath = castPath;
27145 /** Used as references for various `Number` constants. */
27147 var INFINITY$1 = 1 / 0;
27149 * Converts `value` to a string key if it's not a string or symbol.
27152 * @param {*} value The value to inspect.
27153 * @returns {string|symbol} Returns the key.
27156 function toKey(value) {
27157 if (typeof value == 'string' || isSymbol_1(value)) {
27161 var result = value + '';
27162 return result == '0' && 1 / value == -INFINITY$1 ? '-0' : result;
27165 var _toKey = toKey;
27168 * The base implementation of `_.get` without support for default values.
27171 * @param {Object} object The object to query.
27172 * @param {Array|string} path The path of the property to get.
27173 * @returns {*} Returns the resolved value.
27176 function baseGet(object, path) {
27177 path = _castPath(path, object);
27179 length = path.length;
27181 while (object != null && index < length) {
27182 object = object[_toKey(path[index++])];
27185 return index && index == length ? object : undefined;
27188 var _baseGet = baseGet;
27191 * Gets the value at `path` of `object`. If the resolved value is
27192 * `undefined`, the `defaultValue` is returned in its place.
27198 * @param {Object} object The object to query.
27199 * @param {Array|string} path The path of the property to get.
27200 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
27201 * @returns {*} Returns the resolved value.
27204 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
27206 * _.get(object, 'a[0].b.c');
27209 * _.get(object, ['a', '0', 'b', 'c']);
27212 * _.get(object, 'a.b.c', 'default');
27216 function get$1(object, path, defaultValue) {
27217 var result = object == null ? undefined : _baseGet(object, path);
27218 return result === undefined ? defaultValue : result;
27224 * The base implementation of `_.hasIn` without support for deep paths.
27227 * @param {Object} [object] The object to query.
27228 * @param {Array|string} key The key to check.
27229 * @returns {boolean} Returns `true` if `key` exists, else `false`.
27231 function baseHasIn(object, key) {
27232 return object != null && key in Object(object);
27235 var _baseHasIn = baseHasIn;
27238 * Checks if `path` exists on `object`.
27241 * @param {Object} object The object to query.
27242 * @param {Array|string} path The path to check.
27243 * @param {Function} hasFunc The function to check properties.
27244 * @returns {boolean} Returns `true` if `path` exists, else `false`.
27247 function hasPath(object, path, hasFunc) {
27248 path = _castPath(path, object);
27250 length = path.length,
27253 while (++index < length) {
27254 var key = _toKey(path[index]);
27256 if (!(result = object != null && hasFunc(object, key))) {
27260 object = object[key];
27263 if (result || ++index != length) {
27267 length = object == null ? 0 : object.length;
27268 return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object));
27271 var _hasPath = hasPath;
27274 * Checks if `path` is a direct or inherited property of `object`.
27280 * @param {Object} object The object to query.
27281 * @param {Array|string} path The path to check.
27282 * @returns {boolean} Returns `true` if `path` exists, else `false`.
27285 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
27287 * _.hasIn(object, 'a');
27290 * _.hasIn(object, 'a.b');
27293 * _.hasIn(object, ['a', 'b']);
27296 * _.hasIn(object, 'b');
27300 function hasIn(object, path) {
27301 return object != null && _hasPath(object, path, _baseHasIn);
27304 var hasIn_1 = hasIn;
27306 /** Used to compose bitmasks for value comparisons. */
27308 var COMPARE_PARTIAL_FLAG$5 = 1,
27309 COMPARE_UNORDERED_FLAG$3 = 2;
27311 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
27314 * @param {string} path The path of the property to get.
27315 * @param {*} srcValue The value to match.
27316 * @returns {Function} Returns the new spec function.
27319 function baseMatchesProperty(path, srcValue) {
27320 if (_isKey(path) && _isStrictComparable(srcValue)) {
27321 return _matchesStrictComparable(_toKey(path), srcValue);
27324 return function (object) {
27325 var objValue = get_1(object, path);
27326 return objValue === undefined && objValue === srcValue ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);
27330 var _baseMatchesProperty = baseMatchesProperty;
27333 * This method returns the first argument it receives.
27339 * @param {*} value Any value.
27340 * @returns {*} Returns `value`.
27343 * var object = { 'a': 1 };
27345 * console.log(_.identity(object) === object);
27348 function identity(value) {
27352 var identity_1 = identity;
27355 * The base implementation of `_.property` without support for deep paths.
27358 * @param {string} key The key of the property to get.
27359 * @returns {Function} Returns the new accessor function.
27361 function baseProperty(key) {
27362 return function (object) {
27363 return object == null ? undefined : object[key];
27367 var _baseProperty = baseProperty;
27370 * A specialized version of `baseProperty` which supports deep paths.
27373 * @param {Array|string} path The path of the property to get.
27374 * @returns {Function} Returns the new accessor function.
27377 function basePropertyDeep(path) {
27378 return function (object) {
27379 return _baseGet(object, path);
27383 var _basePropertyDeep = basePropertyDeep;
27386 * Creates a function that returns the value at `path` of a given object.
27392 * @param {Array|string} path The path of the property to get.
27393 * @returns {Function} Returns the new accessor function.
27397 * { 'a': { 'b': 2 } },
27398 * { 'a': { 'b': 1 } }
27401 * _.map(objects, _.property('a.b'));
27404 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
27408 function property(path) {
27409 return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
27412 var property_1 = property;
27415 * The base implementation of `_.iteratee`.
27418 * @param {*} [value=_.identity] The value to convert to an iteratee.
27419 * @returns {Function} Returns the iteratee.
27422 function baseIteratee(value) {
27423 // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
27424 // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
27425 if (typeof value == 'function') {
27429 if (value == null) {
27433 if (typeof value == 'object') {
27434 return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value);
27437 return property_1(value);
27440 var _baseIteratee = baseIteratee;
27443 * The base implementation of `_.findIndex` and `_.findLastIndex` without
27444 * support for iteratee shorthands.
27447 * @param {Array} array The array to inspect.
27448 * @param {Function} predicate The function invoked per iteration.
27449 * @param {number} fromIndex The index to search from.
27450 * @param {boolean} [fromRight] Specify iterating from right to left.
27451 * @returns {number} Returns the index of the matched value, else `-1`.
27453 function baseFindIndex(array, predicate, fromIndex, fromRight) {
27454 var length = array.length,
27455 index = fromIndex + (fromRight ? 1 : -1);
27457 while (fromRight ? index-- : ++index < length) {
27458 if (predicate(array[index], index, array)) {
27466 var _baseFindIndex = baseFindIndex;
27469 * The base implementation of `_.isNaN` without support for number objects.
27472 * @param {*} value The value to check.
27473 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
27475 function baseIsNaN(value) {
27476 return value !== value;
27479 var _baseIsNaN = baseIsNaN;
27482 * A specialized version of `_.indexOf` which performs strict equality
27483 * comparisons of values, i.e. `===`.
27486 * @param {Array} array The array to inspect.
27487 * @param {*} value The value to search for.
27488 * @param {number} fromIndex The index to search from.
27489 * @returns {number} Returns the index of the matched value, else `-1`.
27491 function strictIndexOf(array, value, fromIndex) {
27492 var index = fromIndex - 1,
27493 length = array.length;
27495 while (++index < length) {
27496 if (array[index] === value) {
27504 var _strictIndexOf = strictIndexOf;
27507 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
27510 * @param {Array} array The array to inspect.
27511 * @param {*} value The value to search for.
27512 * @param {number} fromIndex The index to search from.
27513 * @returns {number} Returns the index of the matched value, else `-1`.
27516 function baseIndexOf(array, value, fromIndex) {
27517 return value === value ? _strictIndexOf(array, value, fromIndex) : _baseFindIndex(array, _baseIsNaN, fromIndex);
27520 var _baseIndexOf = baseIndexOf;
27523 * A specialized version of `_.includes` for arrays without support for
27524 * specifying an index to search from.
27527 * @param {Array} [array] The array to inspect.
27528 * @param {*} target The value to search for.
27529 * @returns {boolean} Returns `true` if `target` is found, else `false`.
27532 function arrayIncludes(array, value) {
27533 var length = array == null ? 0 : array.length;
27534 return !!length && _baseIndexOf(array, value, 0) > -1;
27537 var _arrayIncludes = arrayIncludes;
27540 * This function is like `arrayIncludes` except that it accepts a comparator.
27543 * @param {Array} [array] The array to inspect.
27544 * @param {*} target The value to search for.
27545 * @param {Function} comparator The comparator invoked per element.
27546 * @returns {boolean} Returns `true` if `target` is found, else `false`.
27548 function arrayIncludesWith(array, value, comparator) {
27550 length = array == null ? 0 : array.length;
27552 while (++index < length) {
27553 if (comparator(value, array[index])) {
27561 var _arrayIncludesWith = arrayIncludesWith;
27564 * This method returns `undefined`.
27572 * _.times(2, _.noop);
27573 * // => [undefined, undefined]
27575 function noop() {// No operation performed.
27580 /** Used as references for various `Number` constants. */
27582 var INFINITY$2 = 1 / 0;
27584 * Creates a set object of `values`.
27587 * @param {Array} values The values to add to the set.
27588 * @returns {Object} Returns the new set.
27591 var createSet = !(_Set && 1 / _setToArray(new _Set([, -0]))[1] == INFINITY$2) ? noop_1 : function (values) {
27592 return new _Set(values);
27594 var _createSet = createSet;
27596 /** Used as the size to enable large array optimizations. */
27598 var LARGE_ARRAY_SIZE$1 = 200;
27600 * The base implementation of `_.uniqBy` without support for iteratee shorthands.
27603 * @param {Array} array The array to inspect.
27604 * @param {Function} [iteratee] The iteratee invoked per element.
27605 * @param {Function} [comparator] The comparator invoked per element.
27606 * @returns {Array} Returns the new duplicate free array.
27609 function baseUniq(array, iteratee, comparator) {
27611 includes = _arrayIncludes,
27612 length = array.length,
27619 includes = _arrayIncludesWith;
27620 } else if (length >= LARGE_ARRAY_SIZE$1) {
27621 var set = iteratee ? null : _createSet(array);
27624 return _setToArray(set);
27628 includes = _cacheHas;
27629 seen = new _SetCache();
27631 seen = iteratee ? [] : result;
27634 outer: while (++index < length) {
27635 var value = array[index],
27636 computed = iteratee ? iteratee(value) : value;
27637 value = comparator || value !== 0 ? value : 0;
27639 if (isCommon && computed === computed) {
27640 var seenIndex = seen.length;
27642 while (seenIndex--) {
27643 if (seen[seenIndex] === computed) {
27649 seen.push(computed);
27652 result.push(value);
27653 } else if (!includes(seen, computed, comparator)) {
27654 if (seen !== result) {
27655 seen.push(computed);
27658 result.push(value);
27665 var _baseUniq = baseUniq;
27668 * This method is like `_.uniq` except that it accepts `iteratee` which is
27669 * invoked for each element in `array` to generate the criterion by which
27670 * uniqueness is computed. The order of result values is determined by the
27671 * order they occur in the array. The iteratee is invoked with one argument:
27678 * @param {Array} array The array to inspect.
27679 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
27680 * @returns {Array} Returns the new duplicate free array.
27683 * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
27686 * // The `_.property` iteratee shorthand.
27687 * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
27688 * // => [{ 'x': 1 }, { 'x': 2 }]
27691 function uniqBy(array, iteratee) {
27692 return array && array.length ? _baseUniq(array, _baseIteratee(iteratee)) : [];
27695 var uniqBy_1 = uniqBy;
27698 * A specialized version of `baseAggregator` for arrays.
27701 * @param {Array} [array] The array to iterate over.
27702 * @param {Function} setter The function to set `accumulator` values.
27703 * @param {Function} iteratee The iteratee to transform keys.
27704 * @param {Object} accumulator The initial aggregated object.
27705 * @returns {Function} Returns `accumulator`.
27707 function arrayAggregator(array, setter, iteratee, accumulator) {
27709 length = array == null ? 0 : array.length;
27711 while (++index < length) {
27712 var value = array[index];
27713 setter(accumulator, value, iteratee(value), array);
27716 return accumulator;
27719 var _arrayAggregator = arrayAggregator;
27722 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
27725 * @param {boolean} [fromRight] Specify iterating from right to left.
27726 * @returns {Function} Returns the new base function.
27728 function createBaseFor(fromRight) {
27729 return function (object, iteratee, keysFunc) {
27731 iterable = Object(object),
27732 props = keysFunc(object),
27733 length = props.length;
27736 var key = props[fromRight ? length : ++index];
27738 if (iteratee(iterable[key], key, iterable) === false) {
27747 var _createBaseFor = createBaseFor;
27750 * The base implementation of `baseForOwn` which iterates over `object`
27751 * properties returned by `keysFunc` and invokes `iteratee` for each property.
27752 * Iteratee functions may exit iteration early by explicitly returning `false`.
27755 * @param {Object} object The object to iterate over.
27756 * @param {Function} iteratee The function invoked per iteration.
27757 * @param {Function} keysFunc The function to get the keys of `object`.
27758 * @returns {Object} Returns `object`.
27761 var baseFor = _createBaseFor();
27762 var _baseFor = baseFor;
27765 * The base implementation of `_.forOwn` without support for iteratee shorthands.
27768 * @param {Object} object The object to iterate over.
27769 * @param {Function} iteratee The function invoked per iteration.
27770 * @returns {Object} Returns `object`.
27773 function baseForOwn(object, iteratee) {
27774 return object && _baseFor(object, iteratee, keys_1);
27777 var _baseForOwn = baseForOwn;
27780 * Creates a `baseEach` or `baseEachRight` function.
27783 * @param {Function} eachFunc The function to iterate over a collection.
27784 * @param {boolean} [fromRight] Specify iterating from right to left.
27785 * @returns {Function} Returns the new base function.
27788 function createBaseEach(eachFunc, fromRight) {
27789 return function (collection, iteratee) {
27790 if (collection == null) {
27794 if (!isArrayLike_1(collection)) {
27795 return eachFunc(collection, iteratee);
27798 var length = collection.length,
27799 index = fromRight ? length : -1,
27800 iterable = Object(collection);
27802 while (fromRight ? index-- : ++index < length) {
27803 if (iteratee(iterable[index], index, iterable) === false) {
27812 var _createBaseEach = createBaseEach;
27815 * The base implementation of `_.forEach` without support for iteratee shorthands.
27818 * @param {Array|Object} collection The collection to iterate over.
27819 * @param {Function} iteratee The function invoked per iteration.
27820 * @returns {Array|Object} Returns `collection`.
27823 var baseEach = _createBaseEach(_baseForOwn);
27824 var _baseEach = baseEach;
27827 * Aggregates elements of `collection` on `accumulator` with keys transformed
27828 * by `iteratee` and values set by `setter`.
27831 * @param {Array|Object} collection The collection to iterate over.
27832 * @param {Function} setter The function to set `accumulator` values.
27833 * @param {Function} iteratee The iteratee to transform keys.
27834 * @param {Object} accumulator The initial aggregated object.
27835 * @returns {Function} Returns `accumulator`.
27838 function baseAggregator(collection, setter, iteratee, accumulator) {
27839 _baseEach(collection, function (value, key, collection) {
27840 setter(accumulator, value, iteratee(value), collection);
27842 return accumulator;
27845 var _baseAggregator = baseAggregator;
27848 * Creates a function like `_.groupBy`.
27851 * @param {Function} setter The function to set accumulator values.
27852 * @param {Function} [initializer] The accumulator object initializer.
27853 * @returns {Function} Returns the new aggregator function.
27856 function createAggregator(setter, initializer) {
27857 return function (collection, iteratee) {
27858 var func = isArray_1(collection) ? _arrayAggregator : _baseAggregator,
27859 accumulator = initializer ? initializer() : {};
27860 return func(collection, setter, _baseIteratee(iteratee), accumulator);
27864 var _createAggregator = createAggregator;
27867 * Creates an array of elements split into two groups, the first of which
27868 * contains elements `predicate` returns truthy for, the second of which
27869 * contains elements `predicate` returns falsey for. The predicate is
27870 * invoked with one argument: (value).
27875 * @category Collection
27876 * @param {Array|Object} collection The collection to iterate over.
27877 * @param {Function} [predicate=_.identity] The function invoked per iteration.
27878 * @returns {Array} Returns the array of grouped elements.
27882 * { 'user': 'barney', 'age': 36, 'active': false },
27883 * { 'user': 'fred', 'age': 40, 'active': true },
27884 * { 'user': 'pebbles', 'age': 1, 'active': false }
27887 * _.partition(users, function(o) { return o.active; });
27888 * // => objects for [['fred'], ['barney', 'pebbles']]
27890 * // The `_.matches` iteratee shorthand.
27891 * _.partition(users, { 'age': 1, 'active': false });
27892 * // => objects for [['pebbles'], ['barney', 'fred']]
27894 * // The `_.matchesProperty` iteratee shorthand.
27895 * _.partition(users, ['active', false]);
27896 * // => objects for [['barney', 'pebbles'], ['fred']]
27898 * // The `_.property` iteratee shorthand.
27899 * _.partition(users, 'active');
27900 * // => objects for [['fred'], ['barney', 'pebbles']]
27903 var partition = _createAggregator(function (result, value, key) {
27904 result[key ? 0 : 1].push(value);
27908 var partition_1 = partition;
27910 var arrayUnion = (...arguments_) => {
27911 return [...new Set([].concat(...arguments_))];
27916 * https://github.com/teambition/merge2
27918 * Copyright (c) 2014-2016 Teambition
27919 * Licensed under the MIT license.
27923 const PassThrough = stream$6.PassThrough;
27924 const slice = Array.prototype.slice;
27925 var merge2_1 = merge2;
27927 function merge2() {
27928 const streamsQueue = [];
27929 let merging = false;
27930 const args = slice.call(arguments);
27931 let options = args[args.length - 1];
27932 if (options && !Array.isArray(options) && options.pipe == null) args.pop();else options = {};
27933 const doEnd = options.end !== false;
27934 if (options.objectMode == null) options.objectMode = true;
27935 if (options.highWaterMark == null) options.highWaterMark = 64 * 1024;
27936 const mergedStream = PassThrough(options);
27938 function addStream() {
27939 for (let i = 0, len = arguments.length; i < len; i++) {
27940 streamsQueue.push(pauseStreams(arguments[i], options));
27947 function mergeStream() {
27948 if (merging) return;
27950 let streams = streamsQueue.shift();
27953 process.nextTick(endStream);
27957 if (!Array.isArray(streams)) streams = [streams];
27958 let pipesCount = streams.length + 1;
27961 if (--pipesCount > 0) return;
27966 function pipe(stream) {
27968 stream.removeListener('merge2UnpipeEnd', onend);
27969 stream.removeListener('end', onend);
27971 } // skip ended stream
27974 if (stream._readableState.endEmitted) return next();
27975 stream.on('merge2UnpipeEnd', onend);
27976 stream.on('end', onend);
27977 stream.pipe(mergedStream, {
27979 }); // compatible for old stream
27984 for (let i = 0; i < streams.length; i++) pipe(streams[i]);
27989 function endStream() {
27990 merging = false; // emit 'queueDrain' when all streams merged.
27992 mergedStream.emit('queueDrain');
27993 return doEnd && mergedStream.end();
27996 mergedStream.setMaxListeners(0);
27997 mergedStream.add = addStream;
27998 mergedStream.on('unpipe', function (stream) {
27999 stream.emit('merge2UnpipeEnd');
28001 if (args.length) addStream.apply(null, args);
28002 return mergedStream;
28003 } // check and pause streams for pipe.
28006 function pauseStreams(streams, options) {
28007 if (!Array.isArray(streams)) {
28008 // Backwards-compat with old-style streams
28009 if (!streams._readableState && streams.pipe) streams = streams.pipe(PassThrough(options));
28011 if (!streams._readableState || !streams.pause || !streams.pipe) {
28012 throw new Error('Only readable stream can be merged.');
28017 for (let i = 0, len = streams.length; i < len; i++) streams[i] = pauseStreams(streams[i], options);
28023 var array$2 = createCommonjsModule(function (module, exports) {
28025 Object.defineProperty(exports, "__esModule", {
28029 function flatten(items) {
28030 return items.reduce((collection, item) => [].concat(collection, item), []);
28033 exports.flatten = flatten;
28035 function splitWhen(items, predicate) {
28036 const result = [[]];
28037 let groupIndex = 0;
28039 for (const item of items) {
28040 if (predicate(item)) {
28042 result[groupIndex] = [];
28044 result[groupIndex].push(item);
28051 exports.splitWhen = splitWhen;
28053 unwrapExports(array$2);
28054 var array_1$1 = array$2.flatten;
28055 var array_2 = array$2.splitWhen;
28057 var errno = createCommonjsModule(function (module, exports) {
28059 Object.defineProperty(exports, "__esModule", {
28063 function isEnoentCodeError(error) {
28064 return error.code === 'ENOENT';
28067 exports.isEnoentCodeError = isEnoentCodeError;
28069 unwrapExports(errno);
28070 var errno_1 = errno.isEnoentCodeError;
28072 var fs$1 = createCommonjsModule(function (module, exports) {
28074 Object.defineProperty(exports, "__esModule", {
28078 class DirentFromStats {
28079 constructor(name, stats) {
28081 this.isBlockDevice = stats.isBlockDevice.bind(stats);
28082 this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
28083 this.isDirectory = stats.isDirectory.bind(stats);
28084 this.isFIFO = stats.isFIFO.bind(stats);
28085 this.isFile = stats.isFile.bind(stats);
28086 this.isSocket = stats.isSocket.bind(stats);
28087 this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
28092 function createDirentFromStats(name, stats) {
28093 return new DirentFromStats(name, stats);
28096 exports.createDirentFromStats = createDirentFromStats;
28098 unwrapExports(fs$1);
28099 var fs_1 = fs$1.createDirentFromStats;
28101 var path_1 = createCommonjsModule(function (module, exports) {
28103 Object.defineProperty(exports, "__esModule", {
28106 const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
28108 const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
28110 * Designed to work only with simple paths: `dir\\file`.
\r
28113 function unixify(filepath) {
28114 return filepath.replace(/\\/g, '/');
28117 exports.unixify = unixify;
28119 function makeAbsolute(cwd, filepath) {
28120 return path$2.resolve(cwd, filepath);
28123 exports.makeAbsolute = makeAbsolute;
28125 function escape(pattern) {
28126 return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
28129 exports.escape = escape;
28131 function removeLeadingDotSegment(entry) {
28132 // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
28133 // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
28134 if (entry.charAt(0) === '.') {
28135 const secondCharactery = entry.charAt(1);
28137 if (secondCharactery === '/' || secondCharactery === '\\') {
28138 return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
28145 exports.removeLeadingDotSegment = removeLeadingDotSegment;
28147 unwrapExports(path_1);
28148 var path_2 = path_1.unixify;
28149 var path_3 = path_1.makeAbsolute;
28150 var path_4 = path_1.escape;
28151 var path_5 = path_1.removeLeadingDotSegment;
28154 * is-extglob <https://github.com/jonschlinkert/is-extglob>
28156 * Copyright (c) 2014-2016, Jon Schlinkert.
28157 * Licensed under the MIT License.
28159 var isExtglob = function isExtglob(str) {
28160 if (typeof str !== 'string' || str === '') {
28166 while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
28167 if (match[2]) return true;
28168 str = str.slice(match.index + match[0].length);
28175 * is-glob <https://github.com/jonschlinkert/is-glob>
28177 * Copyright (c) 2014-2017, Jon Schlinkert.
28178 * Released under the MIT License.
28186 var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
28187 var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
28189 var isGlob = function isGlob(str, options) {
28190 if (typeof str !== 'string' || str === '') {
28194 if (isExtglob(str)) {
28198 var regex = strictRegex;
28199 var match; // optionally relax regex
28201 if (options && options.strict === false) {
28202 regex = relaxedRegex;
28205 while (match = regex.exec(str)) {
28206 if (match[2]) return true;
28207 var idx = match.index + match[0].length; // if an open bracket/brace/paren is escaped,
28208 // set the index to the next closing character
28210 var open = match[1];
28211 var close = open ? chars[open] : null;
28213 if (open && close) {
28214 var n = str.indexOf(close, idx);
28221 str = str.slice(idx);
28227 var pathPosixDirname = path$2.posix.dirname;
28228 var isWin32 = os$1.platform() === 'win32';
28230 var backslash = /\\/g;
28231 var enclosure = /[\{\[].*[\/]*.*[\}\]]$/;
28232 var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
28233 var escaped = /\\([\*\?\|\[\]\(\)\{\}])/g;
28235 * @param {string} str
28236 * @param {Object} opts
28237 * @param {boolean} [opts.flipBackslashes=true]
28240 var globParent = function globParent(str, opts) {
28241 var options = Object.assign({
28242 flipBackslashes: true
28243 }, opts); // flip windows path separators
28245 if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
28246 str = str.replace(backslash, slash);
28247 } // special case for strings ending in enclosure containing path separator
28250 if (enclosure.test(str)) {
28252 } // preserves full path in case of trailing path separator
28255 str += 'a'; // remove path parts that are globby
28258 str = pathPosixDirname(str);
28259 } while (isGlob(str) || globby.test(str)); // remove escape chars and return result
28262 return str.replace(escaped, '$1');
28265 var utils$2 = createCommonjsModule(function (module, exports) {
28267 exports.isInteger = num => {
28268 if (typeof num === 'number') {
28269 return Number.isInteger(num);
28272 if (typeof num === 'string' && num.trim() !== '') {
28273 return Number.isInteger(Number(num));
28279 * Find a node of the given type
28283 exports.find = (node, type) => node.nodes.find(node => node.type === type);
28285 * Find a node of the given type
28289 exports.exceedsLimit = (min, max, step = 1, limit) => {
28290 if (limit === false) return false;
28291 if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
28292 return (Number(max) - Number(min)) / Number(step) >= limit;
28295 * Escape the given node with '\\' before node.value
28299 exports.escapeNode = (block, n = 0, type) => {
28300 let node = block.nodes[n];
28303 if (type && node.type === type || node.type === 'open' || node.type === 'close') {
28304 if (node.escaped !== true) {
28305 node.value = '\\' + node.value;
28306 node.escaped = true;
28311 * Returns true if the given brace node should be enclosed in literal braces
28315 exports.encloseBrace = node => {
28316 if (node.type !== 'brace') return false;
28318 if (node.commas >> 0 + node.ranges >> 0 === 0) {
28319 node.invalid = true;
28326 * Returns true if a brace node is invalid.
28330 exports.isInvalidBrace = block => {
28331 if (block.type !== 'brace') return false;
28332 if (block.invalid === true || block.dollar) return true;
28334 if (block.commas >> 0 + block.ranges >> 0 === 0) {
28335 block.invalid = true;
28339 if (block.open !== true || block.close !== true) {
28340 block.invalid = true;
28347 * Returns true if a node is an open or close node
28351 exports.isOpenOrClose = node => {
28352 if (node.type === 'open' || node.type === 'close') {
28356 return node.open === true || node.close === true;
28359 * Reduce an array of text nodes.
28363 exports.reduce = nodes => nodes.reduce((acc, node) => {
28364 if (node.type === 'text') acc.push(node.value);
28365 if (node.type === 'range') node.type = 'text';
28373 exports.flatten = (...args) => {
28376 const flat = arr => {
28377 for (let i = 0; i < arr.length; i++) {
28379 Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
28389 var utils_1$2 = utils$2.isInteger;
28390 var utils_2$2 = utils$2.find;
28391 var utils_3$2 = utils$2.exceedsLimit;
28392 var utils_4$1 = utils$2.escapeNode;
28393 var utils_5$1 = utils$2.encloseBrace;
28394 var utils_6$1 = utils$2.isInvalidBrace;
28395 var utils_7$1 = utils$2.isOpenOrClose;
28396 var utils_8$1 = utils$2.reduce;
28397 var utils_9$1 = utils$2.flatten;
28399 var stringify = (ast, options = {}) => {
28400 let stringify = (node, parent = {}) => {
28401 let invalidBlock = options.escapeInvalid && utils$2.isInvalidBrace(parent);
28402 let invalidNode = node.invalid === true && options.escapeInvalid === true;
28406 if ((invalidBlock || invalidNode) && utils$2.isOpenOrClose(node)) {
28407 return '\\' + node.value;
28418 for (let child of node.nodes) {
28419 output += stringify(child);
28426 return stringify(ast);
28430 * is-number <https://github.com/jonschlinkert/is-number>
28432 * Copyright (c) 2014-present, Jon Schlinkert.
28433 * Released under the MIT License.
28436 var isNumber = function (num) {
28437 if (typeof num === 'number') {
28438 return num - num === 0;
28441 if (typeof num === 'string' && num.trim() !== '') {
28442 return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
28448 const toRegexRange = (min, max, options) => {
28449 if (isNumber(min) === false) {
28450 throw new TypeError('toRegexRange: expected the first argument to be a number');
28453 if (max === void 0 || min === max) {
28454 return String(min);
28457 if (isNumber(max) === false) {
28458 throw new TypeError('toRegexRange: expected the second argument to be a number.');
28461 let opts = Object.assign({
28465 if (typeof opts.strictZeros === 'boolean') {
28466 opts.relaxZeros = opts.strictZeros === false;
28469 let relax = String(opts.relaxZeros);
28470 let shorthand = String(opts.shorthand);
28471 let capture = String(opts.capture);
28472 let wrap = String(opts.wrap);
28473 let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
28475 if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
28476 return toRegexRange.cache[cacheKey].result;
28479 let a = Math.min(min, max);
28480 let b = Math.max(min, max);
28482 if (Math.abs(a - b) === 1) {
28483 let result = min + '|' + max;
28485 if (opts.capture) {
28486 return `(${result})`;
28489 if (opts.wrap === false) {
28493 return `(?:${result})`;
28496 let isPadded = hasPadding(min) || hasPadding(max);
28503 let positives = [];
28504 let negatives = [];
28507 state.isPadded = isPadded;
28508 state.maxLen = String(state.max).length;
28512 let newMin = b < 0 ? Math.abs(b) : 1;
28513 negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
28518 positives = splitToPatterns(a, b, state, opts);
28521 state.negatives = negatives;
28522 state.positives = positives;
28523 state.result = collatePatterns(negatives, positives);
28525 if (opts.capture === true) {
28526 state.result = `(${state.result})`;
28527 } else if (opts.wrap !== false && positives.length + negatives.length > 1) {
28528 state.result = `(?:${state.result})`;
28531 toRegexRange.cache[cacheKey] = state;
28532 return state.result;
28535 function collatePatterns(neg, pos, options) {
28536 let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
28537 let onlyPositive = filterPatterns(pos, neg, '', false) || [];
28538 let intersected = filterPatterns(neg, pos, '-?', true) || [];
28539 let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
28540 return subpatterns.join('|');
28543 function splitToRanges(min, max) {
28546 let stop = countNines(min, nines);
28547 let stops = new Set([max]);
28549 while (min <= stop && stop <= max) {
28552 stop = countNines(min, nines);
28555 stop = countZeros(max + 1, zeros) - 1;
28557 while (min < stop && stop <= max) {
28560 stop = countZeros(max + 1, zeros) - 1;
28563 stops = [...stops];
28564 stops.sort(compare$1);
28568 * Convert a range to a regex pattern
28569 * @param {Number} `start`
28570 * @param {Number} `stop`
28575 function rangeToPattern(start, stop, options) {
28576 if (start === stop) {
28584 let zipped = zip(start, stop);
28585 let digits = zipped.length;
28589 for (let i = 0; i < digits; i++) {
28590 let [startDigit, stopDigit] = zipped[i];
28592 if (startDigit === stopDigit) {
28593 pattern += startDigit;
28594 } else if (startDigit !== '0' || stopDigit !== '9') {
28595 pattern += toCharacterClass(startDigit, stopDigit);
28602 pattern += options.shorthand === true ? '\\d' : '[0-9]';
28612 function splitToPatterns(min, max, tok, options) {
28613 let ranges = splitToRanges(min, max);
28618 for (let i = 0; i < ranges.length; i++) {
28619 let max = ranges[i];
28620 let obj = rangeToPattern(String(start), String(max), options);
28623 if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
28624 if (prev.count.length > 1) {
28628 prev.count.push(obj.count[0]);
28629 prev.string = prev.pattern + toQuantifier(prev.count);
28634 if (tok.isPadded) {
28635 zeros = padZeros(max, tok, options);
28638 obj.string = zeros + obj.pattern + toQuantifier(obj.count);
28647 function filterPatterns(arr, comparison, prefix, intersection, options) {
28650 for (let ele of arr) {
28653 } = ele; // only push if _both_ are negative...
28655 if (!intersection && !contains(comparison, 'string', string)) {
28656 result.push(prefix + string);
28657 } // or _both_ are positive
28660 if (intersection && contains(comparison, 'string', string)) {
28661 result.push(prefix + string);
28672 function zip(a, b) {
28675 for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
28680 function compare$1(a, b) {
28681 return a > b ? 1 : b > a ? -1 : 0;
28684 function contains(arr, key, val) {
28685 return arr.some(ele => ele[key] === val);
28688 function countNines(min, len) {
28689 return Number(String(min).slice(0, -len) + '9'.repeat(len));
28692 function countZeros(integer, zeros) {
28693 return integer - integer % Math.pow(10, zeros);
28696 function toQuantifier(digits) {
28697 let [start = 0, stop = ''] = digits;
28699 if (stop || start > 1) {
28700 return `{${start + (stop ? ',' + stop : '')}}`;
28706 function toCharacterClass(a, b, options) {
28707 return `[${a}${b - a === 1 ? '' : '-'}${b}]`;
28710 function hasPadding(str) {
28711 return /^-?(0+)\d/.test(str);
28714 function padZeros(value, tok, options) {
28715 if (!tok.isPadded) {
28719 let diff = Math.abs(tok.maxLen - String(value).length);
28720 let relax = options.relaxZeros !== false;
28727 return relax ? '0?' : '0';
28730 return relax ? '0{0,2}' : '00';
28734 return relax ? `0{0,${diff}}` : `0{${diff}}`;
28743 toRegexRange.cache = {};
28745 toRegexRange.clearCache = () => toRegexRange.cache = {};
28747 * Expose `toRegexRange`
28751 var toRegexRange_1 = toRegexRange;
28753 const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
28755 const transform = toNumber => {
28756 return value => toNumber === true ? Number(value) : String(value);
28759 const isValidValue = value => {
28760 return typeof value === 'number' || typeof value === 'string' && value !== '';
28763 const isNumber$1 = num => Number.isInteger(+num);
28765 const zeros = input => {
28766 let value = `${input}`;
28768 if (value[0] === '-') value = value.slice(1);
28769 if (value === '0') return false;
28771 while (value[++index] === '0');
28776 const stringify$1 = (start, end, options) => {
28777 if (typeof start === 'string' || typeof end === 'string') {
28781 return options.stringify === true;
28784 const pad = (input, maxLength, toNumber) => {
28785 if (maxLength > 0) {
28786 let dash = input[0] === '-' ? '-' : '';
28787 if (dash) input = input.slice(1);
28788 input = dash + input.padStart(dash ? maxLength - 1 : maxLength, '0');
28791 if (toNumber === false) {
28792 return String(input);
28798 const toMaxLen = (input, maxLength) => {
28799 let negative = input[0] === '-' ? '-' : '';
28802 input = input.slice(1);
28806 while (input.length < maxLength) input = '0' + input;
28808 return negative ? '-' + input : input;
28811 const toSequence = (parts, options) => {
28812 parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
28813 parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
28814 let prefix = options.capture ? '' : '?:';
28815 let positives = '';
28816 let negatives = '';
28819 if (parts.positives.length) {
28820 positives = parts.positives.join('|');
28823 if (parts.negatives.length) {
28824 negatives = `-(${prefix}${parts.negatives.join('|')})`;
28827 if (positives && negatives) {
28828 result = `${positives}|${negatives}`;
28830 result = positives || negatives;
28833 if (options.wrap) {
28834 return `(${prefix}${result})`;
28840 const toRange = (a, b, isNumbers, options) => {
28842 return toRegexRange_1(a, b, Object.assign({
28847 let start = String.fromCharCode(a);
28848 if (a === b) return start;
28849 let stop = String.fromCharCode(b);
28850 return `[${start}-${stop}]`;
28853 const toRegex = (start, end, options) => {
28854 if (Array.isArray(start)) {
28855 let wrap = options.wrap === true;
28856 let prefix = options.capture ? '' : '?:';
28857 return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
28860 return toRegexRange_1(start, end, options);
28863 const rangeError = (...args) => {
28864 return new RangeError('Invalid range arguments: ' + util$4.inspect(...args));
28867 const invalidRange = (start, end, options) => {
28868 if (options.strictRanges === true) throw rangeError([start, end]);
28872 const invalidStep = (step, options) => {
28873 if (options.strictRanges === true) {
28874 throw new TypeError(`Expected step "${step}" to be a number`);
28880 const fillNumbers = (start, end, step = 1, options = {}) => {
28881 let a = Number(start);
28882 let b = Number(end);
28884 if (!Number.isInteger(a) || !Number.isInteger(b)) {
28885 if (options.strictRanges === true) throw rangeError([start, end]);
28887 } // fix negative zero
28890 if (a === 0) a = 0;
28891 if (b === 0) b = 0;
28892 let descending = a > b;
28893 let startString = String(start);
28894 let endString = String(end);
28895 let stepString = String(step);
28896 step = Math.max(Math.abs(step), 1);
28897 let padded = zeros(startString) || zeros(endString) || zeros(stepString);
28898 let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
28899 let toNumber = padded === false && stringify$1(start, end, options) === false;
28900 let format = options.transform || transform(toNumber);
28902 if (options.toRegex && step === 1) {
28903 return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
28911 let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
28916 while (descending ? a >= b : a <= b) {
28917 if (options.toRegex === true && step > 1) {
28920 range.push(pad(format(a, index), maxLen, toNumber));
28923 a = descending ? a - step : a + step;
28927 if (options.toRegex === true) {
28928 return step > 1 ? toSequence(parts, options) : toRegex(range, null, Object.assign({
28936 const fillLetters = (start, end, step = 1, options = {}) => {
28937 if (!isNumber$1(start) && start.length > 1 || !isNumber$1(end) && end.length > 1) {
28938 return invalidRange(start, end, options);
28941 let format = options.transform || (val => String.fromCharCode(val));
28943 let a = `${start}`.charCodeAt(0);
28944 let b = `${end}`.charCodeAt(0);
28945 let descending = a > b;
28946 let min = Math.min(a, b);
28947 let max = Math.max(a, b);
28949 if (options.toRegex && step === 1) {
28950 return toRange(min, max, false, options);
28956 while (descending ? a >= b : a <= b) {
28957 range.push(format(a, index));
28958 a = descending ? a - step : a + step;
28962 if (options.toRegex === true) {
28963 return toRegex(range, null, {
28972 const fill$2 = (start, end, step, options = {}) => {
28973 if (end == null && isValidValue(start)) {
28977 if (!isValidValue(start) || !isValidValue(end)) {
28978 return invalidRange(start, end, options);
28981 if (typeof step === 'function') {
28982 return fill$2(start, end, 1, {
28987 if (isObject$1(step)) {
28988 return fill$2(start, end, 0, step);
28991 let opts = Object.assign({}, options);
28992 if (opts.capture === true) opts.wrap = true;
28993 step = step || opts.step || 1;
28995 if (!isNumber$1(step)) {
28996 if (step != null && !isObject$1(step)) return invalidStep(step, opts);
28997 return fill$2(start, end, 1, step);
29000 if (isNumber$1(start) && isNumber$1(end)) {
29001 return fillNumbers(start, end, step, opts);
29004 return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
29007 var fillRange = fill$2;
29009 const compile = (ast, options = {}) => {
29010 let walk = (node, parent = {}) => {
29011 let invalidBlock = utils$2.isInvalidBrace(parent);
29012 let invalidNode = node.invalid === true && options.escapeInvalid === true;
29013 let invalid = invalidBlock === true || invalidNode === true;
29014 let prefix = options.escapeInvalid === true ? '\\' : '';
29017 if (node.isOpen === true) {
29018 return prefix + node.value;
29021 if (node.isClose === true) {
29022 return prefix + node.value;
29025 if (node.type === 'open') {
29026 return invalid ? prefix + node.value : '(';
29029 if (node.type === 'close') {
29030 return invalid ? prefix + node.value : ')';
29033 if (node.type === 'comma') {
29034 return node.prev.type === 'comma' ? '' : invalid ? node.value : '|';
29041 if (node.nodes && node.ranges > 0) {
29042 let args = utils$2.reduce(node.nodes);
29043 let range = fillRange(...args, Object.assign({}, options, {
29048 if (range.length !== 0) {
29049 return args.length > 1 && range.length > 1 ? `(${range})` : range;
29054 for (let child of node.nodes) {
29055 output += walk(child, node);
29065 var compile_1 = compile;
29067 const append = (queue = '', stash = '', enclose = false) => {
29069 queue = [].concat(queue);
29070 stash = [].concat(stash);
29071 if (!stash.length) return queue;
29073 if (!queue.length) {
29074 return enclose ? utils$2.flatten(stash).map(ele => `{${ele}}`) : stash;
29077 for (let item of queue) {
29078 if (Array.isArray(item)) {
29079 for (let value of item) {
29080 result.push(append(value, stash, enclose));
29083 for (let ele of stash) {
29084 if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
29085 result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
29090 return utils$2.flatten(result);
29093 const expand$1 = (ast, options = {}) => {
29094 let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
29096 let walk = (node, parent = {}) => {
29099 let q = parent.queue;
29101 while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
29106 if (node.invalid || node.dollar) {
29107 q.push(append(q.pop(), stringify(node, options)));
29111 if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
29112 q.push(append(q.pop(), ['{}']));
29116 if (node.nodes && node.ranges > 0) {
29117 let args = utils$2.reduce(node.nodes);
29119 if (utils$2.exceedsLimit(...args, options.step, rangeLimit)) {
29120 throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
29123 let range = fillRange(...args, options);
29125 if (range.length === 0) {
29126 range = stringify(node, options);
29129 q.push(append(q.pop(), range));
29134 let enclose = utils$2.encloseBrace(node);
29135 let queue = node.queue;
29138 while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
29139 block = block.parent;
29140 queue = block.queue;
29143 for (let i = 0; i < node.nodes.length; i++) {
29144 let child = node.nodes[i];
29146 if (child.type === 'comma' && node.type === 'brace') {
29147 if (i === 1) queue.push('');
29152 if (child.type === 'close') {
29153 q.push(append(q.pop(), queue, enclose));
29157 if (child.value && child.type !== 'open') {
29158 queue.push(append(queue.pop(), child.value));
29170 return utils$2.flatten(walk(ast));
29173 var expand_1 = expand$1;
29175 var constants$2 = {
29176 MAX_LENGTH: 1024 * 64,
29185 CHAR_UPPERCASE_A: 'A',
29188 CHAR_LOWERCASE_A: 'a',
29191 CHAR_UPPERCASE_Z: 'Z',
29194 CHAR_LOWERCASE_Z: 'z',
29197 CHAR_LEFT_PARENTHESES: '(',
29200 CHAR_RIGHT_PARENTHESES: ')',
29203 CHAR_ASTERISK: '*',
29206 // Non-alphabetic chars.
29207 CHAR_AMPERSAND: '&',
29213 CHAR_BACKSLASH: '\\',
29216 CHAR_BACKTICK: '`',
29219 CHAR_CARRIAGE_RETURN: '\r',
29222 CHAR_CIRCUMFLEX_ACCENT: '^',
29237 CHAR_DOUBLE_QUOTE: '"',
29243 CHAR_EXCLAMATION_MARK: '!',
29246 CHAR_FORM_FEED: '\f',
29249 CHAR_FORWARD_SLASH: '/',
29255 CHAR_HYPHEN_MINUS: '-',
29258 CHAR_LEFT_ANGLE_BRACKET: '<',
29261 CHAR_LEFT_CURLY_BRACE: '{',
29264 CHAR_LEFT_SQUARE_BRACKET: '[',
29267 CHAR_LINE_FEED: '\n',
29270 CHAR_NO_BREAK_SPACE: '\u00A0',
29279 CHAR_QUESTION_MARK: '?',
29282 CHAR_RIGHT_ANGLE_BRACKET: '>',
29285 CHAR_RIGHT_CURLY_BRACE: '}',
29288 CHAR_RIGHT_SQUARE_BRACKET: ']',
29291 CHAR_SEMICOLON: ';',
29294 CHAR_SINGLE_QUOTE: '\'',
29303 CHAR_UNDERSCORE: '_',
29306 CHAR_VERTICAL_LINE: '|',
29309 CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF'
29320 MAX_LENGTH: MAX_LENGTH$2,
29327 CHAR_COMMA: CHAR_COMMA$1,
29333 CHAR_LEFT_PARENTHESES,
29336 CHAR_RIGHT_PARENTHESES,
29339 CHAR_LEFT_CURLY_BRACE,
29342 CHAR_RIGHT_CURLY_BRACE,
29345 CHAR_LEFT_SQUARE_BRACKET,
29348 CHAR_RIGHT_SQUARE_BRACKET,
29357 CHAR_NO_BREAK_SPACE,
29358 CHAR_ZERO_WIDTH_NOBREAK_SPACE
29364 const parse$3 = (input, options = {}) => {
29365 if (typeof input !== 'string') {
29366 throw new TypeError('Expected a string');
29369 let opts = options || {};
29370 let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$2, opts.maxLength) : MAX_LENGTH$2;
29372 if (input.length > max) {
29373 throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
29385 let length = input.length;
29393 const advance = () => input[index++];
29395 const push = node => {
29396 if (node.type === 'text' && prev.type === 'dot') {
29397 prev.type = 'text';
29400 if (prev && prev.type === 'text' && node.type === 'text') {
29401 prev.value += node.value;
29405 block.nodes.push(node);
29406 node.parent = block;
29416 while (index < length) {
29417 block = stack[stack.length - 1];
29423 if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
29431 if (value === CHAR_BACKSLASH) {
29434 value: (options.keepEscaping ? value : '') + advance()
29439 * Right square bracket (literal): ']'
29443 if (value === CHAR_RIGHT_SQUARE_BRACKET) {
29446 value: '\\' + value
29451 * Left square bracket: '['
29455 if (value === CHAR_LEFT_SQUARE_BRACKET) {
29459 while (index < length && (next = advance())) {
29462 if (next === CHAR_LEFT_SQUARE_BRACKET) {
29467 if (next === CHAR_BACKSLASH) {
29468 value += advance();
29472 if (next === CHAR_RIGHT_SQUARE_BRACKET) {
29475 if (brackets === 0) {
29492 if (value === CHAR_LEFT_PARENTHESES) {
29505 if (value === CHAR_RIGHT_PARENTHESES) {
29506 if (block.type !== 'paren') {
29514 block = stack.pop();
29519 block = stack[stack.length - 1];
29527 if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
29531 if (options.keepQuotes !== true) {
29535 while (index < length && (next = advance())) {
29536 if (next === CHAR_BACKSLASH) {
29537 value += next + advance();
29541 if (next === open) {
29542 if (options.keepQuotes === true) value += next;
29556 * Left curly brace: '{'
29560 if (value === CHAR_LEFT_CURLY_BRACE) {
29562 let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
29573 block = push(brace);
29582 * Right curly brace: '}'
29586 if (value === CHAR_RIGHT_CURLY_BRACE) {
29587 if (block.type !== 'brace') {
29595 let type = 'close';
29596 block = stack.pop();
29597 block.close = true;
29603 block = stack[stack.length - 1];
29611 if (value === CHAR_COMMA$1 && depth > 0) {
29612 if (block.ranges > 0) {
29614 let open = block.nodes.shift();
29615 block.nodes = [open, {
29617 value: stringify(block)
29633 if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
29634 let siblings = block.nodes;
29636 if (depth === 0 || siblings.length === 0) {
29644 if (prev.type === 'dot') {
29646 prev.value += value;
29647 prev.type = 'range';
29649 if (block.nodes.length !== 3 && block.nodes.length !== 5) {
29650 block.invalid = true;
29652 prev.type = 'text';
29661 if (prev.type === 'range') {
29663 let before = siblings[siblings.length - 1];
29664 before.value += prev.value + value;
29685 } // Mark imbalanced braces and brackets as invalid
29689 block = stack.pop();
29691 if (block.type !== 'root') {
29692 block.nodes.forEach(node => {
29694 if (node.type === 'open') node.isOpen = true;
29695 if (node.type === 'close') node.isClose = true;
29696 if (!node.nodes) node.type = 'text';
29697 node.invalid = true;
29699 }); // get the location of the block on parent.nodes (block's siblings)
29701 let parent = stack[stack.length - 1];
29702 let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes
29704 parent.nodes.splice(index, 1, ...block.nodes);
29706 } while (stack.length > 0);
29714 var parse_1 = parse$3;
29717 * Expand the given pattern or create a regex-compatible string.
29720 * const braces = require('braces');
29721 * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
29722 * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
29724 * @param {String} `str`
29725 * @param {Object} `options`
29731 const braces = (input, options = {}) => {
29734 if (Array.isArray(input)) {
29735 for (let pattern of input) {
29736 let result = braces.create(pattern, options);
29738 if (Array.isArray(result)) {
29739 output.push(...result);
29741 output.push(result);
29745 output = [].concat(braces.create(input, options));
29748 if (options && options.expand === true && options.nodupes === true) {
29749 output = [...new Set(output)];
29755 * Parse the given `str` with the given `options`.
29758 * // braces.parse(pattern, [, options]);
29759 * const ast = braces.parse('a/{b,c}/d');
29760 * console.log(ast);
29762 * @param {String} pattern Brace pattern to parse
29763 * @param {Object} options
29764 * @return {Object} Returns an AST
29769 braces.parse = (input, options = {}) => parse_1(input, options);
29771 * Creates a braces string from an AST, or an AST node.
29774 * const braces = require('braces');
29775 * let ast = braces.parse('foo/{a,b}/bar');
29776 * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
29778 * @param {String} `input` Brace pattern or AST.
29779 * @param {Object} `options`
29780 * @return {Array} Returns an array of expanded values.
29785 braces.stringify = (input, options = {}) => {
29786 if (typeof input === 'string') {
29787 return stringify(braces.parse(input, options), options);
29790 return stringify(input, options);
29793 * Compiles a brace pattern into a regex-compatible, optimized string.
29794 * This method is called by the main [braces](#braces) function by default.
29797 * const braces = require('braces');
29798 * console.log(braces.compile('a/{b,c}/d'));
29799 * //=> ['a/(b|c)/d']
29801 * @param {String} `input` Brace pattern or AST.
29802 * @param {Object} `options`
29803 * @return {Array} Returns an array of expanded values.
29808 braces.compile = (input, options = {}) => {
29809 if (typeof input === 'string') {
29810 input = braces.parse(input, options);
29813 return compile_1(input, options);
29816 * Expands a brace pattern into an array. This method is called by the
29817 * main [braces](#braces) function when `options.expand` is true. Before
29818 * using this method it's recommended that you read the [performance notes](#performance))
29819 * and advantages of using [.compile](#compile) instead.
29822 * const braces = require('braces');
29823 * console.log(braces.expand('a/{b,c}/d'));
29824 * //=> ['a/b/d', 'a/c/d'];
29826 * @param {String} `pattern` Brace pattern
29827 * @param {Object} `options`
29828 * @return {Array} Returns an array of expanded values.
29833 braces.expand = (input, options = {}) => {
29834 if (typeof input === 'string') {
29835 input = braces.parse(input, options);
29838 let result = expand_1(input, options); // filter out empty strings if specified
29840 if (options.noempty === true) {
29841 result = result.filter(Boolean);
29842 } // filter out duplicates if specified
29845 if (options.nodupes === true) {
29846 result = [...new Set(result)];
29852 * Processes a brace pattern and returns either an expanded array
29853 * (if `options.expand` is true), a highly optimized regex-compatible string.
29854 * This method is called by the main [braces](#braces) function.
29857 * const braces = require('braces');
29858 * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
29859 * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
29861 * @param {String} `pattern` Brace pattern
29862 * @param {Object} `options`
29863 * @return {Array} Returns an array of expanded values.
29868 braces.create = (input, options = {}) => {
29869 if (input === '' || input.length < 3) {
29873 return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options);
29880 var braces_1 = braces;
29882 const WIN_SLASH = '\\\\/';
29883 const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
29888 const DOT_LITERAL = '\\.';
29889 const PLUS_LITERAL = '\\+';
29890 const QMARK_LITERAL = '\\?';
29891 const SLASH_LITERAL = '\\/';
29892 const ONE_CHAR = '(?=.)';
29893 const QMARK = '[^/]';
29894 const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
29895 const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
29896 const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
29897 const NO_DOT = `(?!${DOT_LITERAL})`;
29898 const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
29899 const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
29900 const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
29901 const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
29902 const STAR = `${QMARK}*?`;
29903 const POSIX_CHARS = {
29921 * Windows glob regex
29924 const WINDOWS_CHARS = Object.assign({}, POSIX_CHARS, {
29925 SLASH_LITERAL: `[${WIN_SLASH}]`,
29926 QMARK: WIN_NO_SLASH,
29927 STAR: `${WIN_NO_SLASH}*?`,
29928 DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
29929 NO_DOT: `(?!${DOT_LITERAL})`,
29930 NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
29931 NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
29932 NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
29933 QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
29934 START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
29935 END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
29938 * POSIX Bracket Regex
29941 const POSIX_REGEX_SOURCE = {
29942 alnum: 'a-zA-Z0-9',
29944 ascii: '\\x00-\\x7F',
29946 cntrl: '\\x00-\\x1F\\x7F',
29948 graph: '\\x21-\\x7E',
29950 print: '\\x20-\\x7E ',
29951 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
29952 space: ' \\t\\r\\n\\v\\f',
29954 word: 'A-Za-z0-9_',
29955 xdigit: 'A-Fa-f0-9'
29957 var constants$3 = {
29958 MAX_LENGTH: 1024 * 64,
29959 POSIX_REGEX_SOURCE,
29960 // regular expressions
29961 REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
29962 REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
29963 REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
29964 REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
29965 REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
29966 REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
29967 // Replace globs with equivalent patterns to reduce parsing time.
29981 CHAR_UPPERCASE_A: 65,
29984 CHAR_LOWERCASE_A: 97,
29987 CHAR_UPPERCASE_Z: 90,
29990 CHAR_LOWERCASE_Z: 122,
29993 CHAR_LEFT_PARENTHESES: 40,
29996 CHAR_RIGHT_PARENTHESES: 41,
30002 // Non-alphabetic chars.
30003 CHAR_AMPERSAND: 38,
30009 CHAR_BACKWARD_SLASH: 92,
30012 CHAR_CARRIAGE_RETURN: 13,
30015 CHAR_CIRCUMFLEX_ACCENT: 94,
30027 CHAR_DOUBLE_QUOTE: 34,
30033 CHAR_EXCLAMATION_MARK: 33,
30036 CHAR_FORM_FEED: 12,
30039 CHAR_FORWARD_SLASH: 47,
30042 CHAR_GRAVE_ACCENT: 96,
30048 CHAR_HYPHEN_MINUS: 45,
30051 CHAR_LEFT_ANGLE_BRACKET: 60,
30054 CHAR_LEFT_CURLY_BRACE: 123,
30057 CHAR_LEFT_SQUARE_BRACKET: 91,
30060 CHAR_LINE_FEED: 10,
30063 CHAR_NO_BREAK_SPACE: 160,
30072 CHAR_QUESTION_MARK: 63,
30075 CHAR_RIGHT_ANGLE_BRACKET: 62,
30078 CHAR_RIGHT_CURLY_BRACE: 125,
30081 CHAR_RIGHT_SQUARE_BRACKET: 93,
30084 CHAR_SEMICOLON: 59,
30087 CHAR_SINGLE_QUOTE: 39,
30096 CHAR_UNDERSCORE: 95,
30099 CHAR_VERTICAL_LINE: 124,
30102 CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
30108 * Create EXTGLOB_CHARS
30110 extglobChars(chars) {
30115 close: `))${chars.STAR})`
30141 * Create GLOB_CHARS
30144 return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
30149 var utils$3 = createCommonjsModule(function (module, exports) {
30151 const win32 = process.platform === 'win32';
30154 REGEX_REMOVE_BACKSLASH,
30155 REGEX_SPECIAL_CHARS,
30156 REGEX_SPECIAL_CHARS_GLOBAL
30159 exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
30161 exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
30163 exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
30165 exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
30167 exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
30169 exports.removeBackslashes = str => {
30170 return str.replace(REGEX_REMOVE_BACKSLASH, match => {
30171 return match === '\\' ? '' : match;
30175 exports.supportsLookbehinds = () => {
30176 const segs = process.version.slice(1).split('.').map(Number);
30178 if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) {
30185 exports.isWindows = options => {
30186 if (options && typeof options.windows === 'boolean') {
30187 return options.windows;
30190 return win32 === true || path$2.sep === '\\';
30193 exports.escapeLast = (input, char, lastIdx) => {
30194 const idx = input.lastIndexOf(char, lastIdx);
30195 if (idx === -1) return input;
30196 if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
30197 return `${input.slice(0, idx)}\\${input.slice(idx)}`;
30200 exports.removePrefix = (input, state = {}) => {
30201 let output = input;
30203 if (output.startsWith('./')) {
30204 output = output.slice(2);
30205 state.prefix = './';
30211 exports.wrapOutput = (input, state = {}, options = {}) => {
30212 const prepend = options.contains ? '' : '^';
30213 const append = options.contains ? '' : '$';
30214 let output = `${prepend}(?:${input})${append}`;
30216 if (state.negated === true) {
30217 output = `(?:^(?!${output}).*$)`;
30223 var utils_1$3 = utils$3.isObject;
30224 var utils_2$3 = utils$3.hasRegexChars;
30225 var utils_3$3 = utils$3.isRegexChar;
30226 var utils_4$2 = utils$3.escapeRegex;
30227 var utils_5$2 = utils$3.toPosixSlashes;
30228 var utils_6$2 = utils$3.removeBackslashes;
30229 var utils_7$2 = utils$3.supportsLookbehinds;
30230 var utils_8$2 = utils$3.isWindows;
30231 var utils_9$2 = utils$3.escapeLast;
30232 var utils_10$1 = utils$3.removePrefix;
30233 var utils_11$1 = utils$3.wrapOutput;
30242 CHAR_BACKWARD_SLASH,
30245 CHAR_COMMA: CHAR_COMMA$2,
30248 CHAR_DOT: CHAR_DOT$1,
30251 CHAR_EXCLAMATION_MARK,
30254 CHAR_FORWARD_SLASH,
30257 CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1,
30260 CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1,
30263 CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1,
30266 CHAR_PLUS: CHAR_PLUS$1,
30269 CHAR_QUESTION_MARK,
30272 CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1,
30275 CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1,
30278 CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1
30283 const isPathSeparator = code => {
30284 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
30287 const depth = token => {
30288 if (token.isPrefix !== true) {
30289 token.depth = token.isGlobstar ? Infinity : 1;
30293 * Quickly scans a glob pattern and returns an object with a handful of
30294 * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
30295 * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
30298 * const pm = require('picomatch');
30299 * console.log(pm.scan('foo/bar/*.js'));
30300 * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
30302 * @param {String} `str`
30303 * @param {Object} `options`
30304 * @return {Object} Returns an object with tokens and regex source string.
30309 const scan = (input, options) => {
30310 const opts = options || {};
30311 const length = input.length - 1;
30312 const scanToEnd = opts.parts === true || opts.scanToEnd === true;
30313 const slashes = [];
30320 let isBrace = false;
30321 let isBracket = false;
30322 let isGlob = false;
30323 let isExtglob = false;
30324 let isGlobstar = false;
30325 let braceEscaped = false;
30326 let backslashes = false;
30327 let negated = false;
30328 let finished = false;
30338 const eos = () => index >= length;
30340 const peek = () => str.charCodeAt(index + 1);
30342 const advance = () => {
30344 return str.charCodeAt(++index);
30347 while (index < length) {
30351 if (code === CHAR_BACKWARD_SLASH) {
30352 backslashes = token.backslashes = true;
30355 if (code === CHAR_LEFT_CURLY_BRACE$1) {
30356 braceEscaped = true;
30362 if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
30365 while (eos() !== true && (code = advance())) {
30366 if (code === CHAR_BACKWARD_SLASH) {
30367 backslashes = token.backslashes = true;
30372 if (code === CHAR_LEFT_CURLY_BRACE$1) {
30377 if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {
30378 isBrace = token.isBrace = true;
30379 isGlob = token.isGlob = true;
30382 if (scanToEnd === true) {
30389 if (braceEscaped !== true && code === CHAR_COMMA$2) {
30390 isBrace = token.isBrace = true;
30391 isGlob = token.isGlob = true;
30394 if (scanToEnd === true) {
30401 if (code === CHAR_RIGHT_CURLY_BRACE$1) {
30404 if (braces === 0) {
30405 braceEscaped = false;
30406 isBrace = token.isBrace = true;
30413 if (scanToEnd === true) {
30420 if (code === CHAR_FORWARD_SLASH) {
30421 slashes.push(index);
30422 tokens.push(token);
30428 if (finished === true) continue;
30430 if (prev === CHAR_DOT$1 && index === start + 1) {
30435 lastIndex = index + 1;
30439 if (opts.noext !== true) {
30440 const isExtglobChar = code === CHAR_PLUS$1 || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
30442 if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {
30443 isGlob = token.isGlob = true;
30444 isExtglob = token.isExtglob = true;
30447 if (scanToEnd === true) {
30448 while (eos() !== true && (code = advance())) {
30449 if (code === CHAR_BACKWARD_SLASH) {
30450 backslashes = token.backslashes = true;
30455 if (code === CHAR_RIGHT_PARENTHESES$1) {
30456 isGlob = token.isGlob = true;
30469 if (code === CHAR_ASTERISK) {
30470 if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
30471 isGlob = token.isGlob = true;
30474 if (scanToEnd === true) {
30481 if (code === CHAR_QUESTION_MARK) {
30482 isGlob = token.isGlob = true;
30485 if (scanToEnd === true) {
30492 if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
30493 while (eos() !== true && (next = advance())) {
30494 if (next === CHAR_BACKWARD_SLASH) {
30495 backslashes = token.backslashes = true;
30500 if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
30501 isBracket = token.isBracket = true;
30502 isGlob = token.isGlob = true;
30505 if (scanToEnd === true) {
30514 if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
30515 negated = token.negated = true;
30520 if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {
30521 while (eos() !== true && (code = advance())) {
30522 if (code === CHAR_BACKWARD_SLASH) {
30523 backslashes = token.backslashes = true;
30528 if (code === CHAR_RIGHT_PARENTHESES$1) {
30529 isGlob = token.isGlob = true;
30532 if (scanToEnd === true) {
30541 if (isGlob === true) {
30544 if (scanToEnd === true) {
30552 if (opts.noext === true) {
30562 prefix = str.slice(0, start);
30563 str = str.slice(start);
30564 lastIndex -= start;
30567 if (base && isGlob === true && lastIndex > 0) {
30568 base = str.slice(0, lastIndex);
30569 glob = str.slice(lastIndex);
30570 } else if (isGlob === true) {
30577 if (base && base !== '' && base !== '/' && base !== str) {
30578 if (isPathSeparator(base.charCodeAt(base.length - 1))) {
30579 base = base.slice(0, -1);
30583 if (opts.unescape === true) {
30584 if (glob) glob = utils$3.removeBackslashes(glob);
30586 if (base && backslashes === true) {
30587 base = utils$3.removeBackslashes(base);
30605 if (opts.tokens === true) {
30606 state.maxDepth = 0;
30608 if (!isPathSeparator(code)) {
30609 tokens.push(token);
30612 state.tokens = tokens;
30615 if (opts.parts === true || opts.tokens === true) {
30618 for (let idx = 0; idx < slashes.length; idx++) {
30619 const n = prevIndex ? prevIndex + 1 : start;
30620 const i = slashes[idx];
30621 const value = input.slice(n, i);
30624 if (idx === 0 && start !== 0) {
30625 tokens[idx].isPrefix = true;
30626 tokens[idx].value = prefix;
30628 tokens[idx].value = value;
30631 depth(tokens[idx]);
30632 state.maxDepth += tokens[idx].depth;
30635 if (idx !== 0 || value !== '') {
30642 if (prevIndex && prevIndex + 1 < input.length) {
30643 const value = input.slice(prevIndex + 1);
30647 tokens[tokens.length - 1].value = value;
30648 depth(tokens[tokens.length - 1]);
30649 state.maxDepth += tokens[tokens.length - 1].depth;
30653 state.slashes = slashes;
30654 state.parts = parts;
30668 MAX_LENGTH: MAX_LENGTH$3,
30669 POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
30670 REGEX_NON_SPECIAL_CHARS,
30671 REGEX_SPECIAL_CHARS_BACKREF,
30678 const expandRange = (args, options) => {
30679 if (typeof options.expandRange === 'function') {
30680 return options.expandRange(...args, options);
30684 const value = `[${args.join('-')}]`;
30687 /* eslint-disable-next-line no-new */
30690 return args.map(v => utils$3.escapeRegex(v)).join('..');
30696 * Create the message for a syntax error
30700 const syntaxError = (type, char) => {
30701 return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
30704 * Parse the given input string.
30705 * @param {String} input
30706 * @param {Object} options
30711 const parse$4 = (input, options) => {
30712 if (typeof input !== 'string') {
30713 throw new TypeError('Expected a string');
30716 input = REPLACEMENTS[input] || input;
30717 const opts = Object.assign({}, options);
30718 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$3, opts.maxLength) : MAX_LENGTH$3;
30719 let len = input.length;
30722 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
30728 output: opts.prepend || ''
30730 const tokens = [bos];
30731 const capture = opts.capture ? '' : '?:';
30732 const win32 = utils$3.isWindows(options); // create constants based on platform, for windows or posix
30734 const PLATFORM_CHARS = constants$3.globChars(win32);
30735 const EXTGLOB_CHARS = constants$3.extglobChars(PLATFORM_CHARS);
30749 } = PLATFORM_CHARS;
30751 const globstar = opts => {
30752 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
30755 const nodot = opts.dot ? '' : NO_DOT;
30756 const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
30757 let star = opts.bash === true ? globstar(opts) : STAR;
30759 if (opts.capture) {
30760 star = `(${star})`;
30761 } // minimatch options support
30764 if (typeof opts.noext === 'boolean') {
30765 opts.noextglob = opts.noext;
30772 dot: opts.dot === true,
30785 input = utils$3.removePrefix(input, state);
30786 len = input.length;
30787 const extglobs = [];
30793 * Tokenizing helpers
30796 const eos = () => state.index === len - 1;
30798 const peek = state.peek = (n = 1) => input[state.index + n];
30800 const advance = state.advance = () => input[++state.index];
30802 const remaining = () => input.slice(state.index + 1);
30804 const consume = (value = '', num = 0) => {
30805 state.consumed += value;
30806 state.index += num;
30809 const append = token => {
30810 state.output += token.output != null ? token.output : token.value;
30811 consume(token.value);
30814 const negate = () => {
30817 while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
30823 if (count % 2 === 0) {
30827 state.negated = true;
30832 const increment = type => {
30837 const decrement = type => {
30842 * Push tokens onto the tokens array. This helper speeds up
30843 * tokenizing by 1) helping us avoid backtracking as much as possible,
30844 * and 2) helping us avoid creating extra tokens when consecutive
30845 * characters are plain text. This improves performance and simplifies
30850 const push = tok => {
30851 if (prev.type === 'globstar') {
30852 const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
30853 const isExtglob = tok.extglob === true || extglobs.length && (tok.type === 'pipe' || tok.type === 'paren');
30855 if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
30856 state.output = state.output.slice(0, -prev.output.length);
30857 prev.type = 'star';
30859 prev.output = star;
30860 state.output += prev.output;
30864 if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
30865 extglobs[extglobs.length - 1].inner += tok.value;
30868 if (tok.value || tok.output) append(tok);
30870 if (prev && prev.type === 'text' && tok.type === 'text') {
30871 prev.value += tok.value;
30872 prev.output = (prev.output || '') + tok.value;
30881 const extglobOpen = (type, value) => {
30882 const token = Object.assign({}, EXTGLOB_CHARS[value], {
30887 token.parens = state.parens;
30888 token.output = state.output;
30889 const output = (opts.capture ? '(' : '') + token.open;
30890 increment('parens');
30894 output: state.output ? '' : ONE_CHAR
30902 extglobs.push(token);
30905 const extglobClose = token => {
30906 let output = token.close + (opts.capture ? ')' : '');
30908 if (token.type === 'negate') {
30909 let extglobStar = star;
30911 if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
30912 extglobStar = globstar(opts);
30915 if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
30916 output = token.close = `)$))${extglobStar}`;
30919 if (token.prev.type === 'bos' && eos()) {
30920 state.negatedExtglob = true;
30930 decrement('parens');
30937 if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
30938 let backslashes = false;
30939 let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
30940 if (first === '\\') {
30941 backslashes = true;
30945 if (first === '?') {
30947 return esc + first + (rest ? QMARK.repeat(rest.length) : '');
30951 return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
30954 return QMARK.repeat(chars.length);
30957 if (first === '.') {
30958 return DOT_LITERAL.repeat(chars.length);
30961 if (first === '*') {
30963 return esc + first + (rest ? star : '');
30969 return esc ? m : `\\${m}`;
30972 if (backslashes === true) {
30973 if (opts.unescape === true) {
30974 output = output.replace(/\\/g, '');
30976 output = output.replace(/\\+/g, m => {
30977 return m.length % 2 === 0 ? '\\\\' : m ? '\\' : '';
30982 if (output === input && opts.contains === true) {
30983 state.output = input;
30987 state.output = utils$3.wrapOutput(output, state, options);
30991 * Tokenize input until we reach end-of-string
30998 if (value === '\u0000') {
31002 * Escaped characters
31006 if (value === '\\') {
31007 const next = peek();
31009 if (next === '/' && opts.bash !== true) {
31013 if (next === '.' || next === ';') {
31024 } // collapse slashes to reduce potential for exploits
31027 const match = /^\\+/.exec(remaining());
31030 if (match && match[0].length > 2) {
31031 slashes = match[0].length;
31032 state.index += slashes;
31034 if (slashes % 2 !== 0) {
31039 if (opts.unescape === true) {
31040 value = advance() || '';
31042 value += advance() || '';
31045 if (state.brackets === 0) {
31054 * If we're inside a regex character class, continue
31055 * until we reach the closing bracket.
31059 if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
31060 if (opts.posix !== false && value === ':') {
31061 const inner = prev.value.slice(1);
31063 if (inner.includes('[')) {
31066 if (inner.includes(':')) {
31067 const idx = prev.value.lastIndexOf('[');
31068 const pre = prev.value.slice(0, idx);
31069 const rest = prev.value.slice(idx + 2);
31070 const posix = POSIX_REGEX_SOURCE$1[rest];
31073 prev.value = pre + posix;
31074 state.backtrack = true;
31077 if (!bos.output && tokens.indexOf(prev) === 1) {
31078 bos.output = ONE_CHAR;
31087 if (value === '[' && peek() !== ':' || value === '-' && peek() === ']') {
31088 value = `\\${value}`;
31091 if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
31092 value = `\\${value}`;
31095 if (opts.posix === true && value === '!' && prev.value === '[') {
31099 prev.value += value;
31106 * If we're inside a quoted string, continue
31107 * until we reach the closing double quote.
31111 if (state.quotes === 1 && value !== '"') {
31112 value = utils$3.escapeRegex(value);
31113 prev.value += value;
31124 if (value === '"') {
31125 state.quotes = state.quotes === 1 ? 0 : 1;
31127 if (opts.keepQuotes === true) {
31141 if (value === '(') {
31142 increment('parens');
31150 if (value === ')') {
31151 if (state.parens === 0 && opts.strictBrackets === true) {
31152 throw new SyntaxError(syntaxError('opening', '('));
31155 const extglob = extglobs[extglobs.length - 1];
31157 if (extglob && state.parens === extglob.parens + 1) {
31158 extglobClose(extglobs.pop());
31165 output: state.parens ? ')' : '\\)'
31167 decrement('parens');
31175 if (value === '[') {
31176 if (opts.nobracket === true || !remaining().includes(']')) {
31177 if (opts.nobracket !== true && opts.strictBrackets === true) {
31178 throw new SyntaxError(syntaxError('closing', ']'));
31181 value = `\\${value}`;
31183 increment('brackets');
31193 if (value === ']') {
31194 if (opts.nobracket === true || prev && prev.type === 'bracket' && prev.value.length === 1) {
31198 output: `\\${value}`
31203 if (state.brackets === 0) {
31204 if (opts.strictBrackets === true) {
31205 throw new SyntaxError(syntaxError('opening', '['));
31211 output: `\\${value}`
31216 decrement('brackets');
31217 const prevValue = prev.value.slice(1);
31219 if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
31220 value = `/${value}`;
31223 prev.value += value;
31226 }); // when literal brackets are explicitly disabled
31227 // assume we should match with a regex character class
31229 if (opts.literalBrackets === false || utils$3.hasRegexChars(prevValue)) {
31233 const escaped = utils$3.escapeRegex(prev.value);
31234 state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled
31235 // assume we should escape the brackets to match literal characters
31237 if (opts.literalBrackets === true) {
31238 state.output += escaped;
31239 prev.value = escaped;
31241 } // when the user specifies nothing, try to match both
31244 prev.value = `(${capture}${escaped}|${prev.value})`;
31245 state.output += prev.value;
31253 if (value === '{' && opts.nobrace !== true) {
31254 increment('braces');
31259 outputIndex: state.output.length,
31260 tokensIndex: state.tokens.length
31267 if (value === '}') {
31268 const brace = braces[braces.length - 1];
31270 if (opts.nobrace === true || !brace) {
31281 if (brace.dots === true) {
31282 const arr = tokens.slice();
31285 for (let i = arr.length - 1; i >= 0; i--) {
31288 if (arr[i].type === 'brace') {
31292 if (arr[i].type !== 'dots') {
31293 range.unshift(arr[i].value);
31297 output = expandRange(range, opts);
31298 state.backtrack = true;
31301 if (brace.comma !== true && brace.dots !== true) {
31302 const out = state.output.slice(0, brace.outputIndex);
31303 const toks = state.tokens.slice(brace.tokensIndex);
31304 brace.value = brace.output = '\\{';
31305 value = output = `\\}`;
31306 state.output = out;
31308 for (const t of toks) {
31309 state.output += t.output || t.value;
31318 decrement('braces');
31327 if (value === '|') {
31328 if (extglobs.length > 0) {
31329 extglobs[extglobs.length - 1].conditions++;
31343 if (value === ',') {
31344 let output = value;
31345 const brace = braces[braces.length - 1];
31347 if (brace && stack[stack.length - 1] === 'braces') {
31348 brace.comma = true;
31364 if (value === '/') {
31365 // if the beginning of the glob is "./", advance the start
31366 // to the current index, and don't add the "./" characters
31367 // to the state. This greatly simplifies lookbehinds when
31368 // checking for BOS characters like "!" and "." (not "./")
31369 if (prev.type === 'dot' && state.index === state.start + 1) {
31370 state.start = state.index + 1;
31371 state.consumed = '';
31374 prev = bos; // reset "prev" to the first token
31382 output: SLASH_LITERAL
31391 if (value === '.') {
31392 if (state.braces > 0 && prev.type === 'dot') {
31393 if (prev.value === '.') prev.output = DOT_LITERAL;
31394 const brace = braces[braces.length - 1];
31395 prev.type = 'dots';
31396 prev.output += value;
31397 prev.value += value;
31402 if (state.braces + state.parens === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
31406 output: DOT_LITERAL
31414 output: DOT_LITERAL
31423 if (value === '?') {
31424 const isGroup = prev && prev.value === '(';
31426 if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
31427 extglobOpen('qmark', value);
31431 if (prev && prev.type === 'paren') {
31432 const next = peek();
31433 let output = value;
31435 if (next === '<' && !utils$3.supportsLookbehinds()) {
31436 throw new Error('Node.js v10 or higher is required for regex lookbehinds');
31439 if (prev.value === '(' && !/[!=<:]/.test(next) || next === '<' && !/<([!=]|\w+>)/.test(remaining())) {
31440 output = `\\${value}`;
31451 if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
31455 output: QMARK_NO_DOT
31472 if (value === '!') {
31473 if (opts.noextglob !== true && peek() === '(') {
31474 if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
31475 extglobOpen('negate', value);
31480 if (opts.nonegate !== true && state.index === 0) {
31490 if (value === '+') {
31491 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
31492 extglobOpen('plus', value);
31496 if (prev && prev.value === '(' || opts.regex === false) {
31500 output: PLUS_LITERAL
31505 if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace') || state.parens > 0) {
31515 value: PLUS_LITERAL
31524 if (value === '@') {
31525 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
31546 if (value !== '*') {
31547 if (value === '$' || value === '^') {
31548 value = `\\${value}`;
31551 const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
31555 state.index += match[0].length;
31569 if (prev && (prev.type === 'globstar' || prev.star === true)) {
31570 prev.type = 'star';
31572 prev.value += value;
31573 prev.output = star;
31574 state.backtrack = true;
31575 state.globstar = true;
31580 let rest = remaining();
31582 if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
31583 extglobOpen('star', value);
31587 if (prev.type === 'star') {
31588 if (opts.noglobstar === true) {
31593 const prior = prev.prev;
31594 const before = prior.prev;
31595 const isStart = prior.type === 'slash' || prior.type === 'bos';
31596 const afterStar = before && (before.type === 'star' || before.type === 'globstar');
31598 if (opts.bash === true && (!isStart || rest[0] && rest[0] !== '/')) {
31607 const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
31608 const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
31610 if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
31617 } // strip consecutive `/**/`
31620 while (rest.slice(0, 3) === '/**') {
31621 const after = input[state.index + 4];
31623 if (after && after !== '/') {
31627 rest = rest.slice(3);
31631 if (prior.type === 'bos' && eos()) {
31632 prev.type = 'globstar';
31633 prev.value += value;
31634 prev.output = globstar(opts);
31635 state.output = prev.output;
31636 state.globstar = true;
31641 if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
31642 state.output = state.output.slice(0, -(prior.output + prev.output).length);
31643 prior.output = `(?:${prior.output}`;
31644 prev.type = 'globstar';
31645 prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
31646 prev.value += value;
31647 state.globstar = true;
31648 state.output += prior.output + prev.output;
31653 if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
31654 const end = rest[1] !== void 0 ? '|$' : '';
31655 state.output = state.output.slice(0, -(prior.output + prev.output).length);
31656 prior.output = `(?:${prior.output}`;
31657 prev.type = 'globstar';
31658 prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
31659 prev.value += value;
31660 state.output += prior.output + prev.output;
31661 state.globstar = true;
31662 consume(value + advance());
31671 if (prior.type === 'bos' && rest[0] === '/') {
31672 prev.type = 'globstar';
31673 prev.value += value;
31674 prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
31675 state.output = prev.output;
31676 state.globstar = true;
31677 consume(value + advance());
31684 } // remove single star from output
31687 state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar
31689 prev.type = 'globstar';
31690 prev.output = globstar(opts);
31691 prev.value += value; // reset output with globstar
31693 state.output += prev.output;
31694 state.globstar = true;
31705 if (opts.bash === true) {
31706 token.output = '.*?';
31708 if (prev.type === 'bos' || prev.type === 'slash') {
31709 token.output = nodot + token.output;
31716 if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
31717 token.output = value;
31722 if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
31723 if (prev.type === 'dot') {
31724 state.output += NO_DOT_SLASH;
31725 prev.output += NO_DOT_SLASH;
31726 } else if (opts.dot === true) {
31727 state.output += NO_DOTS_SLASH;
31728 prev.output += NO_DOTS_SLASH;
31730 state.output += nodot;
31731 prev.output += nodot;
31734 if (peek() !== '*') {
31735 state.output += ONE_CHAR;
31736 prev.output += ONE_CHAR;
31743 while (state.brackets > 0) {
31744 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
31745 state.output = utils$3.escapeLast(state.output, '[');
31746 decrement('brackets');
31749 while (state.parens > 0) {
31750 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
31751 state.output = utils$3.escapeLast(state.output, '(');
31752 decrement('parens');
31755 while (state.braces > 0) {
31756 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
31757 state.output = utils$3.escapeLast(state.output, '{');
31758 decrement('braces');
31761 if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
31763 type: 'maybe_slash',
31765 output: `${SLASH_LITERAL}?`
31767 } // rebuild the output if we had to backtrack at any point
31770 if (state.backtrack === true) {
31773 for (const token of state.tokens) {
31774 state.output += token.output != null ? token.output : token.value;
31776 if (token.suffix) {
31777 state.output += token.suffix;
31785 * Fast paths for creating regular expressions for common glob patterns.
31786 * This can significantly speed up processing and has very little downside
31787 * impact when none of the fast paths match.
31791 parse$4.fastpaths = (input, options) => {
31792 const opts = Object.assign({}, options);
31793 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$3, opts.maxLength) : MAX_LENGTH$3;
31794 const len = input.length;
31797 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
31800 input = REPLACEMENTS[input] || input;
31801 const win32 = utils$3.isWindows(options); // create constants based on platform, for windows or posix
31813 } = constants$3.globChars(win32);
31814 const nodot = opts.dot ? NO_DOTS : NO_DOT;
31815 const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
31816 const capture = opts.capture ? '' : '?:';
31821 let star = opts.bash === true ? '.*?' : STAR;
31823 if (opts.capture) {
31824 star = `(${star})`;
31827 const globstar = opts => {
31828 if (opts.noglobstar === true) return star;
31829 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
31832 const create = str => {
31835 return `${nodot}${ONE_CHAR}${star}`;
31838 return `${DOT_LITERAL}${ONE_CHAR}${star}`;
31841 return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
31844 return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
31847 return nodot + globstar(opts);
31850 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
31853 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
31856 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
31860 const match = /^(.*?)\.(\w+)$/.exec(str);
31861 if (!match) return;
31862 const source = create(match[1]);
31863 if (!source) return;
31864 return source + DOT_LITERAL + match[2];
31869 const output = utils$3.removePrefix(input, state);
31870 let source = create(output);
31872 if (source && opts.strictSlashes !== true) {
31873 source += `${SLASH_LITERAL}?`;
31879 var parse_1$1 = parse$4;
31881 const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val);
31883 * Creates a matcher function from one or more glob patterns. The
31884 * returned function takes a string to match as its first argument,
31885 * and returns true if the string is a match. The returned matcher
31886 * function also takes a boolean as the second argument that, when true,
31887 * returns an object with additional information.
31890 * const picomatch = require('picomatch');
31891 * // picomatch(glob[, options]);
31893 * const isMatch = picomatch('*.!(*a)');
31894 * console.log(isMatch('a.a')); //=> false
31895 * console.log(isMatch('a.b')); //=> true
31898 * @param {String|Array} `globs` One or more glob patterns.
31899 * @param {Object=} `options`
31900 * @return {Function=} Returns a matcher function.
31905 const picomatch = (glob, options, returnState = false) => {
31906 if (Array.isArray(glob)) {
31907 const fns = glob.map(input => picomatch(input, options, returnState));
31909 const arrayMatcher = str => {
31910 for (const isMatch of fns) {
31911 const state = isMatch(str);
31912 if (state) return state;
31918 return arrayMatcher;
31921 const isState = isObject$2(glob) && glob.tokens && glob.input;
31923 if (glob === '' || typeof glob !== 'string' && !isState) {
31924 throw new TypeError('Expected pattern to be a non-empty string');
31927 const opts = options || {};
31928 const posix = utils$3.isWindows(options);
31929 const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true);
31930 const state = regex.state;
31931 delete regex.state;
31933 let isIgnored = () => false;
31936 const ignoreOpts = Object.assign({}, options, {
31941 isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
31944 const matcher = (input, returnObject = false) => {
31949 } = picomatch.test(input, regex, options, {
31964 if (typeof opts.onResult === 'function') {
31965 opts.onResult(result);
31968 if (isMatch === false) {
31969 result.isMatch = false;
31970 return returnObject ? result : false;
31973 if (isIgnored(input)) {
31974 if (typeof opts.onIgnore === 'function') {
31975 opts.onIgnore(result);
31978 result.isMatch = false;
31979 return returnObject ? result : false;
31982 if (typeof opts.onMatch === 'function') {
31983 opts.onMatch(result);
31986 return returnObject ? result : true;
31990 matcher.state = state;
31996 * Test `input` with the given `regex`. This is used by the main
31997 * `picomatch()` function to test the input string.
32000 * const picomatch = require('picomatch');
32001 * // picomatch.test(input, regex[, options]);
32003 * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
32004 * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
32006 * @param {String} `input` String to test.
32007 * @param {RegExp} `regex`
32008 * @return {Object} Returns an object with matching info.
32013 picomatch.test = (input, regex, options, {
32017 if (typeof input !== 'string') {
32018 throw new TypeError('Expected input to be a string');
32021 if (input === '') {
32028 const opts = options || {};
32029 const format = opts.format || (posix ? utils$3.toPosixSlashes : null);
32030 let match = input === glob;
32031 let output = match && format ? format(input) : input;
32033 if (match === false) {
32034 output = format ? format(input) : input;
32035 match = output === glob;
32038 if (match === false || opts.capture === true) {
32039 if (opts.matchBase === true || opts.basename === true) {
32040 match = picomatch.matchBase(input, regex, options, posix);
32042 match = regex.exec(output);
32047 isMatch: Boolean(match),
32053 * Match the basename of a filepath.
32056 * const picomatch = require('picomatch');
32057 * // picomatch.matchBase(input, glob[, options]);
32058 * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
32060 * @param {String} `input` String to test.
32061 * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
32062 * @return {Boolean}
32067 picomatch.matchBase = (input, glob, options, posix = utils$3.isWindows(options)) => {
32068 const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
32069 return regex.test(path$2.basename(input));
32072 * Returns true if **any** of the given glob `patterns` match the specified `string`.
32075 * const picomatch = require('picomatch');
32076 * // picomatch.isMatch(string, patterns[, options]);
32078 * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
32079 * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
32081 * @param {String|Array} str The string to test.
32082 * @param {String|Array} patterns One or more glob patterns to use for matching.
32083 * @param {Object} [options] See available [options](#options).
32084 * @return {Boolean} Returns true if any patterns match `str`
32089 picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
32091 * Parse a glob pattern to create the source string for a regular
32095 * const picomatch = require('picomatch');
32096 * const result = picomatch.parse(pattern[, options]);
32098 * @param {String} `pattern`
32099 * @param {Object} `options`
32100 * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
32105 picomatch.parse = (pattern, options) => {
32106 if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
32107 return parse_1$1(pattern, Object.assign({}, options, {
32112 * Scan a glob pattern to separate the pattern into segments.
32115 * const picomatch = require('picomatch');
32116 * // picomatch.scan(input[, options]);
32118 * const result = picomatch.scan('!./foo/*.js');
32119 * console.log(result);
32121 * input: '!./foo/*.js',
32126 * isBracket: false,
32128 * isExtglob: false,
32129 * isGlobstar: false,
32132 * @param {String} `input` Glob pattern to scan.
32133 * @param {Object} `options`
32134 * @return {Object} Returns an object with
32139 picomatch.scan = (input, options) => scan_1(input, options);
32141 * Create a regular expression from a glob pattern.
32144 * const picomatch = require('picomatch');
32145 * // picomatch.makeRe(input[, options]);
32147 * console.log(picomatch.makeRe('*.js'));
32148 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
32150 * @param {String} `input` A glob pattern to convert to regex.
32151 * @param {Object} `options`
32152 * @return {RegExp} Returns a regex created from the given pattern.
32157 picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => {
32158 if (returnOutput === true) {
32159 return parsed.output;
32162 const opts = options || {};
32163 const prepend = opts.contains ? '' : '^';
32164 const append = opts.contains ? '' : '$';
32165 let source = `${prepend}(?:${parsed.output})${append}`;
32167 if (parsed && parsed.negated === true) {
32168 source = `^(?!${source}).*$`;
32171 const regex = picomatch.toRegex(source, options);
32173 if (returnState === true) {
32174 regex.state = parsed;
32180 picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
32181 if (!input || typeof input !== 'string') {
32182 throw new TypeError('Expected a non-empty string');
32185 const opts = options || {};
32193 if (input.startsWith('./')) {
32194 input = input.slice(2);
32195 prefix = parsed.prefix = './';
32198 if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
32199 output = parse_1$1.fastpaths(input, options);
32202 if (output === undefined) {
32203 parsed = parse_1$1(input, options);
32204 parsed.prefix = prefix + (parsed.prefix || '');
32206 parsed.output = output;
32209 return picomatch.compileRe(parsed, options, returnOutput, returnState);
32212 * Create a regular expression from the given regex source string.
32215 * const picomatch = require('picomatch');
32216 * // picomatch.toRegex(source[, options]);
32218 * const { output } = picomatch.parse('*.js');
32219 * console.log(picomatch.toRegex(output));
32220 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
32222 * @param {String} `source` Regular expression source string.
32223 * @param {Object} `options`
32229 picomatch.toRegex = (source, options) => {
32231 const opts = options || {};
32232 return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
32234 if (options && options.debug === true) throw err;
32239 * Picomatch constants.
32244 picomatch.constants = constants$3;
32246 * Expose "picomatch"
32249 var picomatch_1 = picomatch;
32251 var picomatch$1 = picomatch_1;
32253 const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');
32255 * Returns an array of strings that match one or more glob patterns.
32258 * const mm = require('micromatch');
32259 * // mm(list, patterns[, options]);
32261 * console.log(mm(['a.js', 'a.txt'], ['*.js']));
32264 * @param {String|Array<string>} list List of strings to match.
32265 * @param {String|Array<string>} patterns One or more glob patterns to use for matching.
32266 * @param {Object} options See available [options](#options)
32267 * @return {Array} Returns an array of matches
32273 const micromatch = (list, patterns, options) => {
32274 patterns = [].concat(patterns);
32275 list = [].concat(list);
32276 let omit = new Set();
32277 let keep = new Set();
32278 let items = new Set();
32281 let onResult = state => {
32282 items.add(state.output);
32284 if (options && options.onResult) {
32285 options.onResult(state);
32289 for (let i = 0; i < patterns.length; i++) {
32290 let isMatch = picomatch$1(String(patterns[i]), Object.assign({}, options, {
32293 let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
32294 if (negated) negatives++;
32296 for (let item of list) {
32297 let matched = isMatch(item, true);
32298 let match = negated ? !matched.isMatch : matched.isMatch;
32299 if (!match) continue;
32302 omit.add(matched.output);
32304 omit.delete(matched.output);
32305 keep.add(matched.output);
32310 let result = negatives === patterns.length ? [...items] : [...keep];
32311 let matches = result.filter(item => !omit.has(item));
32313 if (options && matches.length === 0) {
32314 if (options.failglob === true) {
32315 throw new Error(`No matches found for "${patterns.join(', ')}"`);
32318 if (options.nonull === true || options.nullglob === true) {
32319 return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
32326 * Backwards compatibility
32330 micromatch.match = micromatch;
32332 * Returns a matcher function from the given glob `pattern` and `options`.
32333 * The returned function takes a string to match as its only argument and returns
32334 * true if the string is a match.
32337 * const mm = require('micromatch');
32338 * // mm.matcher(pattern[, options]);
32340 * const isMatch = mm.matcher('*.!(*a)');
32341 * console.log(isMatch('a.a')); //=> false
32342 * console.log(isMatch('a.b')); //=> true
32344 * @param {String} `pattern` Glob pattern
32345 * @param {Object} `options`
32346 * @return {Function} Returns a matcher function.
32350 micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);
32352 * Returns true if **any** of the given glob `patterns` match the specified `string`.
32355 * const mm = require('micromatch');
32356 * // mm.isMatch(string, patterns[, options]);
32358 * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
32359 * console.log(mm.isMatch('a.a', 'b.*')); //=> false
32361 * @param {String} str The string to test.
32362 * @param {String|Array} patterns One or more glob patterns to use for matching.
32363 * @param {Object} [options] See available [options](#options).
32364 * @return {Boolean} Returns true if any patterns match `str`
32369 micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
32371 * Backwards compatibility
32375 micromatch.any = micromatch.isMatch;
32377 * Returns a list of strings that _**do not match any**_ of the given `patterns`.
32380 * const mm = require('micromatch');
32381 * // mm.not(list, patterns[, options]);
32383 * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
32384 * //=> ['b.b', 'c.c']
32386 * @param {Array} `list` Array of strings to match.
32387 * @param {String|Array} `patterns` One or more glob pattern to use for matching.
32388 * @param {Object} `options` See available [options](#options) for changing how matches are performed
32389 * @return {Array} Returns an array of strings that **do not match** the given patterns.
32393 micromatch.not = (list, patterns, options = {}) => {
32394 patterns = [].concat(patterns).map(String);
32395 let result = new Set();
32398 let onResult = state => {
32399 if (options.onResult) options.onResult(state);
32400 items.push(state.output);
32403 let matches = micromatch(list, patterns, Object.assign({}, options, {
32407 for (let item of items) {
32408 if (!matches.includes(item)) {
32413 return [...result];
32416 * Returns true if the given `string` contains the given pattern. Similar
32417 * to [.isMatch](#isMatch) but the pattern can match any part of the string.
32420 * var mm = require('micromatch');
32421 * // mm.contains(string, pattern[, options]);
32423 * console.log(mm.contains('aa/bb/cc', '*b'));
32425 * console.log(mm.contains('aa/bb/cc', '*d'));
32428 * @param {String} `str` The string to match.
32429 * @param {String|Array} `patterns` Glob pattern to use for matching.
32430 * @param {Object} `options` See available [options](#options) for changing how matches are performed
32431 * @return {Boolean} Returns true if the patter matches any part of `str`.
32436 micromatch.contains = (str, pattern, options) => {
32437 if (typeof str !== 'string') {
32438 throw new TypeError(`Expected a string: "${util$4.inspect(str)}"`);
32441 if (Array.isArray(pattern)) {
32442 return pattern.some(p => micromatch.contains(str, p, options));
32445 if (typeof pattern === 'string') {
32446 if (isEmptyString(str) || isEmptyString(pattern)) {
32450 if (str.includes(pattern) || str.startsWith('./') && str.slice(2).includes(pattern)) {
32455 return micromatch.isMatch(str, pattern, Object.assign({}, options, {
32460 * Filter the keys of the given object with the given `glob` pattern
32461 * and `options`. Does not attempt to match nested keys. If you need this feature,
32462 * use [glob-object][] instead.
32465 * const mm = require('micromatch');
32466 * // mm.matchKeys(object, patterns[, options]);
32468 * const obj = { aa: 'a', ab: 'b', ac: 'c' };
32469 * console.log(mm.matchKeys(obj, '*b'));
32472 * @param {Object} `object` The object with keys to filter.
32473 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
32474 * @param {Object} `options` See available [options](#options) for changing how matches are performed
32475 * @return {Object} Returns an object with only keys that match the given patterns.
32480 micromatch.matchKeys = (obj, patterns, options) => {
32481 if (!utils$3.isObject(obj)) {
32482 throw new TypeError('Expected the first argument to be an object');
32485 let keys = micromatch(Object.keys(obj), patterns, options);
32488 for (let key of keys) res[key] = obj[key];
32493 * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
32496 * const mm = require('micromatch');
32497 * // mm.some(list, patterns[, options]);
32499 * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
32501 * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
32504 * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
32505 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
32506 * @param {Object} `options` See available [options](#options) for changing how matches are performed
32507 * @return {Boolean} Returns true if any patterns match `str`
32512 micromatch.some = (list, patterns, options) => {
32513 let items = [].concat(list);
32515 for (let pattern of [].concat(patterns)) {
32516 let isMatch = picomatch$1(String(pattern), options);
32518 if (items.some(item => isMatch(item))) {
32526 * Returns true if every string in the given `list` matches
32527 * any of the given glob `patterns`.
32530 * const mm = require('micromatch');
32531 * // mm.every(list, patterns[, options]);
32533 * console.log(mm.every('foo.js', ['foo.js']));
32535 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
32537 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
32539 * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
32542 * @param {String|Array} `list` The string or array of strings to test.
32543 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
32544 * @param {Object} `options` See available [options](#options) for changing how matches are performed
32545 * @return {Boolean} Returns true if any patterns match `str`
32550 micromatch.every = (list, patterns, options) => {
32551 let items = [].concat(list);
32553 for (let pattern of [].concat(patterns)) {
32554 let isMatch = picomatch$1(String(pattern), options);
32556 if (!items.every(item => isMatch(item))) {
32564 * Returns true if **all** of the given `patterns` match
32565 * the specified string.
32568 * const mm = require('micromatch');
32569 * // mm.all(string, patterns[, options]);
32571 * console.log(mm.all('foo.js', ['foo.js']));
32574 * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
32577 * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
32580 * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
32583 * @param {String|Array} `str` The string to test.
32584 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
32585 * @param {Object} `options` See available [options](#options) for changing how matches are performed
32586 * @return {Boolean} Returns true if any patterns match `str`
32591 micromatch.all = (str, patterns, options) => {
32592 if (typeof str !== 'string') {
32593 throw new TypeError(`Expected a string: "${util$4.inspect(str)}"`);
32596 return [].concat(patterns).every(p => picomatch$1(p, options)(str));
32599 * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
32602 * const mm = require('micromatch');
32603 * // mm.capture(pattern, string[, options]);
32605 * console.log(mm.capture('test/*.js', 'test/foo.js'));
32607 * console.log(mm.capture('test/*.js', 'foo/bar.css'));
32610 * @param {String} `glob` Glob pattern to use for matching.
32611 * @param {String} `input` String to match
32612 * @param {Object} `options` See available [options](#options) for changing how matches are performed
32613 * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
32618 micromatch.capture = (glob, input, options) => {
32619 let posix = utils$3.isWindows(options);
32620 let regex = picomatch$1.makeRe(String(glob), Object.assign({}, options, {
32623 let match = regex.exec(posix ? utils$3.toPosixSlashes(input) : input);
32626 return match.slice(1).map(v => v === void 0 ? '' : v);
32630 * Create a regular expression from the given glob `pattern`.
32633 * const mm = require('micromatch');
32634 * // mm.makeRe(pattern[, options]);
32636 * console.log(mm.makeRe('*.js'));
32637 * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
32639 * @param {String} `pattern` A glob pattern to convert to regex.
32640 * @param {Object} `options`
32641 * @return {RegExp} Returns a regex created from the given pattern.
32646 micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);
32648 * Scan a glob pattern to separate the pattern into segments. Used
32649 * by the [split](#split) method.
32652 * const mm = require('micromatch');
32653 * const state = mm.scan(pattern[, options]);
32655 * @param {String} `pattern`
32656 * @param {Object} `options`
32657 * @return {Object} Returns an object with
32662 micromatch.scan = (...args) => picomatch$1.scan(...args);
32664 * Parse a glob pattern to create the source string for a regular
32668 * const mm = require('micromatch');
32669 * const state = mm(pattern[, options]);
32671 * @param {String} `glob`
32672 * @param {Object} `options`
32673 * @return {Object} Returns an object with useful properties and output to be used as regex source string.
32678 micromatch.parse = (patterns, options) => {
32681 for (let pattern of [].concat(patterns || [])) {
32682 for (let str of braces_1(String(pattern), options)) {
32683 res.push(picomatch$1.parse(str, options));
32690 * Process the given brace `pattern`.
32693 * const { braces } = require('micromatch');
32694 * console.log(braces('foo/{a,b,c}/bar'));
32695 * //=> [ 'foo/(a|b|c)/bar' ]
32697 * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
32698 * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
32700 * @param {String} `pattern` String with brace pattern to process.
32701 * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
32707 micromatch.braces = (pattern, options) => {
32708 if (typeof pattern !== 'string') throw new TypeError('Expected a string');
32710 if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) {
32714 return braces_1(pattern, options);
32721 micromatch.braceExpand = (pattern, options) => {
32722 if (typeof pattern !== 'string') throw new TypeError('Expected a string');
32723 return micromatch.braces(pattern, Object.assign({}, options, {
32728 * Expose micromatch
32732 var micromatch_1 = micromatch;
32734 var pattern = createCommonjsModule(function (module, exports) {
32736 Object.defineProperty(exports, "__esModule", {
32739 const GLOBSTAR = '**';
32740 const ESCAPE_SYMBOL = '\\';
32741 const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
32742 const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/;
32743 const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/;
32744 const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/;
32745 const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/;
32747 function isStaticPattern(pattern, options = {}) {
32748 return !isDynamicPattern(pattern, options);
32751 exports.isStaticPattern = isStaticPattern;
32753 function isDynamicPattern(pattern, options = {}) {
32755 * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
\r
32756 * filepath directly (without read directory).
\r
32758 if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
32762 if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
32766 if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
32770 if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) {
32777 exports.isDynamicPattern = isDynamicPattern;
32779 function convertToPositivePattern(pattern) {
32780 return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
32783 exports.convertToPositivePattern = convertToPositivePattern;
32785 function convertToNegativePattern(pattern) {
32786 return '!' + pattern;
32789 exports.convertToNegativePattern = convertToNegativePattern;
32791 function isNegativePattern(pattern) {
32792 return pattern.startsWith('!') && pattern[1] !== '(';
32795 exports.isNegativePattern = isNegativePattern;
32797 function isPositivePattern(pattern) {
32798 return !isNegativePattern(pattern);
32801 exports.isPositivePattern = isPositivePattern;
32803 function getNegativePatterns(patterns) {
32804 return patterns.filter(isNegativePattern);
32807 exports.getNegativePatterns = getNegativePatterns;
32809 function getPositivePatterns(patterns) {
32810 return patterns.filter(isPositivePattern);
32813 exports.getPositivePatterns = getPositivePatterns;
32815 function getBaseDirectory(pattern) {
32816 return globParent(pattern, {
32817 flipBackslashes: false
32821 exports.getBaseDirectory = getBaseDirectory;
32823 function hasGlobStar(pattern) {
32824 return pattern.includes(GLOBSTAR);
32827 exports.hasGlobStar = hasGlobStar;
32829 function endsWithSlashGlobStar(pattern) {
32830 return pattern.endsWith('/' + GLOBSTAR);
32833 exports.endsWithSlashGlobStar = endsWithSlashGlobStar;
32835 function isAffectDepthOfReadingPattern(pattern) {
32836 const basename = path$2.basename(pattern);
32837 return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
32840 exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
32842 function expandPatternsWithBraceExpansion(patterns) {
32843 return patterns.reduce((collection, pattern) => {
32844 return collection.concat(expandBraceExpansion(pattern));
32848 exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
32850 function expandBraceExpansion(pattern) {
32851 return micromatch_1.braces(pattern, {
32857 exports.expandBraceExpansion = expandBraceExpansion;
32859 function getPatternParts(pattern, options) {
32860 const info = picomatch$1.scan(pattern, Object.assign(Object.assign({}, options), {
32862 })); // See micromatch/picomatch#58 for more details
32864 if (info.parts.length === 0) {
32871 exports.getPatternParts = getPatternParts;
32873 function makeRe(pattern, options) {
32874 return micromatch_1.makeRe(pattern, options);
32877 exports.makeRe = makeRe;
32879 function convertPatternsToRe(patterns, options) {
32880 return patterns.map(pattern => makeRe(pattern, options));
32883 exports.convertPatternsToRe = convertPatternsToRe;
32885 function matchAny(entry, patternsRe) {
32886 return patternsRe.some(patternRe => patternRe.test(entry));
32889 exports.matchAny = matchAny;
32891 unwrapExports(pattern);
32892 var pattern_1 = pattern.isStaticPattern;
32893 var pattern_2 = pattern.isDynamicPattern;
32894 var pattern_3 = pattern.convertToPositivePattern;
32895 var pattern_4 = pattern.convertToNegativePattern;
32896 var pattern_5 = pattern.isNegativePattern;
32897 var pattern_6 = pattern.isPositivePattern;
32898 var pattern_7 = pattern.getNegativePatterns;
32899 var pattern_8 = pattern.getPositivePatterns;
32900 var pattern_9 = pattern.getBaseDirectory;
32901 var pattern_10 = pattern.hasGlobStar;
32902 var pattern_11 = pattern.endsWithSlashGlobStar;
32903 var pattern_12 = pattern.isAffectDepthOfReadingPattern;
32904 var pattern_13 = pattern.expandPatternsWithBraceExpansion;
32905 var pattern_14 = pattern.expandBraceExpansion;
32906 var pattern_15 = pattern.getPatternParts;
32907 var pattern_16 = pattern.makeRe;
32908 var pattern_17 = pattern.convertPatternsToRe;
32909 var pattern_18 = pattern.matchAny;
32911 var stream$1 = createCommonjsModule(function (module, exports) {
32913 Object.defineProperty(exports, "__esModule", {
32917 function merge(streams) {
32918 const mergedStream = merge2_1(streams);
32919 streams.forEach(stream => {
32920 stream.once('error', error => mergedStream.emit('error', error));
32922 mergedStream.once('close', () => propagateCloseEventToSources(streams));
32923 mergedStream.once('end', () => propagateCloseEventToSources(streams));
32924 return mergedStream;
32927 exports.merge = merge;
32929 function propagateCloseEventToSources(streams) {
32930 streams.forEach(stream => stream.emit('close'));
32933 unwrapExports(stream$1);
32934 var stream_1 = stream$1.merge;
32936 var string$1 = createCommonjsModule(function (module, exports) {
32938 Object.defineProperty(exports, "__esModule", {
32942 function isString(input) {
32943 return typeof input === 'string';
32946 exports.isString = isString;
32948 function isEmpty(input) {
32949 return input === '';
32952 exports.isEmpty = isEmpty;
32954 unwrapExports(string$1);
32955 var string_1$1 = string$1.isString;
32956 var string_2 = string$1.isEmpty;
32958 var utils$4 = createCommonjsModule(function (module, exports) {
32960 Object.defineProperty(exports, "__esModule", {
32963 exports.array = array$2;
32964 exports.errno = errno;
32966 exports.path = path_1;
32967 exports.pattern = pattern;
32968 exports.stream = stream$1;
32969 exports.string = string$1;
32971 unwrapExports(utils$4);
32972 var utils_1$4 = utils$4.array;
32973 var utils_2$4 = utils$4.errno;
32974 var utils_3$4 = utils$4.fs;
32975 var utils_4$3 = utils$4.path;
32976 var utils_5$3 = utils$4.pattern;
32977 var utils_6$3 = utils$4.stream;
32978 var utils_7$3 = utils$4.string;
32980 var tasks = createCommonjsModule(function (module, exports) {
32982 Object.defineProperty(exports, "__esModule", {
32986 function generate(patterns, settings) {
32987 const positivePatterns = getPositivePatterns(patterns);
32988 const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
32989 const staticPatterns = positivePatterns.filter(pattern => utils$4.pattern.isStaticPattern(pattern, settings));
32990 const dynamicPatterns = positivePatterns.filter(pattern => utils$4.pattern.isDynamicPattern(pattern, settings));
32991 const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns,
32994 const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns,
32997 return staticTasks.concat(dynamicTasks);
33000 exports.generate = generate;
33002 function convertPatternsToTasks(positive, negative, dynamic) {
33003 const positivePatternsGroup = groupPatternsByBaseDirectory(positive); // When we have a global group – there is no reason to divide the patterns into independent tasks.
33004 // In this case, the global task covers the rest.
33006 if ('.' in positivePatternsGroup) {
33007 const task = convertPatternGroupToTask('.', positive, negative, dynamic);
33011 return convertPatternGroupsToTasks(positivePatternsGroup, negative, dynamic);
33014 exports.convertPatternsToTasks = convertPatternsToTasks;
33016 function getPositivePatterns(patterns) {
33017 return utils$4.pattern.getPositivePatterns(patterns);
33020 exports.getPositivePatterns = getPositivePatterns;
33022 function getNegativePatternsAsPositive(patterns, ignore) {
33023 const negative = utils$4.pattern.getNegativePatterns(patterns).concat(ignore);
33024 const positive = negative.map(utils$4.pattern.convertToPositivePattern);
33028 exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
33030 function groupPatternsByBaseDirectory(patterns) {
33032 return patterns.reduce((collection, pattern) => {
33033 const base = utils$4.pattern.getBaseDirectory(pattern);
33035 if (base in collection) {
33036 collection[base].push(pattern);
33038 collection[base] = [pattern];
33045 exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
33047 function convertPatternGroupsToTasks(positive, negative, dynamic) {
33048 return Object.keys(positive).map(base => {
33049 return convertPatternGroupToTask(base, positive[base], negative, dynamic);
33053 exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
33055 function convertPatternGroupToTask(base, positive, negative, dynamic) {
33061 patterns: [].concat(positive, negative.map(utils$4.pattern.convertToNegativePattern))
33065 exports.convertPatternGroupToTask = convertPatternGroupToTask;
33067 unwrapExports(tasks);
33068 var tasks_1 = tasks.generate;
33069 var tasks_2 = tasks.convertPatternsToTasks;
33070 var tasks_3 = tasks.getPositivePatterns;
33071 var tasks_4 = tasks.getNegativePatternsAsPositive;
33072 var tasks_5 = tasks.groupPatternsByBaseDirectory;
33073 var tasks_6 = tasks.convertPatternGroupsToTasks;
33074 var tasks_7 = tasks.convertPatternGroupToTask;
33076 var async$1 = createCommonjsModule(function (module, exports) {
33078 Object.defineProperty(exports, "__esModule", {
33082 function read(path, settings, callback) {
33083 settings.fs.lstat(path, (lstatError, lstat) => {
33084 if (lstatError !== null) {
33085 return callFailureCallback(callback, lstatError);
33088 if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
33089 return callSuccessCallback(callback, lstat);
33092 settings.fs.stat(path, (statError, stat) => {
33093 if (statError !== null) {
33094 if (settings.throwErrorOnBrokenSymbolicLink) {
33095 return callFailureCallback(callback, statError);
33098 return callSuccessCallback(callback, lstat);
33101 if (settings.markSymbolicLink) {
33102 stat.isSymbolicLink = () => true;
33105 callSuccessCallback(callback, stat);
33110 exports.read = read;
33112 function callFailureCallback(callback, error) {
33116 function callSuccessCallback(callback, result) {
33117 callback(null, result);
33120 unwrapExports(async$1);
33121 var async_1 = async$1.read;
33123 var sync$1 = createCommonjsModule(function (module, exports) {
33125 Object.defineProperty(exports, "__esModule", {
33129 function read(path, settings) {
33130 const lstat = settings.fs.lstatSync(path);
33132 if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
33137 const stat = settings.fs.statSync(path);
33139 if (settings.markSymbolicLink) {
33140 stat.isSymbolicLink = () => true;
33145 if (!settings.throwErrorOnBrokenSymbolicLink) {
33153 exports.read = read;
33155 unwrapExports(sync$1);
33156 var sync_1 = sync$1.read;
33158 var fs_1$1 = createCommonjsModule(function (module, exports) {
33160 Object.defineProperty(exports, "__esModule", {
33163 exports.FILE_SYSTEM_ADAPTER = {
33166 lstatSync: fs$3.lstatSync,
33167 statSync: fs$3.statSync
33170 function createFileSystemAdapter(fsMethods) {
33171 if (fsMethods === undefined) {
33172 return exports.FILE_SYSTEM_ADAPTER;
33175 return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
33178 exports.createFileSystemAdapter = createFileSystemAdapter;
33180 unwrapExports(fs_1$1);
33181 var fs_2 = fs_1$1.FILE_SYSTEM_ADAPTER;
33182 var fs_3 = fs_1$1.createFileSystemAdapter;
33184 var settings = createCommonjsModule(function (module, exports) {
33186 Object.defineProperty(exports, "__esModule", {
33191 constructor(_options = {}) {
33192 this._options = _options;
33193 this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
33194 this.fs = fs_1$1.createFileSystemAdapter(this._options.fs);
33195 this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
33196 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
33199 _getValue(option, value) {
33200 return option === undefined ? value : option;
33205 exports.default = Settings;
33207 unwrapExports(settings);
33209 var out = createCommonjsModule(function (module, exports) {
33211 Object.defineProperty(exports, "__esModule", {
33214 exports.Settings = settings.default;
33216 function stat(path, optionsOrSettingsOrCallback, callback) {
33217 if (typeof optionsOrSettingsOrCallback === 'function') {
33218 return async$1.read(path, getSettings(), optionsOrSettingsOrCallback);
33221 async$1.read(path, getSettings(optionsOrSettingsOrCallback), callback);
33224 exports.stat = stat;
33226 function statSync(path, optionsOrSettings) {
33227 const settings = getSettings(optionsOrSettings);
33228 return sync$1.read(path, settings);
33231 exports.statSync = statSync;
33233 function getSettings(settingsOrOptions = {}) {
33234 if (settingsOrOptions instanceof settings.default) {
33235 return settingsOrOptions;
33238 return new settings.default(settingsOrOptions);
33241 unwrapExports(out);
33242 var out_1 = out.Settings;
33243 var out_2 = out.stat;
33244 var out_3 = out.statSync;
33246 var runParallel_1 = runParallel;
33248 function runParallel(tasks, cb) {
33249 var results, pending, keys;
33252 if (Array.isArray(tasks)) {
33254 pending = tasks.length;
33256 keys = Object.keys(tasks);
33258 pending = keys.length;
33261 function done(err) {
33263 if (cb) cb(err, results);
33267 if (isSync) process.nextTick(end);else end();
33270 function each(i, err, result) {
33271 results[i] = result;
33273 if (--pending === 0 || err) {
33283 keys.forEach(function (key) {
33284 tasks[key](function (err, result) {
33285 each(key, err, result);
33290 tasks.forEach(function (task, i) {
33291 task(function (err, result) {
33292 each(i, err, result);
33300 var constants$4 = createCommonjsModule(function (module, exports) {
33302 Object.defineProperty(exports, "__esModule", {
33305 const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
33306 const MAJOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
33307 const MINOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
33308 const SUPPORTED_MAJOR_VERSION = 10;
33309 const SUPPORTED_MINOR_VERSION = 10;
33310 const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
33311 const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
33313 * IS `true` for Node.js 10.10 and greater.
\r
33316 exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
33318 unwrapExports(constants$4);
33319 var constants_1 = constants$4.IS_SUPPORT_READDIR_WITH_FILE_TYPES;
33321 var fs$2 = createCommonjsModule(function (module, exports) {
33323 Object.defineProperty(exports, "__esModule", {
33327 class DirentFromStats {
33328 constructor(name, stats) {
33330 this.isBlockDevice = stats.isBlockDevice.bind(stats);
33331 this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
33332 this.isDirectory = stats.isDirectory.bind(stats);
33333 this.isFIFO = stats.isFIFO.bind(stats);
33334 this.isFile = stats.isFile.bind(stats);
33335 this.isSocket = stats.isSocket.bind(stats);
33336 this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
33341 function createDirentFromStats(name, stats) {
33342 return new DirentFromStats(name, stats);
33345 exports.createDirentFromStats = createDirentFromStats;
33347 unwrapExports(fs$2);
33348 var fs_1$2 = fs$2.createDirentFromStats;
33350 var utils$5 = createCommonjsModule(function (module, exports) {
33352 Object.defineProperty(exports, "__esModule", {
33357 unwrapExports(utils$5);
33358 var utils_1$5 = utils$5.fs;
33360 var async$2 = createCommonjsModule(function (module, exports) {
33362 Object.defineProperty(exports, "__esModule", {
33366 function read(directory, settings, callback) {
33367 if (!settings.stats && constants$4.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
33368 return readdirWithFileTypes(directory, settings, callback);
33371 return readdir(directory, settings, callback);
33374 exports.read = read;
33376 function readdirWithFileTypes(directory, settings, callback) {
33377 settings.fs.readdir(directory, {
33378 withFileTypes: true
33379 }, (readdirError, dirents) => {
33380 if (readdirError !== null) {
33381 return callFailureCallback(callback, readdirError);
33384 const entries = dirents.map(dirent => ({
33387 path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
33390 if (!settings.followSymbolicLinks) {
33391 return callSuccessCallback(callback, entries);
33394 const tasks = entries.map(entry => makeRplTaskEntry(entry, settings));
33395 runParallel_1(tasks, (rplError, rplEntries) => {
33396 if (rplError !== null) {
33397 return callFailureCallback(callback, rplError);
33400 callSuccessCallback(callback, rplEntries);
33405 exports.readdirWithFileTypes = readdirWithFileTypes;
33407 function makeRplTaskEntry(entry, settings) {
33409 if (!entry.dirent.isSymbolicLink()) {
33410 return done(null, entry);
33413 settings.fs.stat(entry.path, (statError, stats) => {
33414 if (statError !== null) {
33415 if (settings.throwErrorOnBrokenSymbolicLink) {
33416 return done(statError);
33419 return done(null, entry);
33422 entry.dirent = utils$5.fs.createDirentFromStats(entry.name, stats);
33423 return done(null, entry);
33428 function readdir(directory, settings, callback) {
33429 settings.fs.readdir(directory, (readdirError, names) => {
33430 if (readdirError !== null) {
33431 return callFailureCallback(callback, readdirError);
33434 const filepaths = names.map(name => `${directory}${settings.pathSegmentSeparator}${name}`);
33435 const tasks = filepaths.map(filepath => {
33436 return done => out.stat(filepath, settings.fsStatSettings, done);
33438 runParallel_1(tasks, (rplError, results) => {
33439 if (rplError !== null) {
33440 return callFailureCallback(callback, rplError);
33443 const entries = [];
33444 names.forEach((name, index) => {
33445 const stats = results[index];
33448 path: filepaths[index],
33449 dirent: utils$5.fs.createDirentFromStats(name, stats)
33452 if (settings.stats) {
33453 entry.stats = stats;
33456 entries.push(entry);
33458 callSuccessCallback(callback, entries);
33463 exports.readdir = readdir;
33465 function callFailureCallback(callback, error) {
33469 function callSuccessCallback(callback, result) {
33470 callback(null, result);
33473 unwrapExports(async$2);
33474 var async_1$1 = async$2.read;
33475 var async_2 = async$2.readdirWithFileTypes;
33476 var async_3 = async$2.readdir;
33478 var sync$2 = createCommonjsModule(function (module, exports) {
33480 Object.defineProperty(exports, "__esModule", {
33484 function read(directory, settings) {
33485 if (!settings.stats && constants$4.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
33486 return readdirWithFileTypes(directory, settings);
33489 return readdir(directory, settings);
33492 exports.read = read;
33494 function readdirWithFileTypes(directory, settings) {
33495 const dirents = settings.fs.readdirSync(directory, {
33496 withFileTypes: true
33498 return dirents.map(dirent => {
33502 path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
33505 if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
33507 const stats = settings.fs.statSync(entry.path);
33508 entry.dirent = utils$5.fs.createDirentFromStats(entry.name, stats);
33510 if (settings.throwErrorOnBrokenSymbolicLink) {
33520 exports.readdirWithFileTypes = readdirWithFileTypes;
33522 function readdir(directory, settings) {
33523 const names = settings.fs.readdirSync(directory);
33524 return names.map(name => {
33525 const entryPath = `${directory}${settings.pathSegmentSeparator}${name}`;
33526 const stats = out.statSync(entryPath, settings.fsStatSettings);
33530 dirent: utils$5.fs.createDirentFromStats(name, stats)
33533 if (settings.stats) {
33534 entry.stats = stats;
33541 exports.readdir = readdir;
33543 unwrapExports(sync$2);
33544 var sync_1$1 = sync$2.read;
33545 var sync_2 = sync$2.readdirWithFileTypes;
33546 var sync_3 = sync$2.readdir;
33548 var fs_1$3 = createCommonjsModule(function (module, exports) {
33550 Object.defineProperty(exports, "__esModule", {
33553 exports.FILE_SYSTEM_ADAPTER = {
33556 lstatSync: fs$3.lstatSync,
33557 statSync: fs$3.statSync,
33558 readdir: fs$3.readdir,
33559 readdirSync: fs$3.readdirSync
33562 function createFileSystemAdapter(fsMethods) {
33563 if (fsMethods === undefined) {
33564 return exports.FILE_SYSTEM_ADAPTER;
33567 return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
33570 exports.createFileSystemAdapter = createFileSystemAdapter;
33572 unwrapExports(fs_1$3);
33573 var fs_2$1 = fs_1$3.FILE_SYSTEM_ADAPTER;
33574 var fs_3$1 = fs_1$3.createFileSystemAdapter;
33576 var settings$1 = createCommonjsModule(function (module, exports) {
33578 Object.defineProperty(exports, "__esModule", {
33583 constructor(_options = {}) {
33584 this._options = _options;
33585 this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
33586 this.fs = fs_1$3.createFileSystemAdapter(this._options.fs);
33587 this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$2.sep);
33588 this.stats = this._getValue(this._options.stats, false);
33589 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
33590 this.fsStatSettings = new out.Settings({
33591 followSymbolicLink: this.followSymbolicLinks,
33593 throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
33597 _getValue(option, value) {
33598 return option === undefined ? value : option;
33603 exports.default = Settings;
33605 unwrapExports(settings$1);
33607 var out$1 = createCommonjsModule(function (module, exports) {
33609 Object.defineProperty(exports, "__esModule", {
33612 exports.Settings = settings$1.default;
33614 function scandir(path, optionsOrSettingsOrCallback, callback) {
33615 if (typeof optionsOrSettingsOrCallback === 'function') {
33616 return async$2.read(path, getSettings(), optionsOrSettingsOrCallback);
33619 async$2.read(path, getSettings(optionsOrSettingsOrCallback), callback);
33622 exports.scandir = scandir;
33624 function scandirSync(path, optionsOrSettings) {
33625 const settings = getSettings(optionsOrSettings);
33626 return sync$2.read(path, settings);
33629 exports.scandirSync = scandirSync;
33631 function getSettings(settingsOrOptions = {}) {
33632 if (settingsOrOptions instanceof settings$1.default) {
33633 return settingsOrOptions;
33636 return new settings$1.default(settingsOrOptions);
33639 unwrapExports(out$1);
33640 var out_1$1 = out$1.Settings;
33641 var out_2$1 = out$1.scandir;
33642 var out_3$1 = out$1.scandirSync;
33644 function reusify(Constructor) {
33645 var head = new Constructor();
33649 var current = head;
33651 if (current.next) {
33652 head = current.next;
33654 head = new Constructor();
33658 current.next = null;
33662 function release(obj) {
33673 var reusify_1 = reusify;
33675 function fastqueue(context, worker, concurrency) {
33676 if (typeof context === 'function') {
33677 concurrency = worker;
33682 var cache = reusify_1(Task);
33683 var queueHead = null;
33684 var queueTail = null;
33692 concurrency: concurrency,
33700 killAndDrain: killAndDrain
33704 function running() {
33709 self.paused = true;
33712 function length() {
33713 var current = queueHead;
33717 current = current.next;
33724 function resume() {
33725 if (!self.paused) return;
33726 self.paused = false;
33728 for (var i = 0; i < self.concurrency; i++) {
33735 return _running === 0 && self.length() === 0;
33738 function push(value, done) {
33739 var current = cache.get();
33740 current.context = context;
33741 current.release = release;
33742 current.value = value;
33743 current.callback = done || noop$1;
33745 if (_running === self.concurrency || self.paused) {
33747 queueTail.next = current;
33748 queueTail = current;
33750 queueHead = current;
33751 queueTail = current;
33756 worker.call(context, current.value, current.worked);
33760 function unshift(value, done) {
33761 var current = cache.get();
33762 current.context = context;
33763 current.release = release;
33764 current.value = value;
33765 current.callback = done || noop$1;
33767 if (_running === self.concurrency || self.paused) {
33769 current.next = queueHead;
33770 queueHead = current;
33772 queueHead = current;
33773 queueTail = current;
33778 worker.call(context, current.value, current.worked);
33782 function release(holder) {
33784 cache.release(holder);
33787 var next = queueHead;
33790 if (!self.paused) {
33791 if (queueTail === queueHead) {
33795 queueHead = next.next;
33797 worker.call(context, next.value, next.worked);
33799 if (queueTail === null) {
33805 } else if (--_running === 0) {
33813 self.drain = noop$1;
33816 function killAndDrain() {
33820 self.drain = noop$1;
33824 function noop$1() {}
33828 this.callback = noop$1;
33830 this.release = noop$1;
33831 this.context = null;
33834 this.worked = function worked(err, result) {
33835 var callback = self.callback;
33837 self.callback = noop$1;
33838 callback.call(self.context, err, result);
33839 self.release(self);
33843 var queue = fastqueue;
33845 var common$2 = createCommonjsModule(function (module, exports) {
33847 Object.defineProperty(exports, "__esModule", {
33851 function isFatalError(settings, error) {
33852 if (settings.errorFilter === null) {
33856 return !settings.errorFilter(error);
33859 exports.isFatalError = isFatalError;
33861 function isAppliedFilter(filter, value) {
33862 return filter === null || filter(value);
33865 exports.isAppliedFilter = isAppliedFilter;
33867 function replacePathSegmentSeparator(filepath, separator) {
33868 return filepath.split(/[\\/]/).join(separator);
33871 exports.replacePathSegmentSeparator = replacePathSegmentSeparator;
33873 function joinPathSegments(a, b, separator) {
33878 return a + separator + b;
33881 exports.joinPathSegments = joinPathSegments;
33883 unwrapExports(common$2);
33884 var common_1$2 = common$2.isFatalError;
33885 var common_2 = common$2.isAppliedFilter;
33886 var common_3 = common$2.replacePathSegmentSeparator;
33887 var common_4 = common$2.joinPathSegments;
33889 var reader = createCommonjsModule(function (module, exports) {
33891 Object.defineProperty(exports, "__esModule", {
33896 constructor(_root, _settings) {
33897 this._root = _root;
33898 this._settings = _settings;
33899 this._root = common$2.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
33904 exports.default = Reader;
33906 unwrapExports(reader);
33908 var async$3 = createCommonjsModule(function (module, exports) {
33910 Object.defineProperty(exports, "__esModule", {
33914 class AsyncReader extends reader.default {
33915 constructor(_root, _settings) {
33916 super(_root, _settings);
33917 this._settings = _settings;
33918 this._scandir = out$1.scandir;
33919 this._emitter = new events$1.EventEmitter();
33920 this._queue = queue(this._worker.bind(this), this._settings.concurrency);
33921 this._isFatalError = false;
33922 this._isDestroyed = false;
33924 this._queue.drain = () => {
33925 if (!this._isFatalError) {
33926 this._emitter.emit('end');
33932 this._isFatalError = false;
33933 this._isDestroyed = false;
33934 setImmediate(() => {
33935 this._pushToQueue(this._root, this._settings.basePath);
33937 return this._emitter;
33941 if (this._isDestroyed) {
33942 throw new Error('The reader is already destroyed');
33945 this._isDestroyed = true;
33947 this._queue.killAndDrain();
33950 onEntry(callback) {
33951 this._emitter.on('entry', callback);
33954 onError(callback) {
33955 this._emitter.once('error', callback);
33959 this._emitter.once('end', callback);
33962 _pushToQueue(directory, base) {
33963 const queueItem = {
33968 this._queue.push(queueItem, error => {
33969 if (error !== null) {
33970 this._handleError(error);
33975 _worker(item, done) {
33976 this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
33977 if (error !== null) {
33978 return done(error, undefined);
33981 for (const entry of entries) {
33982 this._handleEntry(entry, item.base);
33985 done(null, undefined);
33989 _handleError(error) {
33990 if (!common$2.isFatalError(this._settings, error)) {
33994 this._isFatalError = true;
33995 this._isDestroyed = true;
33997 this._emitter.emit('error', error);
34000 _handleEntry(entry, base) {
34001 if (this._isDestroyed || this._isFatalError) {
34005 const fullpath = entry.path;
34007 if (base !== undefined) {
34008 entry.path = common$2.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
34011 if (common$2.isAppliedFilter(this._settings.entryFilter, entry)) {
34012 this._emitEntry(entry);
34015 if (entry.dirent.isDirectory() && common$2.isAppliedFilter(this._settings.deepFilter, entry)) {
34016 this._pushToQueue(fullpath, entry.path);
34020 _emitEntry(entry) {
34021 this._emitter.emit('entry', entry);
34026 exports.default = AsyncReader;
34028 unwrapExports(async$3);
34030 var async$4 = createCommonjsModule(function (module, exports) {
34032 Object.defineProperty(exports, "__esModule", {
34036 class AsyncProvider {
34037 constructor(_root, _settings) {
34038 this._root = _root;
34039 this._settings = _settings;
34040 this._reader = new async$3.default(this._root, this._settings);
34041 this._storage = new Set();
34045 this._reader.onError(error => {
34046 callFailureCallback(callback, error);
34049 this._reader.onEntry(entry => {
34050 this._storage.add(entry);
34053 this._reader.onEnd(() => {
34054 callSuccessCallback(callback, [...this._storage]);
34057 this._reader.read();
34062 exports.default = AsyncProvider;
34064 function callFailureCallback(callback, error) {
34068 function callSuccessCallback(callback, entries) {
34069 callback(null, entries);
34072 unwrapExports(async$4);
34074 var stream$2 = createCommonjsModule(function (module, exports) {
34076 Object.defineProperty(exports, "__esModule", {
34080 class StreamProvider {
34081 constructor(_root, _settings) {
34082 this._root = _root;
34083 this._settings = _settings;
34084 this._reader = new async$3.default(this._root, this._settings);
34085 this._stream = new stream$6.Readable({
34088 destroy: this._reader.destroy.bind(this._reader)
34093 this._reader.onError(error => {
34094 this._stream.emit('error', error);
34097 this._reader.onEntry(entry => {
34098 this._stream.push(entry);
34101 this._reader.onEnd(() => {
34102 this._stream.push(null);
34105 this._reader.read();
34107 return this._stream;
34112 exports.default = StreamProvider;
34114 unwrapExports(stream$2);
34116 var sync$3 = createCommonjsModule(function (module, exports) {
34118 Object.defineProperty(exports, "__esModule", {
34122 class SyncReader extends reader.default {
34124 super(...arguments);
34125 this._scandir = out$1.scandirSync;
34126 this._storage = new Set();
34127 this._queue = new Set();
34131 this._pushToQueue(this._root, this._settings.basePath);
34133 this._handleQueue();
34135 return [...this._storage];
34138 _pushToQueue(directory, base) {
34146 for (const item of this._queue.values()) {
34147 this._handleDirectory(item.directory, item.base);
34151 _handleDirectory(directory, base) {
34153 const entries = this._scandir(directory, this._settings.fsScandirSettings);
34155 for (const entry of entries) {
34156 this._handleEntry(entry, base);
34159 this._handleError(error);
34163 _handleError(error) {
34164 if (!common$2.isFatalError(this._settings, error)) {
34171 _handleEntry(entry, base) {
34172 const fullpath = entry.path;
34174 if (base !== undefined) {
34175 entry.path = common$2.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
34178 if (common$2.isAppliedFilter(this._settings.entryFilter, entry)) {
34179 this._pushToStorage(entry);
34182 if (entry.dirent.isDirectory() && common$2.isAppliedFilter(this._settings.deepFilter, entry)) {
34183 this._pushToQueue(fullpath, entry.path);
34187 _pushToStorage(entry) {
34188 this._storage.add(entry);
34193 exports.default = SyncReader;
34195 unwrapExports(sync$3);
34197 var sync$4 = createCommonjsModule(function (module, exports) {
34199 Object.defineProperty(exports, "__esModule", {
34203 class SyncProvider {
34204 constructor(_root, _settings) {
34205 this._root = _root;
34206 this._settings = _settings;
34207 this._reader = new sync$3.default(this._root, this._settings);
34211 return this._reader.read();
34216 exports.default = SyncProvider;
34218 unwrapExports(sync$4);
34220 var settings$2 = createCommonjsModule(function (module, exports) {
34222 Object.defineProperty(exports, "__esModule", {
34227 constructor(_options = {}) {
34228 this._options = _options;
34229 this.basePath = this._getValue(this._options.basePath, undefined);
34230 this.concurrency = this._getValue(this._options.concurrency, Infinity);
34231 this.deepFilter = this._getValue(this._options.deepFilter, null);
34232 this.entryFilter = this._getValue(this._options.entryFilter, null);
34233 this.errorFilter = this._getValue(this._options.errorFilter, null);
34234 this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path$2.sep);
34235 this.fsScandirSettings = new out$1.Settings({
34236 followSymbolicLinks: this._options.followSymbolicLinks,
34237 fs: this._options.fs,
34238 pathSegmentSeparator: this._options.pathSegmentSeparator,
34239 stats: this._options.stats,
34240 throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
34244 _getValue(option, value) {
34245 return option === undefined ? value : option;
34250 exports.default = Settings;
34252 unwrapExports(settings$2);
34254 var out$2 = createCommonjsModule(function (module, exports) {
34256 Object.defineProperty(exports, "__esModule", {
34259 exports.Settings = settings$2.default;
34261 function walk(directory, optionsOrSettingsOrCallback, callback) {
34262 if (typeof optionsOrSettingsOrCallback === 'function') {
34263 return new async$4.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
34266 new async$4.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
34269 exports.walk = walk;
34271 function walkSync(directory, optionsOrSettings) {
34272 const settings = getSettings(optionsOrSettings);
34273 const provider = new sync$4.default(directory, settings);
34274 return provider.read();
34277 exports.walkSync = walkSync;
34279 function walkStream(directory, optionsOrSettings) {
34280 const settings = getSettings(optionsOrSettings);
34281 const provider = new stream$2.default(directory, settings);
34282 return provider.read();
34285 exports.walkStream = walkStream;
34287 function getSettings(settingsOrOptions = {}) {
34288 if (settingsOrOptions instanceof settings$2.default) {
34289 return settingsOrOptions;
34292 return new settings$2.default(settingsOrOptions);
34295 unwrapExports(out$2);
34296 var out_1$2 = out$2.Settings;
34297 var out_2$2 = out$2.walk;
34298 var out_3$2 = out$2.walkSync;
34299 var out_4 = out$2.walkStream;
34301 var reader$1 = createCommonjsModule(function (module, exports) {
34303 Object.defineProperty(exports, "__esModule", {
34308 constructor(_settings) {
34309 this._settings = _settings;
34310 this._fsStatSettings = new out.Settings({
34311 followSymbolicLink: this._settings.followSymbolicLinks,
34312 fs: this._settings.fs,
34313 throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
34317 _getFullEntryPath(filepath) {
34318 return path$2.resolve(this._settings.cwd, filepath);
34321 _makeEntry(stats, pattern) {
34325 dirent: utils$4.fs.createDirentFromStats(pattern, stats)
34328 if (this._settings.stats) {
34329 entry.stats = stats;
34335 _isFatalError(error) {
34336 return !utils$4.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
34341 exports.default = Reader;
34343 unwrapExports(reader$1);
34345 var stream$3 = createCommonjsModule(function (module, exports) {
34347 Object.defineProperty(exports, "__esModule", {
34351 class ReaderStream extends reader$1.default {
34353 super(...arguments);
34354 this._walkStream = out$2.walkStream;
34355 this._stat = out.stat;
34358 dynamic(root, options) {
34359 return this._walkStream(root, options);
34362 static(patterns, options) {
34363 const filepaths = patterns.map(this._getFullEntryPath, this);
34364 const stream = new stream$6.PassThrough({
34368 stream._write = (index, _enc, done) => {
34369 return this._getEntry(filepaths[index], patterns[index], options).then(entry => {
34370 if (entry !== null && options.entryFilter(entry)) {
34371 stream.push(entry);
34374 if (index === filepaths.length - 1) {
34382 for (let i = 0; i < filepaths.length; i++) {
34389 _getEntry(filepath, pattern, options) {
34390 return this._getStat(filepath).then(stats => this._makeEntry(stats, pattern)).catch(error => {
34391 if (options.errorFilter(error)) {
34399 _getStat(filepath) {
34400 return new Promise((resolve, reject) => {
34401 this._stat(filepath, this._fsStatSettings, (error, stats) => {
34402 return error === null ? resolve(stats) : reject(error);
34409 exports.default = ReaderStream;
34411 unwrapExports(stream$3);
34413 var matcher = createCommonjsModule(function (module, exports) {
34415 Object.defineProperty(exports, "__esModule", {
34420 constructor(_patterns, _settings, _micromatchOptions) {
34421 this._patterns = _patterns;
34422 this._settings = _settings;
34423 this._micromatchOptions = _micromatchOptions;
34424 this._storage = [];
34426 this._fillStorage();
34431 * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
\r
34432 * So, before expand patterns with brace expansion into separated patterns.
\r
34434 const patterns = utils$4.pattern.expandPatternsWithBraceExpansion(this._patterns);
34436 for (const pattern of patterns) {
34437 const segments = this._getPatternSegments(pattern);
34439 const sections = this._splitSegmentsIntoSections(segments);
34441 this._storage.push({
34442 complete: sections.length <= 1,
34450 _getPatternSegments(pattern) {
34451 const parts = utils$4.pattern.getPatternParts(pattern, this._micromatchOptions);
34452 return parts.map(part => {
34453 const dynamic = utils$4.pattern.isDynamicPattern(part, this._settings);
34465 patternRe: utils$4.pattern.makeRe(part, this._micromatchOptions)
34470 _splitSegmentsIntoSections(segments) {
34471 return utils$4.array.splitWhen(segments, segment => segment.dynamic && utils$4.pattern.hasGlobStar(segment.pattern));
34476 exports.default = Matcher;
34478 unwrapExports(matcher);
34480 var partial = createCommonjsModule(function (module, exports) {
34482 Object.defineProperty(exports, "__esModule", {
34486 class PartialMatcher extends matcher.default {
34488 const parts = filepath.split('/');
34489 const levels = parts.length;
34491 const patterns = this._storage.filter(info => !info.complete || info.segments.length > levels);
34493 for (const pattern of patterns) {
34494 const section = pattern.sections[0];
34496 * In this case, the pattern has a globstar and we must read all directories unconditionally,
\r
34497 * but only if the level has reached the end of the first group.
\r
34499 * fixtures/{a,b}/**
\r
34500 * ^ true/false ^ always true
\r
34503 if (!pattern.complete && levels > section.length) {
34507 const match = parts.every((part, index) => {
34508 const segment = pattern.segments[index];
34510 if (segment.dynamic && segment.patternRe.test(part)) {
34514 if (!segment.dynamic && segment.pattern === part) {
34531 exports.default = PartialMatcher;
34533 unwrapExports(partial);
34535 var deep = createCommonjsModule(function (module, exports) {
34537 Object.defineProperty(exports, "__esModule", {
34542 constructor(_settings, _micromatchOptions) {
34543 this._settings = _settings;
34544 this._micromatchOptions = _micromatchOptions;
34547 getFilter(basePath, positive, negative) {
34548 const matcher = this._getMatcher(positive);
34550 const negativeRe = this._getNegativePatternsRe(negative);
34552 return entry => this._filter(basePath, entry, matcher, negativeRe);
34555 _getMatcher(patterns) {
34556 return new partial.default(patterns, this._settings, this._micromatchOptions);
34559 _getNegativePatternsRe(patterns) {
34560 const affectDepthOfReadingPatterns = patterns.filter(utils$4.pattern.isAffectDepthOfReadingPattern);
34561 return utils$4.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
34564 _filter(basePath, entry, matcher, negativeRe) {
34565 const depth = this._getEntryLevel(basePath, entry.path);
34567 if (this._isSkippedByDeep(depth)) {
34571 if (this._isSkippedSymbolicLink(entry)) {
34575 const filepath = utils$4.path.removeLeadingDotSegment(entry.path);
34577 if (this._isSkippedByPositivePatterns(filepath, matcher)) {
34581 return this._isSkippedByNegativePatterns(filepath, negativeRe);
34584 _isSkippedByDeep(entryDepth) {
34585 return entryDepth >= this._settings.deep;
34588 _isSkippedSymbolicLink(entry) {
34589 return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
34592 _getEntryLevel(basePath, entryPath) {
34593 const basePathDepth = basePath.split('/').length;
34594 const entryPathDepth = entryPath.split('/').length;
34595 return entryPathDepth - (basePath === '' ? 0 : basePathDepth);
34598 _isSkippedByPositivePatterns(entryPath, matcher) {
34599 return !this._settings.baseNameMatch && !matcher.match(entryPath);
34602 _isSkippedByNegativePatterns(entryPath, negativeRe) {
34603 return !utils$4.pattern.matchAny(entryPath, negativeRe);
34608 exports.default = DeepFilter;
34610 unwrapExports(deep);
34612 var entry = createCommonjsModule(function (module, exports) {
34614 Object.defineProperty(exports, "__esModule", {
34618 class EntryFilter {
34619 constructor(_settings, _micromatchOptions) {
34620 this._settings = _settings;
34621 this._micromatchOptions = _micromatchOptions;
34622 this.index = new Map();
34625 getFilter(positive, negative) {
34626 const positiveRe = utils$4.pattern.convertPatternsToRe(positive, this._micromatchOptions);
34627 const negativeRe = utils$4.pattern.convertPatternsToRe(negative, this._micromatchOptions);
34628 return entry => this._filter(entry, positiveRe, negativeRe);
34631 _filter(entry, positiveRe, negativeRe) {
34632 if (this._settings.unique) {
34633 if (this._isDuplicateEntry(entry)) {
34637 this._createIndexRecord(entry);
34640 if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
34644 if (this._isSkippedByAbsoluteNegativePatterns(entry, negativeRe)) {
34648 const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
34649 return this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
34652 _isDuplicateEntry(entry) {
34653 return this.index.has(entry.path);
34656 _createIndexRecord(entry) {
34657 this.index.set(entry.path, undefined);
34660 _onlyFileFilter(entry) {
34661 return this._settings.onlyFiles && !entry.dirent.isFile();
34664 _onlyDirectoryFilter(entry) {
34665 return this._settings.onlyDirectories && !entry.dirent.isDirectory();
34668 _isSkippedByAbsoluteNegativePatterns(entry, negativeRe) {
34669 if (!this._settings.absolute) {
34673 const fullpath = utils$4.path.makeAbsolute(this._settings.cwd, entry.path);
34674 return this._isMatchToPatterns(fullpath, negativeRe);
34677 _isMatchToPatterns(entryPath, patternsRe) {
34678 const filepath = utils$4.path.removeLeadingDotSegment(entryPath);
34679 return utils$4.pattern.matchAny(filepath, patternsRe);
34684 exports.default = EntryFilter;
34686 unwrapExports(entry);
34688 var error = createCommonjsModule(function (module, exports) {
34690 Object.defineProperty(exports, "__esModule", {
34694 class ErrorFilter {
34695 constructor(_settings) {
34696 this._settings = _settings;
34700 return error => this._isNonFatalError(error);
34703 _isNonFatalError(error) {
34704 return utils$4.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
34709 exports.default = ErrorFilter;
34711 unwrapExports(error);
34713 var entry$1 = createCommonjsModule(function (module, exports) {
34715 Object.defineProperty(exports, "__esModule", {
34719 class EntryTransformer {
34720 constructor(_settings) {
34721 this._settings = _settings;
34725 return entry => this._transform(entry);
34728 _transform(entry) {
34729 let filepath = entry.path;
34731 if (this._settings.absolute) {
34732 filepath = utils$4.path.makeAbsolute(this._settings.cwd, filepath);
34733 filepath = utils$4.path.unixify(filepath);
34736 if (this._settings.markDirectories && entry.dirent.isDirectory()) {
34740 if (!this._settings.objectMode) {
34744 return Object.assign(Object.assign({}, entry), {
34751 exports.default = EntryTransformer;
34753 unwrapExports(entry$1);
34755 var provider = createCommonjsModule(function (module, exports) {
34757 Object.defineProperty(exports, "__esModule", {
34762 constructor(_settings) {
34763 this._settings = _settings;
34764 this.errorFilter = new error.default(this._settings);
34765 this.entryFilter = new entry.default(this._settings, this._getMicromatchOptions());
34766 this.deepFilter = new deep.default(this._settings, this._getMicromatchOptions());
34767 this.entryTransformer = new entry$1.default(this._settings);
34770 _getRootDirectory(task) {
34771 return path$2.resolve(this._settings.cwd, task.base);
34774 _getReaderOptions(task) {
34775 const basePath = task.base === '.' ? '' : task.base;
34778 pathSegmentSeparator: '/',
34779 concurrency: this._settings.concurrency,
34780 deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
34781 entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
34782 errorFilter: this.errorFilter.getFilter(),
34783 followSymbolicLinks: this._settings.followSymbolicLinks,
34784 fs: this._settings.fs,
34785 stats: this._settings.stats,
34786 throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
34787 transform: this.entryTransformer.getTransformer()
34791 _getMicromatchOptions() {
34793 dot: this._settings.dot,
34794 matchBase: this._settings.baseNameMatch,
34795 nobrace: !this._settings.braceExpansion,
34796 nocase: !this._settings.caseSensitiveMatch,
34797 noext: !this._settings.extglob,
34798 noglobstar: !this._settings.globstar,
34800 strictSlashes: false
34806 exports.default = Provider;
34808 unwrapExports(provider);
34810 var async$5 = createCommonjsModule(function (module, exports) {
34812 Object.defineProperty(exports, "__esModule", {
34816 class ProviderAsync extends provider.default {
34818 super(...arguments);
34819 this._reader = new stream$3.default(this._settings);
34823 const root = this._getRootDirectory(task);
34825 const options = this._getReaderOptions(task);
34827 const entries = [];
34828 return new Promise((resolve, reject) => {
34829 const stream = this.api(root, task, options);
34830 stream.once('error', reject);
34831 stream.on('data', entry => entries.push(options.transform(entry)));
34832 stream.once('end', () => resolve(entries));
34836 api(root, task, options) {
34837 if (task.dynamic) {
34838 return this._reader.dynamic(root, options);
34841 return this._reader.static(task.patterns, options);
34846 exports.default = ProviderAsync;
34848 unwrapExports(async$5);
34850 var stream$4 = createCommonjsModule(function (module, exports) {
34852 Object.defineProperty(exports, "__esModule", {
34856 class ProviderStream extends provider.default {
34858 super(...arguments);
34859 this._reader = new stream$3.default(this._settings);
34863 const root = this._getRootDirectory(task);
34865 const options = this._getReaderOptions(task);
34867 const source = this.api(root, task, options);
34868 const destination = new stream$6.Readable({
34872 source.once('error', error => destination.emit('error', error)).on('data', entry => destination.emit('data', options.transform(entry))).once('end', () => destination.emit('end'));
34873 destination.once('close', () => source.destroy());
34874 return destination;
34877 api(root, task, options) {
34878 if (task.dynamic) {
34879 return this._reader.dynamic(root, options);
34882 return this._reader.static(task.patterns, options);
34887 exports.default = ProviderStream;
34889 unwrapExports(stream$4);
34891 var sync$5 = createCommonjsModule(function (module, exports) {
34893 Object.defineProperty(exports, "__esModule", {
34897 class ReaderSync extends reader$1.default {
34899 super(...arguments);
34900 this._walkSync = out$2.walkSync;
34901 this._statSync = out.statSync;
34904 dynamic(root, options) {
34905 return this._walkSync(root, options);
34908 static(patterns, options) {
34909 const entries = [];
34911 for (const pattern of patterns) {
34912 const filepath = this._getFullEntryPath(pattern);
34914 const entry = this._getEntry(filepath, pattern, options);
34916 if (entry === null || !options.entryFilter(entry)) {
34920 entries.push(entry);
34926 _getEntry(filepath, pattern, options) {
34928 const stats = this._getStat(filepath);
34930 return this._makeEntry(stats, pattern);
34932 if (options.errorFilter(error)) {
34940 _getStat(filepath) {
34941 return this._statSync(filepath, this._fsStatSettings);
34946 exports.default = ReaderSync;
34948 unwrapExports(sync$5);
34950 var sync$6 = createCommonjsModule(function (module, exports) {
34952 Object.defineProperty(exports, "__esModule", {
34956 class ProviderSync extends provider.default {
34958 super(...arguments);
34959 this._reader = new sync$5.default(this._settings);
34963 const root = this._getRootDirectory(task);
34965 const options = this._getReaderOptions(task);
34967 const entries = this.api(root, task, options);
34968 return entries.map(options.transform);
34971 api(root, task, options) {
34972 if (task.dynamic) {
34973 return this._reader.dynamic(root, options);
34976 return this._reader.static(task.patterns, options);
34981 exports.default = ProviderSync;
34983 unwrapExports(sync$6);
34985 var settings$3 = createCommonjsModule(function (module, exports) {
34987 Object.defineProperty(exports, "__esModule", {
34990 const CPU_COUNT = os$1.cpus().length;
34991 exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
34993 lstatSync: fs$3.lstatSync,
34995 statSync: fs$3.statSync,
34996 readdir: fs$3.readdir,
34997 readdirSync: fs$3.readdirSync
35001 constructor(_options = {}) {
35002 this._options = _options;
35003 this.absolute = this._getValue(this._options.absolute, false);
35004 this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
35005 this.braceExpansion = this._getValue(this._options.braceExpansion, true);
35006 this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
35007 this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
35008 this.cwd = this._getValue(this._options.cwd, process.cwd());
35009 this.deep = this._getValue(this._options.deep, Infinity);
35010 this.dot = this._getValue(this._options.dot, false);
35011 this.extglob = this._getValue(this._options.extglob, true);
35012 this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
35013 this.fs = this._getFileSystemMethods(this._options.fs);
35014 this.globstar = this._getValue(this._options.globstar, true);
35015 this.ignore = this._getValue(this._options.ignore, []);
35016 this.markDirectories = this._getValue(this._options.markDirectories, false);
35017 this.objectMode = this._getValue(this._options.objectMode, false);
35018 this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
35019 this.onlyFiles = this._getValue(this._options.onlyFiles, true);
35020 this.stats = this._getValue(this._options.stats, false);
35021 this.suppressErrors = this._getValue(this._options.suppressErrors, false);
35022 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
35023 this.unique = this._getValue(this._options.unique, true);
35025 if (this.onlyDirectories) {
35026 this.onlyFiles = false;
35030 this.objectMode = true;
35034 _getValue(option, value) {
35035 return option === undefined ? value : option;
35038 _getFileSystemMethods(methods = {}) {
35039 return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
35044 exports.default = Settings;
35046 unwrapExports(settings$3);
35047 var settings_1 = settings$3.DEFAULT_FILE_SYSTEM_ADAPTER;
35049 async function FastGlob(source, options) {
35050 assertPatternsInput(source);
35051 const works = getWorks(source, async$5.default, options);
35052 const result = await Promise.all(works);
35053 return utils$4.array.flatten(result);
35054 } // https://github.com/typescript-eslint/typescript-eslint/issues/60
35055 // eslint-disable-next-line no-redeclare
35058 (function (FastGlob) {
35059 function sync(source, options) {
35060 assertPatternsInput(source);
35061 const works = getWorks(source, sync$6.default, options);
35062 return utils$4.array.flatten(works);
35065 FastGlob.sync = sync;
35067 function stream(source, options) {
35068 assertPatternsInput(source);
35069 const works = getWorks(source, stream$4.default, options);
35071 * The stream returned by the provider cannot work with an asynchronous iterator.
\r
35072 * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
\r
35073 * This affects performance (+25%). I don't see best solution right now.
\r
35076 return utils$4.stream.merge(works);
35079 FastGlob.stream = stream;
35081 function generateTasks(source, options) {
35082 assertPatternsInput(source);
35083 const patterns = [].concat(source);
35084 const settings = new settings$3.default(options);
35085 return tasks.generate(patterns, settings);
35088 FastGlob.generateTasks = generateTasks;
35090 function isDynamicPattern(source, options) {
35091 assertPatternsInput(source);
35092 const settings = new settings$3.default(options);
35093 return utils$4.pattern.isDynamicPattern(source, settings);
35096 FastGlob.isDynamicPattern = isDynamicPattern;
35098 function escapePath(source) {
35099 assertPatternsInput(source);
35100 return utils$4.path.escape(source);
35103 FastGlob.escapePath = escapePath;
35104 })(FastGlob || (FastGlob = {}));
35106 function getWorks(source, _Provider, options) {
35107 const patterns = [].concat(source);
35108 const settings = new settings$3.default(options);
35109 const tasks$1 = tasks.generate(patterns, settings);
35110 const provider = new _Provider(settings);
35111 return tasks$1.map(provider.read, provider);
35114 function assertPatternsInput(input) {
35115 const source = [].concat(input);
35116 const isValidSource = source.every(item => utils$4.string.isString(item) && !utils$4.string.isEmpty(item));
35118 if (!isValidSource) {
35119 throw new TypeError('Patterns must be a string (non empty) or an array of strings');
35123 var out$3 = FastGlob;
35129 async function isType(fsStatType, statsMethodName, filePath) {
35130 if (typeof filePath !== 'string') {
35131 throw new TypeError(`Expected a string, got ${typeof filePath}`);
35135 const stats = await promisify(fs$3[fsStatType])(filePath);
35136 return stats[statsMethodName]();
35138 if (error.code === 'ENOENT') {
35146 function isTypeSync(fsStatType, statsMethodName, filePath) {
35147 if (typeof filePath !== 'string') {
35148 throw new TypeError(`Expected a string, got ${typeof filePath}`);
35152 return fs$3[fsStatType](filePath)[statsMethodName]();
35154 if (error.code === 'ENOENT') {
35162 var isFile = isType.bind(null, 'stat', 'isFile');
35163 var isDirectory = isType.bind(null, 'stat', 'isDirectory');
35164 var isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink');
35165 var isFileSync = isTypeSync.bind(null, 'statSync', 'isFile');
35166 var isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory');
35167 var isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink');
35170 isDirectory: isDirectory,
35171 isSymlink: isSymlink,
35172 isFileSync: isFileSync,
35173 isDirectorySync: isDirectorySync,
35174 isSymlinkSync: isSymlinkSync
35177 const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0];
35179 const getPath = (filepath, cwd) => {
35180 const pth = filepath[0] === '!' ? filepath.slice(1) : filepath;
35181 return path$2.isAbsolute(pth) ? pth : path$2.join(cwd, pth);
35184 const addExtensions = (file, extensions) => {
35185 if (path$2.extname(file)) {
35186 return `**/${file}`;
35189 return `**/${file}.${getExtensions(extensions)}`;
35192 const getGlob = (directory, options) => {
35193 if (options.files && !Array.isArray(options.files)) {
35194 throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``);
35197 if (options.extensions && !Array.isArray(options.extensions)) {
35198 throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``);
35201 if (options.files && options.extensions) {
35202 return options.files.map(x => path$2.posix.join(directory, addExtensions(x, options.extensions)));
35205 if (options.files) {
35206 return options.files.map(x => path$2.posix.join(directory, `**/${x}`));
35209 if (options.extensions) {
35210 return [path$2.posix.join(directory, `**/*.${getExtensions(options.extensions)}`)];
35213 return [path$2.posix.join(directory, '**')];
35216 var dirGlob = async (input, options) => {
35217 options = Object.assign({
35221 if (typeof options.cwd !== 'string') {
35222 throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);
35225 const globs = await Promise.all([].concat(input).map(async x => {
35226 const isDirectory = await pathType.isDirectory(getPath(x, options.cwd));
35227 return isDirectory ? getGlob(x, options) : x;
35229 return [].concat.apply([], globs); // eslint-disable-line prefer-spread
35232 var sync$7 = (input, options) => {
35233 options = Object.assign({
35237 if (typeof options.cwd !== 'string') {
35238 throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);
35241 const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x);
35242 return [].concat.apply([], globs); // eslint-disable-line prefer-spread
35244 dirGlob.sync = sync$7;
35246 // A simple implementation of make-array
35247 function makeArray(subject) {
35248 return Array.isArray(subject) ? subject : [subject];
35251 const REGEX_TEST_BLANK_LINE = /^\s+$/;
35252 const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
35253 const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
35254 const REGEX_SPLITALL_CRLF = /\r?\n/g; // /foo,
35260 const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
35261 const SLASH$1 = '/';
35262 const KEY_IGNORE$1 = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
35263 /* istanbul ignore next */
35266 const define$1 = (object, key, value) => Object.defineProperty(object, key, {
35270 const REGEX_REGEXP_RANGE$1 = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression
35271 // The cases are complicated, see test cases for details
35273 const sanitizeRange$1 = range => range.replace(REGEX_REGEXP_RANGE$1, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match // Invalid range (out of order) which is ok for gitignore rules but
35274 // fatal for JavaScript regular expression, so eliminate it.
35275 : ''); // > If the pattern ends with a slash,
35276 // > it is removed for the purpose of the following description,
35277 // > but it would only find a match with a directory.
35278 // > In other words, foo/ will match a directory foo and paths underneath it,
35279 // > but will not match a regular file or a symbolic link foo
35280 // > (this is consistent with the way how pathspec works in general in Git).
35281 // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
35282 // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
35283 // you could use option `mark: true` with `glob`
35284 // '`foo/`' should not continue with the '`..`'
35287 const REPLACERS = [// > Trailing spaces are ignored unless they are quoted with backslash ("\")
35291 /\\?\s+$/, match => match.indexOf('\\') === 0 ? ' ' : ''], // replace (\ ) with ' '
35292 [/\\\s/g, () => ' '], // Escape metacharacters
35293 // which is written down by users but means special for regular expressions.
35294 // > There are 12 characters with special meanings:
35295 // > - the backslash \,
35296 // > - the caret ^,
35297 // > - the dollar sign $,
35298 // > - the period or dot .,
35299 // > - the vertical bar or pipe symbol |,
35300 // > - the question mark ?,
35301 // > - the asterisk or star *,
35302 // > - the plus sign +,
35303 // > - the opening parenthesis (,
35304 // > - the closing parenthesis ),
35305 // > - and the opening square bracket [,
35306 // > - the opening curly brace {,
35307 // > These special characters are often called "metacharacters".
35308 [/[\\^$.|*+(){]/g, match => `\\${match}`], [// > [abc] matches any character inside the brackets
35309 // > (in this case a, b, or c);
35310 /\[([^\]/]*)($|\])/g, (match, p1, p2) => p2 === ']' ? `[${sanitizeRange$1(p1)}]` : `\\${match}`], [// > a question mark (?) matches a single character
35311 /(?!\\)\?/g, () => '[^/]'], // leading slash
35312 [// > A leading slash matches the beginning of the pathname.
35313 // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
35314 // A leading slash matches the beginning of the pathname
35315 /^\//, () => '^'], // replace special metacharacter slash after the leading slash
35316 [/\//g, () => '\\/'], [// > A leading "**" followed by a slash means match in all directories.
35317 // > For example, "**/foo" matches file or directory "foo" anywhere,
35318 // > the same as pattern "foo".
35319 // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
35320 // > under directory "foo".
35321 // Notice that the '*'s have been replaced as '\\*'
35322 /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo'
35323 () => '^(?:.*\\/)?'], // ending
35324 [// 'js' will not match 'js.'
35325 // 'ab' will not match 'abc'
35326 /(?:[^*])$/, // WTF!
35327 // https://git-scm.com/docs/gitignore
35328 // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
35329 // which re-fixes #24, #38
35330 // > If there is a separator at the end of the pattern then the pattern
35331 // > will only match directories, otherwise the pattern can match both
35332 // > files and directories.
35333 // 'js*' will not match 'a.js'
35334 // 'js/' will not match 'a.js'
35335 // 'js' will match 'a.js' and 'a.js/'
35336 match => /\/$/.test(match) // foo/ will not match 'foo'
35337 ? `${match}$` // foo matches 'foo' and 'foo/'
35338 : `${match}(?=$|\\/$)`], // starting
35339 [// there will be no leading '/'
35340 // (which has been replaced by section "leading slash")
35341 // If starts with '**', adding a '^' to the regular expression also works
35342 /^(?=[^^])/, function startingReplacer() {
35343 // If has a slash `/` at the beginning or middle
35344 return !/\/(?!$)/.test(this) // > Prior to 2.22.1
35345 // > If the pattern does not contain a slash /,
35346 // > Git treats it as a shell glob pattern
35347 // Actually, if there is only a trailing slash,
35348 // git also treats it as a shell glob pattern
35349 // After 2.22.1 (compatible but clearer)
35350 // > If there is a separator at the beginning or middle (or both)
35351 // > of the pattern, then the pattern is relative to the directory
35352 // > level of the particular .gitignore file itself.
35353 // > Otherwise the pattern may also match at any level below
35354 // > the .gitignore level.
35355 ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for
35356 // > consumption by fnmatch(3)
35358 }], // two globstars
35359 [// Use lookahead assertions so that we could match more than one `'/**'`
35360 /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories
35361 // should not use '*', or it will be replaced by the next replacer
35362 // Check if it is not the last `'/**'`
35363 (_, index, str) => index + 6 < str.length // case: /**/
35364 // > A slash followed by two consecutive asterisks then a slash matches
35365 // > zero or more directories.
35366 // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
35368 ? '(?:\\/[^\\/]+)*' // case: /**
35369 // > A trailing `"/**"` matches everything inside.
35370 // #21: everything inside but it should not include the current folder
35371 : '\\/.+'], // intermediate wildcards
35372 [// Never replace escaped '*'
35373 // ignore rule '\*' will match the path '*'
35375 // 'abc.*' -> skip this rule
35376 /(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js'
35377 // '*.js' doesn't match 'abc'
35378 (_, p1) => `${p1}[^\\/]*`], // trailing wildcard
35379 [/(\^|\\\/)?\\\*$/, (_, p1) => {
35380 const prefix = p1 // '\^':
35381 // '/*' does not match ''
35382 // '/*' does not match everything
35384 // 'abc/*' does not match 'abc/'
35385 ? `${p1}[^/]+` // 'a*' matches 'a'
35386 // 'a*' matches 'aa'
35388 return `${prefix}(?=$|\\/$)`;
35390 /\\\\\\/g, () => '\\']]; // A simple cache, because an ignore rule only has only one certain meaning
35392 const regexCache = Object.create(null); // @param {pattern}
35394 const makeRegex = (pattern, negative, ignorecase) => {
35395 const r = regexCache[pattern];
35399 } // const replacers = negative
35400 // ? NEGATIVE_REPLACERS
35401 // : POSITIVE_REPLACERS
35404 const source = REPLACERS.reduce((prev, current) => prev.replace(current[0], current[1].bind(pattern)), pattern);
35405 return regexCache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source);
35408 const isString = subject => typeof subject === 'string'; // > A blank line matches no files, so it can serve as a separator for readability.
35411 const checkPattern$1 = pattern => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment.
35412 && pattern.indexOf('#') !== 0;
35414 const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF);
35417 constructor(origin, pattern, negative, regex) {
35418 this.origin = origin;
35419 this.pattern = pattern;
35420 this.negative = negative;
35421 this.regex = regex;
35426 const createRule$1 = (pattern, ignorecase) => {
35427 const origin = pattern;
35428 let negative = false; // > An optional prefix "!" which negates the pattern;
35430 if (pattern.indexOf('!') === 0) {
35432 pattern = pattern.substr(1);
35435 pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that
35436 // > begin with a literal "!", for example, `"\!important!.txt"`.
35437 .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that
35438 // > begin with a hash.
35439 .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#');
35440 const regex = makeRegex(pattern, negative, ignorecase);
35441 return new IgnoreRule(origin, pattern, negative, regex);
35444 const throwError = (message, Ctor) => {
35445 throw new Ctor(message);
35448 const checkPath = (path, originalPath, doThrow) => {
35449 if (!isString(path)) {
35450 return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
35451 } // We don't know if we should ignore '', so throw
35455 return doThrow(`path must not be empty`, TypeError);
35456 } // Check if it is a relative path
35459 if (checkPath.isNotRelative(path)) {
35460 const r = '`path.relative()`d';
35461 return doThrow(`path should be a ${r} string, but got "${originalPath}"`, RangeError);
35467 const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path);
35469 checkPath.isNotRelative = isNotRelative;
35471 checkPath.convert = p => p;
35478 this._ignorecase = ignorecase;
35479 define$1(this, KEY_IGNORE$1, true);
35485 this._ignoreCache = Object.create(null);
35486 this._testCache = Object.create(null);
35489 _addPattern(pattern) {
35491 if (pattern && pattern[KEY_IGNORE$1]) {
35492 this._rules = this._rules.concat(pattern._rules);
35493 this._added = true;
35497 if (checkPattern$1(pattern)) {
35498 const rule = createRule$1(pattern, this._ignorecase);
35499 this._added = true;
35501 this._rules.push(rule);
35503 } // @param {Array<string> | string | Ignore} pattern
35507 this._added = false;
35508 makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore,
35509 // making the behavior changed.
35519 addPattern(pattern) {
35520 return this.add(pattern);
35521 } // | ignored : unignored
35522 // negative | 0:0 | 0:1 | 1:0 | 1:1
35523 // -------- | ------- | ------- | ------- | --------
35524 // 0 | TEST | TEST | SKIP | X
35525 // 1 | TESTIF | SKIP | TEST | X
35526 // - SKIP: always skip
35527 // - TEST: always test
35528 // - TESTIF: only test if checkUnignored
35529 // - X: that never happen
35530 // @param {boolean} whether should check if the path is unignored,
35531 // setting `checkUnignored` to `false` could reduce additional
35533 // @returns {TestResult} true if a file is ignored
35536 _testOne(path, checkUnignored) {
35537 let ignored = false;
35538 let unignored = false;
35540 this._rules.forEach(rule => {
35545 if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
35549 const matched = rule.regex.test(path);
35552 ignored = !negative;
35553 unignored = negative;
35561 } // @returns {TestResult}
35564 _test(originalPath, cache, checkUnignored, slices) {
35565 const path = originalPath // Supports nullable path
35566 && checkPath.convert(originalPath);
35567 checkPath(path, originalPath, throwError);
35568 return this._t(path, cache, checkUnignored, slices);
35571 _t(path, cache, checkUnignored, slices) {
35572 if (path in cache) {
35573 return cache[path];
35578 // ['path', 'to', 'a.js']
35579 slices = path.split(SLASH$1);
35582 slices.pop(); // If the path has no parent directory, just test it
35584 if (!slices.length) {
35585 return cache[path] = this._testOne(path, checkUnignored);
35588 const parent = this._t(slices.join(SLASH$1) + SLASH$1, cache, checkUnignored, slices); // If the path contains a parent directory, check the parent first
35591 return cache[path] = parent.ignored // > It is not possible to re-include a file if a parent directory of
35592 // > that file is excluded.
35593 ? parent : this._testOne(path, checkUnignored);
35597 return this._test(path, this._ignoreCache, false).ignored;
35601 return path => !this.ignores(path);
35605 return makeArray(paths).filter(this.createFilter());
35606 } // @returns {TestResult}
35610 return this._test(path, this._testCache, true);
35615 const factory = options => new Ignore(options);
35617 const returnFalse = () => false;
35619 const isPathValid = path => checkPath(path && checkPath.convert(path), path, returnFalse);
35621 factory.isPathValid = isPathValid; // Fixes typescript
35623 factory.default = factory;
35624 var ignore$1 = factory; // Windows
35625 // --------------------------------------------------------------
35627 /* istanbul ignore if */
35629 if ( // Detect `process` so that it can run in browsers.
35630 typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
35631 /* eslint no-control-regex: "off" */
35632 const makePosix = str => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, '/');
35634 checkPath.convert = makePosix; // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/'
35637 const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
35639 checkPath.isNotRelative = path => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);
35642 var slash$1 = path => {
35643 const isExtendedLengthPath = /^\\\\\?\\/.test(path);
35644 const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex
35646 if (isExtendedLengthPath || hasNonAscii) {
35650 return path.replace(/\\/g, '/');
35654 promisify: promisify$1
35656 const DEFAULT_IGNORE = ['**/node_modules/**', '**/flow-typed/**', '**/coverage/**', '**/.git'];
35657 const readFileP = promisify$1(fs$3.readFile);
35659 const mapGitIgnorePatternTo = base => ignore => {
35660 if (ignore.startsWith('!')) {
35661 return '!' + path$2.posix.join(base, ignore.slice(1));
35664 return path$2.posix.join(base, ignore);
35667 const parseGitIgnore = (content, options) => {
35668 const base = slash$1(path$2.relative(options.cwd, path$2.dirname(options.fileName)));
35669 return content.split(/\r?\n/).filter(Boolean).filter(line => !line.startsWith('#')).map(mapGitIgnorePatternTo(base));
35672 const reduceIgnore = files => {
35673 return files.reduce((ignores, file) => {
35674 ignores.add(parseGitIgnore(file.content, {
35676 fileName: file.filePath
35682 const ensureAbsolutePathForCwd = (cwd, p) => {
35683 if (path$2.isAbsolute(p)) {
35684 if (p.startsWith(cwd)) {
35688 throw new Error(`Path ${p} is not in cwd ${cwd}`);
35691 return path$2.join(cwd, p);
35694 const getIsIgnoredPredecate = (ignores, cwd) => {
35695 return p => ignores.ignores(slash$1(path$2.relative(cwd, ensureAbsolutePathForCwd(cwd, p))));
35698 const getFile = async (file, cwd) => {
35699 const filePath = path$2.join(cwd, file);
35700 const content = await readFileP(filePath, 'utf8');
35708 const getFileSync = (file, cwd) => {
35709 const filePath = path$2.join(cwd, file);
35710 const content = fs$3.readFileSync(filePath, 'utf8');
35718 const normalizeOptions$3 = ({
35720 cwd = slash$1(process.cwd())
35728 var gitignore = async options => {
35729 options = normalizeOptions$3(options);
35730 const paths = await out$3('**/.gitignore', {
35731 ignore: DEFAULT_IGNORE.concat(options.ignore),
35734 const files = await Promise.all(paths.map(file => getFile(file, options.cwd)));
35735 const ignores = reduceIgnore(files);
35736 return getIsIgnoredPredecate(ignores, options.cwd);
35739 var sync$8 = options => {
35740 options = normalizeOptions$3(options);
35741 const paths = out$3.sync('**/.gitignore', {
35742 ignore: DEFAULT_IGNORE.concat(options.ignore),
35745 const files = paths.map(file => getFileSync(file, options.cwd));
35746 const ignores = reduceIgnore(files);
35747 return getIsIgnoredPredecate(ignores, options.cwd);
35749 gitignore.sync = sync$8;
35755 class ObjectTransform extends Transform {
35764 class FilterStream extends ObjectTransform {
35765 constructor(filter) {
35767 this._filter = filter;
35770 _transform(data, encoding, callback) {
35771 if (this._filter(data)) {
35780 class UniqueStream extends ObjectTransform {
35783 this._pushed = new Set();
35786 _transform(data, encoding, callback) {
35787 if (!this._pushed.has(data)) {
35790 this._pushed.add(data);
35798 var streamUtils = {
35804 FilterStream: FilterStream$1,
35805 UniqueStream: UniqueStream$1
35808 const DEFAULT_FILTER = () => false;
35810 const isNegative = pattern => pattern[0] === '!';
35812 const assertPatternsInput$1 = patterns => {
35813 if (!patterns.every(pattern => typeof pattern === 'string')) {
35814 throw new TypeError('Patterns must be a string or an array of strings');
35818 const checkCwdOption = (options = {}) => {
35819 if (!options.cwd) {
35826 stat = fs$3.statSync(options.cwd);
35831 if (!stat.isDirectory()) {
35832 throw new Error('The `cwd` option must be a path to a directory');
35836 const getPathString = p => p.stats instanceof fs$3.Stats ? p.path : p;
35838 const generateGlobTasks = (patterns, taskOptions) => {
35839 patterns = arrayUnion([].concat(patterns));
35840 assertPatternsInput$1(patterns);
35841 checkCwdOption(taskOptions);
35842 const globTasks = [];
35843 taskOptions = Object.assign({
35845 expandDirectories: true
35848 for (const [index, pattern] of patterns.entries()) {
35849 if (isNegative(pattern)) {
35853 const ignore = patterns.slice(index).filter(isNegative).map(pattern => pattern.slice(1));
35854 const options = Object.assign({}, taskOptions, {
35855 ignore: taskOptions.ignore.concat(ignore)
35866 const globDirs = (task, fn) => {
35869 if (task.options.cwd) {
35870 options.cwd = task.options.cwd;
35873 if (Array.isArray(task.options.expandDirectories)) {
35874 options = Object.assign({}, options, {
35875 files: task.options.expandDirectories
35877 } else if (typeof task.options.expandDirectories === 'object') {
35878 options = Object.assign({}, options, {}, task.options.expandDirectories);
35881 return fn(task.pattern, options);
35884 const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern];
35886 const getFilterSync = options => {
35887 return options && options.gitignore ? gitignore.sync({
35889 ignore: options.ignore
35890 }) : DEFAULT_FILTER;
35893 const globToTask = task => glob => {
35898 if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) {
35899 options.ignore = dirGlob.sync(options.ignore);
35908 var globby$1 = async (patterns, options) => {
35909 const globTasks = generateGlobTasks(patterns, options);
35911 const getFilter = async () => {
35912 return options && options.gitignore ? gitignore({
35914 ignore: options.ignore
35915 }) : DEFAULT_FILTER;
35918 const getTasks = async () => {
35919 const tasks = await Promise.all(globTasks.map(async task => {
35920 const globs = await getPattern(task, dirGlob);
35921 return Promise.all(globs.map(globToTask(task)));
35923 return arrayUnion(...tasks);
35926 const [filter, tasks] = await Promise.all([getFilter(), getTasks()]);
35927 const paths = await Promise.all(tasks.map(task => out$3(task.pattern, task.options)));
35928 return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_)));
35931 var sync$9 = (patterns, options) => {
35932 const globTasks = generateGlobTasks(patterns, options);
35933 const tasks = globTasks.reduce((tasks, task) => {
35934 const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
35935 return tasks.concat(newTask);
35937 const filter = getFilterSync(options);
35938 return tasks.reduce((matches, task) => arrayUnion(matches, out$3.sync(task.pattern, task.options)), []).filter(path_ => !filter(path_));
35941 var stream$5 = (patterns, options) => {
35942 const globTasks = generateGlobTasks(patterns, options);
35943 const tasks = globTasks.reduce((tasks, task) => {
35944 const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
35945 return tasks.concat(newTask);
35947 const filter = getFilterSync(options);
35948 const filterStream = new FilterStream$1(p => !filter(p));
35949 const uniqueStream = new UniqueStream$1();
35950 return merge2_1(tasks.map(task => out$3.stream(task.pattern, task.options))).pipe(filterStream).pipe(uniqueStream);
35953 var generateGlobTasks_1 = generateGlobTasks;
35955 var hasMagic = (patterns, options) => [].concat(patterns).some(pattern => out$3.isDynamicPattern(pattern, options));
35957 var gitignore_1 = gitignore;
35958 globby$1.sync = sync$9;
35959 globby$1.stream = stream$5;
35960 globby$1.generateGlobTasks = generateGlobTasks_1;
35961 globby$1.hasMagic = hasMagic;
35962 globby$1.gitignore = gitignore_1;
35965 addLeadingComment: addLeadingComment$3,
35966 addTrailingComment: addTrailingComment$3,
35967 addDanglingComment: addDanglingComment$3,
35968 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$2
35971 function handleOwnLineComment(comment, text, options, ast, isLastComment) {
35977 return handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleMemberExpressionComments(enclosingNode, followingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleImportSpecifierComments(enclosingNode, comment) || handleForComments(enclosingNode, precedingNode, comment) || handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) || handleAssignmentPatternComments(enclosingNode, comment) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) || handleLabeledStatementComments(enclosingNode, comment);
35980 function handleEndOfLineComment(comment, text, options, ast, isLastComment) {
35986 return handleClosureTypeCastComments(followingNode, comment) || handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) || handleImportSpecifierComments(enclosingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleLabeledStatementComments(enclosingNode, comment) || handleCallExpressionComments(precedingNode, enclosingNode, comment) || handlePropertyComments(enclosingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleTypeAliasComments(enclosingNode, followingNode, comment) || handleVariableDeclaratorComments(enclosingNode, followingNode, comment);
35989 function handleRemainingComment(comment, text, options, ast, isLastComment) {
35996 if (handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) || handleCommentInEmptyParens(text, enclosingNode, comment, options) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleCommentAfterArrowParams(text, enclosingNode, comment, options) || handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) || handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) || handleBreakAndContinueStatementComments(enclosingNode, comment) || handleTSFunctionTrailingComments(text, enclosingNode, followingNode, comment, options)) {
36003 function addBlockStatementFirstComment(node, comment) {
36004 const body = node.body.filter(n => n.type !== "EmptyStatement");
36006 if (body.length === 0) {
36007 addDanglingComment$3(node, comment);
36009 addLeadingComment$3(body[0], comment);
36013 function addBlockOrNotComment(node, comment) {
36014 if (node.type === "BlockStatement") {
36015 addBlockStatementFirstComment(node, comment);
36017 addLeadingComment$3(node, comment);
36021 function handleClosureTypeCastComments(followingNode, comment) {
36022 if (followingNode && isTypeCastComment(comment)) {
36023 addLeadingComment$3(followingNode, comment);
36028 } // There are often comments before the else clause of if statements like
36034 // They are being attached as leading comments of the BlockExpression which
36035 // is not well printed. What we want is to instead move the comment inside
36036 // of the block and make it leadingComment of the first element of the block
36037 // or dangling comment of the block if there is nothing inside
36046 function handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
36047 if (!enclosingNode || enclosingNode.type !== "IfStatement" || !followingNode) {
36049 } // We unfortunately have no way using the AST or location of nodes to know
36050 // if the comment is positioned before the condition parenthesis:
36051 // if (a /* comment */) {}
36052 // The only workaround I found is to look at the next character to see if
36056 const nextCharacter = util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd);
36058 if (nextCharacter === ")") {
36059 addTrailingComment$3(precedingNode, comment);
36061 } // Comments before `else`:
36062 // - treat as trailing comments of the consequent, if it's a BlockStatement
36063 // - treat as a dangling comment otherwise
36066 if (precedingNode === enclosingNode.consequent && followingNode === enclosingNode.alternate) {
36067 if (precedingNode.type === "BlockStatement") {
36068 addTrailingComment$3(precedingNode, comment);
36070 addDanglingComment$3(enclosingNode, comment);
36076 if (followingNode.type === "BlockStatement") {
36077 addBlockStatementFirstComment(followingNode, comment);
36081 if (followingNode.type === "IfStatement") {
36082 addBlockOrNotComment(followingNode.consequent, comment);
36084 } // For comments positioned after the condition parenthesis in an if statement
36085 // before the consequent without brackets on, such as
36086 // if (a) /* comment */ true,
36087 // we look at the next character to see if the following node
36088 // is the consequent for the if statement
36091 if (enclosingNode.consequent === followingNode) {
36092 addLeadingComment$3(followingNode, comment);
36099 function handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
36100 if (!enclosingNode || enclosingNode.type !== "WhileStatement" || !followingNode) {
36102 } // We unfortunately have no way using the AST or location of nodes to know
36103 // if the comment is positioned before the condition parenthesis:
36104 // while (a /* comment */) {}
36105 // The only workaround I found is to look at the next character to see if
36109 const nextCharacter = util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd);
36111 if (nextCharacter === ")") {
36112 addTrailingComment$3(precedingNode, comment);
36116 if (followingNode.type === "BlockStatement") {
36117 addBlockStatementFirstComment(followingNode, comment);
36122 } // Same as IfStatement but for TryStatement
36125 function handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) {
36126 if (!enclosingNode || enclosingNode.type !== "TryStatement" && enclosingNode.type !== "CatchClause" || !followingNode) {
36130 if (enclosingNode.type === "CatchClause" && precedingNode) {
36131 addTrailingComment$3(precedingNode, comment);
36135 if (followingNode.type === "BlockStatement") {
36136 addBlockStatementFirstComment(followingNode, comment);
36140 if (followingNode.type === "TryStatement") {
36141 addBlockOrNotComment(followingNode.finalizer, comment);
36145 if (followingNode.type === "CatchClause") {
36146 addBlockOrNotComment(followingNode.body, comment);
36153 function handleMemberExpressionComments(enclosingNode, followingNode, comment) {
36154 if (enclosingNode && (enclosingNode.type === "MemberExpression" || enclosingNode.type === "OptionalMemberExpression") && followingNode && followingNode.type === "Identifier") {
36155 addLeadingComment$3(enclosingNode, comment);
36162 function handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) {
36163 const isSameLineAsPrecedingNode = precedingNode && !util$1.hasNewlineInRange(text, options.locEnd(precedingNode), options.locStart(comment));
36165 if ((!precedingNode || !isSameLineAsPrecedingNode) && enclosingNode && enclosingNode.type === "ConditionalExpression" && followingNode) {
36166 addLeadingComment$3(followingNode, comment);
36173 function handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) {
36174 if (enclosingNode && (enclosingNode.type === "ObjectProperty" || enclosingNode.type === "Property") && enclosingNode.shorthand && enclosingNode.key === precedingNode && enclosingNode.value.type === "AssignmentPattern") {
36175 addTrailingComment$3(enclosingNode.value.left, comment);
36182 function handleClassComments(enclosingNode, precedingNode, followingNode, comment) {
36183 if (enclosingNode && (enclosingNode.type === "ClassDeclaration" || enclosingNode.type === "ClassExpression") && enclosingNode.decorators && enclosingNode.decorators.length > 0 && !(followingNode && followingNode.type === "Decorator")) {
36184 if (!enclosingNode.decorators || enclosingNode.decorators.length === 0) {
36185 addLeadingComment$3(enclosingNode, comment);
36187 addTrailingComment$3(enclosingNode.decorators[enclosingNode.decorators.length - 1], comment);
36196 function handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) {
36197 // This is only needed for estree parsers (flow, typescript) to attach
36198 // after a method name:
36199 // obj = { fn /*comment*/() {} };
36200 if (enclosingNode && precedingNode && ( // "MethodDefinition" is handled in getCommentChildNodes
36201 enclosingNode.type === "Property" || enclosingNode.type === "TSDeclareMethod" || enclosingNode.type === "TSAbstractMethodDefinition") && precedingNode.type === "Identifier" && enclosingNode.key === precedingNode && // special Property case: { key: /*comment*/(value) };
36202 // comment should be attached to value instead of key
36203 util$1.getNextNonSpaceNonCommentCharacter(text, precedingNode, options.locEnd) !== ":") {
36204 addTrailingComment$3(precedingNode, comment);
36206 } // Print comments between decorators and class methods as a trailing comment
36207 // on the decorator node instead of the method node
36210 if (precedingNode && enclosingNode && precedingNode.type === "Decorator" && (enclosingNode.type === "ClassMethod" || enclosingNode.type === "ClassProperty" || enclosingNode.type === "TSAbstractClassProperty" || enclosingNode.type === "TSAbstractMethodDefinition" || enclosingNode.type === "TSDeclareMethod" || enclosingNode.type === "MethodDefinition")) {
36211 addTrailingComment$3(precedingNode, comment);
36218 function handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) {
36219 if (util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== "(") {
36223 if (precedingNode && enclosingNode && (enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ClassMethod" || enclosingNode.type === "MethodDefinition" || enclosingNode.type === "ObjectMethod")) {
36224 addTrailingComment$3(precedingNode, comment);
36231 function handleCommentAfterArrowParams(text, enclosingNode, comment, options) {
36232 if (!(enclosingNode && enclosingNode.type === "ArrowFunctionExpression")) {
36236 const index = getNextNonSpaceNonCommentCharacterIndex$2(text, comment, options.locEnd);
36238 if (text.slice(index, index + 2) === "=>") {
36239 addDanglingComment$3(enclosingNode, comment);
36246 function handleCommentInEmptyParens(text, enclosingNode, comment, options) {
36247 if (util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== ")") {
36249 } // Only add dangling comments to fix the case when no params are present,
36250 // i.e. a function without any argument.
36253 if (enclosingNode && (isRealFunctionLikeNode(enclosingNode) && // `params` vs `parameters` - see https://github.com/babel/babel/issues/9231
36254 (enclosingNode.params || enclosingNode.parameters).length === 0 || (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression" || enclosingNode.type === "NewExpression") && enclosingNode.arguments.length === 0)) {
36255 addDanglingComment$3(enclosingNode, comment);
36259 if (enclosingNode && enclosingNode.type === "MethodDefinition" && enclosingNode.value.params.length === 0) {
36260 addDanglingComment$3(enclosingNode.value, comment);
36267 function handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
36268 // Flow function type definitions
36269 if (precedingNode && precedingNode.type === "FunctionTypeParam" && enclosingNode && enclosingNode.type === "FunctionTypeAnnotation" && followingNode && followingNode.type !== "FunctionTypeParam") {
36270 addTrailingComment$3(precedingNode, comment);
36272 } // Real functions and TypeScript function type definitions
36275 if (precedingNode && (precedingNode.type === "Identifier" || precedingNode.type === "AssignmentPattern") && enclosingNode && isRealFunctionLikeNode(enclosingNode) && util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) === ")") {
36276 addTrailingComment$3(precedingNode, comment);
36280 if (enclosingNode && enclosingNode.type === "FunctionDeclaration" && followingNode && followingNode.type === "BlockStatement") {
36281 const functionParamRightParenIndex = (() => {
36282 if ((enclosingNode.params || enclosingNode.parameters).length !== 0) {
36283 return util$1.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(util$1.getLast(enclosingNode.params || enclosingNode.parameters)));
36286 const functionParamLeftParenIndex = util$1.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(enclosingNode.id));
36287 return util$1.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, functionParamLeftParenIndex + 1);
36290 if (options.locStart(comment) > functionParamRightParenIndex) {
36291 addBlockStatementFirstComment(followingNode, comment);
36299 function handleImportSpecifierComments(enclosingNode, comment) {
36300 if (enclosingNode && enclosingNode.type === "ImportSpecifier") {
36301 addLeadingComment$3(enclosingNode, comment);
36308 function handleLabeledStatementComments(enclosingNode, comment) {
36309 if (enclosingNode && enclosingNode.type === "LabeledStatement") {
36310 addLeadingComment$3(enclosingNode, comment);
36317 function handleBreakAndContinueStatementComments(enclosingNode, comment) {
36318 if (enclosingNode && (enclosingNode.type === "ContinueStatement" || enclosingNode.type === "BreakStatement") && !enclosingNode.label) {
36319 addTrailingComment$3(enclosingNode, comment);
36326 function handleCallExpressionComments(precedingNode, enclosingNode, comment) {
36327 if (enclosingNode && (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression") && precedingNode && enclosingNode.callee === precedingNode && enclosingNode.arguments.length > 0) {
36328 addLeadingComment$3(enclosingNode.arguments[0], comment);
36335 function handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) {
36336 if (enclosingNode && (enclosingNode.type === "UnionTypeAnnotation" || enclosingNode.type === "TSUnionType")) {
36337 if (util$1.isNodeIgnoreComment(comment)) {
36338 followingNode.prettierIgnore = true;
36339 comment.unignore = true;
36342 if (precedingNode) {
36343 addTrailingComment$3(precedingNode, comment);
36350 if (followingNode && (followingNode.type === "UnionTypeAnnotation" || followingNode.type === "TSUnionType") && util$1.isNodeIgnoreComment(comment)) {
36351 followingNode.types[0].prettierIgnore = true;
36352 comment.unignore = true;
36358 function handlePropertyComments(enclosingNode, comment) {
36359 if (enclosingNode && (enclosingNode.type === "Property" || enclosingNode.type === "ObjectProperty")) {
36360 addLeadingComment$3(enclosingNode, comment);
36367 function handleOnlyComments(enclosingNode, ast, comment, isLastComment) {
36368 // With Flow the enclosingNode is undefined so use the AST instead.
36369 if (ast && ast.body && ast.body.length === 0) {
36370 if (isLastComment) {
36371 addDanglingComment$3(ast, comment);
36373 addLeadingComment$3(ast, comment);
36377 } else if (enclosingNode && enclosingNode.type === "Program" && enclosingNode.body.length === 0 && enclosingNode.directives && enclosingNode.directives.length === 0) {
36378 if (isLastComment) {
36379 addDanglingComment$3(enclosingNode, comment);
36381 addLeadingComment$3(enclosingNode, comment);
36390 function handleForComments(enclosingNode, precedingNode, comment) {
36391 if (enclosingNode && (enclosingNode.type === "ForInStatement" || enclosingNode.type === "ForOfStatement")) {
36392 addLeadingComment$3(enclosingNode, comment);
36399 function handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) {
36400 if (precedingNode && precedingNode.type === "ImportSpecifier" && enclosingNode && enclosingNode.type === "ImportDeclaration" && util$1.hasNewline(text, options.locEnd(comment))) {
36401 addTrailingComment$3(precedingNode, comment);
36408 function handleAssignmentPatternComments(enclosingNode, comment) {
36409 if (enclosingNode && enclosingNode.type === "AssignmentPattern") {
36410 addLeadingComment$3(enclosingNode, comment);
36417 function handleTypeAliasComments(enclosingNode, followingNode, comment) {
36418 if (enclosingNode && enclosingNode.type === "TypeAlias") {
36419 addLeadingComment$3(enclosingNode, comment);
36426 function handleVariableDeclaratorComments(enclosingNode, followingNode, comment) {
36427 if (enclosingNode && (enclosingNode.type === "VariableDeclarator" || enclosingNode.type === "AssignmentExpression") && followingNode && (followingNode.type === "ObjectExpression" || followingNode.type === "ArrayExpression" || followingNode.type === "TemplateLiteral" || followingNode.type === "TaggedTemplateExpression" || isBlockComment(comment))) {
36428 addLeadingComment$3(followingNode, comment);
36435 function handleTSFunctionTrailingComments(text, enclosingNode, followingNode, comment, options) {
36436 if (!followingNode && enclosingNode && (enclosingNode.type === "TSMethodSignature" || enclosingNode.type === "TSDeclareFunction" || enclosingNode.type === "TSAbstractMethodDefinition") && util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) === ";") {
36437 addTrailingComment$3(enclosingNode, comment);
36444 function handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) {
36445 if (!enclosingNode || enclosingNode.type !== "TSMappedType") {
36449 if (followingNode && followingNode.type === "TSTypeParameter" && followingNode.name) {
36450 addLeadingComment$3(followingNode.name, comment);
36454 if (precedingNode && precedingNode.type === "TSTypeParameter" && precedingNode.constraint) {
36455 addTrailingComment$3(precedingNode.constraint, comment);
36462 function isBlockComment(comment) {
36463 return comment.type === "Block" || comment.type === "CommentBlock";
36466 function hasLeadingComment(node, fn = () => true) {
36467 if (node.leadingComments) {
36468 return node.leadingComments.some(fn);
36471 if (node.comments) {
36472 return node.comments.some(comment => comment.leading && fn(comment));
36478 function isRealFunctionLikeNode(node) {
36479 return node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression" || node.type === "FunctionDeclaration" || node.type === "ObjectMethod" || node.type === "ClassMethod" || node.type === "TSDeclareFunction" || node.type === "TSCallSignatureDeclaration" || node.type === "TSConstructSignatureDeclaration" || node.type === "TSConstructSignatureDeclaration" || node.type === "TSMethodSignature" || node.type === "TSConstructorType" || node.type === "TSFunctionType" || node.type === "TSDeclareMethod";
36482 function getGapRegex(enclosingNode) {
36483 if (enclosingNode && enclosingNode.type !== "BinaryExpression" && enclosingNode.type !== "LogicalExpression") {
36484 // Support degenerate single-element unions and intersections.
36485 // E.g.: `type A = /* 1 */ & B`
36486 return /^[\s(&|]*$/;
36490 function getCommentChildNodes(node, options) {
36491 // Prevent attaching comments to FunctionExpression in this case:
36493 // bar() // comment
36498 if ((options.parser === "typescript" || options.parser === "flow") && node.type === "MethodDefinition" && node.value && node.value.type === "FunctionExpression" && node.value.params.length === 0 && !node.value.returnType && (!node.value.typeParameters || node.value.typeParameters.length === 0) && node.value.body) {
36499 return [...(node.decorators || []), node.key, node.value.body];
36503 function isTypeCastComment(comment) {
36504 return isBlockComment(comment) && comment.value[0] === "*" && // TypeScript expects the type to be enclosed in curly brackets, however
36505 // Closure Compiler accepts types in parens and even without any delimiters at all.
36506 // That's why we just search for "@type".
36507 /@type\b/.test(comment.value);
36511 handleOwnLineComment,
36512 handleEndOfLineComment,
36513 handleRemainingComment,
36518 getCommentChildNodes
36522 isBlockComment: isBlockComment$1,
36523 hasLeadingComment: hasLeadingComment$1
36530 hardline: hardline$3,
36531 softline: softline$1,
36532 literalline: literalline$1,
36535 dedentToRoot: dedentToRoot$1
36539 stripTrailingHardline: stripTrailingHardline$1
36543 function embed(path, print, textToDoc, options) {
36544 const node = path.getValue();
36545 const parent = path.getParentNode();
36546 const parentParent = path.getParentNode(1);
36548 switch (node.type) {
36549 case "TemplateLiteral":
36551 const isCss = [isStyledJsx, isStyledComponents, isCssProp, isAngularComponentStyles].some(isIt => isIt(path));
36554 // Get full template literal with expressions replaced by placeholders
36555 const rawQuasis = node.quasis.map(q => q.value.raw);
36556 let placeholderID = 0;
36557 const text = rawQuasis.reduce((prevVal, currVal, idx) => {
36558 return idx === 0 ? currVal : prevVal + "@prettier-placeholder-" + placeholderID++ + "-id" + currVal;
36560 const doc = textToDoc(text, {
36563 return transformCssDoc(doc, path, print);
36566 * react-relay and graphql-tag
36568 * graphql.experimental`...`
36571 * This intentionally excludes Relay Classic tags, as Prettier does not
36572 * support Relay Classic formatting.
36576 if (isGraphQL(path)) {
36577 const expressionDocs = node.expressions ? path.map(print, "expressions") : [];
36578 const numQuasis = node.quasis.length;
36580 if (numQuasis === 1 && node.quasis[0].value.raw.trim() === "") {
36586 for (let i = 0; i < numQuasis; i++) {
36587 const templateElement = node.quasis[i];
36588 const isFirst = i === 0;
36589 const isLast = i === numQuasis - 1;
36590 const text = templateElement.value.cooked; // Bail out if any of the quasis have an invalid escape sequence
36591 // (which would make the `cooked` value be `null` or `undefined`)
36593 if (typeof text !== "string") {
36597 const lines = text.split("\n");
36598 const numLines = lines.length;
36599 const expressionDoc = expressionDocs[i];
36600 const startsWithBlankLine = numLines > 2 && lines[0].trim() === "" && lines[1].trim() === "";
36601 const endsWithBlankLine = numLines > 2 && lines[numLines - 1].trim() === "" && lines[numLines - 2].trim() === "";
36602 const commentsAndWhitespaceOnly = lines.every(line => /^\s*(?:#[^\r\n]*)?$/.test(line)); // Bail out if an interpolation occurs within a comment.
36604 if (!isLast && /#[^\r\n]*$/.test(lines[numLines - 1])) {
36610 if (commentsAndWhitespaceOnly) {
36611 doc = printGraphqlComments(lines);
36613 doc = stripTrailingHardline$1(textToDoc(text, {
36619 doc = escapeTemplateCharacters(doc, false);
36621 if (!isFirst && startsWithBlankLine) {
36627 if (!isLast && endsWithBlankLine) {
36630 } else if (!isFirst && !isLast && startsWithBlankLine) {
36634 if (expressionDoc) {
36635 parts.push(concat$4(["${", expressionDoc, "}"]));
36639 return concat$4(["`", indent$2(concat$4([hardline$3, join$2(hardline$3, parts)])), hardline$3, "`"]);
36642 const htmlParser = isHtml(path) ? "html" : isAngularComponentTemplate(path) ? "angular" : undefined;
36645 return printHtmlTemplateLiteral(path, print, textToDoc, htmlParser, options);
36651 case "TemplateElement":
36657 if (parentParent && parentParent.type === "TaggedTemplateExpression" && parent.quasis.length === 1 && parentParent.tag.type === "Identifier" && (parentParent.tag.name === "md" || parentParent.tag.name === "markdown")) {
36658 const text = parent.quasis[0].value.raw.replace(/((?:\\\\)*)\\`/g, (_, backslashes) => "\\".repeat(backslashes.length / 2) + "`");
36659 const indentation = getIndentation(text);
36660 const hasIndent = indentation !== "";
36661 return concat$4([hasIndent ? indent$2(concat$4([softline$1, printMarkdown(text.replace(new RegExp(`^${indentation}`, "gm"), ""))])) : concat$4([literalline$1, dedentToRoot$1(printMarkdown(text))]), softline$1]);
36668 function printMarkdown(text) {
36669 const doc = textToDoc(text, {
36670 parser: "markdown",
36671 __inJsTemplate: true
36673 return stripTrailingHardline$1(escapeTemplateCharacters(doc, true));
36677 function getIndentation(str) {
36678 const firstMatchedIndent = str.match(/^([^\S\n]*)\S/m);
36679 return firstMatchedIndent === null ? "" : firstMatchedIndent[1];
36682 function uncook(cookedValue) {
36683 return cookedValue.replace(/([\\`]|\$\{)/g, "\\$1");
36686 function escapeTemplateCharacters(doc, raw) {
36687 return mapDoc$1(doc, currentDoc => {
36688 if (!currentDoc.parts) {
36693 currentDoc.parts.forEach(part => {
36694 if (typeof part === "string") {
36695 parts.push(raw ? part.replace(/(\\*)`/g, "$1$1\\`") : uncook(part));
36700 return Object.assign({}, currentDoc, {
36706 function transformCssDoc(quasisDoc, path, print) {
36707 const parentNode = path.getValue();
36708 const isEmpty = parentNode.quasis.length === 1 && !parentNode.quasis[0].value.raw.trim();
36714 const expressionDocs = parentNode.expressions ? path.map(print, "expressions") : [];
36715 const newDoc = replacePlaceholders(quasisDoc, expressionDocs);
36716 /* istanbul ignore if */
36719 throw new Error("Couldn't insert all the expressions");
36722 return concat$4(["`", indent$2(concat$4([hardline$3, stripTrailingHardline$1(newDoc)])), softline$1, "`"]);
36723 } // Search all the placeholders in the quasisDoc tree
36724 // and replace them with the expression docs one by one
36725 // returns a new doc with all the placeholders replaced,
36726 // or null if it couldn't replace any expression
36729 function replacePlaceholders(quasisDoc, expressionDocs) {
36730 if (!expressionDocs || !expressionDocs.length) {
36734 const expressions = expressionDocs.slice();
36735 let replaceCounter = 0;
36736 const newDoc = mapDoc$1(quasisDoc, doc => {
36737 if (!doc || !doc.parts || !doc.parts.length) {
36744 const atIndex = parts.indexOf("@");
36745 const placeholderIndex = atIndex + 1;
36747 if (atIndex > -1 && typeof parts[placeholderIndex] === "string" && parts[placeholderIndex].startsWith("prettier-placeholder")) {
36748 // If placeholder is split, join it
36749 const at = parts[atIndex];
36750 const placeholder = parts[placeholderIndex];
36751 const rest = parts.slice(placeholderIndex + 1);
36752 parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest);
36755 const atPlaceholderIndex = parts.findIndex(part => typeof part === "string" && part.startsWith("@prettier-placeholder"));
36757 if (atPlaceholderIndex > -1) {
36758 const placeholder = parts[atPlaceholderIndex];
36759 const rest = parts.slice(atPlaceholderIndex + 1);
36760 const placeholderMatch = placeholder.match(/@prettier-placeholder-(.+)-id([\s\S]*)/);
36761 const placeholderID = placeholderMatch[1]; // When the expression has a suffix appended, like:
36762 // animation: linear ${time}s ease-out;
36764 const suffix = placeholderMatch[2];
36765 const expression = expressions[placeholderID];
36767 parts = parts.slice(0, atPlaceholderIndex).concat(["${", expression, "}" + suffix]).concat(rest);
36770 return Object.assign({}, doc, {
36774 return expressions.length === replaceCounter ? newDoc : null;
36777 function printGraphqlComments(lines) {
36779 let seenComment = false;
36780 lines.map(textLine => textLine.trim()).forEach((textLine, i, array) => {
36781 // Lines are either whitespace only, or a comment (with potential whitespace
36782 // around it). Drop whitespace-only lines.
36783 if (textLine === "") {
36787 if (array[i - 1] === "" && seenComment) {
36788 // If a non-first comment is preceded by a blank (whitespace only) line,
36789 // add in a blank line.
36790 parts.push(concat$4([hardline$3, textLine]));
36792 parts.push(textLine);
36795 seenComment = true;
36796 }); // If `lines` was whitespace only, return `null`.
36798 return parts.length === 0 ? null : join$2(hardline$3, parts);
36801 * Template literal in these contexts:
36802 * <style jsx>{`div{color:red}`}</style>
36809 function isStyledJsx(path) {
36810 const node = path.getValue();
36811 const parent = path.getParentNode();
36812 const parentParent = path.getParentNode(1);
36813 return parentParent && node.quasis && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXElement" && parentParent.openingElement.name.name === "style" && parentParent.openingElement.attributes.some(attribute => attribute.name.name === "jsx") || parent && parent.type === "TaggedTemplateExpression" && parent.tag.type === "Identifier" && parent.tag.name === "css" || parent && parent.type === "TaggedTemplateExpression" && parent.tag.type === "MemberExpression" && parent.tag.object.name === "css" && (parent.tag.property.name === "global" || parent.tag.property.name === "resolve");
36816 * Angular Components can have:
36817 * - Inline HTML template
36818 * - Inline CSS styles
36820 * ...which are both within template literals somewhere
36821 * inside of the Component decorator factory.
36825 * template: `<div>...</div>`,
36826 * styles: [`h1 { color: blue; }`]
36831 function isAngularComponentStyles(path) {
36832 return path.match(node => node.type === "TemplateLiteral", (node, name) => node.type === "ArrayExpression" && name === "elements", (node, name) => (node.type === "Property" || node.type === "ObjectProperty") && node.key.type === "Identifier" && node.key.name === "styles" && name === "value", ...angularComponentObjectExpressionPredicates);
36835 function isAngularComponentTemplate(path) {
36836 return path.match(node => node.type === "TemplateLiteral", (node, name) => (node.type === "Property" || node.type === "ObjectProperty") && node.key.type === "Identifier" && node.key.name === "template" && name === "value", ...angularComponentObjectExpressionPredicates);
36839 const angularComponentObjectExpressionPredicates = [(node, name) => node.type === "ObjectExpression" && name === "properties", (node, name) => node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "Component" && name === "arguments", (node, name) => node.type === "Decorator" && name === "expression"];
36841 * styled-components template literals
36844 function isStyledComponents(path) {
36845 const parent = path.getParentNode();
36847 if (!parent || parent.type !== "TaggedTemplateExpression") {
36855 switch (tag.type) {
36856 case "MemberExpression":
36857 return (// styled.foo``
36858 isStyledIdentifier(tag.object) || // Component.extend``
36859 isStyledExtend(tag)
36862 case "CallExpression":
36863 return (// styled(Component)``
36864 isStyledIdentifier(tag.callee) || tag.callee.type === "MemberExpression" && (tag.callee.object.type === "MemberExpression" && ( // styled.foo.attrs({})``
36865 isStyledIdentifier(tag.callee.object.object) || // Component.extend.attrs({})``
36866 isStyledExtend(tag.callee.object)) || // styled(Component).attrs({})``
36867 tag.callee.object.type === "CallExpression" && isStyledIdentifier(tag.callee.object.callee))
36872 return tag.name === "css";
36879 * JSX element with CSS prop
36883 function isCssProp(path) {
36884 const parent = path.getParentNode();
36885 const parentParent = path.getParentNode(1);
36886 return parentParent && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" && parentParent.name.type === "JSXIdentifier" && parentParent.name.name === "css";
36889 function isStyledIdentifier(node) {
36890 return node.type === "Identifier" && node.name === "styled";
36893 function isStyledExtend(node) {
36894 return /^[A-Z]/.test(node.object.name) && node.property.name === "extend";
36897 * react-relay and graphql-tag
36899 * graphql.experimental`...`
36901 * GraphQL comment block
36903 * This intentionally excludes Relay Classic tags, as Prettier does not
36904 * support Relay Classic formatting.
36908 function isGraphQL(path) {
36909 const node = path.getValue();
36910 const parent = path.getParentNode();
36911 return hasLanguageComment(node, "GraphQL") || parent && (parent.type === "TaggedTemplateExpression" && (parent.tag.type === "MemberExpression" && parent.tag.object.name === "graphql" && parent.tag.property.name === "experimental" || parent.tag.type === "Identifier" && (parent.tag.name === "gql" || parent.tag.name === "graphql")) || parent.type === "CallExpression" && parent.callee.type === "Identifier" && parent.callee.name === "graphql");
36914 function hasLanguageComment(node, languageName) {
36915 // This checks for a leading comment that is exactly `/* GraphQL */`
36916 // In order to be in line with other implementations of this comment tag
36917 // we will not trim the comment value and we will expect exactly one space on
36918 // either side of the GraphQL string
36919 // Also see ./clean.js
36920 return hasLeadingComment$1(node, comment => isBlockComment$1(comment) && comment.value === ` ${languageName} `);
36924 * - HTML comment block
36928 function isHtml(path) {
36929 return hasLanguageComment(path.getValue(), "HTML") || path.match(node => node.type === "TemplateLiteral", (node, name) => node.type === "TaggedTemplateExpression" && node.tag.type === "Identifier" && node.tag.name === "html" && name === "quasi");
36930 } // The counter is needed to distinguish nested embeds.
36933 let htmlTemplateLiteralCounter = 0;
36935 function printHtmlTemplateLiteral(path, print, textToDoc, parser, options) {
36936 const node = path.getValue();
36937 const counter = htmlTemplateLiteralCounter;
36938 htmlTemplateLiteralCounter = htmlTemplateLiteralCounter + 1 >>> 0;
36940 const composePlaceholder = index => `PRETTIER_HTML_PLACEHOLDER_${index}_${counter}_IN_JS`;
36942 const text = node.quasis.map((quasi, index, quasis) => index === quasis.length - 1 ? quasi.value.cooked : quasi.value.cooked + composePlaceholder(index)).join("");
36943 const expressionDocs = path.map(print, "expressions");
36945 if (expressionDocs.length === 0 && text.trim().length === 0) {
36949 const placeholderRegex = new RegExp(composePlaceholder("(\\d+)"), "g");
36950 let topLevelCount = 0;
36951 const contentDoc = mapDoc$1(stripTrailingHardline$1(textToDoc(text, {
36954 __onHtmlRoot(root) {
36955 topLevelCount = root.children.length;
36959 if (typeof doc !== "string") {
36964 const components = doc.split(placeholderRegex);
36966 for (let i = 0; i < components.length; i++) {
36967 let component = components[i];
36971 component = uncook(component);
36973 if (options.embeddedInHtml) {
36974 component = component.replace(/<\/(script)\b/gi, "<\\/$1");
36977 parts.push(component);
36983 const placeholderIndex = +component;
36984 parts.push(concat$4(["${", group$1(expressionDocs[placeholderIndex]), "}"]));
36987 return concat$4(parts);
36989 const leadingWhitespace = /^\s/.test(text) ? " " : "";
36990 const trailingWhitespace = /\s$/.test(text) ? " " : "";
36991 const linebreak = options.htmlWhitespaceSensitivity === "ignore" ? hardline$3 : leadingWhitespace && trailingWhitespace ? line$2 : null;
36994 return group$1(concat$4(["`", indent$2(concat$4([linebreak, group$1(contentDoc)])), linebreak, "`"]));
36997 return group$1(concat$4(["`", leadingWhitespace, topLevelCount > 1 ? indent$2(group$1(contentDoc)) : group$1(contentDoc), trailingWhitespace, "`"]));
37000 var embed_1 = embed;
37002 function clean(ast, newObj, parent) {
37003 ["range", "raw", "comments", "leadingComments", "trailingComments", "innerComments", "extra", "start", "end", "flags", "errors"].forEach(name => {
37004 delete newObj[name];
37007 if (ast.loc && ast.loc.source === null) {
37008 delete newObj.loc.source;
37011 if (ast.type === "BigIntLiteral") {
37012 newObj.value = newObj.value.toLowerCase();
37013 } // We remove extra `;` and add them when needed
37016 if (ast.type === "EmptyStatement") {
37018 } // We move text around, including whitespaces and add {" "}
37021 if (ast.type === "JSXText") {
37025 if (ast.type === "JSXExpressionContainer" && ast.expression.type === "Literal" && ast.expression.value === " ") {
37027 } // (TypeScript) Ignore `static` in `constructor(static p) {}`
37028 // and `export` in `constructor(export p) {}`
37031 if (ast.type === "TSParameterProperty" && ast.accessibility === null && !ast.readonly) {
37033 type: "Identifier",
37034 name: ast.parameter.name,
37035 typeAnnotation: newObj.parameter.typeAnnotation,
37036 decorators: newObj.decorators
37038 } // (TypeScript) ignore empty `specifiers` array
37041 if (ast.type === "TSNamespaceExportDeclaration" && ast.specifiers && ast.specifiers.length === 0) {
37042 delete newObj.specifiers;
37043 } // We convert <div></div> to <div />
37046 if (ast.type === "JSXOpeningElement") {
37047 delete newObj.selfClosing;
37050 if (ast.type === "JSXElement") {
37051 delete newObj.closingElement;
37052 } // We change {'key': value} into {key: value}
37055 if ((ast.type === "Property" || ast.type === "ObjectProperty" || ast.type === "MethodDefinition" || ast.type === "ClassProperty" || ast.type === "TSPropertySignature" || ast.type === "ObjectTypeProperty") && typeof ast.key === "object" && ast.key && (ast.key.type === "Literal" || ast.key.type === "StringLiteral" || ast.key.type === "Identifier")) {
37059 if (ast.type === "OptionalMemberExpression" && ast.optional === false) {
37060 newObj.type = "MemberExpression";
37061 delete newObj.optional;
37062 } // Remove raw and cooked values from TemplateElement when it's CSS
37066 if (ast.type === "JSXElement" && ast.openingElement.name.name === "style" && ast.openingElement.attributes.some(attr => attr.name.name === "jsx")) {
37067 const templateLiterals = newObj.children.filter(child => child.type === "JSXExpressionContainer" && child.expression.type === "TemplateLiteral").map(container => container.expression);
37068 const quasis = templateLiterals.reduce((quasis, templateLiteral) => quasis.concat(templateLiteral.quasis), []);
37069 quasis.forEach(q => delete q.value);
37070 } // CSS template literals in css prop
37073 if (ast.type === "JSXAttribute" && ast.name.name === "css" && ast.value.type === "JSXExpressionContainer" && ast.value.expression.type === "TemplateLiteral") {
37074 newObj.value.expression.quasis.forEach(q => delete q.value);
37075 } // Angular Components: Inline HTML template and Inline CSS styles
37078 const expression = ast.expression || ast.callee;
37080 if (ast.type === "Decorator" && expression.type === "CallExpression" && expression.callee.name === "Component" && expression.arguments.length === 1) {
37081 const astProps = ast.expression.arguments[0].properties;
37082 newObj.expression.arguments[0].properties.forEach((prop, index) => {
37083 let templateLiteral = null;
37085 switch (astProps[index].key.name) {
37087 if (prop.value.type === "ArrayExpression") {
37088 templateLiteral = prop.value.elements[0];
37094 if (prop.value.type === "TemplateLiteral") {
37095 templateLiteral = prop.value;
37101 if (templateLiteral) {
37102 templateLiteral.quasis.forEach(q => delete q.value);
37105 } // styled-components, graphql, markdown
37108 if (ast.type === "TaggedTemplateExpression" && (ast.tag.type === "MemberExpression" || ast.tag.type === "Identifier" && (ast.tag.name === "gql" || ast.tag.name === "graphql" || ast.tag.name === "css" || ast.tag.name === "md" || ast.tag.name === "markdown" || ast.tag.name === "html") || ast.tag.type === "CallExpression")) {
37109 newObj.quasi.quasis.forEach(quasi => delete quasi.value);
37112 if (ast.type === "TemplateLiteral") {
37113 // This checks for a leading comment that is exactly `/* GraphQL */`
37114 // In order to be in line with other implementations of this comment tag
37115 // we will not trim the comment value and we will expect exactly one space on
37116 // either side of the GraphQL string
37117 // Also see ./embed.js
37118 const hasLanguageComment = ast.leadingComments && ast.leadingComments.some(comment => comment.type === "CommentBlock" && ["GraphQL", "HTML"].some(languageName => comment.value === ` ${languageName} `));
37120 if (hasLanguageComment || parent.type === "CallExpression" && parent.callee.name === "graphql") {
37121 newObj.quasis.forEach(quasi => delete quasi.value);
37126 var clean_1 = clean;
37128 const detectNewline = string => {
37129 if (typeof string !== 'string') {
37130 throw new TypeError('Expected a string');
37133 const newlines = string.match(/(?:\r?\n)/g) || [];
37135 if (newlines.length === 0) {
37139 const crlf = newlines.filter(newline => newline === '\r\n').length;
37140 const lf = newlines.length - crlf;
37141 return crlf > lf ? '\r\n' : '\n';
37144 var detectNewline_1 = detectNewline;
37146 var graceful = string => typeof string === 'string' && detectNewline(string) || '\n';
37147 detectNewline_1.graceful = graceful;
37149 var build = createCommonjsModule(function (module, exports) {
37151 Object.defineProperty(exports, '__esModule', {
37154 exports.extract = extract;
37155 exports.strip = strip;
37156 exports.parse = parse;
37157 exports.parseWithComments = parseWithComments;
37158 exports.print = print;
37163 _os = function () {
37170 function _detectNewline() {
37171 const data = _interopRequireDefault(detectNewline_1);
37173 _detectNewline = function () {
37180 function _interopRequireDefault(obj) {
37181 return obj && obj.__esModule ? obj : {
37186 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
37188 * This source code is licensed under the MIT license found in the
37189 * LICENSE file in the root directory of this source tree.
37193 const commentEndRe = /\*\/$/;
37194 const commentStartRe = /^\/\*\*/;
37195 const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/;
37196 const lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g;
37197 const ltrimNewlineRe = /^(\r?\n)+/;
37198 const multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
37199 const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
37200 const stringStartRe = /(\r?\n|^) *\* ?/g;
37202 function extract(contents) {
37203 const match = contents.match(docblockRe);
37204 return match ? match[0].trimLeft() : '';
37207 function strip(contents) {
37208 const match = contents.match(docblockRe);
37209 return match && match[0] ? contents.substring(match[0].length) : contents;
37212 function parse(docblock) {
37213 return parseWithComments(docblock).pragmas;
37216 function parseWithComments(docblock) {
37217 const line = (0, _detectNewline().default)(docblock) || _os().EOL;
37219 docblock = docblock.replace(commentStartRe, '').replace(commentEndRe, '').replace(stringStartRe, '$1'); // Normalize multi-line directives
37223 while (prev !== docblock) {
37225 docblock = docblock.replace(multilineRe, `${line}$1 $2${line}`);
37228 docblock = docblock.replace(ltrimNewlineRe, '').trimRight();
37229 const result = Object.create(null);
37230 const comments = docblock.replace(propertyRe, '').replace(ltrimNewlineRe, '').trimRight();
37233 while (match = propertyRe.exec(docblock)) {
37234 // strip linecomments from pragmas
37235 const nextPragma = match[2].replace(lineCommentRe, '');
37237 if (typeof result[match[1]] === 'string' || Array.isArray(result[match[1]])) {
37238 result[match[1]] = [].concat(result[match[1]], nextPragma);
37240 result[match[1]] = nextPragma;
37254 const line = (0, _detectNewline().default)(comments) || _os().EOL;
37256 const head = '/**';
37257 const start = ' *';
37258 const tail = ' */';
37259 const keys = Object.keys(pragmas);
37260 const printedObject = keys.map(key => printKeyValues(key, pragmas[key])).reduce((arr, next) => arr.concat(next), []).map(keyValue => start + ' ' + keyValue + line).join('');
37263 if (keys.length === 0) {
37267 if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) {
37268 const value = pragmas[keys[0]];
37269 return `${head} ${printKeyValues(keys[0], value)[0]}${tail}`;
37273 const printedComments = comments.split(line).map(textLine => `${start} ${textLine}`).join(line) + line;
37274 return head + line + (comments ? printedComments : '') + (comments && keys.length ? start + line : '') + printedObject + tail;
37277 function printKeyValues(key, valueOrArray) {
37278 return [].concat(valueOrArray).map(value => `@${key} ${value}`.trim());
37281 unwrapExports(build);
37282 var build_1 = build.extract;
37283 var build_2 = build.strip;
37284 var build_3 = build.parse;
37285 var build_4 = build.parseWithComments;
37286 var build_5 = build.print;
37288 function hasPragma(text) {
37289 const pragmas = Object.keys(build.parse(build.extract(text)));
37290 return pragmas.includes("prettier") || pragmas.includes("format");
37293 function insertPragma(text) {
37294 const parsedDocblock = build.parseWithComments(build.extract(text));
37295 const pragmas = Object.assign({
37297 }, parsedDocblock.pragmas);
37298 const newDocblock = build.print({
37300 comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines
37302 }).replace(/(\r\n|\r)/g, "\n"); // normalise newlines (mitigate use of os.EOL by jest-docblock)
37304 const strippedText = build.strip(text);
37305 const separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n";
37306 return newDocblock + separatingNewlines + strippedText;
37315 getLast: getLast$1,
37316 hasNewline: hasNewline$3,
37317 hasNewlineInRange: hasNewlineInRange$2,
37318 hasIgnoreComment: hasIgnoreComment$1,
37319 hasNodeIgnoreComment: hasNodeIgnoreComment$1,
37320 skipWhitespace: skipWhitespace$2
37322 const isIdentifierName = utils$1.keyword.isIdentifierNameES5; // We match any whitespace except line terminators because
37323 // Flow annotation comments cannot be split across lines. For example:
37326 // : any */).foo = 5;
37328 // is not picked up by Flow (see https://github.com/facebook/flow/issues/7050), so
37329 // removing the newline would create a type annotation that the user did not intend
37332 const NON_LINE_TERMINATING_WHITE_SPACE = "(?:(?=.)\\s)";
37333 const FLOW_SHORTHAND_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*:`);
37334 const FLOW_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*::`);
37336 function hasFlowShorthandAnnotationComment(node) {
37337 // https://flow.org/en/docs/types/comments/
37338 // Syntax example: const r = new (window.Request /*: Class<Request> */)("");
37339 return node.extra && node.extra.parenthesized && node.trailingComments && node.trailingComments[0].value.match(FLOW_SHORTHAND_ANNOTATION);
37342 function hasFlowAnnotationComment(comments) {
37343 return comments && comments[0].value.match(FLOW_ANNOTATION);
37346 function hasNode(node, fn) {
37347 if (!node || typeof node !== "object") {
37351 if (Array.isArray(node)) {
37352 return node.some(value => hasNode(value, fn));
37355 const result = fn(node);
37356 return typeof result === "boolean" ? result : Object.keys(node).some(key => hasNode(node[key], fn));
37359 function hasNakedLeftSide(node) {
37360 return node.type === "AssignmentExpression" || node.type === "BinaryExpression" || node.type === "LogicalExpression" || node.type === "NGPipeExpression" || node.type === "ConditionalExpression" || node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "BindExpression" || node.type === "UpdateExpression" && !node.prefix || node.type === "TSAsExpression" || node.type === "TSNonNullExpression";
37363 function getLeftSide(node) {
37364 if (node.expressions) {
37365 return node.expressions[0];
37368 return node.left || node.test || node.callee || node.object || node.tag || node.argument || node.expression;
37371 function getLeftSidePathName(path, node) {
37372 if (node.expressions) {
37373 return ["expressions", 0];
37396 if (node.argument) {
37397 return ["argument"];
37400 if (node.expression) {
37401 return ["expression"];
37404 throw new Error("Unexpected node has no left side", node);
37407 const exportDeclarationTypes = new Set(["ExportDefaultDeclaration", "ExportDefaultSpecifier", "DeclareExportDeclaration", "ExportNamedDeclaration", "ExportAllDeclaration"]);
37409 function isExportDeclaration(node) {
37410 return node && exportDeclarationTypes.has(node.type);
37413 function getParentExportDeclaration(path) {
37414 const parentNode = path.getParentNode();
37416 if (path.getName() === "declaration" && isExportDeclaration(parentNode)) {
37423 function isLiteral(node) {
37424 return node.type === "BooleanLiteral" || node.type === "DirectiveLiteral" || node.type === "Literal" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "RegExpLiteral" || node.type === "StringLiteral" || node.type === "TemplateLiteral" || node.type === "TSTypeLiteral" || node.type === "JSXText";
37427 function isNumericLiteral(node) {
37428 return node.type === "NumericLiteral" || node.type === "Literal" && typeof node.value === "number";
37431 function isStringLiteral(node) {
37432 return node.type === "StringLiteral" || node.type === "Literal" && typeof node.value === "string";
37435 function isObjectType(n) {
37436 return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral";
37439 function isFunctionOrArrowExpression(node) {
37440 return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
37443 function isFunctionOrArrowExpressionWithBody(node) {
37444 return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement";
37447 function isTemplateLiteral(node) {
37448 return node.type === "TemplateLiteral";
37449 } // `inject` is used in AngularJS 1.x, `async` in Angular 2+
37450 // example: https://docs.angularjs.org/guide/unit-testing#using-beforeall-
37453 function isAngularTestWrapper(node) {
37454 return (node.type === "CallExpression" || node.type === "OptionalCallExpression") && node.callee.type === "Identifier" && (node.callee.name === "async" || node.callee.name === "inject" || node.callee.name === "fakeAsync");
37457 function isJSXNode(node) {
37458 return node.type === "JSXElement" || node.type === "JSXFragment";
37461 function isTheOnlyJSXElementInMarkdown(options, path) {
37462 if (options.parentParser !== "markdown" && options.parentParser !== "mdx") {
37466 const node = path.getNode();
37468 if (!node.expression || !isJSXNode(node.expression)) {
37472 const parent = path.getParentNode();
37473 return parent.type === "Program" && parent.body.length === 1;
37474 } // Detect an expression node representing `{" "}`
37477 function isJSXWhitespaceExpression(node) {
37478 return node.type === "JSXExpressionContainer" && isLiteral(node.expression) && node.expression.value === " " && !node.expression.comments;
37481 function isMemberExpressionChain(node) {
37482 if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") {
37486 if (node.object.type === "Identifier") {
37490 return isMemberExpressionChain(node.object);
37493 function isGetterOrSetter(node) {
37494 return node.kind === "get" || node.kind === "set";
37497 function sameLocStart(nodeA, nodeB, options) {
37498 return options.locStart(nodeA) === options.locStart(nodeB);
37499 } // TODO: This is a bad hack and we need a better way to distinguish between
37500 // arrow functions and otherwise
37503 function isFunctionNotation(node, options) {
37504 return isGetterOrSetter(node) || sameLocStart(node, node.value, options);
37505 } // Hack to differentiate between the following two which have the same ast
37506 // type T = { method: () => void };
37507 // type T = { method(): void };
37510 function isObjectTypePropertyAFunction(node, options) {
37511 return (node.type === "ObjectTypeProperty" || node.type === "ObjectTypeInternalSlot") && node.value.type === "FunctionTypeAnnotation" && !node.static && !isFunctionNotation(node, options);
37512 } // Hack to differentiate between the following two which have the same ast
37513 // declare function f(a): void;
37514 // var f: (a) => void;
37517 function isTypeAnnotationAFunction(node, options) {
37518 return (node.type === "TypeAnnotation" || node.type === "TSTypeAnnotation") && node.typeAnnotation.type === "FunctionTypeAnnotation" && !node.static && !sameLocStart(node, node.typeAnnotation, options);
37521 const binaryishNodeTypes = new Set(["BinaryExpression", "LogicalExpression", "NGPipeExpression"]);
37523 function isBinaryish(node) {
37524 return binaryishNodeTypes.has(node.type);
37527 function isMemberish(node) {
37528 return node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "BindExpression" && node.object;
37531 function isSimpleFlowType(node) {
37532 const flowTypeAnnotations = ["AnyTypeAnnotation", "NullLiteralTypeAnnotation", "GenericTypeAnnotation", "ThisTypeAnnotation", "NumberTypeAnnotation", "VoidTypeAnnotation", "EmptyTypeAnnotation", "MixedTypeAnnotation", "BooleanTypeAnnotation", "BooleanLiteralTypeAnnotation", "StringTypeAnnotation"];
37533 return node && flowTypeAnnotations.includes(node.type) && !(node.type === "GenericTypeAnnotation" && node.typeParameters);
37536 const unitTestRe = /^(skip|[fx]?(it|describe|test))$/;
37538 function isSkipOrOnlyBlock(node) {
37539 return (node.callee.type === "MemberExpression" || node.callee.type === "OptionalMemberExpression") && node.callee.object.type === "Identifier" && node.callee.property.type === "Identifier" && unitTestRe.test(node.callee.object.name) && (node.callee.property.name === "only" || node.callee.property.name === "skip");
37542 function isUnitTestSetUp(n) {
37543 const unitTestSetUpRe = /^(before|after)(Each|All)$/;
37544 return n.callee.type === "Identifier" && unitTestSetUpRe.test(n.callee.name) && n.arguments.length === 1;
37545 } // eg; `describe("some string", (done) => {})`
37548 function isTestCall(n, parent) {
37549 if (n.type !== "CallExpression") {
37553 if (n.arguments.length === 1) {
37554 if (isAngularTestWrapper(n) && parent && isTestCall(parent)) {
37555 return isFunctionOrArrowExpression(n.arguments[0]);
37558 if (isUnitTestSetUp(n)) {
37559 return isAngularTestWrapper(n.arguments[0]);
37561 } else if (n.arguments.length === 2 || n.arguments.length === 3) {
37562 if ((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name) || isSkipOrOnlyBlock(n)) && (isTemplateLiteral(n.arguments[0]) || isStringLiteral(n.arguments[0]))) {
37563 // it("name", () => { ... }, 2500)
37564 if (n.arguments[2] && !isNumericLiteral(n.arguments[2])) {
37568 return (n.arguments.length === 2 ? isFunctionOrArrowExpression(n.arguments[1]) : isFunctionOrArrowExpressionWithBody(n.arguments[1]) && n.arguments[1].params.length <= 1) || isAngularTestWrapper(n.arguments[1]);
37575 function hasLeadingComment$2(node) {
37576 return node.comments && node.comments.some(comment => comment.leading);
37579 function hasTrailingComment(node) {
37580 return node.comments && node.comments.some(comment => comment.trailing);
37583 function isCallOrOptionalCallExpression(node) {
37584 return node.type === "CallExpression" || node.type === "OptionalCallExpression";
37587 function hasDanglingComments(node) {
37588 return node.comments && node.comments.some(comment => !comment.leading && !comment.trailing);
37590 /** identify if an angular expression seems to have side effects */
37593 function hasNgSideEffect(path) {
37594 return hasNode(path.getValue(), node => {
37595 switch (node.type) {
37599 case "CallExpression":
37600 case "OptionalCallExpression":
37601 case "AssignmentExpression":
37607 function isNgForOf(node, index, parentNode) {
37608 return node.type === "NGMicrosyntaxKeyedExpression" && node.key.name === "of" && index === 1 && parentNode.body[0].type === "NGMicrosyntaxLet" && parentNode.body[0].value === null;
37610 /** @param node {import("estree").TemplateLiteral} */
37613 function isSimpleTemplateLiteral(node) {
37614 if (node.expressions.length === 0) {
37618 return node.expressions.every(expr => {
37619 // Disallow comments since printDocToString can't print them here
37620 if (expr.comments) {
37622 } // Allow `x` and `this`
37625 if (expr.type === "Identifier" || expr.type === "ThisExpression") {
37627 } // Allow `a.b.c`, `a.b[c]`, and `this.x.y`
37630 if (expr.type === "MemberExpression" || expr.type === "OptionalMemberExpression") {
37633 while (head.type === "MemberExpression" || head.type === "OptionalMemberExpression") {
37634 if (head.property.type !== "Identifier" && head.property.type !== "Literal" && head.property.type !== "StringLiteral" && head.property.type !== "NumericLiteral") {
37638 head = head.object;
37640 if (head.comments) {
37645 if (head.type === "Identifier" || head.type === "ThisExpression") {
37656 function getFlowVariance(path) {
37657 if (!path.variance) {
37659 } // Babel 7.0 currently uses variance node type, and flow should
37660 // follow suit soon:
37661 // https://github.com/babel/babel/issues/4722
37664 const variance = path.variance.kind || path.variance;
37666 switch (variance) {
37674 /* istanbul ignore next */
37679 function classPropMayCauseASIProblems(path) {
37680 const node = path.getNode();
37682 if (node.type !== "ClassProperty") {
37686 const name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today
37687 // so isn't properly tested yet.
37689 if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) {
37694 function classChildNeedsASIProtection(node) {
37699 if (node.static || node.accessibility // TypeScript
37704 if (!node.computed) {
37705 const name = node.key && node.key.name;
37707 if (name === "in" || name === "instanceof") {
37712 switch (node.type) {
37713 case "ClassProperty":
37714 case "TSAbstractClassProperty":
37715 return node.computed;
37717 case "MethodDefinition": // Flow
37719 case "TSAbstractMethodDefinition": // TypeScript
37721 case "ClassMethod":
37722 case "ClassPrivateMethod":
37725 const isAsync = node.value ? node.value.async : node.async;
37726 const isGenerator = node.value ? node.value.generator : node.generator;
37728 if (isAsync || node.kind === "get" || node.kind === "set") {
37732 if (node.computed || isGenerator) {
37739 case "TSIndexSignature":
37743 /* istanbul ignore next */
37748 function getTypeScriptMappedTypeModifier(tokenNode, keyword) {
37749 if (tokenNode === "+") {
37750 return "+" + keyword;
37751 } else if (tokenNode === "-") {
37752 return "-" + keyword;
37758 function hasNewlineBetweenOrAfterDecorators(node, options) {
37759 return hasNewlineInRange$2(options.originalText, options.locStart(node.decorators[0]), options.locEnd(getLast$1(node.decorators))) || hasNewline$3(options.originalText, options.locEnd(getLast$1(node.decorators)));
37760 } // Only space, newline, carriage return, and tab are treated as whitespace
37764 const jsxWhitespaceChars = " \n\r\t";
37765 const matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)");
37766 const containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]"); // Meaningful if it contains non-whitespace characters,
37767 // or it contains whitespace without a new line.
37769 function isMeaningfulJSXText(node) {
37770 return isLiteral(node) && (containsNonJsxWhitespaceRegex.test(rawText(node)) || !/\n/.test(rawText(node)));
37773 function hasJsxIgnoreComment(path) {
37774 const node = path.getValue();
37775 const parent = path.getParentNode();
37777 if (!parent || !node || !isJSXNode(node) || !isJSXNode(parent)) {
37779 } // Lookup the previous sibling, ignoring any empty JSXText elements
37782 const index = parent.children.indexOf(node);
37783 let prevSibling = null;
37785 for (let i = index; i > 0; i--) {
37786 const candidate = parent.children[i - 1];
37788 if (candidate.type === "JSXText" && !isMeaningfulJSXText(candidate)) {
37792 prevSibling = candidate;
37796 return prevSibling && prevSibling.type === "JSXExpressionContainer" && prevSibling.expression.type === "JSXEmptyExpression" && prevSibling.expression.comments && prevSibling.expression.comments.find(comment => comment.value.trim() === "prettier-ignore");
37799 function isEmptyJSXElement(node) {
37800 if (node.children.length === 0) {
37804 if (node.children.length > 1) {
37806 } // if there is one text child and does not contain any meaningful text
37807 // we can treat the element as empty.
37810 const child = node.children[0];
37811 return isLiteral(child) && !isMeaningfulJSXText(child);
37814 function hasPrettierIgnore(path) {
37815 return hasIgnoreComment$1(path) || hasJsxIgnoreComment(path);
37818 function isLastStatement(path) {
37819 const parent = path.getParentNode();
37825 const node = path.getValue();
37826 const body = (parent.body || parent.consequent).filter(stmt => stmt.type !== "EmptyStatement");
37827 return body && body[body.length - 1] === node;
37830 function isFlowAnnotationComment(text, typeAnnotation, options) {
37831 const start = options.locStart(typeAnnotation);
37832 const end = skipWhitespace$2(text, options.locEnd(typeAnnotation));
37833 return text.slice(start, start + 2) === "/*" && text.slice(end, end + 2) === "*/";
37836 function hasLeadingOwnLineComment(text, node, options) {
37837 if (isJSXNode(node)) {
37838 return hasNodeIgnoreComment$1(node);
37841 const res = node.comments && node.comments.some(comment => comment.leading && hasNewline$3(text, options.locEnd(comment)));
37843 } // This recurses the return argument, looking for the first token
37844 // (the leftmost leaf node) and, if it (or its parents) has any
37845 // leadingComments, returns true (so it can be wrapped in parens).
37848 function returnArgumentHasLeadingComment(options, argument) {
37849 if (hasLeadingOwnLineComment(options.originalText, argument, options)) {
37853 if (hasNakedLeftSide(argument)) {
37854 let leftMost = argument;
37857 while (newLeftMost = getLeftSide(leftMost)) {
37858 leftMost = newLeftMost;
37860 if (hasLeadingOwnLineComment(options.originalText, leftMost, options)) {
37869 function isStringPropSafeToCoerceToIdentifier(node, options) {
37870 return isStringLiteral(node.key) && isIdentifierName(node.key.value) && options.parser !== "json" && // With `--strictPropertyInitialization`, TS treats properties with quoted names differently than unquoted ones.
37871 // See https://github.com/microsoft/TypeScript/pull/20075
37872 !((options.parser === "typescript" || options.parser === "babel-ts") && node.type === "ClassProperty");
37875 function isJestEachTemplateLiteral(node, parentNode) {
37877 * describe.each`table`(name, fn)
37878 * describe.only.each`table`(name, fn)
37879 * describe.skip.each`table`(name, fn)
37880 * test.each`table`(name, fn)
37881 * test.only.each`table`(name, fn)
37882 * test.skip.each`table`(name, fn)
37884 * Ref: https://github.com/facebook/jest/pull/6102
37886 const jestEachTriggerRegex = /^[xf]?(describe|it|test)$/;
37887 return parentNode.type === "TaggedTemplateExpression" && parentNode.quasi === node && parentNode.tag.type === "MemberExpression" && parentNode.tag.property.type === "Identifier" && parentNode.tag.property.name === "each" && (parentNode.tag.object.type === "Identifier" && jestEachTriggerRegex.test(parentNode.tag.object.name) || parentNode.tag.object.type === "MemberExpression" && parentNode.tag.object.property.type === "Identifier" && (parentNode.tag.object.property.name === "only" || parentNode.tag.object.property.name === "skip") && parentNode.tag.object.object.type === "Identifier" && jestEachTriggerRegex.test(parentNode.tag.object.object.name));
37890 function templateLiteralHasNewLines(template) {
37891 return template.quasis.some(quasi => quasi.value.raw.includes("\n"));
37894 function isTemplateOnItsOwnLine(n, text, options) {
37895 return (n.type === "TemplateLiteral" && templateLiteralHasNewLines(n) || n.type === "TaggedTemplateExpression" && templateLiteralHasNewLines(n.quasi)) && !hasNewline$3(text, options.locStart(n), {
37900 function needsHardlineAfterDanglingComment(node) {
37901 if (!node.comments) {
37905 const lastDanglingComment = getLast$1(node.comments.filter(comment => !comment.leading && !comment.trailing));
37906 return lastDanglingComment && !comments$1.isBlockComment(lastDanglingComment);
37907 } // If we have nested conditional expressions, we want to print them in JSX mode
37908 // if there's at least one JSXElement somewhere in the tree.
37910 // A conditional expression chain like this should be printed in normal mode,
37911 // because there aren't JSXElements anywhere in it:
37913 // isA ? "A" : isB ? "B" : isC ? "C" : "Unknown";
37915 // But a conditional expression chain like this should be printed in JSX mode,
37916 // because there is a JSXElement in the last ConditionalExpression:
37918 // isA ? "A" : isB ? "B" : isC ? "C" : <span className="warning">Unknown</span>;
37920 // This type of ConditionalExpression chain is structured like this in the AST:
37922 // ConditionalExpression {
37924 // consequent: ...,
37925 // alternate: ConditionalExpression {
37927 // consequent: ...,
37928 // alternate: ConditionalExpression {
37930 // consequent: ...,
37936 // We want to traverse over that shape and convert it into a flat structure so
37937 // that we can find if there's a JSXElement somewhere inside.
37940 function getConditionalChainContents(node) {
37941 // Given this code:
37943 // // Using a ConditionalExpression as the consequent is uncommon, but should
37945 // A ? B : C ? D : E ? F ? G : H : I
37947 // which has this AST:
37949 // ConditionalExpression {
37950 // test: Identifier(A),
37951 // consequent: Identifier(B),
37952 // alternate: ConditionalExpression {
37953 // test: Identifier(C),
37954 // consequent: Identifier(D),
37955 // alternate: ConditionalExpression {
37956 // test: Identifier(E),
37957 // consequent: ConditionalExpression {
37958 // test: Identifier(F),
37959 // consequent: Identifier(G),
37960 // alternate: Identifier(H),
37962 // alternate: Identifier(I),
37967 // we should return this Array:
37981 // This loses the information about whether each node was the test,
37982 // consequent, or alternate, but we don't care about that here- we are only
37983 // flattening this structure to find if there's any JSXElements inside.
37984 const nonConditionalExpressions = [];
37986 function recurse(node) {
37987 if (node.type === "ConditionalExpression") {
37988 recurse(node.test);
37989 recurse(node.consequent);
37990 recurse(node.alternate);
37992 nonConditionalExpressions.push(node);
37997 return nonConditionalExpressions;
38000 function conditionalExpressionChainContainsJSX(node) {
38001 return Boolean(getConditionalChainContents(node).find(isJSXNode));
38002 } // Logic to check for args with multiple anonymous functions. For instance,
38003 // the following call should be split on multiple lines for readability:
38004 // source.pipe(map((x) => x + x), filter((x) => x % 2 === 0))
38007 function isFunctionCompositionArgs(args) {
38008 if (args.length <= 1) {
38014 for (const arg of args) {
38015 if (isFunctionOrArrowExpression(arg)) {
38021 } else if (isCallOrOptionalCallExpression(arg)) {
38022 for (const childArg of arg.arguments) {
38023 if (isFunctionOrArrowExpression(childArg)) {
38031 } // Logic to determine if a call is a “long curried function call”.
38032 // See https://github.com/prettier/prettier/issues/1420.
38034 // `connect(a, b, c)(d)`
38035 // In the above call expression, the second call is the parent node and the
38036 // first call is the current node.
38039 function isLongCurriedCallExpression(path) {
38040 const node = path.getValue();
38041 const parent = path.getParentNode();
38042 return isCallOrOptionalCallExpression(node) && isCallOrOptionalCallExpression(parent) && parent.callee === node && node.arguments.length > parent.arguments.length && parent.arguments.length > 0;
38045 * @param {import('estree').Node} node
38046 * @param {number} depth
38047 * @returns {boolean}
38051 function isSimpleCallArgument(node, depth) {
38056 const isChildSimple = child => isSimpleCallArgument(child, depth + 1);
38058 const regexpPattern = node.type === "Literal" && node.regex && node.regex.pattern || node.type === "RegExpLiteral" && node.pattern;
38060 if (regexpPattern && regexpPattern.length > 5) {
38064 if (node.type === "Literal" || node.type === "BooleanLiteral" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "StringLiteral" || node.type === "Identifier" || node.type === "ThisExpression" || node.type === "Super" || node.type === "BigIntLiteral" || node.type === "PrivateName" || node.type === "ArgumentPlaceholder" || node.type === "RegExpLiteral" || node.type === "Import") {
38068 if (node.type === "TemplateLiteral") {
38069 return node.expressions.every(isChildSimple);
38072 if (node.type === "ObjectExpression") {
38073 return node.properties.every(p => !p.computed && (p.shorthand || p.value && isChildSimple(p.value)));
38076 if (node.type === "ArrayExpression") {
38077 return node.elements.every(x => x == null || isChildSimple(x));
38080 if (node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "NewExpression") {
38081 return isSimpleCallArgument(node.callee, depth) && node.arguments.every(isChildSimple);
38084 if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
38085 return isSimpleCallArgument(node.object, depth) && isSimpleCallArgument(node.property, depth);
38088 if (node.type === "UnaryExpression" && (node.operator === "!" || node.operator === "-")) {
38089 return isSimpleCallArgument(node.argument, depth);
38092 if (node.type === "TSNonNullExpression") {
38093 return isSimpleCallArgument(node.expression, depth);
38099 function rawText(node) {
38100 return node.extra ? node.extra.raw : node.raw;
38103 function identity$1(x) {
38107 function isTSXFile(options) {
38108 return options.filepath && /\.tsx$/i.test(options.filepath);
38112 classChildNeedsASIProtection,
38113 classPropMayCauseASIProblems,
38114 conditionalExpressionChainContainsJSX,
38116 getLeftSidePathName,
38117 getParentExportDeclaration,
38118 getTypeScriptMappedTypeModifier,
38119 hasDanglingComments,
38120 hasFlowAnnotationComment,
38121 hasFlowShorthandAnnotationComment,
38122 hasLeadingComment: hasLeadingComment$2,
38123 hasLeadingOwnLineComment,
38125 hasNewlineBetweenOrAfterDecorators,
38129 hasTrailingComment,
38130 identity: identity$1,
38132 isCallOrOptionalCallExpression,
38134 isExportDeclaration,
38135 isFlowAnnotationComment,
38136 isFunctionCompositionArgs,
38137 isFunctionNotation,
38138 isFunctionOrArrowExpression,
38140 isJestEachTemplateLiteral,
38142 isJSXWhitespaceExpression,
38145 isLongCurriedCallExpression,
38146 isSimpleCallArgument,
38147 isMeaningfulJSXText,
38148 isMemberExpressionChain,
38153 isObjectTypePropertyAFunction,
38155 isSimpleTemplateLiteral,
38157 isStringPropSafeToCoerceToIdentifier,
38158 isTemplateOnItsOwnLine,
38160 isTheOnlyJSXElementInMarkdown,
38162 isTypeAnnotationAFunction,
38163 matchJsxWhitespaceRegex,
38164 needsHardlineAfterDanglingComment,
38166 returnArgumentHasLeadingComment
38170 getLeftSidePathName: getLeftSidePathName$1,
38171 hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$1,
38172 hasNakedLeftSide: hasNakedLeftSide$1,
38176 function needsParens(path, options) {
38177 const parent = path.getParentNode();
38183 const name = path.getName();
38184 const node = path.getNode(); // If the value of this path is some child of a Node and not a Node
38185 // itself, then it doesn't need parentheses. Only Node objects (in
38186 // fact, only Expression nodes) need parentheses.
38188 if (path.getValue() !== node) {
38190 } // to avoid unexpected `}}` in HTML interpolations
38193 if (options.__isInHtmlInterpolation && !options.bracketSpacing && endsWithRightBracket(node) && isFollowedByRightBracket(path)) {
38195 } // Only statements don't need parentheses.
38198 if (isStatement(node)) {
38202 if ( // Preserve parens if we have a Flow annotation comment, unless we're using the Flow
38203 // parser. The Flow parser turns Flow comments into type annotation nodes in its
38204 // AST, which we handle separately.
38205 options.parser !== "flow" && hasFlowShorthandAnnotationComment$1(path.getValue())) {
38207 } // Identifiers never need parentheses.
38210 if (node.type === "Identifier") {
38211 // ...unless those identifiers are embed placeholders. They might be substituted by complex
38212 // expressions, so the parens around them should not be dropped. Example (JS-in-HTML-in-JS):
38213 // let tpl = html`<script> f((${expr}) / 2); </script>`;
38214 // If the inner JS formatter removes the parens, the expression might change its meaning:
38215 // f((a + b) / 2) vs f(a + b / 2)
38216 if (node.extra && node.extra.parenthesized && /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(node.name)) {
38223 if (parent.type === "ParenthesizedExpression") {
38225 } // Add parens around the extends clause of a class. It is needed for almost
38226 // all expressions.
38229 if ((parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node && (node.type === "ArrowFunctionExpression" || node.type === "AssignmentExpression" || node.type === "AwaitExpression" || node.type === "BinaryExpression" || node.type === "ConditionalExpression" || node.type === "LogicalExpression" || node.type === "NewExpression" || node.type === "ObjectExpression" || node.type === "ParenthesizedExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "UnaryExpression" || node.type === "UpdateExpression" || node.type === "YieldExpression")) {
38233 if (parent.type === "ExportDefaultDeclaration") {
38234 return (// `export default function` or `export default class` can't be followed by
38235 // anything after. So an expression like `export default (function(){}).toString()`
38236 // needs to be followed by a parentheses
38237 shouldWrapFunctionForExportDefault(path, options) || // `export default (foo, bar)` also needs parentheses
38238 node.type === "SequenceExpression"
38242 if (parent.type === "Decorator" && parent.expression === node) {
38243 let hasCallExpression = false;
38244 let hasMemberExpression = false;
38245 let current = node;
38248 switch (current.type) {
38249 case "MemberExpression":
38250 hasMemberExpression = true;
38251 current = current.object;
38254 case "CallExpression":
38257 hasMemberExpression ||
38259 hasCallExpression) {
38263 hasCallExpression = true;
38264 current = current.callee;
38278 if (parent.type === "ArrowFunctionExpression" && parent.body === node && node.type !== "SequenceExpression" && // these have parens added anyway
38279 util$1.startsWithNoLookaheadToken(node,
38280 /* forbidFunctionClassAndDoExpr */
38281 false) || parent.type === "ExpressionStatement" && util$1.startsWithNoLookaheadToken(node,
38282 /* forbidFunctionClassAndDoExpr */
38287 switch (node.type) {
38288 case "SpreadElement":
38289 case "SpreadProperty":
38290 return parent.type === "MemberExpression" && name === "object" && parent.object === node;
38292 case "UpdateExpression":
38293 if (parent.type === "UnaryExpression") {
38294 return node.prefix && (node.operator === "++" && parent.operator === "+" || node.operator === "--" && parent.operator === "-");
38297 // else fallthrough
38299 case "UnaryExpression":
38300 switch (parent.type) {
38301 case "UnaryExpression":
38302 return node.operator === parent.operator && (node.operator === "+" || node.operator === "-");
38304 case "BindExpression":
38307 case "MemberExpression":
38308 case "OptionalMemberExpression":
38309 return name === "object";
38311 case "TaggedTemplateExpression":
38314 case "NewExpression":
38315 case "CallExpression":
38316 case "OptionalCallExpression":
38317 return name === "callee";
38319 case "BinaryExpression":
38320 return parent.operator === "**" && name === "left";
38322 case "TSNonNullExpression":
38329 case "BinaryExpression":
38331 if (parent.type === "UpdateExpression") {
38335 const isLeftOfAForStatement = node => {
38339 const parent = path.getParentNode(i++);
38345 if (parent.type === "ForStatement" && parent.init === node) {
38355 if (node.operator === "in" && isLeftOfAForStatement(node)) {
38361 case "TSTypeAssertion":
38362 case "TSAsExpression":
38363 case "LogicalExpression":
38364 switch (parent.type) {
38365 case "ConditionalExpression":
38366 return node.type === "TSAsExpression";
38368 case "CallExpression":
38369 case "NewExpression":
38370 case "OptionalCallExpression":
38371 return name === "callee";
38373 case "ClassExpression":
38374 case "ClassDeclaration":
38375 return name === "superClass" && parent.superClass === node;
38377 case "TSTypeAssertion":
38378 case "TaggedTemplateExpression":
38379 case "UnaryExpression":
38380 case "JSXSpreadAttribute":
38381 case "SpreadElement":
38382 case "SpreadProperty":
38383 case "BindExpression":
38384 case "AwaitExpression":
38385 case "TSAsExpression":
38386 case "TSNonNullExpression":
38387 case "UpdateExpression":
38390 case "MemberExpression":
38391 case "OptionalMemberExpression":
38392 return name === "object";
38394 case "AssignmentExpression":
38395 return parent.left === node && (node.type === "TSTypeAssertion" || node.type === "TSAsExpression");
38397 case "LogicalExpression":
38398 if (node.type === "LogicalExpression") {
38399 return parent.operator !== node.operator;
38402 // else fallthrough
38404 case "BinaryExpression":
38406 if (!node.operator && node.type !== "TSTypeAssertion") {
38410 const po = parent.operator;
38411 const pp = util$1.getPrecedence(po);
38412 const no = node.operator;
38413 const np = util$1.getPrecedence(no);
38419 if (pp === np && name === "right") {
38420 assert$1.strictEqual(parent.right, node);
38424 if (pp === np && !util$1.shouldFlatten(po, no)) {
38428 if (pp < np && no === "%") {
38429 return po === "+" || po === "-";
38430 } // Add parenthesis when working with bitwise operators
38431 // It's not strictly needed but helps with code understanding
38434 if (util$1.isBitwiseOperator(po)) {
38445 case "SequenceExpression":
38446 switch (parent.type) {
38447 case "ReturnStatement":
38450 case "ForStatement":
38451 // Although parentheses wouldn't hurt around sequence
38452 // expressions in the head of for loops, traditional style
38453 // dictates that e.g. i++, j++ should not be wrapped with
38457 case "ExpressionStatement":
38458 return name !== "expression";
38460 case "ArrowFunctionExpression":
38461 // We do need parentheses, but SequenceExpressions are handled
38462 // specially when printing bodies of arrow functions.
38463 return name !== "body";
38466 // Otherwise err on the side of overparenthesization, adding
38467 // explicit exceptions above if this proves overzealous.
38471 case "YieldExpression":
38472 if (parent.type === "UnaryExpression" || parent.type === "AwaitExpression" || parent.type === "TSAsExpression" || parent.type === "TSNonNullExpression") {
38476 // else fallthrough
38478 case "AwaitExpression":
38479 switch (parent.type) {
38480 case "TaggedTemplateExpression":
38481 case "UnaryExpression":
38482 case "BinaryExpression":
38483 case "LogicalExpression":
38484 case "SpreadElement":
38485 case "SpreadProperty":
38486 case "TSAsExpression":
38487 case "TSNonNullExpression":
38488 case "BindExpression":
38491 case "MemberExpression":
38492 case "OptionalMemberExpression":
38493 return name === "object";
38495 case "NewExpression":
38496 case "CallExpression":
38497 case "OptionalCallExpression":
38498 return name === "callee";
38500 case "ConditionalExpression":
38501 return parent.test === node;
38507 case "TSJSDocFunctionType":
38508 case "TSConditionalType":
38509 if (parent.type === "TSConditionalType" && node === parent.extendsType) {
38515 case "TSFunctionType":
38516 case "TSConstructorType":
38517 if (parent.type === "TSConditionalType" && node === parent.checkType) {
38523 case "TSUnionType":
38524 case "TSIntersectionType":
38525 if (parent.type === "TSUnionType" || parent.type === "TSIntersectionType") {
38531 case "TSTypeOperator":
38532 case "TSInferType":
38533 return parent.type === "TSArrayType" || parent.type === "TSOptionalType" || parent.type === "TSRestType" || parent.type === "TSIndexedAccessType" && node === parent.objectType || parent.type === "TSTypeOperator" || parent.type === "TSTypeAnnotation" && /^TSJSDoc/.test(path.getParentNode(1).type);
38535 case "ArrayTypeAnnotation":
38536 return parent.type === "NullableTypeAnnotation";
38538 case "IntersectionTypeAnnotation":
38539 case "UnionTypeAnnotation":
38540 return parent.type === "ArrayTypeAnnotation" || parent.type === "NullableTypeAnnotation" || parent.type === "IntersectionTypeAnnotation" || parent.type === "UnionTypeAnnotation";
38542 case "NullableTypeAnnotation":
38543 return parent.type === "ArrayTypeAnnotation";
38545 case "FunctionTypeAnnotation":
38547 const ancestor = parent.type === "NullableTypeAnnotation" ? path.getParentNode(1) : parent;
38548 return ancestor.type === "UnionTypeAnnotation" || ancestor.type === "IntersectionTypeAnnotation" || ancestor.type === "ArrayTypeAnnotation" || // We should check ancestor's parent to know whether the parentheses
38549 // are really needed, but since ??T doesn't make sense this check
38550 // will almost never be true.
38551 ancestor.type === "NullableTypeAnnotation";
38554 case "StringLiteral":
38555 case "NumericLiteral":
38557 if (typeof node.value === "string" && parent.type === "ExpressionStatement" && ( // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2
38558 // See corresponding workaround in printer.js case: "Literal"
38559 options.parser !== "typescript" && !parent.directive || options.parser === "typescript" && options.originalText.charAt(options.locStart(node) - 1) === "(")) {
38560 // To avoid becoming a directive
38561 const grandParent = path.getParentNode(1);
38562 return grandParent.type === "Program" || grandParent.type === "BlockStatement";
38565 return parent.type === "MemberExpression" && typeof node.value === "number" && name === "object" && parent.object === node;
38567 case "AssignmentExpression":
38569 const grandParent = path.getParentNode(1);
38571 if (parent.type === "ArrowFunctionExpression" && parent.body === node) {
38573 } else if (parent.type === "ClassProperty" && parent.key === node && parent.computed) {
38575 } else if (parent.type === "TSPropertySignature" && parent.name === node) {
38577 } else if (parent.type === "ForStatement" && (parent.init === node || parent.update === node)) {
38579 } else if (parent.type === "ExpressionStatement") {
38580 return node.left.type === "ObjectPattern";
38581 } else if (parent.type === "TSPropertySignature" && parent.key === node) {
38583 } else if (parent.type === "AssignmentExpression") {
38585 } else if (parent.type === "SequenceExpression" && grandParent && grandParent.type === "ForStatement" && (grandParent.init === parent || grandParent.update === parent)) {
38587 } else if (parent.type === "Property" && parent.value === node) {
38589 } else if (parent.type === "NGChainedExpression") {
38596 case "ConditionalExpression":
38597 switch (parent.type) {
38598 case "TaggedTemplateExpression":
38599 case "UnaryExpression":
38600 case "SpreadElement":
38601 case "SpreadProperty":
38602 case "BinaryExpression":
38603 case "LogicalExpression":
38604 case "NGPipeExpression":
38605 case "ExportDefaultDeclaration":
38606 case "AwaitExpression":
38607 case "JSXSpreadAttribute":
38608 case "TSTypeAssertion":
38609 case "TypeCastExpression":
38610 case "TSAsExpression":
38611 case "TSNonNullExpression":
38614 case "NewExpression":
38615 case "CallExpression":
38616 case "OptionalCallExpression":
38617 return name === "callee";
38619 case "ConditionalExpression":
38620 return name === "test" && parent.test === node;
38622 case "MemberExpression":
38623 case "OptionalMemberExpression":
38624 return name === "object";
38630 case "FunctionExpression":
38631 switch (parent.type) {
38632 case "NewExpression":
38633 case "CallExpression":
38634 case "OptionalCallExpression":
38635 // Not always necessary, but it's clearer to the reader if IIFEs are wrapped in parentheses.
38636 // Is necessary if it is `expression` of `ExpressionStatement`.
38637 return name === "callee";
38639 case "TaggedTemplateExpression":
38641 // This is basically a kind of IIFE.
38647 case "ArrowFunctionExpression":
38648 switch (parent.type) {
38649 case "NewExpression":
38650 case "CallExpression":
38651 case "OptionalCallExpression":
38652 return name === "callee";
38654 case "MemberExpression":
38655 case "OptionalMemberExpression":
38656 return name === "object";
38658 case "TSAsExpression":
38659 case "BindExpression":
38660 case "TaggedTemplateExpression":
38661 case "UnaryExpression":
38662 case "LogicalExpression":
38663 case "BinaryExpression":
38664 case "AwaitExpression":
38665 case "TSTypeAssertion":
38668 case "ConditionalExpression":
38669 return name === "test";
38675 case "ClassExpression":
38676 switch (parent.type) {
38677 case "NewExpression":
38678 return name === "callee" && parent.callee === node;
38684 case "OptionalMemberExpression":
38685 case "OptionalCallExpression":
38686 if (parent.type === "MemberExpression" && name === "object" || (parent.type === "CallExpression" || parent.type === "NewExpression") && name === "callee") {
38692 case "CallExpression":
38693 case "MemberExpression":
38694 case "TaggedTemplateExpression":
38695 case "TSNonNullExpression":
38696 if ((parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee") {
38700 switch (object.type) {
38701 case "CallExpression":
38702 case "OptionalCallExpression":
38705 case "MemberExpression":
38706 case "OptionalMemberExpression":
38707 case "BindExpression":
38708 object = object.object;
38710 // tagged templates are basically member expressions from a grammar perspective
38711 // see https://tc39.github.io/ecma262/#prod-MemberExpression
38713 case "TaggedTemplateExpression":
38714 object = object.tag;
38717 case "TSNonNullExpression":
38718 object = object.expression;
38729 case "BindExpression":
38730 return (parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && name === "object";
38732 case "NGPipeExpression":
38733 if (parent.type === "NGRoot" || parent.type === "NGMicrosyntaxExpression" || parent.type === "ObjectProperty" || parent.type === "ArrayExpression" || (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.arguments[name] === node || parent.type === "NGPipeExpression" && name === "right" || parent.type === "MemberExpression" && name === "property" || parent.type === "AssignmentExpression") {
38739 case "JSXFragment":
38741 return name === "callee" || parent.type !== "ArrayExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "AssignmentExpression" && parent.type !== "AssignmentPattern" && parent.type !== "BinaryExpression" && parent.type !== "CallExpression" && parent.type !== "NewExpression" && parent.type !== "ConditionalExpression" && parent.type !== "ExpressionStatement" && parent.type !== "JsExpressionRoot" && parent.type !== "JSXAttribute" && parent.type !== "JSXElement" && parent.type !== "JSXExpressionContainer" && parent.type !== "JSXFragment" && parent.type !== "LogicalExpression" && parent.type !== "ObjectProperty" && parent.type !== "OptionalCallExpression" && parent.type !== "Property" && parent.type !== "ReturnStatement" && parent.type !== "ThrowStatement" && parent.type !== "TypeCastExpression" && parent.type !== "VariableDeclarator" && parent.type !== "YieldExpression";
38743 case "TypeAnnotation":
38744 return name === "returnType" && parent.type === "ArrowFunctionExpression" && includesFunctionTypeInObjectType(node);
38750 function isStatement(node) {
38751 return node.type === "BlockStatement" || node.type === "BreakStatement" || node.type === "ClassBody" || node.type === "ClassDeclaration" || node.type === "ClassMethod" || node.type === "ClassProperty" || node.type === "ClassPrivateProperty" || node.type === "ContinueStatement" || node.type === "DebuggerStatement" || node.type === "DeclareClass" || node.type === "DeclareExportAllDeclaration" || node.type === "DeclareExportDeclaration" || node.type === "DeclareFunction" || node.type === "DeclareInterface" || node.type === "DeclareModule" || node.type === "DeclareModuleExports" || node.type === "DeclareVariable" || node.type === "DoWhileStatement" || node.type === "EnumDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExpressionStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement" || node.type === "ForStatement" || node.type === "FunctionDeclaration" || node.type === "IfStatement" || node.type === "ImportDeclaration" || node.type === "InterfaceDeclaration" || node.type === "LabeledStatement" || node.type === "MethodDefinition" || node.type === "ReturnStatement" || node.type === "SwitchStatement" || node.type === "ThrowStatement" || node.type === "TryStatement" || node.type === "TSDeclareFunction" || node.type === "TSEnumDeclaration" || node.type === "TSImportEqualsDeclaration" || node.type === "TSInterfaceDeclaration" || node.type === "TSModuleDeclaration" || node.type === "TSNamespaceExportDeclaration" || node.type === "TypeAlias" || node.type === "VariableDeclaration" || node.type === "WhileStatement" || node.type === "WithStatement";
38754 function includesFunctionTypeInObjectType(node) {
38755 return hasNode$1(node, n1 => n1.type === "ObjectTypeAnnotation" && hasNode$1(n1, n2 => n2.type === "FunctionTypeAnnotation" || undefined) || undefined);
38758 function endsWithRightBracket(node) {
38759 switch (node.type) {
38760 case "ObjectExpression":
38768 function isFollowedByRightBracket(path) {
38769 const node = path.getValue();
38770 const parent = path.getParentNode();
38771 const name = path.getName();
38773 switch (parent.type) {
38774 case "NGPipeExpression":
38775 if (typeof name === "number" && parent.arguments[name] === node && parent.arguments.length - 1 === name) {
38776 return path.callParent(isFollowedByRightBracket);
38781 case "ObjectProperty":
38782 if (name === "value") {
38783 const parentParent = path.getParentNode(1);
38784 return parentParent.properties[parentParent.properties.length - 1] === parent;
38789 case "BinaryExpression":
38790 case "LogicalExpression":
38791 if (name === "right") {
38792 return path.callParent(isFollowedByRightBracket);
38797 case "ConditionalExpression":
38798 if (name === "alternate") {
38799 return path.callParent(isFollowedByRightBracket);
38804 case "UnaryExpression":
38805 if (parent.prefix) {
38806 return path.callParent(isFollowedByRightBracket);
38815 function shouldWrapFunctionForExportDefault(path, options) {
38816 const node = path.getValue();
38817 const parent = path.getParentNode();
38819 if (node.type === "FunctionExpression" || node.type === "ClassExpression") {
38820 return parent.type === "ExportDefaultDeclaration" || // in some cases the function is already wrapped
38821 // (e.g. `export default (function() {})();`)
38822 // in this case we don't need to add extra parens
38823 !needsParens(path, options);
38826 if (!hasNakedLeftSide$1(node) || parent.type !== "ExportDefaultDeclaration" && needsParens(path, options)) {
38830 return path.call(childPath => shouldWrapFunctionForExportDefault(childPath, options), ...getLeftSidePathName$1(path, node));
38833 var needsParens_1 = needsParens;
38843 function printHtmlBinding(path, options, print) {
38844 const node = path.getValue();
38846 if (options.__onHtmlBindingRoot && path.getName() === null) {
38847 options.__onHtmlBindingRoot(node, options);
38850 if (node.type !== "File") {
38854 if (options.__isVueForBindingLeft) {
38855 return path.call(functionDeclarationPath => {
38858 } = functionDeclarationPath.getValue();
38859 return concat$5([params.length > 1 ? "(" : "", join$3(concat$5([",", line$3]), functionDeclarationPath.map(print, "params")), params.length > 1 ? ")" : ""]);
38860 }, "program", "body", 0);
38863 if (options.__isVueSlotScope) {
38864 return path.call(functionDeclarationPath => join$3(concat$5([",", line$3]), functionDeclarationPath.map(print, "params")), "program", "body", 0);
38866 } // based on https://github.com/prettier/prettier/blob/master/src/language-html/syntax-vue.js isVueEventBindingExpression()
38869 function isVueEventBindingExpression(node) {
38870 switch (node.type) {
38871 case "MemberExpression":
38872 switch (node.property.type) {
38874 case "NumericLiteral":
38875 case "StringLiteral":
38876 return isVueEventBindingExpression(node.object);
38889 var htmlBinding = {
38890 isVueEventBindingExpression,
38894 function preprocess(ast, options) {
38895 switch (options.parser) {
38898 case "json-stringify":
38899 case "__js_expression":
38900 case "__vue_expression":
38901 return Object.assign({}, ast, {
38902 type: options.parser.startsWith("__") ? "JsExpressionRoot" : "JsonRoot",
38905 rootMarker: options.rootMarker
38913 var preprocess_1 = preprocess;
38916 shouldFlatten: shouldFlatten$1,
38917 getNextNonSpaceNonCommentCharacter: getNextNonSpaceNonCommentCharacter$1,
38918 hasNewline: hasNewline$4,
38919 hasNewlineInRange: hasNewlineInRange$3,
38920 getLast: getLast$2,
38921 getStringWidth: getStringWidth$3,
38922 printString: printString$1,
38923 printNumber: printNumber$1,
38924 hasIgnoreComment: hasIgnoreComment$2,
38925 hasNodeIgnoreComment: hasNodeIgnoreComment$2,
38926 getPenultimate: getPenultimate$1,
38927 startsWithNoLookaheadToken: startsWithNoLookaheadToken$1,
38928 getIndentSize: getIndentSize$2,
38929 getPreferredQuote: getPreferredQuote$1
38932 isNextLineEmpty: isNextLineEmpty$2,
38933 isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$2,
38934 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$3
38937 insertPragma: insertPragma$1
38940 printHtmlBinding: printHtmlBinding$1,
38941 isVueEventBindingExpression: isVueEventBindingExpression$1
38944 classChildNeedsASIProtection: classChildNeedsASIProtection$1,
38945 classPropMayCauseASIProblems: classPropMayCauseASIProblems$1,
38946 conditionalExpressionChainContainsJSX: conditionalExpressionChainContainsJSX$1,
38947 getFlowVariance: getFlowVariance$1,
38948 getLeftSidePathName: getLeftSidePathName$2,
38949 getParentExportDeclaration: getParentExportDeclaration$1,
38950 getTypeScriptMappedTypeModifier: getTypeScriptMappedTypeModifier$1,
38951 hasDanglingComments: hasDanglingComments$1,
38952 hasFlowAnnotationComment: hasFlowAnnotationComment$1,
38953 hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$2,
38954 hasLeadingComment: hasLeadingComment$3,
38955 hasLeadingOwnLineComment: hasLeadingOwnLineComment$1,
38956 hasNakedLeftSide: hasNakedLeftSide$2,
38957 hasNewlineBetweenOrAfterDecorators: hasNewlineBetweenOrAfterDecorators$1,
38958 hasNgSideEffect: hasNgSideEffect$1,
38959 hasPrettierIgnore: hasPrettierIgnore$1,
38960 hasTrailingComment: hasTrailingComment$1,
38961 identity: identity$2,
38962 isBinaryish: isBinaryish$1,
38963 isCallOrOptionalCallExpression: isCallOrOptionalCallExpression$1,
38964 isEmptyJSXElement: isEmptyJSXElement$1,
38965 isExportDeclaration: isExportDeclaration$1,
38966 isFlowAnnotationComment: isFlowAnnotationComment$1,
38967 isFunctionCompositionArgs: isFunctionCompositionArgs$1,
38968 isFunctionNotation: isFunctionNotation$1,
38969 isFunctionOrArrowExpression: isFunctionOrArrowExpression$1,
38970 isGetterOrSetter: isGetterOrSetter$1,
38971 isJestEachTemplateLiteral: isJestEachTemplateLiteral$1,
38972 isJSXNode: isJSXNode$1,
38973 isJSXWhitespaceExpression: isJSXWhitespaceExpression$1,
38974 isLastStatement: isLastStatement$1,
38975 isLiteral: isLiteral$1,
38976 isLongCurriedCallExpression: isLongCurriedCallExpression$1,
38977 isMeaningfulJSXText: isMeaningfulJSXText$1,
38978 isMemberExpressionChain: isMemberExpressionChain$1,
38979 isMemberish: isMemberish$1,
38980 isNgForOf: isNgForOf$1,
38981 isNumericLiteral: isNumericLiteral$1,
38982 isObjectType: isObjectType$1,
38983 isObjectTypePropertyAFunction: isObjectTypePropertyAFunction$1,
38984 isSimpleCallArgument: isSimpleCallArgument$1,
38985 isSimpleFlowType: isSimpleFlowType$1,
38986 isSimpleTemplateLiteral: isSimpleTemplateLiteral$1,
38987 isStringLiteral: isStringLiteral$1,
38988 isStringPropSafeToCoerceToIdentifier: isStringPropSafeToCoerceToIdentifier$1,
38989 isTemplateOnItsOwnLine: isTemplateOnItsOwnLine$1,
38990 isTestCall: isTestCall$1,
38991 isTheOnlyJSXElementInMarkdown: isTheOnlyJSXElementInMarkdown$1,
38992 isTSXFile: isTSXFile$1,
38993 isTypeAnnotationAFunction: isTypeAnnotationAFunction$1,
38994 matchJsxWhitespaceRegex: matchJsxWhitespaceRegex$1,
38995 needsHardlineAfterDanglingComment: needsHardlineAfterDanglingComment$1,
38996 rawText: rawText$1,
38997 returnArgumentHasLeadingComment: returnArgumentHasLeadingComment$1
38999 const needsQuoteProps = new WeakMap();
39005 hardline: hardline$4,
39006 softline: softline$2,
39007 literalline: literalline$2,
39011 conditionalGroup: conditionalGroup$1,
39013 ifBreak: ifBreak$1,
39014 breakParent: breakParent$2,
39015 lineSuffixBoundary: lineSuffixBoundary$1,
39016 addAlignmentToDoc: addAlignmentToDoc$2,
39020 willBreak: willBreak$1,
39021 isLineNext: isLineNext$1,
39022 isEmpty: isEmpty$1,
39023 removeLines: removeLines$1
39026 printDocToString: printDocToString$2
39031 function shouldPrintComma(options, level) {
39032 level = level || "es5";
39034 switch (options.trailingComma) {
39036 if (level === "all") {
39043 if (level === "es5") {
39055 function genericPrint(path, options, printPath, args) {
39056 const node = path.getValue();
39057 let needsParens = false;
39058 const linesWithoutParens = printPathNoParens(path, options, printPath, args);
39060 if (!node || isEmpty$1(linesWithoutParens)) {
39061 return linesWithoutParens;
39064 const parentExportDecl = getParentExportDeclaration$1(path);
39065 const decorators = [];
39067 if (node.type === "ClassMethod" || node.type === "ClassPrivateMethod" || node.type === "ClassProperty" || node.type === "TSAbstractClassProperty" || node.type === "ClassPrivateProperty" || node.type === "MethodDefinition" || node.type === "TSAbstractMethodDefinition" || node.type === "TSDeclareMethod") ; else if (node.decorators && node.decorators.length > 0 && // If the parent node is an export declaration and the decorator
39068 // was written before the export, the export will be responsible
39069 // for printing the decorators.
39070 !(parentExportDecl && options.locStart(parentExportDecl, {
39071 ignoreDecorators: true
39072 }) > options.locStart(node.decorators[0]))) {
39073 const shouldBreak = node.type === "ClassExpression" || node.type === "ClassDeclaration" || hasNewlineBetweenOrAfterDecorators$1(node, options);
39074 const separator = shouldBreak ? hardline$4 : line$4;
39075 path.each(decoratorPath => {
39076 let decorator = decoratorPath.getValue();
39078 if (decorator.expression) {
39079 decorator = decorator.expression;
39081 decorator = decorator.callee;
39084 decorators.push(printPath(decoratorPath), separator);
39087 if (parentExportDecl) {
39088 decorators.unshift(hardline$4);
39090 } else if (isExportDeclaration$1(node) && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0 && // Only print decorators here if they were written before the export,
39091 // otherwise they are printed by the node.declaration
39092 options.locStart(node, {
39093 ignoreDecorators: true
39094 }) > options.locStart(node.declaration.decorators[0])) {
39095 // Export declarations are responsible for printing any decorators
39096 // that logically apply to node.declaration.
39097 path.each(decoratorPath => {
39098 const decorator = decoratorPath.getValue();
39099 const prefix = decorator.type === "Decorator" ? "" : "@";
39100 decorators.push(prefix, printPath(decoratorPath), hardline$4);
39101 }, "declaration", "decorators");
39103 // Nodes with decorators can't have parentheses, so we can avoid
39104 // computing pathNeedsParens() except in this case.
39105 needsParens = needsParens_1(path, options);
39111 parts.unshift("(");
39114 parts.push(linesWithoutParens);
39117 const node = path.getValue();
39119 if (hasFlowShorthandAnnotationComment$2(node)) {
39121 parts.push(node.trailingComments[0].value.trimStart());
39123 node.trailingComments[0].printed = true;
39129 if (decorators.length > 0) {
39130 return group$2(concat$6(decorators.concat(parts)));
39133 return concat$6(parts);
39136 function printDecorators(path, options, print) {
39137 const node = path.getValue();
39138 return group$2(concat$6([join$4(line$4, path.map(print, "decorators")), hasNewlineBetweenOrAfterDecorators$1(node, options) ? hardline$4 : line$4]));
39141 * The following is the shared logic for
39142 * ternary operators, namely ConditionalExpression
39143 * and TSConditionalType
39144 * @typedef {Object} OperatorOptions
39145 * @property {() => Array<string | Doc>} beforeParts - Parts to print before the `?`.
39146 * @property {(breakClosingParen: boolean) => Array<string | Doc>} afterParts - Parts to print after the conditional expression.
39147 * @property {boolean} shouldCheckJsx - Whether to check for and print in JSX mode.
39148 * @property {string} conditionalNodeType - The type of the conditional expression node, ie "ConditionalExpression" or "TSConditionalType".
39149 * @property {string} consequentNodePropertyName - The property at which the consequent node can be found on the main node, eg "consequent".
39150 * @property {string} alternateNodePropertyName - The property at which the alternate node can be found on the main node, eg "alternate".
39151 * @property {string[]} testNodePropertyNames - The properties at which the test nodes can be found on the main node, eg "test".
39152 * @param {FastPath} path - The path to the ConditionalExpression/TSConditionalType node.
39153 * @param {Options} options - Prettier options
39154 * @param {Function} print - Print function to call recursively
39155 * @param {OperatorOptions} operatorOptions
39160 function printTernaryOperator(path, options, print, operatorOptions) {
39161 const node = path.getValue();
39162 const consequentNode = node[operatorOptions.consequentNodePropertyName];
39163 const alternateNode = node[operatorOptions.alternateNodePropertyName];
39164 const parts = []; // We print a ConditionalExpression in either "JSX mode" or "normal mode".
39165 // See tests/jsx/conditional-expression.js for more info.
39167 let jsxMode = false;
39168 const parent = path.getParentNode();
39169 const isParentTest = parent.type === operatorOptions.conditionalNodeType && operatorOptions.testNodePropertyNames.some(prop => parent[prop] === node);
39170 let forceNoIndent = parent.type === operatorOptions.conditionalNodeType && !isParentTest; // Find the outermost non-ConditionalExpression parent, and the outermost
39171 // ConditionalExpression parent. We'll use these to determine if we should
39172 // print in JSX mode.
39175 let previousParent;
39179 previousParent = currentParent || node;
39180 currentParent = path.getParentNode(i);
39182 } while (currentParent && currentParent.type === operatorOptions.conditionalNodeType && operatorOptions.testNodePropertyNames.every(prop => currentParent[prop] !== previousParent));
39184 const firstNonConditionalParent = currentParent || parent;
39185 const lastConditionalParent = previousParent;
39187 if (operatorOptions.shouldCheckJsx && (isJSXNode$1(node[operatorOptions.testNodePropertyNames[0]]) || isJSXNode$1(consequentNode) || isJSXNode$1(alternateNode) || conditionalExpressionChainContainsJSX$1(lastConditionalParent))) {
39189 forceNoIndent = true; // Even though they don't need parens, we wrap (almost) everything in
39190 // parens when using ?: within JSX, because the parens are analogous to
39191 // curly braces in an if statement.
39193 const wrap = doc => concat$6([ifBreak$1("(", ""), indent$3(concat$6([softline$2, doc])), softline$2, ifBreak$1(")", "")]); // The only things we don't wrap are:
39194 // * Nested conditional expressions in alternates
39199 const isNil = node => node.type === "NullLiteral" || node.type === "Literal" && node.value === null || node.type === "Identifier" && node.name === "undefined";
39201 parts.push(" ? ", isNil(consequentNode) ? path.call(print, operatorOptions.consequentNodePropertyName) : wrap(path.call(print, operatorOptions.consequentNodePropertyName)), " : ", alternateNode.type === operatorOptions.conditionalNodeType || isNil(alternateNode) ? path.call(print, operatorOptions.alternateNodePropertyName) : wrap(path.call(print, operatorOptions.alternateNodePropertyName)));
39204 const part = concat$6([line$4, "? ", consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$1("", "(") : "", align$1(2, path.call(print, operatorOptions.consequentNodePropertyName)), consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$1("", ")") : "", line$4, ": ", alternateNode.type === operatorOptions.conditionalNodeType ? path.call(print, operatorOptions.alternateNodePropertyName) : align$1(2, path.call(print, operatorOptions.alternateNodePropertyName))]);
39205 parts.push(parent.type !== operatorOptions.conditionalNodeType || parent[operatorOptions.alternateNodePropertyName] === node || isParentTest ? part : options.useTabs ? dedent$1(indent$3(part)) : align$1(Math.max(0, options.tabWidth - 2), part));
39206 } // We want a whole chain of ConditionalExpressions to all
39207 // break if any of them break. That means we should only group around the
39208 // outer-most ConditionalExpression.
39211 const maybeGroup = doc => parent === firstNonConditionalParent ? group$2(doc) : doc; // Break the closing paren to keep the chain right after it:
39218 const breakClosingParen = !jsxMode && (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression" || parent.type === "NGPipeExpression" && parent.left === node) && !parent.computed;
39219 const result = maybeGroup(concat$6([].concat((testDoc =>
39230 parent.type === operatorOptions.conditionalNodeType && parent[operatorOptions.alternateNodePropertyName] === node ? align$1(2, testDoc) : testDoc)(concat$6(operatorOptions.beforeParts())), forceNoIndent ? concat$6(parts) : indent$3(concat$6(parts)), operatorOptions.afterParts(breakClosingParen))));
39231 return isParentTest ? group$2(concat$6([indent$3(concat$6([softline$2, result])), softline$2])) : result;
39234 function printPathNoParens(path, options, print, args) {
39235 const n = path.getValue();
39236 const semi = options.semi ? ";" : "";
39242 if (typeof n === "string") {
39246 const htmlBinding = printHtmlBinding$1(path, options, print);
39249 return htmlBinding;
39255 case "JsExpressionRoot":
39256 return path.call(print, "node");
39259 return concat$6([path.call(print, "node"), hardline$4]);
39262 // Print @babel/parser's InterpreterDirective here so that
39263 // leading comments on the `Program` node get printed after the hashbang.
39264 if (n.program && n.program.interpreter) {
39265 parts.push(path.call(programPath => programPath.call(print, "interpreter"), "program"));
39268 parts.push(path.call(print, "program"));
39269 return concat$6(parts);
39273 if (n.directives) {
39274 path.each(childPath => {
39275 parts.push(print(childPath), semi, hardline$4);
39277 if (isNextLineEmpty$2(options.originalText, childPath.getValue(), options.locEnd)) {
39278 parts.push(hardline$4);
39283 parts.push(path.call(bodyPath => {
39284 return printStatementSequence(bodyPath, options, print);
39286 parts.push(comments.printDanglingComments(path, options,
39288 true)); // Only force a trailing newline if there were any contents.
39290 if (!n.body.every(({
39292 }) => type === "EmptyStatement") || n.comments) {
39293 parts.push(hardline$4);
39296 return concat$6(parts);
39297 // Babel extension.
39299 case "EmptyStatement":
39302 case "ExpressionStatement":
39303 // Detect Flow-parsed directives
39305 return concat$6([nodeStr(n.expression, options, true), semi]);
39308 if (options.parser === "__vue_event_binding") {
39309 const parent = path.getParentNode();
39311 if (parent.type === "Program" && parent.body.length === 1 && parent.body[0] === n) {
39312 return concat$6([path.call(print, "expression"), isVueEventBindingExpression$1(n.expression) ? ";" : ""]);
39314 } // Do not append semicolon after the only JSX element in a program
39317 return concat$6([path.call(print, "expression"), isTheOnlyJSXElementInMarkdown$1(options, path) ? "" : semi]);
39318 // Babel non-standard node. Used for Closure-style type casts. See postprocess.js.
39320 case "ParenthesizedExpression":
39322 const shouldHug = !n.expression.comments;
39325 return concat$6(["(", path.call(print, "expression"), ")"]);
39328 return group$2(concat$6(["(", indent$3(concat$6([softline$2, path.call(print, "expression")])), softline$2, ")"]));
39331 case "AssignmentExpression":
39332 return printAssignment(n.left, path.call(print, "left"), concat$6([" ", n.operator]), n.right, path.call(print, "right"), options);
39334 case "BinaryExpression":
39335 case "LogicalExpression":
39336 case "NGPipeExpression":
39338 const parent = path.getParentNode();
39339 const parentParent = path.getParentNode(1);
39340 const isInsideParenthesis = n !== parent.body && (parent.type === "IfStatement" || parent.type === "WhileStatement" || parent.type === "SwitchStatement" || parent.type === "DoWhileStatement");
39341 const parts = printBinaryishExpressions(path, print, options,
39343 false, isInsideParenthesis); // if (
39344 // this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft
39347 // looks super weird, we want to break the children if the parent breaks
39350 // this.hasPlugin("dynamicImports") &&
39351 // this.lookahead().type === tt.parenLeft
39354 if (isInsideParenthesis) {
39355 return concat$6(parts);
39356 } // Break between the parens in
39357 // unaries or in a member or specific call expression, i.e.
39366 if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || parent.type === "UnaryExpression" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && !parent.computed) {
39367 return group$2(concat$6([indent$3(concat$6([softline$2, concat$6(parts)])), softline$2]));
39368 } // Avoid indenting sub-expressions in some cases where the first sub-expression is already
39369 // indented accordingly. We should indent sub-expressions where the first case isn't indented.
39372 const shouldNotIndent = parent.type === "ReturnStatement" || parent.type === "ThrowStatement" || parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" || n.operator !== "|" && parent.type === "JsExpressionRoot" || n.type !== "NGPipeExpression" && (parent.type === "NGRoot" && options.parser === "__ng_binding" || parent.type === "NGMicrosyntaxExpression" && parentParent.type === "NGMicrosyntax" && parentParent.body.length === 1) || n === parent.body && parent.type === "ArrowFunctionExpression" || n !== parent.body && parent.type === "ForStatement" || parent.type === "ConditionalExpression" && parentParent.type !== "ReturnStatement" && parentParent.type !== "ThrowStatement" && parentParent.type !== "CallExpression" && parentParent.type !== "OptionalCallExpression" || parent.type === "TemplateLiteral";
39373 const shouldIndentIfInlining = parent.type === "AssignmentExpression" || parent.type === "VariableDeclarator" || parent.type === "ClassProperty" || parent.type === "TSAbstractClassProperty" || parent.type === "ClassPrivateProperty" || parent.type === "ObjectProperty" || parent.type === "Property";
39374 const samePrecedenceSubExpression = isBinaryish$1(n.left) && shouldFlatten$1(n.operator, n.left.operator);
39376 if (shouldNotIndent || shouldInlineLogicalExpression(n) && !samePrecedenceSubExpression || !shouldInlineLogicalExpression(n) && shouldIndentIfInlining) {
39377 return group$2(concat$6(parts));
39380 if (parts.length === 0) {
39382 } // If the right part is a JSX node, we include it in a separate group to
39383 // prevent it breaking the whole chain, so we can print the expression like:
39392 const hasJSX = isJSXNode$1(n.right);
39393 const rest = concat$6(hasJSX ? parts.slice(1, -1) : parts.slice(1));
39394 const groupId = Symbol("logicalChain-" + ++uid);
39395 const chain = group$2(concat$6([// Don't include the initial expression in the indentation
39396 // level. The first item is guaranteed to be the first
39397 // left-most expression.
39398 parts.length > 0 ? parts[0] : "", indent$3(rest)]), {
39406 const jsxPart = getLast$2(parts);
39407 return group$2(concat$6([chain, ifBreak$1(indent$3(jsxPart), jsxPart, {
39412 case "AssignmentPattern":
39413 return concat$6([path.call(print, "left"), " = ", path.call(print, "right")]);
39415 case "TSTypeAssertion":
39417 const shouldBreakAfterCast = !(n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression");
39418 const castGroup = group$2(concat$6(["<", indent$3(concat$6([softline$2, path.call(print, "typeAnnotation")])), softline$2, ">"]));
39419 const exprContents = concat$6([ifBreak$1("("), indent$3(concat$6([softline$2, path.call(print, "expression")])), softline$2, ifBreak$1(")")]);
39421 if (shouldBreakAfterCast) {
39422 return conditionalGroup$1([concat$6([castGroup, path.call(print, "expression")]), concat$6([castGroup, group$2(exprContents, {
39424 })]), concat$6([castGroup, path.call(print, "expression")])]);
39427 return group$2(concat$6([castGroup, path.call(print, "expression")]));
39430 case "OptionalMemberExpression":
39431 case "MemberExpression":
39433 const parent = path.getParentNode();
39434 let firstNonMemberParent;
39438 firstNonMemberParent = path.getParentNode(i);
39440 } while (firstNonMemberParent && (firstNonMemberParent.type === "MemberExpression" || firstNonMemberParent.type === "OptionalMemberExpression" || firstNonMemberParent.type === "TSNonNullExpression"));
39442 const shouldInline = firstNonMemberParent && (firstNonMemberParent.type === "NewExpression" || firstNonMemberParent.type === "BindExpression" || firstNonMemberParent.type === "VariableDeclarator" && firstNonMemberParent.id.type !== "Identifier" || firstNonMemberParent.type === "AssignmentExpression" && firstNonMemberParent.left.type !== "Identifier") || n.computed || n.object.type === "Identifier" && n.property.type === "Identifier" && parent.type !== "MemberExpression" && parent.type !== "OptionalMemberExpression";
39443 return concat$6([path.call(print, "object"), shouldInline ? printMemberLookup(path, options, print) : group$2(indent$3(concat$6([softline$2, printMemberLookup(path, options, print)])))]);
39446 case "MetaProperty":
39447 return concat$6([path.call(print, "meta"), ".", path.call(print, "property")]);
39449 case "BindExpression":
39451 parts.push(path.call(print, "object"));
39454 parts.push(group$2(indent$3(concat$6([softline$2, printBindExpressionCallee(path, options, print)]))));
39455 return concat$6(parts);
39459 return concat$6([n.name, printOptionalToken(path), printTypeAnnotation(path, options, print)]);
39462 case "V8IntrinsicIdentifier":
39463 return concat$6(["%", n.name]);
39465 case "SpreadElement":
39466 case "SpreadElementPattern":
39467 case "SpreadProperty":
39468 case "SpreadPropertyPattern":
39469 case "RestElement":
39470 case "ObjectTypeSpreadProperty":
39471 return concat$6(["...", path.call(print, "argument"), printTypeAnnotation(path, options, print)]);
39473 case "FunctionDeclaration":
39474 case "FunctionExpression":
39475 parts.push(printFunctionDeclaration(path, print, options));
39481 return concat$6(parts);
39483 case "ArrowFunctionExpression":
39486 parts.push("async ");
39489 if (shouldPrintParamsWithoutParens(path, options)) {
39490 parts.push(path.call(print, "params", 0));
39492 parts.push(group$2(concat$6([printFunctionParams(path, print, options,
39494 args && (args.expandLastArg || args.expandFirstArg),
39495 /* printTypeParams */
39496 true), printReturnType(path, print, options)])));
39499 const dangling = comments.printDanglingComments(path, options,
39502 const nextCharacter = getNextNonSpaceNonCommentCharacterIndex$3(options.originalText, comment, options.locEnd);
39503 return options.originalText.slice(nextCharacter, nextCharacter + 2) === "=>";
39507 parts.push(" ", dangling);
39511 const body = path.call(bodyPath => print(bodyPath, args), "body"); // We want to always keep these types of nodes on the same line
39514 if (!hasLeadingOwnLineComment$1(options.originalText, n.body, options) && (n.body.type === "ArrayExpression" || n.body.type === "ObjectExpression" || n.body.type === "BlockStatement" || isJSXNode$1(n.body) || isTemplateOnItsOwnLine$1(n.body, options.originalText, options) || n.body.type === "ArrowFunctionExpression" || n.body.type === "DoExpression")) {
39515 return group$2(concat$6([concat$6(parts), " ", body]));
39516 } // We handle sequence expressions as the body of arrows specially,
39517 // so that the required parentheses end up on their own lines.
39520 if (n.body.type === "SequenceExpression") {
39521 return group$2(concat$6([concat$6(parts), group$2(concat$6([" (", indent$3(concat$6([softline$2, body])), softline$2, ")"]))]));
39522 } // if the arrow function is expanded as last argument, we are adding a
39523 // level of indentation and need to add a softline to align the closing )
39524 // with the opening (, or if it's inside a JSXExpression (e.g. an attribute)
39525 // we should align the expression's closing } with the line with the opening {.
39528 const shouldAddSoftLine = (args && args.expandLastArg || path.getParentNode().type === "JSXExpressionContainer") && !(n.comments && n.comments.length);
39529 const printTrailingComma = args && args.expandLastArg && shouldPrintComma(options, "all"); // In order to avoid confusion between
39533 const shouldAddParens = n.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken$1(n.body,
39534 /* forbidFunctionAndClass */
39536 return group$2(concat$6([concat$6(parts), group$2(concat$6([indent$3(concat$6([line$4, shouldAddParens ? ifBreak$1("", "(") : "", body, shouldAddParens ? ifBreak$1("", ")") : ""])), shouldAddSoftLine ? concat$6([ifBreak$1(printTrailingComma ? "," : ""), softline$2]) : ""]))]));
39539 case "YieldExpression":
39540 parts.push("yield");
39547 parts.push(" ", path.call(print, "argument"));
39550 return concat$6(parts);
39552 case "AwaitExpression":
39554 parts.push("await ", path.call(print, "argument"));
39555 const parent = path.getParentNode();
39557 if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && parent.object === n) {
39558 return group$2(concat$6([indent$3(concat$6([softline$2, concat$6(parts)])), softline$2]));
39561 return concat$6(parts);
39564 case "ImportSpecifier":
39565 if (n.importKind) {
39566 parts.push(path.call(print, "importKind"), " ");
39569 parts.push(path.call(print, "imported"));
39571 if (n.local && n.local.name !== n.imported.name) {
39572 parts.push(" as ", path.call(print, "local"));
39575 return concat$6(parts);
39577 case "ExportSpecifier":
39578 parts.push(path.call(print, "local"));
39580 if (n.exported && n.exported.name !== n.local.name) {
39581 parts.push(" as ", path.call(print, "exported"));
39584 return concat$6(parts);
39586 case "ImportNamespaceSpecifier":
39587 parts.push("* as ");
39588 parts.push(path.call(print, "local"));
39589 return concat$6(parts);
39591 case "ImportDefaultSpecifier":
39592 return path.call(print, "local");
39594 case "TSExportAssignment":
39595 return concat$6(["export = ", path.call(print, "expression"), semi]);
39597 case "ExportDefaultDeclaration":
39598 case "ExportNamedDeclaration":
39599 return printExportDeclaration(path, options, print);
39601 case "ExportAllDeclaration":
39602 parts.push("export ");
39604 if (n.exportKind === "type") {
39605 parts.push("type ");
39611 parts.push("as ", path.call(print, "exported"), " ");
39614 parts.push("from ", path.call(print, "source"), semi);
39615 return concat$6(parts);
39617 case "ExportNamespaceSpecifier":
39618 case "ExportDefaultSpecifier":
39619 return path.call(print, "exported");
39621 case "ImportDeclaration":
39623 parts.push("import ");
39625 if (n.importKind && n.importKind !== "value") {
39626 parts.push(n.importKind + " ");
39629 const standalones = [];
39630 const grouped = [];
39632 if (n.specifiers && n.specifiers.length > 0) {
39633 path.each(specifierPath => {
39634 const value = specifierPath.getValue();
39636 if (value.type === "ImportDefaultSpecifier" || value.type === "ImportNamespaceSpecifier") {
39637 standalones.push(print(specifierPath));
39639 grouped.push(print(specifierPath));
39643 if (standalones.length > 0) {
39644 parts.push(join$4(", ", standalones));
39647 if (standalones.length > 0 && grouped.length > 0) {
39651 if (grouped.length === 1 && standalones.length === 0 && n.specifiers && !n.specifiers.some(node => node.comments)) {
39652 parts.push(concat$6(["{", options.bracketSpacing ? " " : "", concat$6(grouped), options.bracketSpacing ? " " : "", "}"]));
39653 } else if (grouped.length >= 1) {
39654 parts.push(group$2(concat$6(["{", indent$3(concat$6([options.bracketSpacing ? line$4 : softline$2, join$4(concat$6([",", line$4]), grouped)])), ifBreak$1(shouldPrintComma(options) ? "," : ""), options.bracketSpacing ? line$4 : softline$2, "}"])));
39657 parts.push(" from ");
39658 } else if (n.importKind && n.importKind === "type" || // import {} from 'x'
39659 /{\s*}/.test(options.originalText.slice(options.locStart(n), options.locStart(n.source)))) {
39660 parts.push("{} from ");
39663 parts.push(path.call(print, "source"), semi);
39664 return concat$6(parts);
39670 case "TSModuleBlock":
39671 case "BlockStatement":
39673 const naked = path.call(bodyPath => {
39674 return printStatementSequence(bodyPath, options, print);
39676 const hasContent = n.body.find(node => node.type !== "EmptyStatement");
39677 const hasDirectives = n.directives && n.directives.length > 0;
39678 const parent = path.getParentNode();
39679 const parentParent = path.getParentNode(1);
39681 if (!hasContent && !hasDirectives && !hasDanglingComments$1(n) && (parent.type === "ArrowFunctionExpression" || parent.type === "FunctionExpression" || parent.type === "FunctionDeclaration" || parent.type === "ObjectMethod" || parent.type === "ClassMethod" || parent.type === "ClassPrivateMethod" || parent.type === "ForStatement" || parent.type === "WhileStatement" || parent.type === "DoWhileStatement" || parent.type === "DoExpression" || parent.type === "CatchClause" && !parentParent.finalizer || parent.type === "TSModuleDeclaration")) {
39685 parts.push("{"); // Babel 6
39687 if (hasDirectives) {
39688 path.each(childPath => {
39689 parts.push(indent$3(concat$6([hardline$4, print(childPath), semi])));
39691 if (isNextLineEmpty$2(options.originalText, childPath.getValue(), options.locEnd)) {
39692 parts.push(hardline$4);
39698 parts.push(indent$3(concat$6([hardline$4, naked])));
39701 parts.push(comments.printDanglingComments(path, options));
39702 parts.push(hardline$4, "}");
39703 return concat$6(parts);
39706 case "ReturnStatement":
39707 return concat$6(["return", printReturnAndThrowArgument(path, options, print)]);
39709 case "NewExpression":
39710 case "OptionalCallExpression":
39711 case "CallExpression":
39713 const isNew = n.type === "NewExpression";
39714 const optional = printOptionalToken(path);
39716 if ( // We want to keep CommonJS- and AMD-style require calls, and AMD-style
39717 // define calls, as a unit.
39718 // e.g. `define(["some/lib", (lib) => {`
39719 !isNew && n.callee.type === "Identifier" && (n.callee.name === "require" || n.callee.name === "define") || // Template literals as single arguments
39720 n.arguments.length === 1 && isTemplateOnItsOwnLine$1(n.arguments[0], options.originalText, options) || // Keep test declarations on a single line
39721 // e.g. `it('long name', () => {`
39722 !isNew && isTestCall$1(n, path.getParentNode())) {
39723 return concat$6([isNew ? "new " : "", path.call(print, "callee"), optional, printFunctionTypeParameters(path, options, print), concat$6(["(", join$4(", ", path.map(print, "arguments")), ")"])]);
39724 } // Inline Flow annotation comments following Identifiers in Call nodes need to
39725 // stay with the Identifier. For example:
39727 // foo /*:: <SomeGeneric> */(bar);
39729 // Here, we ensure that such comments stay between the Identifier and the Callee.
39732 const isIdentifierWithFlowAnnotation = n.callee.type === "Identifier" && hasFlowAnnotationComment$1(n.callee.trailingComments);
39734 if (isIdentifierWithFlowAnnotation) {
39735 n.callee.trailingComments[0].printed = true;
39736 } // We detect calls on member lookups and possibly print them in a
39737 // special chain format. See `printMemberChain` for more info.
39740 if (!isNew && isMemberish$1(n.callee) && !path.call(path => needsParens_1(path, options), "callee")) {
39741 return printMemberChain(path, options, print);
39744 const contents = concat$6([isNew ? "new " : "", path.call(print, "callee"), optional, isIdentifierWithFlowAnnotation ? `/*:: ${n.callee.trailingComments[0].value.slice(2).trim()} */` : "", printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]); // We group here when the callee is itself a call expression.
39745 // See `isLongCurriedCallExpression` for more info.
39747 if (isCallOrOptionalCallExpression$1(n.callee)) {
39748 return group$2(contents);
39754 case "TSInterfaceDeclaration":
39756 parts.push("declare ");
39759 parts.push(n.abstract ? "abstract " : "", printTypeScriptModifiers(path, options, print), "interface ", path.call(print, "id"), n.typeParameters ? path.call(print, "typeParameters") : "", " ");
39761 if (n.extends && n.extends.length) {
39762 parts.push(group$2(indent$3(concat$6([softline$2, "extends ", (n.extends.length === 1 ? identity$2 : indent$3)(join$4(concat$6([",", line$4]), path.map(print, "extends"))), " "]))));
39765 parts.push(path.call(print, "body"));
39766 return concat$6(parts);
39768 case "ObjectTypeInternalSlot":
39769 return concat$6([n.static ? "static " : "", "[[", path.call(print, "id"), "]]", printOptionalToken(path), n.method ? "" : ": ", path.call(print, "value")]);
39771 case "ObjectExpression":
39772 case "ObjectPattern":
39773 case "ObjectTypeAnnotation":
39774 case "TSInterfaceBody":
39775 case "TSTypeLiteral":
39777 let propertiesField;
39779 if (n.type === "TSTypeLiteral") {
39780 propertiesField = "members";
39781 } else if (n.type === "TSInterfaceBody") {
39782 propertiesField = "body";
39784 propertiesField = "properties";
39787 const isTypeAnnotation = n.type === "ObjectTypeAnnotation";
39790 if (isTypeAnnotation) {
39791 fields.push("indexers", "callProperties", "internalSlots");
39794 fields.push(propertiesField);
39795 const firstProperty = fields.map(field => n[field][0]).sort((a, b) => options.locStart(a) - options.locStart(b))[0];
39796 const parent = path.getParentNode(0);
39797 const isFlowInterfaceLikeBody = isTypeAnnotation && parent && (parent.type === "InterfaceDeclaration" || parent.type === "DeclareInterface" || parent.type === "DeclareClass") && path.getName() === "body";
39798 const shouldBreak = n.type === "TSInterfaceBody" || isFlowInterfaceLikeBody || n.type === "ObjectPattern" && parent.type !== "FunctionDeclaration" && parent.type !== "FunctionExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "ObjectMethod" && parent.type !== "ClassMethod" && parent.type !== "ClassPrivateMethod" && parent.type !== "AssignmentPattern" && parent.type !== "CatchClause" && n.properties.some(property => property.value && (property.value.type === "ObjectPattern" || property.value.type === "ArrayPattern")) || n.type !== "ObjectPattern" && firstProperty && hasNewlineInRange$3(options.originalText, options.locStart(n), options.locStart(firstProperty));
39799 const separator = isFlowInterfaceLikeBody ? ";" : n.type === "TSInterfaceBody" || n.type === "TSTypeLiteral" ? ifBreak$1(semi, ";") : ",";
39800 const leftBrace = n.exact ? "{|" : "{";
39801 const rightBrace = n.exact ? "|}" : "}"; // Unfortunately, things are grouped together in the ast can be
39802 // interleaved in the source code. So we need to reorder them before
39805 const propsAndLoc = [];
39806 fields.forEach(field => {
39807 path.each(childPath => {
39808 const node = childPath.getValue();
39811 printed: print(childPath),
39812 loc: options.locStart(node)
39816 let separatorParts = [];
39817 const props = propsAndLoc.sort((a, b) => a.loc - b.loc).map(prop => {
39818 const result = concat$6(separatorParts.concat(group$2(prop.printed)));
39819 separatorParts = [separator, line$4];
39821 if ((prop.node.type === "TSPropertySignature" || prop.node.type === "TSMethodSignature" || prop.node.type === "TSConstructSignatureDeclaration") && hasNodeIgnoreComment$2(prop.node)) {
39822 separatorParts.shift();
39825 if (isNextLineEmpty$2(options.originalText, prop.node, options.locEnd)) {
39826 separatorParts.push(hardline$4);
39835 if (hasDanglingComments$1(n)) {
39836 const hasLineComments = !n.comments.every(comments$1.isBlockComment);
39837 const printedDanglingComments = comments.printDanglingComments(path, options,
39840 printed = concat$6([printedDanglingComments, hasLineComments || hasNewline$4(options.originalText, options.locEnd(n.comments[n.comments.length - 1])) ? hardline$4 : line$4, "..."]);
39845 props.push(concat$6(separatorParts.concat(printed)));
39848 const lastElem = getLast$2(n[propertiesField]);
39849 const canHaveTrailingSeparator = !(n.inexact || lastElem && (lastElem.type === "RestElement" || hasNodeIgnoreComment$2(lastElem)));
39852 if (props.length === 0) {
39853 if (!hasDanglingComments$1(n)) {
39854 return concat$6([leftBrace, rightBrace, printTypeAnnotation(path, options, print)]);
39857 content = group$2(concat$6([leftBrace, comments.printDanglingComments(path, options), softline$2, rightBrace, printOptionalToken(path), printTypeAnnotation(path, options, print)]));
39859 content = concat$6([leftBrace, indent$3(concat$6([options.bracketSpacing ? line$4 : softline$2, concat$6(props)])), ifBreak$1(canHaveTrailingSeparator && (separator !== "," || shouldPrintComma(options)) ? separator : ""), concat$6([options.bracketSpacing ? line$4 : softline$2, rightBrace]), printOptionalToken(path), printTypeAnnotation(path, options, print)]);
39860 } // If we inline the object as first argument of the parent, we don't want
39861 // to create another group so that the object breaks before the return
39865 if (path.match(node => node.type === "ObjectPattern" && !node.decorators, (node, name, number) => shouldHugArguments(node) && (name === "params" || name === "parameters") && number === 0) || path.match(shouldHugType, (node, name) => name === "typeAnnotation", (node, name) => name === "typeAnnotation", (node, name, number) => shouldHugArguments(node) && (name === "params" || name === "parameters") && number === 0)) {
39869 return group$2(content, {
39875 case "ObjectProperty": // Non-standard AST node type.
39878 if (n.method || n.kind === "get" || n.kind === "set") {
39879 return printMethod(path, options, print);
39883 parts.push(path.call(print, "value"));
39885 parts.push(printAssignment(n.key, printPropertyKey(path, options, print), ":", n.value, path.call(print, "value"), options));
39888 return concat$6(parts);
39891 case "ClassMethod":
39892 case "ClassPrivateMethod":
39893 case "MethodDefinition":
39894 case "TSAbstractMethodDefinition":
39895 case "TSDeclareMethod":
39896 if (n.decorators && n.decorators.length !== 0) {
39897 parts.push(printDecorators(path, options, print));
39900 if (n.accessibility) {
39901 parts.push(n.accessibility + " ");
39905 parts.push("static ");
39908 if (n.type === "TSAbstractMethodDefinition" || n.abstract) {
39909 parts.push("abstract ");
39912 parts.push(printMethod(path, options, print));
39913 return concat$6(parts);
39915 case "ObjectMethod":
39916 return printMethod(path, options, print);
39919 return concat$6(["@", path.call(print, "expression"), path.call(print, "callee")]);
39921 case "ArrayExpression":
39922 case "ArrayPattern":
39923 if (n.elements.length === 0) {
39924 if (!hasDanglingComments$1(n)) {
39927 parts.push(group$2(concat$6(["[", comments.printDanglingComments(path, options), softline$2, "]"])));
39930 const lastElem = getLast$2(n.elements);
39931 const canHaveTrailingComma = !(lastElem && lastElem.type === "RestElement"); // JavaScript allows you to have empty elements in an array which
39932 // changes its length based on the number of commas. The algorithm
39933 // is that if the last argument is null, we need to force insert
39934 // a comma to ensure JavaScript recognizes it.
39935 // [,].length === 1
39936 // [1,].length === 1
39937 // [1,,].length === 2
39939 // Note that getLast returns null if the array is empty, but
39940 // we already check for an empty array just above so we are safe
39942 const needsForcedTrailingComma = canHaveTrailingComma && lastElem === null;
39943 const shouldBreak = n.elements.length > 1 && n.elements.every((element, i, elements) => {
39944 const elementType = element && element.type;
39946 if (elementType !== "ArrayExpression" && elementType !== "ObjectExpression") {
39950 const nextElement = elements[i + 1];
39952 if (nextElement && elementType !== nextElement.type) {
39956 const itemsKey = elementType === "ArrayExpression" ? "elements" : "properties";
39957 return element[itemsKey] && element[itemsKey].length > 1;
39959 parts.push(group$2(concat$6(["[", indent$3(concat$6([softline$2, printArrayItems(path, options, "elements", print)])), needsForcedTrailingComma ? "," : "", ifBreak$1(canHaveTrailingComma && !needsForcedTrailingComma && shouldPrintComma(options) ? "," : ""), comments.printDanglingComments(path, options,
39961 true), softline$2, "]"]), {
39966 parts.push(printOptionalToken(path), printTypeAnnotation(path, options, print));
39967 return concat$6(parts);
39969 case "SequenceExpression":
39971 const parent = path.getParentNode(0);
39973 if (parent.type === "ExpressionStatement" || parent.type === "ForStatement") {
39974 // For ExpressionStatements and for-loop heads, which are among
39975 // the few places a SequenceExpression appears unparenthesized, we want
39976 // to indent expressions after the first.
39979 if (p.getName() === 0) {
39980 parts.push(print(p));
39982 parts.push(",", indent$3(concat$6([line$4, print(p)])));
39985 return group$2(concat$6(parts));
39988 return group$2(concat$6([join$4(concat$6([",", line$4]), path.map(print, "expressions"))]));
39991 case "ThisExpression":
39997 case "NullLiteral":
39998 // Babel 6 Literal split
40001 case "RegExpLiteral":
40002 // Babel 6 Literal split
40003 return printRegex(n);
40005 case "NumericLiteral":
40006 // Babel 6 Literal split
40007 return printNumber$1(n.extra.raw);
40009 case "BigIntLiteral":
40010 // babel: n.extra.raw, typescript: n.raw, flow: n.bigint
40011 return (n.bigint || (n.extra ? n.extra.raw : n.raw)).toLowerCase();
40013 case "BooleanLiteral": // Babel 6 Literal split
40015 case "StringLiteral": // Babel 6 Literal split
40020 return printRegex(n.regex);
40023 if (typeof n.value === "number") {
40024 return printNumber$1(n.raw);
40027 if (typeof n.value !== "string") {
40028 return "" + n.value;
40029 } // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2
40030 // See corresponding workaround in needs-parens.js
40033 const grandParent = path.getParentNode(1);
40034 const isTypeScriptDirective = options.parser === "typescript" && typeof n.value === "string" && grandParent && (grandParent.type === "Program" || grandParent.type === "BlockStatement");
40035 return nodeStr(n, options, isTypeScriptDirective);
40039 return path.call(print, "value");
40042 case "DirectiveLiteral":
40043 return nodeStr(n, options);
40045 case "UnaryExpression":
40046 parts.push(n.operator);
40048 if (/[a-z]$/.test(n.operator)) {
40052 if (n.argument.comments && n.argument.comments.length > 0) {
40053 parts.push(group$2(concat$6(["(", indent$3(concat$6([softline$2, path.call(print, "argument")])), softline$2, ")"])));
40055 parts.push(path.call(print, "argument"));
40058 return concat$6(parts);
40060 case "UpdateExpression":
40061 parts.push(path.call(print, "argument"), n.operator);
40067 return concat$6(parts);
40069 case "ConditionalExpression":
40070 return printTernaryOperator(path, options, print, {
40071 beforeParts: () => [path.call(print, "test")],
40072 afterParts: breakClosingParen => [breakClosingParen ? softline$2 : ""],
40073 shouldCheckJsx: true,
40074 conditionalNodeType: "ConditionalExpression",
40075 consequentNodePropertyName: "consequent",
40076 alternateNodePropertyName: "alternate",
40077 testNodePropertyNames: ["test"]
40080 case "VariableDeclaration":
40082 const printed = path.map(childPath => {
40083 return print(childPath);
40084 }, "declarations"); // We generally want to terminate all variable declarations with a
40085 // semicolon, except when they in the () part of for loops.
40087 const parentNode = path.getParentNode();
40088 const isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement";
40089 const hasValue = n.declarations.some(decl => decl.init);
40092 if (printed.length === 1 && !n.declarations[0].comments) {
40093 firstVariable = printed[0];
40094 } else if (printed.length > 0) {
40095 // Indent first var to comply with eslint one-var rule
40096 firstVariable = indent$3(printed[0]);
40099 parts = [n.declare ? "declare " : "", n.kind, firstVariable ? concat$6([" ", firstVariable]) : "", indent$3(concat$6(printed.slice(1).map(p => concat$6([",", hasValue && !isParentForLoop ? hardline$4 : line$4, p]))))];
40101 if (!(isParentForLoop && parentNode.body !== n)) {
40105 return group$2(concat$6(parts));
40108 case "TSTypeAliasDeclaration":
40111 parts.push("declare ");
40114 const printed = printAssignmentRight(n.id, n.typeAnnotation, n.typeAnnotation && path.call(print, "typeAnnotation"), options);
40115 parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi);
40116 return group$2(concat$6(parts));
40119 case "VariableDeclarator":
40120 return printAssignment(n.id, path.call(print, "id"), " =", n.init, n.init && path.call(print, "init"), options);
40122 case "WithStatement":
40123 return group$2(concat$6(["with (", path.call(print, "object"), ")", adjustClause(n.body, path.call(print, "body"))]));
40125 case "IfStatement":
40127 const con = adjustClause(n.consequent, path.call(print, "consequent"));
40128 const opening = group$2(concat$6(["if (", group$2(concat$6([indent$3(concat$6([softline$2, path.call(print, "test")])), softline$2])), ")", con]));
40129 parts.push(opening);
40132 const commentOnOwnLine = hasTrailingComment$1(n.consequent) && n.consequent.comments.some(comment => comment.trailing && !comments$1.isBlockComment(comment)) || needsHardlineAfterDanglingComment$1(n);
40133 const elseOnSameLine = n.consequent.type === "BlockStatement" && !commentOnOwnLine;
40134 parts.push(elseOnSameLine ? " " : hardline$4);
40136 if (hasDanglingComments$1(n)) {
40137 parts.push(comments.printDanglingComments(path, options, true), commentOnOwnLine ? hardline$4 : " ");
40140 parts.push("else", group$2(adjustClause(n.alternate, path.call(print, "alternate"), n.alternate.type === "IfStatement")));
40143 return concat$6(parts);
40146 case "ForStatement":
40148 const body = adjustClause(n.body, path.call(print, "body")); // We want to keep dangling comments above the loop to stay consistent.
40149 // Any comment positioned between the for statement and the parentheses
40150 // is going to be printed before the statement.
40152 const dangling = comments.printDanglingComments(path, options,
40155 const printedComments = dangling ? concat$6([dangling, softline$2]) : "";
40157 if (!n.init && !n.test && !n.update) {
40158 return concat$6([printedComments, group$2(concat$6(["for (;;)", body]))]);
40161 return concat$6([printedComments, group$2(concat$6(["for (", group$2(concat$6([indent$3(concat$6([softline$2, path.call(print, "init"), ";", line$4, path.call(print, "test"), ";", line$4, path.call(print, "update")])), softline$2])), ")", body]))]);
40164 case "WhileStatement":
40165 return group$2(concat$6(["while (", group$2(concat$6([indent$3(concat$6([softline$2, path.call(print, "test")])), softline$2])), ")", adjustClause(n.body, path.call(print, "body"))]));
40167 case "ForInStatement":
40168 // Note: esprima can't actually parse "for each (".
40169 return group$2(concat$6([n.each ? "for each (" : "for (", path.call(print, "left"), " in ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))]));
40171 case "ForOfStatement":
40172 return group$2(concat$6(["for", n.await ? " await" : "", " (", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))]));
40174 case "DoWhileStatement":
40176 const clause = adjustClause(n.body, path.call(print, "body"));
40177 const doBody = group$2(concat$6(["do", clause]));
40180 if (n.body.type === "BlockStatement") {
40183 parts.push(hardline$4);
40186 parts.push("while (");
40187 parts.push(group$2(concat$6([indent$3(concat$6([softline$2, path.call(print, "test")])), softline$2])), ")", semi);
40188 return concat$6(parts);
40191 case "DoExpression":
40192 return concat$6(["do ", path.call(print, "body")]);
40194 case "BreakStatement":
40195 parts.push("break");
40198 parts.push(" ", path.call(print, "label"));
40202 return concat$6(parts);
40204 case "ContinueStatement":
40205 parts.push("continue");
40208 parts.push(" ", path.call(print, "label"));
40212 return concat$6(parts);
40214 case "LabeledStatement":
40215 if (n.body.type === "EmptyStatement") {
40216 return concat$6([path.call(print, "label"), ":;"]);
40219 return concat$6([path.call(print, "label"), ": ", path.call(print, "body")]);
40221 case "TryStatement":
40222 return concat$6(["try ", path.call(print, "block"), n.handler ? concat$6([" ", path.call(print, "handler")]) : "", n.finalizer ? concat$6([" finally ", path.call(print, "finalizer")]) : ""]);
40224 case "CatchClause":
40226 const hasComments = n.param.comments && n.param.comments.some(comment => !comments$1.isBlockComment(comment) || comment.leading && hasNewline$4(options.originalText, options.locEnd(comment)) || comment.trailing && hasNewline$4(options.originalText, options.locStart(comment), {
40229 const param = path.call(print, "param");
40230 return concat$6(["catch ", hasComments ? concat$6(["(", indent$3(concat$6([softline$2, param])), softline$2, ") "]) : concat$6(["(", param, ") "]), path.call(print, "body")]);
40233 return concat$6(["catch ", path.call(print, "body")]);
40235 case "ThrowStatement":
40236 return concat$6(["throw", printReturnAndThrowArgument(path, options, print)]);
40237 // Note: ignoring n.lexical because it has no printing consequences.
40239 case "SwitchStatement":
40240 return concat$6([group$2(concat$6(["switch (", indent$3(concat$6([softline$2, path.call(print, "discriminant")])), softline$2, ")"])), " {", n.cases.length > 0 ? indent$3(concat$6([hardline$4, join$4(hardline$4, path.map(casePath => {
40241 const caseNode = casePath.getValue();
40242 return concat$6([casePath.call(print), n.cases.indexOf(caseNode) !== n.cases.length - 1 && isNextLineEmpty$2(options.originalText, caseNode, options.locEnd) ? hardline$4 : ""]);
40243 }, "cases"))])) : "", hardline$4, "}"]);
40248 parts.push("case ", path.call(print, "test"), ":");
40250 parts.push("default:");
40253 const consequent = n.consequent.filter(node => node.type !== "EmptyStatement");
40255 if (consequent.length > 0) {
40256 const cons = path.call(consequentPath => {
40257 return printStatementSequence(consequentPath, options, print);
40259 parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? concat$6([" ", cons]) : indent$3(concat$6([hardline$4, cons])));
40262 return concat$6(parts);
40264 // JSX extensions below.
40266 case "DebuggerStatement":
40267 return concat$6(["debugger", semi]);
40269 case "JSXAttribute":
40270 parts.push(path.call(print, "name"));
40275 if (isStringLiteral$1(n.value)) {
40276 const raw = rawText$1(n.value); // Unescape all quotes so we get an accurate preferred quote
40278 let final = raw.replace(/'/g, "'").replace(/"/g, '"');
40279 const quote = getPreferredQuote$1(final, options.jsxSingleQuote ? "'" : '"');
40280 const escape = quote === "'" ? "'" : """;
40281 final = final.slice(1, -1).replace(new RegExp(quote, "g"), escape);
40282 res = concat$6([quote, final, quote]);
40284 res = path.call(print, "value");
40287 parts.push("=", res);
40290 return concat$6(parts);
40292 case "JSXIdentifier":
40293 return "" + n.name;
40295 case "JSXNamespacedName":
40296 return join$4(":", [path.call(print, "namespace"), path.call(print, "name")]);
40298 case "JSXMemberExpression":
40299 return join$4(".", [path.call(print, "object"), path.call(print, "property")]);
40301 case "TSQualifiedName":
40302 return join$4(".", [path.call(print, "left"), path.call(print, "right")]);
40304 case "JSXSpreadAttribute":
40305 case "JSXSpreadChild":
40307 return concat$6(["{", path.call(p => {
40308 const printed = concat$6(["...", print(p)]);
40309 const n = p.getValue();
40311 if (!n.comments || !n.comments.length) {
40315 return concat$6([indent$3(concat$6([softline$2, comments.printComments(p, () => printed, options)])), softline$2]);
40316 }, n.type === "JSXSpreadAttribute" ? "argument" : "expression"), "}"]);
40319 case "JSXExpressionContainer":
40321 const parent = path.getParentNode(0);
40322 const hasComments = n.expression.comments && n.expression.comments.length > 0;
40323 const shouldInline = n.expression.type === "JSXEmptyExpression" || !hasComments && (n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression" || n.expression.type === "ArrowFunctionExpression" || n.expression.type === "CallExpression" || n.expression.type === "OptionalCallExpression" || n.expression.type === "FunctionExpression" || n.expression.type === "TemplateLiteral" || n.expression.type === "TaggedTemplateExpression" || n.expression.type === "DoExpression" || isJSXNode$1(parent) && (n.expression.type === "ConditionalExpression" || isBinaryish$1(n.expression)));
40325 if (shouldInline) {
40326 return group$2(concat$6(["{", path.call(print, "expression"), lineSuffixBoundary$1, "}"]));
40329 return group$2(concat$6(["{", indent$3(concat$6([softline$2, path.call(print, "expression")])), softline$2, lineSuffixBoundary$1, "}"]));
40332 case "JSXFragment":
40335 const elem = comments.printComments(path, () => printJSXElement(path, options, print), options);
40336 return maybeWrapJSXElementInParens(path, elem, options);
40339 case "JSXOpeningElement":
40341 const n = path.getValue();
40342 const nameHasComments = n.name && n.name.comments && n.name.comments.length > 0 || n.typeParameters && n.typeParameters.comments && n.typeParameters.comments.length > 0; // Don't break self-closing elements with no attributes and no comments
40344 if (n.selfClosing && !n.attributes.length && !nameHasComments) {
40345 return concat$6(["<", path.call(print, "name"), path.call(print, "typeParameters"), " />"]);
40346 } // don't break up opening elements with a single long text attribute
40349 if (n.attributes && n.attributes.length === 1 && n.attributes[0].value && isStringLiteral$1(n.attributes[0].value) && !n.attributes[0].value.value.includes("\n") && // We should break for the following cases:
40358 !nameHasComments && (!n.attributes[0].comments || !n.attributes[0].comments.length)) {
40359 return group$2(concat$6(["<", path.call(print, "name"), path.call(print, "typeParameters"), " ", concat$6(path.map(print, "attributes")), n.selfClosing ? " />" : ">"]));
40362 const lastAttrHasTrailingComments = n.attributes.length && hasTrailingComment$1(getLast$2(n.attributes));
40363 const bracketSameLine = // Simple tags (no attributes and no comment in tag name) should be
40364 // kept unbroken regardless of `jsxBracketSameLine`
40365 !n.attributes.length && !nameHasComments || options.jsxBracketSameLine && ( // We should print the bracket in a new line for the following cases:
40372 !nameHasComments || n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a
40373 // string literal with newlines
40375 const shouldBreak = n.attributes && n.attributes.some(attr => attr.value && isStringLiteral$1(attr.value) && attr.value.value.includes("\n"));
40376 return group$2(concat$6(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$6([indent$3(concat$6(path.map(attr => concat$6([line$4, print(attr)]), "attributes"))), n.selfClosing ? line$4 : bracketSameLine ? ">" : softline$2]), n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), {
40381 case "JSXClosingElement":
40382 return concat$6(["</", path.call(print, "name"), ">"]);
40384 case "JSXOpeningFragment":
40385 case "JSXClosingFragment":
40387 const hasComment = n.comments && n.comments.length;
40388 const hasOwnLineComment = hasComment && !n.comments.every(comments$1.isBlockComment);
40389 const isOpeningFragment = n.type === "JSXOpeningFragment";
40390 return concat$6([isOpeningFragment ? "<" : "</", indent$3(concat$6([hasOwnLineComment ? hardline$4 : hasComment && !isOpeningFragment ? " " : "", comments.printDanglingComments(path, options, true)])), hasOwnLineComment ? hardline$4 : "", ">"]);
40394 /* istanbul ignore next */
40395 throw new Error("JSXTest should be handled by JSXElement");
40397 case "JSXEmptyExpression":
40399 const requiresHardline = n.comments && !n.comments.every(comments$1.isBlockComment);
40400 return concat$6([comments.printDanglingComments(path, options,
40402 !requiresHardline), requiresHardline ? hardline$4 : ""]);
40406 if (!n.comments && n.body.length === 0) {
40410 return concat$6(["{", n.body.length > 0 ? indent$3(concat$6([hardline$4, path.call(bodyPath => {
40411 return printStatementSequence(bodyPath, options, print);
40412 }, "body")])) : comments.printDanglingComments(path, options), hardline$4, "}"]);
40414 case "ClassProperty":
40415 case "TSAbstractClassProperty":
40416 case "ClassPrivateProperty":
40418 if (n.decorators && n.decorators.length !== 0) {
40419 parts.push(printDecorators(path, options, print));
40422 if (n.accessibility) {
40423 parts.push(n.accessibility + " ");
40427 parts.push("declare ");
40431 parts.push("static ");
40434 if (n.type === "TSAbstractClassProperty" || n.abstract) {
40435 parts.push("abstract ");
40439 parts.push("readonly ");
40442 const variance = getFlowVariance$1(n);
40445 parts.push(variance);
40448 parts.push(printPropertyKey(path, options, print), printOptionalToken(path), printTypeAnnotation(path, options, print));
40451 parts.push(" =", printAssignmentRight(n.key, n.value, path.call(print, "value"), options));
40455 return group$2(concat$6(parts));
40458 case "ClassDeclaration":
40459 case "ClassExpression":
40461 parts.push("declare ");
40464 parts.push(concat$6(printClass(path, options, print)));
40465 return concat$6(parts);
40467 case "TSInterfaceHeritage":
40468 case "TSExpressionWithTypeArguments":
40470 parts.push(path.call(print, "expression"));
40472 if (n.typeParameters) {
40473 parts.push(path.call(print, "typeParameters"));
40476 return concat$6(parts);
40478 case "TemplateElement":
40479 return join$4(literalline$2, n.value.raw.split(/\r?\n/g));
40481 case "TemplateLiteral":
40483 let expressions = path.map(print, "expressions");
40484 const parentNode = path.getParentNode();
40486 if (isJestEachTemplateLiteral$1(n, parentNode)) {
40487 const printed = printJestEachTemplateLiteral(n, expressions, options);
40494 const isSimple = isSimpleTemplateLiteral$1(n);
40497 expressions = expressions.map(doc => printDocToString$2(doc, Object.assign({}, options, {
40498 printWidth: Infinity
40502 parts.push(lineSuffixBoundary$1, "`");
40503 path.each(childPath => {
40504 const i = childPath.getName();
40505 parts.push(print(childPath));
40507 if (i < expressions.length) {
40508 // For a template literal of the following form:
40515 // the expression is on its own line (there is a \n in the previous
40516 // quasi literal), therefore we want to indent the JavaScript
40517 // expression inside at the beginning of ${ instead of the beginning
40522 const quasi = childPath.getValue();
40523 const indentSize = getIndentSize$2(quasi.value.raw, tabWidth);
40524 let printed = expressions[i];
40527 // Breaks at the template element boundaries (${ and }) are preferred to breaking
40528 // in the middle of a MemberExpression
40529 if (n.expressions[i].comments && n.expressions[i].comments.length || n.expressions[i].type === "MemberExpression" || n.expressions[i].type === "OptionalMemberExpression" || n.expressions[i].type === "ConditionalExpression" || n.expressions[i].type === "SequenceExpression" || n.expressions[i].type === "TSAsExpression" || isBinaryish$1(n.expressions[i])) {
40530 printed = concat$6([indent$3(concat$6([softline$2, printed])), softline$2]);
40534 const aligned = indentSize === 0 && quasi.value.raw.endsWith("\n") ? align$1(-Infinity, printed) : addAlignmentToDoc$2(printed, indentSize, tabWidth);
40535 parts.push(group$2(concat$6(["${", aligned, lineSuffixBoundary$1, "}"])));
40539 return concat$6(parts);
40541 // These types are unprintable because they serve as abstract
40542 // supertypes for other (printable) types.
40544 case "TaggedTemplateExpression":
40545 return concat$6([path.call(print, "tag"), path.call(print, "typeParameters"), path.call(print, "quasi")]);
40549 case "SourceLocation":
40555 case "Declaration":
40557 case "NamedSpecifier":
40559 case "MemberTypeAnnotation": // Flow
40562 /* istanbul ignore next */
40563 throw new Error("unprintable type: " + JSON.stringify(n.type));
40564 // Type Annotations for Facebook Flow, typically stripped out or
40565 // transformed away before printing.
40567 case "TypeAnnotation":
40568 case "TSTypeAnnotation":
40569 if (n.typeAnnotation) {
40570 return path.call(print, "typeAnnotation");
40572 /* istanbul ignore next */
40577 case "TSTupleType":
40578 case "TupleTypeAnnotation":
40580 const typesField = n.type === "TSTupleType" ? "elementTypes" : "types";
40581 const hasRest = n[typesField].length > 0 && getLast$2(n[typesField]).type === "TSRestType";
40582 return group$2(concat$6(["[", indent$3(concat$6([softline$2, printArrayItems(path, options, typesField, print)])), ifBreak$1(shouldPrintComma(options, "all") && !hasRest ? "," : ""), comments.printDanglingComments(path, options,
40584 true), softline$2, "]"]));
40587 case "ExistsTypeAnnotation":
40590 case "EmptyTypeAnnotation":
40593 case "AnyTypeAnnotation":
40596 case "MixedTypeAnnotation":
40599 case "ArrayTypeAnnotation":
40600 return concat$6([path.call(print, "elementType"), "[]"]);
40602 case "BooleanTypeAnnotation":
40605 case "BooleanLiteralTypeAnnotation":
40606 return "" + n.value;
40608 case "DeclareClass":
40609 return printFlowDeclaration(path, printClass(path, options, print));
40611 case "TSDeclareFunction":
40612 // For TypeScript the TSDeclareFunction node shares the AST
40613 // structure with FunctionDeclaration
40614 return concat$6([n.declare ? "declare " : "", printFunctionDeclaration(path, print, options), semi]);
40616 case "DeclareFunction":
40617 return printFlowDeclaration(path, ["function ", path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), semi]);
40619 case "DeclareModule":
40620 return printFlowDeclaration(path, ["module ", path.call(print, "id"), " ", path.call(print, "body")]);
40622 case "DeclareModuleExports":
40623 return printFlowDeclaration(path, ["module.exports", ": ", path.call(print, "typeAnnotation"), semi]);
40625 case "DeclareVariable":
40626 return printFlowDeclaration(path, ["var ", path.call(print, "id"), semi]);
40628 case "DeclareExportAllDeclaration":
40629 return concat$6(["declare export * from ", path.call(print, "source")]);
40631 case "DeclareExportDeclaration":
40632 return concat$6(["declare ", printExportDeclaration(path, options, print)]);
40634 case "DeclareOpaqueType":
40637 parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters"));
40640 parts.push(": ", path.call(print, "supertype"));
40644 parts.push(" = ", path.call(print, "impltype"));
40649 if (n.type === "DeclareOpaqueType") {
40650 return printFlowDeclaration(path, parts);
40653 return concat$6(parts);
40656 case "EnumDeclaration":
40657 return concat$6(["enum ", path.call(print, "id"), " ", path.call(print, "body")]);
40659 case "EnumBooleanBody":
40660 case "EnumNumberBody":
40661 case "EnumStringBody":
40662 case "EnumSymbolBody":
40664 if (n.type === "EnumSymbolBody" || n.explicitType) {
40668 case "EnumBooleanBody":
40672 case "EnumNumberBody":
40676 case "EnumStringBody":
40680 case "EnumSymbolBody":
40685 parts.push("of ", type, " ");
40688 if (n.members.length === 0) {
40689 parts.push(group$2(concat$6(["{", comments.printDanglingComments(path, options), softline$2, "}"])));
40691 parts.push(group$2(concat$6(["{", indent$3(concat$6([hardline$4, printArrayItems(path, options, "members", print), shouldPrintComma(options) ? "," : ""])), comments.printDanglingComments(path, options,
40693 true), hardline$4, "}"])));
40696 return concat$6(parts);
40699 case "EnumBooleanMember":
40700 case "EnumNumberMember":
40701 case "EnumStringMember":
40702 return concat$6([path.call(print, "id"), " = ", typeof n.init === "object" ? path.call(print, "init") : String(n.init)]);
40704 case "EnumDefaultedMember":
40705 return path.call(print, "id");
40707 case "FunctionTypeAnnotation":
40708 case "TSFunctionType":
40710 // FunctionTypeAnnotation is ambiguous:
40711 // declare function foo(a: B): void; OR
40712 // var A: (a: B) => void;
40713 const parent = path.getParentNode(0);
40714 const parentParent = path.getParentNode(1);
40715 const parentParentParent = path.getParentNode(2);
40716 let isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !((parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeInternalSlot") && !getFlowVariance$1(parent) && !parent.optional && options.locStart(parent) === options.locStart(n) || parent.type === "ObjectTypeCallProperty" || parentParentParent && parentParentParent.type === "DeclareFunction");
40717 let needsColon = isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation"); // Sadly we can't put it inside of FastPath::needsColon because we are
40718 // printing ":" as part of the expression and it would put parenthesis
40721 const needsParens = needsColon && isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation") && parentParent.type === "ArrowFunctionExpression";
40723 if (isObjectTypePropertyAFunction$1(parent, options)) {
40724 isArrowFunctionTypeAnnotation = true;
40732 parts.push(printFunctionParams(path, print, options,
40735 /* printTypeParams */
40736 true)); // The returnType is not wrapped in a TypeAnnotation, so the colon
40737 // needs to be added separately.
40739 if (n.returnType || n.predicate || n.typeAnnotation) {
40740 parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType"), path.call(print, "predicate"), path.call(print, "typeAnnotation"));
40747 return group$2(concat$6(parts));
40751 return concat$6(["...", path.call(print, "typeAnnotation")]);
40753 case "TSOptionalType":
40754 return concat$6([path.call(print, "typeAnnotation"), "?"]);
40756 case "FunctionTypeParam":
40757 return concat$6([path.call(print, "name"), printOptionalToken(path), n.name ? ": " : "", path.call(print, "typeAnnotation")]);
40759 case "GenericTypeAnnotation":
40760 return concat$6([path.call(print, "id"), path.call(print, "typeParameters")]);
40762 case "DeclareInterface":
40763 case "InterfaceDeclaration":
40764 case "InterfaceTypeAnnotation":
40766 if (n.type === "DeclareInterface" || n.declare) {
40767 parts.push("declare ");
40770 parts.push("interface");
40772 if (n.type === "DeclareInterface" || n.type === "InterfaceDeclaration") {
40773 parts.push(" ", path.call(print, "id"), path.call(print, "typeParameters"));
40776 if (n.extends.length > 0) {
40777 parts.push(group$2(indent$3(concat$6([line$4, "extends ", (n.extends.length === 1 ? identity$2 : indent$3)(join$4(concat$6([",", line$4]), path.map(print, "extends")))]))));
40780 parts.push(" ", path.call(print, "body"));
40781 return group$2(concat$6(parts));
40784 case "ClassImplements":
40785 case "InterfaceExtends":
40786 return concat$6([path.call(print, "id"), path.call(print, "typeParameters")]);
40788 case "TSClassImplements":
40789 return concat$6([path.call(print, "expression"), path.call(print, "typeParameters")]);
40791 case "TSIntersectionType":
40792 case "IntersectionTypeAnnotation":
40794 const types = path.map(print, "types");
40796 let wasIndented = false;
40798 for (let i = 0; i < types.length; ++i) {
40800 result.push(types[i]);
40801 } else if (isObjectType$1(n.types[i - 1]) && isObjectType$1(n.types[i])) {
40802 // If both are objects, don't indent
40803 result.push(concat$6([" & ", wasIndented ? indent$3(types[i]) : types[i]]));
40804 } else if (!isObjectType$1(n.types[i - 1]) && !isObjectType$1(n.types[i])) {
40805 // If no object is involved, go to the next line if it breaks
40806 result.push(indent$3(concat$6([" &", line$4, types[i]])));
40808 // If you go from object to non-object or vis-versa, then inline it
40810 wasIndented = true;
40813 result.push(" & ", i > 1 ? indent$3(types[i]) : types[i]);
40817 return group$2(concat$6(result));
40820 case "TSUnionType":
40821 case "UnionTypeAnnotation":
40823 // single-line variation
40825 // multi-line variation
40829 const parent = path.getParentNode(); // If there's a leading comment, the parent is doing the indentation
40831 const shouldIndent = parent.type !== "TypeParameterInstantiation" && parent.type !== "TSTypeParameterInstantiation" && parent.type !== "GenericTypeAnnotation" && parent.type !== "TSTypeReference" && parent.type !== "TSTypeAssertion" && parent.type !== "TupleTypeAnnotation" && parent.type !== "TSTupleType" && !(parent.type === "FunctionTypeParam" && !parent.name) && !((parent.type === "TypeAlias" || parent.type === "VariableDeclarator" || parent.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment$1(options.originalText, n, options)); // {
40834 // should be inlined and not be printed in the multi-line variant
40836 const shouldHug = shouldHugType(n); // We want to align the children but without its comment, so it looks like
40841 const printed = path.map(typePath => {
40842 let printedType = typePath.call(print);
40845 printedType = align$1(2, printedType);
40848 return comments.printComments(typePath, () => printedType, options);
40852 return join$4(" | ", printed);
40855 const shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment$1(options.originalText, n, options);
40856 const code = concat$6([ifBreak$1(concat$6([shouldAddStartLine ? line$4 : "", "| "])), join$4(concat$6([line$4, "| "]), printed)]);
40858 if (needsParens_1(path, options)) {
40859 return group$2(concat$6([indent$3(code), softline$2]));
40862 if (parent.type === "TupleTypeAnnotation" && parent.types.length > 1 || parent.type === "TSTupleType" && parent.elementTypes.length > 1) {
40863 return group$2(concat$6([indent$3(concat$6([ifBreak$1(concat$6(["(", softline$2])), code])), softline$2, ifBreak$1(")")]));
40866 return group$2(shouldIndent ? indent$3(code) : code);
40869 case "NullableTypeAnnotation":
40870 return concat$6(["?", path.call(print, "typeAnnotation")]);
40872 case "TSNullKeyword":
40873 case "NullLiteralTypeAnnotation":
40876 case "ThisTypeAnnotation":
40879 case "NumberTypeAnnotation":
40882 case "SymbolTypeAnnotation":
40885 case "ObjectTypeCallProperty":
40887 parts.push("static ");
40890 parts.push(path.call(print, "value"));
40891 return concat$6(parts);
40893 case "ObjectTypeIndexer":
40895 const variance = getFlowVariance$1(n);
40896 return concat$6([variance || "", "[", path.call(print, "id"), n.id ? ": " : "", path.call(print, "key"), "]: ", path.call(print, "value")]);
40899 case "ObjectTypeProperty":
40901 const variance = getFlowVariance$1(n);
40905 modifier = "proto ";
40906 } else if (n.static) {
40907 modifier = "static ";
40910 return concat$6([modifier, isGetterOrSetter$1(n) ? n.kind + " " : "", variance || "", printPropertyKey(path, options, print), printOptionalToken(path), isFunctionNotation$1(n, options) ? "" : ": ", path.call(print, "value")]);
40913 case "QualifiedTypeIdentifier":
40914 return concat$6([path.call(print, "qualification"), ".", path.call(print, "id")]);
40916 case "StringLiteralTypeAnnotation":
40917 return nodeStr(n, options);
40919 case "NumberLiteralTypeAnnotation":
40920 assert$1.strictEqual(typeof n.value, "number");
40922 if (n.extra != null) {
40923 return printNumber$1(n.extra.raw);
40926 return printNumber$1(n.raw);
40928 case "StringTypeAnnotation":
40931 case "DeclareTypeAlias":
40934 if (n.type === "DeclareTypeAlias" || n.declare) {
40935 parts.push("declare ");
40938 const printed = printAssignmentRight(n.id, n.right, path.call(print, "right"), options);
40939 parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi);
40940 return group$2(concat$6(parts));
40943 case "TypeCastExpression":
40945 return concat$6(["(", path.call(print, "expression"), printTypeAnnotation(path, options, print), ")"]);
40948 case "TypeParameterDeclaration":
40949 case "TypeParameterInstantiation":
40951 const value = path.getValue();
40952 const commentStart = value.range ? options.originalText.slice(0, value.range[0]).lastIndexOf("/*") : -1; // As noted in the TypeCastExpression comments above, we're able to use a normal whitespace regex here
40953 // because we know for sure that this is a type definition.
40955 const commentSyntax = commentStart >= 0 && options.originalText.slice(commentStart).match(/^\/\*\s*::/);
40957 if (commentSyntax) {
40958 return concat$6(["/*:: ", printTypeParameters(path, options, print, "params"), " */"]);
40961 return printTypeParameters(path, options, print, "params");
40964 case "TSTypeParameterDeclaration":
40965 case "TSTypeParameterInstantiation":
40966 return printTypeParameters(path, options, print, "params");
40968 case "TSTypeParameter":
40969 case "TypeParameter":
40971 const parent = path.getParentNode();
40973 if (parent.type === "TSMappedType") {
40974 parts.push("[", path.call(print, "name"));
40976 if (n.constraint) {
40977 parts.push(" in ", path.call(print, "constraint"));
40981 return concat$6(parts);
40984 const variance = getFlowVariance$1(n);
40987 parts.push(variance);
40990 parts.push(path.call(print, "name"));
40994 parts.push(path.call(print, "bound"));
40997 if (n.constraint) {
40998 parts.push(" extends ", path.call(print, "constraint"));
41002 parts.push(" = ", path.call(print, "default"));
41003 } // Keep comma if the file extension is .tsx and
41004 // has one type parameter that isn't extend with any types.
41005 // Because, otherwise formatted result will be invalid as tsx.
41008 const grandParent = path.getNode(2);
41010 if (parent.params && parent.params.length === 1 && isTSXFile$1(options) && !n.constraint && grandParent.type === "ArrowFunctionExpression") {
41014 return concat$6(parts);
41017 case "TypeofTypeAnnotation":
41018 return concat$6(["typeof ", path.call(print, "argument")]);
41020 case "VoidTypeAnnotation":
41023 case "InferredPredicate":
41025 // Unhandled types below. If encountered, nodes of these types should
41026 // be either left alone or desugared into AST types that are fully
41027 // supported by the pretty-printer.
41029 case "DeclaredPredicate":
41030 return concat$6(["%checks(", path.call(print, "value"), ")"]);
41032 case "TSAbstractKeyword":
41035 case "TSAnyKeyword":
41038 case "TSAsyncKeyword":
41041 case "TSBooleanKeyword":
41044 case "TSBigIntKeyword":
41047 case "TSConstKeyword":
41050 case "TSDeclareKeyword":
41053 case "TSExportKeyword":
41056 case "TSNeverKeyword":
41059 case "TSNumberKeyword":
41062 case "TSObjectKeyword":
41065 case "TSProtectedKeyword":
41066 return "protected";
41068 case "TSPrivateKeyword":
41071 case "TSPublicKeyword":
41074 case "TSReadonlyKeyword":
41077 case "TSSymbolKeyword":
41080 case "TSStaticKeyword":
41083 case "TSStringKeyword":
41086 case "TSUndefinedKeyword":
41087 return "undefined";
41089 case "TSUnknownKeyword":
41092 case "TSVoidKeyword":
41095 case "TSAsExpression":
41096 return concat$6([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]);
41098 case "TSArrayType":
41099 return concat$6([path.call(print, "elementType"), "[]"]);
41101 case "TSPropertySignature":
41104 parts.push("export ");
41107 if (n.accessibility) {
41108 parts.push(n.accessibility + " ");
41112 parts.push("static ");
41116 parts.push("readonly ");
41119 parts.push(printPropertyKey(path, options, print), printOptionalToken(path));
41121 if (n.typeAnnotation) {
41123 parts.push(path.call(print, "typeAnnotation"));
41124 } // This isn't valid semantically, but it's in the AST so we can print it.
41127 if (n.initializer) {
41128 parts.push(" = ", path.call(print, "initializer"));
41131 return concat$6(parts);
41134 case "TSParameterProperty":
41135 if (n.accessibility) {
41136 parts.push(n.accessibility + " ");
41140 parts.push("export ");
41144 parts.push("static ");
41148 parts.push("readonly ");
41151 parts.push(path.call(print, "parameter"));
41152 return concat$6(parts);
41154 case "TSTypeReference":
41155 return concat$6([path.call(print, "typeName"), printTypeParameters(path, options, print, "typeParameters")]);
41157 case "TSTypeQuery":
41158 return concat$6(["typeof ", path.call(print, "exprName")]);
41160 case "TSIndexSignature":
41162 const parent = path.getParentNode(); // The typescript parser accepts multiple parameters here. If you're
41163 // using them, it makes sense to have a trailing comma. But if you
41164 // aren't, this is more like a computed property name than an array.
41165 // So we leave off the trailing comma when there's just one parameter.
41167 const trailingComma = n.parameters.length > 1 ? ifBreak$1(shouldPrintComma(options) ? "," : "") : "";
41168 const parametersGroup = group$2(concat$6([indent$3(concat$6([softline$2, join$4(concat$6([", ", softline$2]), path.map(print, "parameters"))])), trailingComma, softline$2]));
41169 return concat$6([n.export ? "export " : "", n.accessibility ? concat$6([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", "[", n.parameters ? parametersGroup : "", n.typeAnnotation ? "]: " : "]", n.typeAnnotation ? path.call(print, "typeAnnotation") : "", parent.type === "ClassBody" ? semi : ""]);
41172 case "TSTypePredicate":
41173 return concat$6([n.asserts ? "asserts " : "", path.call(print, "parameterName"), n.typeAnnotation ? concat$6([" is ", path.call(print, "typeAnnotation")]) : ""]);
41175 case "TSNonNullExpression":
41176 return concat$6([path.call(print, "expression"), "!"]);
41181 case "TSImportType":
41182 return concat$6([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, n.parameter ? "parameter" : "argument"), ")", !n.qualifier ? "" : concat$6([".", path.call(print, "qualifier")]), printTypeParameters(path, options, print, "typeParameters")]);
41184 case "TSLiteralType":
41185 return path.call(print, "literal");
41187 case "TSIndexedAccessType":
41188 return concat$6([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]);
41190 case "TSConstructSignatureDeclaration":
41191 case "TSCallSignatureDeclaration":
41192 case "TSConstructorType":
41194 if (n.type !== "TSCallSignatureDeclaration") {
41195 parts.push("new ");
41198 parts.push(group$2(printFunctionParams(path, print, options,
41201 /* printTypeParams */
41204 if (n.returnType || n.typeAnnotation) {
41205 const isType = n.type === "TSConstructorType";
41206 parts.push(isType ? " => " : ": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
41209 return concat$6(parts);
41212 case "TSTypeOperator":
41213 return concat$6([n.operator, " ", path.call(print, "typeAnnotation")]);
41215 case "TSMappedType":
41217 const shouldBreak = hasNewlineInRange$3(options.originalText, options.locStart(n), options.locEnd(n));
41218 return group$2(concat$6(["{", indent$3(concat$6([options.bracketSpacing ? line$4 : softline$2, n.readonly ? concat$6([getTypeScriptMappedTypeModifier$1(n.readonly, "readonly"), " "]) : "", printTypeScriptModifiers(path, options, print), path.call(print, "typeParameter"), n.optional ? getTypeScriptMappedTypeModifier$1(n.optional, "?") : "", n.typeAnnotation ? ": " : "", path.call(print, "typeAnnotation"), ifBreak$1(semi, "")])), comments.printDanglingComments(path, options,
41220 true), options.bracketSpacing ? line$4 : softline$2, "}"]), {
41225 case "TSMethodSignature":
41226 parts.push(n.accessibility ? concat$6([n.accessibility, " "]) : "", n.export ? "export " : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.computed ? "[" : "", path.call(print, "key"), n.computed ? "]" : "", printOptionalToken(path), printFunctionParams(path, print, options,
41229 /* printTypeParams */
41232 if (n.returnType || n.typeAnnotation) {
41233 parts.push(": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
41236 return group$2(concat$6(parts));
41238 case "TSNamespaceExportDeclaration":
41239 parts.push("export as namespace ", path.call(print, "id"));
41241 if (options.semi) {
41245 return group$2(concat$6(parts));
41247 case "TSEnumDeclaration":
41249 parts.push("declare ");
41253 parts.push(printTypeScriptModifiers(path, options, print));
41257 parts.push("const ");
41260 parts.push("enum ", path.call(print, "id"), " ");
41262 if (n.members.length === 0) {
41263 parts.push(group$2(concat$6(["{", comments.printDanglingComments(path, options), softline$2, "}"])));
41265 parts.push(group$2(concat$6(["{", indent$3(concat$6([hardline$4, printArrayItems(path, options, "members", print), shouldPrintComma(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options,
41267 true), hardline$4, "}"])));
41270 return concat$6(parts);
41272 case "TSEnumMember":
41273 parts.push(path.call(print, "id"));
41275 if (n.initializer) {
41276 parts.push(" = ", path.call(print, "initializer"));
41279 return concat$6(parts);
41281 case "TSImportEqualsDeclaration":
41283 parts.push("export ");
41286 parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference"));
41288 if (options.semi) {
41292 return group$2(concat$6(parts));
41294 case "TSExternalModuleReference":
41295 return concat$6(["require(", path.call(print, "expression"), ")"]);
41297 case "TSModuleDeclaration":
41299 const parent = path.getParentNode();
41300 const isExternalModule = isLiteral$1(n.id);
41301 const parentIsDeclaration = parent.type === "TSModuleDeclaration";
41302 const bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration";
41304 if (parentIsDeclaration) {
41308 parts.push("declare ");
41311 parts.push(printTypeScriptModifiers(path, options, print));
41312 const textBetweenNodeAndItsId = options.originalText.slice(options.locStart(n), options.locStart(n.id)); // Global declaration looks like this:
41313 // (declare)? global { ... }
41315 const isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId);
41317 if (!isGlobalDeclaration) {
41318 parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace ");
41322 parts.push(path.call(print, "id"));
41324 if (bodyIsDeclaration) {
41325 parts.push(path.call(print, "body"));
41326 } else if (n.body) {
41327 parts.push(" ", group$2(path.call(print, "body")));
41332 return concat$6(parts);
41335 case "PrivateName":
41336 return concat$6(["#", path.call(print, "id")]);
41337 // TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields.
41339 case "TSPrivateIdentifier":
41340 return n.escapedText;
41342 case "TSConditionalType":
41343 return printTernaryOperator(path, options, print, {
41344 beforeParts: () => [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")],
41345 afterParts: () => [],
41346 shouldCheckJsx: false,
41347 conditionalNodeType: "TSConditionalType",
41348 consequentNodePropertyName: "trueType",
41349 alternateNodePropertyName: "falseType",
41350 testNodePropertyNames: ["checkType", "extendsType"]
41353 case "TSInferType":
41354 return concat$6(["infer", " ", path.call(print, "typeParameter")]);
41356 case "InterpreterDirective":
41357 parts.push("#!", n.value, hardline$4);
41359 if (isNextLineEmpty$2(options.originalText, n, options.locEnd)) {
41360 parts.push(hardline$4);
41363 return concat$6(parts);
41366 return concat$6([].concat(path.call(print, "node"), !n.node.comments || n.node.comments.length === 0 ? [] : concat$6([" //", n.node.comments[0].value.trimEnd()])));
41368 case "NGChainedExpression":
41369 return group$2(join$4(concat$6([";", line$4]), path.map(childPath => hasNgSideEffect$1(childPath) ? print(childPath) : concat$6(["(", print(childPath), ")"]), "expressions")));
41371 case "NGEmptyExpression":
41374 case "NGQuotedExpression":
41375 return concat$6([n.prefix, ": ", n.value.trim()]);
41377 case "NGMicrosyntax":
41378 return concat$6(path.map((childPath, index) => concat$6([index === 0 ? "" : isNgForOf$1(childPath.getValue(), index, n) ? " " : concat$6([";", line$4]), print(childPath)]), "body"));
41380 case "NGMicrosyntaxKey":
41381 return /^[a-z_$][a-z0-9_$]*(-[a-z_$][a-z0-9_$])*$/i.test(n.name) ? n.name : JSON.stringify(n.name);
41383 case "NGMicrosyntaxExpression":
41384 return concat$6([path.call(print, "expression"), n.alias === null ? "" : concat$6([" as ", path.call(print, "alias")])]);
41386 case "NGMicrosyntaxKeyedExpression":
41388 const index = path.getName();
41389 const parentNode = path.getParentNode();
41390 const shouldNotPrintColon = isNgForOf$1(n, index, parentNode) || (index === 1 && (n.key.name === "then" || n.key.name === "else") || index === 2 && n.key.name === "else" && parentNode.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && parentNode.body[index - 1].key.name === "then") && parentNode.body[0].type === "NGMicrosyntaxExpression";
41391 return concat$6([path.call(print, "key"), shouldNotPrintColon ? " " : ": ", path.call(print, "expression")]);
41394 case "NGMicrosyntaxLet":
41395 return concat$6(["let ", path.call(print, "key"), n.value === null ? "" : concat$6([" = ", path.call(print, "value")])]);
41397 case "NGMicrosyntaxAs":
41398 return concat$6([path.call(print, "key"), " as ", path.call(print, "alias")]);
41400 case "ArgumentPlaceholder":
41402 // These are not valid TypeScript. Printing them just for the sake of error recovery.
41404 case "TSJSDocAllType":
41407 case "TSJSDocUnknownType":
41410 case "TSJSDocNullableType":
41411 return concat$6(["?", path.call(print, "typeAnnotation")]);
41413 case "TSJSDocNonNullableType":
41414 return concat$6(["!", path.call(print, "typeAnnotation")]);
41416 case "TSJSDocFunctionType":
41417 return concat$6(["function(", // The parameters could be here, but typescript-estree doesn't convert them anyway (throws an error).
41418 "): ", path.call(print, "typeAnnotation")]);
41421 /* istanbul ignore next */
41422 throw new Error("unknown type: " + JSON.stringify(n.type));
41426 function printStatementSequence(path, options, print) {
41427 const printed = [];
41428 const bodyNode = path.getNode();
41429 const isClass = bodyNode.type === "ClassBody";
41430 path.map((stmtPath, i) => {
41431 const stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy
41432 // "statements," it's safer simply to skip them.
41434 /* istanbul ignore if */
41438 } // Skip printing EmptyStatement nodes to avoid leaving stray
41439 // semicolons lying around.
41442 if (stmt.type === "EmptyStatement") {
41446 const stmtPrinted = print(stmtPath);
41447 const text = options.originalText;
41448 const parts = []; // in no-semi mode, prepend statement with semicolon if it might break ASI
41449 // don't prepend the only JSX element in a program with semicolon
41451 if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown$1(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options)) {
41452 if (stmt.comments && stmt.comments.some(comment => comment.leading)) {
41453 parts.push(print(stmtPath, {
41457 parts.push(";", stmtPrinted);
41460 parts.push(stmtPrinted);
41463 if (!options.semi && isClass) {
41464 if (classPropMayCauseASIProblems$1(stmtPath)) {
41466 } else if (stmt.type === "ClassProperty") {
41467 const nextChild = bodyNode.body[i + 1];
41469 if (classChildNeedsASIProtection$1(nextChild)) {
41475 if (isNextLineEmpty$2(text, stmt, options.locEnd) && !isLastStatement$1(stmtPath)) {
41476 parts.push(hardline$4);
41479 printed.push(concat$6(parts));
41481 return join$4(hardline$4, printed);
41484 function printPropertyKey(path, options, print) {
41485 const node = path.getNode();
41487 if (node.computed) {
41488 return concat$6(["[", path.call(print, "key"), "]"]);
41491 const parent = path.getParentNode();
41496 if (node.type === "ClassPrivateProperty" && // flow has `Identifier` key, and babel has `PrivateName` key
41497 key.type === "Identifier") {
41498 return concat$6(["#", path.call(print, "key")]);
41501 if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) {
41502 const objectHasStringProp = (parent.properties || parent.body || parent.members).some(prop => !prop.computed && prop.key && isStringLiteral$1(prop.key) && !isStringPropSafeToCoerceToIdentifier$1(prop, options));
41503 needsQuoteProps.set(parent, objectHasStringProp);
41506 if (key.type === "Identifier" && (options.parser === "json" || options.quoteProps === "consistent" && needsQuoteProps.get(parent))) {
41508 const prop = printString$1(JSON.stringify(key.name), options);
41509 return path.call(keyPath => comments.printComments(keyPath, () => prop, options), "key");
41512 if (isStringPropSafeToCoerceToIdentifier$1(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) {
41514 return path.call(keyPath => comments.printComments(keyPath, () => key.value, options), "key");
41517 return path.call(print, "key");
41520 function printMethod(path, options, print) {
41521 const node = path.getNode();
41525 const value = node.value || node;
41528 if (!kind || kind === "init" || kind === "method" || kind === "constructor") {
41530 parts.push("async ");
41533 if (value.generator) {
41537 assert$1.ok(kind === "get" || kind === "set");
41538 parts.push(kind, " ");
41541 parts.push(printPropertyKey(path, options, print), node.optional || node.key.optional ? "?" : "", node === value ? printMethodInternal(path, options, print) : path.call(path => printMethodInternal(path, options, print), "value"));
41542 return concat$6(parts);
41545 function printMethodInternal(path, options, print) {
41546 const parts = [printFunctionTypeParameters(path, options, print), group$2(concat$6([printFunctionParams(path, print, options), printReturnType(path, print, options)]))];
41548 if (path.getNode().body) {
41549 parts.push(" ", path.call(print, "body"));
41551 parts.push(options.semi ? ";" : "");
41554 return concat$6(parts);
41557 function couldGroupArg(arg) {
41558 return arg.type === "ObjectExpression" && (arg.properties.length > 0 || arg.comments) || arg.type === "ArrayExpression" && (arg.elements.length > 0 || arg.comments) || arg.type === "TSTypeAssertion" && couldGroupArg(arg.expression) || arg.type === "TSAsExpression" && couldGroupArg(arg.expression) || arg.type === "FunctionExpression" || arg.type === "ArrowFunctionExpression" && ( // we want to avoid breaking inside composite return types but not simple keywords
41559 // https://github.com/prettier/prettier/issues/4070
41560 // export class Thing implements OtherThing {
41561 // do: (type: Type) => Provider<Prop> = memoize(
41562 // (type: ObjectType): Provider<Opts> => {}
41565 // https://github.com/prettier/prettier/issues/6099
41566 // app.get("/", (req, res): void => {
41567 // res.send("Hello World!");
41569 !arg.returnType || !arg.returnType.typeAnnotation || arg.returnType.typeAnnotation.type !== "TSTypeReference") && (arg.body.type === "BlockStatement" || arg.body.type === "ArrowFunctionExpression" || arg.body.type === "ObjectExpression" || arg.body.type === "ArrayExpression" || arg.body.type === "CallExpression" || arg.body.type === "OptionalCallExpression" || arg.body.type === "ConditionalExpression" || isJSXNode$1(arg.body));
41572 function shouldGroupLastArg(args) {
41573 const lastArg = getLast$2(args);
41574 const penultimateArg = getPenultimate$1(args);
41575 return !hasLeadingComment$3(lastArg) && !hasTrailingComment$1(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type,
41576 // disable last element expansion.
41577 !penultimateArg || penultimateArg.type !== lastArg.type);
41580 function shouldGroupFirstArg(args) {
41581 if (args.length !== 2) {
41585 const [firstArg, secondArg] = args;
41586 return (!firstArg.comments || !firstArg.comments.length) && (firstArg.type === "FunctionExpression" || firstArg.type === "ArrowFunctionExpression" && firstArg.body.type === "BlockStatement") && secondArg.type !== "FunctionExpression" && secondArg.type !== "ArrowFunctionExpression" && secondArg.type !== "ConditionalExpression" && !couldGroupArg(secondArg);
41589 function printJestEachTemplateLiteral(node, expressions, options) {
41592 * ${1} | ${1} | ${2}
41593 * ${1} | ${2} | ${3}
41594 * ${2} | ${1} | ${3}
41596 const headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/);
41598 if (headerNames.length > 1 || headerNames.some(headerName => headerName.length !== 0)) {
41600 const stringifiedExpressions = expressions.map(doc => "${" + printDocToString$2(doc, Object.assign({}, options, {
41601 printWidth: Infinity,
41603 })).formatted + "}");
41604 const tableBody = [{
41605 hasLineBreak: false,
41609 for (let i = 1; i < node.quasis.length; i++) {
41610 const row = tableBody[tableBody.length - 1];
41611 const correspondingExpression = stringifiedExpressions[i - 1];
41612 row.cells.push(correspondingExpression);
41614 if (correspondingExpression.includes("\n")) {
41615 row.hasLineBreak = true;
41618 if (node.quasis[i].value.raw.includes("\n")) {
41620 hasLineBreak: false,
41626 const maxColumnCount = Math.max(headerNames.length, ...tableBody.map(row => row.cells.length));
41627 const maxColumnWidths = Array.from({
41628 length: maxColumnCount
41632 }, ...tableBody.filter(row => row.cells.length !== 0)];
41636 } of table.filter(row => !row.hasLineBreak)) {
41637 cells.forEach((cell, index) => {
41638 maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$3(cell));
41642 parts.push(lineSuffixBoundary$1, "`", indent$3(concat$6([hardline$4, join$4(hardline$4, table.map(row => join$4(" | ", row.cells.map((cell, index) => row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$3(cell))))))])), hardline$4, "`");
41643 return concat$6(parts);
41647 function printArgumentsList(path, options, print) {
41648 const node = path.getValue();
41649 const args = node.arguments;
41651 if (args.length === 0) {
41652 return concat$6(["(", comments.printDanglingComments(path, options,
41655 } // useEffect(() => { ... }, [foo, bar, baz])
41658 if (args.length === 2 && args[0].type === "ArrowFunctionExpression" && args[0].params.length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && !args.find(arg => arg.comments)) {
41659 return concat$6(["(", path.call(print, "arguments", 0), ", ", path.call(print, "arguments", 1), ")"]);
41668 function shouldBreakForArrowFunctionInArguments(arg, argPath) {
41669 if (!arg || arg.type !== "ArrowFunctionExpression" || !arg.body || arg.body.type !== "BlockStatement" || !arg.params || arg.params.length < 1) {
41673 let shouldBreak = false;
41674 argPath.each(paramPath => {
41675 const printed = concat$6([print(paramPath)]);
41676 shouldBreak = shouldBreak || willBreak$1(printed);
41678 return shouldBreak;
41681 let anyArgEmptyLine = false;
41682 let shouldBreakForArrowFunction = false;
41683 let hasEmptyLineFollowingFirstArg = false;
41684 const lastArgIndex = args.length - 1;
41685 const printedArguments = path.map((argPath, index) => {
41686 const arg = argPath.getNode();
41687 const parts = [print(argPath)];
41689 if (index === lastArgIndex) ; else if (isNextLineEmpty$2(options.originalText, arg, options.locEnd)) {
41691 hasEmptyLineFollowingFirstArg = true;
41694 anyArgEmptyLine = true;
41695 parts.push(",", hardline$4, hardline$4);
41697 parts.push(",", line$4);
41700 shouldBreakForArrowFunction = shouldBreakForArrowFunctionInArguments(arg, argPath);
41701 return concat$6(parts);
41703 const maybeTrailingComma = // Dynamic imports cannot have trailing commas
41704 !(node.callee && node.callee.type === "Import") && shouldPrintComma(options, "all") ? "," : "";
41706 function allArgsBrokenOut() {
41707 return group$2(concat$6(["(", indent$3(concat$6([line$4, concat$6(printedArguments)])), maybeTrailingComma, line$4, ")"]), {
41712 if (path.getParentNode().type !== "Decorator" && isFunctionCompositionArgs$1(args)) {
41713 return allArgsBrokenOut();
41716 const shouldGroupFirst = shouldGroupFirstArg(args);
41717 const shouldGroupLast = shouldGroupLastArg(args);
41719 if (shouldGroupFirst || shouldGroupLast) {
41720 const shouldBreak = (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$1) : printedArguments.slice(0, -1).some(willBreak$1)) || anyArgEmptyLine || shouldBreakForArrowFunction; // We want to print the last argument with a special flag
41722 let printedExpanded;
41724 path.each(argPath => {
41725 if (shouldGroupFirst && i === 0) {
41726 printedExpanded = [concat$6([argPath.call(p => print(p, {
41727 expandFirstArg: true
41728 })), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$4 : line$4, hasEmptyLineFollowingFirstArg ? hardline$4 : ""])].concat(printedArguments.slice(1));
41731 if (shouldGroupLast && i === args.length - 1) {
41732 printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(p => print(p, {
41733 expandLastArg: true
41739 const somePrintedArgumentsWillBreak = printedArguments.some(willBreak$1);
41740 const simpleConcat = concat$6(["(", concat$6(printedExpanded), ")"]);
41741 return concat$6([somePrintedArgumentsWillBreak ? breakParent$2 : "", conditionalGroup$1([!somePrintedArgumentsWillBreak && !node.typeArguments && !node.typeParameters ? simpleConcat : ifBreak$1(allArgsBrokenOut(), simpleConcat), shouldGroupFirst ? concat$6(["(", group$2(printedExpanded[0], {
41743 }), concat$6(printedExpanded.slice(1)), ")"]) : concat$6(["(", concat$6(printedArguments.slice(0, -1)), group$2(getLast$2(printedExpanded), {
41745 }), ")"]), allArgsBrokenOut()], {
41750 const contents = concat$6(["(", indent$3(concat$6([softline$2, concat$6(printedArguments)])), ifBreak$1(maybeTrailingComma), softline$2, ")"]);
41752 if (isLongCurriedCallExpression$1(path)) {
41753 // By not wrapping the arguments in a group, the printer prioritizes
41754 // breaking up these arguments rather than the args of the parent call.
41758 return group$2(contents, {
41759 shouldBreak: printedArguments.some(willBreak$1) || anyArgEmptyLine
41763 function printTypeAnnotation(path, options, print) {
41764 const node = path.getValue();
41766 if (!node.typeAnnotation) {
41770 const parentNode = path.getParentNode();
41771 const isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite;
41772 const isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node;
41774 if (isFlowAnnotationComment$1(options.originalText, node.typeAnnotation, options)) {
41775 return concat$6([" /*: ", path.call(print, "typeAnnotation"), " */"]);
41778 return concat$6([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path.call(print, "typeAnnotation")]);
41781 function printFunctionTypeParameters(path, options, print) {
41782 const fun = path.getValue();
41784 if (fun.typeArguments) {
41785 return path.call(print, "typeArguments");
41788 if (fun.typeParameters) {
41789 return path.call(print, "typeParameters");
41795 function printFunctionParams(path, print, options, expandArg, printTypeParams) {
41796 const fun = path.getValue();
41797 const parent = path.getParentNode();
41798 const paramsField = fun.parameters ? "parameters" : "params";
41799 const isParametersInTestCall = isTestCall$1(parent);
41800 const shouldHugParameters = shouldHugArguments(fun);
41801 const shouldExpandParameters = expandArg && !(fun[paramsField] && fun[paramsField].some(n => n.comments));
41802 const typeParams = printTypeParams ? printFunctionTypeParameters(path, options, print) : "";
41805 if (fun[paramsField]) {
41806 const lastArgIndex = fun[paramsField].length - 1;
41807 printed = path.map((childPath, index) => {
41809 const param = childPath.getValue();
41810 parts.push(print(childPath));
41812 if (index === lastArgIndex) {
41814 parts.push(",", line$4);
41816 } else if (isParametersInTestCall || shouldHugParameters || shouldExpandParameters) {
41818 } else if (isNextLineEmpty$2(options.originalText, param, options.locEnd)) {
41819 parts.push(",", hardline$4, hardline$4);
41821 parts.push(",", line$4);
41824 return concat$6(parts);
41829 printed.push(concat$6(["...", path.call(print, "rest")]));
41832 if (printed.length === 0) {
41833 return concat$6([typeParams, "(", comments.printDanglingComments(path, options,
41835 true, comment => getNextNonSpaceNonCommentCharacter$1(options.originalText, comment, options.locEnd) === ")"), ")"]);
41838 const lastParam = getLast$2(fun[paramsField]); // If the parent is a call with the first/last argument expansion and this is the
41839 // params of the first/last argument, we don't want the arguments to break and instead
41840 // want the whole expression to be on a new line.
41843 // verylongcall( verylongcall((
41849 if (shouldExpandParameters) {
41850 return group$2(concat$6([removeLines$1(typeParams), "(", concat$6(printed.map(removeLines$1)), ")"]));
41851 } // Single object destructuring should hug
41860 const hasNotParameterDecorator = fun[paramsField].every(param => !param.decorators);
41862 if (shouldHugParameters && hasNotParameterDecorator) {
41863 return concat$6([typeParams, "(", concat$6(printed), ")"]);
41864 } // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
41867 if (isParametersInTestCall) {
41868 return concat$6([typeParams, "(", concat$6(printed), ")"]);
41871 const isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction$1(parent, options) || isTypeAnnotationAFunction$1(parent, options) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === fun) && fun[paramsField].length === 1 && fun[paramsField][0].name === null && fun[paramsField][0].typeAnnotation && fun.typeParameters === null && isSimpleFlowType$1(fun[paramsField][0].typeAnnotation) && !fun.rest;
41873 if (isFlowShorthandWithOneArg) {
41874 if (options.arrowParens === "always") {
41875 return concat$6(["(", concat$6(printed), ")"]);
41878 return concat$6(printed);
41881 const canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest;
41882 return concat$6([typeParams, "(", indent$3(concat$6([softline$2, concat$6(printed)])), ifBreak$1(canHaveTrailingComma && shouldPrintComma(options, "all") ? "," : ""), softline$2, ")"]);
41885 function shouldPrintParamsWithoutParens(path, options) {
41886 if (options.arrowParens === "always") {
41890 if (options.arrowParens === "avoid") {
41891 const node = path.getValue();
41892 return canPrintParamsWithoutParens(node);
41893 } // Fallback default; should be unreachable
41899 function canPrintParamsWithoutParens(node) {
41900 return node.params.length === 1 && !node.rest && !node.typeParameters && !hasDanglingComments$1(node) && node.params[0].type === "Identifier" && !node.params[0].typeAnnotation && !node.params[0].comments && !node.params[0].optional && !node.predicate && !node.returnType;
41903 function printFunctionDeclaration(path, print, options) {
41904 const n = path.getValue();
41908 parts.push("async ");
41912 parts.push("function* ");
41914 parts.push("function ");
41918 parts.push(path.call(print, "id"));
41921 parts.push(printFunctionTypeParameters(path, options, print), group$2(concat$6([printFunctionParams(path, print, options), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body"));
41922 return concat$6(parts);
41925 function printReturnType(path, print, options) {
41926 const n = path.getValue();
41927 const returnType = path.call(print, "returnType");
41929 if (n.returnType && isFlowAnnotationComment$1(options.originalText, n.returnType, options)) {
41930 return concat$6([" /*: ", returnType, " */"]);
41933 const parts = [returnType]; // prepend colon to TypeScript type annotation
41935 if (n.returnType && n.returnType.typeAnnotation) {
41936 parts.unshift(": ");
41940 // The return type will already add the colon, but otherwise we
41941 // need to do it ourselves
41942 parts.push(n.returnType ? " " : ": ", path.call(print, "predicate"));
41945 return concat$6(parts);
41948 function printExportDeclaration(path, options, print) {
41949 const decl = path.getValue();
41950 const semi = options.semi ? ";" : "";
41951 const parts = ["export "];
41952 const isDefault = decl.default || decl.type === "ExportDefaultDeclaration";
41955 parts.push("default ");
41958 parts.push(comments.printDanglingComments(path, options,
41962 if (needsHardlineAfterDanglingComment$1(decl)) {
41963 parts.push(hardline$4);
41966 if (decl.declaration) {
41967 parts.push(path.call(print, "declaration"));
41969 if (isDefault && decl.declaration.type !== "ClassDeclaration" && decl.declaration.type !== "FunctionDeclaration" && decl.declaration.type !== "TSInterfaceDeclaration" && decl.declaration.type !== "DeclareClass" && decl.declaration.type !== "DeclareFunction" && decl.declaration.type !== "TSDeclareFunction") {
41973 if (decl.specifiers && decl.specifiers.length > 0) {
41974 const specifiers = [];
41975 const defaultSpecifiers = [];
41976 const namespaceSpecifiers = [];
41977 path.each(specifierPath => {
41978 const specifierType = path.getValue().type;
41980 if (specifierType === "ExportSpecifier") {
41981 specifiers.push(print(specifierPath));
41982 } else if (specifierType === "ExportDefaultSpecifier") {
41983 defaultSpecifiers.push(print(specifierPath));
41984 } else if (specifierType === "ExportNamespaceSpecifier") {
41985 namespaceSpecifiers.push(concat$6(["* as ", print(specifierPath)]));
41988 const isNamespaceFollowed = namespaceSpecifiers.length !== 0 && specifiers.length !== 0;
41989 const isDefaultFollowed = defaultSpecifiers.length !== 0 && (namespaceSpecifiers.length !== 0 || specifiers.length !== 0);
41990 const canBreak = specifiers.length > 1 || defaultSpecifiers.length > 0 || decl.specifiers && decl.specifiers.some(node => node.comments);
41993 if (specifiers.length !== 0) {
41995 printed = group$2(concat$6(["{", indent$3(concat$6([options.bracketSpacing ? line$4 : softline$2, join$4(concat$6([",", line$4]), specifiers)])), ifBreak$1(shouldPrintComma(options) ? "," : ""), options.bracketSpacing ? line$4 : softline$2, "}"]));
41997 printed = concat$6(["{", options.bracketSpacing ? " " : "", concat$6(specifiers), options.bracketSpacing ? " " : "", "}"]);
42001 parts.push(decl.exportKind === "type" ? "type " : "", concat$6(defaultSpecifiers), concat$6([isDefaultFollowed ? ", " : ""]), concat$6(namespaceSpecifiers), concat$6([isNamespaceFollowed ? ", " : ""]), printed);
42007 parts.push(" from ", path.call(print, "source"));
42013 return concat$6(parts);
42016 function printFlowDeclaration(path, parts) {
42017 const parentExportDecl = getParentExportDeclaration$1(path);
42019 if (parentExportDecl) {
42020 assert$1.strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
42022 // If the parent node has type DeclareExportDeclaration, then it
42023 // will be responsible for printing the "declare" token. Otherwise
42024 // it needs to be printed with this non-exported declaration node.
42025 parts.unshift("declare ");
42028 return concat$6(parts);
42031 function printTypeScriptModifiers(path, options, print) {
42032 const n = path.getValue();
42034 if (!n.modifiers || !n.modifiers.length) {
42038 return concat$6([join$4(" ", path.map(print, "modifiers")), " "]);
42041 function printTypeParameters(path, options, print, paramsKey) {
42042 const n = path.getValue();
42044 if (!n[paramsKey]) {
42046 } // for TypeParameterDeclaration typeParameters is a single node
42049 if (!Array.isArray(n[paramsKey])) {
42050 return path.call(print, paramsKey);
42053 const grandparent = path.getNode(2);
42054 const greatGrandParent = path.getNode(3);
42055 const greatGreatGrandParent = path.getNode(4);
42056 const isParameterInTestCall = grandparent != null && isTestCall$1(grandparent);
42057 const shouldInline = isParameterInTestCall || n[paramsKey].length === 0 || n[paramsKey].length === 1 && (shouldHugType(n[paramsKey][0]) || n[paramsKey][0].type === "GenericTypeAnnotation" && shouldHugType(n[paramsKey][0].id) || n[paramsKey][0].type === "TSTypeReference" && shouldHugType(n[paramsKey][0].typeName) || n[paramsKey][0].type === "NullableTypeAnnotation" || // See https://github.com/prettier/prettier/pull/6467 for the context.
42058 greatGreatGrandParent && greatGreatGrandParent.type === "VariableDeclarator" && grandparent.type === "TSTypeAnnotation" && greatGrandParent.type !== "ArrowFunctionExpression" && n[paramsKey][0].type !== "TSUnionType" && n[paramsKey][0].type !== "UnionTypeAnnotation" && n[paramsKey][0].type !== "TSIntersectionType" && n[paramsKey][0].type !== "IntersectionTypeAnnotation" && n[paramsKey][0].type !== "TSConditionalType" && n[paramsKey][0].type !== "TSMappedType" && n[paramsKey][0].type !== "TSTypeOperator" && n[paramsKey][0].type !== "TSIndexedAccessType" && n[paramsKey][0].type !== "TSArrayType");
42060 function printDanglingCommentsForInline(n) {
42061 if (!hasDanglingComments$1(n)) {
42065 const hasOnlyBlockComments = n.comments.every(comments$1.isBlockComment);
42066 const printed = comments.printDanglingComments(path, options,
42068 hasOnlyBlockComments);
42070 if (hasOnlyBlockComments) {
42074 return concat$6([printed, hardline$4]);
42077 if (shouldInline) {
42078 return concat$6(["<", join$4(", ", path.map(print, paramsKey)), printDanglingCommentsForInline(n), ">"]);
42081 return group$2(concat$6(["<", indent$3(concat$6([softline$2, join$4(concat$6([",", line$4]), path.map(print, paramsKey))])), ifBreak$1(options.parser !== "typescript" && options.parser !== "babel-ts" && shouldPrintComma(options, "all") ? "," : ""), softline$2, ">"]));
42084 function printClass(path, options, print) {
42085 const n = path.getValue();
42089 parts.push("abstract ");
42092 parts.push("class");
42095 parts.push(" ", path.call(print, "id"));
42098 parts.push(path.call(print, "typeParameters"));
42099 const partsGroup = [];
42101 if (n.superClass) {
42102 const printed = concat$6(["extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters")]); // Keep old behaviour of extends in same line
42103 // If there is only on extends and there are not comments
42105 if ((!n.implements || n.implements.length === 0) && (!n.superClass.comments || n.superClass.comments.length === 0)) {
42106 parts.push(concat$6([" ", path.call(superClass => comments.printComments(superClass, () => printed, options), "superClass")]));
42108 partsGroup.push(group$2(concat$6([line$4, path.call(superClass => comments.printComments(superClass, () => printed, options), "superClass")])));
42110 } else if (n.extends && n.extends.length > 0) {
42111 parts.push(" extends ", join$4(", ", path.map(print, "extends")));
42114 if (n.mixins && n.mixins.length > 0) {
42115 partsGroup.push(line$4, "mixins ", group$2(indent$3(join$4(concat$6([",", line$4]), path.map(print, "mixins")))));
42118 if (n.implements && n.implements.length > 0) {
42119 partsGroup.push(line$4, "implements", group$2(indent$3(concat$6([line$4, join$4(concat$6([",", line$4]), path.map(print, "implements"))]))));
42122 if (partsGroup.length > 0) {
42123 parts.push(group$2(indent$3(concat$6(partsGroup))));
42126 if (n.body && n.body.comments && hasLeadingOwnLineComment$1(options.originalText, n.body, options)) {
42127 parts.push(hardline$4);
42132 parts.push(path.call(print, "body"));
42136 function printOptionalToken(path) {
42137 const node = path.getValue();
42139 if (!node.optional || // It's an optional computed method parsed by typescript-estree.
42140 // "?" is printed in `printMethod`.
42141 node.type === "Identifier" && node === path.getParentNode().key) {
42145 if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) {
42152 function printMemberLookup(path, options, print) {
42153 const property = path.call(print, "property");
42154 const n = path.getValue();
42155 const optional = printOptionalToken(path);
42158 return concat$6([optional, ".", property]);
42161 if (!n.property || isNumericLiteral$1(n.property)) {
42162 return concat$6([optional, "[", property, "]"]);
42165 return group$2(concat$6([optional, "[", indent$3(concat$6([softline$2, property])), softline$2, "]"]));
42168 function printBindExpressionCallee(path, options, print) {
42169 return concat$6(["::", path.call(print, "callee")]);
42170 } // We detect calls on member expressions specially to format a
42171 // common pattern better. The pattern we are looking for is this:
42174 // .map(x => x + 1)
42175 // .filter(x => x > 10)
42176 // .some(x => x % 2)
42178 // The way it is structured in the AST is via a nested sequence of
42179 // MemberExpression and CallExpression. We need to traverse the AST
42180 // and make groups out of it to print it in the desired way.
42183 function printMemberChain(path, options, print) {
42184 // The first phase is to linearize the AST by traversing it down.
42187 // has the following AST structure:
42188 // CallExpression(MemberExpression(CallExpression(Identifier)))
42189 // and we transform it into
42190 // [Identifier, CallExpression, MemberExpression, CallExpression]
42191 const printedNodes = []; // Here we try to retain one typed empty line after each call expression or
42192 // the first group whether it is in parentheses or not
42194 function shouldInsertEmptyLineAfter(node) {
42198 const nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$3(originalText, node, options.locEnd);
42199 const nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty
42200 // line after that parenthesis
42202 if (nextChar === ")") {
42203 return isNextLineEmptyAfterIndex$2(originalText, nextCharIndex + 1, options.locEnd);
42206 return isNextLineEmpty$2(originalText, node, options.locEnd);
42209 function rec(path) {
42210 const node = path.getValue();
42212 if ((node.type === "CallExpression" || node.type === "OptionalCallExpression") && (isMemberish$1(node.callee) || node.callee.type === "CallExpression" || node.callee.type === "OptionalCallExpression")) {
42213 printedNodes.unshift({
42215 printed: concat$6([comments.printComments(path, () => concat$6([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]), options), shouldInsertEmptyLineAfter(node) ? hardline$4 : ""])
42217 path.call(callee => rec(callee), "callee");
42218 } else if (isMemberish$1(node)) {
42219 printedNodes.unshift({
42221 needsParens: needsParens_1(path, options),
42222 printed: comments.printComments(path, () => node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup(path, options, print) : printBindExpressionCallee(path, options, print), options)
42224 path.call(object => rec(object), "object");
42225 } else if (node.type === "TSNonNullExpression") {
42226 printedNodes.unshift({
42228 printed: comments.printComments(path, () => "!", options)
42230 path.call(expression => rec(expression), "expression");
42232 printedNodes.unshift({
42234 printed: path.call(print)
42237 } // Note: the comments of the root node have already been printed, so we
42238 // need to extract this first call without printing them as they would
42239 // if handled inside of the recursive call.
42242 const node = path.getValue();
42243 printedNodes.unshift({
42245 printed: concat$6([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)])
42247 path.call(callee => rec(callee), "callee"); // Once we have a linear list of printed nodes, we want to create groups out
42251 // will be grouped as
42253 // [Identifier, CallExpression],
42254 // [MemberExpression, MemberExpression, CallExpression],
42255 // [MemberExpression, CallExpression],
42256 // [MemberExpression],
42258 // so that we can print it as
42263 // The first group is the first node followed by
42264 // - as many CallExpression as possible
42265 // < fn()()() >.something()
42266 // - as many array accessors as possible
42267 // < fn()[0][1][2] >.something()
42268 // - then, as many MemberExpression as possible but the last one
42269 // < this.items >.something()
42272 let currentGroup = [printedNodes[0]];
42275 for (; i < printedNodes.length; ++i) {
42276 if (printedNodes[i].node.type === "TSNonNullExpression" || printedNodes[i].node.type === "OptionalCallExpression" || printedNodes[i].node.type === "CallExpression" || (printedNodes[i].node.type === "MemberExpression" || printedNodes[i].node.type === "OptionalMemberExpression") && printedNodes[i].node.computed && isNumericLiteral$1(printedNodes[i].node.property)) {
42277 currentGroup.push(printedNodes[i]);
42283 if (printedNodes[0].node.type !== "CallExpression" && printedNodes[0].node.type !== "OptionalCallExpression") {
42284 for (; i + 1 < printedNodes.length; ++i) {
42285 if (isMemberish$1(printedNodes[i].node) && isMemberish$1(printedNodes[i + 1].node)) {
42286 currentGroup.push(printedNodes[i]);
42293 groups.push(currentGroup);
42294 currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by
42295 // a sequence of CallExpression. To compute it, we keep adding things to the
42296 // group until we has seen a CallExpression in the past and reach a
42297 // MemberExpression
42299 let hasSeenCallExpression = false;
42301 for (; i < printedNodes.length; ++i) {
42302 if (hasSeenCallExpression && isMemberish$1(printedNodes[i].node)) {
42303 // [0] should be appended at the end of the group instead of the
42304 // beginning of the next one
42305 if (printedNodes[i].node.computed && isNumericLiteral$1(printedNodes[i].node.property)) {
42306 currentGroup.push(printedNodes[i]);
42310 groups.push(currentGroup);
42312 hasSeenCallExpression = false;
42315 if (printedNodes[i].node.type === "CallExpression" || printedNodes[i].node.type === "OptionalCallExpression") {
42316 hasSeenCallExpression = true;
42319 currentGroup.push(printedNodes[i]);
42321 if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(comment => comment.trailing)) {
42322 groups.push(currentGroup);
42324 hasSeenCallExpression = false;
42328 if (currentGroup.length > 0) {
42329 groups.push(currentGroup);
42330 } // There are cases like Object.keys(), Observable.of(), _.values() where
42331 // they are the subject of all the chained calls and therefore should
42332 // be kept on the same line:
42334 // Object.keys(items)
42338 // In order to detect those cases, we use an heuristic: if the first
42339 // node is an identifier with the name starting with a capital
42340 // letter or just a sequence of _$. The rationale is that they are
42341 // likely to be factories.
42344 function isFactory(name) {
42345 return /^[A-Z]|^[_$]+$/.test(name);
42346 } // In case the Identifier is shorter than tab width, we can keep the
42347 // first call in a single line, if it's an ExpressionStatement.
42349 // d3.scaleLinear()
42350 // .domain([0, 100])
42351 // .range([0, width]);
42355 function isShort(name) {
42356 return name.length <= options.tabWidth;
42359 function shouldNotWrap(groups) {
42360 const parent = path.getParentNode();
42361 const isExpression = parent && parent.type === "ExpressionStatement";
42362 const hasComputed = groups[1].length && groups[1][0].node.computed;
42364 if (groups[0].length === 1) {
42365 const firstNode = groups[0][0].node;
42366 return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpression && isShort(firstNode.name) || hasComputed);
42369 const lastNode = getLast$2(groups[0]).node;
42370 return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed);
42373 const shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups);
42375 function printGroup(printedGroup) {
42376 const printed = printedGroup.map(tuple => tuple.printed); // Checks if the last node (i.e. the parent node) needs parens and print
42379 if (printedGroup.length > 0 && printedGroup[printedGroup.length - 1].needsParens) {
42380 return concat$6(["(", ...printed, ")"]);
42383 return concat$6(printed);
42386 function printIndentedGroup(groups) {
42387 if (groups.length === 0) {
42391 return indent$3(group$2(concat$6([hardline$4, join$4(hardline$4, groups.map(printGroup))])));
42394 const printedGroups = groups.map(printGroup);
42395 const oneLine = concat$6(printedGroups);
42396 const cutoff = shouldMerge ? 3 : 2;
42397 const flatGroups = groups.reduce((res, group) => res.concat(group), []);
42398 const hasComment = flatGroups.slice(1, -1).some(node => hasLeadingComment$3(node.node)) || flatGroups.slice(0, -1).some(node => hasTrailingComment$1(node.node)) || groups[cutoff] && hasLeadingComment$3(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just
42399 // render everything concatenated together.
42401 if (groups.length <= cutoff && !hasComment) {
42402 if (isLongCurriedCallExpression$1(path)) {
42406 return group$2(oneLine);
42407 } // Find out the last node in the first group and check if it has an
42408 // empty line after
42411 const lastNodeBeforeIndent = getLast$2(shouldMerge ? groups.slice(1, 2)[0] : groups[0]).node;
42412 const shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== "CallExpression" && lastNodeBeforeIndent.type !== "OptionalCallExpression" && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
42413 const expanded = concat$6([printGroup(groups[0]), shouldMerge ? concat$6(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$4 : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]);
42414 const callExpressions = printedNodes.map(({
42416 }) => node).filter(isCallOrOptionalCallExpression$1); // We don't want to print in one line if the chain has:
42418 // * Non-trivial arguments.
42419 // * Any group but the last one has a hard line.
42420 // If the last group is a function it's okay to inline if it fits.
42422 if (hasComment || callExpressions.length > 2 && callExpressions.some(expr => !expr.arguments.every(arg => isSimpleCallArgument$1(arg, 0))) || printedGroups.slice(0, -1).some(willBreak$1) ||
42424 * scopes.filter(scope => scope.value !== '').map((scope, i) => {
42425 * // multi line content
42428 ((lastGroupDoc, lastGroupNode) => isCallOrOptionalCallExpression$1(lastGroupNode) && willBreak$1(lastGroupDoc))(getLast$2(printedGroups), getLast$2(getLast$2(groups)).node) && callExpressions.slice(0, -1).some(n => n.arguments.some(isFunctionOrArrowExpression$1))) {
42429 return group$2(expanded);
42432 return concat$6([// We only need to check `oneLine` because if `expanded` is chosen
42433 // that means that the parent group has already been broken
42435 willBreak$1(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$2 : "", conditionalGroup$1([oneLine, expanded])]);
42438 function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
42439 if (isFacebookTranslationTag) {
42443 if (childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement) {
42444 return child.length === 1 ? softline$2 : hardline$4;
42450 function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
42451 if (isFacebookTranslationTag) {
42455 if (child.length === 1) {
42456 return childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement ? hardline$4 : softline$2;
42460 } // JSX Children are strange, mostly for two reasons:
42461 // 1. JSX reads newlines into string values, instead of skipping them like JS
42462 // 2. up to one whitespace between elements within a line is significant,
42463 // but not between lines.
42465 // Leading, trailing, and lone whitespace all need to
42466 // turn themselves into the rather ugly `{' '}` when breaking.
42468 // We print JSX using the `fill` doc primitive.
42469 // This requires that we give it an array of alternating
42470 // content and whitespace elements.
42471 // To ensure this we add dummy `""` content elements as needed.
42474 function printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag) {
42475 const n = path.getValue();
42476 const children = []; // using `map` instead of `each` because it provides `i`
42478 path.map((childPath, i) => {
42479 const child = childPath.getValue();
42481 if (isLiteral$1(child)) {
42482 const text = rawText$1(child); // Contains a non-whitespace character
42484 if (isMeaningfulJSXText$1(child)) {
42485 const words = text.split(matchJsxWhitespaceRegex$1); // Starts with whitespace
42487 if (words[0] === "") {
42491 if (/\n/.test(words[0])) {
42492 const next = n.children[i + 1];
42493 children.push(separatorWithWhitespace(isFacebookTranslationTag, words[1], child, next));
42495 children.push(jsxWhitespace);
42501 let endWhitespace; // Ends with whitespace
42503 if (getLast$2(words) === "") {
42505 endWhitespace = words.pop();
42506 } // This was whitespace only without a new line.
42509 if (words.length === 0) {
42513 words.forEach((word, i) => {
42515 children.push(line$4);
42517 children.push(word);
42521 if (endWhitespace !== undefined) {
42522 if (/\n/.test(endWhitespace)) {
42523 const next = n.children[i + 1];
42524 children.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$2(children), child, next));
42526 children.push(jsxWhitespace);
42529 const next = n.children[i + 1];
42530 children.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$2(children), child, next));
42532 } else if (/\n/.test(text)) {
42533 // Keep (up to one) blank line between tags/expressions/text.
42534 // Note: We don't keep blank lines between text elements.
42535 if (text.match(/\n/g).length > 1) {
42537 children.push(hardline$4);
42541 children.push(jsxWhitespace);
42544 const printedChild = print(childPath);
42545 children.push(printedChild);
42546 const next = n.children[i + 1];
42547 const directlyFollowedByMeaningfulText = next && isMeaningfulJSXText$1(next);
42549 if (directlyFollowedByMeaningfulText) {
42550 const firstWord = rawText$1(next).trim().split(matchJsxWhitespaceRegex$1)[0];
42551 children.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord, child, next));
42553 children.push(hardline$4);
42558 } // JSX expands children from the inside-out, instead of the outside-in.
42559 // This is both to break children before attributes,
42560 // and to ensure that when children break, their parents do as well.
42562 // Any element that is written without any newlines and fits on a single line
42563 // is left that way.
42564 // Not only that, any user-written-line containing multiple JSX siblings
42565 // should also be kept on one line if possible,
42566 // so each user-written-line is wrapped in its own group.
42568 // Elements that contain newlines or don't fit on a single line (recursively)
42569 // are fully-split, using hardline and shouldBreak: true.
42571 // To support that case properly, all leading and trailing spaces
42572 // are stripped from the list of children, and replaced with a single hardline.
42575 function printJSXElement(path, options, print) {
42576 const n = path.getValue();
42578 if (n.type === "JSXElement" && isEmptyJSXElement$1(n)) {
42579 return concat$6([path.call(print, "openingElement"), path.call(print, "closingElement")]);
42582 const openingLines = n.type === "JSXElement" ? path.call(print, "openingElement") : path.call(print, "openingFragment");
42583 const closingLines = n.type === "JSXElement" ? path.call(print, "closingElement") : path.call(print, "closingFragment");
42585 if (n.children.length === 1 && n.children[0].type === "JSXExpressionContainer" && (n.children[0].expression.type === "TemplateLiteral" || n.children[0].expression.type === "TaggedTemplateExpression")) {
42586 return concat$6([openingLines, concat$6(path.map(print, "children")), closingLines]);
42587 } // Convert `{" "}` to text nodes containing a space.
42588 // This makes it easy to turn them into `jsxWhitespace` which
42589 // can then print as either a space or `{" "}` when breaking.
42592 n.children = n.children.map(child => {
42593 if (isJSXWhitespaceExpression$1(child)) {
42603 const containsTag = n.children.filter(isJSXNode$1).length > 0;
42604 const containsMultipleExpressions = n.children.filter(child => child.type === "JSXExpressionContainer").length > 1;
42605 const containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true.
42607 let forcedBreak = willBreak$1(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions;
42608 const isMdxBlock = path.getParentNode().rootMarker === "mdx";
42609 const rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}';
42610 const jsxWhitespace = isMdxBlock ? concat$6([" "]) : ifBreak$1(concat$6([rawJsxWhitespace, softline$2]), " ");
42611 const isFacebookTranslationTag = n.openingElement && n.openingElement.name && n.openingElement.name.name === "fbt";
42612 const children = printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag);
42613 const containsText = n.children.some(child => isMeaningfulJSXText$1(child)); // We can end up we multiple whitespace elements with empty string
42614 // content between them.
42615 // We need to remove empty whitespace and softlines before JSX whitespace
42616 // to get the correct output.
42618 for (let i = children.length - 2; i >= 0; i--) {
42619 const isPairOfEmptyStrings = children[i] === "" && children[i + 1] === "";
42620 const isPairOfHardlines = children[i] === hardline$4 && children[i + 1] === "" && children[i + 2] === hardline$4;
42621 const isLineFollowedByJSXWhitespace = (children[i] === softline$2 || children[i] === hardline$4) && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
42622 const isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$2 || children[i + 2] === hardline$4);
42623 const isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
42624 const isPairOfHardOrSoftLines = children[i] === softline$2 && children[i + 1] === "" && children[i + 2] === hardline$4 || children[i] === hardline$4 && children[i + 1] === "" && children[i + 2] === softline$2;
42626 if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace || isPairOfHardOrSoftLines) {
42627 children.splice(i, 2);
42628 } else if (isJSXWhitespaceFollowedByLine) {
42629 children.splice(i + 1, 2);
42631 } // Trim trailing lines (or empty strings)
42634 while (children.length && (isLineNext$1(getLast$2(children)) || isEmpty$1(getLast$2(children)))) {
42636 } // Trim leading lines (or empty strings)
42639 while (children.length && (isLineNext$1(children[0]) || isEmpty$1(children[0])) && (isLineNext$1(children[1]) || isEmpty$1(children[1]))) {
42642 } // Tweak how we format children if outputting this element over multiple lines.
42643 // Also detect whether we will force this element to output over multiple lines.
42646 const multilineChildren = [];
42647 children.forEach((child, i) => {
42648 // There are a number of situations where we need to ensure we display
42649 // whitespace as `{" "}` when outputting this element over multiple lines.
42650 if (child === jsxWhitespace) {
42651 if (i === 1 && children[i - 1] === "") {
42652 if (children.length === 2) {
42653 // Solitary whitespace
42654 multilineChildren.push(rawJsxWhitespace);
42656 } // Leading whitespace
42659 multilineChildren.push(concat$6([rawJsxWhitespace, hardline$4]));
42661 } else if (i === children.length - 1) {
42662 // Trailing whitespace
42663 multilineChildren.push(rawJsxWhitespace);
42665 } else if (children[i - 1] === "" && children[i - 2] === hardline$4) {
42666 // Whitespace after line break
42667 multilineChildren.push(rawJsxWhitespace);
42672 multilineChildren.push(child);
42674 if (willBreak$1(child)) {
42675 forcedBreak = true;
42677 }); // If there is text we use `fill` to fit as much onto each line as possible.
42678 // When there is no text (just tags and expressions) we use `group`
42679 // to output each on a separate line.
42681 const content = containsText ? fill$3(multilineChildren) : group$2(concat$6(multilineChildren), {
42689 const multiLineElem = group$2(concat$6([openingLines, indent$3(concat$6([hardline$4, content])), hardline$4, closingLines]));
42692 return multiLineElem;
42695 return conditionalGroup$1([group$2(concat$6([openingLines, concat$6(children), closingLines])), multiLineElem]);
42698 function maybeWrapJSXElementInParens(path, elem, options) {
42699 const parent = path.getParentNode();
42705 const NO_WRAP_PARENTS = {
42706 ArrayExpression: true,
42707 JSXAttribute: true,
42709 JSXExpressionContainer: true,
42711 ExpressionStatement: true,
42712 CallExpression: true,
42713 OptionalCallExpression: true,
42714 ConditionalExpression: true,
42715 JsExpressionRoot: true
42718 if (NO_WRAP_PARENTS[parent.type]) {
42722 const shouldBreak = path.match(undefined, node => node.type === "ArrowFunctionExpression", isCallOrOptionalCallExpression$1, node => node.type === "JSXExpressionContainer");
42723 const needsParens = needsParens_1(path, options);
42724 return group$2(concat$6([needsParens ? "" : ifBreak$1("("), indent$3(concat$6([softline$2, elem])), softline$2, needsParens ? "" : ifBreak$1(")")]), {
42729 function shouldInlineLogicalExpression(node) {
42730 if (node.type !== "LogicalExpression") {
42734 if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) {
42738 if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) {
42742 if (isJSXNode$1(node.right)) {
42747 } // For binary expressions to be consistent, we need to group
42748 // subsequent operators with the same precedence level under a single
42749 // group. Otherwise they will be nested such that some of them break
42750 // onto new lines but not all. Operators with the same precedence
42751 // level should either all break or not. Because we group them by
42752 // precedence level and the AST is structured based on precedence
42753 // level, things are naturally broken up correctly, i.e. `&&` is
42754 // broken before `+`.
42757 function printBinaryishExpressions(path, print, options, isNested, isInsideParenthesis) {
42759 const node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same.
42761 if (isBinaryish$1(node)) {
42762 // Put all operators with the same precedence level in the same
42763 // group. The reason we only need to do this with the `left`
42764 // expression is because given an expression like `1 + 2 - 3`, it
42765 // is always parsed like `((1 + 2) - 3)`, meaning the `left` side
42766 // is where the rest of the expression will exist. Binary
42767 // expressions on the right side mean they have a difference
42768 // precedence level and should be treated as a separate group, so
42769 // print them normally. (This doesn't hold for the `**` operator,
42770 // which is unique in that it is right-associative.)
42771 if (shouldFlatten$1(node.operator, node.left.operator)) {
42772 // Flatten them out by recursively calling this function.
42773 parts = parts.concat(path.call(left => printBinaryishExpressions(left, print, options,
42775 true, isInsideParenthesis), "left"));
42777 parts.push(path.call(print, "left"));
42780 const shouldInline = shouldInlineLogicalExpression(node);
42781 const lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment$1(options.originalText, node.right, options);
42782 const operator = node.type === "NGPipeExpression" ? "|" : node.operator;
42783 const rightSuffix = node.type === "NGPipeExpression" && node.arguments.length !== 0 ? group$2(indent$3(concat$6([softline$2, ": ", join$4(concat$6([softline$2, ":", ifBreak$1(" ")]), path.map(print, "arguments").map(arg => align$1(2, group$2(arg))))]))) : "";
42784 const right = shouldInline ? concat$6([operator, " ", path.call(print, "right"), rightSuffix]) : concat$6([lineBeforeOperator ? softline$2 : "", operator, lineBeforeOperator ? " " : line$4, path.call(print, "right"), rightSuffix]); // If there's only a single binary expression, we want to create a group
42785 // in order to avoid having a small right part like -1 be on its own line.
42787 const parent = path.getParentNode();
42788 const shouldGroup = !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type;
42789 parts.push(" ", shouldGroup ? group$2(right) : right); // The root comments are already printed, but we need to manually print
42790 // the other ones since we don't call the normal print on BinaryExpression,
42791 // only for the left and right parts
42793 if (isNested && node.comments) {
42794 parts = comments.printComments(path, () => concat$6(parts), options);
42797 // Our stopping case. Simply print the node normally.
42798 parts.push(path.call(print));
42804 function printAssignmentRight(leftNode, rightNode, printedRight, options) {
42805 if (hasLeadingOwnLineComment$1(options.originalText, rightNode, options)) {
42806 return indent$3(concat$6([line$4, printedRight]));
42809 const canBreak = isBinaryish$1(rightNode) && !shouldInlineLogicalExpression(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish$1(rightNode.test) && !shouldInlineLogicalExpression(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || rightNode.type === "ClassExpression" && rightNode.decorators && rightNode.decorators.length || (leftNode.type === "Identifier" || isStringLiteral$1(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral$1(rightNode) || isMemberExpressionChain$1(rightNode)) && // do not put values on a separate line from the key in json
42810 options.parser !== "json" && options.parser !== "json5" || rightNode.type === "SequenceExpression";
42813 return group$2(indent$3(concat$6([line$4, printedRight])));
42816 return concat$6([" ", printedRight]);
42819 function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) {
42821 return printedLeft;
42824 const printed = printAssignmentRight(leftNode, rightNode, printedRight, options);
42825 return group$2(concat$6([printedLeft, operator, printed]));
42828 function adjustClause(node, clause, forceSpace) {
42829 if (node.type === "EmptyStatement") {
42833 if (node.type === "BlockStatement" || forceSpace) {
42834 return concat$6([" ", clause]);
42837 return indent$3(concat$6([line$4, clause]));
42840 function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) {
42841 const raw = rawText$1(node);
42842 const isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral";
42843 return printString$1(raw, options, isDirectiveLiteral);
42846 function printRegex(node) {
42847 const flags = node.flags.split("").sort().join("");
42848 return `/${node.pattern}/${flags}`;
42851 function exprNeedsASIProtection(path, options) {
42852 const node = path.getValue();
42853 const maybeASIProblem = needsParens_1(path, options) || node.type === "ParenthesizedExpression" || node.type === "TypeCastExpression" || node.type === "ArrowFunctionExpression" && !shouldPrintParamsWithoutParens(path, options) || node.type === "ArrayExpression" || node.type === "ArrayPattern" || node.type === "UnaryExpression" && node.prefix && (node.operator === "+" || node.operator === "-") || node.type === "TemplateLiteral" || node.type === "TemplateElement" || isJSXNode$1(node) || node.type === "BindExpression" && !node.object || node.type === "RegExpLiteral" || node.type === "Literal" && node.pattern || node.type === "Literal" && node.regex;
42855 if (maybeASIProblem) {
42859 if (!hasNakedLeftSide$2(node)) {
42863 return path.call(childPath => exprNeedsASIProtection(childPath, options), ...getLeftSidePathName$2(path, node));
42866 function stmtNeedsASIProtection(path, options) {
42867 const node = path.getNode();
42869 if (node.type !== "ExpressionStatement") {
42873 return path.call(childPath => exprNeedsASIProtection(childPath, options), "expression");
42876 function shouldHugType(node) {
42877 if (isSimpleFlowType$1(node) || isObjectType$1(node)) {
42881 if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") {
42882 const voidCount = node.types.filter(n => n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword").length;
42883 const hasObject = node.types.some(n => n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}>
42884 n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference");
42886 if (node.types.length - 1 === voidCount && hasObject) {
42894 function shouldHugArguments(fun) {
42895 if (!fun || fun.rest) {
42899 const params = fun.params || fun.parameters;
42901 if (!params || params.length !== 1) {
42905 const param = params[0];
42906 return !param.comments && (param.type === "ObjectPattern" || param.type === "ArrayPattern" || param.type === "Identifier" && param.typeAnnotation && (param.typeAnnotation.type === "TypeAnnotation" || param.typeAnnotation.type === "TSTypeAnnotation") && isObjectType$1(param.typeAnnotation.typeAnnotation) || param.type === "FunctionTypeParam" && isObjectType$1(param.typeAnnotation) || param.type === "AssignmentPattern" && (param.left.type === "ObjectPattern" || param.left.type === "ArrayPattern") && (param.right.type === "Identifier" || param.right.type === "ObjectExpression" && param.right.properties.length === 0 || param.right.type === "ArrayExpression" && param.right.elements.length === 0));
42909 function printArrayItems(path, options, printPath, print) {
42910 const printedElements = [];
42911 let separatorParts = [];
42912 path.each(childPath => {
42913 printedElements.push(concat$6(separatorParts));
42914 printedElements.push(group$2(print(childPath)));
42915 separatorParts = [",", line$4];
42917 if (childPath.getValue() && isNextLineEmpty$2(options.originalText, childPath.getValue(), options.locEnd)) {
42918 separatorParts.push(softline$2);
42921 return concat$6(printedElements);
42924 function printReturnAndThrowArgument(path, options, print) {
42925 const node = path.getValue();
42926 const semi = options.semi ? ";" : "";
42929 if (node.argument) {
42930 if (returnArgumentHasLeadingComment$1(options, node.argument)) {
42931 parts.push(concat$6([" (", indent$3(concat$6([hardline$4, path.call(print, "argument")])), hardline$4, ")"]));
42932 } else if (isBinaryish$1(node.argument) || node.argument.type === "SequenceExpression") {
42933 parts.push(group$2(concat$6([ifBreak$1(" (", " "), indent$3(concat$6([softline$2, path.call(print, "argument")])), softline$2, ifBreak$1(")")])));
42935 parts.push(" ", path.call(print, "argument"));
42939 const lastComment = Array.isArray(node.comments) && node.comments[node.comments.length - 1];
42940 const isLastCommentLine = lastComment && (lastComment.type === "CommentLine" || lastComment.type === "Line");
42942 if (isLastCommentLine) {
42946 if (hasDanglingComments$1(node)) {
42947 parts.push(" ", comments.printDanglingComments(path, options,
42952 if (!isLastCommentLine) {
42956 return concat$6(parts);
42959 function willPrintOwnComments(path
42962 const node = path.getValue();
42963 const parent = path.getParentNode();
42964 return (node && (isJSXNode$1(node) || hasFlowShorthandAnnotationComment$2(node) || parent && (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && (hasFlowAnnotationComment$1(node.leadingComments) || hasFlowAnnotationComment$1(node.trailingComments))) || parent && (parent.type === "JSXSpreadAttribute" || parent.type === "JSXSpreadChild" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node)) && (!hasIgnoreComment$2(path) || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType");
42967 function canAttachComment(node) {
42968 return node.type && node.type !== "CommentBlock" && node.type !== "CommentLine" && node.type !== "Line" && node.type !== "Block" && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import";
42971 function printComment$1(commentPath, options) {
42972 const comment = commentPath.getValue();
42974 switch (comment.type) {
42975 case "CommentBlock":
42978 if (isIndentableBlockComment(comment)) {
42979 const printed = printIndentableBlockComment(comment); // We need to prevent an edge case of a previous trailing comment
42980 // printed as a `lineSuffix` which causes the comments to be
42981 // interleaved. See https://github.com/prettier/prettier/issues/4412
42983 if (comment.trailing && !hasNewline$4(options.originalText, options.locStart(comment), {
42986 return concat$6([hardline$4, printed]);
42992 const commentEnd = options.locEnd(comment);
42993 const isInsideFlowComment = options.originalText.slice(commentEnd - 3, commentEnd) === "*-/";
42994 return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/");
42997 case "CommentLine":
42999 // Print shebangs with the proper comment characters
43000 if (options.originalText.slice(options.locStart(comment)).startsWith("#!")) {
43001 return "#!" + comment.value.trimEnd();
43004 return "//" + comment.value.trimEnd();
43007 throw new Error("Not a comment: " + JSON.stringify(comment));
43011 function isIndentableBlockComment(comment) {
43012 // If the comment has multiple lines and every line starts with a star
43013 // we can fix the indentation of each line. The stars in the `/*` and
43014 // `*/` delimiters are not included in the comment value, so add them
43016 const lines = `*${comment.value}*`.split("\n");
43017 return lines.length > 1 && lines.every(line => line.trim()[0] === "*");
43020 function printIndentableBlockComment(comment) {
43021 const lines = comment.value.split("\n");
43022 return concat$6(["/*", join$4(hardline$4, lines.map((line, index) => index === 0 ? line.trimEnd() : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()))), "*/"]);
43025 var printerEstree = {
43026 preprocess: preprocess_1,
43027 print: genericPrint,
43029 insertPragma: insertPragma$1,
43030 massageAstNode: clean_1,
43031 hasPrettierIgnore: hasPrettierIgnore$1,
43032 willPrintOwnComments,
43034 printComment: printComment$1,
43035 isBlockComment: comments$1.isBlockComment,
43037 ownLine: comments$1.handleOwnLineComment,
43038 endOfLine: comments$1.handleEndOfLineComment,
43039 remaining: comments$1.handleRemainingComment
43041 getGapRegex: comments$1.getGapRegex,
43042 getCommentChildNodes: comments$1.getCommentChildNodes
43047 hardline: hardline$5,
43050 } = document.builders;
43052 function genericPrint$1(path, options, print) {
43053 const node = path.getValue();
43055 switch (node.type) {
43057 return concat$7([path.call(print, "node"), hardline$5]);
43059 case "ArrayExpression":
43060 return node.elements.length === 0 ? "[]" : concat$7(["[", indent$4(concat$7([hardline$5, join$5(concat$7([",", hardline$5]), path.map(print, "elements"))])), hardline$5, "]"]);
43062 case "ObjectExpression":
43063 return node.properties.length === 0 ? "{}" : concat$7(["{", indent$4(concat$7([hardline$5, join$5(concat$7([",", hardline$5]), path.map(print, "properties"))])), hardline$5, "}"]);
43065 case "ObjectProperty":
43066 return concat$7([path.call(print, "key"), ": ", path.call(print, "value")]);
43068 case "UnaryExpression":
43069 return concat$7([node.operator === "+" ? "" : node.operator, path.call(print, "argument")]);
43071 case "NullLiteral":
43074 case "BooleanLiteral":
43075 return node.value ? "true" : "false";
43077 case "StringLiteral":
43078 case "NumericLiteral":
43079 return JSON.stringify(node.value);
43082 return JSON.stringify(node.name);
43085 /* istanbul ignore next */
43086 throw new Error("unknown type: " + JSON.stringify(node.type));
43090 function clean$1(node, newNode
43093 delete newNode.start;
43094 delete newNode.end;
43095 delete newNode.extra;
43096 delete newNode.loc;
43097 delete newNode.comments;
43098 delete newNode.errors;
43100 if (node.type === "Identifier") {
43102 type: "StringLiteral",
43107 if (node.type === "UnaryExpression" && node.operator === "+") {
43108 return newNode.argument;
43112 var printerEstreeJson = {
43113 preprocess: preprocess_1,
43114 print: genericPrint$1,
43115 massageAstNode: clean$1
43118 const CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
43120 var commonOptions = {
43123 category: CATEGORY_COMMON,
43126 description: "Print spaces between brackets.",
43127 oppositeDescription: "Do not print spaces between brackets."
43131 category: CATEGORY_COMMON,
43134 description: "Use single quotes instead of double quotes."
43138 category: CATEGORY_COMMON,
43147 description: "How to wrap prose.",
43151 description: "Wrap prose if it exceeds the print width."
43155 description: "Do not wrap prose."
43159 description: "Wrap prose as-is."
43164 const CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
43169 category: CATEGORY_JAVASCRIPT,
43178 description: "Include parentheses around a sole arrow function parameter.",
43181 description: "Always include parens. Example: `(x) => x`"
43184 description: "Omit parens when possible. Example: `x => x`"
43187 bracketSpacing: commonOptions.bracketSpacing,
43188 jsxBracketSameLine: {
43190 category: CATEGORY_JAVASCRIPT,
43193 description: "Put > on the last line instead of at a new line."
43197 category: CATEGORY_JAVASCRIPT,
43200 description: "Print semicolons.",
43201 oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them."
43203 singleQuote: commonOptions.singleQuote,
43206 category: CATEGORY_JAVASCRIPT,
43209 description: "Use single quotes in JSX."
43213 category: CATEGORY_JAVASCRIPT,
43215 default: "as-needed",
43216 description: "Change when properties in objects are quoted.",
43218 value: "as-needed",
43219 description: "Only add quotes around object properties where required."
43221 value: "consistent",
43222 description: "If at least one property in an object requires quotes, quote all properties."
43225 description: "Respect the input use of quotes in object properties."
43230 category: CATEGORY_JAVASCRIPT,
43242 description: "Print trailing commas wherever possible when multi-line.",
43245 description: "Trailing commas where valid in ES5 (objects, arrays, etc.)"
43248 description: "No trailing commas."
43251 description: "Trailing commas wherever possible (including function arguments)."
43256 var createLanguage = function (linguistData, override) {
43260 rest = _objectWithoutPropertiesLoose(linguistData, ["languageId"]);
43262 return Object.assign({
43263 linguistLanguageId: languageId
43264 }, rest, {}, override(linguistData));
43267 var name$2 = "JavaScript";
43268 var type = "programming";
43269 var tmScope = "source.js";
43270 var aceMode = "javascript";
43271 var codemirrorMode = "javascript";
43272 var codemirrorMimeType = "text/javascript";
43273 var color = "#f1e05a";
43304 var interpreters = [
43315 var languageId = 183;
43321 codemirrorMode: codemirrorMode,
43322 codemirrorMimeType: codemirrorMimeType,
43325 extensions: extensions,
43326 filenames: filenames,
43327 interpreters: interpreters,
43328 languageId: languageId
43331 var JavaScript$1 = /*#__PURE__*/Object.freeze({
43337 codemirrorMode: codemirrorMode,
43338 codemirrorMimeType: codemirrorMimeType,
43341 extensions: extensions,
43342 filenames: filenames,
43343 interpreters: interpreters,
43344 languageId: languageId,
43345 'default': JavaScript
43348 var name$3 = "JSX";
43349 var type$1 = "programming";
43350 var group$3 = "JavaScript";
43351 var extensions$1 = [
43354 var tmScope$1 = "source.js.jsx";
43355 var aceMode$1 = "javascript";
43356 var codemirrorMode$1 = "jsx";
43357 var codemirrorMimeType$1 = "text/jsx";
43358 var languageId$1 = 178;
43363 extensions: extensions$1,
43364 tmScope: tmScope$1,
43365 aceMode: aceMode$1,
43366 codemirrorMode: codemirrorMode$1,
43367 codemirrorMimeType: codemirrorMimeType$1,
43368 languageId: languageId$1
43371 var JSX$1 = /*#__PURE__*/Object.freeze({
43376 extensions: extensions$1,
43377 tmScope: tmScope$1,
43378 aceMode: aceMode$1,
43379 codemirrorMode: codemirrorMode$1,
43380 codemirrorMimeType: codemirrorMimeType$1,
43381 languageId: languageId$1,
43385 var name$4 = "TypeScript";
43386 var type$2 = "programming";
43387 var color$1 = "#2b7489";
43391 var interpreters$1 = [
43395 var extensions$2 = [
43398 var tmScope$2 = "source.ts";
43399 var aceMode$2 = "typescript";
43400 var codemirrorMode$2 = "javascript";
43401 var codemirrorMimeType$2 = "application/typescript";
43402 var languageId$2 = 378;
43407 aliases: aliases$1,
43408 interpreters: interpreters$1,
43409 extensions: extensions$2,
43410 tmScope: tmScope$2,
43411 aceMode: aceMode$2,
43412 codemirrorMode: codemirrorMode$2,
43413 codemirrorMimeType: codemirrorMimeType$2,
43414 languageId: languageId$2
43417 var TypeScript$1 = /*#__PURE__*/Object.freeze({
43422 aliases: aliases$1,
43423 interpreters: interpreters$1,
43424 extensions: extensions$2,
43425 tmScope: tmScope$2,
43426 aceMode: aceMode$2,
43427 codemirrorMode: codemirrorMode$2,
43428 codemirrorMimeType: codemirrorMimeType$2,
43429 languageId: languageId$2,
43430 'default': TypeScript
43433 var name$5 = "TSX";
43434 var type$3 = "programming";
43435 var group$4 = "TypeScript";
43436 var extensions$3 = [
43439 var tmScope$3 = "source.tsx";
43440 var aceMode$3 = "javascript";
43441 var codemirrorMode$3 = "jsx";
43442 var codemirrorMimeType$3 = "text/jsx";
43443 var languageId$3 = 94901924;
43448 extensions: extensions$3,
43449 tmScope: tmScope$3,
43450 aceMode: aceMode$3,
43451 codemirrorMode: codemirrorMode$3,
43452 codemirrorMimeType: codemirrorMimeType$3,
43453 languageId: languageId$3
43456 var TSX$1 = /*#__PURE__*/Object.freeze({
43461 extensions: extensions$3,
43462 tmScope: tmScope$3,
43463 aceMode: aceMode$3,
43464 codemirrorMode: codemirrorMode$3,
43465 codemirrorMimeType: codemirrorMimeType$3,
43466 languageId: languageId$3,
43470 var name$6 = "JSON";
43471 var type$4 = "data";
43472 var tmScope$4 = "source.json";
43473 var aceMode$4 = "json";
43474 var codemirrorMode$4 = "javascript";
43475 var codemirrorMimeType$4 = "application/json";
43476 var searchable = false;
43477 var extensions$4 = [
43484 ".JSON-tmLanguage",
43495 var filenames$1 = [
43504 var languageId$4 = 174;
43508 tmScope: tmScope$4,
43509 aceMode: aceMode$4,
43510 codemirrorMode: codemirrorMode$4,
43511 codemirrorMimeType: codemirrorMimeType$4,
43512 searchable: searchable,
43513 extensions: extensions$4,
43514 filenames: filenames$1,
43515 languageId: languageId$4
43518 var _JSON$1 = /*#__PURE__*/Object.freeze({
43522 tmScope: tmScope$4,
43523 aceMode: aceMode$4,
43524 codemirrorMode: codemirrorMode$4,
43525 codemirrorMimeType: codemirrorMimeType$4,
43526 searchable: searchable,
43527 extensions: extensions$4,
43528 filenames: filenames$1,
43529 languageId: languageId$4,
43533 var name$7 = "JSON with Comments";
43534 var type$5 = "data";
43535 var group$5 = "JSON";
43536 var tmScope$5 = "source.js";
43537 var aceMode$5 = "javascript";
43538 var codemirrorMode$5 = "javascript";
43539 var codemirrorMimeType$5 = "text/javascript";
43543 var extensions$5 = [
43546 ".sublime-commands",
43547 ".sublime-completions",
43551 ".sublime-mousemap",
43552 ".sublime-project",
43553 ".sublime-settings",
43555 ".sublime-workspace",
43556 ".sublime_metrics",
43559 var filenames$2 = [
43566 "language-configuration.json",
43569 var languageId$5 = 423;
43570 var JSON_with_Comments = {
43574 tmScope: tmScope$5,
43575 aceMode: aceMode$5,
43576 codemirrorMode: codemirrorMode$5,
43577 codemirrorMimeType: codemirrorMimeType$5,
43578 aliases: aliases$2,
43579 extensions: extensions$5,
43580 filenames: filenames$2,
43581 languageId: languageId$5
43584 var JSON_with_Comments$1 = /*#__PURE__*/Object.freeze({
43589 tmScope: tmScope$5,
43590 aceMode: aceMode$5,
43591 codemirrorMode: codemirrorMode$5,
43592 codemirrorMimeType: codemirrorMimeType$5,
43593 aliases: aliases$2,
43594 extensions: extensions$5,
43595 filenames: filenames$2,
43596 languageId: languageId$5,
43597 'default': JSON_with_Comments
43600 var name$8 = "JSON5";
43601 var type$6 = "data";
43602 var extensions$6 = [
43605 var tmScope$6 = "source.js";
43606 var aceMode$6 = "javascript";
43607 var codemirrorMode$6 = "javascript";
43608 var codemirrorMimeType$6 = "application/json";
43609 var languageId$6 = 175;
43613 extensions: extensions$6,
43614 tmScope: tmScope$6,
43615 aceMode: aceMode$6,
43616 codemirrorMode: codemirrorMode$6,
43617 codemirrorMimeType: codemirrorMimeType$6,
43618 languageId: languageId$6
43621 var JSON5$1 = /*#__PURE__*/Object.freeze({
43625 extensions: extensions$6,
43626 tmScope: tmScope$6,
43627 aceMode: aceMode$6,
43628 codemirrorMode: codemirrorMode$6,
43629 codemirrorMimeType: codemirrorMimeType$6,
43630 languageId: languageId$6,
43634 var require$$0$1 = getCjsExportFromNamespace(JavaScript$1);
43636 var require$$1$1 = getCjsExportFromNamespace(JSX$1);
43638 var require$$2 = getCjsExportFromNamespace(TypeScript$1);
43640 var require$$3 = getCjsExportFromNamespace(TSX$1);
43642 var require$$4$1 = getCjsExportFromNamespace(_JSON$1);
43644 var require$$5 = getCjsExportFromNamespace(JSON_with_Comments$1);
43646 var require$$6 = getCjsExportFromNamespace(JSON5$1);
43648 const languages = [createLanguage(require$$0$1, data => ({
43650 parsers: ["babel", "flow"],
43651 vscodeLanguageIds: ["javascript", "mongo"],
43652 interpreters: data.interpreters.concat(["nodejs"])
43653 })), createLanguage(require$$0$1, () => ({
43656 parsers: ["babel", "flow"],
43657 vscodeLanguageIds: ["javascript"],
43660 extensions: [".js.flow"]
43661 })), createLanguage(require$$1$1, () => ({
43663 parsers: ["babel", "flow"],
43664 vscodeLanguageIds: ["javascriptreact"]
43665 })), createLanguage(require$$2, () => ({
43667 parsers: ["typescript", "babel-ts"],
43668 vscodeLanguageIds: ["typescript"]
43669 })), createLanguage(require$$3, () => ({
43671 parsers: ["typescript", "babel-ts"],
43672 vscodeLanguageIds: ["typescriptreact"]
43673 })), createLanguage(require$$4$1, () => ({
43674 name: "JSON.stringify",
43676 parsers: ["json-stringify"],
43677 vscodeLanguageIds: ["json"],
43679 // .json file defaults to json instead of json-stringify
43680 filenames: ["package.json", "package-lock.json", "composer.json"]
43681 })), createLanguage(require$$4$1, data => ({
43684 vscodeLanguageIds: ["json"],
43685 filenames: data.filenames.concat([".prettierrc"])
43686 })), createLanguage(require$$5, data => ({
43689 vscodeLanguageIds: ["jsonc"],
43690 filenames: data.filenames.concat([".eslintrc"])
43691 })), createLanguage(require$$6, () => ({
43693 parsers: ["json5"],
43694 vscodeLanguageIds: ["json5"]
43697 estree: printerEstree,
43698 "estree-json": printerEstreeJson
43702 options: options$2,
43706 function clean$2(ast, newObj, parent) {
43707 ["raw", // front-matter
43708 "raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(name => {
43709 delete newObj[name];
43712 if (ast.type === "yaml") {
43713 delete newObj.value;
43714 } // --insert-pragma
43717 if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0 && ( // first non-front-matter comment
43718 parent.nodes[0] === ast || (parent.nodes[0].type === "yaml" || parent.nodes[0].type === "toml") && parent.nodes[1] === ast)) {
43724 delete newObj.text; // standalone pragma
43726 if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) {
43731 if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") {
43732 delete newObj.value;
43735 if (ast.type === "css-rule") {
43736 delete newObj.params;
43739 if (ast.type === "selector-combinator") {
43740 newObj.value = newObj.value.replace(/\s+/g, " ");
43743 if (ast.type === "media-feature") {
43744 newObj.value = newObj.value.replace(/ /g, "");
43747 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") {
43748 newObj.value = newObj.value.toLowerCase();
43751 if (ast.type === "css-decl") {
43752 newObj.prop = newObj.prop.toLowerCase();
43755 if (ast.type === "css-atrule" || ast.type === "css-import") {
43756 newObj.name = newObj.name.toLowerCase();
43759 if (ast.type === "value-number") {
43760 newObj.unit = newObj.unit.toLowerCase();
43763 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) {
43764 newObj.value = cleanCSSStrings(newObj.value);
43767 if (ast.type === "selector-attribute") {
43768 newObj.attribute = newObj.attribute.trim();
43770 if (newObj.namespace) {
43771 if (typeof newObj.namespace === "string") {
43772 newObj.namespace = newObj.namespace.trim();
43774 if (newObj.namespace.length === 0) {
43775 newObj.namespace = true;
43780 if (newObj.value) {
43781 newObj.value = newObj.value.trim().replace(/^['"]|['"]$/g, "");
43782 delete newObj.quoted;
43786 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) {
43787 newObj.value = newObj.value.replace(/([\d.eE+-]+)([a-zA-Z]*)/g, (match, numStr, unit) => {
43788 const num = Number(numStr);
43789 return isNaN(num) ? match : num + unit.toLowerCase();
43793 if (ast.type === "selector-tag") {
43794 const lowercasedValue = ast.value.toLowerCase();
43796 if (["from", "to"].includes(lowercasedValue)) {
43797 newObj.value = lowercasedValue;
43799 } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func`
43802 if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") {
43803 delete newObj.value;
43804 } // Workaround for SCSS nested properties
43807 if (ast.type === "selector-unknown") {
43808 delete newObj.value;
43812 function cleanCSSStrings(value) {
43813 return value.replace(/'/g, '"').replace(/\\([^a-fA-F\d])/g, "$1");
43816 var clean_1$1 = clean$2;
43820 hardline: hardline$6,
43821 literalline: literalline$3,
43823 markAsRoot: markAsRoot$1
43830 function embed$1(path, print, textToDoc
43833 const node = path.getValue();
43835 if (node.type === "yaml") {
43836 return markAsRoot$1(concat$8(["---", hardline$6, node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
43838 })) : "", "---", hardline$6]));
43843 function replaceNewlinesWithLiterallines(doc) {
43844 return mapDoc$2(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$8(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$3)) : currentDoc);
43848 var embed_1$1 = embed$1;
43850 const DELIMITER_MAP = {
43855 function parse$5(text) {
43856 const delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp$2).join("|");
43857 const match = text.match( // trailing spaces after delimiters are allowed
43858 new RegExp(`^(${delimiterRegex})[^\\n\\S]*\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)`));
43860 if (match === null) {
43867 const [raw, delimiter, value] = match;
43870 type: DELIMITER_MAP[delimiter],
43872 raw: raw.replace(/\n$/, "")
43874 content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length)
43878 var frontMatter = parse$5;
43880 function hasPragma$1(text) {
43881 return pragma.hasPragma(frontMatter(text).content);
43884 function insertPragma$2(text) {
43886 frontMatter: frontMatter$1,
43888 } = frontMatter(text);
43889 return (frontMatter$1 ? frontMatter$1.raw + "\n\n" : "") + pragma.insertPragma(content);
43893 hasPragma: hasPragma$1,
43894 insertPragma: insertPragma$2
43897 var lineColumnToIndex = function (lineColumn, text) {
43900 for (let i = 0; i < lineColumn.line - 1; ++i) {
43901 index = text.indexOf("\n", index) + 1;
43903 if (index === -1) {
43908 return index + lineColumn.column;
43912 getLast: getLast$3,
43913 skipEverythingButNewLine: skipEverythingButNewLine$2
43916 function calculateLocStart(node, text) {
43918 return lineColumnToIndex(node.source.start, text) - 1;
43924 function calculateLocEnd(node, text) {
43925 if (node.type === "css-comment" && node.inline) {
43926 return skipEverythingButNewLine$2(text, node.source.startOffset);
43929 const endNode = node.nodes && getLast$3(node.nodes);
43931 if (endNode && node.source && !node.source.end) {
43935 if (node.source && node.source.end) {
43936 return lineColumnToIndex(node.source.end, text);
43942 function calculateLoc(node, text) {
43943 if (node && typeof node === "object") {
43945 node.source.startOffset = calculateLocStart(node, text);
43946 node.source.endOffset = calculateLocEnd(node, text);
43949 for (const key in node) {
43950 calculateLoc(node[key], text);
43955 * Workaround for a bug: quotes in inline comments corrupt loc data of subsequent nodes.
43956 * This function replaces the quotes with U+FFFE and U+FFFF. Later, when the comments are printed,
43957 * their content is extracted from the original text or restored by replacing the placeholder
43958 * characters back with quotes.
43959 * - https://github.com/prettier/prettier/issues/7780
43960 * - https://github.com/shellscape/postcss-less/issues/145
43961 * - About noncharacters (U+FFFE and U+FFFF): http://www.unicode.org/faq/private_use.html#nonchar1
43962 * @param text {string}
43966 function replaceQuotesInInlineComments(text) {
43967 /** @typedef { 'initial' | 'single-quotes' | 'double-quotes' | 'url' | 'comment-block' | 'comment-inline' } State */
43969 /** @type {State} */
43970 let state = "initial";
43971 /** @type {State} */
43973 let stateToReturnFromQuotes = "initial";
43974 let inlineCommentStartIndex;
43975 let inlineCommentContainsQuotes = false;
43976 const inlineCommentsToReplace = [];
43978 for (let i = 0; i < text.length; i++) {
43984 state = "single-quotes";
43989 state = "double-quotes";
43993 if ((c === "u" || c === "U") && text.slice(i, i + 4).toLowerCase() === "url(") {
43999 if (c === "*" && text[i - 1] === "/") {
44000 state = "comment-block";
44004 if (c === "/" && text[i - 1] === "/") {
44005 state = "comment-inline";
44006 inlineCommentStartIndex = i - 1;
44012 case "single-quotes":
44013 if (c === "'" && text[i - 1] !== "\\") {
44014 state = stateToReturnFromQuotes;
44015 stateToReturnFromQuotes = "initial";
44018 if (c === "\n" || c === "\r") {
44019 return text; // invalid input
44024 case "double-quotes":
44025 if (c === '"' && text[i - 1] !== "\\") {
44026 state = stateToReturnFromQuotes;
44027 stateToReturnFromQuotes = "initial";
44030 if (c === "\n" || c === "\r") {
44031 return text; // invalid input
44041 if (c === "\n" || c === "\r") {
44042 return text; // invalid input
44046 state = "single-quotes";
44047 stateToReturnFromQuotes = "url";
44052 state = "double-quotes";
44053 stateToReturnFromQuotes = "url";
44059 case "comment-block":
44060 if (c === "/" && text[i - 1] === "*") {
44066 case "comment-inline":
44067 if (c === '"' || c === "'") {
44068 inlineCommentContainsQuotes = true;
44071 if (c === "\n" || c === "\r") {
44072 if (inlineCommentContainsQuotes) {
44073 inlineCommentsToReplace.push([inlineCommentStartIndex, i]);
44077 inlineCommentContainsQuotes = false;
44084 for (const [start, end] of inlineCommentsToReplace) {
44085 text = text.slice(0, start) + text.slice(start, end).replace(/'/g, "\ufffe").replace(/"/g, "\uffff") + text.slice(end);
44091 function restoreQuotesInInlineComments(text) {
44092 return text.replace(/\ufffe/g, "'").replace(/\uffff/g, '"');
44097 replaceQuotesInInlineComments,
44098 restoreQuotesInInlineComments
44101 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"];
44103 function getAncestorCounter(path, typeOrTypes) {
44104 const types = [].concat(typeOrTypes);
44108 while (ancestorNode = path.getParentNode(++counter)) {
44109 if (types.includes(ancestorNode.type)) {
44117 function getAncestorNode(path, typeOrTypes) {
44118 const counter = getAncestorCounter(path, typeOrTypes);
44119 return counter === -1 ? null : path.getParentNode(counter);
44122 function getPropOfDeclNode(path) {
44123 const declAncestorNode = getAncestorNode(path, "css-decl");
44124 return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase();
44127 function isSCSS(parser, text) {
44128 const hasExplicitParserChoice = parser === "less" || parser === "scss";
44129 const IS_POSSIBLY_SCSS = /(\w\s*:\s*[^}:]+|#){|@import[^\n]+(?:url|,)/;
44130 return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text);
44133 function isWideKeywords(value) {
44134 return ["initial", "inherit", "unset", "revert"].includes(value.toLowerCase());
44137 function isKeyframeAtRuleKeywords(path, value) {
44138 const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
44139 return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].includes(value.toLowerCase());
44142 function maybeToLowerCase(value) {
44143 return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase();
44146 function insideValueFunctionNode(path, functionName) {
44147 const funcAncestorNode = getAncestorNode(path, "value-func");
44148 return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName;
44151 function insideICSSRuleNode(path) {
44152 const ruleAncestorNode = getAncestorNode(path, "css-rule");
44153 return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export"));
44156 function insideAtRuleNode(path, atRuleNameOrAtRuleNames) {
44157 const atRuleNames = [].concat(atRuleNameOrAtRuleNames);
44158 const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
44159 return atRuleAncestorNode && atRuleNames.includes(atRuleAncestorNode.name.toLowerCase());
44162 function insideURLFunctionInImportAtRuleNode(path) {
44163 const node = path.getValue();
44164 const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
44165 return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2;
44168 function isURLFunctionNode(node) {
44169 return node.type === "value-func" && node.value.toLowerCase() === "url";
44172 function isLastNode(path, node) {
44173 const parentNode = path.getParentNode();
44182 return nodes && nodes.indexOf(node) === nodes.length - 1;
44185 function isDetachedRulesetDeclarationNode(node) {
44186 // If a Less file ends up being parsed with the SCSS parser, Less
44187 // variable declarations will be parsed as atrules with names ending
44188 // with a colon, so keep the original case then.
44189 if (!node.selector) {
44193 return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value);
44196 function isForKeywordNode(node) {
44197 return node.type === "value-word" && ["from", "through", "end"].includes(node.value);
44200 function isIfElseKeywordNode(node) {
44201 return node.type === "value-word" && ["and", "or", "not"].includes(node.value);
44204 function isEachKeywordNode(node) {
44205 return node.type === "value-word" && node.value === "in";
44208 function isMultiplicationNode(node) {
44209 return node.type === "value-operator" && node.value === "*";
44212 function isDivisionNode(node) {
44213 return node.type === "value-operator" && node.value === "/";
44216 function isAdditionNode(node) {
44217 return node.type === "value-operator" && node.value === "+";
44220 function isSubtractionNode(node) {
44221 return node.type === "value-operator" && node.value === "-";
44224 function isModuloNode(node) {
44225 return node.type === "value-operator" && node.value === "%";
44228 function isMathOperatorNode(node) {
44229 return isMultiplicationNode(node) || isDivisionNode(node) || isAdditionNode(node) || isSubtractionNode(node) || isModuloNode(node);
44232 function isEqualityOperatorNode(node) {
44233 return node.type === "value-word" && ["==", "!="].includes(node.value);
44236 function isRelationalOperatorNode(node) {
44237 return node.type === "value-word" && ["<", ">", "<=", ">="].includes(node.value);
44240 function isSCSSControlDirectiveNode(node) {
44241 return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].includes(node.name);
44244 function isSCSSNestedPropertyNode(node) {
44245 if (!node.selector) {
44249 return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":");
44252 function isDetachedRulesetCallNode(node) {
44253 return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params);
44256 function isTemplatePlaceholderNode(node) {
44257 return node.name.startsWith("prettier-placeholder");
44260 function isTemplatePropNode(node) {
44261 return node.prop.startsWith("@prettier-placeholder");
44264 function isPostcssSimpleVarNode(currentNode, nextNode) {
44265 return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before;
44268 function hasComposesNode(node) {
44269 return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes";
44272 function hasParensAroundNode(node) {
44273 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;
44276 function hasEmptyRawBefore(node) {
44277 return node.raws && node.raws.before === "";
44280 function isKeyValuePairNode(node) {
44281 return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon";
44284 function isKeyValuePairInParenGroupNode(node) {
44285 return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode(node.groups[0]);
44288 function isSCSSMapItemNode(path) {
44289 const node = path.getValue(); // Ignore empty item (i.e. `$key: ()`)
44291 if (node.groups.length === 0) {
44295 const parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`)
44297 if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) {
44301 const declNode = getAncestorNode(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`)
44303 if (declNode && declNode.prop && declNode.prop.startsWith("$")) {
44305 } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`)
44308 if (isKeyValuePairInParenGroupNode(parentParentNode)) {
44310 } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`)
44313 if (parentParentNode.type === "value-func") {
44320 function isInlineValueCommentNode(node) {
44321 return node.type === "value-comment" && node.inline;
44324 function isHashNode(node) {
44325 return node.type === "value-word" && node.value === "#";
44328 function isLeftCurlyBraceNode(node) {
44329 return node.type === "value-word" && node.value === "{";
44332 function isRightCurlyBraceNode(node) {
44333 return node.type === "value-word" && node.value === "}";
44336 function isWordNode(node) {
44337 return ["value-word", "value-atword"].includes(node.type);
44340 function isColonNode(node) {
44341 return node.type === "value-colon";
44344 function isMediaAndSupportsKeywords(node) {
44345 return node.value && ["not", "and", "or"].includes(node.value.toLowerCase());
44348 function isColorAdjusterFuncNode(node) {
44349 if (node.type !== "value-func") {
44353 return colorAdjusterFunctions.includes(node.value.toLowerCase());
44354 } // TODO: only check `less` when we don't use `less` to parse `css`
44357 function isLessParser(options) {
44358 return options.parser === "css" || options.parser === "less";
44361 function lastLineHasInlineComment(text) {
44362 return /\/\//.test(text.split(/[\r\n]/).pop());
44366 getAncestorCounter,
44370 insideValueFunctionNode,
44371 insideICSSRuleNode,
44373 insideURLFunctionInImportAtRuleNode,
44374 isKeyframeAtRuleKeywords,
44379 isSCSSControlDirectiveNode,
44380 isDetachedRulesetDeclarationNode,
44381 isRelationalOperatorNode,
44382 isEqualityOperatorNode,
44383 isMultiplicationNode,
44388 isMathOperatorNode,
44392 isIfElseKeywordNode,
44394 hasParensAroundNode,
44396 isSCSSNestedPropertyNode,
44397 isDetachedRulesetCallNode,
44398 isTemplatePlaceholderNode,
44399 isTemplatePropNode,
44400 isPostcssSimpleVarNode,
44401 isKeyValuePairNode,
44402 isKeyValuePairInParenGroupNode,
44404 isInlineValueCommentNode,
44406 isLeftCurlyBraceNode,
44407 isRightCurlyBraceNode,
44410 isMediaAndSupportsKeywords,
44411 isColorAdjusterFuncNode,
44412 lastLineHasInlineComment
44416 insertPragma: insertPragma$3
44419 printNumber: printNumber$2,
44420 printString: printString$2,
44421 hasIgnoreComment: hasIgnoreComment$3,
44422 hasNewline: hasNewline$5
44425 isNextLineEmpty: isNextLineEmpty$3
44428 restoreQuotesInInlineComments: restoreQuotesInInlineComments$1
44435 hardline: hardline$7,
44436 softline: softline$3,
44444 removeLines: removeLines$2
44448 getAncestorNode: getAncestorNode$1,
44449 getPropOfDeclNode: getPropOfDeclNode$1,
44450 maybeToLowerCase: maybeToLowerCase$1,
44451 insideValueFunctionNode: insideValueFunctionNode$1,
44452 insideICSSRuleNode: insideICSSRuleNode$1,
44453 insideAtRuleNode: insideAtRuleNode$1,
44454 insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1,
44455 isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1,
44456 isWideKeywords: isWideKeywords$1,
44458 isLastNode: isLastNode$1,
44459 isLessParser: isLessParser$1,
44460 isSCSSControlDirectiveNode: isSCSSControlDirectiveNode$1,
44461 isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode$1,
44462 isRelationalOperatorNode: isRelationalOperatorNode$1,
44463 isEqualityOperatorNode: isEqualityOperatorNode$1,
44464 isMultiplicationNode: isMultiplicationNode$1,
44465 isDivisionNode: isDivisionNode$1,
44466 isAdditionNode: isAdditionNode$1,
44467 isSubtractionNode: isSubtractionNode$1,
44468 isMathOperatorNode: isMathOperatorNode$1,
44469 isEachKeywordNode: isEachKeywordNode$1,
44470 isForKeywordNode: isForKeywordNode$1,
44471 isURLFunctionNode: isURLFunctionNode$1,
44472 isIfElseKeywordNode: isIfElseKeywordNode$1,
44473 hasComposesNode: hasComposesNode$1,
44474 hasParensAroundNode: hasParensAroundNode$1,
44475 hasEmptyRawBefore: hasEmptyRawBefore$1,
44476 isKeyValuePairNode: isKeyValuePairNode$1,
44477 isDetachedRulesetCallNode: isDetachedRulesetCallNode$1,
44478 isTemplatePlaceholderNode: isTemplatePlaceholderNode$1,
44479 isTemplatePropNode: isTemplatePropNode$1,
44480 isPostcssSimpleVarNode: isPostcssSimpleVarNode$1,
44481 isSCSSMapItemNode: isSCSSMapItemNode$1,
44482 isInlineValueCommentNode: isInlineValueCommentNode$1,
44483 isHashNode: isHashNode$1,
44484 isLeftCurlyBraceNode: isLeftCurlyBraceNode$1,
44485 isRightCurlyBraceNode: isRightCurlyBraceNode$1,
44486 isWordNode: isWordNode$1,
44487 isColonNode: isColonNode$1,
44488 isMediaAndSupportsKeywords: isMediaAndSupportsKeywords$1,
44489 isColorAdjusterFuncNode: isColorAdjusterFuncNode$1,
44490 lastLineHasInlineComment: lastLineHasInlineComment$1
44493 function shouldPrintComma$1(options) {
44494 switch (options.trailingComma) {
44505 function genericPrint$2(path, options, print) {
44506 const node = path.getValue();
44507 /* istanbul ignore if */
44513 if (typeof node === "string") {
44517 switch (node.type) {
44520 return concat$9([node.raw, hardline$7]);
44524 const nodes = printNodeSequence(path, options, print);
44526 if (nodes.parts.length) {
44527 return concat$9([nodes, options.__isHTMLStyleAttribute ? "" : hardline$7]);
44533 case "css-comment":
44535 const isInlineComment = node.inline || node.raws.inline;
44536 const text = options.originalText.slice(options.locStart(node), options.locEnd(node));
44537 return isInlineComment ? text.trimEnd() : text;
44542 return concat$9([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$9([node.selector && node.selector.type === "selector-unknown" && lastLineHasInlineComment$1(node.selector.value) ? line$5 : " ", "{", node.nodes.length > 0 ? indent$5(concat$9([hardline$7, printNodeSequence(path, options, print)])) : "", hardline$7, "}", isDetachedRulesetDeclarationNode$1(node) ? ";" : ""]) : ";"]);
44547 const parentNode = path.getParentNode();
44548 return concat$9([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$2(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$9([" {", indent$5(concat$9([softline$3, printNodeSequence(path, options, print)])), softline$3, "}"]) : isTemplatePropNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : ";"]);
44553 const parentNode = path.getParentNode();
44554 const isTemplatePlaceholderNodeWithoutSemiColon = isTemplatePlaceholderNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";";
44556 if (isLessParser$1(options)) {
44558 return concat$9([path.call(print, "selector"), node.important ? " !important" : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
44561 if (node.function) {
44562 return concat$9([node.name, concat$9([path.call(print, "params")]), isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
44565 if (node.variable) {
44566 return concat$9(["@", node.name, ": ", node.value ? concat$9([path.call(print, "value")]) : "", node.raws.between.trim() ? node.raws.between.trim() + " " : "", node.nodes ? concat$9(["{", indent$5(concat$9([node.nodes.length > 0 ? softline$3 : "", printNodeSequence(path, options, print)])), softline$3, "}"]) : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
44570 return concat$9(["@", // If a Less file ends up being parsed with the SCSS parser, Less
44571 // variable declarations will be parsed as at-rules with names ending
44572 // with a colon, so keep the original case then.
44573 isDetachedRulesetCallNode$1(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase$1(node.name), node.params ? concat$9([isDetachedRulesetCallNode$1(node) ? "" : isTemplatePlaceholderNode$1(node) ? node.raws.afterName === "" ? "" : node.name.endsWith(":") ? " " : /^\s*\n\s*\n/.test(node.raws.afterName) ? concat$9([hardline$7, hardline$7]) : /^\s*\n/.test(node.raws.afterName) ? hardline$7 : " " : " ", path.call(print, "params")]) : "", node.selector ? indent$5(concat$9([" ", path.call(print, "selector")])) : "", node.value ? group$6(concat$9([" ", path.call(print, "value"), isSCSSControlDirectiveNode$1(node) ? hasParensAroundNode$1(node) ? " " : line$5 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$9([isSCSSControlDirectiveNode$1(node) ? "" : " ", "{", indent$5(concat$9([node.nodes.length > 0 ? softline$3 : "", printNodeSequence(path, options, print)])), softline$3, "}"]) : isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
44575 // postcss-media-query-parser
44577 case "media-query-list":
44580 path.each(childPath => {
44581 const node = childPath.getValue();
44583 if (node.type === "media-query" && node.value === "") {
44587 parts.push(childPath.call(print));
44589 return group$6(indent$5(join$6(line$5, parts)));
44592 case "media-query":
44594 return concat$9([join$6(" ", path.map(print, "nodes")), isLastNode$1(path, node) ? "" : ","]);
44599 return adjustNumbers(adjustStrings(node.value, options));
44602 case "media-feature-expression":
44608 return concat$9(["(", concat$9(path.map(print, "nodes")), ")"]);
44611 case "media-feature":
44613 return maybeToLowerCase$1(adjustStrings(node.value.replace(/ +/g, " "), options));
44616 case "media-colon":
44618 return concat$9([node.value, " "]);
44621 case "media-value":
44623 return adjustNumbers(adjustStrings(node.value, options));
44626 case "media-keyword":
44628 return adjustStrings(node.value, options);
44633 return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options);
44636 case "media-unknown":
44640 // postcss-selector-parser
44642 case "selector-root":
44644 return group$6(concat$9([insideAtRuleNode$1(path, "custom-selector") ? concat$9([getAncestorNode$1(path, "css-atrule").customSelector, line$5]) : "", join$6(concat$9([",", insideAtRuleNode$1(path, ["extend", "custom-selector", "nest"]) ? line$5 : hardline$7]), path.map(print, "nodes"))]));
44647 case "selector-selector":
44649 return group$6(indent$5(concat$9(path.map(print, "nodes"))));
44652 case "selector-comment":
44657 case "selector-string":
44659 return adjustStrings(node.value, options);
44662 case "selector-tag":
44664 const parentNode = path.getParentNode();
44665 const index = parentNode && parentNode.nodes.indexOf(node);
44666 const prevNode = index && parentNode.nodes[index - 1];
44667 return concat$9([node.namespace ? concat$9([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isKeyframeAtRuleKeywords$1(path, node.value) ? node.value.toLowerCase() : node.value)]);
44670 case "selector-id":
44672 return concat$9(["#", node.value]);
44675 case "selector-class":
44677 return concat$9([".", adjustNumbers(adjustStrings(node.value, options))]);
44680 case "selector-attribute":
44682 return concat$9(["[", node.namespace ? concat$9([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" : "", "]"]);
44685 case "selector-combinator":
44687 if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") {
44688 const parentNode = path.getParentNode();
44689 const leading = parentNode.type === "selector-selector" && parentNode.nodes[0] === node ? "" : line$5;
44690 return concat$9([leading, node.value, isLastNode$1(path, node) ? "" : " "]);
44693 const leading = node.value.trim().startsWith("(") ? line$5 : "";
44694 const value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$5;
44695 return concat$9([leading, value]);
44698 case "selector-universal":
44700 return concat$9([node.namespace ? concat$9([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]);
44703 case "selector-pseudo":
44705 return concat$9([maybeToLowerCase$1(node.value), node.nodes && node.nodes.length > 0 ? concat$9(["(", join$6(", ", path.map(print, "nodes")), ")"]) : ""]);
44708 case "selector-nesting":
44713 case "selector-unknown":
44715 const ruleAncestorNode = getAncestorNode$1(path, "css-rule"); // Nested SCSS property
44717 if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) {
44718 return adjustNumbers(adjustStrings(maybeToLowerCase$1(node.value), options));
44719 } // originalText has to be used for Less, see replaceQuotesInInlineComments in loc.js
44722 const parentNode = path.getParentNode();
44724 if (parentNode.raws && parentNode.raws.selector) {
44725 const start = options.locStart(parentNode);
44726 const end = start + parentNode.raws.selector.length;
44727 return options.originalText.slice(start, end).trim();
44732 // postcss-values-parser
44734 case "value-value":
44737 return path.call(print, "group");
44740 case "value-comment":
44742 return concat$9([node.inline ? "//" : "/*", // see replaceQuotesInInlineComments in loc.js
44743 // value-* nodes don't have correct location data, so we have to rely on placeholder characters.
44744 restoreQuotesInInlineComments$1(node.value), node.inline ? "" : "*/"]);
44747 case "value-comma_group":
44749 const parentNode = path.getParentNode();
44750 const parentParentNode = path.getParentNode(1);
44751 const declAncestorProp = getPropOfDeclNode$1(path);
44752 const isGridValue = declAncestorProp && parentNode.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template"));
44753 const atRuleAncestorNode = getAncestorNode$1(path, "css-atrule");
44754 const isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode$1(atRuleAncestorNode);
44755 const printed = path.map(print, "groups");
44757 const insideURLFunction = insideValueFunctionNode$1(path, "url");
44758 let insideSCSSInterpolationInString = false;
44759 let didBreak = false;
44761 for (let i = 0; i < node.groups.length; ++i) {
44762 parts.push(printed[i]);
44763 const iPrevNode = node.groups[i - 1];
44764 const iNode = node.groups[i];
44765 const iNextNode = node.groups[i + 1];
44766 const iNextNextNode = node.groups[i + 2];
44768 if (insideURLFunction) {
44769 if (iNextNode && isAdditionNode$1(iNextNode) || isAdditionNode$1(iNode)) {
44774 } // Ignore after latest node (i.e. before semicolon)
44779 } // styled.div` background: var(--${one}); `
44782 if (!iPrevNode && iNode.value === "--" && iNextNode.type === "value-atword") {
44784 } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`)
44787 const isStartSCSSInterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{");
44788 const isEndingSCSSInterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}");
44790 if (isStartSCSSInterpolationInString || isEndingSCSSInterpolationInString) {
44791 insideSCSSInterpolationInString = !insideSCSSInterpolationInString;
44795 if (insideSCSSInterpolationInString) {
44797 } // Ignore colon (i.e. `:`)
44800 if (isColonNode$1(iNode) || isColonNode$1(iNextNode)) {
44802 } // Ignore `@` in Less (i.e. `@@var;`)
44805 if (iNode.type === "value-atword" && iNode.value === "") {
44807 } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`)
44810 if (iNode.value === "~") {
44812 } // Ignore escape `\`
44815 if (iNode.value && iNode.value.includes("\\") && iNextNode && iNextNode.type !== "value-comment") {
44817 } // Ignore escaped `/`
44820 if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") {
44822 } // Ignore `\` (i.e. `$variable: \@small;`)
44825 if (iNode.value === "\\") {
44827 } // Ignore `$$` (i.e. `background-color: $$(style)Color;`)
44830 if (isPostcssSimpleVarNode$1(iNode, iNextNode)) {
44832 } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`)
44835 if (isHashNode$1(iNode) || isLeftCurlyBraceNode$1(iNode) || isRightCurlyBraceNode$1(iNextNode) || isLeftCurlyBraceNode$1(iNextNode) && hasEmptyRawBefore$1(iNextNode) || isRightCurlyBraceNode$1(iNode) && hasEmptyRawBefore$1(iNextNode)) {
44837 } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`)
44840 if (iNode.value === "--" && isHashNode$1(iNextNode)) {
44842 } // Formatting math operations
44845 const isMathOperator = isMathOperatorNode$1(iNode);
44846 const isNextMathOperator = isMathOperatorNode$1(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is
44847 // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`)
44848 // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`)
44850 if ((isMathOperator && isHashNode$1(iNextNode) || isNextMathOperator && isRightCurlyBraceNode$1(iNode)) && hasEmptyRawBefore$1(iNextNode)) {
44852 } // Print spaces before and after addition and subtraction math operators as is in `calc` function
44853 // due to the fact that it is not valid syntax
44854 // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`)
44857 if (insideValueFunctionNode$1(path, "calc") && (isAdditionNode$1(iNode) || isAdditionNode$1(iNextNode) || isSubtractionNode$1(iNode) || isSubtractionNode$1(iNextNode)) && hasEmptyRawBefore$1(iNextNode)) {
44859 } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`)
44860 // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is.
44863 const isColorAdjusterNode = (isAdditionNode$1(iNode) || isSubtractionNode$1(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode$1(parentParentNode) && !hasEmptyRawBefore$1(iNextNode);
44864 const requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode$1(iNextNextNode) || iNode.type === "value-func" || isWordNode$1(iNode);
44865 const requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode$1(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode$1(iPrevNode); // Formatting `/`, `+`, `-` sign
44867 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)))) {
44869 } // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`)
44872 if (isInlineValueCommentNode$1(iNode)) {
44873 parts.push(hardline$7);
44875 } // Handle keywords in SCSS control directive
44878 if (isControlDirective && (isEqualityOperatorNode$1(iNextNode) || isRelationalOperatorNode$1(iNextNode) || isIfElseKeywordNode$1(iNextNode) || isEachKeywordNode$1(iNode) || isForKeywordNode$1(iNode))) {
44881 } // At-rule `namespace` should be in one line
44884 if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") {
44887 } // Formatting `grid` property
44891 if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) {
44892 parts.push(hardline$7);
44899 } // Add `space` before next math operation
44900 // Note: `grip` property have `/` delimiter and it is not math operation, so
44901 // `grid` property handles above
44904 if (isNextMathOperator) {
44907 } // Be default all values go through `line`
44910 parts.push(line$5);
44914 parts.unshift(hardline$7);
44917 if (isControlDirective) {
44918 return group$6(indent$5(concat$9(parts)));
44919 } // Indent is not needed for import url when url is very long
44920 // and node has two groups
44921 // when type is value-comma_group
44922 // example @import url("verylongurl") projection,tv
44925 if (insideURLFunctionInImportAtRuleNode$1(path)) {
44926 return group$6(fill$4(parts));
44929 return group$6(indent$5(fill$4(parts)));
44932 case "value-paren_group":
44934 const parentNode = path.getParentNode();
44936 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:"))) {
44937 return concat$9([node.open ? path.call(print, "open") : "", join$6(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]);
44941 const printed = path.map(print, "groups");
44944 for (let i = 0; i < printed.length; i++) {
44946 res.push(concat$9([",", line$5]));
44949 res.push(printed[i]);
44952 return group$6(indent$5(fill$4(res)));
44955 const isSCSSMapItem = isSCSSMapItemNode$1(path);
44956 const lastItem = node.groups[node.groups.length - 1];
44957 const isLastItemComment = lastItem && lastItem.type === "value-comment";
44958 return group$6(concat$9([node.open ? path.call(print, "open") : "", indent$5(concat$9([softline$3, join$6(concat$9([",", line$5]), path.map(childPath => {
44959 const node = childPath.getValue();
44960 const printed = print(childPath); // Key/Value pair in open paren already indented
44962 if (isKeyValuePairNode$1(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") {
44963 printed.contents.contents.parts[1] = group$6(printed.contents.contents.parts[1]);
44964 return group$6(dedent$2(printed));
44968 }, "groups"))])), ifBreak$2(!isLastItemComment && isSCSS$1(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma$1(options) ? "," : ""), softline$3, node.close ? path.call(print, "close") : ""]), {
44969 shouldBreak: isSCSSMapItem
44975 return concat$9([node.value, insideAtRuleNode$1(path, "supports") && isMediaAndSupportsKeywords$1(node) ? " " : "", path.call(print, "group")]);
44978 case "value-paren":
44983 case "value-number":
44985 return concat$9([printCssNumber(node.value), maybeToLowerCase$1(node.unit)]);
44988 case "value-operator":
44995 if (node.isColor && node.isHex || isWideKeywords$1(node.value)) {
44996 return node.value.toLowerCase();
45002 case "value-colon":
45004 return concat$9([node.value, // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`)
45005 insideValueFunctionNode$1(path, "url") ? "" : line$5]);
45008 case "value-comma":
45010 return concat$9([node.value, " "]);
45013 case "value-string":
45015 return printString$2(node.raws.quote + node.value + node.raws.quote, options);
45018 case "value-atword":
45020 return concat$9(["@", node.value]);
45023 case "value-unicode-range":
45028 case "value-unknown":
45034 /* istanbul ignore next */
45035 throw new Error(`Unknown postcss type ${JSON.stringify(node.type)}`);
45039 function printNodeSequence(path, options, print) {
45040 const node = path.getValue();
45043 path.map(pathChild => {
45044 const prevNode = node.nodes[i - 1];
45046 if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") {
45047 const childNode = pathChild.getValue();
45048 parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode)));
45050 parts.push(pathChild.call(print));
45053 if (i !== node.nodes.length - 1) {
45054 if (node.nodes[i + 1].type === "css-comment" && !hasNewline$5(options.originalText, options.locStart(node.nodes[i + 1]), {
45056 }) && 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") {
45059 parts.push(options.__isHTMLStyleAttribute ? line$5 : hardline$7);
45061 if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), options.locEnd) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml") {
45062 parts.push(hardline$7);
45069 return concat$9(parts);
45072 const STRING_REGEX$3 = /(['"])(?:(?!\1)[^\\]|\\[\s\S])*\1/g;
45073 const NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g;
45074 const STANDARD_UNIT_REGEX = /[a-zA-Z]+/g;
45075 const WORD_PART_REGEX = /[$@]?[a-zA-Z_\u0080-\uFFFF][\w\-\u0080-\uFFFF]*/g;
45076 const ADJUST_NUMBERS_REGEX = new RegExp(STRING_REGEX$3.source + "|" + `(${WORD_PART_REGEX.source})?` + `(${NUMBER_REGEX.source})` + `(${STANDARD_UNIT_REGEX.source})?`, "g");
45078 function adjustStrings(value, options) {
45079 return value.replace(STRING_REGEX$3, match => printString$2(match, options));
45082 function quoteAttributeValue(value, options) {
45083 const quote = options.singleQuote ? "'" : '"';
45084 return value.includes('"') || value.includes("'") ? value : quote + value + quote;
45087 function adjustNumbers(value) {
45088 return value.replace(ADJUST_NUMBERS_REGEX, (match, quote, wordPart, number, unit) => !wordPart && number ? printCssNumber(number) + maybeToLowerCase$1(unit || "") : match);
45091 function printCssNumber(rawNumber) {
45092 return printNumber$2(rawNumber) // Remove trailing `.0`.
45093 .replace(/\.0(?=$|e)/, "");
45096 var printerPostcss = {
45097 print: genericPrint$2,
45099 insertPragma: insertPragma$3,
45100 hasPrettierIgnore: hasIgnoreComment$3,
45101 massageAstNode: clean_1$1
45105 singleQuote: commonOptions.singleQuote
45108 var name$9 = "CSS";
45109 var type$7 = "markup";
45110 var tmScope$7 = "source.css";
45111 var aceMode$7 = "css";
45112 var codemirrorMode$7 = "css";
45113 var codemirrorMimeType$7 = "text/css";
45114 var color$2 = "#563d7c";
45115 var extensions$7 = [
45118 var languageId$7 = 50;
45122 tmScope: tmScope$7,
45123 aceMode: aceMode$7,
45124 codemirrorMode: codemirrorMode$7,
45125 codemirrorMimeType: codemirrorMimeType$7,
45127 extensions: extensions$7,
45128 languageId: languageId$7
45131 var CSS$1 = /*#__PURE__*/Object.freeze({
45135 tmScope: tmScope$7,
45136 aceMode: aceMode$7,
45137 codemirrorMode: codemirrorMode$7,
45138 codemirrorMimeType: codemirrorMimeType$7,
45140 extensions: extensions$7,
45141 languageId: languageId$7,
45145 var name$a = "PostCSS";
45146 var type$8 = "markup";
45147 var tmScope$8 = "source.postcss";
45148 var group$7 = "CSS";
45149 var extensions$8 = [
45153 var aceMode$8 = "text";
45154 var languageId$8 = 262764437;
45158 tmScope: tmScope$8,
45160 extensions: extensions$8,
45161 aceMode: aceMode$8,
45162 languageId: languageId$8
45165 var PostCSS$1 = /*#__PURE__*/Object.freeze({
45169 tmScope: tmScope$8,
45171 extensions: extensions$8,
45172 aceMode: aceMode$8,
45173 languageId: languageId$8,
45177 var name$b = "Less";
45178 var type$9 = "markup";
45179 var group$8 = "CSS";
45180 var extensions$9 = [
45183 var tmScope$9 = "source.css.less";
45184 var aceMode$9 = "less";
45185 var codemirrorMode$8 = "css";
45186 var codemirrorMimeType$8 = "text/css";
45187 var languageId$9 = 198;
45192 extensions: extensions$9,
45193 tmScope: tmScope$9,
45194 aceMode: aceMode$9,
45195 codemirrorMode: codemirrorMode$8,
45196 codemirrorMimeType: codemirrorMimeType$8,
45197 languageId: languageId$9
45200 var Less$1 = /*#__PURE__*/Object.freeze({
45205 extensions: extensions$9,
45206 tmScope: tmScope$9,
45207 aceMode: aceMode$9,
45208 codemirrorMode: codemirrorMode$8,
45209 codemirrorMimeType: codemirrorMimeType$8,
45210 languageId: languageId$9,
45214 var name$c = "SCSS";
45215 var type$a = "markup";
45216 var tmScope$a = "source.css.scss";
45217 var group$9 = "CSS";
45218 var aceMode$a = "scss";
45219 var codemirrorMode$9 = "css";
45220 var codemirrorMimeType$9 = "text/x-scss";
45221 var extensions$a = [
45224 var languageId$a = 329;
45228 tmScope: tmScope$a,
45230 aceMode: aceMode$a,
45231 codemirrorMode: codemirrorMode$9,
45232 codemirrorMimeType: codemirrorMimeType$9,
45233 extensions: extensions$a,
45234 languageId: languageId$a
45237 var SCSS$1 = /*#__PURE__*/Object.freeze({
45241 tmScope: tmScope$a,
45243 aceMode: aceMode$a,
45244 codemirrorMode: codemirrorMode$9,
45245 codemirrorMimeType: codemirrorMimeType$9,
45246 extensions: extensions$a,
45247 languageId: languageId$a,
45251 var require$$0$2 = getCjsExportFromNamespace(CSS$1);
45253 var require$$1$2 = getCjsExportFromNamespace(PostCSS$1);
45255 var require$$2$1 = getCjsExportFromNamespace(Less$1);
45257 var require$$3$1 = getCjsExportFromNamespace(SCSS$1);
45259 const languages$1 = [createLanguage(require$$0$2, () => ({
45262 vscodeLanguageIds: ["css"]
45263 })), createLanguage(require$$1$2, () => ({
45266 vscodeLanguageIds: ["postcss"]
45267 })), createLanguage(require$$2$1, () => ({
45270 vscodeLanguageIds: ["less"]
45271 })), createLanguage(require$$3$1, () => ({
45274 vscodeLanguageIds: ["scss"]
45276 const printers$1 = {
45277 postcss: printerPostcss
45279 var languageCss = {
45280 languages: languages$1,
45281 options: options$3,
45282 printers: printers$1
45285 var clean$3 = function (ast, newNode) {
45286 delete newNode.loc;
45287 delete newNode.selfClosing; // (Glimmer/HTML) ignore TextNode whitespace
45289 if (ast.type === "TextNode") {
45290 const trimmed = ast.chars.trim();
45296 newNode.chars = trimmed;
45300 function isUppercase(string) {
45301 return string.toUpperCase() === string;
45304 function isGlimmerComponent(node) {
45305 return isNodeOfSomeType(node, ["ElementNode"]) && typeof node.tag === "string" && (isUppercase(node.tag[0]) || node.tag.includes("."));
45308 function isWhitespaceNode(node) {
45309 return isNodeOfSomeType(node, ["TextNode"]) && !/\S/.test(node.chars);
45312 function isNodeOfSomeType(node, types) {
45313 return node && types.some(type => node.type === type);
45316 function isParentOfSomeType(path, types) {
45317 const parentNode = path.getParentNode(0);
45318 return isNodeOfSomeType(parentNode, types);
45321 function isPreviousNodeOfSomeType(path, types) {
45322 const previousNode = getPreviousNode(path);
45323 return isNodeOfSomeType(previousNode, types);
45326 function isNextNodeOfSomeType(path, types) {
45327 const nextNode = getNextNode(path);
45328 return isNodeOfSomeType(nextNode, types);
45331 function getSiblingNode(path, offset) {
45332 const node = path.getValue();
45333 const parentNode = path.getParentNode(0) || {};
45334 const children = parentNode.children || parentNode.body || [];
45335 const index = children.indexOf(node);
45336 return index !== -1 && children[index + offset];
45339 function getPreviousNode(path, lookBack = 1) {
45340 return getSiblingNode(path, -lookBack);
45343 function getNextNode(path) {
45344 return getSiblingNode(path, 1);
45347 function isPrettierIgnoreNode(node) {
45348 return isNodeOfSomeType(node, ["MustacheCommentStatement"]) && typeof node.value === "string" && node.value.trim() === "prettier-ignore";
45351 function hasPrettierIgnore$2(path) {
45352 const node = path.getValue();
45353 const previousPreviousNode = getPreviousNode(path, 2);
45354 return isPrettierIgnoreNode(node) || isPrettierIgnoreNode(previousPreviousNode);
45360 hasPrettierIgnore: hasPrettierIgnore$2,
45361 isGlimmerComponent,
45362 isNextNodeOfSomeType,
45364 isParentOfSomeType,
45365 isPreviousNodeOfSomeType,
45372 softline: softline$4,
45373 hardline: hardline$8,
45378 } = document.builders;
45380 getNextNode: getNextNode$1,
45381 getPreviousNode: getPreviousNode$1,
45382 hasPrettierIgnore: hasPrettierIgnore$3,
45383 isGlimmerComponent: isGlimmerComponent$1,
45384 isNextNodeOfSomeType: isNextNodeOfSomeType$1,
45385 isParentOfSomeType: isParentOfSomeType$1,
45386 isPreviousNodeOfSomeType: isPreviousNodeOfSomeType$1,
45387 isWhitespaceNode: isWhitespaceNode$1
45388 } = utils$8; // http://w3c.github.io/html/single-page.html#void-elements
45390 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:
45391 // https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts
45393 function print(path, options, print) {
45394 const n = path.getValue();
45395 /* istanbul ignore if*/
45401 if (hasPrettierIgnore$3(path)) {
45402 const startOffset = locationToOffset(options.originalText, n.loc.start.line - 1, n.loc.start.column);
45403 const endOffset = locationToOffset(options.originalText, n.loc.end.line - 1, n.loc.end.column);
45404 const ignoredText = options.originalText.slice(startOffset, endOffset);
45405 return ignoredText;
45413 return group$a(concat$a(path.map(print, "body")));
45416 case "ElementNode":
45418 const hasChildren = n.children.length > 0;
45419 const hasNonWhitespaceChildren = n.children.some(n => !isWhitespaceNode$1(n));
45420 const isVoid = isGlimmerComponent$1(n) && (!hasChildren || !hasNonWhitespaceChildren) || voidTags.includes(n.tag);
45421 const closeTagForNoBreak = isVoid ? concat$a([" />", softline$4]) : ">";
45422 const closeTagForBreak = isVoid ? "/>" : ">";
45424 const printParams = (path, print) => indent$6(concat$a([n.attributes.length ? line$6 : "", join$7(line$6, path.map(print, "attributes")), n.modifiers.length ? line$6 : "", join$7(line$6, path.map(print, "modifiers")), n.comments.length ? line$6 : "", join$7(line$6, path.map(print, "comments"))]));
45426 const nextNode = getNextNode$1(path);
45427 return concat$a([group$a(concat$a(["<", n.tag, printParams(path, print), n.blockParams.length ? ` as |${n.blockParams.join(" ")}|` : "", ifBreak$3(softline$4, ""), ifBreak$3(closeTagForBreak, closeTagForNoBreak)])), !isVoid ? group$a(concat$a([hasNonWhitespaceChildren ? indent$6(printChildren(path, options, print)) : "", ifBreak$3(hasChildren ? hardline$8 : "", ""), concat$a(["</", n.tag, ">"])])) : "", nextNode && nextNode.type === "ElementNode" ? hardline$8 : ""]);
45430 case "BlockStatement":
45432 const pp = path.getParentNode(1);
45433 const isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if";
45434 const hasElseIf = n.inverse && n.inverse.body.length === 1 && n.inverse.body[0].type === "BlockStatement" && n.inverse.body[0].path.parts[0] === "if";
45435 const indentElse = hasElseIf ? a => a : indent$6;
45436 const inverseElseStatement = (n.inverseStrip.open ? "{{~" : "{{") + "else" + (n.inverseStrip.close ? "~}}" : "}}");
45439 return concat$a([isElseIf ? concat$a([n.openStrip.open ? "{{~else " : "{{else ", printPathParams(path, print), n.openStrip.close ? "~}}" : "}}"]) : printOpenBlock(path, print, n.openStrip), indent$6(concat$a([hardline$8, path.call(print, "program")])), n.inverse && !hasElseIf ? concat$a([hardline$8, inverseElseStatement]) : "", n.inverse ? indentElse(concat$a([hardline$8, path.call(print, "inverse")])) : "", isElseIf ? "" : concat$a([hardline$8, printCloseBlock(path, print, n.closeStrip)])]);
45440 } else if (isElseIf) {
45441 return concat$a([concat$a([n.openStrip.open ? "{{~else" : "{{else ", printPathParams(path, print), n.openStrip.close ? "~}}" : "}}"]), indent$6(concat$a([hardline$8, path.call(print, "program")]))]);
45444 const hasNonWhitespaceChildren = n.program.body.some(n => !isWhitespaceNode$1(n));
45445 return concat$a([printOpenBlock(path, print, n.openStrip), group$a(concat$a([indent$6(concat$a([softline$4, path.call(print, "program")])), hasNonWhitespaceChildren ? hardline$8 : softline$4, printCloseBlock(path, print, n.closeStrip)]))]);
45448 case "ElementModifierStatement":
45450 return group$a(concat$a(["{{", printPathParams(path, print), softline$4, "}}"]));
45453 case "MustacheStatement":
45455 const isEscaped = n.escaped === false;
45460 const opening = (isEscaped ? "{{{" : "{{") + (openStrip ? "~" : "");
45461 const closing = (closeStrip ? "~" : "") + (isEscaped ? "}}}" : "}}");
45462 const leading = isParentOfSomeType$1(path, ["AttrNode", "ConcatStatement", "ElementNode"]) ? [opening, indent$6(softline$4)] : [opening];
45463 return group$a(concat$a([...leading, printPathParams(path, print), softline$4, closing]));
45466 case "SubExpression":
45468 const params = printParams(path, print);
45469 const printedParams = params.length > 0 ? indent$6(concat$a([line$6, group$a(join$7(line$6, params))])) : "";
45470 return group$a(concat$a(["(", printPath(path, print), printedParams, softline$4, ")"]));
45475 const isText = n.value.type === "TextNode";
45476 const isEmptyText = isText && n.value.chars === ""; // If the text is empty and the value's loc start and end columns are the
45477 // same, there is no value for this AttrNode and it should be printed
45478 // without the `=""`. Example: `<img data-test>` -> `<img data-test>`
45480 const isEmptyValue = isEmptyText && n.value.loc.start.column === n.value.loc.end.column;
45482 if (isEmptyValue) {
45483 return concat$a([n.name]);
45486 const value = path.call(print, "value");
45487 const quotedValue = isText ? printStringLiteral(value.parts.join(), options) : value;
45488 return concat$a([n.name, "=", quotedValue]);
45491 case "ConcatStatement":
45493 return concat$a(['"', concat$a(path.map(partPath => print(partPath), "parts").filter(a => a !== "")), '"']);
45498 return concat$a([join$7(line$6, path.map(print, "pairs"))]);
45503 return concat$a([n.key, "=", path.call(print, "value")]);
45508 const maxLineBreaksToPreserve = 2;
45509 const isFirstElement = !getPreviousNode$1(path);
45510 const isLastElement = !getNextNode$1(path);
45511 const isWhitespaceOnly = !/\S/.test(n.chars);
45512 const lineBreaksCount = countNewLines(n.chars);
45513 const hasBlockParent = path.getParentNode(0).type === "Block";
45514 const hasElementParent = path.getParentNode(0).type === "ElementNode";
45515 const hasTemplateParent = path.getParentNode(0).type === "Template";
45516 let leadingLineBreaksCount = countLeadingNewLines(n.chars);
45517 let trailingLineBreaksCount = countTrailingNewLines(n.chars);
45519 if ((isFirstElement || isLastElement) && isWhitespaceOnly && (hasBlockParent || hasElementParent || hasTemplateParent)) {
45523 if (isWhitespaceOnly && lineBreaksCount) {
45524 leadingLineBreaksCount = Math.min(lineBreaksCount, maxLineBreaksToPreserve);
45525 trailingLineBreaksCount = 0;
45527 if (isNextNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) {
45528 trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1);
45531 if (isPreviousNodeOfSomeType$1(path, ["ElementNode"]) || isPreviousNodeOfSomeType$1(path, ["BlockStatement"])) {
45532 leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1);
45536 let leadingSpace = "";
45537 let trailingSpace = ""; // preserve a space inside of an attribute node where whitespace present,
45538 // when next to mustache statement.
45540 const inAttrNode = path.stack.includes("attributes");
45543 const parentNode = path.getParentNode(0);
45544 const isConcat = parentNode.type === "ConcatStatement";
45550 const partIndex = parts.indexOf(n);
45552 if (partIndex > 0) {
45553 const partType = parts[partIndex - 1].type;
45554 const isMustache = partType === "MustacheStatement";
45557 leadingSpace = " ";
45561 if (partIndex < parts.length - 1) {
45562 const partType = parts[partIndex + 1].type;
45563 const isMustache = partType === "MustacheStatement";
45566 trailingSpace = " ";
45571 if (trailingLineBreaksCount === 0 && isNextNodeOfSomeType$1(path, ["MustacheStatement"])) {
45572 trailingSpace = " ";
45575 if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) {
45576 leadingSpace = " ";
45579 if (isFirstElement) {
45580 leadingLineBreaksCount = 0;
45584 if (isLastElement) {
45585 trailingLineBreaksCount = 0;
45586 trailingSpace = "";
45590 return concat$a([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), n.chars.replace(/^[\s ]+/g, leadingSpace).replace(/[\s ]+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)].filter(Boolean));
45593 case "MustacheCommentStatement":
45595 const dashes = n.value.includes("}}") ? "--" : "";
45596 return concat$a(["{{!", dashes, n.value, dashes, "}}"]);
45599 case "PathExpression":
45604 case "BooleanLiteral":
45606 return String(n.value);
45609 case "CommentStatement":
45611 return concat$a(["<!--", n.value, "-->"]);
45614 case "StringLiteral":
45616 return printStringLiteral(n.value, options);
45619 case "NumberLiteral":
45621 return String(n.value);
45624 case "UndefinedLiteral":
45626 return "undefined";
45629 case "NullLiteral":
45634 /* istanbul ignore next */
45637 throw new Error("unknown glimmer type: " + JSON.stringify(n.type));
45641 function printChildren(path, options, print) {
45642 return concat$a(path.map((childPath, childIndex) => {
45643 const childNode = path.getValue();
45644 const isFirstNode = childIndex === 0;
45645 const isLastNode = childIndex === path.getParentNode(0).children.length - 1;
45646 const isLastNodeInMultiNodeList = isLastNode && !isFirstNode;
45647 const isWhitespace = isWhitespaceNode$1(childNode);
45649 if (isWhitespace && isLastNodeInMultiNodeList) {
45650 return print(childPath, options, print);
45651 } else if (isFirstNode) {
45652 return concat$a([softline$4, print(childPath, options, print)]);
45655 return print(childPath, options, print);
45659 * Prints a string literal with the correct surrounding quotes based on
45660 * `options.singleQuote` and the number of escaped quotes contained in
45661 * the string literal. This function is the glimmer equivalent of `printString`
45662 * in `common/util`, but has differences because of the way escaped characters
45663 * are treated in hbs string literals.
45664 * @param {string} stringLiteral - the string literal value
45665 * @param {object} options - the prettier options object
45669 function printStringLiteral(stringLiteral, options) {
45678 const preferred = options.singleQuote ? single : double;
45679 const alternate = preferred === single ? double : single;
45680 let shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for
45681 // enclosing the string, we might want to enclose with the alternate quote
45682 // instead, to minimize the number of escaped quotes.
45684 if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) {
45685 const numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length;
45686 const numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length;
45687 shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes;
45690 const enclosingQuote = shouldUseAlternateQuote ? alternate : preferred;
45691 const escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, `\\${enclosingQuote.quote}`);
45692 return concat$a([enclosingQuote.quote, escapedStringLiteral, enclosingQuote.quote]);
45695 function printPath(path, print) {
45696 return path.call(print, "path");
45699 function printParams(path, print) {
45700 const node = path.getValue();
45703 if (node.params.length > 0) {
45704 parts = parts.concat(path.map(print, "params"));
45707 if (node.hash && node.hash.pairs.length > 0) {
45708 parts.push(path.call(print, "hash"));
45714 function printPathParams(path, print) {
45715 const printedPath = printPath(path, print);
45716 const printedParams = printParams(path, print);
45717 const parts = [printedPath, ...printedParams];
45718 return indent$6(group$a(join$7(line$6, parts)));
45721 function printBlockParams(path) {
45722 const block = path.getValue();
45724 if (!block.program || !block.program.blockParams.length) {
45728 return concat$a([" as |", block.program.blockParams.join(" "), "|"]);
45731 function printOpenBlock(path, print, {
45732 open: isOpenStrip = false,
45733 close: isCloseStrip = false
45735 return group$a(concat$a([isOpenStrip ? "{{~#" : "{{#", printPathParams(path, print), printBlockParams(path), softline$4, isCloseStrip ? "~}}" : "}}"]));
45738 function printCloseBlock(path, print, {
45739 open: isOpenStrip = false,
45740 close: isCloseStrip = false
45742 return concat$a([isOpenStrip ? "{{~/" : "{{/", path.call(print, "path"), isCloseStrip ? "~}}" : "}}"]);
45745 function countNewLines(string) {
45746 /* istanbul ignore next */
45747 string = typeof string === "string" ? string : "";
45748 return string.split("\n").length - 1;
45751 function countLeadingNewLines(string) {
45752 /* istanbul ignore next */
45753 string = typeof string === "string" ? string : "";
45754 const newLines = (string.match(/^([^\S\r\n]*[\r\n])+/g) || [])[0] || "";
45755 return countNewLines(newLines);
45758 function countTrailingNewLines(string) {
45759 /* istanbul ignore next */
45760 string = typeof string === "string" ? string : "";
45761 const newLines = (string.match(/([\r\n][^\S\r\n]*)+$/g) || [])[0] || "";
45762 return countNewLines(newLines);
45765 function generateHardlines(number = 0, max = 0) {
45766 return new Array(Math.min(number, max)).fill(hardline$8);
45768 /* istanbul ignore next
45769 https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/compiler/lib/location.ts#L5-L29
45773 function locationToOffset(source, line, column) {
45775 let seenChars = 0; // eslint-disable-next-line no-constant-condition
45778 if (seenChars === source.length) {
45782 let nextLine = source.indexOf("\n", seenChars);
45784 if (nextLine === -1) {
45785 nextLine = source.length;
45788 if (seenLines === line) {
45789 if (seenChars + column > nextLine) {
45793 return seenChars + column;
45794 } else if (nextLine === -1) {
45799 seenChars = nextLine + 1;
45803 var printerGlimmer = {
45805 massageAstNode: clean$3
45808 var name$d = "Handlebars";
45809 var type$b = "markup";
45810 var group$b = "HTML";
45815 var extensions$b = [
45819 var tmScope$b = "text.html.handlebars";
45820 var aceMode$b = "handlebars";
45821 var languageId$b = 155;
45826 aliases: aliases$3,
45827 extensions: extensions$b,
45828 tmScope: tmScope$b,
45829 aceMode: aceMode$b,
45830 languageId: languageId$b
45833 var Handlebars$1 = /*#__PURE__*/Object.freeze({
45838 aliases: aliases$3,
45839 extensions: extensions$b,
45840 tmScope: tmScope$b,
45841 aceMode: aceMode$b,
45842 languageId: languageId$b,
45843 'default': Handlebars
45846 var require$$0$3 = getCjsExportFromNamespace(Handlebars$1);
45848 const languages$2 = [createLanguage(require$$0$3, () => ({
45851 parsers: ["glimmer"],
45852 vscodeLanguageIds: ["handlebars"]
45854 const printers$2 = {
45855 glimmer: printerGlimmer
45857 var languageHandlebars = {
45858 languages: languages$2,
45859 printers: printers$2
45862 function hasPragma$2(text) {
45863 return /^\s*#[^\n\S]*@(format|prettier)\s*(\n|$)/.test(text);
45866 function insertPragma$4(text) {
45867 return "# @format\n\n" + text;
45871 hasPragma: hasPragma$2,
45872 insertPragma: insertPragma$4
45878 hardline: hardline$9,
45880 softline: softline$5,
45884 } = document.builders;
45886 hasIgnoreComment: hasIgnoreComment$4
45889 isNextLineEmpty: isNextLineEmpty$4
45892 insertPragma: insertPragma$5
45895 function genericPrint$3(path, options, print) {
45896 const n = path.getValue();
45902 if (typeof n === "string") {
45910 path.map((pathChild, index) => {
45911 parts.push(concat$b([pathChild.call(print)]));
45913 if (index !== n.definitions.length - 1) {
45914 parts.push(hardline$9);
45916 if (isNextLineEmpty$4(options.originalText, pathChild.getValue(), options.locEnd)) {
45917 parts.push(hardline$9);
45921 return concat$b([concat$b(parts), hardline$9]);
45924 case "OperationDefinition":
45926 const hasOperation = options.originalText[options.locStart(n)] !== "{";
45927 const hasName = !!n.name;
45928 return concat$b([hasOperation ? n.operation : "", hasOperation && hasName ? concat$b([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.map(print, "variableDefinitions"))])), softline$5, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]);
45931 case "FragmentDefinition":
45933 return concat$b(["fragment ", path.call(print, "name"), n.variableDefinitions && n.variableDefinitions.length ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.map(print, "variableDefinitions"))])), softline$5, ")"])) : "", " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
45936 case "SelectionSet":
45938 return concat$b(["{", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(selectionsPath => printSequence(selectionsPath, options, print), "selections"))])), hardline$9, "}"]);
45943 return group$c(concat$b([n.alias ? concat$b([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$5, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")]));
45951 case "StringValue":
45954 return concat$b(['"""', hardline$9, join$8(hardline$9, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$9, '"""']);
45957 return concat$b(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']);
45967 case "BooleanValue":
45969 return n.value ? "true" : "false";
45979 return concat$b(["$", path.call(print, "name")]);
45984 return group$c(concat$b(["[", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.map(print, "values"))])), softline$5, "]"]));
45987 case "ObjectValue":
45989 return group$c(concat$b(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.map(print, "fields"))])), softline$5, ifBreak$4("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"]));
45992 case "ObjectField":
45995 return concat$b([path.call(print, "name"), ": ", path.call(print, "value")]);
46000 return concat$b(["@", path.call(print, "name"), n.arguments.length > 0 ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$5, ")"])) : ""]);
46005 return path.call(print, "name");
46008 case "VariableDefinition":
46010 return concat$b([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$b([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
46013 case "TypeExtensionDefinition":
46015 return concat$b(["extend ", path.call(print, "definition")]);
46018 case "ObjectTypeExtension":
46019 case "ObjectTypeDefinition":
46021 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$b([" implements ", concat$b(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$b([" {", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$9, "}"]) : ""]);
46024 case "FieldDefinition":
46026 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", path.call(print, "name"), n.arguments.length > 0 ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$5, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]);
46029 case "DirectiveDefinition":
46031 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$5, ")"])) : "", n.repeatable ? " repeatable" : "", concat$b([" on ", join$8(" | ", path.map(print, "locations"))])]);
46034 case "EnumTypeExtension":
46035 case "EnumTypeDefinition":
46037 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$b([" {", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(valuesPath => printSequence(valuesPath, options, print), "values"))])), hardline$9, "}"]) : ""]);
46040 case "EnumValueDefinition":
46042 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", path.call(print, "name"), printDirectives(path, print, n)]);
46045 case "InputValueDefinition":
46047 return concat$b([path.call(print, "description"), n.description ? n.description.block ? hardline$9 : line$7 : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$b([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
46050 case "InputObjectTypeExtension":
46051 case "InputObjectTypeDefinition":
46053 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$b([" {", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$9, "}"]) : ""]);
46056 case "SchemaDefinition":
46058 return concat$b(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(opsPath => printSequence(opsPath, options, print), "operationTypes"))])) : "", hardline$9, "}"]);
46061 case "OperationTypeDefinition":
46063 return concat$b([path.call(print, "operation"), ": ", path.call(print, "type")]);
46066 case "InterfaceTypeExtension":
46067 case "InterfaceTypeDefinition":
46069 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$b([" {", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$9, "}"]) : ""]);
46072 case "FragmentSpread":
46074 return concat$b(["...", path.call(print, "name"), printDirectives(path, print, n)]);
46077 case "InlineFragment":
46079 return concat$b(["...", n.typeCondition ? concat$b([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
46082 case "UnionTypeExtension":
46083 case "UnionTypeDefinition":
46085 return group$c(concat$b([path.call(print, "description"), n.description ? hardline$9 : "", group$c(concat$b([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$b([" =", ifBreak$4("", " "), indent$7(concat$b([ifBreak$4(concat$b([line$7, " "])), join$8(concat$b([line$7, "| "]), path.map(print, "types"))]))]) : ""]))]));
46088 case "ScalarTypeExtension":
46089 case "ScalarTypeDefinition":
46091 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]);
46094 case "NonNullType":
46096 return concat$b([path.call(print, "type"), "!"]);
46101 return concat$b(["[", path.call(print, "type"), "]"]);
46105 /* istanbul ignore next */
46106 throw new Error("unknown graphql type: " + JSON.stringify(n.kind));
46110 function printDirectives(path, print, n) {
46111 if (n.directives.length === 0) {
46115 return concat$b([" ", group$c(indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", " "), softline$5]), path.map(print, "directives"))])))]);
46118 function printSequence(sequencePath, options, print) {
46119 const count = sequencePath.getValue().length;
46120 return sequencePath.map((path, i) => {
46121 const printed = print(path);
46123 if (isNextLineEmpty$4(options.originalText, path.getValue(), options.locEnd) && i < count - 1) {
46124 return concat$b([printed, hardline$9]);
46131 function canAttachComment$1(node) {
46132 return node.kind && node.kind !== "Comment";
46135 function printComment$2(commentPath) {
46136 const comment = commentPath.getValue();
46138 if (comment.kind === "Comment") {
46139 return "#" + comment.value.trimEnd();
46142 throw new Error("Not a comment: " + JSON.stringify(comment));
46145 function determineInterfaceSeparatorBetween(first, second, options) {
46146 const textBetween = options.originalText.slice(first.loc.end, second.loc.start).replace(/#.*/g, "").trim();
46147 return textBetween === "," ? ", " : " & ";
46150 function printInterfaces(path, options, print) {
46151 const node = path.getNode();
46156 const printed = path.map(node => print(node), "interfaces");
46158 for (let index = 0; index < interfaces.length; index++) {
46159 const interfaceNode = interfaces[index];
46162 parts.push(determineInterfaceSeparatorBetween(interfaces[index - 1], interfaceNode, options));
46165 parts.push(printed[index]);
46171 function clean$4(node, newNode
46174 delete newNode.loc;
46175 delete newNode.comments;
46178 var printerGraphql = {
46179 print: genericPrint$3,
46180 massageAstNode: clean$4,
46181 hasPrettierIgnore: hasIgnoreComment$4,
46182 insertPragma: insertPragma$5,
46183 printComment: printComment$2,
46184 canAttachComment: canAttachComment$1
46188 bracketSpacing: commonOptions.bracketSpacing
46191 var name$e = "GraphQL";
46192 var type$c = "data";
46193 var extensions$c = [
46198 var tmScope$c = "source.graphql";
46199 var aceMode$c = "text";
46200 var languageId$c = 139;
46204 extensions: extensions$c,
46205 tmScope: tmScope$c,
46206 aceMode: aceMode$c,
46207 languageId: languageId$c
46210 var GraphQL$1 = /*#__PURE__*/Object.freeze({
46214 extensions: extensions$c,
46215 tmScope: tmScope$c,
46216 aceMode: aceMode$c,
46217 languageId: languageId$c,
46221 var require$$0$4 = getCjsExportFromNamespace(GraphQL$1);
46223 const languages$3 = [createLanguage(require$$0$4, () => ({
46225 parsers: ["graphql"],
46226 vscodeLanguageIds: ["graphql"]
46228 const printers$3 = {
46229 graphql: printerGraphql
46231 var languageGraphql = {
46232 languages: languages$3,
46233 options: options$4,
46234 printers: printers$3
46238 "cjkPattern": "[\\u02ea-\\u02eb\\u1100-\\u11ff\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u3000-\\u303f\\u3041-\\u3096\\u3099-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u3191\\u3196-\\u31ba\\u31c0-\\u31e3\\u31f0-\\u321e\\u322a-\\u3247\\u3260-\\u327e\\u328a-\\u32b0\\u32c0-\\u32cb\\u32d0-\\u3370\\u337b-\\u337f\\u33e0-\\u33fe\\u3400-\\u4db5\\u4e00-\\u9fef\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufe10-\\ufe1f\\ufe30-\\ufe6f\\uff00-\\uffef]|[\\ud840-\\ud868\\ud86a-\\ud86c\\ud86f-\\ud872\\ud874-\\ud879][\\udc00-\\udfff]|\\ud82c[\\udc00-\\udd1e\\udd50-\\udd52\\udd64-\\udd67]|\\ud83c[\\ude00\\ude50-\\ude51]|\\ud869[\\udc00-\\uded6\\udf00-\\udfff]|\\ud86d[\\udc00-\\udf34\\udf40-\\udfff]|\\ud86e[\\udc00-\\udc1d\\udc20-\\udfff]|\\ud873[\\udc00-\\udea1\\udeb0-\\udfff]|\\ud87a[\\udc00-\\udfe0]|\\ud87e[\\udc00-\\ude1d]",
46239 "kPattern": "[\\u1100-\\u11ff\\u3001-\\u3003\\u3008-\\u3011\\u3013-\\u301f\\u302e-\\u3030\\u3037\\u30fb\\u3131-\\u318e\\u3200-\\u321e\\u3260-\\u327e\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\ufe45-\\ufe46\\uff61-\\uff65\\uffa0-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc]",
46240 "punctuationPattern": "[\\u0021-\\u002f\\u003a-\\u0040\\u005b-\\u0060\\u007b-\\u007e\\u00a1\\u00a7\\u00ab\\u00b6-\\u00b7\\u00bb\\u00bf\\u037e\\u0387\\u055a-\\u055f\\u0589-\\u058a\\u05be\\u05c0\\u05c3\\u05c6\\u05f3-\\u05f4\\u0609-\\u060a\\u060c-\\u060d\\u061b\\u061e-\\u061f\\u066a-\\u066d\\u06d4\\u0700-\\u070d\\u07f7-\\u07f9\\u0830-\\u083e\\u085e\\u0964-\\u0965\\u0970\\u09fd\\u0a76\\u0af0\\u0c77\\u0c84\\u0df4\\u0e4f\\u0e5a-\\u0e5b\\u0f04-\\u0f12\\u0f14\\u0f3a-\\u0f3d\\u0f85\\u0fd0-\\u0fd4\\u0fd9-\\u0fda\\u104a-\\u104f\\u10fb\\u1360-\\u1368\\u1400\\u166e\\u169b-\\u169c\\u16eb-\\u16ed\\u1735-\\u1736\\u17d4-\\u17d6\\u17d8-\\u17da\\u1800-\\u180a\\u1944-\\u1945\\u1a1e-\\u1a1f\\u1aa0-\\u1aa6\\u1aa8-\\u1aad\\u1b5a-\\u1b60\\u1bfc-\\u1bff\\u1c3b-\\u1c3f\\u1c7e-\\u1c7f\\u1cc0-\\u1cc7\\u1cd3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205e\\u207d-\\u207e\\u208d-\\u208e\\u2308-\\u230b\\u2329-\\u232a\\u2768-\\u2775\\u27c5-\\u27c6\\u27e6-\\u27ef\\u2983-\\u2998\\u29d8-\\u29db\\u29fc-\\u29fd\\u2cf9-\\u2cfc\\u2cfe-\\u2cff\\u2d70\\u2e00-\\u2e2e\\u2e30-\\u2e4f\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301f\\u3030\\u303d\\u30a0\\u30fb\\ua4fe-\\ua4ff\\ua60d-\\ua60f\\ua673\\ua67e\\ua6f2-\\ua6f7\\ua874-\\ua877\\ua8ce-\\ua8cf\\ua8f8-\\ua8fa\\ua8fc\\ua92e-\\ua92f\\ua95f\\ua9c1-\\ua9cd\\ua9de-\\ua9df\\uaa5c-\\uaa5f\\uaade-\\uaadf\\uaaf0-\\uaaf1\\uabeb\\ufd3e-\\ufd3f\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe61\\ufe63\\ufe68\\ufe6a-\\ufe6b\\uff01-\\uff03\\uff05-\\uff0a\\uff0c-\\uff0f\\uff1a-\\uff1b\\uff1f-\\uff20\\uff3b-\\uff3d\\uff3f\\uff5b\\uff5d\\uff5f-\\uff65]|\\ud800[\\udd00-\\udd02\\udf9f\\udfd0]|\\ud801[\\udd6f]|\\ud802[\\udc57\\udd1f\\udd3f\\ude50-\\ude58\\ude7f\\udef0-\\udef6\\udf39-\\udf3f\\udf99-\\udf9c]|\\ud803[\\udf55-\\udf59]|\\ud804[\\udc47-\\udc4d\\udcbb-\\udcbc\\udcbe-\\udcc1\\udd40-\\udd43\\udd74-\\udd75\\uddc5-\\uddc8\\uddcd\\udddb\\udddd-\\udddf\\ude38-\\ude3d\\udea9]|\\ud805[\\udc4b-\\udc4f\\udc5b\\udc5d\\udcc6\\uddc1-\\uddd7\\ude41-\\ude43\\ude60-\\ude6c\\udf3c-\\udf3e]|\\ud806[\\udc3b\\udde2\\ude3f-\\ude46\\ude9a-\\ude9c\\ude9e-\\udea2]|\\ud807[\\udc41-\\udc45\\udc70-\\udc71\\udef7-\\udef8\\udfff]|\\ud809[\\udc70-\\udc74]|\\ud81a[\\ude6e-\\ude6f\\udef5\\udf37-\\udf3b\\udf44]|\\ud81b[\\ude97-\\ude9a\\udfe2]|\\ud82f[\\udc9f]|\\ud836[\\ude87-\\ude8b]|\\ud83a[\\udd5e-\\udd5f]"
46251 const INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"];
46252 const INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]);
46253 const kRegex = new RegExp(kPattern);
46254 const punctuationRegex = new RegExp(punctuationPattern);
46256 * split text into whitespaces and words
46257 * @param {string} text
46258 * @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>}
46261 function splitText(text, options) {
46262 const KIND_NON_CJK = "non-cjk";
46263 const KIND_CJ_LETTER = "cj-letter";
46264 const KIND_K_LETTER = "k-letter";
46265 const KIND_CJK_PUNCTUATION = "cjk-punctuation";
46267 (options.proseWrap === "preserve" ? text : text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")).split(/([ \t\n]+)/).forEach((token, index, tokens) => {
46269 if (index % 2 === 1) {
46271 type: "whitespace",
46272 value: /\n/.test(token) ? "\n" : " "
46275 } // word separated by whitespace
46278 if ((index === 0 || index === tokens.length - 1) && token === "") {
46282 token.split(new RegExp(`(${cjkPattern})`)).forEach((innerToken, innerIndex, innerTokens) => {
46283 if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") {
46288 if (innerIndex % 2 === 0) {
46289 if (innerToken !== "") {
46293 kind: KIND_NON_CJK,
46294 hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
46295 hasTrailingPunctuation: punctuationRegex.test(getLast$4(innerToken))
46303 appendNode(punctuationRegex.test(innerToken) ? {
46306 kind: KIND_CJK_PUNCTUATION,
46307 hasLeadingPunctuation: true,
46308 hasTrailingPunctuation: true
46312 kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER,
46313 hasLeadingPunctuation: false,
46314 hasTrailingPunctuation: false
46320 function appendNode(node) {
46321 const lastNode = getLast$4(nodes);
46323 if (lastNode && lastNode.type === "word") {
46324 if (lastNode.kind === KIND_NON_CJK && node.kind === KIND_CJ_LETTER && !lastNode.hasTrailingPunctuation || lastNode.kind === KIND_CJ_LETTER && node.kind === KIND_NON_CJK && !node.hasLeadingPunctuation) {
46326 type: "whitespace",
46329 } else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace
46330 ![lastNode.value, node.value].some(value => /\u3000/.test(value))) {
46332 type: "whitespace",
46340 function isBetween(kind1, kind2) {
46341 return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1;
46346 function getOrderedListItemInfo(orderListItem, originalText) {
46347 const [, numberText, marker, leadingSpaces] = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/);
46355 function hasGitDiffFriendlyOrderedList(node, options) {
46356 if (!node.ordered) {
46360 if (node.children.length < 2) {
46364 const firstNumber = Number(getOrderedListItemInfo(node.children[0], options.originalText).numberText);
46365 const secondNumber = Number(getOrderedListItemInfo(node.children[1], options.originalText).numberText);
46367 if (firstNumber === 0 && node.children.length > 2) {
46368 const thirdNumber = Number(getOrderedListItemInfo(node.children[2], options.originalText).numberText);
46369 return secondNumber === 1 && thirdNumber === 1;
46372 return secondNumber === 1;
46373 } // workaround for https://github.com/remarkjs/remark/issues/351
46374 // leading and trailing newlines are stripped by remark
46377 function getFencedCodeBlockValue(node, originalText) {
46378 const text = originalText.slice(node.position.start.offset, node.position.end.offset);
46379 const leadingSpaceCount = text.match(/^\s*/)[0].length;
46380 const replaceRegex = new RegExp(`^\\s{0,${leadingSpaceCount}}`);
46381 const lineContents = text.split("\n");
46382 const markerStyle = text[leadingSpaceCount]; // ` or ~
46384 const marker = text.slice(leadingSpaceCount).match(new RegExp(`^[${markerStyle}]+`))[0]; // https://spec.commonmark.org/0.28/#example-104: Closing fences may be indented by 0-3 spaces
46385 // https://spec.commonmark.org/0.28/#example-93: The closing code fence must be at least as long as the opening fence
46387 const hasEndMarker = new RegExp(`^\\s{0,3}${marker}`).test(lineContents[lineContents.length - 1].slice(getIndent(lineContents.length - 1)));
46388 return lineContents.slice(1, hasEndMarker ? -1 : undefined).map((x, i) => x.slice(getIndent(i + 1)).replace(replaceRegex, "")).join("\n");
46390 function getIndent(lineIndex) {
46391 return node.position.indent[lineIndex - 1] - 1;
46395 function mapAst(ast, handler) {
46396 return function preorder(node, index, parentStack) {
46397 parentStack = parentStack || [];
46398 const newNode = Object.assign({}, handler(node, index, parentStack));
46400 if (newNode.children) {
46401 newNode.children = newNode.children.map((child, index) => {
46402 return preorder(child, index, [newNode].concat(parentStack));
46407 }(ast, null, null);
46413 punctuationPattern,
46414 getFencedCodeBlockValue,
46415 getOrderedListItemInfo,
46416 hasGitDiffFriendlyOrderedList,
46418 INLINE_NODE_WRAPPER_TYPES
46423 hardline: hardline$a,
46424 literalline: literalline$4,
46426 markAsRoot: markAsRoot$2
46433 getFencedCodeBlockValue: getFencedCodeBlockValue$1
46436 function embed$2(path, print, textToDoc, options) {
46437 const node = path.getValue();
46439 if (node.type === "code" && node.lang !== null) {
46440 // only look for the first string so as to support [markdown-preview-enhanced](https://shd101wyy.github.io/markdown-preview-enhanced/#/code-chunk)
46441 const langMatch = node.lang.match(/^[A-Za-z0-9_-]+/);
46442 const lang = langMatch ? langMatch[0] : "";
46443 const parser = getParserName(lang);
46446 const styleUnit = options.__inJsTemplate ? "~" : "`";
46447 const style = styleUnit.repeat(Math.max(3, util$1.getMaxContinuousCount(node.value, styleUnit) + 1));
46448 const doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), {
46451 return markAsRoot$2(concat$c([style, node.lang, hardline$a, replaceNewlinesWithLiterallines(doc), style]));
46455 if (node.type === "yaml") {
46456 return markAsRoot$2(concat$c(["---", hardline$a, node.value && node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
46458 })) : "", "---"]));
46462 switch (node.type) {
46463 case "importExport":
46464 return textToDoc(node.value, {
46469 return textToDoc(`<$>${node.value}</$>`, {
46470 parser: "__js_expression",
46477 function getParserName(lang) {
46478 const supportInfo = support.getSupportInfo({
46479 plugins: options.plugins
46481 const language = supportInfo.languages.find(language => language.name.toLowerCase() === lang || language.aliases && language.aliases.includes(lang) || language.extensions && language.extensions.find(ext => ext === `.${lang}`));
46484 return language.parsers[0];
46490 function replaceNewlinesWithLiterallines(doc) {
46491 return mapDoc$3(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$c(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$4)) : currentDoc);
46495 var embed_1$2 = embed$2;
46497 const pragmas = ["format", "prettier"];
46499 function startWithPragma(text) {
46500 const pragma = `@(${pragmas.join("|")})`;
46501 const regex = new RegExp([`<!--\\s*${pragma}\\s*-->`, `<!--.*\r?\n[\\s\\S]*(^|\n)[^\\S\n]*${pragma}[^\\S\n]*($|\n)[\\s\\S]*\n.*-->`].join("|"), "m");
46502 const matched = text.match(regex);
46503 return matched && matched.index === 0;
46508 hasPragma: text => startWithPragma(frontMatter(text).content.trimStart()),
46509 insertPragma: text => {
46510 const extracted = frontMatter(text);
46511 const pragma = `<!-- @${pragmas[0]} -->`;
46512 return extracted.frontMatter ? `${extracted.frontMatter.raw}\n\n${pragma}\n\n${extracted.content}` : `${pragma}\n\n${extracted.content}`;
46517 getOrderedListItemInfo: getOrderedListItemInfo$1,
46519 splitText: splitText$1
46520 } = utils$9; // 0x0 ~ 0x10ffff
46521 // eslint-disable-next-line no-control-regex
46523 const isSingleCharRegex = /^([\u0000-\uffff]|[\ud800-\udbff][\udc00-\udfff])$/;
46525 function preprocess$1(ast, options) {
46526 ast = restoreUnescapedCharacter(ast, options);
46527 ast = mergeContinuousTexts(ast);
46528 ast = transformInlineCode(ast);
46529 ast = transformIndentedCodeblockAndMarkItsParentList(ast, options);
46530 ast = markAlignedList(ast, options);
46531 ast = splitTextIntoSentences(ast, options);
46532 ast = transformImportExport(ast);
46533 ast = mergeContinuousImportExport(ast);
46537 function transformImportExport(ast) {
46538 return mapAst$1(ast, node => {
46539 if (node.type !== "import" && node.type !== "export") {
46543 return Object.assign({}, node, {
46544 type: "importExport"
46549 function transformInlineCode(ast) {
46550 return mapAst$1(ast, node => {
46551 if (node.type !== "inlineCode") {
46555 return Object.assign({}, node, {
46556 value: node.value.replace(/\s+/g, " ")
46561 function restoreUnescapedCharacter(ast, options) {
46562 return mapAst$1(ast, node => {
46563 return node.type !== "text" ? node : Object.assign({}, node, {
46564 value: node.value !== "*" && node.value !== "_" && node.value !== "$" && // handle these cases in printer
46565 isSingleCharRegex.test(node.value) && node.position.end.offset - node.position.start.offset !== node.value.length ? options.originalText.slice(node.position.start.offset, node.position.end.offset) : node.value
46570 function mergeContinuousImportExport(ast) {
46571 return mergeChildren(ast, (prevNode, node) => prevNode.type === "importExport" && node.type === "importExport", (prevNode, node) => ({
46572 type: "importExport",
46573 value: prevNode.value + "\n\n" + node.value,
46575 start: prevNode.position.start,
46576 end: node.position.end
46581 function mergeChildren(ast, shouldMerge, mergeNode) {
46582 return mapAst$1(ast, node => {
46583 if (!node.children) {
46587 const children = node.children.reduce((current, child) => {
46588 const lastChild = current[current.length - 1];
46590 if (lastChild && shouldMerge(lastChild, child)) {
46591 current.splice(-1, 1, mergeNode(lastChild, child));
46593 current.push(child);
46598 return Object.assign({}, node, {
46604 function mergeContinuousTexts(ast) {
46605 return mergeChildren(ast, (prevNode, node) => prevNode.type === "text" && node.type === "text", (prevNode, node) => ({
46607 value: prevNode.value + node.value,
46609 start: prevNode.position.start,
46610 end: node.position.end
46615 function splitTextIntoSentences(ast, options) {
46616 return mapAst$1(ast, (node, index, [parentNode]) => {
46617 if (node.type !== "text") {
46625 if (parentNode.type === "paragraph") {
46627 value = value.trimStart();
46630 if (index === parentNode.children.length - 1) {
46631 value = value.trimEnd();
46637 position: node.position,
46638 children: splitText$1(value, options)
46643 function transformIndentedCodeblockAndMarkItsParentList(ast, options) {
46644 return mapAst$1(ast, (node, index, parentStack) => {
46645 if (node.type === "code") {
46646 // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it
46647 const isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset));
46648 node.isIndented = isIndented;
46651 for (let i = 0; i < parentStack.length; i++) {
46652 const parent = parentStack[i]; // no need to check checked items
46654 if (parent.hasIndentedCodeblock) {
46658 if (parent.type === "list") {
46659 parent.hasIndentedCodeblock = true;
46669 function markAlignedList(ast, options) {
46670 return mapAst$1(ast, (node, index, parentStack) => {
46671 if (node.type === "list" && node.children.length !== 0) {
46672 // if one of its parents is not aligned, it's not possible to be aligned in sub-lists
46673 for (let i = 0; i < parentStack.length; i++) {
46674 const parent = parentStack[i];
46676 if (parent.type === "list" && !parent.isAligned) {
46677 node.isAligned = false;
46682 node.isAligned = isAligned(node);
46688 function getListItemStart(listItem) {
46689 return listItem.children.length === 0 ? -1 : listItem.children[0].position.start.column - 1;
46692 function isAligned(list) {
46693 if (!list.ordered) {
46701 const [firstItem, secondItem] = list.children;
46702 const firstInfo = getOrderedListItemInfo$1(firstItem, options.originalText);
46704 if (firstInfo.leadingSpaces.length > 1) {
46714 const firstStart = getListItemStart(firstItem);
46716 if (firstStart === -1) {
46726 if (list.children.length === 1) {
46736 return firstStart % options.tabWidth === 0;
46739 const secondStart = getListItemStart(secondItem);
46741 if (firstStart !== secondStart) {
46752 if (firstStart % options.tabWidth === 0) {
46772 const secondInfo = getOrderedListItemInfo$1(secondItem, options.originalText);
46773 return secondInfo.leadingSpaces.length > 1;
46777 var preprocess_1$1 = preprocess$1;
46781 breakParent: breakParent$3,
46785 literalline: literalline$5,
46786 markAsRoot: markAsRoot$3,
46787 hardline: hardline$b,
46788 softline: softline$6,
46789 ifBreak: ifBreak$5,
46799 printDocToString: printDocToString$3
46803 getFencedCodeBlockValue: getFencedCodeBlockValue$2,
46804 hasGitDiffFriendlyOrderedList: hasGitDiffFriendlyOrderedList$1,
46805 splitText: splitText$2,
46806 punctuationPattern: punctuationPattern$1,
46807 INLINE_NODE_TYPES: INLINE_NODE_TYPES$1,
46808 INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES$1
46811 replaceEndOfLineWith: replaceEndOfLineWith$1
46813 const TRAILING_HARDLINE_NODES = ["importExport"];
46814 const SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"];
46815 const SIBLING_NODE_TYPES = ["listItem", "definition", "footnoteDefinition"];
46817 function genericPrint$4(path, options, print) {
46818 const node = path.getValue();
46820 if (shouldRemainTheSameContent(path)) {
46821 return concat$d(splitText$2(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(node => node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options)));
46824 switch (node.type) {
46826 if (node.children.length === 0) {
46830 return concat$d([normalizeDoc(printRoot(path, options, print)), !TRAILING_HARDLINE_NODES.includes(getLastDescendantNode(node).type) ? hardline$b : ""]);
46833 return printChildren$1(path, options, print, {
46834 postprocessor: fill$5
46838 return printChildren$1(path, options, print);
46841 return node.value.replace(/[*$]/g, "\\$&") // escape all `*` and `$` (math)
46842 .replace(new RegExp([`(^|${punctuationPattern$1})(_+)`, `(_+)(${punctuationPattern$1}|$)`].join("|"), "g"), (_, text1, underscore1, underscore2, text2) => (underscore1 ? `${text1}${underscore1}` : `${underscore2}${text2}`).replace(/_/g, "\\_"));
46843 // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
46847 const parentNode = path.getParentNode();
46848 const index = parentNode.children.indexOf(node);
46849 const nextNode = parentNode.children[index + 1];
46850 const proseWrap = // leading char that may cause different syntax
46851 nextNode && /^>|^([-+*]|#{1,6}|[0-9]+[.)])$/.test(nextNode.value) ? "never" : options.proseWrap;
46852 return printLine(path, node.value, {
46859 const parentNode = path.getParentNode();
46860 const index = parentNode.children.indexOf(node);
46861 const prevNode = parentNode.children[index - 1];
46862 const nextNode = parentNode.children[index + 1];
46863 const hasPrevOrNextWord = // `1*2*3` is considered emphasis but `1_2_3` is not
46864 prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && util$1.getLast(prevNode.children).type === "word" && !util$1.getLast(prevNode.children).hasTrailingPunctuation || nextNode && nextNode.type === "sentence" && nextNode.children.length > 0 && nextNode.children[0].type === "word" && !nextNode.children[0].hasLeadingPunctuation;
46865 const style = hasPrevOrNextWord || getAncestorNode$2(path, "emphasis") ? "*" : "_";
46866 return concat$d([style, printChildren$1(path, options, print), style]);
46870 return concat$d(["**", printChildren$1(path, options, print), "**"]);
46873 return concat$d(["~~", printChildren$1(path, options, print), "~~"]);
46877 const backtickCount = util$1.getMinNotPresentContinuousCount(node.value, "`");
46878 const style = "`".repeat(backtickCount || 1);
46879 const gap = backtickCount ? " " : "";
46880 return concat$d([style, gap, node.value, gap, style]);
46884 switch (options.originalText[node.position.start.offset]) {
46887 const mailto = "mailto:";
46888 const url = // <hello@example.com> is parsed as { url: "mailto:hello@example.com" }
46889 node.url.startsWith(mailto) && options.originalText.slice(node.position.start.offset + 1, node.position.start.offset + 1 + mailto.length) !== mailto ? node.url.slice(mailto.length) : node.url;
46890 return concat$d(["<", url, ">"]);
46894 return concat$d(["[", printChildren$1(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
46897 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
46901 return concat$d(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
46904 return concat$d(["> ", align$2("> ", printChildren$1(path, options, print))]);
46907 return concat$d(["#".repeat(node.depth) + " ", printChildren$1(path, options, print)]);
46911 if (node.isIndented) {
46912 // indented code block
46913 const alignment = " ".repeat(4);
46914 return align$2(alignment, concat$d([alignment, concat$d(replaceEndOfLineWith$1(node.value, hardline$b))]));
46915 } // fenced code block
46918 const styleUnit = options.__inJsTemplate ? "~" : "`";
46919 const style = styleUnit.repeat(Math.max(3, util$1.getMaxContinuousCount(node.value, styleUnit) + 1));
46920 return concat$d([style, node.lang || "", hardline$b, concat$d(replaceEndOfLineWith$1(getFencedCodeBlockValue$2(node, options.originalText), hardline$b)), hardline$b, style]);
46925 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
46929 const parentNode = path.getParentNode();
46930 const value = parentNode.type === "root" && util$1.getLast(parentNode.children) === node ? node.value.trimEnd() : node.value;
46931 const isHtmlComment = /^<!--[\s\S]*-->$/.test(value);
46932 return concat$d(replaceEndOfLineWith$1(value, isHtmlComment ? hardline$b : markAsRoot$3(literalline$5)));
46937 const nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode());
46938 const isGitDiffFriendlyOrderedList = hasGitDiffFriendlyOrderedList$1(node, options);
46939 return printChildren$1(path, options, print, {
46940 processor: (childPath, index) => {
46941 const prefix = getPrefix();
46942 const childNode = childPath.getValue();
46944 if (childNode.children.length === 2 && childNode.children[1].type === "html" && childNode.children[0].position.start.column !== childNode.children[1].position.start.column) {
46945 return concat$d([prefix, printListItem(childPath, options, print, prefix)]);
46948 return concat$d([prefix, align$2(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]);
46950 function getPrefix() {
46951 const rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* ";
46952 return node.isAligned ||
46953 /* workaround for https://github.com/remarkjs/remark/issues/315 */
46954 node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix;
46960 case "thematicBreak":
46962 const counter = getAncestorCounter$1(path, "list");
46964 if (counter === -1) {
46968 const nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1));
46969 return nthSiblingIndex % 2 === 0 ? "***" : "---";
46972 case "linkReference":
46973 return concat$d(["[", printChildren$1(path, options, print), "]", node.referenceType === "full" ? concat$d(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]);
46975 case "imageReference":
46976 switch (node.referenceType) {
46978 return concat$d(["![", node.alt || "", "][", node.identifier, "]"]);
46981 return concat$d(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]);
46986 const lineOrSpace = options.proseWrap === "always" ? line$8 : " ";
46987 return group$d(concat$d([concat$d(["[", node.identifier, "]:"]), indent$8(concat$d([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$d([lineOrSpace, printTitle(node.title, options, false)])]))]));
46991 return concat$d(["[^", printChildren$1(path, options, print), "]"]);
46993 case "footnoteReference":
46994 return concat$d(["[^", node.identifier, "]"]);
46996 case "footnoteDefinition":
46998 const nextNode = path.getParentNode().children[path.getName() + 1];
46999 const shouldInlineFootnote = node.children.length === 1 && node.children[0].type === "paragraph" && (options.proseWrap === "never" || options.proseWrap === "preserve" && node.children[0].position.start.line === node.children[0].position.end.line);
47000 return concat$d(["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$1(path, options, print) : group$d(concat$d([align$2(" ".repeat(options.tabWidth), printChildren$1(path, options, print, {
47001 processor: (childPath, index) => {
47002 return index === 0 ? group$d(concat$d([softline$6, childPath.call(print)])) : childPath.call(print);
47004 })), nextNode && nextNode.type === "footnoteDefinition" ? softline$6 : ""]))]);
47008 return printTable(path, options, print);
47011 return printChildren$1(path, options, print);
47014 return /\s/.test(options.originalText[node.position.start.offset]) ? concat$d([" ", markAsRoot$3(literalline$5)]) : concat$d(["\\", hardline$b]);
47017 return concat$d(replaceEndOfLineWith$1(node.value, hardline$b));
47020 case "importExport":
47023 // fallback to the original text if multiparser failed
47026 return concat$d(["$$", hardline$b, node.value ? concat$d([concat$d(replaceEndOfLineWith$1(node.value, hardline$b)), hardline$b]) : "", "$$"]);
47030 // remark-math trims content but we don't want to remove whitespaces
47031 // since it's very possible that it's recognized as math accidentally
47032 return options.originalText.slice(options.locStart(node), options.locEnd(node));
47035 case "tableRow": // handled in "table"
47037 case "listItem": // handled in "list"
47040 throw new Error(`Unknown markdown type ${JSON.stringify(node.type)}`);
47044 function printListItem(path, options, print, listPrefix) {
47045 const node = path.getValue();
47046 const prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
47047 return concat$d([prefix, printChildren$1(path, options, print, {
47048 processor: (childPath, index) => {
47049 if (index === 0 && childPath.getValue().type !== "list") {
47050 return align$2(" ".repeat(prefix.length), childPath.call(print));
47053 const alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
47055 return concat$d([alignment, align$2(alignment, childPath.call(print))]);
47060 function alignListPrefix(prefix, options) {
47061 const additionalSpaces = getAdditionalSpaces();
47062 return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block
47065 function getAdditionalSpaces() {
47066 const restSpaces = prefix.length % options.tabWidth;
47067 return restSpaces === 0 ? 0 : options.tabWidth - restSpaces;
47071 function getNthListSiblingIndex(node, parentNode) {
47072 return getNthSiblingIndex(node, parentNode, siblingNode => siblingNode.ordered === node.ordered);
47075 function getNthSiblingIndex(node, parentNode, condition) {
47076 condition = condition || (() => true);
47080 for (const childNode of parentNode.children) {
47081 if (childNode.type === node.type && condition(childNode)) {
47087 if (childNode === node) {
47093 function getAncestorCounter$1(path, typeOrTypes) {
47094 const types = [].concat(typeOrTypes);
47098 while (ancestorNode = path.getParentNode(++counter)) {
47099 if (types.includes(ancestorNode.type)) {
47107 function getAncestorNode$2(path, typeOrTypes) {
47108 const counter = getAncestorCounter$1(path, typeOrTypes);
47109 return counter === -1 ? null : path.getParentNode(counter);
47112 function printLine(path, value, options) {
47113 if (options.proseWrap === "preserve" && value === "\n") {
47117 const isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES);
47118 return value !== "" ? isBreakable ? line$8 : " " : isBreakable ? softline$6 : "";
47121 function printTable(path, options, print) {
47122 const hardlineWithoutBreakParent = hardline$b.parts[0];
47123 const node = path.getValue();
47124 const contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } }
47126 path.map(rowPath => {
47127 const rowContents = [];
47128 rowPath.map(cellPath => {
47129 rowContents.push(printDocToString$3(cellPath.call(print), options).formatted);
47131 contents.push(rowContents);
47132 }, "children"); // Get the width of each column
47134 const columnMaxWidths = contents.reduce((currentWidths, rowContents) => currentWidths.map((width, columnIndex) => Math.max(width, util$1.getStringWidth(rowContents[columnIndex]))), contents[0].map(() => 3) // minimum width = 3 (---, :--, :-:, --:)
47136 const alignedTable = join$9(hardlineWithoutBreakParent, [printRow(contents[0]), printSeparator(), join$9(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents)))]);
47138 if (options.proseWrap !== "never") {
47139 return concat$d([breakParent$3, alignedTable]);
47140 } // Only if the --prose-wrap never is set and it exceeds the print width.
47143 const compactTable = join$9(hardlineWithoutBreakParent, [printRow(contents[0],
47145 true), printSeparator(
47147 true), join$9(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents,
47150 return concat$d([breakParent$3, group$d(ifBreak$5(compactTable, alignedTable))]);
47152 function printSeparator(isCompact) {
47153 return concat$d(["| ", join$9(" | ", columnMaxWidths.map((width, index) => {
47154 const spaces = isCompact ? 3 : width;
47156 switch (node.align[index]) {
47158 return ":" + "-".repeat(spaces - 1);
47161 return "-".repeat(spaces - 1) + ":";
47164 return ":" + "-".repeat(spaces - 2) + ":";
47167 return "-".repeat(spaces);
47172 function printRow(rowContents, isCompact) {
47173 return concat$d(["| ", join$9(" | ", isCompact ? rowContents : rowContents.map((rowContent, columnIndex) => {
47174 switch (node.align[columnIndex]) {
47176 return alignRight(rowContent, columnMaxWidths[columnIndex]);
47179 return alignCenter(rowContent, columnMaxWidths[columnIndex]);
47182 return alignLeft(rowContent, columnMaxWidths[columnIndex]);
47187 function alignLeft(text, width) {
47188 const spaces = width - util$1.getStringWidth(text);
47189 return concat$d([text, " ".repeat(spaces)]);
47192 function alignRight(text, width) {
47193 const spaces = width - util$1.getStringWidth(text);
47194 return concat$d([" ".repeat(spaces), text]);
47197 function alignCenter(text, width) {
47198 const spaces = width - util$1.getStringWidth(text);
47199 const left = Math.floor(spaces / 2);
47200 const right = spaces - left;
47201 return concat$d([" ".repeat(left), text, " ".repeat(right)]);
47205 function printRoot(path, options, print) {
47206 /** @typedef {{ index: number, offset: number }} IgnorePosition */
47208 /** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */
47209 const ignoreRanges = [];
47210 /** @type {IgnorePosition | null} */
47212 let ignoreStart = null;
47215 } = path.getValue();
47216 children.forEach((childNode, index) => {
47217 switch (isPrettierIgnore(childNode)) {
47219 if (ignoreStart === null) {
47222 offset: childNode.position.end.offset
47229 if (ignoreStart !== null) {
47230 ignoreRanges.push({
47231 start: ignoreStart,
47234 offset: childNode.position.start.offset
47237 ignoreStart = null;
47243 return printChildren$1(path, options, print, {
47244 processor: (childPath, index) => {
47245 if (ignoreRanges.length !== 0) {
47246 const ignoreRange = ignoreRanges[0];
47248 if (index === ignoreRange.start.index) {
47249 return concat$d([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]);
47252 if (ignoreRange.start.index < index && index < ignoreRange.end.index) {
47256 if (index === ignoreRange.end.index) {
47257 ignoreRanges.shift();
47262 return childPath.call(print);
47267 function printChildren$1(path, options, print, events) {
47268 events = events || {};
47269 const postprocessor = events.postprocessor || concat$d;
47271 const processor = events.processor || (childPath => childPath.call(print));
47273 const node = path.getValue();
47276 path.map((childPath, index) => {
47277 const childNode = childPath.getValue();
47278 const result = processor(childPath, index);
47280 if (result !== false) {
47283 prevNode: lastChildNode,
47288 if (!shouldNotPrePrintHardline(childNode, data)) {
47289 parts.push(hardline$b);
47291 if (lastChildNode && TRAILING_HARDLINE_NODES.includes(lastChildNode.type)) {
47292 if (shouldPrePrintTripleHardline(childNode, data)) {
47293 parts.push(hardline$b);
47296 if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
47297 parts.push(hardline$b);
47300 if (shouldPrePrintTripleHardline(childNode, data)) {
47301 parts.push(hardline$b);
47306 parts.push(result);
47307 lastChildNode = childNode;
47310 return postprocessor(parts);
47313 function getLastDescendantNode(node) {
47314 let current = node;
47316 while (current.children && current.children.length !== 0) {
47317 current = current.children[current.children.length - 1];
47322 /** @return {false | 'next' | 'start' | 'end'} */
47325 function isPrettierIgnore(node) {
47326 if (node.type !== "html") {
47330 const match = node.value.match(/^<!--\s*prettier-ignore(?:-(start|end))?\s*-->$/);
47331 return match === null ? false : match[1] ? match[1] : "next";
47334 function shouldNotPrePrintHardline(node, data) {
47335 const isFirstNode = data.parts.length === 0;
47336 const isInlineNode = INLINE_NODE_TYPES$1.includes(node.type);
47337 const isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES$1.includes(data.parentNode.type);
47338 return isFirstNode || isInlineNode || isInlineHTML;
47341 function shouldPrePrintDoubleHardline(node, data) {
47342 const isSequence = (data.prevNode && data.prevNode.type) === node.type;
47343 const isSiblingNode = isSequence && SIBLING_NODE_TYPES.includes(node.type);
47344 const isInTightListItem = data.parentNode.type === "listItem" && !data.parentNode.loose;
47345 const isPrevNodeLooseListItem = data.prevNode && data.prevNode.type === "listItem" && data.prevNode.loose;
47346 const isPrevNodePrettierIgnore = isPrettierIgnore(data.prevNode) === "next";
47347 const isBlockHtmlWithoutBlankLineBetweenPrevHtml = node.type === "html" && data.prevNode && data.prevNode.type === "html" && data.prevNode.position.end.line + 1 === node.position.start.line;
47348 const isHtmlDirectAfterListItem = node.type === "html" && data.parentNode.type === "listItem" && data.prevNode && data.prevNode.type === "paragraph" && data.prevNode.position.end.line + 1 === node.position.start.line;
47349 return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml || isHtmlDirectAfterListItem);
47352 function shouldPrePrintTripleHardline(node, data) {
47353 const isPrevNodeList = data.prevNode && data.prevNode.type === "list";
47354 const isIndentedCode = node.type === "code" && node.isIndented;
47355 return isPrevNodeList && isIndentedCode;
47358 function shouldRemainTheSameContent(path) {
47359 const ancestorNode = getAncestorNode$2(path, ["linkReference", "imageReference"]);
47360 return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full");
47363 function normalizeDoc(doc) {
47364 return mapDoc$4(doc, currentDoc => {
47365 if (!currentDoc.parts) {
47369 if (currentDoc.type === "concat" && currentDoc.parts.length === 1) {
47370 return currentDoc.parts[0];
47373 const parts = currentDoc.parts.reduce((parts, part) => {
47374 if (part.type === "concat") {
47375 parts.push(...part.parts);
47376 } else if (part !== "") {
47382 return Object.assign({}, currentDoc, {
47383 parts: normalizeParts(parts)
47388 function printUrl(url, dangerousCharOrChars) {
47389 const dangerousChars = [" "].concat(dangerousCharOrChars || []);
47390 return new RegExp(dangerousChars.map(x => `\\${x}`).join("|")).test(url) ? `<${url}>` : url;
47393 function printTitle(title, options, printSpace) {
47394 if (printSpace == null) {
47403 return " " + printTitle(title, options, false);
47406 if (title.includes('"') && title.includes("'") && !title.includes(")")) {
47407 return `(${title})`; // avoid escaped quotes
47408 } // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split
47411 const singleCount = title.split("'").length - 1;
47412 const doubleCount = title.split('"').length - 1;
47413 const quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"';
47414 title = title.replace(new RegExp(`(${quote})`, "g"), "\\$1");
47415 return `${quote}${title}${quote}`;
47418 function normalizeParts(parts) {
47419 return parts.reduce((current, part) => {
47420 const lastPart = util$1.getLast(current);
47422 if (typeof lastPart === "string" && typeof part === "string") {
47423 current.splice(-1, 1, lastPart + part);
47425 current.push(part);
47432 function clamp(value, min, max) {
47433 return value < min ? min : value > max ? max : value;
47436 function clean$5(ast, newObj, parent) {
47437 delete newObj.position;
47438 delete newObj.raw; // front-matter
47441 if (ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") {
47442 delete newObj.value;
47445 if (ast.type === "list") {
47446 delete newObj.isAligned;
47447 } // texts can be splitted or merged
47450 if (ast.type === "text") {
47454 if (ast.type === "inlineCode") {
47455 newObj.value = ast.value.replace(/[ \t\n]+/g, " ");
47456 } // for insert pragma
47459 if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || (parent.children[0].type === "yaml" || parent.children[0].type === "toml") && parent.children[1] === ast) && ast.type === "html" && pragma$3.startWithPragma(ast.value)) {
47464 function hasPrettierIgnore$4(path) {
47465 const index = +path.getName();
47471 const prevNode = path.getParentNode().children[index - 1];
47472 return isPrettierIgnore(prevNode) === "next";
47475 var printerMarkdown = {
47476 preprocess: preprocess_1$1,
47477 print: genericPrint$4,
47479 massageAstNode: clean$5,
47480 hasPrettierIgnore: hasPrettierIgnore$4,
47481 insertPragma: pragma$3.insertPragma
47485 proseWrap: commonOptions.proseWrap,
47486 singleQuote: commonOptions.singleQuote
47489 var name$f = "Markdown";
47490 var type$d = "prose";
47494 var aceMode$d = "markdown";
47495 var codemirrorMode$a = "gfm";
47496 var codemirrorMimeType$a = "text/x-gfm";
47498 var extensions$d = [
47510 var filenames$3 = [
47513 var tmScope$d = "source.gfm";
47514 var languageId$d = 222;
47518 aliases: aliases$4,
47519 aceMode: aceMode$d,
47520 codemirrorMode: codemirrorMode$a,
47521 codemirrorMimeType: codemirrorMimeType$a,
47523 extensions: extensions$d,
47524 filenames: filenames$3,
47525 tmScope: tmScope$d,
47526 languageId: languageId$d
47529 var Markdown$1 = /*#__PURE__*/Object.freeze({
47533 aliases: aliases$4,
47534 aceMode: aceMode$d,
47535 codemirrorMode: codemirrorMode$a,
47536 codemirrorMimeType: codemirrorMimeType$a,
47538 extensions: extensions$d,
47539 filenames: filenames$3,
47540 tmScope: tmScope$d,
47541 languageId: languageId$d,
47542 'default': Markdown
47545 var require$$0$5 = getCjsExportFromNamespace(Markdown$1);
47547 const languages$4 = [createLanguage(require$$0$5, data => ({
47549 parsers: ["markdown"],
47550 vscodeLanguageIds: ["markdown"],
47551 filenames: data.filenames.concat(["README"]),
47552 extensions: data.extensions.filter(extension => extension !== ".mdx")
47553 })), createLanguage(require$$0$5, () => ({
47557 vscodeLanguageIds: ["mdx"],
47559 extensions: [".mdx"]
47561 const printers$4 = {
47562 mdast: printerMarkdown
47564 var languageMarkdown = {
47565 languages: languages$4,
47566 options: options$5,
47567 printers: printers$4
47570 var clean$6 = function (ast, newNode) {
47571 delete newNode.sourceSpan;
47572 delete newNode.startSourceSpan;
47573 delete newNode.endSourceSpan;
47574 delete newNode.nameSpan;
47575 delete newNode.valueSpan;
47577 if (ast.type === "text" || ast.type === "comment") {
47579 } // may be formatted by multiparser
47582 if (ast.type === "yaml" || ast.type === "toml") {
47586 if (ast.type === "attribute") {
47587 delete newNode.value;
47590 if (ast.type === "docType") {
47591 delete newNode.value;
47596 "CSS_DISPLAY_TAGS": {
47599 "basefont": "none",
47600 "datalist": "none",
47605 "noframes": "none",
47611 "template": "inline",
47616 "address": "block",
47617 "blockquote": "block",
47621 "figcaption": "block",
47627 "listing": "block",
47630 "plaintext": "block",
47633 "slot": "contents",
47636 "article": "block",
47646 "section": "block",
47655 "caption": "table-caption",
47656 "colgroup": "table-column-group",
47657 "col": "table-column",
47658 "thead": "table-header-group",
47659 "tbody": "table-row-group",
47660 "tfoot": "table-footer-group",
47662 "td": "table-cell",
47663 "th": "table-cell",
47664 "fieldset": "block",
47665 "button": "inline-block",
47666 "video": "inline-block",
47667 "audio": "inline-block"
47669 "CSS_DISPLAY_DEFAULT": "inline",
47670 "CSS_WHITE_SPACE_TAGS": {
47672 "plaintext": "pre",
47676 "table": "initial",
47677 "textarea": "pre-wrap"
47679 "CSS_WHITE_SPACE_DEFAULT": "normal"
47833 var htmlTagNames = /*#__PURE__*/Object.freeze({
48061 "allowpaymentrequest",
48443 basefont: basefont,
48445 blockquote: blockquote,
48452 colgroup: colgroup,
48462 fieldset: fieldset,
48466 frameset: frameset,
48491 optgroup: optgroup,
48497 progress: progress,
48507 textarea: textarea,
48518 var htmlElementAttributes = /*#__PURE__*/Object.freeze({
48526 basefont: basefont,
48528 blockquote: blockquote,
48535 colgroup: colgroup,
48545 fieldset: fieldset,
48549 frameset: frameset,
48574 optgroup: optgroup,
48580 progress: progress,
48590 textarea: textarea,
48602 var htmlTagNames$1 = getCjsExportFromNamespace(htmlTagNames);
48604 var htmlElementAttributes$1 = getCjsExportFromNamespace(htmlElementAttributes);
48608 CSS_DISPLAY_DEFAULT,
48609 CSS_WHITE_SPACE_TAGS,
48610 CSS_WHITE_SPACE_DEFAULT
48612 const HTML_TAGS = arrayToMap(htmlTagNames$1);
48613 const HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes$1, arrayToMap);
48615 function arrayToMap(array) {
48616 const map = Object.create(null);
48618 for (const value of array) {
48625 function mapObject(object, fn) {
48626 const newObject = Object.create(null);
48628 for (const key of Object.keys(object)) {
48629 newObject[key] = fn(object[key], key);
48635 function shouldPreserveContent(node, options) {
48636 if (!node.endSourceSpan) {
48640 if (node.type === "element" && node.fullName === "template" && node.attrMap.lang && node.attrMap.lang !== "html") {
48642 } // unterminated node in ie conditional comment
48643 // e.g. <!--[if lt IE 9]><html><![endif]-->
48646 if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) {
48648 } // incomplete html in ie conditional comment
48649 // e.g. <!--[if lt IE 9]></div><![endif]-->
48652 if (node.type === "ieConditionalComment" && !node.complete) {
48654 } // top-level elements (excluding <template>, <style> and <script>) in Vue SFC are considered custom block
48655 // custom blocks can be written in other languages so we should preserve them to not break the code
48658 if (options.parser === "vue" && node.type === "element" && node.parent.type === "root" && !["template", "style", "script", // vue parser can be used for vue dom template as well, so we should still format top-level <html>
48659 "html"].includes(node.fullName)) {
48661 } // TODO: handle non-text children in <pre>
48664 if (isPreLikeNode(node) && node.children.some(child => child.type !== "text" && child.type !== "interpolation")) {
48671 function hasPrettierIgnore$5(node) {
48672 if (node.type === "attribute") {
48676 if (!node.parent) {
48680 if (typeof node.index !== "number" || node.index === 0) {
48684 const prevNode = node.parent.children[node.index - 1];
48685 return isPrettierIgnore$1(prevNode);
48688 function isPrettierIgnore$1(node) {
48689 return node.type === "comment" && node.value.trim() === "prettier-ignore";
48692 function getPrettierIgnoreAttributeCommentData(value) {
48693 const match = value.trim().match(/^prettier-ignore-attribute(?:\s+([^]+))?$/);
48703 return match[1].split(/\s+/);
48705 /** there's no opening/closing tag or it's considered not breakable */
48708 function isTextLikeNode(node) {
48709 return node.type === "text" || node.type === "comment";
48712 function isScriptLikeTag(node) {
48713 return node.type === "element" && (node.fullName === "script" || node.fullName === "style" || node.fullName === "svg:style" || isUnknownNamespace(node) && (node.name === "script" || node.name === "style"));
48716 function isFrontMatterNode(node) {
48717 return node.type === "yaml" || node.type === "toml";
48720 function canHaveInterpolation(node) {
48721 return node.children && !isScriptLikeTag(node);
48724 function isWhitespaceSensitiveNode(node) {
48725 return isScriptLikeTag(node) || node.type === "interpolation" || isIndentationSensitiveNode(node);
48728 function isIndentationSensitiveNode(node) {
48729 return getNodeCssStyleWhiteSpace(node).startsWith("pre");
48732 function isLeadingSpaceSensitiveNode(node) {
48733 const isLeadingSpaceSensitive = _isLeadingSpaceSensitiveNode();
48735 if (isLeadingSpaceSensitive && !node.prev && node.parent && node.parent.tagDefinition && node.parent.tagDefinition.ignoreFirstLf) {
48736 return node.type === "interpolation";
48739 return isLeadingSpaceSensitive;
48741 function _isLeadingSpaceSensitiveNode() {
48742 if (isFrontMatterNode(node)) {
48746 if ((node.type === "text" || node.type === "interpolation") && node.prev && (node.prev.type === "text" || node.prev.type === "interpolation")) {
48750 if (!node.parent || node.parent.cssDisplay === "none") {
48754 if (isPreLikeNode(node.parent)) {
48758 if (!node.prev && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
48762 if (node.prev && !isNextLeadingSpaceSensitiveCssDisplay(node.prev.cssDisplay)) {
48770 function isTrailingSpaceSensitiveNode(node) {
48771 if (isFrontMatterNode(node)) {
48775 if ((node.type === "text" || node.type === "interpolation") && node.next && (node.next.type === "text" || node.next.type === "interpolation")) {
48779 if (!node.parent || node.parent.cssDisplay === "none") {
48783 if (isPreLikeNode(node.parent)) {
48787 if (!node.next && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
48791 if (node.next && !isPrevTrailingSpaceSensitiveCssDisplay(node.next.cssDisplay)) {
48798 function isDanglingSpaceSensitiveNode(node) {
48799 return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag(node);
48802 function forceNextEmptyLine(node) {
48803 return isFrontMatterNode(node) || node.next && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line;
48805 /** firstChild leadingSpaces and lastChild trailingSpaces */
48808 function forceBreakContent(node) {
48809 return forceBreakChildren(node) || node.type === "element" && node.children.length !== 0 && (["body", "script", "style"].includes(node.name) || node.children.some(child => hasNonTextChild(child))) || node.firstChild && node.firstChild === node.lastChild && hasLeadingLineBreak(node.firstChild) && (!node.lastChild.isTrailingSpaceSensitive || hasTrailingLineBreak(node.lastChild));
48811 /** spaces between children */
48814 function forceBreakChildren(node) {
48815 return node.type === "element" && node.children.length !== 0 && (["html", "head", "ul", "ol", "select"].includes(node.name) || node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell");
48818 function preferHardlineAsLeadingSpaces(node) {
48819 return preferHardlineAsSurroundingSpaces(node) || node.prev && preferHardlineAsTrailingSpaces(node.prev) || hasSurroundingLineBreak(node);
48822 function preferHardlineAsTrailingSpaces(node) {
48823 return preferHardlineAsSurroundingSpaces(node) || node.type === "element" && node.fullName === "br" || hasSurroundingLineBreak(node);
48826 function hasSurroundingLineBreak(node) {
48827 return hasLeadingLineBreak(node) && hasTrailingLineBreak(node);
48830 function hasLeadingLineBreak(node) {
48831 return node.hasLeadingSpaces && (node.prev ? node.prev.sourceSpan.end.line < node.sourceSpan.start.line : node.parent.type === "root" || node.parent.startSourceSpan.end.line < node.sourceSpan.start.line);
48834 function hasTrailingLineBreak(node) {
48835 return node.hasTrailingSpaces && (node.next ? node.next.sourceSpan.start.line > node.sourceSpan.end.line : node.parent.type === "root" || node.parent.endSourceSpan && node.parent.endSourceSpan.start.line > node.sourceSpan.end.line);
48838 function preferHardlineAsSurroundingSpaces(node) {
48839 switch (node.type) {
48840 case "ieConditionalComment":
48846 return ["script", "select"].includes(node.name);
48852 function getLastDescendant(node) {
48853 return node.lastChild ? getLastDescendant(node.lastChild) : node;
48856 function hasNonTextChild(node) {
48857 return node.children && node.children.some(child => child.type !== "text");
48860 function inferScriptParser(node) {
48861 if (node.name === "script" && !node.attrMap.src) {
48862 if (!node.attrMap.lang && !node.attrMap.type || node.attrMap.type === "module" || node.attrMap.type === "text/javascript" || node.attrMap.type === "text/babel" || node.attrMap.type === "application/javascript" || node.attrMap.lang === "jsx") {
48866 if (node.attrMap.type === "application/x-typescript" || node.attrMap.lang === "ts" || node.attrMap.lang === "tsx") {
48867 return "typescript";
48870 if (node.attrMap.type === "text/markdown") {
48874 if (node.attrMap.type.endsWith("json") || node.attrMap.type.endsWith("importmap")) {
48878 if (node.attrMap.type === "text/x-handlebars-template") {
48883 if (node.name === "style") {
48884 if (!node.attrMap.lang || node.attrMap.lang === "postcss" || node.attrMap.lang === "css") {
48888 if (node.attrMap.lang === "scss") {
48892 if (node.attrMap.lang === "less") {
48900 function isBlockLikeCssDisplay(cssDisplay) {
48901 return cssDisplay === "block" || cssDisplay === "list-item" || cssDisplay.startsWith("table");
48904 function isFirstChildLeadingSpaceSensitiveCssDisplay(cssDisplay) {
48905 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
48908 function isLastChildTrailingSpaceSensitiveCssDisplay(cssDisplay) {
48909 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
48912 function isPrevTrailingSpaceSensitiveCssDisplay(cssDisplay) {
48913 return !isBlockLikeCssDisplay(cssDisplay);
48916 function isNextLeadingSpaceSensitiveCssDisplay(cssDisplay) {
48917 return !isBlockLikeCssDisplay(cssDisplay);
48920 function isDanglingSpaceSensitiveCssDisplay(cssDisplay) {
48921 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
48924 function isPreLikeNode(node) {
48925 return getNodeCssStyleWhiteSpace(node).startsWith("pre");
48928 function countParents(path, predicate = () => true) {
48931 for (let i = path.stack.length - 1; i >= 0; i--) {
48932 const value = path.stack[i];
48934 if (value && typeof value === "object" && !Array.isArray(value) && predicate(value)) {
48942 function hasParent(node, fn) {
48943 let current = node;
48950 current = current.parent;
48956 function getNodeCssStyleDisplay(node, options) {
48957 if (node.prev && node.prev.type === "comment") {
48958 // <!-- display: block -->
48959 const match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/);
48966 let isInSvgForeignObject = false;
48968 if (node.type === "element" && node.namespace === "svg") {
48969 if (hasParent(node, parent => parent.fullName === "svg:foreignObject")) {
48970 isInSvgForeignObject = true;
48972 return node.name === "svg" ? "inline-block" : "block";
48976 switch (options.htmlWhitespaceSensitivity) {
48984 return node.type === "element" && (!node.namespace || isInSvgForeignObject || isUnknownNamespace(node)) && CSS_DISPLAY_TAGS[node.name] || CSS_DISPLAY_DEFAULT;
48988 function isUnknownNamespace(node) {
48989 return node.type === "element" && !node.hasExplicitNamespace && !["html", "svg"].includes(node.namespace);
48992 function getNodeCssStyleWhiteSpace(node) {
48993 return node.type === "element" && (!node.namespace || isUnknownNamespace(node)) && CSS_WHITE_SPACE_TAGS[node.name] || CSS_WHITE_SPACE_DEFAULT;
48996 function getMinIndentation(text) {
48997 let minIndentation = Infinity;
48999 for (const lineText of text.split("\n")) {
49000 if (lineText.length === 0) {
49004 if (/\S/.test(lineText[0])) {
49008 const indentation = lineText.match(/^\s*/)[0].length;
49010 if (lineText.length === indentation) {
49014 if (indentation < minIndentation) {
49015 minIndentation = indentation;
49019 return minIndentation === Infinity ? 0 : minIndentation;
49022 function dedentString(text, minIndent = getMinIndentation(text)) {
49023 return minIndent === 0 ? text : text.split("\n").map(lineText => lineText.slice(minIndent)).join("\n");
49026 function normalizeParts$1(parts) {
49027 const newParts = [];
49028 const restParts = parts.slice();
49030 while (restParts.length !== 0) {
49031 const part = restParts.shift();
49037 if (part.type === "concat") {
49038 restParts.unshift(...part.parts);
49042 if (newParts.length !== 0 && typeof newParts[newParts.length - 1] === "string" && typeof part === "string") {
49043 newParts.push(newParts.pop() + part);
49047 newParts.push(part);
49053 function identity$3(x) {
49057 function shouldNotPrintClosingTag(node, options) {
49058 return !node.isSelfClosing && !node.endSourceSpan && (hasPrettierIgnore$5(node) || shouldPreserveContent(node.parent, options));
49061 function countChars(text, char) {
49064 for (let i = 0; i < text.length; i++) {
49065 if (text[i] === char) {
49073 function unescapeQuoteEntities(text) {
49074 return text.replace(/'/g, "'").replace(/"/g, '"');
49078 HTML_ELEMENT_ATTRIBUTES,
49080 canHaveInterpolation,
49084 forceBreakChildren,
49086 forceNextEmptyLine,
49088 getNodeCssStyleDisplay,
49089 getNodeCssStyleWhiteSpace,
49090 getPrettierIgnoreAttributeCommentData,
49091 hasPrettierIgnore: hasPrettierIgnore$5,
49092 identity: identity$3,
49094 isDanglingSpaceSensitiveNode,
49096 isIndentationSensitiveNode,
49097 isLeadingSpaceSensitiveNode,
49101 isTrailingSpaceSensitiveNode,
49102 isWhitespaceSensitiveNode,
49103 isUnknownNamespace,
49104 normalizeParts: normalizeParts$1,
49105 preferHardlineAsLeadingSpaces,
49106 preferHardlineAsTrailingSpaces,
49107 shouldNotPrintClosingTag,
49108 shouldPreserveContent,
49109 unescapeQuoteEntities
49113 canHaveInterpolation: canHaveInterpolation$1,
49114 getNodeCssStyleDisplay: getNodeCssStyleDisplay$1,
49115 isDanglingSpaceSensitiveNode: isDanglingSpaceSensitiveNode$1,
49116 isIndentationSensitiveNode: isIndentationSensitiveNode$1,
49117 isLeadingSpaceSensitiveNode: isLeadingSpaceSensitiveNode$1,
49118 isTrailingSpaceSensitiveNode: isTrailingSpaceSensitiveNode$1,
49119 isWhitespaceSensitiveNode: isWhitespaceSensitiveNode$1
49121 const PREPROCESS_PIPELINE = [removeIgnorableFirstLf, mergeIeConditonalStartEndCommentIntoElementOpeningTag, mergeCdataIntoText, extractInterpolation, extractWhitespaces, addCssDisplay, addIsSelfClosing, addHasHtmComponentClosingTag, addIsSpaceSensitive, mergeSimpleElementIntoText];
49123 function preprocess$2(ast, options) {
49124 for (const fn of PREPROCESS_PIPELINE) {
49125 ast = fn(ast, options);
49131 function removeIgnorableFirstLf(ast
49134 return ast.map(node => {
49135 if (node.type === "element" && node.tagDefinition.ignoreFirstLf && node.children.length !== 0 && node.children[0].type === "text" && node.children[0].value[0] === "\n") {
49136 const [text, ...rest] = node.children;
49137 return node.clone({
49138 children: text.value.length === 1 ? rest : [text.clone({
49139 value: text.value.slice(1)
49148 function mergeIeConditonalStartEndCommentIntoElementOpeningTag(ast
49152 * <!--[if ...]><!--><target><!--<![endif]-->
49154 const isTarget = node => node.type === "element" && node.prev && node.prev.type === "ieConditionalStartComment" && node.prev.sourceSpan.end.offset === node.startSourceSpan.start.offset && node.firstChild && node.firstChild.type === "ieConditionalEndComment" && node.firstChild.sourceSpan.start.offset === node.startSourceSpan.end.offset;
49156 return ast.map(node => {
49157 if (node.children) {
49158 const isTargetResults = node.children.map(isTarget);
49160 if (isTargetResults.some(Boolean)) {
49161 const newChildren = [];
49163 for (let i = 0; i < node.children.length; i++) {
49164 const child = node.children[i];
49166 if (isTargetResults[i + 1]) {
49167 // ieConditionalStartComment
49171 if (isTargetResults[i]) {
49172 const ieConditionalStartComment = child.prev;
49173 const ieConditionalEndComment = child.firstChild;
49174 const ParseSourceSpan = child.sourceSpan.constructor;
49175 const startSourceSpan = new ParseSourceSpan(ieConditionalStartComment.sourceSpan.start, ieConditionalEndComment.sourceSpan.end);
49176 const sourceSpan = new ParseSourceSpan(startSourceSpan.start, child.sourceSpan.end);
49177 newChildren.push(child.clone({
49178 condition: ieConditionalStartComment.condition,
49181 children: child.children.slice(1)
49186 newChildren.push(child);
49189 return node.clone({
49190 children: newChildren
49199 function mergeNodeIntoText(ast, shouldMerge, getValue) {
49200 return ast.map(node => {
49201 if (node.children) {
49202 const shouldMergeResults = node.children.map(shouldMerge);
49204 if (shouldMergeResults.some(Boolean)) {
49205 const newChildren = [];
49207 for (let i = 0; i < node.children.length; i++) {
49208 const child = node.children[i];
49210 if (child.type !== "text" && !shouldMergeResults[i]) {
49211 newChildren.push(child);
49215 const newChild = child.type === "text" ? child : child.clone({
49217 value: getValue(child)
49220 if (newChildren.length === 0 || newChildren[newChildren.length - 1].type !== "text") {
49221 newChildren.push(newChild);
49225 const lastChild = newChildren.pop();
49226 const ParseSourceSpan = lastChild.sourceSpan.constructor;
49227 newChildren.push(lastChild.clone({
49228 value: lastChild.value + newChild.value,
49229 sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, newChild.sourceSpan.end)
49233 return node.clone({
49234 children: newChildren
49243 function mergeCdataIntoText(ast
49246 return mergeNodeIntoText(ast, node => node.type === "cdata", node => `<![CDATA[${node.value}]]>`);
49249 function mergeSimpleElementIntoText(ast
49252 const isSimpleElement = node => node.type === "element" && node.attrs.length === 0 && node.children.length === 1 && node.firstChild.type === "text" && // \xA0: non-breaking whitespace
49253 !/[^\S\xA0]/.test(node.children[0].value) && !node.firstChild.hasLeadingSpaces && !node.firstChild.hasTrailingSpaces && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces && node.prev && node.prev.type === "text" && node.next && node.next.type === "text";
49255 return ast.map(node => {
49256 if (node.children) {
49257 const isSimpleElementResults = node.children.map(isSimpleElement);
49259 if (isSimpleElementResults.some(Boolean)) {
49260 const newChildren = [];
49262 for (let i = 0; i < node.children.length; i++) {
49263 const child = node.children[i];
49265 if (isSimpleElementResults[i]) {
49266 const lastChild = newChildren.pop();
49267 const nextChild = node.children[++i];
49268 const ParseSourceSpan = node.sourceSpan.constructor;
49270 isTrailingSpaceSensitive,
49273 newChildren.push(lastChild.clone({
49274 value: lastChild.value + `<${child.rawName}>` + child.firstChild.value + `</${child.rawName}>` + nextChild.value,
49275 sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, nextChild.sourceSpan.end),
49276 isTrailingSpaceSensitive,
49280 newChildren.push(child);
49284 return node.clone({
49285 children: newChildren
49294 function extractInterpolation(ast, options) {
49295 if (options.parser === "html") {
49299 const interpolationRegex = /\{\{([\s\S]+?)\}\}/g;
49300 return ast.map(node => {
49301 if (!canHaveInterpolation$1(node)) {
49305 const newChildren = [];
49307 for (const child of node.children) {
49308 if (child.type !== "text") {
49309 newChildren.push(child);
49313 const ParseSourceSpan = child.sourceSpan.constructor;
49314 let startSourceSpan = child.sourceSpan.start;
49315 let endSourceSpan = null;
49316 const components = child.value.split(interpolationRegex);
49318 for (let i = 0; i < components.length; i++, startSourceSpan = endSourceSpan) {
49319 const value = components[i];
49322 endSourceSpan = startSourceSpan.moveBy(value.length);
49324 if (value.length !== 0) {
49328 sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan)
49335 endSourceSpan = startSourceSpan.moveBy(value.length + 4); // `{{` + `}}`
49338 type: "interpolation",
49339 sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan),
49340 children: value.length === 0 ? [] : [{
49343 sourceSpan: new ParseSourceSpan(startSourceSpan.moveBy(2), endSourceSpan.moveBy(-2))
49349 return node.clone({
49350 children: newChildren
49355 * - add `hasLeadingSpaces` field
49356 * - add `hasTrailingSpaces` field
49357 * - add `hasDanglingSpaces` field for parent nodes
49358 * - add `isWhitespaceSensitive`, `isIndentationSensitive` field for text nodes
49359 * - remove insensitive whitespaces
49363 function extractWhitespaces(ast
49366 const TYPE_WHITESPACE = "whitespace";
49367 return ast.map(node => {
49368 if (!node.children) {
49372 if (node.children.length === 0 || node.children.length === 1 && node.children[0].type === "text" && node.children[0].value.trim().length === 0) {
49373 return node.clone({
49375 hasDanglingSpaces: node.children.length !== 0
49379 const isWhitespaceSensitive = isWhitespaceSensitiveNode$1(node);
49380 const isIndentationSensitive = isIndentationSensitiveNode$1(node);
49381 return node.clone({
49382 isWhitespaceSensitive,
49383 isIndentationSensitive,
49384 children: node.children // extract whitespace nodes
49385 .reduce((newChildren, child) => {
49386 if (child.type !== "text" || isWhitespaceSensitive) {
49387 return newChildren.concat(child);
49390 const localChildren = [];
49391 const [, leadingSpaces, text, trailingSpaces] = child.value.match(/^(\s*)([\s\S]*?)(\s*)$/);
49393 if (leadingSpaces) {
49394 localChildren.push({
49395 type: TYPE_WHITESPACE
49399 const ParseSourceSpan = child.sourceSpan.constructor;
49402 localChildren.push({
49405 sourceSpan: new ParseSourceSpan(child.sourceSpan.start.moveBy(leadingSpaces.length), child.sourceSpan.end.moveBy(-trailingSpaces.length))
49409 if (trailingSpaces) {
49410 localChildren.push({
49411 type: TYPE_WHITESPACE
49415 return newChildren.concat(localChildren);
49416 }, []) // set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
49417 .reduce((newChildren, child, i, children) => {
49418 if (child.type === TYPE_WHITESPACE) {
49419 return newChildren;
49422 const hasLeadingSpaces = i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
49423 const hasTrailingSpaces = i !== children.length - 1 && children[i + 1].type === TYPE_WHITESPACE;
49424 return newChildren.concat(Object.assign({}, child, {
49433 function addIsSelfClosing(ast
49436 return ast.map(node => Object.assign(node, {
49437 isSelfClosing: !node.children || node.type === "element" && (node.tagDefinition.isVoid || // self-closing
49438 node.startSourceSpan === node.endSourceSpan)
49442 function addHasHtmComponentClosingTag(ast, options) {
49443 return ast.map(node => node.type !== "element" ? node : Object.assign(node, {
49444 hasHtmComponentClosingTag: node.endSourceSpan && /^<\s*\/\s*\/\s*>$/.test(options.originalText.slice(node.endSourceSpan.start.offset, node.endSourceSpan.end.offset))
49448 function addCssDisplay(ast, options) {
49449 return ast.map(node => Object.assign(node, {
49450 cssDisplay: getNodeCssStyleDisplay$1(node, options)
49454 * - add `isLeadingSpaceSensitive` field
49455 * - add `isTrailingSpaceSensitive` field
49456 * - add `isDanglingSpaceSensitive` field for parent nodes
49460 function addIsSpaceSensitive(ast
49463 return ast.map(node => {
49464 if (!node.children) {
49468 if (node.children.length === 0) {
49469 return node.clone({
49470 isDanglingSpaceSensitive: isDanglingSpaceSensitiveNode$1(node)
49474 return node.clone({
49475 children: node.children.map(child => {
49476 return Object.assign({}, child, {
49477 isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode$1(child),
49478 isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode$1(child)
49480 }).map((child, index, children) => Object.assign({}, child, {
49481 isLeadingSpaceSensitive: index === 0 ? child.isLeadingSpaceSensitive : children[index - 1].isTrailingSpaceSensitive && child.isLeadingSpaceSensitive,
49482 isTrailingSpaceSensitive: index === children.length - 1 ? child.isTrailingSpaceSensitive : children[index + 1].isLeadingSpaceSensitive && child.isTrailingSpaceSensitive
49488 var preprocess_1$2 = preprocess$2;
49490 function hasPragma$3(text) {
49491 return /^\s*<!--\s*@(format|prettier)\s*-->/.test(text);
49494 function insertPragma$6(text) {
49495 return "<!-- @format -->\n\n" + text.replace(/^\s*\n/, "");
49499 hasPragma: hasPragma$3,
49500 insertPragma: insertPragma$6
49510 * v-for="... in ..."
49511 * v-for="... of ..."
49512 * v-for="(..., ...) in ..."
49513 * v-for="(..., ...) of ..."
49516 function printVueFor(value, textToDoc) {
49521 } = parseVueFor(value);
49522 return concat$e([group$e(textToDoc(`function _(${left}) {}`, {
49524 __isVueForBindingLeft: true
49525 })), " ", operator, " ", textToDoc(right, {
49526 parser: "__js_expression"
49528 } // modified from https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/parser/index.js#L370-L387
49531 function parseVueFor(value) {
49532 const forAliasRE = /([^]*?)\s+(in|of)\s+([^]*)/;
49533 const forIteratorRE = /,([^,}\]]*)(?:,([^,}\]]*))?$/;
49534 const stripParensRE = /^\(|\)$/g;
49535 const inMatch = value.match(forAliasRE);
49542 res.for = inMatch[3].trim();
49543 const alias = inMatch[1].trim().replace(stripParensRE, "");
49544 const iteratorMatch = alias.match(forIteratorRE);
49546 if (iteratorMatch) {
49547 res.alias = alias.replace(forIteratorRE, "");
49548 res.iterator1 = iteratorMatch[1].trim();
49550 if (iteratorMatch[2]) {
49551 res.iterator2 = iteratorMatch[2].trim();
49558 left: `${[res.alias, res.iterator1, res.iterator2].filter(Boolean).join(",")}`,
49559 operator: inMatch[2],
49564 function printVueSlotScope(value, textToDoc) {
49565 return textToDoc(`function _(${value}) {}`, {
49567 __isVueSlotScope: true
49571 function isVueEventBindingExpression$2(eventBindingValue) {
49572 // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/codegen/events.js#L3-L4
49573 // arrow function or anonymous function
49574 const fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; // simple member expression chain (a, a.b, a['b'], a["b"], a[0], a[b])
49576 const simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/; // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/helpers.js#L104
49578 const value = eventBindingValue.trim();
49579 return fnExpRE.test(value) || simplePathRE.test(value);
49583 isVueEventBindingExpression: isVueEventBindingExpression$2,
49588 const integerRegex = /^\d+$/;
49590 function deepUnique(array) {
49591 return array.sort().filter((element, index) => {
49592 return JSON.stringify(element) !== JSON.stringify(array[index - 1]);
49596 var parse$6 = string => {
49597 return deepUnique(string.split(',').map(part => {
49599 part.trim().split(/\s+/).forEach((element, index) => {
49601 result.url = element;
49605 const value = element.slice(0, element.length - 1);
49606 const postfix = element[element.length - 1];
49607 const integerValue = parseInt(value, 10);
49608 const floatValue = parseFloat(value);
49610 if (postfix === 'w' && integerRegex.test(value)) {
49611 result.width = integerValue;
49612 } else if (postfix === 'h' && integerRegex.test(value)) {
49613 result.height = integerValue;
49614 } else if (postfix === 'x' && !Number.isNaN(floatValue)) {
49615 result.density = floatValue;
49617 throw new Error(`Invalid srcset descriptor: ${element}`);
49624 var stringify$2 = array => {
49625 return [...new Set(array.map(element => {
49626 if (!element.url) {
49627 throw new Error('URL is required');
49630 const result = [element.url];
49632 if (element.width) {
49633 result.push(`${element.width}w`);
49636 if (element.height) {
49637 result.push(`${element.height}h`);
49640 if (element.density) {
49641 result.push(`${element.density}x`);
49644 return result.join(' ');
49650 stringify: stringify$2
49656 ifBreak: ifBreak$6,
49661 const parseSrcset = srcset.parse;
49663 function printImgSrcset(value) {
49664 const srcset = parseSrcset(value);
49665 const hasW = srcset.some(src => src.width);
49666 const hasH = srcset.some(src => src.height);
49667 const hasX = srcset.some(src => src.density);
49669 if (hasW + hasH + hasX > 1) {
49670 throw new Error("Mixed descriptor in srcset is not supported");
49673 const key = hasW ? "width" : hasH ? "height" : "density";
49674 const unit = hasW ? "w" : hasH ? "h" : "x";
49676 const getMax = values => Math.max(...values);
49678 const urls = srcset.map(src => src.url);
49679 const maxUrlLength = getMax(urls.map(url => url.length));
49680 const descriptors = srcset.map(src => src[key]).map(descriptor => descriptor ? descriptor.toString() : "");
49681 const descriptorLeftLengths = descriptors.map(descriptor => {
49682 const index = descriptor.indexOf(".");
49683 return index === -1 ? descriptor.length : index;
49685 const maxDescriptorLeftLength = getMax(descriptorLeftLengths);
49686 return join$a(concat$f([",", line$9]), urls.map((url, index) => {
49687 const parts = [url];
49688 const descriptor = descriptors[index];
49691 const urlPadding = maxUrlLength - url.length + 1;
49692 const descriptorPadding = maxDescriptorLeftLength - descriptorLeftLengths[index];
49693 const alignment = " ".repeat(urlPadding + descriptorPadding);
49694 parts.push(ifBreak$6(alignment, " "), descriptor + unit);
49697 return concat$f(parts);
49701 function printClassNames(value) {
49702 return value.trim().split(/\s+/).join(" ");
49705 var syntaxAttribute = {
49713 stripTrailingHardline: stripTrailingHardline$2,
49718 breakParent: breakParent$4,
49719 dedentToRoot: dedentToRoot$2,
49722 hardline: hardline$c,
49723 ifBreak: ifBreak$7,
49727 literalline: literalline$6,
49728 markAsRoot: markAsRoot$4,
49729 softline: softline$7
49732 countChars: countChars$1,
49733 countParents: countParents$1,
49734 dedentString: dedentString$1,
49735 forceBreakChildren: forceBreakChildren$1,
49736 forceBreakContent: forceBreakContent$1,
49737 forceNextEmptyLine: forceNextEmptyLine$1,
49738 getLastDescendant: getLastDescendant$1,
49739 getPrettierIgnoreAttributeCommentData: getPrettierIgnoreAttributeCommentData$1,
49740 hasPrettierIgnore: hasPrettierIgnore$6,
49741 inferScriptParser: inferScriptParser$1,
49742 isScriptLikeTag: isScriptLikeTag$1,
49743 isTextLikeNode: isTextLikeNode$1,
49744 normalizeParts: normalizeParts$2,
49745 preferHardlineAsLeadingSpaces: preferHardlineAsLeadingSpaces$1,
49746 shouldNotPrintClosingTag: shouldNotPrintClosingTag$1,
49747 shouldPreserveContent: shouldPreserveContent$1,
49748 unescapeQuoteEntities: unescapeQuoteEntities$1
49751 replaceEndOfLineWith: replaceEndOfLineWith$2
49754 insertPragma: insertPragma$7
49757 printVueFor: printVueFor$1,
49758 printVueSlotScope: printVueSlotScope$1,
49759 isVueEventBindingExpression: isVueEventBindingExpression$3
49762 printImgSrcset: printImgSrcset$1,
49763 printClassNames: printClassNames$1
49764 } = syntaxAttribute;
49766 function concat$g(parts) {
49767 const newParts = normalizeParts$2(parts);
49768 return newParts.length === 0 ? "" : newParts.length === 1 ? newParts[0] : builders.concat(newParts);
49771 function embed$4(path, print, textToDoc, options) {
49772 const node = path.getValue();
49774 switch (node.type) {
49777 if (isScriptLikeTag$1(node.parent)) {
49778 const parser = inferScriptParser$1(node.parent);
49781 const value = parser === "markdown" ? dedentString$1(node.value.replace(/^[^\S\n]*?\n/, "")) : node.value;
49782 return builders.concat([concat$g([breakParent$4, printOpeningTagPrefix(node, options), stripTrailingHardline$2(textToDoc(value, {
49784 })), printClosingTagSuffix(node, options)])]);
49786 } else if (node.parent.type === "interpolation") {
49787 return concat$g([indent$9(concat$g([line$a, textToDoc(node.value, Object.assign({
49788 __isInHtmlInterpolation: true
49789 }, options.parser === "angular" ? {
49790 parser: "__ng_interpolation",
49791 trailingComma: "none"
49792 } : options.parser === "vue" ? {
49793 parser: "__vue_expression"
49795 parser: "__js_expression"
49796 }))])), node.parent.next && needsToBorrowPrevClosingTagEndMarker(node.parent.next) ? " " : line$a]);
49806 } // lit-html: html`<my-element obj=${obj}></my-element>`
49809 if (/^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
49810 return concat$g([node.rawName, "=", node.value]);
49811 } // lwc: html`<my-element data-for={value}></my-element>`
49814 if (options.parser === "lwc") {
49815 const interpolationRegex = /^\{[\s\S]*\}$/;
49817 if (interpolationRegex.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
49818 return concat$g([node.rawName, "=", node.value]);
49822 const embeddedAttributeValueDoc = printEmbeddedAttributeValue(node, (code, opts) => // strictly prefer single quote to avoid unnecessary html entity escape
49823 textToDoc(code, Object.assign({
49824 __isInHtmlAttribute: true
49825 }, opts)), options);
49827 if (embeddedAttributeValueDoc) {
49828 return concat$g([node.rawName, '="', group$f(mapDoc$5(embeddedAttributeValueDoc, doc => typeof doc === "string" ? doc.replace(/"/g, """) : doc)), '"']);
49835 return markAsRoot$4(concat$g(["---", hardline$c, node.value.trim().length === 0 ? "" : textToDoc(node.value, {
49841 function genericPrint$5(path, options, print) {
49842 const node = path.getValue();
49844 switch (node.type) {
49846 if (options.__onHtmlRoot) {
49847 options.__onHtmlRoot(node);
49848 } // use original concat to not break stripTrailingHardline
49851 return builders.concat([group$f(printChildren$2(path, options, print)), hardline$c]);
49854 case "ieConditionalComment":
49865 * exception: break if the opening tag breaks
49876 const shouldHugContent = node.children.length === 1 && node.firstChild.type === "interpolation" && node.firstChild.isLeadingSpaceSensitive && !node.firstChild.hasLeadingSpaces && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces;
49877 const attrGroupId = Symbol("element-attr-group-id");
49878 return concat$g([group$f(concat$g([group$f(printOpeningTag(path, options, print), {
49880 }), node.children.length === 0 ? node.hasDanglingSpaces && node.isDanglingSpaceSensitive ? line$a : "" : concat$g([forceBreakContent$1(node) ? breakParent$4 : "", (childrenDoc => shouldHugContent ? ifBreak$7(indent$9(childrenDoc), childrenDoc, {
49881 groupId: attrGroupId
49882 }) : isScriptLikeTag$1(node) && node.parent.type === "root" && options.parser === "vue" && !options.vueIndentScriptAndStyle ? childrenDoc : indent$9(childrenDoc))(concat$g([shouldHugContent ? ifBreak$7(softline$7, "", {
49883 groupId: attrGroupId
49884 }) : node.firstChild.hasLeadingSpaces && node.firstChild.isLeadingSpaceSensitive ? line$a : node.firstChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive ? dedentToRoot$2(softline$7) : softline$7, printChildren$2(path, options, print)])), (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? " " : "" : shouldHugContent ? ifBreak$7(softline$7, "", {
49885 groupId: attrGroupId
49886 }) : node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? line$a : (node.lastChild.type === "comment" || node.lastChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive) && new RegExp(`\\n\\s{${options.tabWidth * countParents$1(path, n => n.parent && n.parent.type !== "root")}}$`).test(node.lastChild.value) ?
49895 "" : softline$7])])), printClosingTag(node, options)]);
49898 case "ieConditionalStartComment":
49899 case "ieConditionalEndComment":
49900 return concat$g([printOpeningTagStart(node), printClosingTagEnd(node)]);
49902 case "interpolation":
49903 return concat$g([printOpeningTagStart(node, options), concat$g(path.map(print, "children")), printClosingTagEnd(node, options)]);
49907 if (node.parent.type === "interpolation") {
49908 // replace the trailing literalline with hardline for better readability
49909 const trailingNewlineRegex = /\n[^\S\n]*?$/;
49910 const hasTrailingNewline = trailingNewlineRegex.test(node.value);
49911 const value = hasTrailingNewline ? node.value.replace(trailingNewlineRegex, "") : node.value;
49912 return concat$g([concat$g(replaceEndOfLineWith$2(value, literalline$6)), hasTrailingNewline ? hardline$c : ""]);
49915 return fill$6(normalizeParts$2([].concat(printOpeningTagPrefix(node, options), getTextValueParts(node), printClosingTagSuffix(node, options))));
49919 return concat$g([group$f(concat$g([printOpeningTagStart(node, options), " ", node.value.replace(/^html\b/i, "html").replace(/\s+/g, " ")])), printClosingTagEnd(node, options)]);
49923 return concat$g([printOpeningTagPrefix(node, options), concat$g(replaceEndOfLineWith$2(options.originalText.slice(options.locStart(node), options.locEnd(node)), literalline$6)), printClosingTagSuffix(node, options)]);
49928 if (node.value === null) {
49929 return node.rawName;
49932 const value = unescapeQuoteEntities$1(node.value);
49933 const singleQuoteCount = countChars$1(value, "'");
49934 const doubleQuoteCount = countChars$1(value, '"');
49935 const quote = singleQuoteCount < doubleQuoteCount ? "'" : '"';
49936 return concat$g([node.rawName, concat$g(["=", quote, concat$g(replaceEndOfLineWith$2(quote === '"' ? value.replace(/"/g, """) : value.replace(/'/g, "'"), literalline$6)), quote])]);
49941 return concat$g(replaceEndOfLineWith$2(node.raw, literalline$6));
49944 throw new Error(`Unexpected node type ${node.type}`);
49948 function printChildren$2(path, options, print) {
49949 const node = path.getValue();
49951 if (forceBreakChildren$1(node)) {
49952 return concat$g([breakParent$4, concat$g(path.map(childPath => {
49953 const childNode = childPath.getValue();
49954 const prevBetweenLine = !childNode.prev ? "" : printBetweenLine(childNode.prev, childNode);
49955 return concat$g([!prevBetweenLine ? "" : concat$g([prevBetweenLine, forceNextEmptyLine$1(childNode.prev) ? hardline$c : ""]), printChild(childPath)]);
49959 const groupIds = node.children.map(() => Symbol(""));
49960 return concat$g(path.map((childPath, childIndex) => {
49961 const childNode = childPath.getValue();
49963 if (isTextLikeNode$1(childNode)) {
49964 if (childNode.prev && isTextLikeNode$1(childNode.prev)) {
49965 const prevBetweenLine = printBetweenLine(childNode.prev, childNode);
49967 if (prevBetweenLine) {
49968 if (forceNextEmptyLine$1(childNode.prev)) {
49969 return concat$g([hardline$c, hardline$c, printChild(childPath)]);
49972 return concat$g([prevBetweenLine, printChild(childPath)]);
49976 return printChild(childPath);
49979 const prevParts = [];
49980 const leadingParts = [];
49981 const trailingParts = [];
49982 const nextParts = [];
49983 const prevBetweenLine = childNode.prev ? printBetweenLine(childNode.prev, childNode) : "";
49984 const nextBetweenLine = childNode.next ? printBetweenLine(childNode, childNode.next) : "";
49986 if (prevBetweenLine) {
49987 if (forceNextEmptyLine$1(childNode.prev)) {
49988 prevParts.push(hardline$c, hardline$c);
49989 } else if (prevBetweenLine === hardline$c) {
49990 prevParts.push(hardline$c);
49992 if (isTextLikeNode$1(childNode.prev)) {
49993 leadingParts.push(prevBetweenLine);
49995 leadingParts.push(ifBreak$7("", softline$7, {
49996 groupId: groupIds[childIndex - 1]
50002 if (nextBetweenLine) {
50003 if (forceNextEmptyLine$1(childNode)) {
50004 if (isTextLikeNode$1(childNode.next)) {
50005 nextParts.push(hardline$c, hardline$c);
50007 } else if (nextBetweenLine === hardline$c) {
50008 if (isTextLikeNode$1(childNode.next)) {
50009 nextParts.push(hardline$c);
50012 trailingParts.push(nextBetweenLine);
50016 return concat$g([].concat(prevParts, group$f(concat$g([concat$g(leadingParts), group$f(concat$g([printChild(childPath), concat$g(trailingParts)]), {
50017 id: groupIds[childIndex]
50018 })])), nextParts));
50021 function printChild(childPath) {
50022 const child = childPath.getValue();
50024 if (hasPrettierIgnore$6(child)) {
50025 return concat$g([].concat(printOpeningTagPrefix(child, options), replaceEndOfLineWith$2(options.originalText.slice(options.locStart(child) + (child.prev && needsToBorrowNextOpeningTagStartMarker(child.prev) ? printOpeningTagStartMarker(child).length : 0), options.locEnd(child) - (child.next && needsToBorrowPrevClosingTagEndMarker(child.next) ? printClosingTagEndMarker(child, options).length : 0)), literalline$6), printClosingTagSuffix(child, options)));
50028 if (shouldPreserveContent$1(child, options)) {
50029 return concat$g([].concat(printOpeningTagPrefix(child, options), group$f(printOpeningTag(childPath, options, print)), replaceEndOfLineWith$2(options.originalText.slice(child.startSourceSpan.end.offset + (child.firstChild && needsToBorrowParentOpeningTagEndMarker(child.firstChild) ? -printOpeningTagEndMarker(child).length : 0), child.endSourceSpan.start.offset + (child.lastChild && needsToBorrowParentClosingTagStartMarker(child.lastChild) ? printClosingTagStartMarker(child, options).length : needsToBorrowLastChildClosingTagEndMarker(child) ? -printClosingTagEndMarker(child.lastChild, options).length : 0)), literalline$6), printClosingTag(child, options), printClosingTagSuffix(child, options)));
50032 return print(childPath);
50035 function printBetweenLine(prevNode, nextNode) {
50036 return isTextLikeNode$1(prevNode) && isTextLikeNode$1(nextNode) ? prevNode.isTrailingSpaceSensitive ? prevNode.hasTrailingSpaces ? preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$c : line$a : "" : preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$c : softline$7 : needsToBorrowNextOpeningTagStartMarker(prevNode) && (hasPrettierIgnore$6(nextNode) ||
50042 nextNode.firstChild ||
50048 nextNode.isSelfClosing ||
50054 nextNode.type === "element" && nextNode.attrs.length !== 0) ||
50061 prevNode.type === "element" && prevNode.isSelfClosing && needsToBorrowPrevClosingTagEndMarker(nextNode) ? "" : !nextNode.isLeadingSpaceSensitive || preferHardlineAsLeadingSpaces$1(nextNode) ||
50063 * Want to write us a letter? Use our<a
50064 * ><b><a>mailing address</a></b></a
50068 needsToBorrowPrevClosingTagEndMarker(nextNode) && prevNode.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild) && prevNode.lastChild.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild.lastChild) ? hardline$c : nextNode.hasLeadingSpaces ? line$a : softline$7;
50072 function printOpeningTag(path, options, print) {
50073 const node = path.getValue();
50074 const forceNotToBreakAttrContent = node.type === "element" && node.fullName === "script" && node.attrs.length === 1 && node.attrs[0].fullName === "src" && node.children.length === 0;
50075 return concat$g([printOpeningTagStart(node, options), !node.attrs || node.attrs.length === 0 ? node.isSelfClosing ?
50080 " " : "" : concat$g([indent$9(concat$g([forceNotToBreakAttrContent ? " " : line$a, join$b(line$a, (ignoreAttributeData => {
50081 const hasPrettierIgnoreAttribute = typeof ignoreAttributeData === "boolean" ? () => ignoreAttributeData : Array.isArray(ignoreAttributeData) ? attr => ignoreAttributeData.includes(attr.rawName) : () => false;
50082 return path.map(attrPath => {
50083 const attr = attrPath.getValue();
50084 return hasPrettierIgnoreAttribute(attr) ? concat$g(replaceEndOfLineWith$2(options.originalText.slice(options.locStart(attr), options.locEnd(attr)), literalline$6)) : print(attrPath);
50086 })(node.prev && node.prev.type === "comment" && getPrettierIgnoreAttributeCommentData$1(node.prev.value)))])),
50093 node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ||
50100 node.isSelfClosing && needsToBorrowLastChildClosingTagEndMarker(node.parent) ? node.isSelfClosing ? " " : "" : node.isSelfClosing ? forceNotToBreakAttrContent ? " " : line$a : forceNotToBreakAttrContent ? "" : softline$7]), node.isSelfClosing ? "" : printOpeningTagEnd(node)]);
50103 function printOpeningTagStart(node, options) {
50104 return node.prev && needsToBorrowNextOpeningTagStartMarker(node.prev) ? "" : concat$g([printOpeningTagPrefix(node, options), printOpeningTagStartMarker(node)]);
50107 function printOpeningTagEnd(node) {
50108 return node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ? "" : printOpeningTagEndMarker(node);
50111 function printClosingTag(node, options) {
50112 return concat$g([node.isSelfClosing ? "" : printClosingTagStart(node, options), printClosingTagEnd(node, options)]);
50115 function printClosingTagStart(node, options) {
50116 return node.lastChild && needsToBorrowParentClosingTagStartMarker(node.lastChild) ? "" : concat$g([printClosingTagPrefix(node, options), printClosingTagStartMarker(node, options)]);
50119 function printClosingTagEnd(node, options) {
50120 return (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? "" : concat$g([printClosingTagEndMarker(node, options), printClosingTagSuffix(node, options)]);
50123 function needsToBorrowNextOpeningTagStartMarker(node) {
50129 return node.next && !isTextLikeNode$1(node.next) && isTextLikeNode$1(node) && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces;
50132 function needsToBorrowParentOpeningTagEndMarker(node) {
50142 return !node.prev && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
50145 function needsToBorrowPrevClosingTagEndMarker(node) {
50155 return node.prev && !isTextLikeNode$1(node.prev) && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
50158 function needsToBorrowLastChildClosingTagEndMarker(node) {
50166 return node.lastChild && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces && !isTextLikeNode$1(getLastDescendant$1(node.lastChild));
50169 function needsToBorrowParentClosingTagStartMarker(node) {
50181 return !node.next && !node.hasTrailingSpaces && node.isTrailingSpaceSensitive && isTextLikeNode$1(getLastDescendant$1(node));
50184 function printOpeningTagPrefix(node, options) {
50185 return needsToBorrowParentOpeningTagEndMarker(node) ? printOpeningTagEndMarker(node.parent) : needsToBorrowPrevClosingTagEndMarker(node) ? printClosingTagEndMarker(node.prev, options) : "";
50188 function printClosingTagPrefix(node, options) {
50189 return needsToBorrowLastChildClosingTagEndMarker(node) ? printClosingTagEndMarker(node.lastChild, options) : "";
50192 function printClosingTagSuffix(node, options) {
50193 return needsToBorrowParentClosingTagStartMarker(node) ? printClosingTagStartMarker(node.parent, options) : needsToBorrowNextOpeningTagStartMarker(node) ? printOpeningTagStartMarker(node.next) : "";
50196 function printOpeningTagStartMarker(node) {
50197 switch (node.type) {
50198 case "ieConditionalComment":
50199 case "ieConditionalStartComment":
50200 return `<!--[if ${node.condition}`;
50202 case "ieConditionalEndComment":
50205 case "interpolation":
50209 return "<!DOCTYPE";
50212 if (node.condition) {
50213 return `<!--[if ${node.condition}]><!--><${node.rawName}`;
50219 return `<${node.rawName}`;
50223 function printOpeningTagEndMarker(node) {
50224 assert$1(!node.isSelfClosing);
50226 switch (node.type) {
50227 case "ieConditionalComment":
50231 if (node.condition) {
50232 return "><!--<![endif]-->";
50242 function printClosingTagStartMarker(node, options) {
50243 assert$1(!node.isSelfClosing);
50245 if (shouldNotPrintClosingTag$1(node, options)) {
50249 switch (node.type) {
50250 case "ieConditionalComment":
50254 if (node.hasHtmComponentClosingTag) {
50261 return `</${node.rawName}`;
50265 function printClosingTagEndMarker(node, options) {
50266 if (shouldNotPrintClosingTag$1(node, options)) {
50270 switch (node.type) {
50271 case "ieConditionalComment":
50272 case "ieConditionalEndComment":
50273 return "[endif]-->";
50275 case "ieConditionalStartComment":
50278 case "interpolation":
50282 if (node.isSelfClosing) {
50293 function getTextValueParts(node, value = node.value) {
50294 return node.parent.isWhitespaceSensitive ? node.parent.isIndentationSensitive ? replaceEndOfLineWith$2(value, literalline$6) : replaceEndOfLineWith$2(dedentString$1(value.replace(/^\s*?\n|\n\s*?$/g, "")), hardline$c) : // https://infra.spec.whatwg.org/#ascii-whitespace
50295 join$b(line$a, value.split(/[\t\n\f\r ]+/)).parts;
50298 function printEmbeddedAttributeValue(node, originalTextToDoc, options) {
50299 const isKeyMatched = patterns => new RegExp(patterns.join("|")).test(node.fullName);
50301 const getValue = () => unescapeQuoteEntities$1(node.value);
50303 let shouldHug = false;
50305 const __onHtmlBindingRoot = (root, options) => {
50306 const rootNode = root.type === "NGRoot" ? root.node.type === "NGMicrosyntax" && root.node.body.length === 1 && root.node.body[0].type === "NGMicrosyntaxExpression" ? root.node.body[0].expression : root.node : root.type === "JsExpressionRoot" ? root.node : root;
50308 if (rootNode && (rootNode.type === "ObjectExpression" || rootNode.type === "ArrayExpression" || options.parser === "__vue_expression" && (rootNode.type === "TemplateLiteral" || rootNode.type === "StringLiteral"))) {
50313 const printHug = doc => group$f(doc);
50315 const printExpand = (doc, canHaveTrailingWhitespace = true) => group$f(concat$g([indent$9(concat$g([softline$7, doc])), canHaveTrailingWhitespace ? softline$7 : ""]));
50317 const printMaybeHug = doc => shouldHug ? printHug(doc) : printExpand(doc);
50319 const textToDoc = (code, opts) => originalTextToDoc(code, Object.assign({
50320 __onHtmlBindingRoot
50323 if (node.fullName === "srcset" && (node.parent.fullName === "img" || node.parent.fullName === "source")) {
50324 return printExpand(printImgSrcset$1(getValue()));
50327 if (node.fullName === "class" && !options.parentParser) {
50328 const value = getValue();
50330 if (!value.includes("{{")) {
50331 return printClassNames$1(value);
50335 if (node.fullName === "style" && !options.parentParser) {
50336 const value = getValue();
50338 if (!value.includes("{{")) {
50339 return printExpand(textToDoc(value, {
50341 __isHTMLStyleAttribute: true
50346 if (options.parser === "vue") {
50347 if (node.fullName === "v-for") {
50348 return printVueFor$1(getValue(), textToDoc);
50351 if (node.fullName === "slot-scope") {
50352 return printVueSlotScope$1(getValue(), textToDoc);
50355 * @click="jsStatement"
50356 * @click="jsExpression"
50357 * v-on:click="jsStatement"
50358 * v-on:click="jsExpression"
50362 const vueEventBindingPatterns = ["^@", "^v-on:"];
50364 * :class="vueExpression"
50365 * v-bind:id="vueExpression"
50368 const vueExpressionBindingPatterns = ["^:", "^v-bind:"];
50370 * v-if="jsExpression"
50373 const jsExpressionBindingPatterns = ["^v-"];
50375 if (isKeyMatched(vueEventBindingPatterns)) {
50376 const value = getValue();
50377 return printMaybeHug(isVueEventBindingExpression$3(value) ? textToDoc(value, {
50378 parser: "__js_expression"
50379 }) : stripTrailingHardline$2(textToDoc(value, {
50380 parser: "__vue_event_binding"
50384 if (isKeyMatched(vueExpressionBindingPatterns)) {
50385 return printMaybeHug(textToDoc(getValue(), {
50386 parser: "__vue_expression"
50390 if (isKeyMatched(jsExpressionBindingPatterns)) {
50391 return printMaybeHug(textToDoc(getValue(), {
50392 parser: "__js_expression"
50397 if (options.parser === "angular") {
50398 const ngTextToDoc = (code, opts) => // angular does not allow trailing comma
50399 textToDoc(code, Object.assign({}, opts, {
50400 trailingComma: "none"
50403 * *directive="angularDirective"
50407 const ngDirectiveBindingPatterns = ["^\\*"];
50409 * (click)="angularStatement"
50410 * on-click="angularStatement"
50413 const ngStatementBindingPatterns = ["^\\(.+\\)$", "^on-"];
50415 * [target]="angularExpression"
50416 * bind-target="angularExpression"
50417 * [(target)]="angularExpression"
50418 * bindon-target="angularExpression"
50421 const ngExpressionBindingPatterns = ["^\\[.+\\]$", "^bind(on)?-", // Unofficial rudimentary support for some of the most used directives of AngularJS 1.x
50422 "^ng-(if|show|hide|class|style)$"];
50424 * i18n="longDescription"
50425 * i18n-attr="longDescription"
50428 const ngI18nPatterns = ["^i18n(-.+)?$"];
50430 if (isKeyMatched(ngStatementBindingPatterns)) {
50431 return printMaybeHug(ngTextToDoc(getValue(), {
50432 parser: "__ng_action"
50436 if (isKeyMatched(ngExpressionBindingPatterns)) {
50437 return printMaybeHug(ngTextToDoc(getValue(), {
50438 parser: "__ng_binding"
50442 if (isKeyMatched(ngI18nPatterns)) {
50443 const value = getValue().trim();
50444 return printExpand(fill$6(getTextValueParts(node, value)), !value.includes("@@"));
50447 if (isKeyMatched(ngDirectiveBindingPatterns)) {
50448 return printMaybeHug(ngTextToDoc(getValue(), {
50449 parser: "__ng_directive"
50453 const interpolationRegex = /\{\{([\s\S]+?)\}\}/g;
50454 const value = getValue();
50456 if (interpolationRegex.test(value)) {
50458 value.split(interpolationRegex).forEach((part, index) => {
50459 if (index % 2 === 0) {
50460 parts.push(concat$g(replaceEndOfLineWith$2(part, literalline$6)));
50463 parts.push(group$f(concat$g(["{{", indent$9(concat$g([line$a, ngTextToDoc(part, {
50464 parser: "__ng_interpolation",
50465 __isInHtmlInterpolation: true // to avoid unexpected `}}`
50467 })])), line$a, "}}"])));
50469 parts.push("{{", concat$g(replaceEndOfLineWith$2(part, literalline$6)), "}}");
50473 return group$f(concat$g(parts));
50480 var printerHtml = {
50481 preprocess: preprocess_1$2,
50482 print: genericPrint$5,
50483 insertPragma: insertPragma$7,
50484 massageAstNode: clean$6,
50488 const CATEGORY_HTML = "HTML"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
50491 htmlWhitespaceSensitivity: {
50493 category: CATEGORY_HTML,
50496 description: "How to handle whitespaces in HTML.",
50499 description: "Respect the default value of CSS display property."
50502 description: "Whitespaces are considered sensitive."
50505 description: "Whitespaces are considered insensitive."
50508 vueIndentScriptAndStyle: {
50510 category: CATEGORY_HTML,
50513 description: "Indent script and style tags in Vue files."
50517 var name$g = "HTML";
50518 var type$e = "markup";
50519 var tmScope$e = "text.html.basic";
50520 var aceMode$e = "html";
50521 var codemirrorMode$b = "htmlmixed";
50522 var codemirrorMimeType$b = "text/html";
50523 var color$3 = "#e34c26";
50527 var extensions$e = [
50536 var languageId$e = 146;
50540 tmScope: tmScope$e,
50541 aceMode: aceMode$e,
50542 codemirrorMode: codemirrorMode$b,
50543 codemirrorMimeType: codemirrorMimeType$b,
50545 aliases: aliases$5,
50546 extensions: extensions$e,
50547 languageId: languageId$e
50550 var HTML$1 = /*#__PURE__*/Object.freeze({
50554 tmScope: tmScope$e,
50555 aceMode: aceMode$e,
50556 codemirrorMode: codemirrorMode$b,
50557 codemirrorMimeType: codemirrorMimeType$b,
50559 aliases: aliases$5,
50560 extensions: extensions$e,
50561 languageId: languageId$e,
50565 var name$h = "Vue";
50566 var type$f = "markup";
50567 var color$4 = "#2c3e50";
50568 var extensions$f = [
50571 var tmScope$f = "text.html.vue";
50572 var aceMode$f = "html";
50573 var languageId$f = 391;
50578 extensions: extensions$f,
50579 tmScope: tmScope$f,
50580 aceMode: aceMode$f,
50581 languageId: languageId$f
50584 var Vue$1 = /*#__PURE__*/Object.freeze({
50589 extensions: extensions$f,
50590 tmScope: tmScope$f,
50591 aceMode: aceMode$f,
50592 languageId: languageId$f,
50596 var require$$0$6 = getCjsExportFromNamespace(HTML$1);
50598 var require$$1$3 = getCjsExportFromNamespace(Vue$1);
50600 const languages$5 = [createLanguage(require$$0$6, () => ({
50603 parsers: ["angular"],
50604 vscodeLanguageIds: ["html"],
50605 extensions: [".component.html"],
50607 })), createLanguage(require$$0$6, data => ({
50610 vscodeLanguageIds: ["html"],
50611 extensions: data.extensions.concat([".mjml" // MJML is considered XML in Linguist but it should be formatted as HTML
50613 })), createLanguage(require$$0$6, () => ({
50614 name: "Lightning Web Components",
50617 vscodeLanguageIds: ["html"],
50620 })), createLanguage(require$$1$3, () => ({
50623 vscodeLanguageIds: ["vue"]
50625 const printers$5 = {
50628 var languageHtml = {
50629 languages: languages$5,
50630 printers: printers$5,
50634 function isPragma(text) {
50635 return /^\s*@(prettier|format)\s*$/.test(text);
50638 function hasPragma$4(text) {
50639 return /^\s*#[^\n\S]*@(prettier|format)\s*?(\n|$)/.test(text);
50642 function insertPragma$8(text) {
50643 return `# @format\n\n${text}`;
50648 hasPragma: hasPragma$4,
50649 insertPragma: insertPragma$8
50656 function getAncestorCount(path, filter) {
50658 const pathStackLength = path.stack.length - 1;
50660 for (let i = 0; i < pathStackLength; i++) {
50661 const value = path.stack[i];
50663 if (isNode(value) && filter(value)) {
50671 * @param {any} value
50672 * @param {string[]=} types
50676 function isNode(value, types) {
50677 return value && typeof value.type === "string" && (!types || types.includes(value.type));
50680 function mapNode(node, callback, parent) {
50681 return callback("children" in node ? Object.assign({}, node, {
50682 children: node.children.map(childNode => mapNode(childNode, callback, node))
50683 }) : node, parent);
50686 function defineShortcut(x, key, getter) {
50687 Object.defineProperty(x, key, {
50693 function isNextLineEmpty$5(node, text) {
50694 let newlineCount = 0;
50695 const textLength = text.length;
50697 for (let i = node.position.end.offset - 1; i < textLength; i++) {
50698 const char = text[i];
50700 if (char === "\n") {
50704 if (newlineCount === 1 && /\S/.test(char)) {
50708 if (newlineCount === 2) {
50716 function isLastDescendantNode(path) {
50717 const node = path.getValue();
50719 switch (node.type) {
50726 const pathStackLength = path.stack.length;
50728 for (let i = 1; i < pathStackLength; i++) {
50729 const item = path.stack[i];
50730 const parentItem = path.stack[i - 1];
50732 if (Array.isArray(parentItem) && typeof item === "number" && item !== parentItem.length - 1) {
50740 function getLastDescendantNode$1(node) {
50741 return "children" in node && node.children.length !== 0 ? getLastDescendantNode$1(getLast$5(node.children)) : node;
50744 function isPrettierIgnore$2(comment) {
50745 return comment.value.trim() === "prettier-ignore";
50748 function hasPrettierIgnore$7(path) {
50749 const node = path.getValue();
50751 if (node.type === "documentBody") {
50752 const document = path.getParentNode();
50753 return hasEndComments(document.head) && isPrettierIgnore$2(getLast$5(document.head.endComments));
50756 return hasLeadingComments(node) && isPrettierIgnore$2(getLast$5(node.leadingComments));
50759 function isEmptyNode(node) {
50760 return (!node.children || node.children.length === 0) && !hasComments(node);
50763 function hasComments(node) {
50764 return hasLeadingComments(node) || hasMiddleComments(node) || hasIndicatorComment(node) || hasTrailingComment$2(node) || hasEndComments(node);
50767 function hasLeadingComments(node) {
50768 return node && node.leadingComments && node.leadingComments.length !== 0;
50771 function hasMiddleComments(node) {
50772 return node && node.middleComments && node.middleComments.length !== 0;
50775 function hasIndicatorComment(node) {
50776 return node && node.indicatorComment;
50779 function hasTrailingComment$2(node) {
50780 return node && node.trailingComment;
50783 function hasEndComments(node) {
50784 return node && node.endComments && node.endComments.length !== 0;
50787 * " a b c d e f " -> [" a b", "c d", "e f "]
50791 function splitWithSingleSpace(text) {
50793 let lastPart = undefined;
50795 for (const part of text.split(/( +)/g)) {
50796 if (part !== " ") {
50797 if (lastPart === " ") {
50800 parts.push((parts.pop() || "") + part);
50802 } else if (lastPart === undefined) {
50809 if (lastPart === " ") {
50810 parts.push((parts.pop() || "") + " ");
50813 if (parts[0] === "") {
50815 parts.unshift(" " + (parts.shift() || ""));
50821 function getFlowScalarLineContents(nodeType, content, options) {
50822 const rawLineContents = content.split("\n").map((lineContent, index, lineContents) => index === 0 && index === lineContents.length - 1 ? lineContent : index !== 0 && index !== lineContents.length - 1 ? lineContent.trim() : index === 0 ? lineContent.trimEnd() : lineContent.trimStart());
50824 if (options.proseWrap === "preserve") {
50825 return rawLineContents.map(lineContent => lineContent.length === 0 ? [] : [lineContent]);
50828 return rawLineContents.map(lineContent => lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent)).reduce((reduced, lineContentWords, index) => index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !( // trailing backslash in quoteDouble should be preserved
50829 nodeType === "quoteDouble" && getLast$5(getLast$5(reduced)).endsWith("\\")) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]), []).map(lineContentWords => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords);
50832 function getBlockValueLineContents(node, {
50837 const content = node.position.start.line === node.position.end.line ? "" : options.originalText.slice(node.position.start.offset, node.position.end.offset) // exclude open line `>` or `|`
50838 .match(/^[^\n]*?\n([\s\S]*)$/)[1];
50839 const leadingSpaceCount = node.indent === null ? (match => match ? match[1].length : Infinity)(content.match(/^( *)\S/m)) : node.indent - 1 + parentIndent;
50840 const rawLineContents = content.split("\n").map(lineContent => lineContent.slice(leadingSpaceCount));
50842 if (options.proseWrap === "preserve" || node.type === "blockLiteral") {
50843 return removeUnnecessaryTrailingNewlines(rawLineContents.map(lineContent => lineContent.length === 0 ? [] : [lineContent]));
50846 return removeUnnecessaryTrailingNewlines(rawLineContents.map(lineContent => lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent)).reduce((reduced, lineContentWords, index) => index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !/^\s/.test(lineContentWords[0]) && !/^\s|\s$/.test(getLast$5(reduced)) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]), []).map(lineContentWords => lineContentWords.reduce((reduced, word) => // disallow trailing spaces
50847 reduced.length !== 0 && /\s$/.test(getLast$5(reduced)) ? reduced.concat(reduced.pop() + " " + word) : reduced.concat(word), [])).map(lineContentWords => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords));
50849 function removeUnnecessaryTrailingNewlines(lineContents) {
50850 if (node.chomping === "keep") {
50851 return getLast$5(lineContents).length === 0 ? lineContents.slice(0, -1) : lineContents;
50854 let trailingNewlineCount = 0;
50856 for (let i = lineContents.length - 1; i >= 0; i--) {
50857 if (lineContents[i].length === 0) {
50858 trailingNewlineCount++;
50864 return trailingNewlineCount === 0 ? lineContents : trailingNewlineCount >= 2 && !isLastDescendant ? // next empty line
50865 lineContents.slice(0, -(trailingNewlineCount - 1)) : lineContents.slice(0, -trailingNewlineCount);
50870 getLast: getLast$5,
50876 isNextLineEmpty: isNextLineEmpty$5,
50877 isLastDescendantNode,
50878 getBlockValueLineContents,
50879 getFlowScalarLineContents,
50880 getLastDescendantNode: getLastDescendantNode$1,
50881 hasPrettierIgnore: hasPrettierIgnore$7,
50882 hasLeadingComments,
50884 hasIndicatorComment,
50885 hasTrailingComment: hasTrailingComment$2,
50890 insertPragma: insertPragma$9,
50891 isPragma: isPragma$1
50894 getAncestorCount: getAncestorCount$1,
50895 getBlockValueLineContents: getBlockValueLineContents$1,
50896 getFlowScalarLineContents: getFlowScalarLineContents$1,
50897 getLast: getLast$6,
50898 getLastDescendantNode: getLastDescendantNode$2,
50899 hasLeadingComments: hasLeadingComments$1,
50900 hasMiddleComments: hasMiddleComments$1,
50901 hasIndicatorComment: hasIndicatorComment$1,
50902 hasTrailingComment: hasTrailingComment$3,
50903 hasEndComments: hasEndComments$1,
50904 hasPrettierIgnore: hasPrettierIgnore$8,
50905 isLastDescendantNode: isLastDescendantNode$1,
50906 isNextLineEmpty: isNextLineEmpty$6,
50908 isEmptyNode: isEmptyNode$1,
50909 defineShortcut: defineShortcut$1,
50912 const docBuilders$2 = document.builders;
50914 conditionalGroup: conditionalGroup$2,
50915 breakParent: breakParent$5,
50918 dedentToRoot: dedentToRoot$3,
50921 hardline: hardline$d,
50922 ifBreak: ifBreak$8,
50925 lineSuffix: lineSuffix$2,
50926 literalline: literalline$7,
50927 markAsRoot: markAsRoot$5,
50928 softline: softline$8
50931 replaceEndOfLineWith: replaceEndOfLineWith$3
50934 function preprocess$3(ast) {
50935 return mapNode$1(ast, defineShortcuts);
50938 function defineShortcuts(node) {
50939 switch (node.type) {
50941 defineShortcut$1(node, "head", () => node.children[0]);
50942 defineShortcut$1(node, "body", () => node.children[1]);
50945 case "documentBody":
50946 case "sequenceItem":
50947 case "flowSequenceItem":
50949 case "mappingValue":
50950 defineShortcut$1(node, "content", () => node.children[0]);
50953 case "mappingItem":
50954 case "flowMappingItem":
50955 defineShortcut$1(node, "key", () => node.children[0]);
50956 defineShortcut$1(node, "value", () => node.children[1]);
50963 function genericPrint$6(path, options, print) {
50964 const node = path.getValue();
50965 const parentNode = path.getParentNode();
50966 const tag = !node.tag ? "" : path.call(print, "tag");
50967 const anchor = !node.anchor ? "" : path.call(print, "anchor");
50968 const nextEmptyLine = isNode$1(node, ["mapping", "sequence", "comment", "directive", "mappingItem", "sequenceItem"]) && !isLastDescendantNode$1(path) ? printNextEmptyLine(path, options.originalText) : "";
50969 return concat$h([node.type !== "mappingValue" && hasLeadingComments$1(node) ? concat$h([join$c(hardline$d, path.map(print, "leadingComments")), hardline$d]) : "", tag, tag && anchor ? " " : "", anchor, tag || anchor ? isNode$1(node, ["sequence", "mapping"]) && !hasMiddleComments$1(node) ? hardline$d : " " : "", hasMiddleComments$1(node) ? concat$h([node.middleComments.length === 1 ? "" : hardline$d, join$c(hardline$d, path.map(print, "middleComments")), hardline$d]) : "", hasPrettierIgnore$8(path) ? concat$h(replaceEndOfLineWith$3(options.originalText.slice(node.position.start.offset, node.position.end.offset), literalline$7)) : group$g(_print(node, parentNode, path, options, print)), hasTrailingComment$3(node) && !isNode$1(node, ["document", "documentHead"]) ? lineSuffix$2(concat$h([node.type === "mappingValue" && !node.content ? "" : " ", parentNode.type === "mappingKey" && path.getParentNode(2).type === "mapping" && isInlineNode(node) ? "" : breakParent$5, path.call(print, "trailingComment")])) : "", nextEmptyLine, hasEndComments$1(node) && !isNode$1(node, ["documentHead", "documentBody"]) ? align$3(node.type === "sequenceItem" ? 2 : 0, concat$h([hardline$d, join$c(hardline$d, path.map(print, "endComments"))])) : ""]);
50972 function _print(node, parentNode, path, options, print) {
50973 switch (node.type) {
50975 return concat$h([join$c(hardline$d, path.map((childPath, index) => {
50976 const document = node.children[index];
50977 const nextDocument = node.children[index + 1];
50978 return concat$h([print(childPath), shouldPrintDocumentEndMarker(document, nextDocument) ? concat$h([hardline$d, "...", hasTrailingComment$3(document) ? concat$h([" ", path.call(print, "trailingComment")]) : ""]) : !nextDocument || hasTrailingComment$3(nextDocument.head) ? "" : concat$h([hardline$d, "---"])]);
50979 }, "children")), node.children.length === 0 || (lastDescendantNode => isNode$1(lastDescendantNode, ["blockLiteral", "blockFolded"]) && lastDescendantNode.chomping === "keep")(getLastDescendantNode$2(node)) ? "" : hardline$d]);
50983 const nextDocument = parentNode.children[path.getName() + 1];
50984 return join$c(hardline$d, [shouldPrintDocumentHeadEndMarker(node, nextDocument, parentNode, options) === "head" ? join$c(hardline$d, [node.head.children.length === 0 && node.head.endComments.length === 0 ? "" : path.call(print, "head"), concat$h(["---", hasTrailingComment$3(node.head) ? concat$h([" ", path.call(print, "head", "trailingComment")]) : ""])].filter(Boolean)) : "", shouldPrintDocumentBody(node) ? path.call(print, "body") : ""].filter(Boolean));
50987 case "documentHead":
50988 return join$c(hardline$d, [].concat(path.map(print, "children"), path.map(print, "endComments")));
50990 case "documentBody":
50992 const children = join$c(hardline$d, path.map(print, "children")).parts;
50993 const endComments = join$c(hardline$d, path.map(print, "endComments")).parts;
50994 const separator = children.length === 0 || endComments.length === 0 ? "" : (lastDescendantNode => isNode$1(lastDescendantNode, ["blockFolded", "blockLiteral"]) ? lastDescendantNode.chomping === "keep" ? // there's already a newline printed at the end of blockValue (chomping=keep, lastDescendant=true)
50995 "" : // an extra newline for better readability
50996 concat$h([hardline$d, hardline$d]) : hardline$d)(getLastDescendantNode$2(node));
50997 return concat$h([].concat(children, separator, endComments));
51001 return concat$h(["%", join$c(" ", [node.name].concat(node.parameters))]);
51004 return concat$h(["#", node.value]);
51007 return concat$h(["*", node.value]);
51010 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
51013 return concat$h(["&", node.value]);
51016 return printFlowScalarContent(node.type, options.originalText.slice(node.position.start.offset, node.position.end.offset), options);
51018 case "quoteDouble":
51019 case "quoteSingle":
51021 const singleQuote = "'";
51022 const doubleQuote = '"';
51023 const raw = options.originalText.slice(node.position.start.offset + 1, node.position.end.offset - 1);
51025 if (node.type === "quoteSingle" && raw.includes("\\") || node.type === "quoteDouble" && /\\[^"]/.test(raw)) {
51026 // only quoteDouble can use escape chars
51027 // and quoteSingle do not need to escape backslashes
51028 const originalQuote = node.type === "quoteDouble" ? doubleQuote : singleQuote;
51029 return concat$h([originalQuote, printFlowScalarContent(node.type, raw, options), originalQuote]);
51030 } else if (raw.includes(doubleQuote)) {
51031 return concat$h([singleQuote, printFlowScalarContent(node.type, node.type === "quoteDouble" ? raw // double quote needs to be escaped by backslash in quoteDouble
51032 .replace(/\\"/g, doubleQuote).replace(/'/g, singleQuote.repeat(2)) : raw, options), singleQuote]);
51035 if (raw.includes(singleQuote)) {
51036 return concat$h([doubleQuote, printFlowScalarContent(node.type, node.type === "quoteSingle" ? // single quote needs to be escaped by 2 single quotes in quoteSingle
51037 raw.replace(/''/g, singleQuote) : raw, options), doubleQuote]);
51040 const quote = options.singleQuote ? singleQuote : doubleQuote;
51041 return concat$h([quote, printFlowScalarContent(node.type, raw, options), quote]);
51044 case "blockFolded":
51045 case "blockLiteral":
51047 const parentIndent = getAncestorCount$1(path, ancestorNode => isNode$1(ancestorNode, ["sequence", "mapping"]));
51048 const isLastDescendant = isLastDescendantNode$1(path);
51049 return concat$h([node.type === "blockFolded" ? ">" : "|", node.indent === null ? "" : node.indent.toString(), node.chomping === "clip" ? "" : node.chomping === "keep" ? "+" : "-", hasIndicatorComment$1(node) ? concat$h([" ", path.call(print, "indicatorComment")]) : "", (node.indent === null ? dedent$3 : dedentToRoot$3)(align$3(node.indent === null ? options.tabWidth : node.indent - 1 + parentIndent, concat$h(getBlockValueLineContents$1(node, {
51053 }).reduce((reduced, lineWords, index, lineContents) => reduced.concat(index === 0 ? hardline$d : "", fill$7(join$c(line$b, lineWords).parts), index !== lineContents.length - 1 ? lineWords.length === 0 ? hardline$d : markAsRoot$5(literalline$7) : node.chomping === "keep" && isLastDescendant ? lineWords.length === 0 ? dedentToRoot$3(hardline$d) : dedentToRoot$3(literalline$7) : ""), []))))]);
51057 return join$c(hardline$d, path.map(print, "children"));
51059 case "sequenceItem":
51060 return concat$h(["- ", align$3(2, !node.content ? "" : path.call(print, "content"))]);
51063 return !node.content ? "" : path.call(print, "content");
51065 case "mappingValue":
51066 return !node.content ? "" : path.call(print, "content");
51069 return join$c(hardline$d, path.map(print, "children"));
51071 case "mappingItem":
51072 case "flowMappingItem":
51074 const isEmptyMappingKey = isEmptyNode$1(node.key);
51075 const isEmptyMappingValue = isEmptyNode$1(node.value);
51077 if (isEmptyMappingKey && isEmptyMappingValue) {
51078 return concat$h([": "]);
51081 const key = path.call(print, "key");
51082 const value = path.call(print, "value");
51084 if (isEmptyMappingValue) {
51085 return node.type === "flowMappingItem" && parentNode.type === "flowMapping" ? key : node.type === "mappingItem" && isAbsolutelyPrintedAsSingleLineNode(node.key.content, options) && !hasTrailingComment$3(node.key.content) && (!parentNode.tag || parentNode.tag.value !== "tag:yaml.org,2002:set") ? concat$h([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ":"]) : concat$h(["? ", align$3(2, key)]);
51088 if (isEmptyMappingKey) {
51089 return concat$h([": ", align$3(2, value)]);
51092 const groupId = Symbol("mappingKey");
51093 const forceExplicitKey = hasLeadingComments$1(node.value) || !isInlineNode(node.key.content);
51094 return forceExplicitKey ? concat$h(["? ", align$3(2, key), hardline$d, join$c("", path.map(print, "value", "leadingComments").map(comment => concat$h([comment, hardline$d]))), ": ", align$3(2, value)]) : // force singleline
51095 isSingleLineNode(node.key.content) && !hasLeadingComments$1(node.key.content) && !hasMiddleComments$1(node.key.content) && !hasTrailingComment$3(node.key.content) && !hasEndComments$1(node.key) && !hasLeadingComments$1(node.value.content) && !hasMiddleComments$1(node.value.content) && !hasEndComments$1(node.value) && isAbsolutelyPrintedAsSingleLineNode(node.value.content, options) ? concat$h([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ": ", value]) : conditionalGroup$2([concat$h([group$g(concat$h([ifBreak$8("? "), group$g(align$3(2, key), {
51097 })])), ifBreak$8(concat$h([hardline$d, ": ", align$3(2, value)]), indent(concat$h([needsSpaceInFrontOfMappingValue(node) ? " " : "", ":", hasLeadingComments$1(node.value.content) || hasEndComments$1(node.value) && node.value.content && !isNode$1(node.value.content, ["mapping", "sequence"]) || parentNode.type === "mapping" && hasTrailingComment$3(node.key.content) && isInlineNode(node.value.content) || isNode$1(node.value.content, ["mapping", "sequence"]) && node.value.content.tag === null && node.value.content.anchor === null ? hardline$d : !node.value.content ? "" : line$b, value])), {
51102 case "flowMapping":
51103 case "flowSequence":
51105 const openMarker = node.type === "flowMapping" ? "{" : "[";
51106 const closeMarker = node.type === "flowMapping" ? "}" : "]";
51107 const bracketSpacing = node.type === "flowMapping" && node.children.length !== 0 && options.bracketSpacing ? line$b : softline$8;
51109 const isLastItemEmptyMappingItem = node.children.length !== 0 && (lastItem => lastItem.type === "flowMappingItem" && isEmptyNode$1(lastItem.key) && isEmptyNode$1(lastItem.value))(getLast$6(node.children));
51111 return concat$h([openMarker, indent(concat$h([bracketSpacing, concat$h(path.map((childPath, index) => concat$h([print(childPath), index === node.children.length - 1 ? "" : concat$h([",", line$b, node.children[index].position.start.line !== node.children[index + 1].position.start.line ? printNextEmptyLine(childPath, options.originalText) : ""])]), "children")), ifBreak$8(",", "")])), isLastItemEmptyMappingItem ? "" : bracketSpacing, closeMarker]);
51114 case "flowSequenceItem":
51115 return path.call(print, "content");
51116 // istanbul ignore next
51119 throw new Error(`Unexpected node type ${node.type}`);
51122 function indent(doc) {
51123 return docBuilders$2.align(" ".repeat(options.tabWidth), doc);
51127 function align$3(n, doc) {
51128 return typeof n === "number" && n > 0 ? docBuilders$2.align(" ".repeat(n), doc) : docBuilders$2.align(n, doc);
51131 function isInlineNode(node) {
51136 switch (node.type) {
51138 case "quoteDouble":
51139 case "quoteSingle":
51141 case "flowMapping":
51142 case "flowSequence":
51150 function isSingleLineNode(node) {
51155 switch (node.type) {
51157 case "quoteDouble":
51158 case "quoteSingle":
51159 return node.position.start.line === node.position.end.line;
51169 function shouldPrintDocumentBody(document) {
51170 return document.body.children.length !== 0 || hasEndComments$1(document.body);
51173 function shouldPrintDocumentEndMarker(document, nextDocument) {
51176 *... # trailingComment
51178 hasTrailingComment$3(document) || nextDocument && (
51184 nextDocument.head.children.length !== 0 ||
51190 hasEndComments$1(nextDocument.head))
51194 function shouldPrintDocumentHeadEndMarker(document, nextDocument, root, options) {
51198 * preserve the first document head end marker
51200 root.children[0] === document && /---(\s|$)/.test(options.originalText.slice(options.locStart(document), options.locStart(document) + 4)) ||
51205 document.head.children.length !== 0 ||
51210 hasEndComments$1(document.head) ||
51212 * --- # trailing comment
51214 hasTrailingComment$3(document.head)) {
51218 if (shouldPrintDocumentEndMarker(document, nextDocument)) {
51222 return nextDocument ? "root" : false;
51225 function isAbsolutelyPrintedAsSingleLineNode(node, options) {
51230 switch (node.type) {
51232 case "quoteSingle":
51233 case "quoteDouble":
51243 if (options.proseWrap === "preserve") {
51244 return node.position.start.line === node.position.end.line;
51247 if ( // backslash-newline
51248 /\\$/m.test(options.originalText.slice(node.position.start.offset, node.position.end.offset))) {
51252 switch (options.proseWrap) {
51254 return !node.value.includes("\n");
51257 return !/[\n ]/.test(node.value);
51258 // istanbul ignore next
51265 function needsSpaceInFrontOfMappingValue(node) {
51266 return node.key.content && node.key.content.type === "alias";
51269 function printNextEmptyLine(path, originalText) {
51270 const node = path.getValue();
51271 const root = path.stack[0];
51272 root.isNextEmptyLinePrintedChecklist = root.isNextEmptyLinePrintedChecklist || [];
51274 if (!root.isNextEmptyLinePrintedChecklist[node.position.end.line]) {
51275 if (isNextLineEmpty$6(node, originalText)) {
51276 root.isNextEmptyLinePrintedChecklist[node.position.end.line] = true;
51284 function printFlowScalarContent(nodeType, content, options) {
51285 const lineContents = getFlowScalarLineContents$1(nodeType, content, options);
51286 return join$c(hardline$d, lineContents.map(lineContentWords => fill$7(join$c(line$b, lineContentWords).parts)));
51289 function clean$7(node, newNode
51292 if (isNode$1(newNode)) {
51293 delete newNode.position;
51295 switch (newNode.type) {
51298 if (isPragma$1(newNode.value)) {
51304 case "quoteDouble":
51305 case "quoteSingle":
51306 newNode.type = "quote";
51312 var printerYaml = {
51313 preprocess: preprocess$3,
51314 print: genericPrint$6,
51315 massageAstNode: clean$7,
51316 insertPragma: insertPragma$9
51320 bracketSpacing: commonOptions.bracketSpacing,
51321 singleQuote: commonOptions.singleQuote,
51322 proseWrap: commonOptions.proseWrap
51325 var name$i = "YAML";
51326 var type$g = "data";
51327 var tmScope$g = "source.yaml";
51331 var extensions$g = [
51339 ".yaml-tmlanguage",
51343 var filenames$4 = [
51350 var aceMode$g = "yaml";
51351 var codemirrorMode$c = "yaml";
51352 var codemirrorMimeType$c = "text/x-yaml";
51353 var languageId$g = 407;
51357 tmScope: tmScope$g,
51358 aliases: aliases$6,
51359 extensions: extensions$g,
51360 filenames: filenames$4,
51361 aceMode: aceMode$g,
51362 codemirrorMode: codemirrorMode$c,
51363 codemirrorMimeType: codemirrorMimeType$c,
51364 languageId: languageId$g
51367 var YAML$1 = /*#__PURE__*/Object.freeze({
51371 tmScope: tmScope$g,
51372 aliases: aliases$6,
51373 extensions: extensions$g,
51374 filenames: filenames$4,
51375 aceMode: aceMode$g,
51376 codemirrorMode: codemirrorMode$c,
51377 codemirrorMimeType: codemirrorMimeType$c,
51378 languageId: languageId$g,
51382 var require$$0$7 = getCjsExportFromNamespace(YAML$1);
51384 const languages$6 = [createLanguage(require$$0$7, data => ({
51387 vscodeLanguageIds: ["yaml"],
51388 // yarn.lock is not YAML: https://github.com/yarnpkg/yarn/issues/5629
51389 filenames: data.filenames.filter(filename => filename !== "yarn.lock")
51391 var languageYaml = {
51392 languages: languages$6,
51399 // plugin will look for `eval("require")()` and transform to `require()` in the bundle,
51400 // and rewrite the paths to require from the top-level.
51401 // We need to list the parsers and getters so we can load them only when necessary.
51404 var internalPlugins = [// JS
51409 return require("./parser-babel").parsers.babel;
51412 get "babel-flow"() {
51413 return require("./parser-babel").parsers["babel-flow"];
51417 return require("./parser-babel").parsers["babel-ts"];
51421 return require("./parser-babel").parsers.json;
51425 return require("./parser-babel").parsers.json5;
51428 get "json-stringify"() {
51429 return require("./parser-babel").parsers["json-stringify"];
51432 get __js_expression() {
51433 return require("./parser-babel").parsers.__js_expression;
51436 get __vue_expression() {
51437 return require("./parser-babel").parsers.__vue_expression;
51440 get __vue_event_binding() {
51441 return require("./parser-babel").parsers.__vue_event_binding;
51446 return require("./parser-flow").parsers.flow;
51451 return require("./parser-typescript").parsers.typescript;
51454 // JS - Angular Action
51455 get __ng_action() {
51456 return require("./parser-angular").parsers.__ng_action;
51459 // JS - Angular Binding
51460 get __ng_binding() {
51461 return require("./parser-angular").parsers.__ng_binding;
51464 // JS - Angular Interpolation
51465 get __ng_interpolation() {
51466 return require("./parser-angular").parsers.__ng_interpolation;
51469 // JS - Angular Directive
51470 get __ng_directive() {
51471 return require("./parser-angular").parsers.__ng_directive;
51478 // TODO: switch these to just `postcss` and use `language` instead.
51480 return require("./parser-postcss").parsers.css;
51484 return require("./parser-postcss").parsers.less;
51488 return require("./parser-postcss").parsers.scss;
51493 languageHandlebars, {
51496 return require("./parser-glimmer").parsers.glimmer;
51504 return require("./parser-graphql").parsers.graphql;
51509 languageMarkdown, {
51512 return require("./parser-markdown").parsers.remark;
51516 return require("./parser-markdown").parsers.remark;
51520 return require("./parser-markdown").parsers.mdx;
51528 return require("./parser-html").parsers.html;
51533 return require("./parser-html").parsers.vue;
51538 return require("./parser-html").parsers.angular;
51541 // Lightning Web Components
51543 return require("./parser-html").parsers.lwc;
51551 return require("./parser-yaml").parsers.yaml;
51557 const memoizedLoad = mem_1(load, {
51558 cacheKey: JSON.stringify
51560 const memoizedSearch = mem_1(findPluginsInNodeModules);
51562 const clearCache$2 = () => {
51563 mem_1.clear(memoizedLoad);
51564 mem_1.clear(memoizedSearch);
51567 function load(plugins, pluginSearchDirs) {
51572 if (!pluginSearchDirs) {
51573 pluginSearchDirs = [];
51574 } // unless pluginSearchDirs are provided, auto-load plugins from node_modules that are parent to Prettier
51577 if (!pluginSearchDirs.length) {
51578 const autoLoadDir = thirdParty.findParentDir(__dirname, "node_modules");
51581 pluginSearchDirs = [autoLoadDir];
51585 const [externalPluginNames, externalPluginInstances] = partition_1(plugins, plugin => typeof plugin === "string");
51586 const externalManualLoadPluginInfos = externalPluginNames.map(pluginName => {
51591 requirePath = resolve_1(path$2.resolve(process.cwd(), pluginName));
51593 // try node modules
51594 requirePath = resolve_1(pluginName, {
51595 paths: [process.cwd()]
51604 const externalAutoLoadPluginInfos = pluginSearchDirs.map(pluginSearchDir => {
51605 const resolvedPluginSearchDir = path$2.resolve(process.cwd(), pluginSearchDir);
51606 const nodeModulesDir = path$2.resolve(resolvedPluginSearchDir, "node_modules"); // In some fringe cases (ex: files "mounted" as virtual directories), the
51607 // isDirectory(resolvedPluginSearchDir) check might be false even though
51608 // the node_modules actually exists.
51610 if (!isDirectory$1(nodeModulesDir) && !isDirectory$1(resolvedPluginSearchDir)) {
51611 throw new Error(`${pluginSearchDir} does not exist or is not a directory`);
51614 return memoizedSearch(nodeModulesDir).map(pluginName => ({
51616 requirePath: resolve_1(pluginName, {
51617 paths: [resolvedPluginSearchDir]
51620 }).reduce((a, b) => a.concat(b), []);
51621 const externalPlugins = uniqBy_1(externalManualLoadPluginInfos.concat(externalAutoLoadPluginInfos), "requirePath").map(externalPluginInfo => Object.assign({
51622 name: externalPluginInfo.name
51623 }, require(externalPluginInfo.requirePath))).concat(externalPluginInstances);
51624 return internalPlugins.concat(externalPlugins);
51627 function findPluginsInNodeModules(nodeModulesDir) {
51628 const pluginPackageJsonPaths = globby$1.sync(["prettier-plugin-*/package.json", "@*/prettier-plugin-*/package.json", "@prettier/plugin-*/package.json"], {
51629 cwd: nodeModulesDir,
51630 expandDirectories: false
51632 return pluginPackageJsonPaths.map(path$2.dirname);
51635 function isDirectory$1(dir) {
51637 return fs$3.statSync(dir).isDirectory();
51643 var loadPlugins = {
51644 loadPlugins: memoizedLoad,
51645 clearCache: clearCache$2
51652 getSupportInfo: getSupportInfo$2
51655 function _withPlugins(fn, optsArgIdx = 1 // Usually `opts` is the 2nd argument
51657 return (...args) => {
51658 const opts = args[optsArgIdx] || {};
51659 args[optsArgIdx] = Object.assign({}, opts, {
51660 plugins: loadPlugins.loadPlugins(opts.plugins, opts.pluginSearchDirs)
51662 return fn(...args);
51666 function withPlugins(fn, optsArgIdx) {
51667 const resultingFn = _withPlugins(fn, optsArgIdx);
51671 resultingFn.sync = _withPlugins(fn.sync, optsArgIdx);
51674 return resultingFn;
51677 const formatWithCursor = withPlugins(core.formatWithCursor);
51681 format(text, opts) {
51682 return formatWithCursor(text, opts).formatted;
51685 check(text, opts) {
51688 } = formatWithCursor(text, opts);
51689 return formatted === text;
51693 resolveConfig: resolveConfig_1.resolveConfig,
51694 resolveConfigFile: resolveConfig_1.resolveConfigFile,
51696 clearConfigCache() {
51697 resolveConfig_1.clearCache();
51698 loadPlugins.clearCache();
51702 /** @type {typeof getFileInfo} */
51703 withPlugins(getFileInfo_1),
51705 /** @type {typeof getSupportInfo} */
51706 withPlugins(getSupportInfo$2, 0),
51707 version: version$2,
51710 /* istanbul ignore next */
51712 parse: withPlugins(core.parse),
51713 formatAST: withPlugins(core.formatAST),
51714 formatDoc: withPlugins(core.formatDoc),
51715 printToDoc: withPlugins(core.printToDoc),
51716 printDocToString: withPlugins(core.printDocToString)
51720 var prettier = src$1;
51723 // The index of the current character
51725 // The current character
51737 error$1 = function (m) {
51738 // Call error when something is wrong.
51740 name: 'SyntaxError',
51746 next = function (c) {
51747 // If a c parameter is provided, verify that it matches the current character.
51748 if (c && c !== ch) {
51749 error$1("Expected '" + c + "' instead of '" + ch + "'");
51750 } // Get the next character. When there are no more characters,
51751 // return the empty string.
51754 ch = text.charAt(at);
51758 number$1 = function () {
51759 // Parse a number value.
51768 while (ch >= '0' && ch <= '9') {
51776 while (next() && ch >= '0' && ch <= '9') {
51781 if (ch === 'e' || ch === 'E') {
51785 if (ch === '-' || ch === '+') {
51790 while (ch >= '0' && ch <= '9') {
51798 if (!isFinite(number)) {
51799 error$1("Bad number");
51804 string$2 = function () {
51805 // Parse a string value.
51809 uffff; // When parsing for string values, we must look for " and \ characters.
51816 } else if (ch === '\\') {
51822 for (i = 0; i < 4; i += 1) {
51823 hex = parseInt(next(), 16);
51825 if (!isFinite(hex)) {
51829 uffff = uffff * 16 + hex;
51832 string += String.fromCharCode(uffff);
51833 } else if (typeof escapee[ch] === 'string') {
51834 string += escapee[ch];
51844 error$1("Bad string");
51846 white = function () {
51847 // Skip whitespace.
51848 while (ch && ch <= ' ') {
51852 word = function () {
51853 // true, false, or null.
51878 error$1("Unexpected '" + ch + "'");
51881 // Place holder for the value function.
51882 array$3 = function () {
51883 // Parse an array value.
51892 return array; // empty array
51896 array.push(value());
51909 error$1("Bad array");
51911 object$1 = function () {
51912 // Parse an object value.
51922 return object; // empty object
51930 if (Object.hasOwnProperty.call(object, key)) {
51931 error$1('Duplicate key "' + key + '"');
51934 object[key] = value();
51947 error$1("Bad object");
51950 value = function () {
51951 // Parse a JSON value. It could be an object, an array, a string, a number,
51969 return ch >= '0' && ch <= '9' ? number$1() : word();
51971 }; // Return the json_parse function. It will have access to all of the above
51972 // functions and variables.
51975 var parse$7 = function (source, reviver) {
51984 error$1("Syntax error");
51985 } // If there is a reviver function, we recursively walk the new structure,
51986 // passing each name/value pair to the reviver function for possible
51987 // transformation, starting with a temporary root object that holds the result
51988 // in an empty key. If there is not a reviver function, we simply return the
51992 return typeof reviver === 'function' ? function walk(holder, key) {
51995 value = holder[key];
51997 if (value && typeof value === 'object') {
51999 if (Object.prototype.hasOwnProperty.call(value, k)) {
52000 v = walk(value, k);
52002 if (v !== undefined) {
52011 return reviver.call(holder, key, value);
52017 var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
52021 // table of character substitutions
52032 function quote(string) {
52033 // If the string contains no control characters, no quote characters, and no
52034 // backslash characters, then we can safely slap some quotes around it.
52035 // Otherwise we must also replace the offending characters with safe escape
52037 escapable.lastIndex = 0;
52038 return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
52040 return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
52041 }) + '"' : '"' + string + '"';
52044 function str(key, holder) {
52045 // Produce a string from holder[key].
52047 // The loop counter.
52051 // The member value.
52055 value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value.
52057 if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
52058 value = value.toJSON(key);
52059 } // If we were called with a replacer function, then call the replacer to
52060 // obtain a replacement value.
52063 if (typeof rep === 'function') {
52064 value = rep.call(holder, key, value);
52065 } // What happens next depends on the value's type.
52068 switch (typeof value) {
52070 return quote(value);
52073 // JSON numbers must be finite. Encode non-finite numbers as null.
52074 return isFinite(value) ? String(value) : 'null';
52078 // If the value is a boolean or null, convert it to a string. Note:
52079 // typeof null does not produce 'null'. The case is included here in
52080 // the remote chance that this gets fixed someday.
52081 return String(value);
52084 if (!value) return 'null';
52086 partial = []; // Array.isArray
52088 if (Object.prototype.toString.apply(value) === '[object Array]') {
52089 length = value.length;
52091 for (i = 0; i < length; i += 1) {
52092 partial[i] = str(i, value) || 'null';
52093 } // Join all of the elements together, separated with commas, and
52094 // wrap them in brackets.
52097 v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']';
52100 } // If the replacer is an array, use it to select the members to be
52104 if (rep && typeof rep === 'object') {
52105 length = rep.length;
52107 for (i = 0; i < length; i += 1) {
52110 if (typeof k === 'string') {
52114 partial.push(quote(k) + (gap ? ': ' : ':') + v);
52119 // Otherwise, iterate through all of the keys in the object.
52121 if (Object.prototype.hasOwnProperty.call(value, k)) {
52125 partial.push(quote(k) + (gap ? ': ' : ':') + v);
52129 } // Join all of the member texts together, separated with commas,
52130 // and wrap them in braces.
52133 v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}';
52139 var stringify$3 = function (value, replacer, space) {
52142 indent$a = ''; // If the space parameter is a number, make an indent string containing that
52145 if (typeof space === 'number') {
52146 for (i = 0; i < space; i += 1) {
52149 } // If the space parameter is a string, it will be used as the indent string.
52150 else if (typeof space === 'string') {
52152 } // If there is a replacer, it must be a function or an array.
52153 // Otherwise, throw an error.
52158 if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) {
52159 throw new Error('JSON.stringify');
52160 } // Make a fake root object containing our value under the key of ''.
52161 // Return the result of stringifying the value.
52169 var parse$8 = parse$7;
52170 var stringify$4 = stringify$3;
52173 stringify: stringify$4
52176 var json$2 = typeof JSON !== 'undefined' ? JSON : jsonify;
52178 var jsonStableStringify = function (obj, opts) {
52179 if (!opts) opts = {};
52180 if (typeof opts === 'function') opts = {
52183 var space = opts.space || '';
52184 if (typeof space === 'number') space = Array(space + 1).join(' ');
52185 var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false;
52187 var replacer = opts.replacer || function (key, value) {
52191 var cmp = opts.cmp && function (f) {
52192 return function (node) {
52193 return function (a, b) {
52202 return f(aobj, bobj);
52208 return function stringify(parent, key, node, level) {
52209 var indent = space ? '\n' + new Array(level + 1).join(space) : '';
52210 var colonSeparator = space ? ': ' : ':';
52212 if (node && node.toJSON && typeof node.toJSON === 'function') {
52213 node = node.toJSON();
52216 node = replacer.call(parent, key, node);
52218 if (node === undefined) {
52222 if (typeof node !== 'object' || node === null) {
52223 return json$2.stringify(node);
52226 if (isArray$2(node)) {
52229 for (var i = 0; i < node.length; i++) {
52230 var item = stringify(node, i, node[i], level + 1) || json$2.stringify(null);
52231 out.push(indent + space + item);
52234 return '[' + out.join(',') + indent + ']';
52236 if (seen.indexOf(node) !== -1) {
52237 if (cycles) return json$2.stringify('__cycle__');
52238 throw new TypeError('Converting circular structure to JSON');
52239 } else seen.push(node);
52241 var keys = objectKeys(node).sort(cmp && cmp(node));
52244 for (var i = 0; i < keys.length; i++) {
52246 var value = stringify(node, key, node[key], level + 1);
52247 if (!value) continue;
52248 var keyValue = json$2.stringify(key) + colonSeparator + value;
52249 out.push(indent + space + keyValue);
52252 seen.splice(seen.indexOf(node), 1);
52253 return '{' + out.join(',') + indent + '}';
52260 var isArray$2 = Array.isArray || function (x) {
52261 return {}.toString.call(x) === '[object Array]';
52264 var objectKeys = Object.keys || function (obj) {
52265 var has = Object.prototype.hasOwnProperty || function () {
52271 for (var key in obj) {
52272 if (has.call(obj, key)) keys.push(key);
52278 const preserveCamelCase = string => {
52279 let isLastCharLower = false;
52280 let isLastCharUpper = false;
52281 let isLastLastCharUpper = false;
52283 for (let i = 0; i < string.length; i++) {
52284 const character = string[i];
52286 if (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) {
52287 string = string.slice(0, i) + '-' + string.slice(i);
52288 isLastCharLower = false;
52289 isLastLastCharUpper = isLastCharUpper;
52290 isLastCharUpper = true;
52292 } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) {
52293 string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
52294 isLastLastCharUpper = isLastCharUpper;
52295 isLastCharUpper = false;
52296 isLastCharLower = true;
52298 isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character;
52299 isLastLastCharUpper = isLastCharUpper;
52300 isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character;
52307 const camelCase = (input, options) => {
52308 if (!(typeof input === 'string' || Array.isArray(input))) {
52309 throw new TypeError('Expected the input to be `string | string[]`');
52312 options = Object.assign({
52316 const postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x;
52318 if (Array.isArray(input)) {
52319 input = input.map(x => x.trim()).filter(x => x.length).join('-');
52321 input = input.trim();
52324 if (input.length === 0) {
52328 if (input.length === 1) {
52329 return options.pascalCase ? input.toUpperCase() : input.toLowerCase();
52332 const hasUpperCase = input !== input.toLowerCase();
52334 if (hasUpperCase) {
52335 input = preserveCamelCase(input);
52338 input = input.replace(/^[_.\- ]+/, '').toLowerCase().replace(/[_.\- ]+(\w|$)/g, (_, p1) => p1.toUpperCase()).replace(/\d+(\w|$)/g, m => m.toUpperCase());
52339 return postProcess(input);
52342 var camelcase = camelCase; // TODO: Remove this for the next major release
52344 var default_1$3 = camelCase;
52345 camelcase.default = default_1$3;
52348 * dashify <https://github.com/jonschlinkert/dashify>
52350 * Copyright (c) 2015-2017, Jon Schlinkert.
52351 * Released under the MIT License.
52354 var dashify = (str, options) => {
52355 if (typeof str !== 'string') throw new TypeError('expected a string');
52356 return str.trim().replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\W/g, m => /[À-ž]/.test(m) ? m : '-').replace(/^-+|-+$/g, '').replace(/-{2,}/g, m => options && options.condense ? '-' : m).toLowerCase();
52359 var defineProperty$1 = function () {
52361 var func = _getNative(Object, 'defineProperty');
52367 var _defineProperty = defineProperty$1;
52370 * The base implementation of `assignValue` and `assignMergeValue` without
52374 * @param {Object} object The object to modify.
52375 * @param {string} key The key of the property to assign.
52376 * @param {*} value The value to assign.
52379 function baseAssignValue(object, key, value) {
52380 if (key == '__proto__' && _defineProperty) {
52381 _defineProperty(object, key, {
52382 'configurable': true,
52383 'enumerable': true,
52388 object[key] = value;
52392 var _baseAssignValue = baseAssignValue;
52394 /** Used for built-in method references. */
52396 var objectProto$c = Object.prototype;
52397 /** Used to check objects for own properties. */
52399 var hasOwnProperty$b = objectProto$c.hasOwnProperty;
52401 * Assigns `value` to `key` of `object` if the existing value is not equivalent
52402 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
52403 * for equality comparisons.
52406 * @param {Object} object The object to modify.
52407 * @param {string} key The key of the property to assign.
52408 * @param {*} value The value to assign.
52411 function assignValue(object, key, value) {
52412 var objValue = object[key];
52414 if (!(hasOwnProperty$b.call(object, key) && eq_1(objValue, value)) || value === undefined && !(key in object)) {
52415 _baseAssignValue(object, key, value);
52419 var _assignValue = assignValue;
52422 * The base implementation of `_.set`.
52425 * @param {Object} object The object to modify.
52426 * @param {Array|string} path The path of the property to set.
52427 * @param {*} value The value to set.
52428 * @param {Function} [customizer] The function to customize path creation.
52429 * @returns {Object} Returns `object`.
52432 function baseSet(object, path, value, customizer) {
52433 if (!isObject_1(object)) {
52437 path = _castPath(path, object);
52439 length = path.length,
52440 lastIndex = length - 1,
52443 while (nested != null && ++index < length) {
52444 var key = _toKey(path[index]),
52447 if (index != lastIndex) {
52448 var objValue = nested[key];
52449 newValue = customizer ? customizer(objValue, key, nested) : undefined;
52451 if (newValue === undefined) {
52452 newValue = isObject_1(objValue) ? objValue : _isIndex(path[index + 1]) ? [] : {};
52456 _assignValue(nested, key, newValue);
52457 nested = nested[key];
52463 var _baseSet = baseSet;
52466 * The base implementation of `_.pickBy` without support for iteratee shorthands.
52469 * @param {Object} object The source object.
52470 * @param {string[]} paths The property paths to pick.
52471 * @param {Function} predicate The function invoked per property.
52472 * @returns {Object} Returns the new object.
52475 function basePickBy(object, paths, predicate) {
52477 length = paths.length,
52480 while (++index < length) {
52481 var path = paths[index],
52482 value = _baseGet(object, path);
52484 if (predicate(value, path)) {
52485 _baseSet(result, _castPath(path, object), value);
52492 var _basePickBy = basePickBy;
52495 * The base implementation of `_.pick` without support for individual
52496 * property identifiers.
52499 * @param {Object} object The source object.
52500 * @param {string[]} paths The property paths to pick.
52501 * @returns {Object} Returns the new object.
52504 function basePick(object, paths) {
52505 return _basePickBy(object, paths, function (value, path) {
52506 return hasIn_1(object, path);
52510 var _basePick = basePick;
52512 /** Built-in value references. */
52514 var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
52516 * Checks if `value` is a flattenable `arguments` object or array.
52519 * @param {*} value The value to check.
52520 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
52523 function isFlattenable(value) {
52524 return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
52527 var _isFlattenable = isFlattenable;
52530 * The base implementation of `_.flatten` with support for restricting flattening.
52533 * @param {Array} array The array to flatten.
52534 * @param {number} depth The maximum recursion depth.
52535 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
52536 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
52537 * @param {Array} [result=[]] The initial result value.
52538 * @returns {Array} Returns the new flattened array.
52541 function baseFlatten(array, depth, predicate, isStrict, result) {
52543 length = array.length;
52544 predicate || (predicate = _isFlattenable);
52545 result || (result = []);
52547 while (++index < length) {
52548 var value = array[index];
52550 if (depth > 0 && predicate(value)) {
52552 // Recursively flatten arrays (susceptible to call stack limits).
52553 baseFlatten(value, depth - 1, predicate, isStrict, result);
52555 _arrayPush(result, value);
52557 } else if (!isStrict) {
52558 result[result.length] = value;
52565 var _baseFlatten = baseFlatten;
52568 * Flattens `array` a single level deep.
52574 * @param {Array} array The array to flatten.
52575 * @returns {Array} Returns the new flattened array.
52578 * _.flatten([1, [2, [3, [4]], 5]]);
52579 * // => [1, 2, [3, [4]], 5]
52582 function flatten(array) {
52583 var length = array == null ? 0 : array.length;
52584 return length ? _baseFlatten(array, 1) : [];
52587 var flatten_1 = flatten;
52590 * A faster alternative to `Function#apply`, this function invokes `func`
52591 * with the `this` binding of `thisArg` and the arguments of `args`.
52594 * @param {Function} func The function to invoke.
52595 * @param {*} thisArg The `this` binding of `func`.
52596 * @param {Array} args The arguments to invoke `func` with.
52597 * @returns {*} Returns the result of `func`.
52599 function apply(func, thisArg, args) {
52600 switch (args.length) {
52602 return func.call(thisArg);
52605 return func.call(thisArg, args[0]);
52608 return func.call(thisArg, args[0], args[1]);
52611 return func.call(thisArg, args[0], args[1], args[2]);
52614 return func.apply(thisArg, args);
52617 var _apply = apply;
52619 /* Built-in method references for those with the same name as other `lodash` methods. */
52621 var nativeMax = Math.max;
52623 * A specialized version of `baseRest` which transforms the rest array.
52626 * @param {Function} func The function to apply a rest parameter to.
52627 * @param {number} [start=func.length-1] The start position of the rest parameter.
52628 * @param {Function} transform The rest array transform.
52629 * @returns {Function} Returns the new function.
52632 function overRest(func, start, transform) {
52633 start = nativeMax(start === undefined ? func.length - 1 : start, 0);
52634 return function () {
52635 var args = arguments,
52637 length = nativeMax(args.length - start, 0),
52638 array = Array(length);
52640 while (++index < length) {
52641 array[index] = args[start + index];
52645 var otherArgs = Array(start + 1);
52647 while (++index < start) {
52648 otherArgs[index] = args[index];
52651 otherArgs[start] = transform(array);
52652 return _apply(func, this, otherArgs);
52656 var _overRest = overRest;
52659 * Creates a function that returns `value`.
52665 * @param {*} value The value to return from the new function.
52666 * @returns {Function} Returns the new constant function.
52669 * var objects = _.times(2, _.constant({ 'a': 1 }));
52671 * console.log(objects);
52672 * // => [{ 'a': 1 }, { 'a': 1 }]
52674 * console.log(objects[0] === objects[1]);
52677 function constant(value) {
52678 return function () {
52683 var constant_1 = constant;
52686 * The base implementation of `setToString` without support for hot loop shorting.
52689 * @param {Function} func The function to modify.
52690 * @param {Function} string The `toString` result.
52691 * @returns {Function} Returns `func`.
52694 var baseSetToString = !_defineProperty ? identity_1 : function (func, string) {
52695 return _defineProperty(func, 'toString', {
52696 'configurable': true,
52697 'enumerable': false,
52698 'value': constant_1(string),
52702 var _baseSetToString = baseSetToString;
52704 /** Used to detect hot functions by number of calls within a span of milliseconds. */
52705 var HOT_COUNT = 800,
52707 /* Built-in method references for those with the same name as other `lodash` methods. */
52709 var nativeNow = Date.now;
52711 * Creates a function that'll short out and invoke `identity` instead
52712 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
52716 * @param {Function} func The function to restrict.
52717 * @returns {Function} Returns the new shortable function.
52720 function shortOut(func) {
52723 return function () {
52724 var stamp = nativeNow(),
52725 remaining = HOT_SPAN - (stamp - lastCalled);
52726 lastCalled = stamp;
52728 if (remaining > 0) {
52729 if (++count >= HOT_COUNT) {
52730 return arguments[0];
52736 return func.apply(undefined, arguments);
52740 var _shortOut = shortOut;
52743 * Sets the `toString` method of `func` to return `string`.
52746 * @param {Function} func The function to modify.
52747 * @param {Function} string The `toString` result.
52748 * @returns {Function} Returns `func`.
52751 var setToString = _shortOut(_baseSetToString);
52752 var _setToString = setToString;
52755 * A specialized version of `baseRest` which flattens the rest array.
52758 * @param {Function} func The function to apply a rest parameter to.
52759 * @returns {Function} Returns the new function.
52762 function flatRest(func) {
52763 return _setToString(_overRest(func, undefined, flatten_1), func + '');
52766 var _flatRest = flatRest;
52769 * Creates an object composed of the picked `object` properties.
52775 * @param {Object} object The source object.
52776 * @param {...(string|string[])} [paths] The property paths to pick.
52777 * @returns {Object} Returns the new object.
52780 * var object = { 'a': 1, 'b': '2', 'c': 3 };
52782 * _.pick(object, ['a', 'c']);
52783 * // => { 'a': 1, 'c': 3 }
52786 var pick = _flatRest(function (object, paths) {
52787 return object == null ? {} : _basePick(object, paths);
52791 /** Used for built-in method references. */
52793 var objectProto$d = Object.prototype;
52794 /** Used to check objects for own properties. */
52796 var hasOwnProperty$c = objectProto$d.hasOwnProperty;
52798 * Creates an object composed of keys generated from the results of running
52799 * each element of `collection` thru `iteratee`. The order of grouped values
52800 * is determined by the order they occur in `collection`. The corresponding
52801 * value of each key is an array of elements responsible for generating the
52802 * key. The iteratee is invoked with one argument: (value).
52807 * @category Collection
52808 * @param {Array|Object} collection The collection to iterate over.
52809 * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
52810 * @returns {Object} Returns the composed aggregate object.
52813 * _.groupBy([6.1, 4.2, 6.3], Math.floor);
52814 * // => { '4': [4.2], '6': [6.1, 6.3] }
52816 * // The `_.property` iteratee shorthand.
52817 * _.groupBy(['one', 'two', 'three'], 'length');
52818 * // => { '3': ['one', 'two'], '5': ['three'] }
52821 var groupBy = _createAggregator(function (result, value, key) {
52822 if (hasOwnProperty$c.call(result, key)) {
52823 result[key].push(value);
52825 _baseAssignValue(result, key, [value]);
52828 var groupBy_1 = groupBy;
52830 var minimist = function (args, opts) {
52831 if (!opts) opts = {};
52838 if (typeof opts['unknown'] === 'function') {
52839 flags.unknownFn = opts['unknown'];
52842 if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
52843 flags.allBools = true;
52845 [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
52846 flags.bools[key] = true;
52851 Object.keys(opts.alias || {}).forEach(function (key) {
52852 aliases[key] = [].concat(opts.alias[key]);
52853 aliases[key].forEach(function (x) {
52854 aliases[x] = [key].concat(aliases[key].filter(function (y) {
52859 [].concat(opts.string).filter(Boolean).forEach(function (key) {
52860 flags.strings[key] = true;
52862 if (aliases[key]) {
52863 flags.strings[aliases[key]] = true;
52866 var defaults = opts['default'] || {};
52870 Object.keys(flags.bools).forEach(function (key) {
52871 setArg(key, defaults[key] === undefined ? false : defaults[key]);
52875 if (args.indexOf('--') !== -1) {
52876 notFlags = args.slice(args.indexOf('--') + 1);
52877 args = args.slice(0, args.indexOf('--'));
52880 function argDefined(key, arg) {
52881 return flags.allBools && /^--[^=]+$/.test(arg) || flags.strings[key] || flags.bools[key] || aliases[key];
52884 function setArg(key, val, arg) {
52885 if (arg && flags.unknownFn && !argDefined(key, arg)) {
52886 if (flags.unknownFn(arg) === false) return;
52889 var value = !flags.strings[key] && isNumber$2(val) ? Number(val) : val;
52890 setKey(argv, key.split('.'), value);
52891 (aliases[key] || []).forEach(function (x) {
52892 setKey(argv, x.split('.'), value);
52896 function setKey(obj, keys, value) {
52899 for (var i = 0; i < keys.length - 1; i++) {
52901 if (key === '__proto__') return;
52902 if (o[key] === undefined) o[key] = {};
52903 if (o[key] === Object.prototype || o[key] === Number.prototype || o[key] === String.prototype) o[key] = {};
52904 if (o[key] === Array.prototype) o[key] = [];
52908 var key = keys[keys.length - 1];
52909 if (key === '__proto__') return;
52910 if (o === Object.prototype || o === Number.prototype || o === String.prototype) o = {};
52911 if (o === Array.prototype) o = [];
52913 if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
52915 } else if (Array.isArray(o[key])) {
52916 o[key].push(value);
52918 o[key] = [o[key], value];
52922 function aliasIsBoolean(key) {
52923 return aliases[key].some(function (x) {
52924 return flags.bools[x];
52928 for (var i = 0; i < args.length; i++) {
52931 if (/^--.+=/.test(arg)) {
52932 // Using [\s\S] instead of . because js doesn't support the
52933 // 'dotall' regex modifier. See:
52934 // http://stackoverflow.com/a/1068308/13216
52935 var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
52939 if (flags.bools[key]) {
52940 value = value !== 'false';
52943 setArg(key, value, arg);
52944 } else if (/^--no-.+/.test(arg)) {
52945 var key = arg.match(/^--no-(.+)/)[1];
52946 setArg(key, false, arg);
52947 } else if (/^--.+/.test(arg)) {
52948 var key = arg.match(/^--(.+)/)[1];
52949 var next = args[i + 1];
52951 if (next !== undefined && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
52952 setArg(key, next, arg);
52954 } else if (/^(true|false)$/.test(next)) {
52955 setArg(key, next === 'true', arg);
52958 setArg(key, flags.strings[key] ? '' : true, arg);
52960 } else if (/^-[^-]+/.test(arg)) {
52961 var letters = arg.slice(1, -1).split('');
52962 var broken = false;
52964 for (var j = 0; j < letters.length; j++) {
52965 var next = arg.slice(j + 2);
52967 if (next === '-') {
52968 setArg(letters[j], next, arg);
52972 if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
52973 setArg(letters[j], next.split('=')[1], arg);
52978 if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
52979 setArg(letters[j], next, arg);
52984 if (letters[j + 1] && letters[j + 1].match(/\W/)) {
52985 setArg(letters[j], arg.slice(j + 2), arg);
52989 setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
52993 var key = arg.slice(-1)[0];
52995 if (!broken && key !== '-') {
52996 if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
52997 setArg(key, args[i + 1], arg);
52999 } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) {
53000 setArg(key, args[i + 1] === 'true', arg);
53003 setArg(key, flags.strings[key] ? '' : true, arg);
53007 if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
53008 argv._.push(flags.strings['_'] || !isNumber$2(arg) ? arg : Number(arg));
53011 if (opts.stopEarly) {
53012 argv._.push.apply(argv._, args.slice(i + 1));
53019 Object.keys(defaults).forEach(function (key) {
53020 if (!hasKey$1(argv, key.split('.'))) {
53021 setKey(argv, key.split('.'), defaults[key]);
53022 (aliases[key] || []).forEach(function (x) {
53023 setKey(argv, x.split('.'), defaults[key]);
53029 argv['--'] = new Array();
53030 notFlags.forEach(function (key) {
53031 argv['--'].push(key);
53034 notFlags.forEach(function (key) {
53042 function hasKey$1(obj, keys) {
53044 keys.slice(0, -1).forEach(function (key) {
53047 var key = keys[keys.length - 1];
53051 function isNumber$2(x) {
53052 if (typeof x === 'number') return true;
53053 if (/^0x[0-9a-f]+$/i.test(x)) return true;
53054 return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
53057 const PLACEHOLDER = null;
53059 * unspecified boolean flag without default value is parsed as `undefined` instead of `false`
53062 var minimist_1 = function (args, options) {
53063 const boolean = options.boolean || [];
53064 const defaults = options.default || {};
53065 const booleanWithoutDefault = boolean.filter(key => !(key in defaults));
53066 const newDefaults = Object.assign({}, defaults, {}, fromPairs_1(booleanWithoutDefault.map(key => [key, PLACEHOLDER])));
53067 const parsed = minimist(args, Object.assign({}, options, {
53068 default: newDefaults
53070 return fromPairs_1(Object.entries(parsed).filter(([, value]) => value !== PLACEHOLDER));
53073 /** @typedef {import('./util').Context} Context */
53076 * @param {Context} context
53080 function* expandPatterns(context) {
53081 const cwd = process.cwd();
53082 const seen = new Set();
53083 let noResults = true;
53085 for (const pathOrError of expandPatternsInternal(context)) {
53088 if (typeof pathOrError !== "string") {
53093 const relativePath = path$2.relative(cwd, pathOrError); // filter out duplicates
53095 if (seen.has(relativePath)) {
53099 seen.add(relativePath);
53100 yield relativePath;
53104 // If there was no files and no other errors, let's yield a general error.
53106 error: `No matching files. Patterns: ${context.filePatterns.join(" ")}`
53111 * @param {Context} context
53115 function* expandPatternsInternal(context) {
53116 // Ignores files in version control systems directories and `node_modules`
53117 const silentlyIgnoredDirs = {
53121 node_modules: context.argv["with-node-modules"] !== true
53123 const globOptions = {
53125 ignore: Object.keys(silentlyIgnoredDirs).filter(dir => silentlyIgnoredDirs[dir]).map(dir => "**/" + dir)
53127 let supportedFilesGlob;
53128 const cwd = process.cwd();
53129 /** @type {Array<{ type: 'file' | 'dir' | 'glob'; glob: string; input: string; }>} */
53131 const entries = [];
53133 for (const pattern of context.filePatterns) {
53134 const absolutePath = path$2.resolve(cwd, pattern);
53136 if (containsIgnoredPathSegment(absolutePath, cwd, silentlyIgnoredDirs)) {
53140 const stat = statSafeSync(absolutePath);
53143 if (stat.isFile()) {
53146 glob: escapePathForGlob(fixWindowsSlashes(pattern)),
53149 } else if (stat.isDirectory()) {
53152 glob: escapePathForGlob(fixWindowsSlashes(pattern)) + "/" + getSupportedFilesGlob(),
53156 } else if (pattern[0] === "!") {
53157 // convert negative patterns to `ignore` entries
53158 globOptions.ignore.push(fixWindowsSlashes(pattern.slice(1)));
53162 glob: fixWindowsSlashes(pattern),
53176 result = out$3.sync(glob, globOptions);
53181 error: `${errorMessages.globError[type]}: ${input}\n${message}`
53186 if (result.length === 0) {
53188 error: `${errorMessages.emptyResults[type]}: "${input}".`
53191 yield* sortPaths(result);
53195 function getSupportedFilesGlob() {
53196 if (!supportedFilesGlob) {
53197 const extensions = flatten_1(context.languages.map(lang => lang.extensions || []));
53198 const filenames = flatten_1(context.languages.map(lang => lang.filenames || []));
53199 supportedFilesGlob = `**/{${extensions.map(ext => "*" + (ext[0] === "." ? ext : "." + ext)).concat(filenames)}}`;
53202 return supportedFilesGlob;
53206 const errorMessages = {
53208 file: "Unable to resolve file",
53209 dir: "Unable to expand directory",
53210 glob: "Unable to expand glob pattern"
53213 file: "Explicitly specified file was ignored due to negative glob patterns",
53214 dir: "No supported files were found in the directory",
53215 glob: "No files matching the pattern were found"
53219 * @param {string} absolutePath
53220 * @param {string} cwd
53221 * @param {Record<string, boolean>} ignoredDirectories
53224 function containsIgnoredPathSegment(absolutePath, cwd, ignoredDirectories) {
53225 return path$2.relative(cwd, absolutePath).split(path$2.sep).some(dir => ignoredDirectories[dir]);
53228 * @param {string[]} paths
53232 function sortPaths(paths) {
53233 return paths.sort((a, b) => a.localeCompare(b));
53236 * Get stats of a given path.
53237 * @param {string} filePath The path to target file.
53238 * @returns {fs.Stats | undefined} The stats.
53242 function statSafeSync(filePath) {
53244 return fs$3.statSync(filePath);
53246 /* istanbul ignore next */
53247 if (error.code !== "ENOENT") {
53253 * This function should be replaced with `fastGlob.escapePath` when these issues are fixed:
53254 * - https://github.com/mrmlnc/fast-glob/issues/261
53255 * - https://github.com/mrmlnc/fast-glob/issues/262
53256 * @param {string} path
53260 function escapePathForGlob(path) {
53261 return out$3.escapePath(path.replace(/\\/g, "\0") // Workaround for fast-glob#262 (part 1)
53262 ).replace(/\\!/g, "@(!)") // Workaround for fast-glob#261
53263 .replace(/\0/g, "@(\\\\)"); // Workaround for fast-glob#262 (part 2)
53266 const isWindows = path$2.sep === "\\";
53268 * Using backslashes in globs is probably not okay, but not accepting
53269 * backslashes as path separators on Windows is even more not okay.
53270 * https://github.com/prettier/prettier/pull/6776#discussion_r380723717
53271 * https://github.com/mrmlnc/fast-glob#how-to-write-patterns-on-windows
53272 * @param {string} pattern
53275 function fixWindowsSlashes(pattern) {
53276 return isWindows ? pattern.replace(/\\/g, "/") : pattern;
53279 var expandPatterns_1 = expandPatterns;
53281 const categoryOrder = [coreOptions.CATEGORY_OUTPUT, coreOptions.CATEGORY_FORMAT, coreOptions.CATEGORY_CONFIG, coreOptions.CATEGORY_EDITOR, coreOptions.CATEGORY_OTHER];
53285 * // The type of the option. For 'choice', see also `choices` below.
53286 * // When passing a type other than the ones listed below, the option is
53287 * // treated as taking any string as argument, and `--option <${type}>` will
53288 * // be displayed in --help.
53289 * type: "boolean" | "choice" | "int" | string;
53291 * // Default value to be passed to the minimist option `default`.
53294 * // Alias name to be passed to the minimist option `alias`.
53297 * // For grouping options by category in --help.
53298 * category?: string;
53300 * // Description to be displayed in --help. If omitted, the option won't be
53301 * // shown at all in --help (but see also `oppositeDescription` below).
53302 * description?: string;
53304 * // Description for `--no-${name}` to be displayed in --help. If omitted,
53305 * // `--no-${name}` won't be shown.
53306 * oppositeDescription?: string;
53308 * // Indicate if this option is simply passed to the API.
53309 * // true: use camelified name as the API option name.
53310 * // string: use this value as the API option name.
53311 * forwardToApi?: boolean | string;
53313 * // Indicate that a CLI flag should be an array when forwarded to the API.
53316 * // Specify available choices for validation. They will also be displayed
53317 * // in --help as <a|b|c>.
53318 * // Use an object instead of a string if a choice is deprecated and should
53319 * // be treated as `redirect` instead, or if you'd like to add description for
53323 * | { value: string, description?: string, deprecated?: boolean, redirect?: string }
53326 * // If the option has a value that is an exception to the regular value
53327 * // constraints, indicate that value here (or use a function for more
53329 * exception?: ((value: any) => boolean);
53331 * // Indicate that the option is deprecated. Use a string to add an extra
53332 * // message to --help for the option, for example to suggest a replacement
53334 * deprecated?: true | string;
53338 * Note: The options below are sorted alphabetically.
53341 const options$8 = {
53344 category: coreOptions.CATEGORY_OUTPUT,
53346 description: dedent_1`
53347 Check if the given files are formatted, print a human-friendly summary
53348 message and paths to unformatted files (see also --list-different).
53352 // The supports-color package (a sub sub dependency) looks directly at
53353 // `process.argv` for `--no-color` and such-like options. The reason it is
53354 // listed here is to avoid "Ignored unknown option: --no-color" warnings.
53355 // See https://github.com/chalk/supports-color/#info for more information.
53358 description: "Colorize error messages.",
53359 oppositeDescription: "Do not colorize error messages."
53363 category: coreOptions.CATEGORY_CONFIG,
53364 description: "Path to a Prettier configuration file (.prettierrc, package.json, prettier.config.js).",
53365 oppositeDescription: "Do not look for a configuration file.",
53366 exception: value => value === false
53368 "config-precedence": {
53370 category: coreOptions.CATEGORY_CONFIG,
53371 default: "cli-override",
53373 value: "cli-override",
53374 description: "CLI options take precedence over config file"
53376 value: "file-override",
53377 description: "Config file take precedence over CLI options"
53379 value: "prefer-file",
53380 description: dedent_1`
53381 If a config file is found will evaluate it and ignore other CLI options.
53382 If no config file is found CLI options will evaluate as normal.
53385 description: "Define in which order config files and CLI options should be evaluated."
53387 "debug-benchmark": {
53388 // Run the formatting benchmarks. Requires 'benchmark' module to be installed.
53392 // Run the formatting once again on the formatted output, throw if different.
53395 "debug-print-doc": {
53399 // Repeat the formatting a few times and measure the average duration.
53405 category: coreOptions.CATEGORY_CONFIG,
53406 description: "Take .editorconfig into account when parsing configuration.",
53407 oppositeDescription: "Don't take .editorconfig into account when parsing configuration.",
53410 "find-config-path": {
53412 category: coreOptions.CATEGORY_CONFIG,
53413 description: "Find and print the path to a configuration file for the given input file."
53417 description: dedent_1`
53418 Extract the following info (as JSON) for a given file path. Reported fields:
53419 * ignored (boolean) - true if file path is filtered by --ignore-path
53420 * inferredParser (string | null) - name of parser inferred from file path
53426 description: dedent_1`
53427 Show CLI usage, or details about the given flag.
53428 Example: --help write
53430 exception: value => value === ""
53434 category: coreOptions.CATEGORY_CONFIG,
53435 default: ".prettierignore",
53436 description: "Path to a file with patterns describing files to ignore."
53438 "list-different": {
53440 category: coreOptions.CATEGORY_OUTPUT,
53442 description: "Print the names of files that are different from Prettier's formatting (see also --check)."
53446 description: "What level of logs to report.",
53448 choices: ["silent", "error", "warn", "log", "debug"]
53452 description: "Print support information as JSON."
53457 description: "Print Prettier version."
53459 "with-node-modules": {
53461 category: coreOptions.CATEGORY_CONFIG,
53462 description: "Process files inside 'node_modules' directory."
53466 category: coreOptions.CATEGORY_OUTPUT,
53467 description: "Edit files in-place. (Beware!)"
53470 const usageSummary = dedent_1`
53471 Usage: prettier [options] [file/dir/glob ...]
53473 By default, output is written to stdout.
53474 Stdin is read if it is piped to Prettier and no files are given.
53478 options: options$8,
53482 // which causes unwanted lines in the output. An additional check for isCI() helps.
53483 // See https://github.com/prettier/prettier/issues/5801
53486 var isTty = function isTTY() {
53487 return process.stdout.isTTY && !thirdParty.isCI();
53490 const OPTION_USAGE_THRESHOLD = 25;
53491 const CHOICE_USAGE_MARGIN = 3;
53492 const CHOICE_USAGE_INDENTATION = 2;
53494 function getOptions(argv, detailedOptions) {
53495 return fromPairs_1(detailedOptions.filter(({
53497 }) => forwardToApi).map(({
53500 }) => [forwardToApi, argv[name]]));
53503 function cliifyOptions(object, apiDetailedOptionMap) {
53504 return Object.keys(object || {}).reduce((output, key) => {
53505 const apiOption = apiDetailedOptionMap[key];
53506 const cliKey = apiOption ? apiOption.name : key;
53507 output[dashify(cliKey)] = object[key];
53512 function diff(a, b) {
53513 return require$$0.createTwoFilesPatch("", "", a, b, "", "", {
53518 function handleError(context, filename, error) {
53519 if (error instanceof errors.UndefinedParserError) {
53520 if (context.argv.write && isTty()) {
53521 readline$1.clearLine(process.stdout, 0);
53522 readline$1.cursorTo(process.stdout, 0, null);
53525 if (!context.argv.check && !context.argv["list-different"]) {
53526 process.exitCode = 2;
53529 context.logger.error(error.message);
53533 if (context.argv.write) {
53534 // Add newline to split errors from filename line.
53535 process.stdout.write("\n");
53538 const isParseError = Boolean(error && error.loc);
53539 const isValidationError = /^Invalid \S+ value\./.test(error && error.message);
53541 if (isParseError) {
53542 // `invalid.js: SyntaxError: Unexpected token (1:1)`.
53543 context.logger.error(`${filename}: ${String(error)}`);
53544 } else if (isValidationError || error instanceof errors.ConfigError) {
53545 // `Invalid printWidth value. Expected an integer, but received 0.5.`
53546 context.logger.error(error.message); // If validation fails for one file, it will fail for all of them.
53549 } else if (error instanceof errors.DebugError) {
53550 // `invalid.js: Some debug error message`
53551 context.logger.error(`${filename}: ${error.message}`);
53553 // `invalid.js: Error: Some unexpected error\n[stack trace]`
53554 context.logger.error(filename + ": " + (error.stack || error));
53555 } // Don't exit the process if one file failed
53558 process.exitCode = 2;
53561 function logResolvedConfigPathOrDie(context) {
53562 const configFile = prettier.resolveConfigFile.sync(context.argv["find-config-path"]);
53565 context.logger.log(path$2.relative(process.cwd(), configFile));
53571 function logFileInfoOrDie(context) {
53573 ignorePath: context.argv["ignore-path"],
53574 withNodeModules: context.argv["with-node-modules"],
53575 plugins: context.argv.plugin,
53576 pluginSearchDirs: context.argv["plugin-search-dir"]
53578 context.logger.log(prettier.format(jsonStableStringify(prettier.getFileInfo.sync(context.argv["file-info"], options)), {
53583 function writeOutput(context, result, options) {
53584 // Don't use `console.log` here since it adds an extra newline at the end.
53585 process.stdout.write(context.argv["debug-check"] ? result.filepath : result.formatted);
53587 if (options && options.cursorOffset >= 0) {
53588 process.stderr.write(result.cursorOffset + "\n");
53592 function listDifferent(context, input, options, filename) {
53593 if (!context.argv.check && !context.argv["list-different"]) {
53598 if (!options.filepath && !options.parser) {
53599 throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
53602 if (!prettier.check(input, options)) {
53603 if (!context.argv.write) {
53604 context.logger.log(filename);
53605 process.exitCode = 1;
53609 context.logger.error(error.message);
53615 function format$1(context, input, opt) {
53616 if (!opt.parser && !opt.filepath) {
53617 throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
53620 if (context.argv["debug-print-doc"]) {
53621 const doc = prettier.__debug.printToDoc(input, opt);
53624 formatted: prettier.__debug.formatDoc(doc)
53628 if (context.argv["debug-check"]) {
53629 const pp = prettier.format(input, opt);
53630 const pppp = prettier.format(pp, opt);
53633 throw new errors.DebugError("prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp));
53635 const stringify = obj => JSON.stringify(obj, null, 2);
53637 const ast = stringify(prettier.__debug.parse(input, opt,
53640 const past = stringify(prettier.__debug.parse(pp, opt,
53643 /* istanbul ignore next */
53645 if (ast !== past) {
53646 const MAX_AST_SIZE = 2097152; // 2MB
53648 const astDiff = ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE ? "AST diff too large to render" : diff(ast, past);
53649 throw new errors.DebugError("ast(input) !== ast(prettier(input))\n" + astDiff + "\n" + diff(input, pp));
53655 filepath: opt.filepath || "(stdin)\n"
53658 /* istanbul ignore next */
53661 if (context.argv["debug-benchmark"]) {
53665 benchmark = require("benchmark");
53667 context.logger.debug("'--debug-benchmark' requires the 'benchmark' package to be installed.");
53671 context.logger.debug("'--debug-benchmark' option found, measuring formatWithCursor with 'benchmark' module.");
53672 const suite = new benchmark.Suite();
53673 suite.add("format", () => {
53674 prettier.formatWithCursor(input, opt);
53675 }).on("cycle", event => {
53677 benchmark: String(event.target),
53678 hz: event.target.hz,
53679 ms: event.target.times.cycle * 1000
53681 context.logger.debug("'--debug-benchmark' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
53685 } else if (context.argv["debug-repeat"] > 0) {
53686 const repeat = context.argv["debug-repeat"];
53687 context.logger.debug("'--debug-repeat' option found, running formatWithCursor " + repeat + " times."); // should be using `performance.now()`, but only `Date` is cross-platform enough
53689 const now = Date.now ? () => Date.now() : () => +new Date();
53692 for (let i = 0; i < repeat; ++i) {
53693 const startMs = now();
53694 prettier.formatWithCursor(input, opt);
53695 totalMs += now() - startMs;
53698 const averageMs = totalMs / repeat;
53701 hz: 1000 / averageMs,
53704 context.logger.debug("'--debug-repeat' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
53707 return prettier.formatWithCursor(input, opt);
53710 function getOptionsOrDie(context, filePath) {
53712 if (context.argv.config === false) {
53713 context.logger.debug("'--no-config' option found, skip loading config file.");
53717 context.logger.debug(context.argv.config ? `load config file from '${context.argv.config}'` : `resolve config from '${filePath}'`);
53718 const options = prettier.resolveConfig.sync(filePath, {
53719 editorconfig: context.argv.editorconfig,
53720 config: context.argv.config
53722 context.logger.debug("loaded options `" + JSON.stringify(options) + "`");
53725 context.logger.error(`Invalid configuration file \`${filePath}\`: ` + error.message);
53730 function getOptionsForFile(context, filepath) {
53731 const options = getOptionsOrDie(context, filepath);
53732 const hasPlugins = options && options.plugins;
53735 pushContextPlugins(context, options.plugins);
53738 const appliedOptions = Object.assign({
53740 }, applyConfigPrecedence(context, options && optionsNormalizer.normalizeApiOptions(options, context.supportOptions, {
53741 logger: context.logger
53743 context.logger.debug(`applied config-precedence (${context.argv["config-precedence"]}): ` + `${JSON.stringify(appliedOptions)}`);
53746 popContextPlugins(context);
53749 return appliedOptions;
53752 function parseArgsToOptions(context, overrideDefaults) {
53753 const minimistOptions = createMinimistOptions(context.detailedOptions);
53754 const apiDetailedOptionMap = createApiDetailedOptionMap(context.detailedOptions);
53755 return getOptions(optionsNormalizer.normalizeCliOptions(minimist_1(context.args, {
53756 string: minimistOptions.string,
53757 boolean: minimistOptions.boolean,
53758 default: cliifyOptions(overrideDefaults, apiDetailedOptionMap)
53759 }), context.detailedOptions, {
53761 }), context.detailedOptions);
53764 function applyConfigPrecedence(context, options) {
53766 switch (context.argv["config-precedence"]) {
53767 case "cli-override":
53768 return parseArgsToOptions(context, options);
53770 case "file-override":
53771 return Object.assign({}, parseArgsToOptions(context), {}, options);
53773 case "prefer-file":
53774 return options || parseArgsToOptions(context);
53777 context.logger.error(error.toString());
53782 function formatStdin(context) {
53783 const filepath = context.argv["stdin-filepath"] ? path$2.resolve(process.cwd(), context.argv["stdin-filepath"]) : process.cwd();
53784 const ignorer = createIgnorerFromContextOrDie(context); // If there's an ignore-path set, the filename must be relative to the
53785 // ignore path, not the current working directory.
53787 const relativeFilepath = context.argv["ignore-path"] ? path$2.relative(path$2.dirname(context.argv["ignore-path"]), filepath) : path$2.relative(process.cwd(), filepath);
53788 thirdParty.getStream(process.stdin).then(input => {
53789 if (relativeFilepath && ignorer.filter([relativeFilepath]).length === 0) {
53790 writeOutput(context, {
53796 const options = getOptionsForFile(context, filepath);
53798 if (listDifferent(context, input, options, "(stdin)")) {
53802 writeOutput(context, format$1(context, input, options), options);
53803 }).catch(error => {
53804 handleError(context, relativeFilepath || "stdin", error);
53808 function createIgnorerFromContextOrDie(context) {
53810 return createIgnorer_1.sync(context.argv["ignore-path"], context.argv["with-node-modules"]);
53812 context.logger.error(e.message);
53817 function formatFiles(context) {
53818 // The ignorer will be used to filter file paths after the glob is checked,
53819 // before any files are actually written
53820 const ignorer = createIgnorerFromContextOrDie(context);
53821 let numberOfUnformattedFilesFound = 0;
53823 if (context.argv.check) {
53824 context.logger.log("Checking formatting...");
53827 for (const pathOrError of expandPatterns_1(context)) {
53828 if (typeof pathOrError === "object") {
53829 context.logger.error(pathOrError.error); // Don't exit, but set the exit code to 2
53831 process.exitCode = 2;
53835 const filename = pathOrError; // If there's an ignore-path set, the filename must be relative to the
53836 // ignore path, not the current working directory.
53838 const ignoreFilename = context.argv["ignore-path"] ? path$2.relative(path$2.dirname(context.argv["ignore-path"]), filename) : filename;
53839 const fileIgnored = ignorer.filter([ignoreFilename]).length === 0;
53841 if (fileIgnored && (context.argv["debug-check"] || context.argv.write || context.argv.check || context.argv["list-different"])) {
53845 const options = Object.assign({}, getOptionsForFile(context, filename), {
53850 context.logger.log(filename, {
53858 input = fs$3.readFileSync(filename, "utf8");
53860 // Add newline to split errors from filename line.
53861 context.logger.log("");
53862 context.logger.error(`Unable to read file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
53864 process.exitCode = 2;
53869 writeOutput(context, {
53875 const start = Date.now();
53880 result = format$1(context, input, options);
53881 output = result.formatted;
53883 handleError(context, filename, error);
53887 const isDifferent = output !== input;
53890 // Remove previously printed filename to log it with duration.
53891 readline$1.clearLine(process.stdout, 0);
53892 readline$1.cursorTo(process.stdout, 0, null);
53895 if (context.argv.write) {
53896 // Don't write the file if it won't change in order not to invalidate
53897 // mtime based caches.
53899 if (!context.argv.check && !context.argv["list-different"]) {
53900 context.logger.log(`${filename} ${Date.now() - start}ms`);
53904 fs$3.writeFileSync(filename, output, "utf8");
53906 context.logger.error(`Unable to write file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
53908 process.exitCode = 2;
53910 } else if (!context.argv.check && !context.argv["list-different"]) {
53911 context.logger.log(`${source.grey(filename)} ${Date.now() - start}ms`);
53913 } else if (context.argv["debug-check"]) {
53914 if (result.filepath) {
53915 context.logger.log(result.filepath);
53917 process.exitCode = 2;
53919 } else if (!context.argv.check && !context.argv["list-different"]) {
53920 writeOutput(context, result, options);
53923 if ((context.argv.check || context.argv["list-different"]) && isDifferent) {
53924 context.logger.log(filename);
53925 numberOfUnformattedFilesFound += 1;
53927 } // Print check summary based on expected exit code
53930 if (context.argv.check) {
53931 context.logger.log(numberOfUnformattedFilesFound === 0 ? "All matched files use Prettier code style!" : context.argv.write ? "Code style issues fixed in the above file(s)." : "Code style issues found in the above file(s). Forgot to run Prettier?");
53932 } // Ensure non-zero exitCode when using --check/list-different is not combined with --write
53935 if ((context.argv.check || context.argv["list-different"]) && numberOfUnformattedFilesFound > 0 && !process.exitCode && !context.argv.write) {
53936 process.exitCode = 1;
53940 function getOptionsWithOpposites(options) {
53941 // Add --no-foo after --foo.
53942 const optionsWithOpposites = options.map(option => [option.description ? option : null, option.oppositeDescription ? Object.assign({}, option, {
53943 name: `no-${option.name}`,
53945 description: option.oppositeDescription
53947 return flatten_1(optionsWithOpposites).filter(Boolean);
53950 function createUsage(context) {
53951 const options = getOptionsWithOpposites(context.detailedOptions).filter( // remove unnecessary option (e.g. `semi`, `color`, etc.), which is only used for --help <flag>
53952 option => !(option.type === "boolean" && option.oppositeDescription && !option.name.startsWith("no-")));
53953 const groupedOptions = groupBy_1(options, option => option.category);
53954 const firstCategories = constant$1.categoryOrder.slice(0, -1);
53955 const lastCategories = constant$1.categoryOrder.slice(-1);
53956 const restCategories = Object.keys(groupedOptions).filter(category => !constant$1.categoryOrder.includes(category));
53957 const allCategories = [...firstCategories, ...restCategories, ...lastCategories];
53958 const optionsUsage = allCategories.map(category => {
53959 const categoryOptions = groupedOptions[category].map(option => createOptionUsage(context, option, OPTION_USAGE_THRESHOLD)).join("\n");
53960 return `${category} options:\n\n${indent$b(categoryOptions, 2)}`;
53962 return [constant$1.usageSummary].concat(optionsUsage, [""]).join("\n\n");
53965 function createOptionUsage(context, option, threshold) {
53966 const header = createOptionUsageHeader(option);
53967 const optionDefaultValue = getOptionDefaultValue(context, option.name);
53968 return createOptionUsageRow(header, `${option.description}${optionDefaultValue === undefined ? "" : `\nDefaults to ${createDefaultValueDisplay(optionDefaultValue)}.`}`, threshold);
53971 function createDefaultValueDisplay(value) {
53972 return Array.isArray(value) ? `[${value.map(createDefaultValueDisplay).join(", ")}]` : value;
53975 function createOptionUsageHeader(option) {
53976 const name = `--${option.name}`;
53977 const alias = option.alias ? `-${option.alias},` : null;
53978 const type = createOptionUsageType(option);
53979 return [alias, name, type].filter(Boolean).join(" ");
53982 function createOptionUsageRow(header, content, threshold) {
53983 const separator = header.length >= threshold ? `\n${" ".repeat(threshold)}` : " ".repeat(threshold - header.length);
53984 const description = content.replace(/\n/g, `\n${" ".repeat(threshold)}`);
53985 return `${header}${separator}${description}`;
53988 function createOptionUsageType(option) {
53989 switch (option.type) {
53994 return `<${option.choices.filter(choice => !choice.deprecated && choice.since !== null).map(choice => choice.value).join("|")}>`;
53997 return `<${option.type}>`;
54001 function createChoiceUsages(choices, margin, indentation) {
54002 const activeChoices = choices.filter(choice => !choice.deprecated && choice.since !== null);
54003 const threshold = activeChoices.map(choice => choice.value.length).reduce((current, length) => Math.max(current, length), 0) + margin;
54004 return activeChoices.map(choice => indent$b(createOptionUsageRow(choice.value, choice.description, threshold), indentation));
54007 function createDetailedUsage(context, flag) {
54008 const option = getOptionsWithOpposites(context.detailedOptions).find(option => option.name === flag || option.alias === flag);
54009 const header = createOptionUsageHeader(option);
54010 const description = `\n\n${indent$b(option.description, 2)}`;
54011 const choices = option.type !== "choice" ? "" : `\n\nValid options:\n\n${createChoiceUsages(option.choices, CHOICE_USAGE_MARGIN, CHOICE_USAGE_INDENTATION).join("\n")}`;
54012 const optionDefaultValue = getOptionDefaultValue(context, option.name);
54013 const defaults = optionDefaultValue !== undefined ? `\n\nDefault: ${createDefaultValueDisplay(optionDefaultValue)}` : "";
54014 const pluginDefaults = option.pluginDefaults && Object.keys(option.pluginDefaults).length ? `\nPlugin defaults:${Object.keys(option.pluginDefaults).map(key => `\n* ${key}: ${createDefaultValueDisplay(option.pluginDefaults[key])}`)}` : "";
54015 return `${header}${description}${choices}${defaults}${pluginDefaults}`;
54018 function getOptionDefaultValue(context, optionName) {
54020 if (!(optionName in context.detailedOptionMap)) {
54024 const option = context.detailedOptionMap[optionName];
54026 if (option.default !== undefined) {
54027 return option.default;
54030 const optionCamelName = camelcase(optionName);
54032 if (optionCamelName in context.apiDefaultOptions) {
54033 return context.apiDefaultOptions[optionCamelName];
54039 function indent$b(str, spaces) {
54040 return str.replace(/^/gm, " ".repeat(spaces));
54043 function createLogger(logLevel) {
54045 warn: createLogFunc("warn", "yellow"),
54046 error: createLogFunc("error", "red"),
54047 debug: createLogFunc("debug", "blue"),
54048 log: createLogFunc("log")
54051 function createLogFunc(loggerName, color) {
54052 if (!shouldLog(loggerName)) {
54056 const prefix = color ? `[${source[color](loggerName)}] ` : "";
54057 return function (message, opts) {
54058 opts = Object.assign({
54061 const stream = process[loggerName === "log" ? "stdout" : "stderr"];
54062 stream.write(message.replace(/^/gm, prefix) + (opts.newline ? "\n" : ""));
54066 function shouldLog(loggerName) {
54067 switch (logLevel) {
54075 if (loggerName === "debug") {
54082 if (loggerName === "log") {
54089 if (loggerName === "warn") {
54096 return loggerName === "error";
54101 function normalizeDetailedOption(name, option) {
54102 return Object.assign({
54103 category: coreOptions.CATEGORY_OTHER
54105 choices: option.choices && option.choices.map(choice => {
54106 const newChoice = Object.assign({
54109 }, typeof choice === "object" ? choice : {
54113 if (newChoice.value === true) {
54114 newChoice.value = ""; // backward compatibility for original boolean option
54122 function normalizeDetailedOptionMap(detailedOptionMap) {
54123 return fromPairs_1(Object.entries(detailedOptionMap).sort(([leftName], [rightName]) => leftName.localeCompare(rightName)).map(([name, option]) => [name, normalizeDetailedOption(name, option)]));
54126 function createMinimistOptions(detailedOptions) {
54128 // we use vnopts' AliasSchema to handle aliases for better error messages
54130 boolean: detailedOptions.filter(option => option.type === "boolean").map(option => [option.name].concat(option.alias || [])).reduce((a, b) => a.concat(b)),
54131 string: detailedOptions.filter(option => option.type !== "boolean").map(option => [option.name].concat(option.alias || [])).reduce((a, b) => a.concat(b)),
54132 default: detailedOptions.filter(option => !option.deprecated && (!option.forwardToApi || option.name === "plugin" || option.name === "plugin-search-dir") && option.default !== undefined).reduce((current, option) => Object.assign({
54133 [option.name]: option.default
54138 function createApiDetailedOptionMap(detailedOptions) {
54139 return fromPairs_1(detailedOptions.filter(option => option.forwardToApi && option.forwardToApi !== option.name).map(option => [option.forwardToApi, option]));
54142 function createDetailedOptionMap(supportOptions) {
54143 return fromPairs_1(supportOptions.map(option => {
54144 const newOption = Object.assign({}, option, {
54145 name: option.cliName || dashify(option.name),
54146 description: option.cliDescription || option.description,
54147 category: option.cliCategory || coreOptions.CATEGORY_FORMAT,
54148 forwardToApi: option.name
54151 if (option.deprecated) {
54152 delete newOption.forwardToApi;
54153 delete newOption.description;
54154 delete newOption.oppositeDescription;
54155 newOption.deprecated = true;
54158 return [newOption.name, newOption];
54160 } //-----------------------------context-util-start-------------------------------
54163 * @typedef {Object} Context
54165 * @property {string[]} args
54167 * @property {string[]} filePatterns
54168 * @property {any[]} supportOptions
54169 * @property detailedOptions
54170 * @property detailedOptionMap
54171 * @property apiDefaultOptions
54172 * @property languages
54173 * @property {Partial<Context>[]} stack
54176 /** @returns {Context} */
54179 function createContext(args) {
54184 updateContextArgv(context);
54185 normalizeContextArgv(context, ["loglevel", "plugin", "plugin-search-dir"]);
54186 context.logger = createLogger(context.argv.loglevel);
54187 updateContextArgv(context, context.argv.plugin, context.argv["plugin-search-dir"]);
54189 /** @type {Context} */
54194 function initContext(context) {
54195 // split into 2 step so that we could wrap this in a `try..catch` in cli/index.js
54196 normalizeContextArgv(context);
54199 * @param {Context} context
54200 * @param {string[]} plugins
54201 * @param {string[]=} pluginSearchDirs
54205 function updateContextOptions(context, plugins, pluginSearchDirs) {
54207 options: supportOptions,
54209 } = prettier.getSupportInfo({
54210 showDeprecated: true,
54211 showUnreleased: true,
54212 showInternal: true,
54216 const detailedOptionMap = normalizeDetailedOptionMap(Object.assign({}, createDetailedOptionMap(supportOptions), {}, constant$1.options));
54217 const detailedOptions = arrayify(detailedOptionMap, "name");
54218 const apiDefaultOptions = Object.assign({}, options$1.hiddenDefaults, {}, fromPairs_1(supportOptions.filter(({
54220 }) => !deprecated).map(option => [option.name, option.default])));
54221 Object.assign(context, {
54230 * @param {Context} context
54231 * @param {string[]} plugins
54232 * @param {string[]=} pluginSearchDirs
54236 function pushContextPlugins(context, plugins, pluginSearchDirs) {
54237 context.stack.push(pick_1(context, ["supportOptions", "detailedOptions", "detailedOptionMap", "apiDefaultOptions", "languages"]));
54238 updateContextOptions(context, plugins, pluginSearchDirs);
54241 * @param {Context} context
54245 function popContextPlugins(context) {
54246 Object.assign(context, context.stack.pop());
54249 function updateContextArgv(context, plugins, pluginSearchDirs) {
54250 pushContextPlugins(context, plugins, pluginSearchDirs);
54251 const minimistOptions = createMinimistOptions(context.detailedOptions);
54252 const argv = minimist_1(context.args, minimistOptions);
54253 context.argv = argv;
54254 context.filePatterns = argv._;
54257 function normalizeContextArgv(context, keys) {
54258 const detailedOptions = !keys ? context.detailedOptions : context.detailedOptions.filter(option => keys.includes(option.name));
54259 const argv = !keys ? context.argv : pick_1(context.argv, keys);
54260 context.argv = optionsNormalizer.normalizeCliOptions(argv, detailedOptions, {
54261 logger: context.logger
54263 } //------------------------------context-util-end--------------------------------
54268 createDetailedOptionMap,
54269 createDetailedUsage,
54275 logResolvedConfigPathOrDie,
54277 normalizeDetailedOptionMap
54280 pleaseUpgradeNode(require$$1);
54282 function run(args) {
54283 const context = util$3.createContext(args);
54286 util$3.initContext(context);
54287 context.logger.debug(`normalized argv: ${JSON.stringify(context.argv)}`);
54289 if (context.argv.check && context.argv["list-different"]) {
54290 context.logger.error("Cannot use --check and --list-different together.");
54294 if (context.argv.write && context.argv["debug-check"]) {
54295 context.logger.error("Cannot use --write and --debug-check together.");
54299 if (context.argv["find-config-path"] && context.filePatterns.length) {
54300 context.logger.error("Cannot use --find-config-path with multiple files");
54304 if (context.argv["file-info"] && context.filePatterns.length) {
54305 context.logger.error("Cannot use --file-info with multiple files");
54309 if (context.argv.version) {
54310 context.logger.log(prettier.version);
54314 if (context.argv.help !== undefined) {
54315 context.logger.log(typeof context.argv.help === "string" && context.argv.help !== "" ? util$3.createDetailedUsage(context, context.argv.help) : util$3.createUsage(context));
54319 if (context.argv["support-info"]) {
54320 context.logger.log(prettier.format(jsonStableStringify(prettier.getSupportInfo()), {
54326 const hasFilePatterns = context.filePatterns.length !== 0;
54327 const useStdin = !hasFilePatterns && (!process.stdin.isTTY || context.args["stdin-filepath"]);
54329 if (context.argv["find-config-path"]) {
54330 util$3.logResolvedConfigPathOrDie(context);
54331 } else if (context.argv["file-info"]) {
54332 util$3.logFileInfoOrDie(context);
54333 } else if (useStdin) {
54334 util$3.formatStdin(context);
54335 } else if (hasFilePatterns) {
54336 util$3.formatFiles(context);
54338 context.logger.log(util$3.createUsage(context));
54342 context.logger.error(error.message);
54351 cli.run(process.argv.slice(2));