3 var fs$4 = require('fs');
4 var path$3 = require('path');
5 var os$2 = require('os');
6 var tty$2 = require('tty');
7 var assert$2 = require('assert');
8 var util$6 = require('util');
9 var stream_1 = require('stream');
10 var events_1 = require('events');
12 function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
14 var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$4);
15 var path__default = /*#__PURE__*/_interopDefaultLegacy(path$3);
16 var os__default = /*#__PURE__*/_interopDefaultLegacy(os$2);
17 var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty$2);
18 var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert$2);
19 var util__default = /*#__PURE__*/_interopDefaultLegacy(util$6);
20 var stream_1__default = /*#__PURE__*/_interopDefaultLegacy(stream_1);
21 var events_1__default = /*#__PURE__*/_interopDefaultLegacy(events_1);
23 var name = "prettier";
24 var version = "2.2.1";
25 var description = "Prettier is an opinionated code formatter";
26 var bin = "./bin/prettier.js";
27 var repository = "prettier/prettier";
28 var homepage = "https://prettier.io";
29 var author = "James Long";
31 var main = "./index.js";
32 var browser = "./standalone.js";
33 var unpkg = "./standalone.js";
44 "@angular/compiler": "10.2.3",
45 "@babel/code-frame": "7.10.4",
46 "@babel/parser": "7.12.5",
47 "@glimmer/syntax": "0.66.0",
48 "@iarna/toml": "2.2.5",
49 "@typescript-eslint/typescript-estree": "4.8.1",
50 "angular-estree-parser": "2.2.1",
51 "angular-html-parser": "1.7.1",
54 "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540",
59 editorconfig: "0.15.3",
60 "editorconfig-to-prettier": "0.2.0",
61 "escape-string-regexp": "4.0.0",
65 "fast-json-stable-stringify": "2.1.0",
66 "find-parent-dir": "0.3.0",
67 "flow-parser": "0.138.0",
71 "html-element-attributes": "2.3.0",
72 "html-styles": "1.0.0",
73 "html-tag-names": "1.1.5",
74 "html-void-elements": "1.0.5",
76 "jest-docblock": "26.0.0",
79 "lines-and-columns": "1.1.6",
80 "linguist-languages": "7.12.1",
86 "n-readlines": "1.0.1",
88 "parse-srcset": "ikatyang/parse-srcset#54eb9c1cb21db5c62b4d0e275d7249516df6f0ee",
89 "please-upgrade-node": "3.2.0",
90 "postcss-less": "3.1.4",
91 "postcss-media-query-parser": "0.2.3",
92 "postcss-scss": "2.1.1",
93 "postcss-selector-parser": "2.2.3",
94 "postcss-values-parser": "2.0.1",
95 "regexp-util": "1.2.2",
96 "remark-footnotes": "2.0.0",
97 "remark-math": "3.0.1",
98 "remark-parse": "8.0.3",
101 "string-width": "4.2.0",
103 "unicode-regex": "3.0.0",
106 "yaml-unist-parser": "1.3.1"
108 var devDependencies = {
109 "@babel/core": "7.12.3",
110 "@babel/preset-env": "7.12.1",
111 "@babel/types": "7.12.6",
112 "@glimmer/reference": "0.66.0",
113 "@rollup/plugin-alias": "3.1.1",
114 "@rollup/plugin-babel": "5.2.1",
115 "@rollup/plugin-commonjs": "16.0.0",
116 "@rollup/plugin-json": "4.1.0",
117 "@rollup/plugin-node-resolve": "10.0.0",
118 "@rollup/plugin-replace": "2.3.4",
119 "@types/estree": "0.0.45",
120 "@types/node": "14.14.0",
121 "@typescript-eslint/types": "4.8.1",
122 "babel-jest": "26.6.3",
123 "babel-loader": "8.2.1",
125 "builtin-modules": "3.1.0",
126 "cross-env": "7.0.2",
129 "eslint-config-prettier": "6.15.0",
130 "eslint-formatter-friendly": "7.0.0",
131 "eslint-plugin-import": "2.22.1",
132 "eslint-plugin-jest": "24.1.3",
133 "eslint-plugin-prettier-internal-rules": "file:scripts/tools/eslint-plugin-prettier-internal-rules",
134 "eslint-plugin-react": "7.21.5",
135 "eslint-plugin-unicorn": "23.0.0",
138 "jest-snapshot-serializer-ansi": "1.0.0",
139 "jest-snapshot-serializer-raw": "1.1.0",
140 "jest-watch-typeahead": "0.6.1",
141 "npm-run-all": "4.1.5",
142 "path-browserify": "1.0.1",
146 "rollup-plugin-node-globals": "1.4.0",
147 "rollup-plugin-terser": "7.0.2",
149 "snapshot-diff": "0.8.1",
150 "strip-ansi": "6.0.0",
151 "synchronous-promise": "2.0.15",
153 "terser-webpack-plugin": "5.0.3",
157 prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1",
158 "prepare-release": "yarn && yarn build && yarn test:dist",
160 "test:dev-package": "cross-env INSTALL_PACKAGE=1 jest",
161 "test:dist": "cross-env NODE_ENV=production jest",
162 "test:dist-standalone": "cross-env NODE_ENV=production TEST_STANDALONE=1 jest",
163 "test:integration": "jest tests_integration",
164 "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",
165 "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",
166 "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",
167 lint: "run-p lint:*",
168 "lint:typecheck": "tsc",
169 "lint:eslint": "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly",
170 "lint:changelog": "node ./scripts/lint-changelog.js",
171 "lint:prettier": "prettier . \"!test*\" --check",
172 "lint:dist": "eslint --no-eslintrc --no-ignore --env=es6,browser --parser-options=ecmaVersion:2018 \"dist/!(bin-prettier|index|third-party).js\"",
173 "lint:spellcheck": "cspell \"**/*\" \".github/**/*\"",
174 "lint:deps": "node ./scripts/check-deps.js",
175 fix: "run-s fix:eslint fix:prettier",
176 "fix:eslint": "yarn lint:eslint --fix",
177 "fix:prettier": "yarn lint:prettier --write",
178 build: "node --max-old-space-size=3072 ./scripts/build/build.js",
179 "build-docs": "node ./scripts/build-docs.js"
184 description: description,
186 repository: repository,
195 dependencies: dependencies,
196 devDependencies: devDependencies,
203 diff: function diff(oldString, newString) {
204 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
205 var callback = options.callback;
207 if (typeof options === 'function') {
212 this.options = options;
215 function done(value) {
217 setTimeout(function () {
218 callback(undefined, value);
224 } // Allow subclasses to massage the input prior to running
227 oldString = this.castInput(oldString);
228 newString = this.castInput(newString);
229 oldString = this.removeEmpty(this.tokenize(oldString));
230 newString = this.removeEmpty(this.tokenize(newString));
231 var newLen = newString.length,
232 oldLen = oldString.length;
234 var maxEditLength = newLen + oldLen;
238 }]; // Seed editLength = 0, i.e. the content starts with the same values
240 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
242 if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
243 // Identity per the equality and tokenizer
245 value: this.join(newString),
246 count: newString.length
248 } // Main worker method. checks all permutations of a given edit length for acceptance.
251 function execEditLength() {
252 for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
253 var basePath = void 0;
255 var addPath = bestPath[diagonalPath - 1],
256 removePath = bestPath[diagonalPath + 1],
257 _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
260 // No one else is going to attempt to use this value, clear it
261 bestPath[diagonalPath - 1] = undefined;
264 var canAdd = addPath && addPath.newPos + 1 < newLen,
265 canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
267 if (!canAdd && !canRemove) {
268 // If this path is a terminal then prune
269 bestPath[diagonalPath] = undefined;
271 } // Select the diagonal that we want to branch from. We select the prior
272 // path whose position in the new string is the farthest from the origin
273 // and does not pass the bounds of the diff graph
276 if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
277 basePath = clonePath(removePath);
278 self.pushComponent(basePath.components, undefined, true);
280 basePath = addPath; // No need to clone, we've pulled it from the list
283 self.pushComponent(basePath.components, true, undefined);
286 _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
288 if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
289 return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
291 // Otherwise track this path as a potential candidate and continue.
292 bestPath[diagonalPath] = basePath;
297 } // Performs the length of edit iteration. Is a bit fugly as this has to support the
298 // sync and async mode which is never fun. Loops over execEditLength until a value
304 setTimeout(function () {
305 // This should not happen, but we want to be safe.
307 /* istanbul ignore next */
308 if (editLength > maxEditLength) {
312 if (!execEditLength()) {
318 while (editLength <= maxEditLength) {
319 var ret = execEditLength();
327 pushComponent: function pushComponent(components, added, removed) {
328 var last = components[components.length - 1];
330 if (last && last.added === added && last.removed === removed) {
331 // We need to clone here as the component clone operation is just
332 // as shallow array clone
333 components[components.length - 1] = {
334 count: last.count + 1,
346 extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
347 var newLen = newString.length,
348 oldLen = oldString.length,
349 newPos = basePath.newPos,
350 oldPos = newPos - diagonalPath,
353 while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
360 basePath.components.push({
365 basePath.newPos = newPos;
368 equals: function equals(left, right) {
369 if (this.options.comparator) {
370 return this.options.comparator(left, right);
372 return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
375 removeEmpty: function removeEmpty(array) {
378 for (var i = 0; i < array.length; i++) {
386 castInput: function castInput(value) {
389 tokenize: function tokenize(value) {
390 return value.split('');
392 join: function join(chars) {
393 return chars.join('');
397 function buildValues(diff, components, newString, oldString, useLongestToken) {
398 var componentPos = 0,
399 componentLen = components.length,
403 for (; componentPos < componentLen; componentPos++) {
404 var component = components[componentPos];
406 if (!component.removed) {
407 if (!component.added && useLongestToken) {
408 var value = newString.slice(newPos, newPos + component.count);
409 value = value.map(function (value, i) {
410 var oldValue = oldString[oldPos + i];
411 return oldValue.length > value.length ? oldValue : value;
413 component.value = diff.join(value);
415 component.value = diff.join(newString.slice(newPos, newPos + component.count));
418 newPos += component.count; // Common case
420 if (!component.added) {
421 oldPos += component.count;
424 component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
425 oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
426 // The diffing algorithm is tied to add then remove output and this is the simplest
427 // route to get the desired output with minimal overhead.
429 if (componentPos && components[componentPos - 1].added) {
430 var tmp = components[componentPos - 1];
431 components[componentPos - 1] = components[componentPos];
432 components[componentPos] = tmp;
435 } // Special case handle for when one terminal is ignored (i.e. whitespace).
436 // For this case we merge the terminal into the prior string and drop the change.
437 // This is only available for string mode.
440 var lastComponent = components[componentLen - 1];
442 if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
443 components[componentLen - 2].value += lastComponent.value;
450 function clonePath(path) {
453 components: path.components.slice(0)
457 var characterDiff = new Diff();
459 function diffChars(oldStr, newStr, options) {
460 return characterDiff.diff(oldStr, newStr, options);
463 function generateOptions(options, defaults) {
464 if (typeof options === 'function') {
465 defaults.callback = options;
466 } else if (options) {
467 for (var name in options) {
468 /* istanbul ignore else */
469 if (options.hasOwnProperty(name)) {
470 defaults[name] = options[name];
477 // Ranges and exceptions:
478 // Latin-1 Supplement, 0080–00FF
479 // - U+00D7 × Multiplication sign
480 // - U+00F7 ÷ Division sign
481 // Latin Extended-A, 0100–017F
482 // Latin Extended-B, 0180–024F
483 // IPA Extensions, 0250–02AF
484 // Spacing Modifier Letters, 02B0–02FF
485 // - U+02C7 ˇ ˇ Caron
486 // - U+02D8 ˘ ˘ Breve
487 // - U+02D9 ˙ ˙ Dot Above
488 // - U+02DA ˚ ˚ Ring Above
489 // - U+02DB ˛ ˛ Ogonek
490 // - U+02DC ˜ ˜ Small Tilde
491 // - U+02DD ˝ ˝ Double Acute Accent
492 // Latin Extended Additional, 1E00–1EFF
495 var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
496 var reWhitespace = /\S/;
497 var wordDiff = new Diff();
499 wordDiff.equals = function (left, right) {
500 if (this.options.ignoreCase) {
501 left = left.toLowerCase();
502 right = right.toLowerCase();
505 return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
508 wordDiff.tokenize = function (value) {
509 // All whitespace symbols except newline group into one token, each newline - in separate token
510 var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
512 for (var i = 0; i < tokens.length - 1; i++) {
513 // If we have an empty string in the next field and we have only word chars before and after, merge
514 if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
515 tokens[i] += tokens[i + 2];
516 tokens.splice(i + 1, 2);
524 function diffWords(oldStr, newStr, options) {
525 options = generateOptions(options, {
526 ignoreWhitespace: true
528 return wordDiff.diff(oldStr, newStr, options);
531 function diffWordsWithSpace(oldStr, newStr, options) {
532 return wordDiff.diff(oldStr, newStr, options);
535 var lineDiff = new Diff();
537 lineDiff.tokenize = function (value) {
539 linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
541 if (!linesAndNewlines[linesAndNewlines.length - 1]) {
542 linesAndNewlines.pop();
543 } // Merge the content and line separators into single tokens
546 for (var i = 0; i < linesAndNewlines.length; i++) {
547 var line = linesAndNewlines[i];
549 if (i % 2 && !this.options.newlineIsToken) {
550 retLines[retLines.length - 1] += line;
552 if (this.options.ignoreWhitespace) {
563 function diffLines(oldStr, newStr, callback) {
564 return lineDiff.diff(oldStr, newStr, callback);
567 function diffTrimmedLines(oldStr, newStr, callback) {
568 var options = generateOptions(callback, {
569 ignoreWhitespace: true
571 return lineDiff.diff(oldStr, newStr, options);
574 var sentenceDiff = new Diff();
576 sentenceDiff.tokenize = function (value) {
577 return value.split(/(\S.+?[.!?])(?=\s+|$)/);
580 function diffSentences(oldStr, newStr, callback) {
581 return sentenceDiff.diff(oldStr, newStr, callback);
584 var cssDiff = new Diff();
586 cssDiff.tokenize = function (value) {
587 return value.split(/([{}:;,]|\s+)/);
590 function diffCss(oldStr, newStr, callback) {
591 return cssDiff.diff(oldStr, newStr, callback);
594 function _typeof(obj) {
595 "@babel/helpers - typeof";
597 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
598 _typeof = function (obj) {
602 _typeof = function (obj) {
603 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
610 function _toConsumableArray(arr) {
611 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
614 function _arrayWithoutHoles(arr) {
615 if (Array.isArray(arr)) return _arrayLikeToArray(arr);
618 function _iterableToArray(iter) {
619 if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
622 function _unsupportedIterableToArray(o, minLen) {
624 if (typeof o === "string") return _arrayLikeToArray(o, minLen);
625 var n = Object.prototype.toString.call(o).slice(8, -1);
626 if (n === "Object" && o.constructor) n = o.constructor.name;
627 if (n === "Map" || n === "Set") return Array.from(o);
628 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
631 function _arrayLikeToArray(arr, len) {
632 if (len == null || len > arr.length) len = arr.length;
634 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
639 function _nonIterableSpread() {
640 throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
643 var objectPrototypeToString = Object.prototype.toString;
644 var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
645 // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
647 jsonDiff.useLongestToken = true;
648 jsonDiff.tokenize = lineDiff.tokenize;
650 jsonDiff.castInput = function (value) {
651 var _this$options = this.options,
652 undefinedReplacement = _this$options.undefinedReplacement,
653 _this$options$stringi = _this$options.stringifyReplacer,
654 stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
655 return typeof v === 'undefined' ? undefinedReplacement : v;
656 } : _this$options$stringi;
657 return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
660 jsonDiff.equals = function (left, right) {
661 return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
664 function diffJson(oldObj, newObj, options) {
665 return jsonDiff.diff(oldObj, newObj, options);
666 } // This function handles the presence of circular references by bailing out when encountering an
667 // object that is already on the "stack" of items being processed. Accepts an optional replacer
670 function canonicalize(obj, stack, replacementStack, replacer, key) {
672 replacementStack = replacementStack || [];
675 obj = replacer(key, obj);
680 for (i = 0; i < stack.length; i += 1) {
681 if (stack[i] === obj) {
682 return replacementStack[i];
686 var canonicalizedObj;
688 if ('[object Array]' === objectPrototypeToString.call(obj)) {
690 canonicalizedObj = new Array(obj.length);
691 replacementStack.push(canonicalizedObj);
693 for (i = 0; i < obj.length; i += 1) {
694 canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
698 replacementStack.pop();
699 return canonicalizedObj;
702 if (obj && obj.toJSON) {
706 if (_typeof(obj) === 'object' && obj !== null) {
708 canonicalizedObj = {};
709 replacementStack.push(canonicalizedObj);
715 /* istanbul ignore else */
716 if (obj.hasOwnProperty(_key)) {
717 sortedKeys.push(_key);
723 for (i = 0; i < sortedKeys.length; i += 1) {
724 _key = sortedKeys[i];
725 canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
729 replacementStack.pop();
731 canonicalizedObj = obj;
734 return canonicalizedObj;
737 var arrayDiff = new Diff();
739 arrayDiff.tokenize = function (value) {
740 return value.slice();
743 arrayDiff.join = arrayDiff.removeEmpty = function (value) {
747 function diffArrays(oldArr, newArr, callback) {
748 return arrayDiff.diff(oldArr, newArr, callback);
751 function parsePatch(uniDiff) {
752 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
753 var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
754 delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
758 function parseIndex() {
760 list.push(index); // Parse diff metadata
762 while (i < diffstr.length) {
763 var line = diffstr[i]; // File header found, end parsing diff metadata
765 if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
770 var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
773 index.index = header[1];
777 } // Parse file headers if they are defined. Unified diff requires them, but
778 // there's no technical issues to have an isolated hunk without file header
781 parseFileHeader(index);
782 parseFileHeader(index); // Parse hunks
786 while (i < diffstr.length) {
787 var _line = diffstr[i];
789 if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
791 } else if (/^@@/.test(_line)) {
792 index.hunks.push(parseHunk());
793 } else if (_line && options.strict) {
794 // Ignore unexpected content unless in strict mode
795 throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
800 } // Parses the --- and +++ headers, if none are found, no lines
804 function parseFileHeader(index) {
805 var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
808 var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
809 var data = fileHeader[2].split('\t', 2);
810 var fileName = data[0].replace(/\\\\/g, '\\');
812 if (/^".*"$/.test(fileName)) {
813 fileName = fileName.substr(1, fileName.length - 2);
816 index[keyPrefix + 'FileName'] = fileName;
817 index[keyPrefix + 'Header'] = (data[1] || '').trim();
821 // This assumes that we are at the start of a hunk.
824 function parseHunk() {
825 var chunkHeaderIndex = i,
826 chunkHeaderLine = diffstr[i++],
827 chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
829 oldStart: +chunkHeader[1],
830 oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2],
831 newStart: +chunkHeader[3],
832 newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4],
835 }; // Unified Diff Format quirk: If the chunk size is 0,
836 // the first number is one lower than one would expect.
837 // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
839 if (hunk.oldLines === 0) {
843 if (hunk.newLines === 0) {
850 for (; i < diffstr.length; i++) {
851 // Lines starting with '---' could be mistaken for the "remove line" operation
852 // But they could be the header for the next file. Therefore prune such cases out.
853 if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
857 var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
859 if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
860 hunk.lines.push(diffstr[i]);
861 hunk.linedelimiters.push(delimiters[i] || '\n');
863 if (operation === '+') {
865 } else if (operation === '-') {
867 } else if (operation === ' ') {
874 } // Handle the empty block count case
877 if (!addCount && hunk.newLines === 1) {
881 if (!removeCount && hunk.oldLines === 1) {
883 } // Perform optional sanity checking
886 if (options.strict) {
887 if (addCount !== hunk.newLines) {
888 throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
891 if (removeCount !== hunk.oldLines) {
892 throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
899 while (i < diffstr.length) {
904 } // Iterator that traverses in the range of [min, max], stepping
905 // by distance from a given start position. I.e. for [0, 4], with
906 // start of 2, this will iterate 2, 3, 1, 4, 0.
909 function distanceIterator(start, minLine, maxLine) {
910 var wantForward = true,
911 backwardExhausted = false,
912 forwardExhausted = false,
914 return function iterator() {
915 if (wantForward && !forwardExhausted) {
916 if (backwardExhausted) {
920 } // Check if trying to fit beyond text length, and if not, check it fits
921 // after offset location (or desired location on first iteration)
924 if (start + localOffset <= maxLine) {
928 forwardExhausted = true;
931 if (!backwardExhausted) {
932 if (!forwardExhausted) {
934 } // Check if trying to fit before text beginning, and if not, check it fits
935 // before offset location
938 if (minLine <= start - localOffset) {
939 return -localOffset++;
942 backwardExhausted = true;
944 } // We tried to fit hunk before text beginning and beyond text length, then
945 // hunk can't fit on the text. Return undefined
950 function applyPatch(source, uniDiff) {
951 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
953 if (typeof uniDiff === 'string') {
954 uniDiff = parsePatch(uniDiff);
957 if (Array.isArray(uniDiff)) {
958 if (uniDiff.length > 1) {
959 throw new Error('applyPatch only works with a single input.');
962 uniDiff = uniDiff[0];
963 } // Apply the diff to the input
966 var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
967 delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
968 hunks = uniDiff.hunks,
969 compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
970 return line === patchContent;
973 fuzzFactor = options.fuzzFactor || 0,
979 * Checks if the hunk exactly fits on the provided location
983 function hunkFits(hunk, toPos) {
984 for (var j = 0; j < hunk.lines.length; j++) {
985 var line = hunk.lines[j],
986 operation = line.length > 0 ? line[0] : ' ',
987 content = line.length > 0 ? line.substr(1) : line;
989 if (operation === ' ' || operation === '-') {
990 // Context sanity check
991 if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
994 if (errorCount > fuzzFactor) {
1004 } // Search best fit offsets for each hunk based on the previous ones
1007 for (var i = 0; i < hunks.length; i++) {
1008 var hunk = hunks[i],
1009 maxLine = lines.length - hunk.oldLines,
1011 toPos = offset + hunk.oldStart - 1;
1012 var iterator = distanceIterator(toPos, minLine, maxLine);
1014 for (; localOffset !== undefined; localOffset = iterator()) {
1015 if (hunkFits(hunk, toPos + localOffset)) {
1016 hunk.offset = offset += localOffset;
1021 if (localOffset === undefined) {
1023 } // Set lower text limit to end of the current hunk, so next ones don't try
1024 // to fit over already patched text
1027 minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
1028 } // Apply patch hunks
1033 for (var _i = 0; _i < hunks.length; _i++) {
1034 var _hunk = hunks[_i],
1035 _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
1037 diffOffset += _hunk.newLines - _hunk.oldLines;
1039 for (var j = 0; j < _hunk.lines.length; j++) {
1040 var line = _hunk.lines[j],
1041 operation = line.length > 0 ? line[0] : ' ',
1042 content = line.length > 0 ? line.substr(1) : line,
1043 delimiter = _hunk.linedelimiters[j];
1045 if (operation === ' ') {
1047 } else if (operation === '-') {
1048 lines.splice(_toPos, 1);
1049 delimiters.splice(_toPos, 1);
1050 /* istanbul ignore else */
1051 } else if (operation === '+') {
1052 lines.splice(_toPos, 0, content);
1053 delimiters.splice(_toPos, 0, delimiter);
1055 } else if (operation === '\\') {
1056 var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
1058 if (previousOperation === '+') {
1060 } else if (previousOperation === '-') {
1065 } // Handle EOFNL insertion/removal
1069 while (!lines[lines.length - 1]) {
1073 } else if (addEOFNL) {
1075 delimiters.push('\n');
1078 for (var _k = 0; _k < lines.length - 1; _k++) {
1079 lines[_k] = lines[_k] + delimiters[_k];
1082 return lines.join('');
1083 } // Wrapper that supports multiple file patches via callbacks.
1086 function applyPatches(uniDiff, options) {
1087 if (typeof uniDiff === 'string') {
1088 uniDiff = parsePatch(uniDiff);
1091 var currentIndex = 0;
1093 function processIndex() {
1094 var index = uniDiff[currentIndex++];
1097 return options.complete();
1100 options.loadFile(index, function (err, data) {
1102 return options.complete(err);
1105 var updatedContent = applyPatch(data, index, options);
1106 options.patched(index, updatedContent, function (err) {
1108 return options.complete(err);
1119 function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1124 if (typeof options.context === 'undefined') {
1125 options.context = 4;
1128 var diff = diffLines(oldStr, newStr, options);
1132 }); // Append an empty value to make cleanup easier
1134 function contextLines(lines) {
1135 return lines.map(function (entry) {
1141 var oldRangeStart = 0,
1147 var _loop = function _loop(i) {
1148 var current = diff[i],
1149 lines = current.lines || current.value.replace(/\n$/, '').split('\n');
1150 current.lines = lines;
1152 if (current.added || current.removed) {
1153 var _curRange; // If we have previous context, start with that
1156 if (!oldRangeStart) {
1157 var prev = diff[i - 1];
1158 oldRangeStart = oldLine;
1159 newRangeStart = newLine;
1162 curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
1163 oldRangeStart -= curRange.length;
1164 newRangeStart -= curRange.length;
1166 } // Output our changes
1169 (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
1170 return (current.added ? '+' : '-') + entry;
1171 }))); // Track the updated file position
1174 if (current.added) {
1175 newLine += lines.length;
1177 oldLine += lines.length;
1180 // Identical context lines. Track line changes
1181 if (oldRangeStart) {
1182 // Close out any changes that have been output (or join overlapping)
1183 if (lines.length <= options.context * 2 && i < diff.length - 2) {
1184 var _curRange2; // Overlapping
1187 (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
1189 var _curRange3; // end the range and output
1192 var contextSize = Math.min(lines.length, options.context);
1194 (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
1197 oldStart: oldRangeStart,
1198 oldLines: oldLine - oldRangeStart + contextSize,
1199 newStart: newRangeStart,
1200 newLines: newLine - newRangeStart + contextSize,
1204 if (i >= diff.length - 2 && lines.length <= options.context) {
1205 // EOF is inside this hunk
1206 var oldEOFNewline = /\n$/.test(oldStr);
1207 var newEOFNewline = /\n$/.test(newStr);
1208 var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
1210 if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) {
1211 // special case: old has no eol and no trailing context; no-nl can end up before adds
1212 // however, if the old file is empty, do not output the no-nl line
1213 curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
1216 if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
1217 curRange.push('\\ No newline at end of file');
1228 oldLine += lines.length;
1229 newLine += lines.length;
1233 for (var i = 0; i < diff.length; i++) {
1238 oldFileName: oldFileName,
1239 newFileName: newFileName,
1240 oldHeader: oldHeader,
1241 newHeader: newHeader,
1246 function formatPatch(diff) {
1249 if (diff.oldFileName == diff.newFileName) {
1250 ret.push('Index: ' + diff.oldFileName);
1253 ret.push('===================================================================');
1254 ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
1255 ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
1257 for (var i = 0; i < diff.hunks.length; i++) {
1258 var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0,
1259 // the first number is one lower than one would expect.
1260 // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
1262 if (hunk.oldLines === 0) {
1266 if (hunk.newLines === 0) {
1270 ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
1271 ret.push.apply(ret, hunk.lines);
1274 return ret.join('\n') + '\n';
1277 function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1278 return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options));
1281 function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
1282 return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
1285 function arrayEqual(a, b) {
1286 if (a.length !== b.length) {
1290 return arrayStartsWith(a, b);
1293 function arrayStartsWith(array, start) {
1294 if (start.length > array.length) {
1298 for (var i = 0; i < start.length; i++) {
1299 if (start[i] !== array[i]) {
1307 function calcLineCount(hunk) {
1308 var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
1309 oldLines = _calcOldNewLineCount.oldLines,
1310 newLines = _calcOldNewLineCount.newLines;
1312 if (oldLines !== undefined) {
1313 hunk.oldLines = oldLines;
1315 delete hunk.oldLines;
1318 if (newLines !== undefined) {
1319 hunk.newLines = newLines;
1321 delete hunk.newLines;
1325 function merge(mine, theirs, base) {
1326 mine = loadPatch(mine, base);
1327 theirs = loadPatch(theirs, base);
1328 var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
1329 // Leaving sanity checks on this to the API consumer that may know more about the
1330 // meaning in their own context.
1332 if (mine.index || theirs.index) {
1333 ret.index = mine.index || theirs.index;
1336 if (mine.newFileName || theirs.newFileName) {
1337 if (!fileNameChanged(mine)) {
1338 // No header or no change in ours, use theirs (and ours if theirs does not exist)
1339 ret.oldFileName = theirs.oldFileName || mine.oldFileName;
1340 ret.newFileName = theirs.newFileName || mine.newFileName;
1341 ret.oldHeader = theirs.oldHeader || mine.oldHeader;
1342 ret.newHeader = theirs.newHeader || mine.newHeader;
1343 } else if (!fileNameChanged(theirs)) {
1344 // No header or no change in theirs, use ours
1345 ret.oldFileName = mine.oldFileName;
1346 ret.newFileName = mine.newFileName;
1347 ret.oldHeader = mine.oldHeader;
1348 ret.newHeader = mine.newHeader;
1350 // Both changed... figure it out
1351 ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
1352 ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
1353 ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
1354 ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
1364 while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
1365 var mineCurrent = mine.hunks[mineIndex] || {
1368 theirsCurrent = theirs.hunks[theirsIndex] || {
1372 if (hunkBefore(mineCurrent, theirsCurrent)) {
1373 // This patch does not overlap with any of the others, yay.
1374 ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
1376 theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
1377 } else if (hunkBefore(theirsCurrent, mineCurrent)) {
1378 // This patch does not overlap with any of the others, yay.
1379 ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
1381 mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
1383 // Overlap, merge as best we can
1385 oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
1387 newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
1391 mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
1394 ret.hunks.push(mergedHunk);
1401 function loadPatch(param, base) {
1402 if (typeof param === 'string') {
1403 if (/^@@/m.test(param) || /^Index:/m.test(param)) {
1404 return parsePatch(param)[0];
1408 throw new Error('Must provide a base reference or pass in a patch');
1411 return structuredPatch(undefined, undefined, base, param);
1417 function fileNameChanged(patch) {
1418 return patch.newFileName && patch.newFileName !== patch.oldFileName;
1421 function selectField(index, mine, theirs) {
1422 if (mine === theirs) {
1425 index.conflict = true;
1433 function hunkBefore(test, check) {
1434 return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
1437 function cloneHunk(hunk, offset) {
1439 oldStart: hunk.oldStart,
1440 oldLines: hunk.oldLines,
1441 newStart: hunk.newStart + offset,
1442 newLines: hunk.newLines,
1447 function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
1448 // This will generally result in a conflicted hunk, but there are cases where the context
1449 // is the only overlap where we can successfully merge the content here.
1456 offset: theirOffset,
1459 }; // Handle any leading content
1461 insertLeading(hunk, mine, their);
1462 insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
1464 while (mine.index < mine.lines.length && their.index < their.lines.length) {
1465 var mineCurrent = mine.lines[mine.index],
1466 theirCurrent = their.lines[their.index];
1468 if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
1469 // Both modified ...
1470 mutualChange(hunk, mine, their);
1471 } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
1472 var _hunk$lines; // Mine inserted
1475 (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
1476 } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
1477 var _hunk$lines2; // Theirs inserted
1480 (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
1481 } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
1482 // Mine removed or edited
1483 removal(hunk, mine, their);
1484 } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
1485 // Their removed or edited
1486 removal(hunk, their, mine, true);
1487 } else if (mineCurrent === theirCurrent) {
1489 hunk.lines.push(mineCurrent);
1494 conflict(hunk, collectChange(mine), collectChange(their));
1496 } // Now push anything that may be remaining
1499 insertTrailing(hunk, mine);
1500 insertTrailing(hunk, their);
1501 calcLineCount(hunk);
1504 function mutualChange(hunk, mine, their) {
1505 var myChanges = collectChange(mine),
1506 theirChanges = collectChange(their);
1508 if (allRemoves(myChanges) && allRemoves(theirChanges)) {
1509 // Special case for remove changes that are supersets of one another
1510 if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
1513 (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
1516 } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
1519 (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
1523 } else if (arrayEqual(myChanges, theirChanges)) {
1526 (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
1531 conflict(hunk, myChanges, theirChanges);
1534 function removal(hunk, mine, their, swap) {
1535 var myChanges = collectChange(mine),
1536 theirChanges = collectContext(their, myChanges);
1538 if (theirChanges.merged) {
1541 (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
1543 conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
1547 function conflict(hunk, mine, their) {
1548 hunk.conflict = true;
1556 function insertLeading(hunk, insert, their) {
1557 while (insert.offset < their.offset && insert.index < insert.lines.length) {
1558 var line = insert.lines[insert.index++];
1559 hunk.lines.push(line);
1564 function insertTrailing(hunk, insert) {
1565 while (insert.index < insert.lines.length) {
1566 var line = insert.lines[insert.index++];
1567 hunk.lines.push(line);
1571 function collectChange(state) {
1573 operation = state.lines[state.index][0];
1575 while (state.index < state.lines.length) {
1576 var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
1578 if (operation === '-' && line[0] === '+') {
1582 if (operation === line[0]) {
1593 function collectContext(state, matchChanges) {
1597 contextChanges = false,
1600 while (matchIndex < matchChanges.length && state.index < state.lines.length) {
1601 var change = state.lines[state.index],
1602 match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
1604 if (match[0] === '+') {
1608 contextChanges = contextChanges || change[0] !== ' ';
1610 matchIndex++; // Consume any additions in the other block as a conflict to attempt
1611 // to pull in the remaining context after this
1613 if (change[0] === '+') {
1616 while (change[0] === '+') {
1617 changes.push(change);
1618 change = state.lines[++state.index];
1622 if (match.substr(1) === change.substr(1)) {
1623 changes.push(change);
1630 if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
1638 while (matchIndex < matchChanges.length) {
1639 merged.push(matchChanges[matchIndex++]);
1648 function allRemoves(changes) {
1649 return changes.reduce(function (prev, change) {
1650 return prev && change[0] === '-';
1654 function skipRemoveSuperset(state, removeChanges, delta) {
1655 for (var i = 0; i < delta; i++) {
1656 var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
1658 if (state.lines[state.index + i] !== ' ' + changeContent) {
1663 state.index += delta;
1667 function calcOldNewLineCount(lines) {
1670 lines.forEach(function (line) {
1671 if (typeof line !== 'string') {
1672 var myCount = calcOldNewLineCount(line.mine);
1673 var theirCount = calcOldNewLineCount(line.theirs);
1675 if (oldLines !== undefined) {
1676 if (myCount.oldLines === theirCount.oldLines) {
1677 oldLines += myCount.oldLines;
1679 oldLines = undefined;
1683 if (newLines !== undefined) {
1684 if (myCount.newLines === theirCount.newLines) {
1685 newLines += myCount.newLines;
1687 newLines = undefined;
1691 if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
1695 if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
1704 } // See: http://code.google.com/p/google-diff-match-patch/wiki/API
1707 function convertChangesToDMP(changes) {
1712 for (var i = 0; i < changes.length; i++) {
1713 change = changes[i];
1717 } else if (change.removed) {
1723 ret.push([operation, change.value]);
1729 function convertChangesToXML(changes) {
1732 for (var i = 0; i < changes.length; i++) {
1733 var change = changes[i];
1737 } else if (change.removed) {
1741 ret.push(escapeHTML(change.value));
1745 } else if (change.removed) {
1750 return ret.join('');
1753 function escapeHTML(s) {
1755 n = n.replace(/&/g, '&');
1756 n = n.replace(/</g, '<');
1757 n = n.replace(/>/g, '>');
1758 n = n.replace(/"/g, '"');
1762 var index_es6 = /*#__PURE__*/Object.freeze({
1765 applyPatch: applyPatch,
1766 applyPatches: applyPatches,
1767 canonicalize: canonicalize,
1768 convertChangesToDMP: convertChangesToDMP,
1769 convertChangesToXML: convertChangesToXML,
1770 createPatch: createPatch,
1771 createTwoFilesPatch: createTwoFilesPatch,
1772 diffArrays: diffArrays,
1773 diffChars: diffChars,
1776 diffLines: diffLines,
1777 diffSentences: diffSentences,
1778 diffTrimmedLines: diffTrimmedLines,
1779 diffWords: diffWords,
1780 diffWordsWithSpace: diffWordsWithSpace,
1782 parsePatch: parsePatch,
1783 structuredPatch: structuredPatch
1787 * @param {Doc[]} parts
1792 function concat(parts) {
1793 // access the internals of a document directly.
1794 // if(parts.length === 1) {
1795 // // If it's a single document, no need to concat it.
1806 * @param {Doc} contents
1811 function indent(contents) {
1819 * @param {number | string} n
1820 * @param {Doc} contents
1825 function align(n, contents) {
1834 * @param {Doc} contents
1835 * @param {object} [opts] - TBD ???
1840 function group(contents, opts) {
1847 break: !!opts.shouldBreak,
1848 expandedStates: opts.expandedStates
1852 * @param {Doc} contents
1857 function dedentToRoot(contents) {
1858 return align(-Infinity, contents);
1861 * @param {Doc} contents
1866 function markAsRoot(contents) {
1867 // @ts-ignore - TBD ???:
1873 * @param {Doc} contents
1878 function dedent(contents) {
1879 return align(-1, contents);
1882 * @param {Doc[]} states
1883 * @param {object} [opts] - TBD ???
1888 function conditionalGroup(states, opts) {
1889 return group(states[0], Object.assign({}, opts, {
1890 expandedStates: states
1894 * @param {Doc[]} parts
1899 function fill(parts) {
1907 * @param {Doc} [breakContents]
1908 * @param {Doc} [flatContents]
1909 * @param {object} [opts] - TBD ???
1914 function ifBreak(breakContents, flatContents, opts) {
1921 groupId: opts.groupId
1925 * @param {Doc} contents
1930 function lineSuffix(contents) {
1933 type: "line-suffix",
1938 const lineSuffixBoundary = {
1939 type: "line-suffix-boundary"
1941 const breakParent = {
1942 type: "break-parent"
1954 const hardline = concat([{
1958 const literalline = concat([{
1965 placeholder: Symbol("cursor")
1969 * @param {Doc[]} arr
1973 function join(sep, arr) {
1976 for (let i = 0; i < arr.length; i++) {
1988 * @param {number} size
1989 * @param {number} tabWidth
1993 function addAlignmentToDoc(doc, size, tabWidth) {
1997 // Use indent to add tabs for all the levels of tabs we need
1998 for (let i = 0; i < Math.floor(size / tabWidth); ++i) {
1999 aligned = indent(aligned);
2000 } // Use align for all the spaces that are needed
2003 aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current
2004 // indentation, so we use -Infinity to reset the indentation to 0
2006 aligned = align(-Infinity, aligned);
2039 const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|');
2040 return new RegExp(pattern, onlyFirst ? undefined : 'g');
2043 var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
2045 /* eslint-disable yoda */
2047 const isFullwidthCodePoint = codePoint => {
2048 if (Number.isNaN(codePoint)) {
2050 } // Code points are derived from:
2051 // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
2054 if (codePoint >= 0x1100 && (codePoint <= 0x115F || // Hangul Jamo
2055 codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET
2056 codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET
2057 // CJK Radicals Supplement .. Enclosed CJK Letters and Months
2058 0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
2059 0x3250 <= codePoint && codePoint <= 0x4DBF || // CJK Unified Ideographs .. Yi Radicals
2060 0x4E00 <= codePoint && codePoint <= 0xA4C6 || // Hangul Jamo Extended-A
2061 0xA960 <= codePoint && codePoint <= 0xA97C || // Hangul Syllables
2062 0xAC00 <= codePoint && codePoint <= 0xD7A3 || // CJK Compatibility Ideographs
2063 0xF900 <= codePoint && codePoint <= 0xFAFF || // Vertical Forms
2064 0xFE10 <= codePoint && codePoint <= 0xFE19 || // CJK Compatibility Forms .. Small Form Variants
2065 0xFE30 <= codePoint && codePoint <= 0xFE6B || // Halfwidth and Fullwidth Forms
2066 0xFF01 <= codePoint && codePoint <= 0xFF60 || 0xFFE0 <= codePoint && codePoint <= 0xFFE6 || // Kana Supplement
2067 0x1B000 <= codePoint && codePoint <= 0x1B001 || // Enclosed Ideographic Supplement
2068 0x1F200 <= codePoint && codePoint <= 0x1F251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
2069 0x20000 <= codePoint && codePoint <= 0x3FFFD)) {
2076 var isFullwidthCodePoint_1 = isFullwidthCodePoint;
2077 var _default = isFullwidthCodePoint;
2078 isFullwidthCodePoint_1.default = _default;
2080 var emojiRegex = function () {
2081 // https://mths.be/emoji
2082 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;
2085 const stringWidth = string => {
2086 string = string.replace(emojiRegex(), ' ');
2088 if (typeof string !== 'string' || string.length === 0) {
2092 string = stripAnsi(string);
2095 for (let i = 0; i < string.length; i++) {
2096 const code = string.codePointAt(i); // Ignore control characters
2098 if (code <= 0x1F || code >= 0x7F && code <= 0x9F) {
2100 } // Ignore combining characters
2103 if (code >= 0x300 && code <= 0x36F) {
2108 if (code > 0xFFFF) {
2112 width += isFullwidthCodePoint_1(code) ? 2 : 1;
2118 var stringWidth_1 = stringWidth; // TODO: remove this in the next major version
2120 var _default$1 = stringWidth;
2121 stringWidth_1.default = _default$1;
2123 var escapeStringRegexp = string => {
2124 if (typeof string !== 'string') {
2125 throw new TypeError('Expected a string');
2126 } // Escape characters with special meaning either inside or outside character sets.
2127 // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.
2130 return string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d');
2133 var getLast = arr => arr[arr.length - 1];
2135 function _objectWithoutPropertiesLoose(source, excluded) {
2136 if (source == null) return {};
2138 var sourceKeys = Object.keys(source);
2141 for (i = 0; i < sourceKeys.length; i++) {
2142 key = sourceKeys[i];
2143 if (excluded.indexOf(key) >= 0) continue;
2144 target[key] = source[key];
2150 const debug = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error('SEMVER', ...args) : () => {};
2151 var debug_1 = debug;
2153 // Note: this is the semver.org version of the spec that it implements
2154 // Not necessarily the package version of this code.
2155 const SEMVER_SPEC_VERSION = '2.0.0';
2156 const MAX_LENGTH = 256;
2157 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
2158 /* istanbul ignore next */
2159 9007199254740991; // Max safe segment length for coercion.
2161 const MAX_SAFE_COMPONENT_LENGTH = 16;
2163 SEMVER_SPEC_VERSION,
2166 MAX_SAFE_COMPONENT_LENGTH
2169 function createCommonjsModule(fn, basedir, module) {
2173 require: function (path, base) {
2174 return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
2176 }, fn(module, module.exports), module.exports;
2179 function getDefaultExportFromNamespaceIfPresent (n) {
2180 return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
2183 function commonjsRequire () {
2184 throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
2187 var re_1 = createCommonjsModule(function (module, exports) {
2189 MAX_SAFE_COMPONENT_LENGTH
2191 exports = module.exports = {}; // The actual regexps go on exports.re
2193 const re = exports.re = [];
2194 const src = exports.src = [];
2195 const t = exports.t = {};
2198 const createToken = (name, value, isGlobal) => {
2200 debug_1(index, value);
2203 re[index] = new RegExp(value, isGlobal ? 'g' : undefined);
2204 }; // The following Regular Expressions can be used for tokenizing,
2205 // validating, and parsing SemVer version strings.
2206 // ## Numeric Identifier
2207 // A single `0`, or a non-zero digit followed by zero or more digits.
2210 createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*');
2211 createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); // ## Non-numeric Identifier
2212 // Zero or more digits, followed by a letter or hyphen, and then zero or
2213 // more letters, digits, or hyphens.
2215 createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); // ## Main Version
2216 // Three dot-separated numeric identifiers.
2218 createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`);
2219 createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); // ## Pre-release Version Identifier
2220 // A numeric identifier, or a non-numeric identifier.
2222 createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`);
2223 createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`); // ## Pre-release Version
2224 // Hyphen, followed by one or more dot-separated pre-release version
2227 createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
2228 createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); // ## Build Metadata Identifier
2229 // Any combination of digits, letters, or hyphens.
2231 createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); // ## Build Metadata
2232 // Plus sign, followed by one or more period-separated build metadata
2235 createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); // ## Full Version String
2236 // A main version, followed optionally by a pre-release version and
2238 // Note that the only major, minor, patch, and pre-release sections of
2239 // the version string are capturing groups. The build metadata is not a
2240 // capturing group, because it should not ever be used in version
2243 createToken('FULLPLAIN', `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
2244 createToken('FULL', `^${src[t.FULLPLAIN]}$`); // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
2245 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
2246 // common in the npm registry.
2248 createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
2249 createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`);
2250 createToken('GTLT', '((?:<|>)?=?)'); // Something like "2.*" or "1.2.x".
2251 // Note that "x.x" is a valid xRange identifer, meaning "any version"
2252 // Only the first item is strictly required.
2254 createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
2255 createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
2256 createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?` + `)?)?`);
2257 createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?` + `)?)?`);
2258 createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
2259 createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); // Coercion.
2260 // Extract anything that could conceivably be a part of a valid semver
2262 createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`);
2263 createToken('COERCERTL', src[t.COERCE], true); // Tilde ranges.
2264 // Meaning is "reasonably at or greater than"
2266 createToken('LONETILDE', '(?:~>?)');
2267 createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true);
2268 exports.tildeTrimReplace = '$1~';
2269 createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
2270 createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); // Caret ranges.
2271 // Meaning is "at least and backwards compatible with"
2273 createToken('LONECARET', '(?:\\^)');
2274 createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true);
2275 exports.caretTrimReplace = '$1^';
2276 createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
2277 createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); // A simple gt/lt/eq thing, or just "" to indicate "any version"
2279 createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
2280 createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); // An expression to strip any whitespace between the gtlt and the thing
2281 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
2283 createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
2284 exports.comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
2285 // Note that these all use the loose form, because they'll be
2286 // checked against either the strict or loose comparator form
2289 createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`);
2290 createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`); // Star ranges basically just allow anything at all.
2292 createToken('STAR', '(<|>)?=?\\s*\\*'); // >=0.0.0 is like a star
2294 createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$');
2295 createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$');
2298 const numeric = /^[0-9]+$/;
2300 const compareIdentifiers = (a, b) => {
2301 const anum = numeric.test(a);
2302 const bnum = numeric.test(b);
2309 return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
2312 const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
2320 MAX_LENGTH: MAX_LENGTH$1,
2321 MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1
2328 compareIdentifiers: compareIdentifiers$1
2332 constructor(version, options) {
2333 if (!options || typeof options !== 'object') {
2336 includePrerelease: false
2340 if (version instanceof SemVer) {
2341 if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
2344 version = version.version;
2346 } else if (typeof version !== 'string') {
2347 throw new TypeError(`Invalid Version: ${version}`);
2350 if (version.length > MAX_LENGTH$1) {
2351 throw new TypeError(`version is longer than ${MAX_LENGTH$1} characters`);
2354 debug_1('SemVer', version, options);
2355 this.options = options;
2356 this.loose = !!options.loose; // this isn't actually relevant for versions, but keep it so that we
2357 // don't run into trouble passing this.options around.
2359 this.includePrerelease = !!options.includePrerelease;
2360 const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
2363 throw new TypeError(`Invalid Version: ${version}`);
2366 this.raw = version; // these are actually numbers
2372 if (this.major > MAX_SAFE_INTEGER$1 || this.major < 0) {
2373 throw new TypeError('Invalid major version');
2376 if (this.minor > MAX_SAFE_INTEGER$1 || this.minor < 0) {
2377 throw new TypeError('Invalid minor version');
2380 if (this.patch > MAX_SAFE_INTEGER$1 || this.patch < 0) {
2381 throw new TypeError('Invalid patch version');
2382 } // numberify any prerelease numeric ids
2386 this.prerelease = [];
2388 this.prerelease = m[4].split('.').map(id => {
2389 if (/^[0-9]+$/.test(id)) {
2392 if (num >= 0 && num < MAX_SAFE_INTEGER$1) {
2401 this.build = m[5] ? m[5].split('.') : [];
2406 this.version = `${this.major}.${this.minor}.${this.patch}`;
2408 if (this.prerelease.length) {
2409 this.version += `-${this.prerelease.join('.')}`;
2412 return this.version;
2416 return this.version;
2420 debug_1('SemVer.compare', this.version, this.options, other);
2422 if (!(other instanceof SemVer)) {
2423 if (typeof other === 'string' && other === this.version) {
2427 other = new SemVer(other, this.options);
2430 if (other.version === this.version) {
2434 return this.compareMain(other) || this.comparePre(other);
2437 compareMain(other) {
2438 if (!(other instanceof SemVer)) {
2439 other = new SemVer(other, this.options);
2442 return compareIdentifiers$1(this.major, other.major) || compareIdentifiers$1(this.minor, other.minor) || compareIdentifiers$1(this.patch, other.patch);
2446 if (!(other instanceof SemVer)) {
2447 other = new SemVer(other, this.options);
2448 } // NOT having a prerelease is > having one
2451 if (this.prerelease.length && !other.prerelease.length) {
2453 } else if (!this.prerelease.length && other.prerelease.length) {
2455 } else if (!this.prerelease.length && !other.prerelease.length) {
2462 const a = this.prerelease[i];
2463 const b = other.prerelease[i];
2464 debug_1('prerelease compare', i, a, b);
2466 if (a === undefined && b === undefined) {
2468 } else if (b === undefined) {
2470 } else if (a === undefined) {
2472 } else if (a === b) {
2475 return compareIdentifiers$1(a, b);
2480 compareBuild(other) {
2481 if (!(other instanceof SemVer)) {
2482 other = new SemVer(other, this.options);
2488 const a = this.build[i];
2489 const b = other.build[i];
2490 debug_1('prerelease compare', i, a, b);
2492 if (a === undefined && b === undefined) {
2494 } else if (b === undefined) {
2496 } else if (a === undefined) {
2498 } else if (a === b) {
2501 return compareIdentifiers$1(a, b);
2504 } // preminor will bump the version up to the next minor release, and immediately
2505 // down to pre-release. premajor and prepatch work the same way.
2508 inc(release, identifier) {
2511 this.prerelease.length = 0;
2515 this.inc('pre', identifier);
2519 this.prerelease.length = 0;
2522 this.inc('pre', identifier);
2526 // If this is already a prerelease, it will bump to the next version
2527 // drop any prereleases that might already exist, since they are not
2528 // relevant at this point.
2529 this.prerelease.length = 0;
2530 this.inc('patch', identifier);
2531 this.inc('pre', identifier);
2533 // If the input is a non-prerelease version, this acts the same as
2537 if (this.prerelease.length === 0) {
2538 this.inc('patch', identifier);
2541 this.inc('pre', identifier);
2545 // If this is a pre-major version, bump up to the same major version.
2546 // Otherwise increment major.
2547 // 1.0.0-5 bumps to 1.0.0
2548 // 1.1.0 bumps to 2.0.0
2549 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
2555 this.prerelease = [];
2559 // If this is a pre-minor version, bump up to the same minor version.
2560 // Otherwise increment minor.
2561 // 1.2.0-5 bumps to 1.2.0
2562 // 1.2.1 bumps to 1.3.0
2563 if (this.patch !== 0 || this.prerelease.length === 0) {
2568 this.prerelease = [];
2572 // If this is not a pre-release version, it will increment the patch.
2573 // If it is a pre-release it will bump up to the same patch version.
2574 // 1.2.0-5 patches to 1.2.0
2575 // 1.2.0 patches to 1.2.1
2576 if (this.prerelease.length === 0) {
2580 this.prerelease = [];
2582 // This probably shouldn't be used publicly.
2583 // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
2586 if (this.prerelease.length === 0) {
2587 this.prerelease = [0];
2589 let i = this.prerelease.length;
2592 if (typeof this.prerelease[i] === 'number') {
2593 this.prerelease[i]++;
2599 // didn't increment anything
2600 this.prerelease.push(0);
2605 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
2606 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
2607 if (this.prerelease[0] === identifier) {
2608 if (isNaN(this.prerelease[1])) {
2609 this.prerelease = [identifier, 0];
2612 this.prerelease = [identifier, 0];
2619 throw new Error(`invalid increment argument: ${release}`);
2623 this.raw = this.version;
2629 var semver = SemVer;
2631 const compare = (a, b, loose) => new semver(a, loose).compare(new semver(b, loose));
2633 var compare_1 = compare;
2635 const lt = (a, b, loose) => compare_1(a, b, loose) < 0;
2639 const gte = (a, b, loose) => compare_1(a, b, loose) >= 0;
2643 var arrayify = (object, keyName) => Object.entries(object).map(([key, value]) => Object.assign({
2647 var lib = createCommonjsModule(function (module, exports) {
2649 Object.defineProperty(exports, "__esModule", {
2651 }); // In the absence of a WeakSet or WeakMap implementation, don't break, but don't cache either.
2656 for (var _i = 0; _i < arguments.length; _i++) {
2657 args[_i] = arguments[_i];
2661 function createWeakMap() {
2662 if (typeof WeakMap !== 'undefined') {
2663 return new WeakMap();
2665 return fakeSetOrMap();
2669 * Creates and returns a no-op implementation of a WeakMap / WeakSet that never stores anything.
2673 function fakeSetOrMap() {
2683 } // Safe hasOwnProperty
2686 var hop = Object.prototype.hasOwnProperty;
2688 var has = function (obj, prop) {
2689 return hop.call(obj, prop);
2690 }; // Copy all own enumerable properties from source to target
2693 function extend(target, source) {
2694 for (var prop in source) {
2695 if (has(source, prop)) {
2696 target[prop] = source[prop];
2703 var reLeadingNewline = /^[ \t]*(?:\r\n|\r|\n)/;
2704 var reTrailingNewline = /(?:\r\n|\r|\n)[ \t]*$/;
2705 var reStartsWithNewlineOrIsEmpty = /^(?:[\r\n]|$)/;
2706 var reDetectIndentation = /(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/;
2707 var reOnlyWhitespaceWithAtLeastOneNewline = /^[ \t]*[\r\n][ \t\r\n]*$/;
2709 function _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options) {
2710 // If first interpolated value is a reference to outdent,
2711 // determine indentation level from the indentation of the interpolated value.
2712 var indentationLevel = 0;
2713 var match = strings[0].match(reDetectIndentation);
2716 indentationLevel = match[1].length;
2719 var reSource = "(\\r\\n|\\r|\\n).{0," + indentationLevel + "}";
2720 var reMatchIndent = new RegExp(reSource, 'g');
2722 if (firstInterpolatedValueSetsIndentationLevel) {
2723 strings = strings.slice(1);
2726 var newline = options.newline,
2727 trimLeadingNewline = options.trimLeadingNewline,
2728 trimTrailingNewline = options.trimTrailingNewline;
2729 var normalizeNewlines = typeof newline === 'string';
2730 var l = strings.length;
2731 var outdentedStrings = strings.map(function (v, i) {
2732 // Remove leading indentation from all lines
2733 v = v.replace(reMatchIndent, '$1'); // Trim a leading newline from the first string
2735 if (i === 0 && trimLeadingNewline) {
2736 v = v.replace(reLeadingNewline, '');
2737 } // Trim a trailing newline from the last string
2740 if (i === l - 1 && trimTrailingNewline) {
2741 v = v.replace(reTrailingNewline, '');
2742 } // Normalize newlines
2745 if (normalizeNewlines) {
2746 v = v.replace(/\r\n|\n|\r/g, function (_) {
2753 return outdentedStrings;
2756 function concatStringsAndValues(strings, values) {
2759 for (var i = 0, l = strings.length; i < l; i++) {
2770 function isTemplateStringsArray(v) {
2771 return has(v, 'raw') && has(v, 'length');
2774 * It is assumed that opts will not change. If this is a problem, clone your options object and pass the clone to
2781 function createInstance(options) {
2782 /** Cache of pre-processed template literal arrays */
2783 var arrayAutoIndentCache = createWeakMap();
2785 * Cache of pre-processed template literal arrays, where first interpolated value is a reference to outdent,
2786 * before interpolated values are injected.
2789 var arrayFirstInterpSetsIndentCache = createWeakMap();
2791 function outdent(stringsOrOptions) {
2794 for (var _i = 1; _i < arguments.length; _i++) {
2795 values[_i - 1] = arguments[_i];
2797 /* tslint:enable:no-shadowed-variable */
2800 if (isTemplateStringsArray(stringsOrOptions)) {
2801 var strings = stringsOrOptions; // Is first interpolated value a reference to outdent, alone on its own line, without any preceding non-whitespace?
2803 var firstInterpolatedValueSetsIndentationLevel = (values[0] === outdent || values[0] === defaultOutdent) && reOnlyWhitespaceWithAtLeastOneNewline.test(strings[0]) && reStartsWithNewlineOrIsEmpty.test(strings[1]); // Perform outdentation
2805 var cache = firstInterpolatedValueSetsIndentationLevel ? arrayFirstInterpSetsIndentCache : arrayAutoIndentCache;
2806 var renderedArray = cache.get(strings);
2808 if (!renderedArray) {
2809 renderedArray = _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options);
2810 cache.set(strings, renderedArray);
2812 /** If no interpolated values, skip concatenation step */
2815 if (values.length === 0) {
2816 return renderedArray[0];
2818 /** Concatenate string literals with interpolated values */
2821 var rendered = concatStringsAndValues(renderedArray, firstInterpolatedValueSetsIndentationLevel ? values.slice(1) : values);
2824 // Create and return a new instance of outdent with the given options
2825 return createInstance(extend(extend({}, options), stringsOrOptions || {}));
2829 var fullOutdent = extend(outdent, {
2830 string: function (str) {
2831 return _outdentArray([str], false, options)[0];
2837 var defaultOutdent = createInstance({
2838 trimLeadingNewline: true,
2839 trimTrailingNewline: true
2841 exports.outdent = defaultOutdent; // Named exports. Simple and preferred.
2842 // import outdent from 'outdent';
2844 exports.default = defaultOutdent;
2847 // In webpack harmony-modules environments, module.exports is read-only,
2848 // so we fail gracefully.
2850 module.exports = defaultOutdent;
2851 Object.defineProperty(defaultOutdent, '__esModule', {
2854 defaultOutdent.default = defaultOutdent;
2855 defaultOutdent.outdent = defaultOutdent;
2863 const CATEGORY_CONFIG = "Config";
2864 const CATEGORY_EDITOR = "Editor";
2865 const CATEGORY_FORMAT = "Format";
2866 const CATEGORY_OTHER = "Other";
2867 const CATEGORY_OUTPUT = "Output";
2868 const CATEGORY_GLOBAL = "Global";
2869 const CATEGORY_SPECIAL = "Special";
2871 * @typedef {Object} OptionInfo
2872 * @property {string} [since] - available since version
2873 * @property {string} category
2874 * @property {'int' | 'boolean' | 'choice' | 'path'} type
2875 * @property {boolean} [array] - indicate it's an array of the specified type
2876 * @property {OptionValueInfo} [default]
2877 * @property {OptionRangeInfo} [range] - for type int
2878 * @property {string} description
2879 * @property {string} [deprecated] - deprecated since version
2880 * @property {OptionRedirectInfo} [redirect] - redirect deprecated option
2881 * @property {(value: any) => boolean} [exception]
2882 * @property {OptionChoiceInfo[]} [choices] - for type choice
2883 * @property {string} [cliName]
2884 * @property {string} [cliCategory]
2885 * @property {string} [cliDescription]
2887 * @typedef {number | boolean | string} OptionValue
2888 * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo
2890 * @typedef {Object} OptionRedirectInfo
2891 * @property {string} option
2892 * @property {OptionValue} value
2894 * @typedef {Object} OptionRangeInfo
2895 * @property {number} start - recommended range start
2896 * @property {number} end - recommended range end
2897 * @property {number} step - recommended range step
2899 * @typedef {Object} OptionChoiceInfo
2900 * @property {boolean | string} value - boolean for the option that is originally boolean type
2901 * @property {string} description
2902 * @property {string} [since] - undefined if available since the first version of the option
2903 * @property {string} [deprecated] - deprecated since version
2904 * @property {OptionValueInfo} [redirect] - redirect deprecated value
2907 /** @type {{ [name: string]: OptionInfo }} */
2912 category: CATEGORY_SPECIAL,
2920 description: outdent`
2921 Print (to stderr) where a cursor at the given position would move to after formatting.
2922 This option cannot be used with --range-start and --range-end.
2924 cliCategory: CATEGORY_EDITOR
2928 category: CATEGORY_GLOBAL,
2937 description: "Which end of line characters to apply.",
2940 description: "Line Feed only (\\n), common on Linux and macOS as well as inside git repos"
2943 description: "Carriage Return + Line Feed characters (\\r\\n), common on Windows"
2946 description: "Carriage Return character only (\\r), used very rarely"
2949 description: outdent`
2951 (mixed values within one file are normalised by looking at what's used after the first line)
2957 category: CATEGORY_SPECIAL,
2959 description: "Specify the input filepath. This will be used to do parser inference.",
2960 cliName: "stdin-filepath",
2961 cliCategory: CATEGORY_OTHER,
2962 cliDescription: "Path to the file to pretend that stdin comes from."
2966 category: CATEGORY_SPECIAL,
2969 description: "Insert @format pragma into file's first docblock comment.",
2970 cliCategory: CATEGORY_OTHER
2974 category: CATEGORY_GLOBAL,
2983 description: "Which parser to use.",
2984 exception: value => typeof value === "string" || typeof value === "function",
2991 description: "JavaScript"
2993 value: "babel-flow",
2999 description: "TypeScript"
3001 value: "typescript",
3003 description: "TypeScript"
3007 description: "JavaScript"
3011 description: "JavaScript"
3031 description: "JSON5"
3033 value: "json-stringify",
3035 description: "JSON.stringify"
3039 description: "GraphQL"
3043 description: "Markdown"
3059 description: "Handlebars"
3067 description: "Angular"
3071 description: "Lightning Web Components"
3081 category: CATEGORY_GLOBAL,
3082 description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.",
3083 exception: value => typeof value === "string" || typeof value === "object",
3085 cliCategory: CATEGORY_CONFIG
3094 category: CATEGORY_GLOBAL,
3095 description: outdent`
3096 Custom directory that contains prettier plugins in node_modules subdirectory.
3097 Overrides default behavior when plugins are searched relatively to the location of Prettier.
3098 Multiple values are accepted.
3100 exception: value => typeof value === "string" || typeof value === "object",
3101 cliName: "plugin-search-dir",
3102 cliCategory: CATEGORY_CONFIG
3106 category: CATEGORY_GLOBAL,
3109 description: "The line length where Prettier will try wrap.",
3118 category: CATEGORY_SPECIAL,
3126 description: outdent`
3127 Format code ending at a given character offset (exclusive).
3128 The range will extend forwards to the end of the selected statement.
3129 This option cannot be used with --cursor-offset.
3131 cliCategory: CATEGORY_EDITOR
3135 category: CATEGORY_SPECIAL,
3143 description: outdent`
3144 Format code starting at a given character offset.
3145 The range will extend backwards to the start of the first line containing the selected statement.
3146 This option cannot be used with --cursor-offset.
3148 cliCategory: CATEGORY_EDITOR
3152 category: CATEGORY_SPECIAL,
3155 description: outdent`
3156 Require either '@prettier' or '@format' to be present in the file's first docblock comment
3157 in order for it to be formatted.
3159 cliCategory: CATEGORY_OTHER
3163 category: CATEGORY_GLOBAL,
3165 description: "Number of spaces per indentation level.",
3174 category: CATEGORY_GLOBAL,
3177 description: "Indent with tabs instead of spaces."
3179 embeddedLanguageFormatting: {
3181 category: CATEGORY_GLOBAL,
3187 description: "Control how Prettier formats quoted code embedded in the file.",
3190 description: "Format embedded code if Prettier can automatically identify it."
3193 description: "Never automatically format embedded code."
3213 const currentVersion = require$$0.version;
3214 const coreOptions$1 = coreOptions.options;
3216 * Strings in `plugins` and `pluginSearchDirs` are handled by a wrapped version
3217 * of this function created by `withPlugins`. Don't pass them here directly.
3218 * @param {object} param0
3219 * @param {(string | object)[]=} param0.plugins Strings are resolved by `withPlugins`.
3220 * @param {string[]=} param0.pluginSearchDirs Added by `withPlugins`.
3221 * @param {boolean=} param0.showUnreleased
3222 * @param {boolean=} param0.showDeprecated
3223 * @param {boolean=} param0.showInternal
3226 function getSupportInfo({
3228 showUnreleased = false,
3229 showDeprecated = false,
3230 showInternal = false
3232 // pre-release version is smaller than the normal version in semver,
3233 // we need to treat it as the normal one so as to test new features.
3234 const version = currentVersion.split("-", 1)[0];
3235 const languages = plugins.reduce((all, plugin) => all.concat(plugin.languages || []), []).filter(filterSince);
3236 const options = arrayify(Object.assign({}, ...plugins.map(({
3238 }) => 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 => {
3239 option = Object.assign({}, option);
3241 if (Array.isArray(option.default)) {
3242 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;
3245 if (Array.isArray(option.choices)) {
3246 option.choices = option.choices.filter(option => filterSince(option) && filterDeprecated(option));
3248 if (option.name === "parser") {
3249 collectParsersFromLanguages(option, languages, plugins);
3253 const pluginDefaults = plugins.filter(plugin => plugin.defaultOptions && plugin.defaultOptions[option.name] !== undefined).reduce((reduced, plugin) => {
3254 reduced[plugin.name] = plugin.defaultOptions[option.name];
3257 return Object.assign({}, option, {
3266 function filterSince(object) {
3267 return showUnreleased || !("since" in object) || object.since && semver$1.gte(version, object.since);
3270 function filterDeprecated(object) {
3271 return showDeprecated || !("deprecated" in object) || object.deprecated && semver$1.lt(version, object.deprecated);
3274 function mapInternal(object) {
3279 const newObject = _objectWithoutPropertiesLoose(object, ["cliName", "cliCategory", "cliDescription"]);
3285 function collectParsersFromLanguages(option, languages, plugins) {
3286 const existingValues = new Set(option.choices.map(choice => choice.value));
3288 for (const language of languages) {
3289 if (language.parsers) {
3290 for (const value of language.parsers) {
3291 if (!existingValues.has(value)) {
3292 existingValues.add(value);
3293 const plugin = plugins.find(plugin => plugin.parsers && plugin.parsers[value]);
3294 let description = language.name;
3296 if (plugin && plugin.name) {
3297 description += ` (plugin: ${plugin.name})`;
3300 option.choices.push({
3315 getSupportInfo: getSupportInfo$1
3317 const notAsciiRegex = /[^\x20-\x7F]/;
3319 const getPenultimate = arr => arr[arr.length - 2];
3321 * @typedef {{backwards?: boolean}} SkipOptions
3325 * @param {string | RegExp} chars
3326 * @returns {(text: string, index: number | false, opts?: SkipOptions) => number | false}
3330 function skip(chars) {
3331 return (text, index, opts) => {
3332 const backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having
3333 // to check for failures (did someone say monads?).
3335 /* istanbul ignore next */
3337 if (index === false) {
3346 while (cursor >= 0 && cursor < length) {
3347 const c = text.charAt(cursor);
3349 if (chars instanceof RegExp) {
3350 if (!chars.test(c)) {
3353 } else if (!chars.includes(c)) {
3357 backwards ? cursor-- : cursor++;
3360 if (cursor === -1 || cursor === length) {
3361 // If we reached the beginning or end of the file, return the
3362 // out-of-bounds cursor. It's up to the caller to handle this
3363 // correctly. We don't want to indicate `false` though if it
3364 // actually skipped valid characters.
3372 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
3376 const skipWhitespace = skip(/\s/);
3378 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
3381 const skipSpaces = skip(" \t");
3383 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
3386 const skipToLineEnd = skip(",; \t");
3388 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
3391 const skipEverythingButNewLine = skip(/[^\n\r]/);
3393 * @param {string} text
3394 * @param {number | false} index
3395 * @returns {number | false}
3398 function skipInlineComment(text, index) {
3399 /* istanbul ignore next */
3400 if (index === false) {
3404 if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") {
3405 for (let i = index + 2; i < text.length; ++i) {
3406 if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") {
3415 * @param {string} text
3416 * @param {number | false} index
3417 * @returns {number | false}
3421 function skipTrailingComment(text, index) {
3422 /* istanbul ignore next */
3423 if (index === false) {
3427 if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") {
3428 return skipEverythingButNewLine(text, index);
3432 } // This one doesn't use the above helper function because it wants to
3433 // test \r\n in order and `skip` doesn't support ordering and we only
3434 // want to skip one newline. It's simple to implement.
3437 * @param {string} text
3438 * @param {number | false} index
3439 * @param {SkipOptions=} opts
3440 * @returns {number | false}
3444 function skipNewline(text, index, opts) {
3445 const backwards = opts && opts.backwards;
3447 if (index === false) {
3451 const atIndex = text.charAt(index);
3454 // We already replace `\r\n` with `\n` before parsing
3456 /* istanbul ignore next */
3457 if (text.charAt(index - 1) === "\r" && atIndex === "\n") {
3461 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
3465 // We already replace `\r\n` with `\n` before parsing
3467 /* istanbul ignore next */
3468 if (atIndex === "\r" && text.charAt(index + 1) === "\n") {
3472 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
3480 * @param {string} text
3481 * @param {number} index
3482 * @param {SkipOptions=} opts
3483 * @returns {boolean}
3487 function hasNewline(text, index, opts) {
3489 const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
3490 const idx2 = skipNewline(text, idx, opts);
3491 return idx !== idx2;
3494 * @param {string} text
3495 * @param {number} start
3496 * @param {number} end
3497 * @returns {boolean}
3501 function hasNewlineInRange(text, start, end) {
3502 for (let i = start; i < end; ++i) {
3503 if (text.charAt(i) === "\n") {
3509 } // Note: this function doesn't ignore leading comments unlike isNextLineEmpty
3513 * @param {string} text
3515 * @param {(node: N) => number} locStart
3519 function isPreviousLineEmpty(text, node, locStart) {
3520 /** @type {number | false} */
3521 let idx = locStart(node) - 1;
3522 idx = skipSpaces(text, idx, {
3525 idx = skipNewline(text, idx, {
3528 idx = skipSpaces(text, idx, {
3531 const idx2 = skipNewline(text, idx, {
3534 return idx !== idx2;
3537 * @param {string} text
3538 * @param {number} index
3539 * @returns {boolean}
3543 function isNextLineEmptyAfterIndex(text, index) {
3544 /** @type {number | false} */
3546 /** @type {number | false} */
3550 while (idx !== oldIdx) {
3551 // We need to skip all the potential trailing inline comments
3553 idx = skipToLineEnd(text, idx);
3554 idx = skipInlineComment(text, idx);
3555 idx = skipSpaces(text, idx);
3558 idx = skipTrailingComment(text, idx);
3559 idx = skipNewline(text, idx);
3560 return idx !== false && hasNewline(text, idx);
3564 * @param {string} text
3566 * @param {(node: N) => number} locEnd
3567 * @returns {boolean}
3571 function isNextLineEmpty(text, node, locEnd) {
3572 return isNextLineEmptyAfterIndex(text, locEnd(node));
3575 * @param {string} text
3576 * @param {number} idx
3577 * @returns {number | false}
3581 function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) {
3582 /** @type {number | false} */
3584 /** @type {number | false} */
3588 while (nextIdx !== oldIdx) {
3590 nextIdx = skipSpaces(text, nextIdx);
3591 nextIdx = skipInlineComment(text, nextIdx);
3592 nextIdx = skipTrailingComment(text, nextIdx);
3593 nextIdx = skipNewline(text, nextIdx);
3600 * @param {string} text
3602 * @param {(node: N) => number} locEnd
3603 * @returns {number | false}
3607 function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) {
3608 return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node));
3612 * @param {string} text
3614 * @param {(node: N) => number} locEnd
3619 function getNextNonSpaceNonCommentCharacter(text, node, locEnd) {
3620 return text.charAt( // @ts-ignore => TBD: can return false, should we define a fallback?
3621 getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd));
3622 } // Not using, but it's public utils
3624 /* istanbul ignore next */
3627 * @param {string} text
3628 * @param {number} index
3629 * @param {SkipOptions=} opts
3630 * @returns {boolean}
3634 function hasSpaces(text, index, opts) {
3636 const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
3637 return idx !== index;
3640 * @param {string} value
3641 * @param {number} tabWidth
3642 * @param {number=} startIndex
3647 function getAlignmentSize(value, tabWidth, startIndex) {
3648 startIndex = startIndex || 0;
3651 for (let i = startIndex; i < value.length; ++i) {
3652 if (value[i] === "\t") {
3653 // Tabs behave in a way that they are aligned to the nearest
3654 // multiple of tabWidth:
3655 // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4
3656 // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ...
3657 size = size + tabWidth - size % tabWidth;
3666 * @param {string} value
3667 * @param {number} tabWidth
3672 function getIndentSize(value, tabWidth) {
3673 const lastNewlineIndex = value.lastIndexOf("\n");
3675 if (lastNewlineIndex === -1) {
3679 return getAlignmentSize( // All the leading whitespaces
3680 value.slice(lastNewlineIndex + 1).match(/^[\t ]*/)[0], tabWidth);
3683 * @typedef {'"' | "'"} Quote
3688 * @param {string} raw
3689 * @param {Quote} preferredQuote
3694 function getPreferredQuote(raw, preferredQuote) {
3695 // `rawContent` is the string exactly like it appeared in the input source
3696 // code, without its enclosing quotes.
3697 const rawContent = raw.slice(1, -1);
3698 /** @type {{ quote: '"', regex: RegExp }} */
3704 /** @type {{ quote: "'", regex: RegExp }} */
3710 const preferred = preferredQuote === "'" ? single : double;
3711 const alternate = preferred === single ? double : single;
3712 let result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing
3713 // the string, we might want to enclose with the alternate quote instead, to
3714 // minimize the number of escaped quotes.
3716 if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) {
3717 const numPreferredQuotes = (rawContent.match(preferred.regex) || []).length;
3718 const numAlternateQuotes = (rawContent.match(alternate.regex) || []).length;
3719 result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote;
3725 function printString(raw, options, isDirectiveLiteral) {
3726 // `rawContent` is the string exactly like it appeared in the input source
3727 // code, without its enclosing quotes.
3728 const rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap
3729 // the quotes on a DirectiveLiteral.
3731 const canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'");
3732 /** @type {Quote} */
3734 const enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't
3735 // change the escape sequences they use.
3736 // See https://github.com/prettier/prettier/issues/1555
3737 // and https://tc39.github.io/ecma262/#directive-prologue
3739 if (isDirectiveLiteral) {
3740 if (canChangeDirectiveQuotes) {
3741 return enclosingQuote + rawContent + enclosingQuote;
3745 } // It might sound unnecessary to use `makeString` even if the string already
3746 // is enclosed with `enclosingQuote`, but it isn't. The string could contain
3747 // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes
3748 // sure that we consistently output the minimum amount of escaped quotes.
3751 return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.embeddedInHtml));
3754 * @param {string} rawContent
3755 * @param {Quote} enclosingQuote
3756 * @param {boolean=} unescapeUnnecessaryEscapes
3761 function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) {
3762 const otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double).
3764 const regex = /\\([\S\s])|(["'])/g; // Escape and unescape single and double quotes as needed to be able to
3765 // enclose `rawContent` with `enclosingQuote`.
3767 const newContent = rawContent.replace(regex, (match, escaped, quote) => {
3768 // If we matched an escape, and the escaped character is a quote of the
3769 // other type than we intend to enclose the string with, there's no need for
3770 // it to be escaped, so return it _without_ the backslash.
3771 if (escaped === otherQuote) {
3773 } // If we matched an unescaped quote and it is of the _same_ type as we
3774 // intend to enclose the string with, it must be escaped, so return it with
3778 if (quote === enclosingQuote) {
3779 return "\\" + quote;
3784 } // Unescape any unnecessarily escaped character.
3785 // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27
3788 return unescapeUnnecessaryEscapes && /^[^\n\r"'0-7\\bfnrt-vx\u2028\u2029]$/.test(escaped) ? escaped : "\\" + escaped;
3790 return enclosingQuote + newContent + enclosingQuote;
3793 function printNumber(rawNumber) {
3794 return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation.
3795 .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0).
3796 .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit.
3797 .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes.
3798 .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot.
3799 .replace(/\.(?=e|$)/, "");
3802 * @param {string} str
3803 * @param {string} target
3808 function getMaxContinuousCount(str, target) {
3809 const results = str.match(new RegExp(`(${escapeStringRegexp(target)})+`, "g"));
3811 if (results === null) {
3815 return results.reduce((maxCount, result) => Math.max(maxCount, result.length / target.length), 0);
3818 function getMinNotPresentContinuousCount(str, target) {
3819 const matches = str.match(new RegExp(`(${escapeStringRegexp(target)})+`, "g"));
3821 if (matches === null) {
3825 const countPresent = new Map();
3828 for (const match of matches) {
3829 const count = match.length / target.length;
3830 countPresent.set(count, true);
3837 for (let i = 1; i < max; i++) {
3838 if (!countPresent.get(i)) {
3846 * @param {string} text
3851 function getStringWidth(text) {
3854 } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width`
3857 if (!notAsciiRegex.test(text)) {
3861 return stringWidth_1(text);
3864 function isNodeIgnoreComment(comment) {
3865 return comment.value.trim() === "prettier-ignore";
3868 function addCommentHelper(node, comment) {
3869 const comments = node.comments || (node.comments = []);
3870 comments.push(comment);
3871 comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment
3872 // We already "print" it via the raw text, we don't need to re-print it as a
3875 /* istanbul ignore next */
3877 if (node.type === "JSXText") {
3878 comment.printed = true;
3882 function addLeadingComment(node, comment) {
3883 comment.leading = true;
3884 comment.trailing = false;
3885 addCommentHelper(node, comment);
3888 function addDanglingComment(node, comment, marker) {
3889 comment.leading = false;
3890 comment.trailing = false;
3893 comment.marker = marker;
3896 addCommentHelper(node, comment);
3899 function addTrailingComment(node, comment) {
3900 comment.leading = false;
3901 comment.trailing = true;
3902 addCommentHelper(node, comment);
3905 function replaceEndOfLineWith(text, replacement) {
3908 for (const part of text.split("\n")) {
3909 if (parts.length !== 0) {
3910 parts.push(replacement);
3919 function inferParserByLanguage(language, options) {
3922 } = getSupportInfo$1({
3923 plugins: options.plugins
3925 const matched = languages.find(({
3927 }) => name.toLowerCase() === language) || languages.find(({
3929 }) => Array.isArray(aliases) && aliases.includes(language)) || languages.find(({
3931 }) => Array.isArray(extensions) && extensions.includes(`.${language}`));
3932 return matched && matched.parsers[0];
3935 function isFrontMatterNode(node) {
3936 return node && node.type === "front-matter";
3939 function getShebang(text) {
3940 if (!text.startsWith("#!")) {
3944 const index = text.indexOf("\n");
3950 return text.slice(0, index);
3954 inferParserByLanguage,
3955 replaceEndOfLineWith,
3957 getMaxContinuousCount,
3958 getMinNotPresentContinuousCount,
3961 getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
3962 getNextNonSpaceNonCommentCharacterIndex,
3963 getNextNonSpaceNonCommentCharacter,
3968 skipEverythingButNewLine,
3970 skipTrailingComment,
3972 isNextLineEmptyAfterIndex,
3974 isPreviousLineEmpty,
3983 isNodeIgnoreComment,
3992 function guessEndOfLine(text) {
3993 const index = text.indexOf("\r");
3996 return text.charAt(index + 1) === "\n" ? "crlf" : "cr";
4002 function convertEndOfLineToChars(value) {
4015 function countEndOfLineChars(text, eol) {
4017 /* istanbul ignore else */
4021 } else if (eol === "\r") {
4023 } else if (eol === "\r\n") {
4026 throw new Error(`Unexpected "eol" ${JSON.stringify(eol)}.`);
4029 const endOfLines = text.match(regex);
4030 return endOfLines ? endOfLines.length : 0;
4033 function normalizeEndOfLine(text) {
4034 return text.replace(/\r\n?/g, "\n");
4039 convertEndOfLineToChars,
4040 countEndOfLineChars,
4045 getStringWidth: getStringWidth$1
4048 convertEndOfLineToChars: convertEndOfLineToChars$1
4055 /** @type {Record<symbol, typeof MODE_BREAK | typeof MODE_FLAT>} */
4058 const MODE_BREAK = 1;
4059 const MODE_FLAT = 2;
4061 function rootIndent() {
4069 function makeIndent(ind, options) {
4070 return generateInd(ind, {
4075 function makeAlign(indent, n, options) {
4076 if (n === -Infinity) {
4077 return indent.root || rootIndent();
4081 return generateInd(indent, {
4090 if (n.type === "root") {
4091 return Object.assign({}, indent, {
4096 const alignType = typeof n === "string" ? "stringAlign" : "numberAlign";
4097 return generateInd(indent, {
4103 function generateInd(ind, newPart, options) {
4104 const queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart);
4110 for (const part of queue) {
4111 switch (part.type) {
4115 if (options.useTabs) {
4118 addSpaces(options.tabWidth);
4126 length += part.n.length;
4131 lastSpaces += part.n;
4134 /* istanbul ignore next */
4137 throw new Error(`Unexpected type '${part.type}'`);
4142 return Object.assign({}, ind, {
4148 function addTabs(count) {
4149 value += "\t".repeat(count);
4150 length += options.tabWidth * count;
4153 function addSpaces(count) {
4154 value += " ".repeat(count);
4159 if (options.useTabs) {
4166 function flushTabs() {
4174 function flushSpaces() {
4175 if (lastSpaces > 0) {
4176 addSpaces(lastSpaces);
4182 function resetLast() {
4188 function trim$1(out) {
4189 if (out.length === 0) {
4193 let trimCount = 0; // Trim whitespace at the end of line
4195 while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[\t ]*$/)) {
4196 trimCount += out.pop().length;
4199 if (out.length && typeof out[out.length - 1] === "string") {
4200 const trimmed = out[out.length - 1].replace(/[\t ]*$/, "");
4201 trimCount += out[out.length - 1].length - trimmed.length;
4202 out[out.length - 1] = trimmed;
4208 function fits(next, restCommands, width, options, mustBeFlat) {
4209 let restIdx = restCommands.length;
4210 const cmds = [next]; // `out` is only used for width counting because `trim` requires to look
4211 // backwards for space characters.
4215 while (width >= 0) {
4216 if (cmds.length === 0) {
4217 if (restIdx === 0) {
4221 cmds.push(restCommands[restIdx - 1]);
4226 const [ind, mode, doc] = cmds.pop();
4228 if (typeof doc === "string") {
4230 width -= getStringWidth$1(doc);
4234 for (let i = doc.parts.length - 1; i >= 0; i--) {
4235 cmds.push([ind, mode, doc.parts[i]]);
4241 cmds.push([makeIndent(ind, options), mode, doc.contents]);
4245 cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
4249 width += trim$1(out);
4253 if (mustBeFlat && doc.break) {
4257 cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]);
4260 groupModeMap[doc.id] = cmds[cmds.length - 1][1];
4266 for (let i = doc.parts.length - 1; i >= 0; i--) {
4267 cmds.push([ind, mode, doc.parts[i]]);
4274 const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
4276 if (groupMode === MODE_BREAK) {
4277 if (doc.breakContents) {
4278 cmds.push([ind, mode, doc.breakContents]);
4282 if (groupMode === MODE_FLAT) {
4283 if (doc.flatContents) {
4284 cmds.push([ind, mode, doc.flatContents]);
4318 function printDocToString(doc, options) {
4320 const width = options.printWidth;
4321 const newLine = convertEndOfLineToChars$1(options.endOfLine);
4322 let pos = 0; // cmds is basically a stack. We've turned a recursive call into a
4323 // while loop which is much faster. The while loop below adds new
4324 // cmds to the array instead of recursively calling `print`.
4326 const cmds = [[rootIndent(), MODE_BREAK, doc]];
4328 let shouldRemeasure = false;
4329 let lineSuffix = [];
4331 while (cmds.length !== 0) {
4332 const [ind, mode, doc] = cmds.pop();
4334 if (typeof doc === "string") {
4335 const formatted = newLine !== "\n" && doc.includes("\n") ? doc.replace(/\n/g, newLine) : doc;
4336 out.push(formatted);
4337 pos += getStringWidth$1(formatted);
4341 out.push(cursor$1.placeholder);
4345 for (let i = doc.parts.length - 1; i >= 0; i--) {
4346 cmds.push([ind, mode, doc.parts[i]]);
4352 cmds.push([makeIndent(ind, options), mode, doc.contents]);
4356 cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
4366 if (!shouldRemeasure) {
4367 cmds.push([ind, doc.break ? MODE_BREAK : MODE_FLAT, doc.contents]);
4375 shouldRemeasure = false;
4376 const next = [ind, MODE_FLAT, doc.contents];
4377 const rem = width - pos;
4379 if (!doc.break && fits(next, cmds, rem, options)) {
4382 // Expanded states are a rare case where a document
4383 // can manually provide multiple representations of
4384 // itself. It provides an array of documents
4385 // going from the least expanded (most flattened)
4386 // representation first to the most expanded. If a
4387 // group has these, we need to manually go through
4388 // these states and find the first one that fits.
4389 if (doc.expandedStates) {
4390 const mostExpanded = doc.expandedStates[doc.expandedStates.length - 1];
4393 cmds.push([ind, MODE_BREAK, mostExpanded]);
4396 for (let i = 1; i < doc.expandedStates.length + 1; i++) {
4397 if (i >= doc.expandedStates.length) {
4398 cmds.push([ind, MODE_BREAK, mostExpanded]);
4401 const state = doc.expandedStates[i];
4402 const cmd = [ind, MODE_FLAT, state];
4404 if (fits(cmd, cmds, rem, options)) {
4412 cmds.push([ind, MODE_BREAK, doc.contents]);
4421 groupModeMap[doc.id] = cmds[cmds.length - 1][1];
4425 // Fills each line with as much code as possible before moving to a new
4426 // line with the same indentation.
4428 // Expects doc.parts to be an array of alternating content and
4429 // whitespace. The whitespace contains the linebreaks.
4432 // ["I", line, "love", line, "monkeys"]
4434 // [{ type: group, ... }, softline, { type: group, ... }]
4436 // It uses this parts structure to handle three main layout cases:
4437 // * The first two content items fit on the same line without
4439 // -> output the first content item and the whitespace "flat".
4440 // * Only the first content item fits on the line without breaking
4441 // -> output the first content item "flat" and the whitespace with
4443 // * Neither content item fits on the line without breaking
4444 // -> output the first content item and the whitespace with "break".
4448 const rem = width - pos;
4453 if (parts.length === 0) {
4457 const [content, whitespace] = parts;
4458 const contentFlatCmd = [ind, MODE_FLAT, content];
4459 const contentBreakCmd = [ind, MODE_BREAK, content];
4460 const contentFits = fits(contentFlatCmd, [], rem, options, true);
4462 if (parts.length === 1) {
4464 cmds.push(contentFlatCmd);
4466 cmds.push(contentBreakCmd);
4472 const whitespaceFlatCmd = [ind, MODE_FLAT, whitespace];
4473 const whitespaceBreakCmd = [ind, MODE_BREAK, whitespace];
4475 if (parts.length === 2) {
4477 cmds.push(whitespaceFlatCmd);
4478 cmds.push(contentFlatCmd);
4480 cmds.push(whitespaceBreakCmd);
4481 cmds.push(contentBreakCmd);
4485 } // At this point we've handled the first pair (context, separator)
4486 // and will create a new fill doc for the rest of the content.
4487 // Ideally we wouldn't mutate the array here but copying all the
4488 // elements to a new array would make this algorithm quadratic,
4489 // which is unusable for large arrays (e.g. large texts in JSX).
4493 const remainingCmd = [ind, mode, fill$1(parts)];
4494 const secondContent = parts[0];
4495 const firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$1([content, whitespace, secondContent])];
4496 const firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], rem, options, true);
4498 if (firstAndSecondContentFits) {
4499 cmds.push(remainingCmd);
4500 cmds.push(whitespaceFlatCmd);
4501 cmds.push(contentFlatCmd);
4502 } else if (contentFits) {
4503 cmds.push(remainingCmd);
4504 cmds.push(whitespaceBreakCmd);
4505 cmds.push(contentFlatCmd);
4507 cmds.push(remainingCmd);
4508 cmds.push(whitespaceBreakCmd);
4509 cmds.push(contentBreakCmd);
4517 const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
4519 if (groupMode === MODE_BREAK) {
4520 if (doc.breakContents) {
4521 cmds.push([ind, mode, doc.breakContents]);
4525 if (groupMode === MODE_FLAT) {
4526 if (doc.flatContents) {
4527 cmds.push([ind, mode, doc.flatContents]);
4535 lineSuffix.push([ind, mode, doc.contents]);
4538 case "line-suffix-boundary":
4539 if (lineSuffix.length > 0) {
4540 cmds.push([ind, mode, {
4559 // This line was forced into the output even if we
4560 // were in flattened mode, so we need to tell the next
4561 // group that no matter what, it needs to remeasure
4562 // because the previous measurement didn't accurately
4563 // capture the entire expression (this is necessary
4564 // for nested groups)
4565 shouldRemeasure = true;
4571 if (lineSuffix.length) {
4572 cmds.push([ind, mode, doc]);
4573 cmds.push(...lineSuffix.reverse());
4580 out.push(newLine, ind.root.value);
4581 pos = ind.root.length;
4588 out.push(newLine + ind.value);
4597 } // Flush remaining line-suffix contents at the end of the document, in case
4598 // there is no new line after the line-suffix.
4601 if (cmds.length === 0 && lineSuffix.length) {
4602 cmds.push(...lineSuffix.reverse());
4607 const cursorPlaceholderIndex = out.indexOf(cursor$1.placeholder);
4609 if (cursorPlaceholderIndex !== -1) {
4610 const otherCursorPlaceholderIndex = out.indexOf(cursor$1.placeholder, cursorPlaceholderIndex + 1);
4611 const beforeCursor = out.slice(0, cursorPlaceholderIndex).join("");
4612 const aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join("");
4613 const afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join("");
4615 formatted: beforeCursor + aroundCursor + afterCursor,
4616 cursorNodeStart: beforeCursor.length,
4617 cursorNodeText: aroundCursor
4622 formatted: out.join("")
4631 literalline: literalline$1,
4633 } = docBuilders; // Using a unique object to compare by reference.
4635 const traverseDocOnExitStackMarker = {};
4637 function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) {
4638 const docsStack = [doc];
4640 while (docsStack.length !== 0) {
4641 const doc = docsStack.pop();
4643 if (doc === traverseDocOnExitStackMarker) {
4644 onExit(docsStack.pop());
4649 docsStack.push(doc, traverseDocOnExitStackMarker);
4652 if ( // Should Recurse
4653 !onEnter || onEnter(doc) !== false) {
4654 // When there are multiple parts to process,
4655 // the parts need to be pushed onto the stack in reverse order,
4656 // so that they are processed in the original order
4657 // when the stack is popped.
4658 if (doc.type === "concat" || doc.type === "fill") {
4659 for (let ic = doc.parts.length, i = ic - 1; i >= 0; --i) {
4660 docsStack.push(doc.parts[i]);
4662 } else if (doc.type === "if-break") {
4663 if (doc.flatContents) {
4664 docsStack.push(doc.flatContents);
4667 if (doc.breakContents) {
4668 docsStack.push(doc.breakContents);
4670 } else if (doc.type === "group" && doc.expandedStates) {
4671 if (shouldTraverseConditionalGroups) {
4672 for (let ic = doc.expandedStates.length, i = ic - 1; i >= 0; --i) {
4673 docsStack.push(doc.expandedStates[i]);
4676 docsStack.push(doc.contents);
4678 } else if (doc.contents) {
4679 docsStack.push(doc.contents);
4685 function mapDoc(doc, cb) {
4686 if (doc.type === "concat" || doc.type === "fill") {
4687 const parts = doc.parts.map(part => mapDoc(part, cb));
4688 return cb(Object.assign({}, doc, {
4691 } else if (doc.type === "if-break") {
4692 const breakContents = doc.breakContents && mapDoc(doc.breakContents, cb);
4693 const flatContents = doc.flatContents && mapDoc(doc.flatContents, cb);
4694 return cb(Object.assign({}, doc, {
4698 } else if (doc.contents) {
4699 const contents = mapDoc(doc.contents, cb);
4700 return cb(Object.assign({}, doc, {
4708 function findInDoc(doc, fn, defaultValue) {
4709 let result = defaultValue;
4710 let hasStopped = false;
4712 function findInDocOnEnterFn(doc) {
4713 const maybeResult = fn(doc);
4715 if (maybeResult !== undefined) {
4717 result = maybeResult;
4725 traverseDoc(doc, findInDocOnEnterFn);
4729 function isEmpty(n) {
4730 return typeof n === "string" && n.length === 0;
4733 function isLineNextFn(doc) {
4734 if (typeof doc === "string") {
4738 if (doc.type === "line") {
4743 function isLineNext(doc) {
4744 return findInDoc(doc, isLineNextFn, false);
4747 function willBreakFn(doc) {
4748 if (doc.type === "group" && doc.break) {
4752 if (doc.type === "line" && doc.hard) {
4756 if (doc.type === "break-parent") {
4761 function willBreak(doc) {
4762 return findInDoc(doc, willBreakFn, false);
4765 function breakParentGroup(groupStack) {
4766 if (groupStack.length > 0) {
4767 const parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because
4768 // the user is expected to manually handle what breaks.
4770 if (!parentGroup.expandedStates) {
4771 parentGroup.break = true;
4778 function propagateBreaks(doc) {
4779 const alreadyVisitedSet = new Set();
4780 const groupStack = [];
4782 function propagateBreaksOnEnterFn(doc) {
4783 if (doc.type === "break-parent") {
4784 breakParentGroup(groupStack);
4787 if (doc.type === "group") {
4788 groupStack.push(doc);
4790 if (alreadyVisitedSet.has(doc)) {
4794 alreadyVisitedSet.add(doc);
4798 function propagateBreaksOnExitFn(doc) {
4799 if (doc.type === "group") {
4800 const group = groupStack.pop();
4803 breakParentGroup(groupStack);
4808 traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn,
4809 /* shouldTraverseConditionalGroups */
4813 function removeLinesFn(doc) {
4814 // Force this doc into flat mode by statically converting all
4815 // lines into spaces (or soft lines into nothing). Hard lines
4816 // should still output because there's too great of a chance
4817 // of breaking existing assumptions otherwise.
4818 if (doc.type === "line" && !doc.hard) {
4819 return doc.soft ? "" : " ";
4820 } else if (doc.type === "if-break") {
4821 return doc.flatContents || "";
4827 function removeLines(doc) {
4828 return mapDoc(doc, removeLinesFn);
4831 function getInnerParts(doc) {
4835 let lastPart; // Avoid a falsy element like ""
4837 for (let i = doc.parts.length; i > 0 && !lastPart; i--) {
4838 lastPart = parts[i - 1];
4841 if (lastPart.type === "group") {
4842 parts = lastPart.contents.parts;
4848 function stripTrailingHardline(doc, withInnerParts = false) {
4849 // HACK remove ending hardline, original PR: #1984
4850 if (doc.type === "concat" && doc.parts.length !== 0) {
4851 const parts = withInnerParts ? getInnerParts(doc) : doc.parts;
4852 const lastPart = parts[parts.length - 1];
4854 if (lastPart.type === "concat") {
4855 if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") {
4858 parts: parts.slice(0, -1)
4864 parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart))
4872 function normalizeParts(parts) {
4873 const newParts = [];
4874 const restParts = parts.filter(Boolean);
4876 while (restParts.length !== 0) {
4877 const part = restParts.shift();
4883 if (part.type === "concat") {
4884 restParts.unshift(...part.parts);
4888 if (newParts.length !== 0 && typeof newParts[newParts.length - 1] === "string" && typeof part === "string") {
4889 newParts[newParts.length - 1] += part;
4893 newParts.push(part);
4899 function normalizeDoc(doc) {
4900 return mapDoc(doc, currentDoc => {
4901 if (!currentDoc.parts) {
4905 return Object.assign({}, currentDoc, {
4906 parts: normalizeParts(currentDoc.parts)
4911 function replaceNewlinesWithLiterallines(doc) {
4912 return mapDoc(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$2(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$1)) : currentDoc);
4924 stripTrailingHardline,
4927 replaceNewlinesWithLiterallines
4930 function flattenDoc(doc) {
4931 if (doc.type === "concat") {
4934 for (let i = 0; i < doc.parts.length; ++i) {
4935 const doc2 = doc.parts[i];
4937 if (typeof doc2 !== "string" && doc2.type === "concat") {
4938 res.push(...flattenDoc(doc2).parts);
4940 const flattened = flattenDoc(doc2);
4942 if (flattened !== "") {
4943 res.push(flattened);
4948 return Object.assign({}, doc, {
4951 } else if (doc.type === "if-break") {
4952 return Object.assign({}, doc, {
4953 breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null,
4954 flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null
4956 } else if (doc.type === "group") {
4957 return Object.assign({}, doc, {
4958 contents: flattenDoc(doc.contents),
4959 expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates
4961 } else if (doc.contents) {
4962 return Object.assign({}, doc, {
4963 contents: flattenDoc(doc.contents)
4970 function printDoc(doc) {
4971 if (typeof doc === "string") {
4972 return JSON.stringify(doc);
4975 if (doc.type === "line") {
4977 return "literalline";
4991 if (doc.type === "break-parent") {
4992 return "breakParent";
4995 if (doc.type === "trim") {
4999 if (doc.type === "concat") {
5000 return "[" + doc.parts.map(printDoc).join(", ") + "]";
5003 if (doc.type === "indent") {
5004 return "indent(" + printDoc(doc.contents) + ")";
5007 if (doc.type === "align") {
5008 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) + ")";
5011 if (doc.type === "if-break") {
5012 return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")";
5015 if (doc.type === "group") {
5016 if (doc.expandedStates) {
5017 return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])";
5020 return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")";
5023 if (doc.type === "fill") {
5024 return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")";
5027 if (doc.type === "line-suffix") {
5028 return "lineSuffix(" + printDoc(doc.contents) + ")";
5031 if (doc.type === "line-suffix-boundary") {
5032 return "lineSuffixBoundary";
5035 throw new Error("Unknown doc type " + doc.type);
5039 printDocToDebug(doc) {
5040 return printDoc(flattenDoc(doc));
5046 * @typedef {import("./doc-builders").Doc} Doc
5051 builders: docBuilders,
5052 printer: docPrinter,
5063 constructor(file, options) {
5064 options = options || {};
5065 if (!options.readChunk) options.readChunk = 1024;
5067 if (!options.newLineCharacter) {
5068 options.newLineCharacter = 0x0a; //linux line ending
5070 options.newLineCharacter = options.newLineCharacter.charCodeAt(0);
5073 if (typeof file === 'number') {
5076 this.fd = fs__default['default'].openSync(file, 'r');
5079 this.options = options;
5080 this.newLineCharacter = options.newLineCharacter;
5084 _searchInBuffer(buffer, hexNeedle) {
5087 for (let i = 0; i <= buffer.length; i++) {
5088 let b_byte = buffer[i];
5090 if (b_byte === hexNeedle) {
5100 this.eofReached = false;
5101 this.linesCache = [];
5102 this.fdPosition = 0;
5106 fs__default['default'].closeSync(this.fd);
5110 _extractLines(buffer) {
5113 let bufferPosition = 0;
5114 let lastNewLineBufferPosition = 0;
5117 let bufferPositionValue = buffer[bufferPosition++];
5119 if (bufferPositionValue === this.newLineCharacter) {
5120 line = buffer.slice(lastNewLineBufferPosition, bufferPosition);
5122 lastNewLineBufferPosition = bufferPosition;
5123 } else if (bufferPositionValue === undefined) {
5128 let leftovers = buffer.slice(lastNewLineBufferPosition, bufferPosition);
5130 if (leftovers.length) {
5131 lines.push(leftovers);
5137 _readChunk(lineLeftovers) {
5138 let totalBytesRead = 0;
5143 const readBuffer = new Buffer(this.options.readChunk);
5144 bytesRead = fs__default['default'].readSync(this.fd, readBuffer, 0, this.options.readChunk, this.fdPosition);
5145 totalBytesRead = totalBytesRead + bytesRead;
5146 this.fdPosition = this.fdPosition + bytesRead;
5147 buffers.push(readBuffer);
5148 } while (bytesRead && this._searchInBuffer(buffers[buffers.length - 1], this.options.newLineCharacter) === -1);
5150 let bufferData = Buffer.concat(buffers);
5152 if (bytesRead < this.options.readChunk) {
5153 this.eofReached = true;
5154 bufferData = bufferData.slice(0, totalBytesRead);
5157 if (totalBytesRead) {
5158 this.linesCache = this._extractLines(bufferData);
5160 if (lineLeftovers) {
5161 this.linesCache[0] = Buffer.concat([lineLeftovers, this.linesCache[0]]);
5165 return totalBytesRead;
5169 if (!this.fd) return false;
5172 if (this.eofReached && this.linesCache.length === 0) {
5178 if (!this.linesCache.length) {
5179 bytesRead = this._readChunk();
5182 if (this.linesCache.length) {
5183 line = this.linesCache.shift();
5184 const lastLineCharacter = line[line.length - 1];
5186 if (lastLineCharacter !== this.newLineCharacter) {
5187 bytesRead = this._readChunk(line);
5190 line = this.linesCache.shift();
5195 if (this.eofReached && this.linesCache.length === 0) {
5199 if (line && line[line.length - 1] === this.newLineCharacter) {
5200 line = line.slice(0, line.length - 1);
5208 var readlines = LineByLine;
5211 * The inverse of `_.toPairs`; this method returns an object composed
5212 * from key-value `pairs`.
5218 * @param {Array} pairs The key-value pairs.
5219 * @returns {Object} Returns the new object.
5222 * _.fromPairs([['a', 1], ['b', 2]]);
5223 * // => { 'a': 1, 'b': 2 }
5225 function fromPairs(pairs) {
5227 length = pairs == null ? 0 : pairs.length,
5230 while (++index < length) {
5231 var pair = pairs[index];
5232 result[pair[0]] = pair[1];
5238 var fromPairs_1 = fromPairs;
5240 class ConfigError extends Error {}
5242 class DebugError extends Error {}
5244 class UndefinedParserError extends Error {}
5249 UndefinedParserError
5252 /*! *****************************************************************************
\r
5253 Copyright (c) Microsoft Corporation.
\r
5255 Permission to use, copy, modify, and/or distribute this software for any
\r
5256 purpose with or without fee is hereby granted.
\r
5258 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
\r
5259 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
\r
5260 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
\r
5261 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
\r
5262 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
\r
5263 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
\r
5264 PERFORMANCE OF THIS SOFTWARE.
\r
5265 ***************************************************************************** */
5267 /* global Reflect, Promise */
5268 var extendStatics = function (d, b) {
5269 extendStatics = Object.setPrototypeOf || {
5271 } instanceof Array && function (d, b) {
5273 } || function (d, b) {
5274 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5277 return extendStatics(d, b);
5280 function __extends(d, b) {
5281 extendStatics(d, b);
5284 this.constructor = d;
5287 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5289 var __assign = function () {
5290 __assign = Object.assign || function __assign(t) {
5291 for (var s, i = 1, n = arguments.length; i < n; i++) {
5294 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
5300 return __assign.apply(this, arguments);
5302 function __rest(s, e) {
5305 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
5307 if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
5308 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
5312 function __decorate(decorators, target, key, desc) {
5313 var c = arguments.length,
5314 r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
5316 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;
5317 return c > 3 && r && Object.defineProperty(target, key, r), r;
5319 function __param(paramIndex, decorator) {
5320 return function (target, key) {
5321 decorator(target, key, paramIndex);
5324 function __metadata(metadataKey, metadataValue) {
5325 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
5327 function __awaiter(thisArg, _arguments, P, generator) {
5328 function adopt(value) {
5329 return value instanceof P ? value : new P(function (resolve) {
5334 return new (P || (P = Promise))(function (resolve, reject) {
5335 function fulfilled(value) {
5337 step(generator.next(value));
5343 function rejected(value) {
5345 step(generator["throw"](value));
5351 function step(result) {
5352 result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
5355 step((generator = generator.apply(thisArg, _arguments || [])).next());
5358 function __generator(thisArg, body) {
5362 if (t[0] & 1) throw t[1];
5376 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
5381 return function (v) {
5382 return step([n, v]);
5387 if (f) throw new TypeError("Generator is already executing.");
5390 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;
5391 if (y = 0, t) op = [op[0] & 2, t.value];
5420 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
5425 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
5430 if (op[0] === 6 && _.label < t[1]) {
5436 if (t && _.label < t[2]) {
5444 if (t[2]) _.ops.pop();
5451 op = body.call(thisArg, _);
5459 if (op[0] & 5) throw op[1];
5461 value: op[0] ? op[1] : void 0,
5466 function __createBinding(o, m, k, k2) {
5467 if (k2 === undefined) k2 = k;
5470 function __exportStar(m, exports) {
5471 for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p];
5473 function __values(o) {
5474 var s = typeof Symbol === "function" && Symbol.iterator,
5477 if (m) return m.call(o);
5478 if (o && typeof o.length === "number") return {
5480 if (o && i >= o.length) o = void 0;
5487 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
5489 function __read(o, n) {
5490 var m = typeof Symbol === "function" && o[Symbol.iterator];
5498 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
5505 if (r && !r.done && (m = i["return"])) m.call(i);
5507 if (e) throw e.error;
5513 function __spread() {
5514 for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
5518 function __spreadArrays() {
5519 for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
5521 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];
5525 function __await(v) {
5526 return this instanceof __await ? (this.v = v, this) : new __await(v);
5528 function __asyncGenerator(thisArg, _arguments, generator) {
5529 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
5530 var g = generator.apply(thisArg, _arguments || []),
5533 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
5538 if (g[n]) i[n] = function (v) {
5539 return new Promise(function (a, b) {
5540 q.push([n, v, a, b]) > 1 || resume(n, v);
5545 function resume(n, v) {
5554 r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
5557 function fulfill(value) {
5558 resume("next", value);
5561 function reject(value) {
5562 resume("throw", value);
5565 function settle(f, v) {
5566 if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
5569 function __asyncDelegator(o) {
5571 return i = {}, verb("next"), verb("throw", function (e) {
5573 }), verb("return"), i[Symbol.iterator] = function () {
5577 function verb(n, f) {
5578 i[n] = o[n] ? function (v) {
5580 value: __await(o[n](v)),
5581 done: n === "return"
5586 function __asyncValues(o) {
5587 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
5588 var m = o[Symbol.asyncIterator],
5590 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 () {
5595 i[n] = o[n] && function (v) {
5596 return new Promise(function (resolve, reject) {
5597 v = o[n](v), settle(resolve, reject, v.done, v.value);
5602 function settle(resolve, reject, d, v) {
5603 Promise.resolve(v).then(function (v) {
5611 function __makeTemplateObject(cooked, raw) {
5612 if (Object.defineProperty) {
5613 Object.defineProperty(cooked, "raw", {
5622 function __importStar(mod) {
5623 if (mod && mod.__esModule) return mod;
5625 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
5626 result.default = mod;
5629 function __importDefault(mod) {
5630 return mod && mod.__esModule ? mod : {
5634 function __classPrivateFieldGet(receiver, privateMap) {
5635 if (!privateMap.has(receiver)) {
5636 throw new TypeError("attempted to get private field on non-instance");
5639 return privateMap.get(receiver);
5641 function __classPrivateFieldSet(receiver, privateMap, value) {
5642 if (!privateMap.has(receiver)) {
5643 throw new TypeError("attempted to set private field on non-instance");
5646 privateMap.set(receiver, value);
5650 var tslib_es6 = /*#__PURE__*/Object.freeze({
5652 __extends: __extends,
5653 get __assign () { return __assign; },
5655 __decorate: __decorate,
5657 __metadata: __metadata,
5658 __awaiter: __awaiter,
5659 __generator: __generator,
5660 __createBinding: __createBinding,
5661 __exportStar: __exportStar,
5665 __spreadArrays: __spreadArrays,
5667 __asyncGenerator: __asyncGenerator,
5668 __asyncDelegator: __asyncDelegator,
5669 __asyncValues: __asyncValues,
5670 __makeTemplateObject: __makeTemplateObject,
5671 __importStar: __importStar,
5672 __importDefault: __importDefault,
5673 __classPrivateFieldGet: __classPrivateFieldGet,
5674 __classPrivateFieldSet: __classPrivateFieldSet
5677 var api = createCommonjsModule(function (module, exports) {
5679 Object.defineProperty(exports, "__esModule", {
5682 exports.apiDescriptor = {
5683 key: key => /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(key) ? key : JSON.stringify(key),
5686 if (value === null || typeof value !== 'object') {
5687 return JSON.stringify(value);
5690 if (Array.isArray(value)) {
5691 return `[${value.map(subValue => exports.apiDescriptor.value(subValue)).join(', ')}]`;
5694 const keys = Object.keys(value);
5695 return keys.length === 0 ? '{}' : `{ ${keys.map(key => `${exports.apiDescriptor.key(key)}: ${exports.apiDescriptor.value(value[key])}`).join(', ')} }`;
5701 }) => exports.apiDescriptor.value({
5707 var descriptors = createCommonjsModule(function (module, exports) {
5709 Object.defineProperty(exports, "__esModule", {
5713 tslib_es6.__exportStar(api, exports);
5716 var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
5718 var escapeStringRegexp$1 = function (str) {
5719 if (typeof str !== 'string') {
5720 throw new TypeError('Expected a string');
5723 return str.replace(matchOperatorsRe, '\\$&');
5727 "aliceblue": [240, 248, 255],
5728 "antiquewhite": [250, 235, 215],
5729 "aqua": [0, 255, 255],
5730 "aquamarine": [127, 255, 212],
5731 "azure": [240, 255, 255],
5732 "beige": [245, 245, 220],
5733 "bisque": [255, 228, 196],
5735 "blanchedalmond": [255, 235, 205],
5736 "blue": [0, 0, 255],
5737 "blueviolet": [138, 43, 226],
5738 "brown": [165, 42, 42],
5739 "burlywood": [222, 184, 135],
5740 "cadetblue": [95, 158, 160],
5741 "chartreuse": [127, 255, 0],
5742 "chocolate": [210, 105, 30],
5743 "coral": [255, 127, 80],
5744 "cornflowerblue": [100, 149, 237],
5745 "cornsilk": [255, 248, 220],
5746 "crimson": [220, 20, 60],
5747 "cyan": [0, 255, 255],
5748 "darkblue": [0, 0, 139],
5749 "darkcyan": [0, 139, 139],
5750 "darkgoldenrod": [184, 134, 11],
5751 "darkgray": [169, 169, 169],
5752 "darkgreen": [0, 100, 0],
5753 "darkgrey": [169, 169, 169],
5754 "darkkhaki": [189, 183, 107],
5755 "darkmagenta": [139, 0, 139],
5756 "darkolivegreen": [85, 107, 47],
5757 "darkorange": [255, 140, 0],
5758 "darkorchid": [153, 50, 204],
5759 "darkred": [139, 0, 0],
5760 "darksalmon": [233, 150, 122],
5761 "darkseagreen": [143, 188, 143],
5762 "darkslateblue": [72, 61, 139],
5763 "darkslategray": [47, 79, 79],
5764 "darkslategrey": [47, 79, 79],
5765 "darkturquoise": [0, 206, 209],
5766 "darkviolet": [148, 0, 211],
5767 "deeppink": [255, 20, 147],
5768 "deepskyblue": [0, 191, 255],
5769 "dimgray": [105, 105, 105],
5770 "dimgrey": [105, 105, 105],
5771 "dodgerblue": [30, 144, 255],
5772 "firebrick": [178, 34, 34],
5773 "floralwhite": [255, 250, 240],
5774 "forestgreen": [34, 139, 34],
5775 "fuchsia": [255, 0, 255],
5776 "gainsboro": [220, 220, 220],
5777 "ghostwhite": [248, 248, 255],
5778 "gold": [255, 215, 0],
5779 "goldenrod": [218, 165, 32],
5780 "gray": [128, 128, 128],
5781 "green": [0, 128, 0],
5782 "greenyellow": [173, 255, 47],
5783 "grey": [128, 128, 128],
5784 "honeydew": [240, 255, 240],
5785 "hotpink": [255, 105, 180],
5786 "indianred": [205, 92, 92],
5787 "indigo": [75, 0, 130],
5788 "ivory": [255, 255, 240],
5789 "khaki": [240, 230, 140],
5790 "lavender": [230, 230, 250],
5791 "lavenderblush": [255, 240, 245],
5792 "lawngreen": [124, 252, 0],
5793 "lemonchiffon": [255, 250, 205],
5794 "lightblue": [173, 216, 230],
5795 "lightcoral": [240, 128, 128],
5796 "lightcyan": [224, 255, 255],
5797 "lightgoldenrodyellow": [250, 250, 210],
5798 "lightgray": [211, 211, 211],
5799 "lightgreen": [144, 238, 144],
5800 "lightgrey": [211, 211, 211],
5801 "lightpink": [255, 182, 193],
5802 "lightsalmon": [255, 160, 122],
5803 "lightseagreen": [32, 178, 170],
5804 "lightskyblue": [135, 206, 250],
5805 "lightslategray": [119, 136, 153],
5806 "lightslategrey": [119, 136, 153],
5807 "lightsteelblue": [176, 196, 222],
5808 "lightyellow": [255, 255, 224],
5809 "lime": [0, 255, 0],
5810 "limegreen": [50, 205, 50],
5811 "linen": [250, 240, 230],
5812 "magenta": [255, 0, 255],
5813 "maroon": [128, 0, 0],
5814 "mediumaquamarine": [102, 205, 170],
5815 "mediumblue": [0, 0, 205],
5816 "mediumorchid": [186, 85, 211],
5817 "mediumpurple": [147, 112, 219],
5818 "mediumseagreen": [60, 179, 113],
5819 "mediumslateblue": [123, 104, 238],
5820 "mediumspringgreen": [0, 250, 154],
5821 "mediumturquoise": [72, 209, 204],
5822 "mediumvioletred": [199, 21, 133],
5823 "midnightblue": [25, 25, 112],
5824 "mintcream": [245, 255, 250],
5825 "mistyrose": [255, 228, 225],
5826 "moccasin": [255, 228, 181],
5827 "navajowhite": [255, 222, 173],
5828 "navy": [0, 0, 128],
5829 "oldlace": [253, 245, 230],
5830 "olive": [128, 128, 0],
5831 "olivedrab": [107, 142, 35],
5832 "orange": [255, 165, 0],
5833 "orangered": [255, 69, 0],
5834 "orchid": [218, 112, 214],
5835 "palegoldenrod": [238, 232, 170],
5836 "palegreen": [152, 251, 152],
5837 "paleturquoise": [175, 238, 238],
5838 "palevioletred": [219, 112, 147],
5839 "papayawhip": [255, 239, 213],
5840 "peachpuff": [255, 218, 185],
5841 "peru": [205, 133, 63],
5842 "pink": [255, 192, 203],
5843 "plum": [221, 160, 221],
5844 "powderblue": [176, 224, 230],
5845 "purple": [128, 0, 128],
5846 "rebeccapurple": [102, 51, 153],
5848 "rosybrown": [188, 143, 143],
5849 "royalblue": [65, 105, 225],
5850 "saddlebrown": [139, 69, 19],
5851 "salmon": [250, 128, 114],
5852 "sandybrown": [244, 164, 96],
5853 "seagreen": [46, 139, 87],
5854 "seashell": [255, 245, 238],
5855 "sienna": [160, 82, 45],
5856 "silver": [192, 192, 192],
5857 "skyblue": [135, 206, 235],
5858 "slateblue": [106, 90, 205],
5859 "slategray": [112, 128, 144],
5860 "slategrey": [112, 128, 144],
5861 "snow": [255, 250, 250],
5862 "springgreen": [0, 255, 127],
5863 "steelblue": [70, 130, 180],
5864 "tan": [210, 180, 140],
5865 "teal": [0, 128, 128],
5866 "thistle": [216, 191, 216],
5867 "tomato": [255, 99, 71],
5868 "turquoise": [64, 224, 208],
5869 "violet": [238, 130, 238],
5870 "wheat": [245, 222, 179],
5871 "white": [255, 255, 255],
5872 "whitesmoke": [245, 245, 245],
5873 "yellow": [255, 255, 0],
5874 "yellowgreen": [154, 205, 50]
5877 var conversions = createCommonjsModule(function (module) {
5879 // NOTE: conversions should only return primitive values (i.e. arrays, or
5880 // values that give correct `typeof` results).
5881 // do not use box values types (i.e. Number(), String(), etc.)
5882 var reverseKeywords = {};
5884 for (var key in colorName) {
5885 if (colorName.hasOwnProperty(key)) {
5886 reverseKeywords[colorName[key]] = key;
5890 var convert = module.exports = {
5941 labels: ['h', 'c', 'g']
5945 labels: ['r16', 'g16', 'b16']
5951 }; // hide .channels and .labels properties
5953 for (var model in convert) {
5954 if (convert.hasOwnProperty(model)) {
5955 if (!('channels' in convert[model])) {
5956 throw new Error('missing channels property: ' + model);
5959 if (!('labels' in convert[model])) {
5960 throw new Error('missing channel labels property: ' + model);
5963 if (convert[model].labels.length !== convert[model].channels) {
5964 throw new Error('channel and label counts mismatch: ' + model);
5967 var channels = convert[model].channels;
5968 var labels = convert[model].labels;
5969 delete convert[model].channels;
5970 delete convert[model].labels;
5971 Object.defineProperty(convert[model], 'channels', {
5974 Object.defineProperty(convert[model], 'labels', {
5980 convert.rgb.hsl = function (rgb) {
5981 var r = rgb[0] / 255;
5982 var g = rgb[1] / 255;
5983 var b = rgb[2] / 255;
5984 var min = Math.min(r, g, b);
5985 var max = Math.max(r, g, b);
5986 var delta = max - min;
5993 } else if (r === max) {
5994 h = (g - b) / delta;
5995 } else if (g === max) {
5996 h = 2 + (b - r) / delta;
5997 } else if (b === max) {
5998 h = 4 + (r - g) / delta;
6001 h = Math.min(h * 60, 360);
6007 l = (min + max) / 2;
6011 } else if (l <= 0.5) {
6012 s = delta / (max + min);
6014 s = delta / (2 - max - min);
6017 return [h, s * 100, l * 100];
6020 convert.rgb.hsv = function (rgb) {
6026 var r = rgb[0] / 255;
6027 var g = rgb[1] / 255;
6028 var b = rgb[2] / 255;
6029 var v = Math.max(r, g, b);
6030 var diff = v - Math.min(r, g, b);
6032 var diffc = function (c) {
6033 return (v - c) / 6 / diff + 1 / 2;
6046 } else if (g === v) {
6047 h = 1 / 3 + rdif - bdif;
6048 } else if (b === v) {
6049 h = 2 / 3 + gdif - rdif;
6059 return [h * 360, s * 100, v * 100];
6062 convert.rgb.hwb = function (rgb) {
6066 var h = convert.rgb.hsl(rgb)[0];
6067 var w = 1 / 255 * Math.min(r, Math.min(g, b));
6068 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
6069 return [h, w * 100, b * 100];
6072 convert.rgb.cmyk = function (rgb) {
6073 var r = rgb[0] / 255;
6074 var g = rgb[1] / 255;
6075 var b = rgb[2] / 255;
6080 k = Math.min(1 - r, 1 - g, 1 - b);
6081 c = (1 - r - k) / (1 - k) || 0;
6082 m = (1 - g - k) / (1 - k) || 0;
6083 y = (1 - b - k) / (1 - k) || 0;
6084 return [c * 100, m * 100, y * 100, k * 100];
6087 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
6091 function comparativeDistance(x, y) {
6092 return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
6095 convert.rgb.keyword = function (rgb) {
6096 var reversed = reverseKeywords[rgb];
6102 var currentClosestDistance = Infinity;
6103 var currentClosestKeyword;
6105 for (var keyword in colorName) {
6106 if (colorName.hasOwnProperty(keyword)) {
6107 var value = colorName[keyword]; // Compute comparative distance
6109 var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
6111 if (distance < currentClosestDistance) {
6112 currentClosestDistance = distance;
6113 currentClosestKeyword = keyword;
6118 return currentClosestKeyword;
6121 convert.keyword.rgb = function (keyword) {
6122 return colorName[keyword];
6125 convert.rgb.xyz = function (rgb) {
6126 var r = rgb[0] / 255;
6127 var g = rgb[1] / 255;
6128 var b = rgb[2] / 255; // assume sRGB
6130 r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
6131 g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
6132 b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
6133 var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
6134 var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
6135 var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
6136 return [x * 100, y * 100, z * 100];
6139 convert.rgb.lab = function (rgb) {
6140 var xyz = convert.rgb.xyz(rgb);
6150 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
6151 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
6152 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
6159 convert.hsl.rgb = function (hsl) {
6160 var h = hsl[0] / 360;
6161 var s = hsl[1] / 100;
6162 var l = hsl[2] / 100;
6171 return [val, val, val];
6183 for (var i = 0; i < 3; i++) {
6184 t3 = h + 1 / 3 * -(i - 1);
6195 val = t1 + (t2 - t1) * 6 * t3;
6196 } else if (2 * t3 < 1) {
6198 } else if (3 * t3 < 2) {
6199 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
6210 convert.hsl.hsv = function (hsl) {
6212 var s = hsl[1] / 100;
6213 var l = hsl[2] / 100;
6215 var lmin = Math.max(l, 0.01);
6219 s *= l <= 1 ? l : 2 - l;
6220 smin *= lmin <= 1 ? lmin : 2 - lmin;
6222 sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
6223 return [h, sv * 100, v * 100];
6226 convert.hsv.rgb = function (hsv) {
6227 var h = hsv[0] / 60;
6228 var s = hsv[1] / 100;
6229 var v = hsv[2] / 100;
6230 var hi = Math.floor(h) % 6;
6231 var f = h - Math.floor(h);
6232 var p = 255 * v * (1 - s);
6233 var q = 255 * v * (1 - s * f);
6234 var t = 255 * v * (1 - s * (1 - f));
6258 convert.hsv.hsl = function (hsv) {
6260 var s = hsv[1] / 100;
6261 var v = hsv[2] / 100;
6262 var vmin = Math.max(v, 0.01);
6267 lmin = (2 - s) * vmin;
6269 sl /= lmin <= 1 ? lmin : 2 - lmin;
6272 return [h, sl * 100, l * 100];
6273 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
6276 convert.hwb.rgb = function (hwb) {
6277 var h = hwb[0] / 360;
6278 var wh = hwb[1] / 100;
6279 var bl = hwb[2] / 100;
6280 var ratio = wh + bl;
6284 var n; // wh + bl cant be > 1
6291 i = Math.floor(6 * h);
6295 if ((i & 0x01) !== 0) {
6299 n = wh + f * (v - wh); // linear interpolation
6345 return [r * 255, g * 255, b * 255];
6348 convert.cmyk.rgb = function (cmyk) {
6349 var c = cmyk[0] / 100;
6350 var m = cmyk[1] / 100;
6351 var y = cmyk[2] / 100;
6352 var k = cmyk[3] / 100;
6356 r = 1 - Math.min(1, c * (1 - k) + k);
6357 g = 1 - Math.min(1, m * (1 - k) + k);
6358 b = 1 - Math.min(1, y * (1 - k) + k);
6359 return [r * 255, g * 255, b * 255];
6362 convert.xyz.rgb = function (xyz) {
6363 var x = xyz[0] / 100;
6364 var y = xyz[1] / 100;
6365 var z = xyz[2] / 100;
6369 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
6370 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
6371 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
6373 r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
6374 g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
6375 b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
6376 r = Math.min(Math.max(0, r), 1);
6377 g = Math.min(Math.max(0, g), 1);
6378 b = Math.min(Math.max(0, b), 1);
6379 return [r * 255, g * 255, b * 255];
6382 convert.xyz.lab = function (xyz) {
6392 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
6393 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
6394 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
6401 convert.lab.xyz = function (lab) {
6411 var y2 = Math.pow(y, 3);
6412 var x2 = Math.pow(x, 3);
6413 var z2 = Math.pow(z, 3);
6414 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
6415 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
6416 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
6423 convert.lab.lch = function (lab) {
6430 hr = Math.atan2(b, a);
6431 h = hr * 360 / 2 / Math.PI;
6437 c = Math.sqrt(a * a + b * b);
6441 convert.lch.lab = function (lch) {
6448 hr = h / 360 * 2 * Math.PI;
6449 a = c * Math.cos(hr);
6450 b = c * Math.sin(hr);
6454 convert.rgb.ansi16 = function (args) {
6458 var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
6460 value = Math.round(value / 50);
6466 var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
6475 convert.hsv.ansi16 = function (args) {
6476 // optimization here; we already know the value and don't need to get
6477 // it converted for us.
6478 return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
6481 convert.rgb.ansi256 = function (args) {
6484 var b = args[2]; // we use the extended greyscale palette here, with the exception of
6485 // black and white. normal palette only has 4 greyscale shades.
6487 if (r === g && g === b) {
6496 return Math.round((r - 8) / 247 * 24) + 232;
6499 var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
6503 convert.ansi16.rgb = function (args) {
6504 var color = args % 10; // handle greyscale
6506 if (color === 0 || color === 7) {
6511 color = color / 10.5 * 255;
6512 return [color, color, color];
6515 var mult = (~~(args > 50) + 1) * 0.5;
6516 var r = (color & 1) * mult * 255;
6517 var g = (color >> 1 & 1) * mult * 255;
6518 var b = (color >> 2 & 1) * mult * 255;
6522 convert.ansi256.rgb = function (args) {
6525 var c = (args - 232) * 10 + 8;
6531 var r = Math.floor(args / 36) / 5 * 255;
6532 var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
6533 var b = rem % 6 / 5 * 255;
6537 convert.rgb.hex = function (args) {
6538 var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
6539 var string = integer.toString(16).toUpperCase();
6540 return '000000'.substring(string.length) + string;
6543 convert.hex.rgb = function (args) {
6544 var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
6550 var colorString = match[0];
6552 if (match[0].length === 3) {
6553 colorString = colorString.split('').map(function (char) {
6558 var integer = parseInt(colorString, 16);
6559 var r = integer >> 16 & 0xFF;
6560 var g = integer >> 8 & 0xFF;
6561 var b = integer & 0xFF;
6565 convert.rgb.hcg = function (rgb) {
6566 var r = rgb[0] / 255;
6567 var g = rgb[1] / 255;
6568 var b = rgb[2] / 255;
6569 var max = Math.max(Math.max(r, g), b);
6570 var min = Math.min(Math.min(r, g), b);
6571 var chroma = max - min;
6576 grayscale = min / (1 - chroma);
6583 } else if (max === r) {
6584 hue = (g - b) / chroma % 6;
6585 } else if (max === g) {
6586 hue = 2 + (b - r) / chroma;
6588 hue = 4 + (r - g) / chroma + 4;
6593 return [hue * 360, chroma * 100, grayscale * 100];
6596 convert.hsl.hcg = function (hsl) {
6597 var s = hsl[1] / 100;
6598 var l = hsl[2] / 100;
6605 c = 2.0 * s * (1.0 - l);
6609 f = (l - 0.5 * c) / (1.0 - c);
6612 return [hsl[0], c * 100, f * 100];
6615 convert.hsv.hcg = function (hsv) {
6616 var s = hsv[1] / 100;
6617 var v = hsv[2] / 100;
6622 f = (v - c) / (1 - c);
6625 return [hsv[0], c * 100, f * 100];
6628 convert.hcg.rgb = function (hcg) {
6629 var h = hcg[0] / 360;
6630 var c = hcg[1] / 100;
6631 var g = hcg[2] / 100;
6634 return [g * 255, g * 255, g * 255];
6637 var pure = [0, 0, 0];
6643 switch (Math.floor(hi)) {
6681 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
6684 convert.hcg.hsv = function (hcg) {
6685 var c = hcg[1] / 100;
6686 var g = hcg[2] / 100;
6687 var v = c + g * (1.0 - c);
6694 return [hcg[0], f * 100, v * 100];
6697 convert.hcg.hsl = function (hcg) {
6698 var c = hcg[1] / 100;
6699 var g = hcg[2] / 100;
6700 var l = g * (1.0 - c) + 0.5 * c;
6703 if (l > 0.0 && l < 0.5) {
6705 } else if (l >= 0.5 && l < 1.0) {
6706 s = c / (2 * (1 - l));
6709 return [hcg[0], s * 100, l * 100];
6712 convert.hcg.hwb = function (hcg) {
6713 var c = hcg[1] / 100;
6714 var g = hcg[2] / 100;
6715 var v = c + g * (1.0 - c);
6716 return [hcg[0], (v - c) * 100, (1 - v) * 100];
6719 convert.hwb.hcg = function (hwb) {
6720 var w = hwb[1] / 100;
6721 var b = hwb[2] / 100;
6727 g = (v - c) / (1 - c);
6730 return [hwb[0], c * 100, g * 100];
6733 convert.apple.rgb = function (apple) {
6734 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
6737 convert.rgb.apple = function (rgb) {
6738 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
6741 convert.gray.rgb = function (args) {
6742 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
6745 convert.gray.hsl = convert.gray.hsv = function (args) {
6746 return [0, 0, args[0]];
6749 convert.gray.hwb = function (gray) {
6750 return [0, 100, gray[0]];
6753 convert.gray.cmyk = function (gray) {
6754 return [0, 0, 0, gray[0]];
6757 convert.gray.lab = function (gray) {
6758 return [gray[0], 0, 0];
6761 convert.gray.hex = function (gray) {
6762 var val = Math.round(gray[0] / 100 * 255) & 0xFF;
6763 var integer = (val << 16) + (val << 8) + val;
6764 var string = integer.toString(16).toUpperCase();
6765 return '000000'.substring(string.length) + string;
6768 convert.rgb.gray = function (rgb) {
6769 var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
6770 return [val / 255 * 100];
6775 this function routes a model to all other models.
6777 all functions that are routed have a property `.conversion` attached
6778 to the returned synthetic function. This property is an array
6779 of strings, each with the steps in between the 'from' and 'to'
6780 color models (inclusive).
6782 conversions that are not possible simply are not included.
6785 function buildGraph() {
6786 var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
6788 var models = Object.keys(conversions);
6790 for (var len = models.length, i = 0; i < len; i++) {
6791 graph[models[i]] = {
6792 // http://jsperf.com/1-vs-infinity
6793 // micro-opt, but this is simple.
6800 } // https://en.wikipedia.org/wiki/Breadth-first_search
6803 function deriveBFS(fromModel) {
6804 var graph = buildGraph();
6805 var queue = [fromModel]; // unshift -> queue -> pop
6807 graph[fromModel].distance = 0;
6809 while (queue.length) {
6810 var current = queue.pop();
6811 var adjacents = Object.keys(conversions[current]);
6813 for (var len = adjacents.length, i = 0; i < len; i++) {
6814 var adjacent = adjacents[i];
6815 var node = graph[adjacent];
6817 if (node.distance === -1) {
6818 node.distance = graph[current].distance + 1;
6819 node.parent = current;
6820 queue.unshift(adjacent);
6828 function link(from, to) {
6829 return function (args) {
6830 return to(from(args));
6834 function wrapConversion(toModel, graph) {
6835 var path = [graph[toModel].parent, toModel];
6836 var fn = conversions[graph[toModel].parent][toModel];
6837 var cur = graph[toModel].parent;
6839 while (graph[cur].parent) {
6840 path.unshift(graph[cur].parent);
6841 fn = link(conversions[graph[cur].parent][cur], fn);
6842 cur = graph[cur].parent;
6845 fn.conversion = path;
6849 var route = function (fromModel) {
6850 var graph = deriveBFS(fromModel);
6851 var conversion = {};
6852 var models = Object.keys(graph);
6854 for (var len = models.length, i = 0; i < len; i++) {
6855 var toModel = models[i];
6856 var node = graph[toModel];
6858 if (node.parent === null) {
6859 // no possible conversion, or this node is the source model.
6863 conversion[toModel] = wrapConversion(toModel, graph);
6870 var models = Object.keys(conversions);
6872 function wrapRaw(fn) {
6873 var wrappedFn = function (args) {
6874 if (args === undefined || args === null) {
6878 if (arguments.length > 1) {
6879 args = Array.prototype.slice.call(arguments);
6883 }; // preserve .conversion property if there is one
6886 if ('conversion' in fn) {
6887 wrappedFn.conversion = fn.conversion;
6893 function wrapRounded(fn) {
6894 var wrappedFn = function (args) {
6895 if (args === undefined || args === null) {
6899 if (arguments.length > 1) {
6900 args = Array.prototype.slice.call(arguments);
6903 var result = fn(args); // we're assuming the result is an array here.
6904 // see notice in conversions.js; don't use box types
6905 // in conversion functions.
6907 if (typeof result === 'object') {
6908 for (var len = result.length, i = 0; i < len; i++) {
6909 result[i] = Math.round(result[i]);
6914 }; // preserve .conversion property if there is one
6917 if ('conversion' in fn) {
6918 wrappedFn.conversion = fn.conversion;
6924 models.forEach(function (fromModel) {
6925 convert[fromModel] = {};
6926 Object.defineProperty(convert[fromModel], 'channels', {
6927 value: conversions[fromModel].channels
6929 Object.defineProperty(convert[fromModel], 'labels', {
6930 value: conversions[fromModel].labels
6932 var routes = route(fromModel);
6933 var routeModels = Object.keys(routes);
6934 routeModels.forEach(function (toModel) {
6935 var fn = routes[toModel];
6936 convert[fromModel][toModel] = wrapRounded(fn);
6937 convert[fromModel][toModel].raw = wrapRaw(fn);
6940 var colorConvert = convert;
6942 var ansiStyles = createCommonjsModule(function (module) {
6944 const wrapAnsi16 = (fn, offset) => function () {
6945 const code = fn.apply(colorConvert, arguments);
6946 return `\u001B[${code + offset}m`;
6949 const wrapAnsi256 = (fn, offset) => function () {
6950 const code = fn.apply(colorConvert, arguments);
6951 return `\u001B[${38 + offset};5;${code}m`;
6954 const wrapAnsi16m = (fn, offset) => function () {
6955 const rgb = fn.apply(colorConvert, arguments);
6956 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
6959 function assembleStyles() {
6960 const codes = new Map();
6964 // 21 isn't widely supported and 22 does the same thing
6971 strikethrough: [9, 29]
6984 redBright: [91, 39],
6985 greenBright: [92, 39],
6986 yellowBright: [93, 39],
6987 blueBright: [94, 39],
6988 magentaBright: [95, 39],
6989 cyanBright: [96, 39],
6990 whiteBright: [97, 39]
6998 bgMagenta: [45, 49],
7002 bgBlackBright: [100, 49],
7003 bgRedBright: [101, 49],
7004 bgGreenBright: [102, 49],
7005 bgYellowBright: [103, 49],
7006 bgBlueBright: [104, 49],
7007 bgMagentaBright: [105, 49],
7008 bgCyanBright: [106, 49],
7009 bgWhiteBright: [107, 49]
7013 styles.color.grey = styles.color.gray;
7015 for (const groupName of Object.keys(styles)) {
7016 const group = styles[groupName];
7018 for (const styleName of Object.keys(group)) {
7019 const style = group[styleName];
7020 styles[styleName] = {
7021 open: `\u001B[${style[0]}m`,
7022 close: `\u001B[${style[1]}m`
7024 group[styleName] = styles[styleName];
7025 codes.set(style[0], style[1]);
7028 Object.defineProperty(styles, groupName, {
7032 Object.defineProperty(styles, 'codes', {
7038 const ansi2ansi = n => n;
7040 const rgb2rgb = (r, g, b) => [r, g, b];
7042 styles.color.close = '\u001B[39m';
7043 styles.bgColor.close = '\u001B[49m';
7044 styles.color.ansi = {
7045 ansi: wrapAnsi16(ansi2ansi, 0)
7047 styles.color.ansi256 = {
7048 ansi256: wrapAnsi256(ansi2ansi, 0)
7050 styles.color.ansi16m = {
7051 rgb: wrapAnsi16m(rgb2rgb, 0)
7053 styles.bgColor.ansi = {
7054 ansi: wrapAnsi16(ansi2ansi, 10)
7056 styles.bgColor.ansi256 = {
7057 ansi256: wrapAnsi256(ansi2ansi, 10)
7059 styles.bgColor.ansi16m = {
7060 rgb: wrapAnsi16m(rgb2rgb, 10)
7063 for (let key of Object.keys(colorConvert)) {
7064 if (typeof colorConvert[key] !== 'object') {
7068 const suite = colorConvert[key];
7070 if (key === 'ansi16') {
7074 if ('ansi16' in suite) {
7075 styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
7076 styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
7079 if ('ansi256' in suite) {
7080 styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
7081 styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
7084 if ('rgb' in suite) {
7085 styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
7086 styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
7091 } // Make the export immutable
7094 Object.defineProperty(module, 'exports', {
7100 var hasFlag = (flag, argv) => {
7101 argv = argv || process.argv;
7102 const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
7103 const pos = argv.indexOf(prefix + flag);
7104 const terminatorPos = argv.indexOf('--');
7105 return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
7108 const env = process.env;
7111 if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
7113 } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
7117 if ('FORCE_COLOR' in env) {
7118 forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
7121 function translateLevel(level) {
7134 function supportsColor(stream) {
7135 if (forceColor === false) {
7139 if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
7143 if (hasFlag('color=256')) {
7147 if (stream && !stream.isTTY && forceColor !== true) {
7151 const min = forceColor ? 1 : 0;
7153 if (process.platform === 'win32') {
7154 // Node.js 7.5.0 is the first version of Node.js to include a patch to
7155 // libuv that enables 256 color output on Windows. Anything earlier and it
7156 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
7157 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
7158 // release that supports 256 colors. Windows 10 build 14931 is the first release
7159 // that supports 16m/TrueColor.
7160 const osRelease = os__default['default'].release().split('.');
7162 if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
7163 return Number(osRelease[2]) >= 14931 ? 3 : 2;
7170 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
7177 if ('TEAMCITY_VERSION' in env) {
7178 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
7181 if (env.COLORTERM === 'truecolor') {
7185 if ('TERM_PROGRAM' in env) {
7186 const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
7188 switch (env.TERM_PROGRAM) {
7190 return version >= 3 ? 3 : 2;
7192 case 'Apple_Terminal':
7198 if (/-256(color)?$/i.test(env.TERM)) {
7202 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
7206 if ('COLORTERM' in env) {
7210 if (env.TERM === 'dumb') {
7217 function getSupportLevel(stream) {
7218 const level = supportsColor(stream);
7219 return translateLevel(level);
7222 var supportsColor_1 = {
7223 supportsColor: getSupportLevel,
7224 stdout: getSupportLevel(process.stdout),
7225 stderr: getSupportLevel(process.stderr)
7228 const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
7229 const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
7230 const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
7231 const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
7232 const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
7234 function unescape(c) {
7235 if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
7236 return String.fromCharCode(parseInt(c.slice(1), 16));
7239 return ESCAPES.get(c) || c;
7242 function parseArguments(name, args) {
7244 const chunks = args.trim().split(/\s*,\s*/g);
7247 for (const chunk of chunks) {
7248 if (!isNaN(chunk)) {
7249 results.push(Number(chunk));
7250 } else if (matches = chunk.match(STRING_REGEX)) {
7251 results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
7253 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
7260 function parseStyle(style) {
7261 STYLE_REGEX.lastIndex = 0;
7265 while ((matches = STYLE_REGEX.exec(style)) !== null) {
7266 const name = matches[1];
7269 const args = parseArguments(name, matches[2]);
7270 results.push([name].concat(args));
7272 results.push([name]);
7279 function buildStyle(chalk, styles) {
7282 for (const layer of styles) {
7283 for (const style of layer.styles) {
7284 enabled[style[0]] = layer.inverse ? null : style.slice(1);
7288 let current = chalk;
7290 for (const styleName of Object.keys(enabled)) {
7291 if (Array.isArray(enabled[styleName])) {
7292 if (!(styleName in current)) {
7293 throw new Error(`Unknown Chalk style: ${styleName}`);
7296 if (enabled[styleName].length > 0) {
7297 current = current[styleName].apply(current, enabled[styleName]);
7299 current = current[styleName];
7307 var templates = (chalk, tmp) => {
7310 let chunk = []; // eslint-disable-next-line max-params
7312 tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
7314 chunk.push(unescape(escapeChar));
7316 const str = chunk.join('');
7318 chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
7321 styles: parseStyle(style)
7324 if (styles.length === 0) {
7325 throw new Error('Found extraneous } in Chalk template literal');
7328 chunks.push(buildStyle(chalk, styles)(chunk.join('')));
7335 chunks.push(chunk.join(''));
7337 if (styles.length > 0) {
7338 const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
7339 throw new Error(errMsg);
7342 return chunks.join('');
7345 var chalk = createCommonjsModule(function (module) {
7347 const stdoutColor = supportsColor_1.stdout;
7348 const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
7350 const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
7352 const skipModels = new Set(['gray']);
7353 const styles = Object.create(null);
7355 function applyOptions(obj, options) {
7356 options = options || {}; // Detect level if not set manually
7358 const scLevel = stdoutColor ? stdoutColor.level : 0;
7359 obj.level = options.level === undefined ? scLevel : options.level;
7360 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
7363 function Chalk(options) {
7364 // We check for this.template here since calling `chalk.constructor()`
7365 // by itself will have a `this` of a previously constructed chalk object
7366 if (!this || !(this instanceof Chalk) || this.template) {
7368 applyOptions(chalk, options);
7370 chalk.template = function () {
7371 const args = [].slice.call(arguments);
7372 return chalkTag.apply(null, [chalk.template].concat(args));
7375 Object.setPrototypeOf(chalk, Chalk.prototype);
7376 Object.setPrototypeOf(chalk.template, chalk);
7377 chalk.template.constructor = Chalk;
7378 return chalk.template;
7381 applyOptions(this, options);
7382 } // Use bright blue on Windows as the normal blue color is illegible
7385 if (isSimpleWindowsTerm) {
7386 ansiStyles.blue.open = '\u001B[94m';
7389 for (const key of Object.keys(ansiStyles)) {
7390 ansiStyles[key].closeRe = new RegExp(escapeStringRegexp$1(ansiStyles[key].close), 'g');
7393 const codes = ansiStyles[key];
7394 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
7402 return build.call(this, this._styles || [], true, 'visible');
7406 ansiStyles.color.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles.color.close), 'g');
7408 for (const model of Object.keys(ansiStyles.color.ansi)) {
7409 if (skipModels.has(model)) {
7415 const level = this.level;
7416 return function () {
7417 const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
7420 close: ansiStyles.color.close,
7421 closeRe: ansiStyles.color.closeRe
7423 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
7430 ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles.bgColor.close), 'g');
7432 for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
7433 if (skipModels.has(model)) {
7437 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
7440 const level = this.level;
7441 return function () {
7442 const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
7445 close: ansiStyles.bgColor.close,
7446 closeRe: ansiStyles.bgColor.closeRe
7448 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
7455 const proto = Object.defineProperties(() => {}, styles);
7457 function build(_styles, _empty, key) {
7458 const builder = function () {
7459 return applyStyle.apply(builder, arguments);
7462 builder._styles = _styles;
7463 builder._empty = _empty;
7465 Object.defineProperty(builder, 'level', {
7477 Object.defineProperty(builder, 'enabled', {
7481 return self.enabled;
7485 self.enabled = enabled;
7488 }); // See below for fix regarding invisible grey/dim combination on Windows
7490 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
7491 // no way to create a function with a different prototype
7493 builder.__proto__ = proto; // eslint-disable-line no-proto
7498 function applyStyle() {
7499 // Support varags, but simply cast to string in case there's only one arg
7500 const args = arguments;
7501 const argsLen = args.length;
7502 let str = String(arguments[0]);
7504 if (argsLen === 0) {
7509 // Don't slice `arguments`, it prevents V8 optimizations
7510 for (let a = 1; a < argsLen; a++) {
7511 str += ' ' + args[a];
7515 if (!this.enabled || this.level <= 0 || !str) {
7516 return this._empty ? '' : str;
7517 } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
7518 // see https://github.com/chalk/chalk/issues/58
7519 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
7522 const originalDim = ansiStyles.dim.open;
7524 if (isSimpleWindowsTerm && this.hasGrey) {
7525 ansiStyles.dim.open = '';
7528 for (const code of this._styles.slice().reverse()) {
7529 // Replace any instances already present with a re-opening code
7530 // otherwise only the part of the string until said closing code
7531 // will be colored, and the rest will simply be 'plain'.
7532 str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
7533 // after next line to fix a bleed issue on macOS
7534 // https://github.com/chalk/chalk/pull/92
7536 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
7537 } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
7540 ansiStyles.dim.open = originalDim;
7544 function chalkTag(chalk, strings) {
7545 if (!Array.isArray(strings)) {
7546 // If chalk() was called by itself or with a string,
7547 // return the string itself as a string.
7548 return [].slice.call(arguments, 1).join(' ');
7551 const args = [].slice.call(arguments, 2);
7552 const parts = [strings.raw[0]];
7554 for (let i = 1; i < strings.length; i++) {
7555 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
7556 parts.push(String(strings.raw[i]));
7559 return templates(chalk, parts.join(''));
7562 Object.defineProperties(Chalk.prototype, styles);
7563 module.exports = Chalk(); // eslint-disable-line new-cap
7565 module.exports.supportsColor = stdoutColor;
7566 module.exports.default = module.exports; // For TypeScript
7569 var common = createCommonjsModule(function (module, exports) {
7571 Object.defineProperty(exports, "__esModule", {
7575 exports.commonDeprecatedHandler = (keyOrPair, redirectTo, {
7578 const messages = [`${chalk.default.yellow(typeof keyOrPair === 'string' ? descriptor.key(keyOrPair) : descriptor.pair(keyOrPair))} is deprecated`];
7581 messages.push(`we now treat it as ${chalk.default.blue(typeof redirectTo === 'string' ? descriptor.key(redirectTo) : descriptor.pair(redirectTo))}`);
7584 return messages.join('; ') + '.';
7588 var deprecated = createCommonjsModule(function (module, exports) {
7590 Object.defineProperty(exports, "__esModule", {
7594 tslib_es6.__exportStar(common, exports);
7597 var common$1 = createCommonjsModule(function (module, exports) {
7599 Object.defineProperty(exports, "__esModule", {
7603 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(' ');
7606 var invalid = createCommonjsModule(function (module, exports) {
7608 Object.defineProperty(exports, "__esModule", {
7612 tslib_es6.__exportStar(common$1, exports);
7615 /* eslint-disable no-nested-ternary */
7618 var charCodeCache = [];
7620 var leven = function (a, b) {
7625 var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the
7626 // shortest & which one is the longest
7628 if (a.length > b.length) {
7633 var aLen = a.length;
7634 var bLen = b.length;
7642 } // Performing suffix trimming:
7643 // We can linearly drop suffix common to both strings since they
7644 // don't increase distance at all
7645 // Note: `~-` is the bitwise way to perform a `- 1` operation
7648 while (aLen > 0 && a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen)) {
7655 } // Performing prefix trimming
7656 // We can linearly drop prefix common to both strings since they
7657 // don't increase distance at all
7662 while (start < aLen && a.charCodeAt(start) === b.charCodeAt(start)) {
7681 charCodeCache[start + i] = a.charCodeAt(start + i);
7686 bCharCode = b.charCodeAt(start + j);
7690 for (i = 0; i < aLen; i++) {
7691 tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1;
7693 ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2;
7700 var leven_1 = createCommonjsModule(function (module, exports) {
7702 Object.defineProperty(exports, "__esModule", {
7706 exports.levenUnknownHandler = (key, value, {
7711 const messages = [`Ignored unknown option ${chalk.default.yellow(descriptor.pair({
7715 const suggestion = Object.keys(schemas).sort().find(knownKey => leven(key, knownKey) < 3);
7718 messages.push(`Did you mean ${chalk.default.blue(descriptor.key(suggestion))}?`);
7721 logger.warn(messages.join(' '));
7725 var unknown = createCommonjsModule(function (module, exports) {
7727 Object.defineProperty(exports, "__esModule", {
7731 tslib_es6.__exportStar(leven_1, exports);
7734 var handlers = createCommonjsModule(function (module, exports) {
7736 Object.defineProperty(exports, "__esModule", {
7740 tslib_es6.__exportStar(deprecated, exports);
7742 tslib_es6.__exportStar(invalid, exports);
7744 tslib_es6.__exportStar(unknown, exports);
7747 var schema = createCommonjsModule(function (module, exports) {
7749 Object.defineProperty(exports, "__esModule", {
7752 const HANDLER_KEYS = ['default', 'expected', 'validate', 'deprecated', 'forward', 'redirect', 'overlap', 'preprocess', 'postprocess'];
7754 function createSchema(SchemaConstructor, parameters) {
7755 const schema = new SchemaConstructor(parameters);
7756 const subSchema = Object.create(schema);
7758 for (const handlerKey of HANDLER_KEYS) {
7759 if (handlerKey in parameters) {
7760 subSchema[handlerKey] = normalizeHandler(parameters[handlerKey], schema, Schema.prototype[handlerKey].length);
7767 exports.createSchema = createSchema;
7770 constructor(parameters) {
7771 this.name = parameters.name;
7774 static create(parameters) {
7775 // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/5863
7776 return createSchema(this, parameters);
7781 } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
7786 } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
7789 validate(_value, _utils) {
7793 deprecated(_value, _utils) {
7797 forward(_value, _utils) {
7801 redirect(_value, _utils) {
7805 overlap(currentValue, _newValue, _utils) {
7806 return currentValue;
7809 preprocess(value, _utils) {
7813 postprocess(value, _utils) {
7819 exports.Schema = Schema;
7821 function normalizeHandler(handler, superSchema, handlerArgumentsLength) {
7822 return typeof handler === 'function' ? (...args) => handler(...args.slice(0, handlerArgumentsLength - 1), superSchema, ...args.slice(handlerArgumentsLength - 1)) : () => handler;
7826 var alias = createCommonjsModule(function (module, exports) {
7828 Object.defineProperty(exports, "__esModule", {
7832 class AliasSchema extends schema.Schema {
7833 constructor(parameters) {
7835 this._sourceName = parameters.sourceName;
7839 return utils.schemas[this._sourceName].expected(utils);
7842 validate(value, utils) {
7843 return utils.schemas[this._sourceName].validate(value, utils);
7846 redirect(_value, _utils) {
7847 return this._sourceName;
7852 exports.AliasSchema = AliasSchema;
7855 var any = createCommonjsModule(function (module, exports) {
7857 Object.defineProperty(exports, "__esModule", {
7861 class AnySchema extends schema.Schema {
7872 exports.AnySchema = AnySchema;
7875 var array = createCommonjsModule(function (module, exports) {
7877 Object.defineProperty(exports, "__esModule", {
7881 class ArraySchema extends schema.Schema {
7885 name = valueSchema.name
7887 handlers = tslib_es6.__rest(_a, ["valueSchema", "name"]);
7889 super(Object.assign({}, handlers, {
7892 this._valueSchema = valueSchema;
7896 return `an array of ${this._valueSchema.expected(utils)}`;
7899 validate(value, utils) {
7900 if (!Array.isArray(value)) {
7904 const invalidValues = [];
7906 for (const subValue of value) {
7907 const subValidateResult = utils.normalizeValidateResult(this._valueSchema.validate(subValue, utils), subValue);
7909 if (subValidateResult !== true) {
7910 invalidValues.push(subValidateResult.value);
7914 return invalidValues.length === 0 ? true : {
7915 value: invalidValues
7919 deprecated(value, utils) {
7920 const deprecatedResult = [];
7922 for (const subValue of value) {
7923 const subDeprecatedResult = utils.normalizeDeprecatedResult(this._valueSchema.deprecated(subValue, utils), subValue);
7925 if (subDeprecatedResult !== false) {
7926 deprecatedResult.push(...subDeprecatedResult.map(({
7927 value: deprecatedValue
7929 value: [deprecatedValue]
7934 return deprecatedResult;
7937 forward(value, utils) {
7938 const forwardResult = [];
7940 for (const subValue of value) {
7941 const subForwardResult = utils.normalizeForwardResult(this._valueSchema.forward(subValue, utils), subValue);
7942 forwardResult.push(...subForwardResult.map(wrapTransferResult));
7945 return forwardResult;
7948 redirect(value, utils) {
7950 const redirect = [];
7952 for (const subValue of value) {
7953 const subRedirectResult = utils.normalizeRedirectResult(this._valueSchema.redirect(subValue, utils), subValue);
7955 if ('remain' in subRedirectResult) {
7956 remain.push(subRedirectResult.remain);
7959 redirect.push(...subRedirectResult.redirect.map(wrapTransferResult));
7962 return remain.length === 0 ? {
7970 overlap(currentValue, newValue) {
7971 return currentValue.concat(newValue);
7976 exports.ArraySchema = ArraySchema;
7978 function wrapTransferResult({
7989 var boolean_1 = createCommonjsModule(function (module, exports) {
7991 Object.defineProperty(exports, "__esModule", {
7995 class BooleanSchema extends schema.Schema {
7997 return 'true or false';
8001 return typeof value === 'boolean';
8006 exports.BooleanSchema = BooleanSchema;
8009 var utils = createCommonjsModule(function (module, exports) {
8011 Object.defineProperty(exports, "__esModule", {
8015 function recordFromArray(array, mainKey) {
8016 const record = Object.create(null);
8018 for (const value of array) {
8019 const key = value[mainKey]; // istanbul ignore next
8022 throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`);
8026 record[key] = value;
8032 exports.recordFromArray = recordFromArray;
8034 function mapFromArray(array, mainKey) {
8035 const map = new Map();
8037 for (const value of array) {
8038 const key = value[mainKey]; // istanbul ignore next
8041 throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`);
8044 map.set(key, value);
8050 exports.mapFromArray = mapFromArray;
8052 function createAutoChecklist() {
8053 const map = Object.create(null);
8055 const idString = JSON.stringify(id);
8057 if (map[idString]) {
8061 map[idString] = true;
8066 exports.createAutoChecklist = createAutoChecklist;
8068 function partition(array, predicate) {
8069 const trueArray = [];
8070 const falseArray = [];
8072 for (const value of array) {
8073 if (predicate(value)) {
8074 trueArray.push(value);
8076 falseArray.push(value);
8080 return [trueArray, falseArray];
8083 exports.partition = partition;
8085 function isInt(value) {
8086 return value === Math.floor(value);
8089 exports.isInt = isInt;
8091 function comparePrimitive(a, b) {
8096 const typeofA = typeof a;
8097 const typeofB = typeof b;
8098 const orders = ['undefined', 'object', 'boolean', 'number', 'string'];
8100 if (typeofA !== typeofB) {
8101 return orders.indexOf(typeofA) - orders.indexOf(typeofB);
8104 if (typeofA !== 'string') {
8105 return Number(a) - Number(b);
8108 return a.localeCompare(b);
8111 exports.comparePrimitive = comparePrimitive;
8113 function normalizeDefaultResult(result) {
8114 return result === undefined ? {} : result;
8117 exports.normalizeDefaultResult = normalizeDefaultResult;
8119 function normalizeValidateResult(result, value) {
8120 return result === true ? true : result === false ? {
8125 exports.normalizeValidateResult = normalizeValidateResult;
8127 function normalizeDeprecatedResult(result, value, doNotNormalizeTrue = false) {
8128 return result === false ? false : result === true ? doNotNormalizeTrue ? true : [{
8130 }] : 'value' in result ? [result] : result.length === 0 ? false : result;
8133 exports.normalizeDeprecatedResult = normalizeDeprecatedResult;
8135 function normalizeTransferResult(result, value) {
8136 return typeof result === 'string' || 'key' in result ? {
8139 } : 'from' in result ? {
8148 exports.normalizeTransferResult = normalizeTransferResult;
8150 function normalizeForwardResult(result, value) {
8151 return result === undefined ? [] : Array.isArray(result) ? result.map(transferResult => normalizeTransferResult(transferResult, value)) : [normalizeTransferResult(result, value)];
8154 exports.normalizeForwardResult = normalizeForwardResult;
8156 function normalizeRedirectResult(result, value) {
8157 const redirect = normalizeForwardResult(typeof result === 'object' && 'redirect' in result ? result.redirect : result, value);
8158 return redirect.length === 0 ? {
8161 } : typeof result === 'object' && 'remain' in result ? {
8162 remain: result.remain,
8169 exports.normalizeRedirectResult = normalizeRedirectResult;
8172 var choice = createCommonjsModule(function (module, exports) {
8174 Object.defineProperty(exports, "__esModule", {
8178 class ChoiceSchema extends schema.Schema {
8179 constructor(parameters) {
8181 this._choices = utils.mapFromArray(parameters.choices.map(choice => choice && typeof choice === 'object' ? choice : {
8189 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);
8190 const head = choiceValues.slice(0, -2);
8191 const tail = choiceValues.slice(-2);
8192 return head.concat(tail.join(' or ')).join(', ');
8196 return this._choices.has(value);
8200 const choiceInfo = this._choices.get(value);
8202 return choiceInfo && choiceInfo.deprecated ? {
8208 const choiceInfo = this._choices.get(value);
8210 return choiceInfo ? choiceInfo.forward : undefined;
8214 const choiceInfo = this._choices.get(value);
8216 return choiceInfo ? choiceInfo.redirect : undefined;
8221 exports.ChoiceSchema = ChoiceSchema;
8224 var number = createCommonjsModule(function (module, exports) {
8226 Object.defineProperty(exports, "__esModule", {
8230 class NumberSchema extends schema.Schema {
8235 validate(value, _utils) {
8236 return typeof value === 'number';
8241 exports.NumberSchema = NumberSchema;
8244 var integer = createCommonjsModule(function (module, exports) {
8246 Object.defineProperty(exports, "__esModule", {
8250 class IntegerSchema extends number.NumberSchema {
8252 return 'an integer';
8255 validate(value, utils$1) {
8256 return utils$1.normalizeValidateResult(super.validate(value, utils$1), value) === true && utils.isInt(value);
8261 exports.IntegerSchema = IntegerSchema;
8264 var string = createCommonjsModule(function (module, exports) {
8266 Object.defineProperty(exports, "__esModule", {
8270 class StringSchema extends schema.Schema {
8276 return typeof value === 'string';
8281 exports.StringSchema = StringSchema;
8284 var schemas = createCommonjsModule(function (module, exports) {
8286 Object.defineProperty(exports, "__esModule", {
8290 tslib_es6.__exportStar(alias, exports);
8292 tslib_es6.__exportStar(any, exports);
8294 tslib_es6.__exportStar(array, exports);
8296 tslib_es6.__exportStar(boolean_1, exports);
8298 tslib_es6.__exportStar(choice, exports);
8300 tslib_es6.__exportStar(integer, exports);
8302 tslib_es6.__exportStar(number, exports);
8304 tslib_es6.__exportStar(string, exports);
8307 var defaults = createCommonjsModule(function (module, exports) {
8309 Object.defineProperty(exports, "__esModule", {
8312 exports.defaultDescriptor = api.apiDescriptor;
8313 exports.defaultUnknownHandler = leven_1.levenUnknownHandler;
8314 exports.defaultInvalidHandler = invalid.commonInvalidHandler;
8315 exports.defaultDeprecatedHandler = common.commonDeprecatedHandler;
8318 var normalize = createCommonjsModule(function (module, exports) {
8320 Object.defineProperty(exports, "__esModule", {
8324 exports.normalize = (options, schemas, opts) => new Normalizer(schemas, opts).normalize(options);
8327 constructor(schemas, opts) {
8328 // istanbul ignore next
8331 descriptor = defaults.defaultDescriptor,
8332 unknown = defaults.defaultUnknownHandler,
8333 invalid = defaults.defaultInvalidHandler,
8334 deprecated = defaults.defaultDeprecatedHandler
8339 /* istanbul ignore next */
8343 schemas: utils.recordFromArray(schemas, 'name'),
8344 normalizeDefaultResult: utils.normalizeDefaultResult,
8345 normalizeDeprecatedResult: utils.normalizeDeprecatedResult,
8346 normalizeForwardResult: utils.normalizeForwardResult,
8347 normalizeRedirectResult: utils.normalizeRedirectResult,
8348 normalizeValidateResult: utils.normalizeValidateResult
8350 this._unknownHandler = unknown;
8351 this._invalidHandler = invalid;
8352 this._deprecatedHandler = deprecated;
8353 this.cleanHistory();
8357 this._hasDeprecationWarned = utils.createAutoChecklist();
8360 normalize(options) {
8361 const normalized = {};
8362 const restOptionsArray = [options];
8364 const applyNormalization = () => {
8365 while (restOptionsArray.length !== 0) {
8366 const currentOptions = restOptionsArray.shift();
8368 const transferredOptionsArray = this._applyNormalization(currentOptions, normalized);
8370 restOptionsArray.push(...transferredOptionsArray);
8374 applyNormalization();
8376 for (const key of Object.keys(this._utils.schemas)) {
8377 const schema = this._utils.schemas[key];
8379 if (!(key in normalized)) {
8380 const defaultResult = utils.normalizeDefaultResult(schema.default(this._utils));
8382 if ('value' in defaultResult) {
8383 restOptionsArray.push({
8384 [key]: defaultResult.value
8390 applyNormalization();
8392 for (const key of Object.keys(this._utils.schemas)) {
8393 const schema = this._utils.schemas[key];
8395 if (key in normalized) {
8396 normalized[key] = schema.postprocess(normalized[key], this._utils);
8403 _applyNormalization(options, normalized) {
8404 const transferredOptionsArray = [];
8405 const [knownOptionNames, unknownOptionNames] = utils.partition(Object.keys(options), key => key in this._utils.schemas);
8407 for (const key of knownOptionNames) {
8408 const schema = this._utils.schemas[key];
8409 const value = schema.preprocess(options[key], this._utils);
8410 const validateResult = utils.normalizeValidateResult(schema.validate(value, this._utils), value);
8412 if (validateResult !== true) {
8417 const errorMessageOrError = this._invalidHandler(key, invalidValue, this._utils);
8419 throw typeof errorMessageOrError === 'string' ? new Error(errorMessageOrError) :
8420 /* istanbul ignore next*/
8421 errorMessageOrError;
8424 const appendTransferredOptions = ({
8428 transferredOptionsArray.push(typeof to === 'string' ? {
8435 const warnDeprecated = ({
8436 value: currentValue,
8439 const deprecatedResult = utils.normalizeDeprecatedResult(schema.deprecated(currentValue, this._utils), value,
8440 /* doNotNormalizeTrue */
8443 if (deprecatedResult === false) {
8447 if (deprecatedResult === true) {
8448 if (!this._hasDeprecationWarned(key)) {
8449 this._utils.logger.warn(this._deprecatedHandler(key, redirectTo, this._utils));
8453 value: deprecatedValue
8454 } of deprecatedResult) {
8457 value: deprecatedValue
8460 if (!this._hasDeprecationWarned(pair)) {
8461 const redirectToPair = typeof redirectTo === 'string' ? {
8463 value: deprecatedValue
8466 this._utils.logger.warn(this._deprecatedHandler(pair, redirectToPair, this._utils));
8472 const forwardResult = utils.normalizeForwardResult(schema.forward(value, this._utils), value);
8473 forwardResult.forEach(appendTransferredOptions);
8474 const redirectResult = utils.normalizeRedirectResult(schema.redirect(value, this._utils), value);
8475 redirectResult.redirect.forEach(appendTransferredOptions);
8477 if ('remain' in redirectResult) {
8478 const remainingValue = redirectResult.remain;
8479 normalized[key] = key in normalized ? schema.overlap(normalized[key], remainingValue, this._utils) : remainingValue;
8481 value: remainingValue
8488 } of redirectResult.redirect) {
8496 for (const key of unknownOptionNames) {
8497 const value = options[key];
8499 const unknownResult = this._unknownHandler(key, value, this._utils);
8501 if (unknownResult) {
8502 for (const unknownKey of Object.keys(unknownResult)) {
8503 const unknownOption = {
8504 [unknownKey]: unknownResult[unknownKey]
8507 if (unknownKey in this._utils.schemas) {
8508 transferredOptionsArray.push(unknownOption);
8510 Object.assign(normalized, unknownOption);
8516 return transferredOptionsArray;
8521 exports.Normalizer = Normalizer;
8524 var lib$1 = createCommonjsModule(function (module, exports) {
8526 Object.defineProperty(exports, "__esModule", {
8530 tslib_es6.__exportStar(descriptors, exports);
8532 tslib_es6.__exportStar(handlers, exports);
8534 tslib_es6.__exportStar(schemas, exports);
8536 tslib_es6.__exportStar(normalize, exports);
8538 tslib_es6.__exportStar(schema, exports);
8542 const charCodeCache$1 = [];
8544 const leven$1 = (left, right) => {
8545 if (left === right) {
8549 const swap = left; // Swapping the strings if `a` is longer than `b` so we know which one is the
8550 // shortest & which one is the longest
8552 if (left.length > right.length) {
8557 let leftLength = left.length;
8558 let rightLength = right.length; // Performing suffix trimming:
8559 // We can linearly drop suffix common to both strings since they
8560 // don't increase distance at all
8561 // Note: `~-` is the bitwise way to perform a `- 1` operation
8563 while (leftLength > 0 && left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength)) {
8566 } // Performing prefix trimming
8567 // We can linearly drop prefix common to both strings since they
8568 // don't increase distance at all
8573 while (start < leftLength && left.charCodeAt(start) === right.charCodeAt(start)) {
8577 leftLength -= start;
8578 rightLength -= start;
8580 if (leftLength === 0) {
8591 while (i < leftLength) {
8592 charCodeCache$1[i] = left.charCodeAt(start + i);
8596 while (j < rightLength) {
8597 bCharCode = right.charCodeAt(start + j);
8601 for (i = 0; i < leftLength; i++) {
8602 temp2 = bCharCode === charCodeCache$1[i] ? temp : temp + 1;
8603 temp = array$1[i]; // eslint-disable-next-line no-multi-assign
8605 result = array$1[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2;
8612 var leven_1$1 = leven$1; // TODO: Remove this for the next major release
8614 var _default$2 = leven$1;
8615 leven_1$1.default = _default$2;
8618 "aliceblue": [240, 248, 255],
8619 "antiquewhite": [250, 235, 215],
8620 "aqua": [0, 255, 255],
8621 "aquamarine": [127, 255, 212],
8622 "azure": [240, 255, 255],
8623 "beige": [245, 245, 220],
8624 "bisque": [255, 228, 196],
8626 "blanchedalmond": [255, 235, 205],
8627 "blue": [0, 0, 255],
8628 "blueviolet": [138, 43, 226],
8629 "brown": [165, 42, 42],
8630 "burlywood": [222, 184, 135],
8631 "cadetblue": [95, 158, 160],
8632 "chartreuse": [127, 255, 0],
8633 "chocolate": [210, 105, 30],
8634 "coral": [255, 127, 80],
8635 "cornflowerblue": [100, 149, 237],
8636 "cornsilk": [255, 248, 220],
8637 "crimson": [220, 20, 60],
8638 "cyan": [0, 255, 255],
8639 "darkblue": [0, 0, 139],
8640 "darkcyan": [0, 139, 139],
8641 "darkgoldenrod": [184, 134, 11],
8642 "darkgray": [169, 169, 169],
8643 "darkgreen": [0, 100, 0],
8644 "darkgrey": [169, 169, 169],
8645 "darkkhaki": [189, 183, 107],
8646 "darkmagenta": [139, 0, 139],
8647 "darkolivegreen": [85, 107, 47],
8648 "darkorange": [255, 140, 0],
8649 "darkorchid": [153, 50, 204],
8650 "darkred": [139, 0, 0],
8651 "darksalmon": [233, 150, 122],
8652 "darkseagreen": [143, 188, 143],
8653 "darkslateblue": [72, 61, 139],
8654 "darkslategray": [47, 79, 79],
8655 "darkslategrey": [47, 79, 79],
8656 "darkturquoise": [0, 206, 209],
8657 "darkviolet": [148, 0, 211],
8658 "deeppink": [255, 20, 147],
8659 "deepskyblue": [0, 191, 255],
8660 "dimgray": [105, 105, 105],
8661 "dimgrey": [105, 105, 105],
8662 "dodgerblue": [30, 144, 255],
8663 "firebrick": [178, 34, 34],
8664 "floralwhite": [255, 250, 240],
8665 "forestgreen": [34, 139, 34],
8666 "fuchsia": [255, 0, 255],
8667 "gainsboro": [220, 220, 220],
8668 "ghostwhite": [248, 248, 255],
8669 "gold": [255, 215, 0],
8670 "goldenrod": [218, 165, 32],
8671 "gray": [128, 128, 128],
8672 "green": [0, 128, 0],
8673 "greenyellow": [173, 255, 47],
8674 "grey": [128, 128, 128],
8675 "honeydew": [240, 255, 240],
8676 "hotpink": [255, 105, 180],
8677 "indianred": [205, 92, 92],
8678 "indigo": [75, 0, 130],
8679 "ivory": [255, 255, 240],
8680 "khaki": [240, 230, 140],
8681 "lavender": [230, 230, 250],
8682 "lavenderblush": [255, 240, 245],
8683 "lawngreen": [124, 252, 0],
8684 "lemonchiffon": [255, 250, 205],
8685 "lightblue": [173, 216, 230],
8686 "lightcoral": [240, 128, 128],
8687 "lightcyan": [224, 255, 255],
8688 "lightgoldenrodyellow": [250, 250, 210],
8689 "lightgray": [211, 211, 211],
8690 "lightgreen": [144, 238, 144],
8691 "lightgrey": [211, 211, 211],
8692 "lightpink": [255, 182, 193],
8693 "lightsalmon": [255, 160, 122],
8694 "lightseagreen": [32, 178, 170],
8695 "lightskyblue": [135, 206, 250],
8696 "lightslategray": [119, 136, 153],
8697 "lightslategrey": [119, 136, 153],
8698 "lightsteelblue": [176, 196, 222],
8699 "lightyellow": [255, 255, 224],
8700 "lime": [0, 255, 0],
8701 "limegreen": [50, 205, 50],
8702 "linen": [250, 240, 230],
8703 "magenta": [255, 0, 255],
8704 "maroon": [128, 0, 0],
8705 "mediumaquamarine": [102, 205, 170],
8706 "mediumblue": [0, 0, 205],
8707 "mediumorchid": [186, 85, 211],
8708 "mediumpurple": [147, 112, 219],
8709 "mediumseagreen": [60, 179, 113],
8710 "mediumslateblue": [123, 104, 238],
8711 "mediumspringgreen": [0, 250, 154],
8712 "mediumturquoise": [72, 209, 204],
8713 "mediumvioletred": [199, 21, 133],
8714 "midnightblue": [25, 25, 112],
8715 "mintcream": [245, 255, 250],
8716 "mistyrose": [255, 228, 225],
8717 "moccasin": [255, 228, 181],
8718 "navajowhite": [255, 222, 173],
8719 "navy": [0, 0, 128],
8720 "oldlace": [253, 245, 230],
8721 "olive": [128, 128, 0],
8722 "olivedrab": [107, 142, 35],
8723 "orange": [255, 165, 0],
8724 "orangered": [255, 69, 0],
8725 "orchid": [218, 112, 214],
8726 "palegoldenrod": [238, 232, 170],
8727 "palegreen": [152, 251, 152],
8728 "paleturquoise": [175, 238, 238],
8729 "palevioletred": [219, 112, 147],
8730 "papayawhip": [255, 239, 213],
8731 "peachpuff": [255, 218, 185],
8732 "peru": [205, 133, 63],
8733 "pink": [255, 192, 203],
8734 "plum": [221, 160, 221],
8735 "powderblue": [176, 224, 230],
8736 "purple": [128, 0, 128],
8737 "rebeccapurple": [102, 51, 153],
8739 "rosybrown": [188, 143, 143],
8740 "royalblue": [65, 105, 225],
8741 "saddlebrown": [139, 69, 19],
8742 "salmon": [250, 128, 114],
8743 "sandybrown": [244, 164, 96],
8744 "seagreen": [46, 139, 87],
8745 "seashell": [255, 245, 238],
8746 "sienna": [160, 82, 45],
8747 "silver": [192, 192, 192],
8748 "skyblue": [135, 206, 235],
8749 "slateblue": [106, 90, 205],
8750 "slategray": [112, 128, 144],
8751 "slategrey": [112, 128, 144],
8752 "snow": [255, 250, 250],
8753 "springgreen": [0, 255, 127],
8754 "steelblue": [70, 130, 180],
8755 "tan": [210, 180, 140],
8756 "teal": [0, 128, 128],
8757 "thistle": [216, 191, 216],
8758 "tomato": [255, 99, 71],
8759 "turquoise": [64, 224, 208],
8760 "violet": [238, 130, 238],
8761 "wheat": [245, 222, 179],
8762 "white": [255, 255, 255],
8763 "whitesmoke": [245, 245, 245],
8764 "yellow": [255, 255, 0],
8765 "yellowgreen": [154, 205, 50]
8770 /* eslint-disable no-mixed-operators */
8771 // NOTE: conversions should only return primitive values (i.e. arrays, or
8772 // values that give correct `typeof` results).
8773 // do not use box values types (i.e. Number(), String(), etc.)
8775 const reverseKeywords = {};
8777 for (const key of Object.keys(colorName$1)) {
8778 reverseKeywords[colorName$1[key]] = key;
8832 labels: ['h', 'c', 'g']
8836 labels: ['r16', 'g16', 'b16']
8843 var conversions$1 = convert$1; // Hide .channels and .labels properties
8845 for (const model of Object.keys(convert$1)) {
8846 if (!('channels' in convert$1[model])) {
8847 throw new Error('missing channels property: ' + model);
8850 if (!('labels' in convert$1[model])) {
8851 throw new Error('missing channel labels property: ' + model);
8854 if (convert$1[model].labels.length !== convert$1[model].channels) {
8855 throw new Error('channel and label counts mismatch: ' + model);
8861 } = convert$1[model];
8862 delete convert$1[model].channels;
8863 delete convert$1[model].labels;
8864 Object.defineProperty(convert$1[model], 'channels', {
8867 Object.defineProperty(convert$1[model], 'labels', {
8872 convert$1.rgb.hsl = function (rgb) {
8873 const r = rgb[0] / 255;
8874 const g = rgb[1] / 255;
8875 const b = rgb[2] / 255;
8876 const min = Math.min(r, g, b);
8877 const max = Math.max(r, g, b);
8878 const delta = max - min;
8884 } else if (r === max) {
8885 h = (g - b) / delta;
8886 } else if (g === max) {
8887 h = 2 + (b - r) / delta;
8888 } else if (b === max) {
8889 h = 4 + (r - g) / delta;
8892 h = Math.min(h * 60, 360);
8898 const l = (min + max) / 2;
8902 } else if (l <= 0.5) {
8903 s = delta / (max + min);
8905 s = delta / (2 - max - min);
8908 return [h, s * 100, l * 100];
8911 convert$1.rgb.hsv = function (rgb) {
8917 const r = rgb[0] / 255;
8918 const g = rgb[1] / 255;
8919 const b = rgb[2] / 255;
8920 const v = Math.max(r, g, b);
8921 const diff = v - Math.min(r, g, b);
8923 const diffc = function (c) {
8924 return (v - c) / 6 / diff + 1 / 2;
8938 } else if (g === v) {
8939 h = 1 / 3 + rdif - bdif;
8940 } else if (b === v) {
8941 h = 2 / 3 + gdif - rdif;
8951 return [h * 360, s * 100, v * 100];
8954 convert$1.rgb.hwb = function (rgb) {
8958 const h = convert$1.rgb.hsl(rgb)[0];
8959 const w = 1 / 255 * Math.min(r, Math.min(g, b));
8960 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
8961 return [h, w * 100, b * 100];
8964 convert$1.rgb.cmyk = function (rgb) {
8965 const r = rgb[0] / 255;
8966 const g = rgb[1] / 255;
8967 const b = rgb[2] / 255;
8968 const k = Math.min(1 - r, 1 - g, 1 - b);
8969 const c = (1 - r - k) / (1 - k) || 0;
8970 const m = (1 - g - k) / (1 - k) || 0;
8971 const y = (1 - b - k) / (1 - k) || 0;
8972 return [c * 100, m * 100, y * 100, k * 100];
8975 function comparativeDistance(x, y) {
8977 See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
8979 return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2;
8982 convert$1.rgb.keyword = function (rgb) {
8983 const reversed = reverseKeywords[rgb];
8989 let currentClosestDistance = Infinity;
8990 let currentClosestKeyword;
8992 for (const keyword of Object.keys(colorName$1)) {
8993 const value = colorName$1[keyword]; // Compute comparative distance
8995 const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
8997 if (distance < currentClosestDistance) {
8998 currentClosestDistance = distance;
8999 currentClosestKeyword = keyword;
9003 return currentClosestKeyword;
9006 convert$1.keyword.rgb = function (keyword) {
9007 return colorName$1[keyword];
9010 convert$1.rgb.xyz = function (rgb) {
9011 let r = rgb[0] / 255;
9012 let g = rgb[1] / 255;
9013 let b = rgb[2] / 255; // Assume sRGB
9015 r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92;
9016 g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92;
9017 b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92;
9018 const x = r * 0.4124 + g * 0.3576 + b * 0.1805;
9019 const y = r * 0.2126 + g * 0.7152 + b * 0.0722;
9020 const z = r * 0.0193 + g * 0.1192 + b * 0.9505;
9021 return [x * 100, y * 100, z * 100];
9024 convert$1.rgb.lab = function (rgb) {
9025 const xyz = convert$1.rgb.xyz(rgb);
9032 x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
9033 y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
9034 z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
9035 const l = 116 * y - 16;
9036 const a = 500 * (x - y);
9037 const b = 200 * (y - z);
9041 convert$1.hsl.rgb = function (hsl) {
9042 const h = hsl[0] / 360;
9043 const s = hsl[1] / 100;
9044 const l = hsl[2] / 100;
9051 return [val, val, val];
9060 const t1 = 2 * l - t2;
9061 const rgb = [0, 0, 0];
9063 for (let i = 0; i < 3; i++) {
9064 t3 = h + 1 / 3 * -(i - 1);
9075 val = t1 + (t2 - t1) * 6 * t3;
9076 } else if (2 * t3 < 1) {
9078 } else if (3 * t3 < 2) {
9079 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
9090 convert$1.hsl.hsv = function (hsl) {
9092 let s = hsl[1] / 100;
9093 let l = hsl[2] / 100;
9095 const lmin = Math.max(l, 0.01);
9097 s *= l <= 1 ? l : 2 - l;
9098 smin *= lmin <= 1 ? lmin : 2 - lmin;
9099 const v = (l + s) / 2;
9100 const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
9101 return [h, sv * 100, v * 100];
9104 convert$1.hsv.rgb = function (hsv) {
9105 const h = hsv[0] / 60;
9106 const s = hsv[1] / 100;
9107 let v = hsv[2] / 100;
9108 const hi = Math.floor(h) % 6;
9109 const f = h - Math.floor(h);
9110 const p = 255 * v * (1 - s);
9111 const q = 255 * v * (1 - s * f);
9112 const t = 255 * v * (1 - s * (1 - f));
9136 convert$1.hsv.hsl = function (hsv) {
9138 const s = hsv[1] / 100;
9139 const v = hsv[2] / 100;
9140 const vmin = Math.max(v, 0.01);
9144 const lmin = (2 - s) * vmin;
9146 sl /= lmin <= 1 ? lmin : 2 - lmin;
9149 return [h, sl * 100, l * 100];
9150 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
9153 convert$1.hwb.rgb = function (hwb) {
9154 const h = hwb[0] / 360;
9155 let wh = hwb[1] / 100;
9156 let bl = hwb[2] / 100;
9157 const ratio = wh + bl;
9158 let f; // Wh + bl cant be > 1
9165 const i = Math.floor(6 * h);
9169 if ((i & 0x01) !== 0) {
9173 const n = wh + f * (v - wh); // Linear interpolation
9178 /* eslint-disable max-statements-per-line,no-multi-spaces */
9219 /* eslint-enable max-statements-per-line,no-multi-spaces */
9222 return [r * 255, g * 255, b * 255];
9225 convert$1.cmyk.rgb = function (cmyk) {
9226 const c = cmyk[0] / 100;
9227 const m = cmyk[1] / 100;
9228 const y = cmyk[2] / 100;
9229 const k = cmyk[3] / 100;
9230 const r = 1 - Math.min(1, c * (1 - k) + k);
9231 const g = 1 - Math.min(1, m * (1 - k) + k);
9232 const b = 1 - Math.min(1, y * (1 - k) + k);
9233 return [r * 255, g * 255, b * 255];
9236 convert$1.xyz.rgb = function (xyz) {
9237 const x = xyz[0] / 100;
9238 const y = xyz[1] / 100;
9239 const z = xyz[2] / 100;
9243 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
9244 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
9245 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // Assume sRGB
9247 r = r > 0.0031308 ? 1.055 * r ** (1.0 / 2.4) - 0.055 : r * 12.92;
9248 g = g > 0.0031308 ? 1.055 * g ** (1.0 / 2.4) - 0.055 : g * 12.92;
9249 b = b > 0.0031308 ? 1.055 * b ** (1.0 / 2.4) - 0.055 : b * 12.92;
9250 r = Math.min(Math.max(0, r), 1);
9251 g = Math.min(Math.max(0, g), 1);
9252 b = Math.min(Math.max(0, b), 1);
9253 return [r * 255, g * 255, b * 255];
9256 convert$1.xyz.lab = function (xyz) {
9263 x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
9264 y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
9265 z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
9266 const l = 116 * y - 16;
9267 const a = 500 * (x - y);
9268 const b = 200 * (y - z);
9272 convert$1.lab.xyz = function (lab) {
9285 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
9286 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
9287 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
9294 convert$1.lab.lch = function (lab) {
9299 const hr = Math.atan2(b, a);
9300 h = hr * 360 / 2 / Math.PI;
9306 const c = Math.sqrt(a * a + b * b);
9310 convert$1.lch.lab = function (lch) {
9314 const hr = h / 360 * 2 * Math.PI;
9315 const a = c * Math.cos(hr);
9316 const b = c * Math.sin(hr);
9320 convert$1.rgb.ansi16 = function (args, saturation = null) {
9321 const [r, g, b] = args;
9322 let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
9324 value = Math.round(value / 50);
9330 let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
9339 convert$1.hsv.ansi16 = function (args) {
9340 // Optimization here; we already know the value and don't need to get
9341 // it converted for us.
9342 return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
9345 convert$1.rgb.ansi256 = function (args) {
9348 const b = args[2]; // We use the extended greyscale palette here, with the exception of
9349 // black and white. normal palette only has 4 greyscale shades.
9351 if (r === g && g === b) {
9360 return Math.round((r - 8) / 247 * 24) + 232;
9363 const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
9367 convert$1.ansi16.rgb = function (args) {
9368 let color = args % 10; // Handle greyscale
9370 if (color === 0 || color === 7) {
9375 color = color / 10.5 * 255;
9376 return [color, color, color];
9379 const mult = (~~(args > 50) + 1) * 0.5;
9380 const r = (color & 1) * mult * 255;
9381 const g = (color >> 1 & 1) * mult * 255;
9382 const b = (color >> 2 & 1) * mult * 255;
9386 convert$1.ansi256.rgb = function (args) {
9389 const c = (args - 232) * 10 + 8;
9395 const r = Math.floor(args / 36) / 5 * 255;
9396 const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
9397 const b = rem % 6 / 5 * 255;
9401 convert$1.rgb.hex = function (args) {
9402 const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
9403 const string = integer.toString(16).toUpperCase();
9404 return '000000'.substring(string.length) + string;
9407 convert$1.hex.rgb = function (args) {
9408 const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
9414 let colorString = match[0];
9416 if (match[0].length === 3) {
9417 colorString = colorString.split('').map(char => {
9422 const integer = parseInt(colorString, 16);
9423 const r = integer >> 16 & 0xFF;
9424 const g = integer >> 8 & 0xFF;
9425 const b = integer & 0xFF;
9429 convert$1.rgb.hcg = function (rgb) {
9430 const r = rgb[0] / 255;
9431 const g = rgb[1] / 255;
9432 const b = rgb[2] / 255;
9433 const max = Math.max(Math.max(r, g), b);
9434 const min = Math.min(Math.min(r, g), b);
9435 const chroma = max - min;
9440 grayscale = min / (1 - chroma);
9447 } else if (max === r) {
9448 hue = (g - b) / chroma % 6;
9449 } else if (max === g) {
9450 hue = 2 + (b - r) / chroma;
9452 hue = 4 + (r - g) / chroma;
9457 return [hue * 360, chroma * 100, grayscale * 100];
9460 convert$1.hsl.hcg = function (hsl) {
9461 const s = hsl[1] / 100;
9462 const l = hsl[2] / 100;
9463 const c = l < 0.5 ? 2.0 * s * l : 2.0 * s * (1.0 - l);
9467 f = (l - 0.5 * c) / (1.0 - c);
9470 return [hsl[0], c * 100, f * 100];
9473 convert$1.hsv.hcg = function (hsv) {
9474 const s = hsv[1] / 100;
9475 const v = hsv[2] / 100;
9480 f = (v - c) / (1 - c);
9483 return [hsv[0], c * 100, f * 100];
9486 convert$1.hcg.rgb = function (hcg) {
9487 const h = hcg[0] / 360;
9488 const c = hcg[1] / 100;
9489 const g = hcg[2] / 100;
9492 return [g * 255, g * 255, g * 255];
9495 const pure = [0, 0, 0];
9496 const hi = h % 1 * 6;
9500 /* eslint-disable max-statements-per-line */
9502 switch (Math.floor(hi)) {
9538 /* eslint-enable max-statements-per-line */
9542 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
9545 convert$1.hcg.hsv = function (hcg) {
9546 const c = hcg[1] / 100;
9547 const g = hcg[2] / 100;
9548 const v = c + g * (1.0 - c);
9555 return [hcg[0], f * 100, v * 100];
9558 convert$1.hcg.hsl = function (hcg) {
9559 const c = hcg[1] / 100;
9560 const g = hcg[2] / 100;
9561 const l = g * (1.0 - c) + 0.5 * c;
9564 if (l > 0.0 && l < 0.5) {
9566 } else if (l >= 0.5 && l < 1.0) {
9567 s = c / (2 * (1 - l));
9570 return [hcg[0], s * 100, l * 100];
9573 convert$1.hcg.hwb = function (hcg) {
9574 const c = hcg[1] / 100;
9575 const g = hcg[2] / 100;
9576 const v = c + g * (1.0 - c);
9577 return [hcg[0], (v - c) * 100, (1 - v) * 100];
9580 convert$1.hwb.hcg = function (hwb) {
9581 const w = hwb[1] / 100;
9582 const b = hwb[2] / 100;
9588 g = (v - c) / (1 - c);
9591 return [hwb[0], c * 100, g * 100];
9594 convert$1.apple.rgb = function (apple) {
9595 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
9598 convert$1.rgb.apple = function (rgb) {
9599 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
9602 convert$1.gray.rgb = function (args) {
9603 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
9606 convert$1.gray.hsl = function (args) {
9607 return [0, 0, args[0]];
9610 convert$1.gray.hsv = convert$1.gray.hsl;
9612 convert$1.gray.hwb = function (gray) {
9613 return [0, 100, gray[0]];
9616 convert$1.gray.cmyk = function (gray) {
9617 return [0, 0, 0, gray[0]];
9620 convert$1.gray.lab = function (gray) {
9621 return [gray[0], 0, 0];
9624 convert$1.gray.hex = function (gray) {
9625 const val = Math.round(gray[0] / 100 * 255) & 0xFF;
9626 const integer = (val << 16) + (val << 8) + val;
9627 const string = integer.toString(16).toUpperCase();
9628 return '000000'.substring(string.length) + string;
9631 convert$1.rgb.gray = function (rgb) {
9632 const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
9633 return [val / 255 * 100];
9637 This function routes a model to all other models.
9639 all functions that are routed have a property `.conversion` attached
9640 to the returned synthetic function. This property is an array
9641 of strings, each with the steps in between the 'from' and 'to'
9642 color models (inclusive).
9644 conversions that are not possible simply are not included.
9647 function buildGraph$1() {
9648 const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
9650 const models = Object.keys(conversions$1);
9652 for (let len = models.length, i = 0; i < len; i++) {
9653 graph[models[i]] = {
9654 // http://jsperf.com/1-vs-infinity
9655 // micro-opt, but this is simple.
9662 } // https://en.wikipedia.org/wiki/Breadth-first_search
9665 function deriveBFS$1(fromModel) {
9666 const graph = buildGraph$1();
9667 const queue = [fromModel]; // Unshift -> queue -> pop
9669 graph[fromModel].distance = 0;
9671 while (queue.length) {
9672 const current = queue.pop();
9673 const adjacents = Object.keys(conversions$1[current]);
9675 for (let len = adjacents.length, i = 0; i < len; i++) {
9676 const adjacent = adjacents[i];
9677 const node = graph[adjacent];
9679 if (node.distance === -1) {
9680 node.distance = graph[current].distance + 1;
9681 node.parent = current;
9682 queue.unshift(adjacent);
9690 function link$1(from, to) {
9691 return function (args) {
9692 return to(from(args));
9696 function wrapConversion$1(toModel, graph) {
9697 const path = [graph[toModel].parent, toModel];
9698 let fn = conversions$1[graph[toModel].parent][toModel];
9699 let cur = graph[toModel].parent;
9701 while (graph[cur].parent) {
9702 path.unshift(graph[cur].parent);
9703 fn = link$1(conversions$1[graph[cur].parent][cur], fn);
9704 cur = graph[cur].parent;
9707 fn.conversion = path;
9711 var route$1 = function (fromModel) {
9712 const graph = deriveBFS$1(fromModel);
9713 const conversion = {};
9714 const models = Object.keys(graph);
9716 for (let len = models.length, i = 0; i < len; i++) {
9717 const toModel = models[i];
9718 const node = graph[toModel];
9720 if (node.parent === null) {
9721 // No possible conversion, or this node is the source model.
9725 conversion[toModel] = wrapConversion$1(toModel, graph);
9731 const convert$2 = {};
9732 const models$1 = Object.keys(conversions$1);
9734 function wrapRaw$1(fn) {
9735 const wrappedFn = function (...args) {
9736 const arg0 = args[0];
9738 if (arg0 === undefined || arg0 === null) {
9742 if (arg0.length > 1) {
9747 }; // Preserve .conversion property if there is one
9750 if ('conversion' in fn) {
9751 wrappedFn.conversion = fn.conversion;
9757 function wrapRounded$1(fn) {
9758 const wrappedFn = function (...args) {
9759 const arg0 = args[0];
9761 if (arg0 === undefined || arg0 === null) {
9765 if (arg0.length > 1) {
9769 const result = fn(args); // We're assuming the result is an array here.
9770 // see notice in conversions.js; don't use box types
9771 // in conversion functions.
9773 if (typeof result === 'object') {
9774 for (let len = result.length, i = 0; i < len; i++) {
9775 result[i] = Math.round(result[i]);
9780 }; // Preserve .conversion property if there is one
9783 if ('conversion' in fn) {
9784 wrappedFn.conversion = fn.conversion;
9790 models$1.forEach(fromModel => {
9791 convert$2[fromModel] = {};
9792 Object.defineProperty(convert$2[fromModel], 'channels', {
9793 value: conversions$1[fromModel].channels
9795 Object.defineProperty(convert$2[fromModel], 'labels', {
9796 value: conversions$1[fromModel].labels
9798 const routes = route$1(fromModel);
9799 const routeModels = Object.keys(routes);
9800 routeModels.forEach(toModel => {
9801 const fn = routes[toModel];
9802 convert$2[fromModel][toModel] = wrapRounded$1(fn);
9803 convert$2[fromModel][toModel].raw = wrapRaw$1(fn);
9806 var colorConvert$1 = convert$2;
9808 var ansiStyles$1 = createCommonjsModule(function (module) {
9810 const wrapAnsi16 = (fn, offset) => (...args) => {
9811 const code = fn(...args);
9812 return `\u001B[${code + offset}m`;
9815 const wrapAnsi256 = (fn, offset) => (...args) => {
9816 const code = fn(...args);
9817 return `\u001B[${38 + offset};5;${code}m`;
9820 const wrapAnsi16m = (fn, offset) => (...args) => {
9821 const rgb = fn(...args);
9822 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
9825 const ansi2ansi = n => n;
9827 const rgb2rgb = (r, g, b) => [r, g, b];
9829 const setLazyProperty = (object, property, get) => {
9830 Object.defineProperty(object, property, {
9832 const value = get();
9833 Object.defineProperty(object, property, {
9844 /** @type {typeof import('color-convert')} */
9849 const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
9850 if (colorConvert === undefined) {
9851 colorConvert = colorConvert$1;
9854 const offset = isBackground ? 10 : 0;
9857 for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
9858 const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
9860 if (sourceSpace === targetSpace) {
9861 styles[name] = wrap(identity, offset);
9862 } else if (typeof suite === 'object') {
9863 styles[name] = wrap(suite[targetSpace], offset);
9870 function assembleStyles() {
9871 const codes = new Map();
9875 // 21 isn't widely supported and 22 does the same thing
9882 strikethrough: [9, 29]
9894 blackBright: [90, 39],
9895 redBright: [91, 39],
9896 greenBright: [92, 39],
9897 yellowBright: [93, 39],
9898 blueBright: [94, 39],
9899 magentaBright: [95, 39],
9900 cyanBright: [96, 39],
9901 whiteBright: [97, 39]
9909 bgMagenta: [45, 49],
9913 bgBlackBright: [100, 49],
9914 bgRedBright: [101, 49],
9915 bgGreenBright: [102, 49],
9916 bgYellowBright: [103, 49],
9917 bgBlueBright: [104, 49],
9918 bgMagentaBright: [105, 49],
9919 bgCyanBright: [106, 49],
9920 bgWhiteBright: [107, 49]
9922 }; // Alias bright black as gray (and grey)
9924 styles.color.gray = styles.color.blackBright;
9925 styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
9926 styles.color.grey = styles.color.blackBright;
9927 styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
9929 for (const [groupName, group] of Object.entries(styles)) {
9930 for (const [styleName, style] of Object.entries(group)) {
9931 styles[styleName] = {
9932 open: `\u001B[${style[0]}m`,
9933 close: `\u001B[${style[1]}m`
9935 group[styleName] = styles[styleName];
9936 codes.set(style[0], style[1]);
9939 Object.defineProperty(styles, groupName, {
9945 Object.defineProperty(styles, 'codes', {
9949 styles.color.close = '\u001B[39m';
9950 styles.bgColor.close = '\u001B[49m';
9951 setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
9952 setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
9953 setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
9954 setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
9955 setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
9956 setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
9958 } // Make the export immutable
9961 Object.defineProperty(module, 'exports', {
9967 var hasFlag$1 = (flag, argv = process.argv) => {
9968 const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
9969 const position = argv.indexOf(prefix + flag);
9970 const terminatorPosition = argv.indexOf('--');
9971 return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
9979 if (hasFlag$1('no-color') || hasFlag$1('no-colors') || hasFlag$1('color=false') || hasFlag$1('color=never')) {
9981 } else if (hasFlag$1('color') || hasFlag$1('colors') || hasFlag$1('color=true') || hasFlag$1('color=always')) {
9985 if ('FORCE_COLOR' in env$1) {
9986 if (env$1.FORCE_COLOR === 'true') {
9988 } else if (env$1.FORCE_COLOR === 'false') {
9991 forceColor$1 = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3);
9995 function translateLevel$1(level) {
10003 has256: level >= 2,
10008 function supportsColor$1(haveStream, streamIsTTY) {
10009 if (forceColor$1 === 0) {
10013 if (hasFlag$1('color=16m') || hasFlag$1('color=full') || hasFlag$1('color=truecolor')) {
10017 if (hasFlag$1('color=256')) {
10021 if (haveStream && !streamIsTTY && forceColor$1 === undefined) {
10025 const min = forceColor$1 || 0;
10027 if (env$1.TERM === 'dumb') {
10031 if (process.platform === 'win32') {
10032 // Windows 10 build 10586 is the first Windows release that supports 256 colors.
10033 // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
10034 const osRelease = os__default['default'].release().split('.');
10036 if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
10037 return Number(osRelease[2]) >= 14931 ? 3 : 2;
10043 if ('CI' in env$1) {
10044 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') {
10051 if ('TEAMCITY_VERSION' in env$1) {
10052 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
10055 if ('GITHUB_ACTIONS' in env$1) {
10059 if (env$1.COLORTERM === 'truecolor') {
10063 if ('TERM_PROGRAM' in env$1) {
10064 const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
10066 switch (env$1.TERM_PROGRAM) {
10068 return version >= 3 ? 3 : 2;
10070 case 'Apple_Terminal':
10076 if (/-256(color)?$/i.test(env$1.TERM)) {
10080 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
10084 if ('COLORTERM' in env$1) {
10091 function getSupportLevel$1(stream) {
10092 const level = supportsColor$1(stream, stream && stream.isTTY);
10093 return translateLevel$1(level);
10096 var supportsColor_1$1 = {
10097 supportsColor: getSupportLevel$1,
10098 stdout: translateLevel$1(supportsColor$1(true, tty__default['default'].isatty(1))),
10099 stderr: translateLevel$1(supportsColor$1(true, tty__default['default'].isatty(2)))
10102 const stringReplaceAll = (string, substring, replacer) => {
10103 let index = string.indexOf(substring);
10105 if (index === -1) {
10109 const substringLength = substring.length;
10111 let returnValue = '';
10114 returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
10115 endIndex = index + substringLength;
10116 index = string.indexOf(substring, endIndex);
10117 } while (index !== -1);
10119 returnValue += string.substr(endIndex);
10120 return returnValue;
10123 const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
10125 let returnValue = '';
10128 const gotCR = string[index - 1] === '\r';
10129 returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
10130 endIndex = index + 1;
10131 index = string.indexOf('\n', endIndex);
10132 } while (index !== -1);
10134 returnValue += string.substr(endIndex);
10135 return returnValue;
10140 stringEncaseCRLFWithFirstIndex
10143 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;
10144 const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
10145 const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
10146 const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
10147 const ESCAPES$1 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
10149 function unescape$1(c) {
10150 const u = c[0] === 'u';
10151 const bracket = c[1] === '{';
10153 if (u && !bracket && c.length === 5 || c[0] === 'x' && c.length === 3) {
10154 return String.fromCharCode(parseInt(c.slice(1), 16));
10157 if (u && bracket) {
10158 return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
10161 return ESCAPES$1.get(c) || c;
10164 function parseArguments$1(name, arguments_) {
10165 const results = [];
10166 const chunks = arguments_.trim().split(/\s*,\s*/g);
10169 for (const chunk of chunks) {
10170 const number = Number(chunk);
10172 if (!Number.isNaN(number)) {
10173 results.push(number);
10174 } else if (matches = chunk.match(STRING_REGEX$1)) {
10175 results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$1(escape) : character));
10177 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
10184 function parseStyle$1(style) {
10185 STYLE_REGEX$1.lastIndex = 0;
10186 const results = [];
10189 while ((matches = STYLE_REGEX$1.exec(style)) !== null) {
10190 const name = matches[1];
10193 const args = parseArguments$1(name, matches[2]);
10194 results.push([name].concat(args));
10196 results.push([name]);
10203 function buildStyle$1(chalk, styles) {
10204 const enabled = {};
10206 for (const layer of styles) {
10207 for (const style of layer.styles) {
10208 enabled[style[0]] = layer.inverse ? null : style.slice(1);
10212 let current = chalk;
10214 for (const [styleName, styles] of Object.entries(enabled)) {
10215 if (!Array.isArray(styles)) {
10219 if (!(styleName in current)) {
10220 throw new Error(`Unknown Chalk style: ${styleName}`);
10223 current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
10229 var templates$1 = (chalk, temporary) => {
10232 let chunk = []; // eslint-disable-next-line max-params
10234 temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => {
10235 if (escapeCharacter) {
10236 chunk.push(unescape$1(escapeCharacter));
10237 } else if (style) {
10238 const string = chunk.join('');
10240 chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string));
10243 styles: parseStyle$1(style)
10245 } else if (close) {
10246 if (styles.length === 0) {
10247 throw new Error('Found extraneous } in Chalk template literal');
10250 chunks.push(buildStyle$1(chalk, styles)(chunk.join('')));
10254 chunk.push(character);
10257 chunks.push(chunk.join(''));
10259 if (styles.length > 0) {
10260 const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
10261 throw new Error(errMessage);
10264 return chunks.join('');
10268 stdout: stdoutColor,
10269 stderr: stderrColor
10270 } = supportsColor_1$1;
10272 stringReplaceAll: stringReplaceAll$1,
10273 stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
10277 } = Array; // `supportsColor.level` → `ansiStyles.color[name]` mapping
10279 const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
10280 const styles = Object.create(null);
10282 const applyOptions = (object, options = {}) => {
10283 if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
10284 throw new Error('The `level` option should be an integer from 0 to 3');
10285 } // Detect level if not set manually
10288 const colorLevel = stdoutColor ? stdoutColor.level : 0;
10289 object.level = options.level === undefined ? colorLevel : options.level;
10293 constructor(options) {
10294 // eslint-disable-next-line no-constructor-return
10295 return chalkFactory(options);
10300 const chalkFactory = options => {
10302 applyOptions(chalk, options);
10304 chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
10306 Object.setPrototypeOf(chalk, Chalk.prototype);
10307 Object.setPrototypeOf(chalk.template, chalk);
10309 chalk.template.constructor = () => {
10310 throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
10313 chalk.template.Instance = ChalkClass;
10314 return chalk.template;
10317 function Chalk(options) {
10318 return chalkFactory(options);
10321 for (const [styleName, style] of Object.entries(ansiStyles$1)) {
10322 styles[styleName] = {
10324 const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
10325 Object.defineProperty(this, styleName, {
10336 const builder = createBuilder(this, this._styler, true);
10337 Object.defineProperty(this, 'visible', {
10344 const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
10346 for (const model of usedModels) {
10352 return function (...arguments_) {
10353 const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler);
10354 return createBuilder(this, styler, this._isEmpty);
10361 for (const model of usedModels) {
10362 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
10363 styles[bgModel] = {
10368 return function (...arguments_) {
10369 const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler);
10370 return createBuilder(this, styler, this._isEmpty);
10377 const proto = Object.defineProperties(() => {}, Object.assign({}, styles, {
10382 return this._generator.level;
10386 this._generator.level = level;
10392 const createStyler = (open, close, parent) => {
10396 if (parent === undefined) {
10400 openAll = parent.openAll + open;
10401 closeAll = close + parent.closeAll;
10413 const createBuilder = (self, _styler, _isEmpty) => {
10414 const builder = (...arguments_) => {
10415 if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) {
10416 // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
10417 return applyStyle(builder, chalkTag(builder, ...arguments_));
10418 } // Single argument is hot path, implicit coercion is faster than anything
10419 // eslint-disable-next-line no-implicit-coercion
10422 return applyStyle(builder, arguments_.length === 1 ? '' + arguments_[0] : arguments_.join(' '));
10423 }; // We alter the prototype because we must return a function, but there is
10424 // no way to create a function with a different prototype
10427 Object.setPrototypeOf(builder, proto);
10428 builder._generator = self;
10429 builder._styler = _styler;
10430 builder._isEmpty = _isEmpty;
10434 const applyStyle = (self, string) => {
10435 if (self.level <= 0 || !string) {
10436 return self._isEmpty ? '' : string;
10439 let styler = self._styler;
10441 if (styler === undefined) {
10450 if (string.indexOf('\u001B') !== -1) {
10451 while (styler !== undefined) {
10452 // Replace any instances already present with a re-opening code
10453 // otherwise only the part of the string until said closing code
10454 // will be colored, and the rest will simply be 'plain'.
10455 string = stringReplaceAll$1(string, styler.close, styler.open);
10456 styler = styler.parent;
10458 } // We can move both next actions out of loop, because remaining actions in loop won't have
10459 // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
10460 // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
10463 const lfIndex = string.indexOf('\n');
10465 if (lfIndex !== -1) {
10466 string = stringEncaseCRLFWithFirstIndex$1(string, closeAll, openAll, lfIndex);
10469 return openAll + string + closeAll;
10474 const chalkTag = (chalk, ...strings) => {
10475 const [firstString] = strings;
10477 if (!isArray(firstString) || !isArray(firstString.raw)) {
10478 // If chalk() was called by itself or with a string,
10479 // return the string itself as a string.
10480 return strings.join(' ');
10483 const arguments_ = strings.slice(1);
10484 const parts = [firstString.raw[0]];
10486 for (let i = 1; i < firstString.length; i++) {
10487 parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]));
10490 if (template === undefined) {
10491 template = templates$1;
10494 return template(chalk, parts.join(''));
10497 Object.defineProperties(Chalk.prototype, styles);
10498 const chalk$1 = Chalk(); // eslint-disable-line new-cap
10500 chalk$1.supportsColor = stdoutColor;
10501 chalk$1.stderr = Chalk({
10502 level: stderrColor ? stderrColor.level : 0
10503 }); // eslint-disable-line new-cap
10505 chalk$1.stderr.supportsColor = stderrColor;
10506 var source = chalk$1;
10509 * Appends the elements of `values` to `array`.
10512 * @param {Array} array The array to modify.
10513 * @param {Array} values The values to append.
10514 * @returns {Array} Returns `array`.
10516 function arrayPush(array, values) {
10518 length = values.length,
10519 offset = array.length;
10521 while (++index < length) {
10522 array[offset + index] = values[index];
10528 var _arrayPush = arrayPush;
10530 /** Detect free variable `global` from Node.js. */
10531 var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
10532 var _freeGlobal = freeGlobal;
10534 /** Detect free variable `self`. */
10536 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
10537 /** Used as a reference to the global object. */
10539 var root = _freeGlobal || freeSelf || Function('return this')();
10542 /** Built-in value references. */
10544 var Symbol$1 = _root.Symbol;
10545 var _Symbol = Symbol$1;
10547 /** Used for built-in method references. */
10549 var objectProto = Object.prototype;
10550 /** Used to check objects for own properties. */
10552 var hasOwnProperty = objectProto.hasOwnProperty;
10554 * Used to resolve the
10555 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
10559 var nativeObjectToString = objectProto.toString;
10560 /** Built-in value references. */
10562 var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
10564 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
10567 * @param {*} value The value to query.
10568 * @returns {string} Returns the raw `toStringTag`.
10571 function getRawTag(value) {
10572 var isOwn = hasOwnProperty.call(value, symToStringTag),
10573 tag = value[symToStringTag];
10576 value[symToStringTag] = undefined;
10577 var unmasked = true;
10580 var result = nativeObjectToString.call(value);
10584 value[symToStringTag] = tag;
10586 delete value[symToStringTag];
10593 var _getRawTag = getRawTag;
10595 /** Used for built-in method references. */
10596 var objectProto$1 = Object.prototype;
10598 * Used to resolve the
10599 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
10603 var nativeObjectToString$1 = objectProto$1.toString;
10605 * Converts `value` to a string using `Object.prototype.toString`.
10608 * @param {*} value The value to convert.
10609 * @returns {string} Returns the converted string.
10612 function objectToString(value) {
10613 return nativeObjectToString$1.call(value);
10616 var _objectToString = objectToString;
10618 /** `Object#toString` result references. */
10620 var nullTag = '[object Null]',
10621 undefinedTag = '[object Undefined]';
10622 /** Built-in value references. */
10624 var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
10626 * The base implementation of `getTag` without fallbacks for buggy environments.
10629 * @param {*} value The value to query.
10630 * @returns {string} Returns the `toStringTag`.
10633 function baseGetTag(value) {
10634 if (value == null) {
10635 return value === undefined ? undefinedTag : nullTag;
10638 return symToStringTag$1 && symToStringTag$1 in Object(value) ? _getRawTag(value) : _objectToString(value);
10641 var _baseGetTag = baseGetTag;
10644 * Checks if `value` is object-like. A value is object-like if it's not `null`
10645 * and has a `typeof` result of "object".
10651 * @param {*} value The value to check.
10652 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
10655 * _.isObjectLike({});
10658 * _.isObjectLike([1, 2, 3]);
10661 * _.isObjectLike(_.noop);
10664 * _.isObjectLike(null);
10667 function isObjectLike(value) {
10668 return value != null && typeof value == 'object';
10671 var isObjectLike_1 = isObjectLike;
10673 /** `Object#toString` result references. */
10675 var argsTag = '[object Arguments]';
10677 * The base implementation of `_.isArguments`.
10680 * @param {*} value The value to check.
10681 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
10684 function baseIsArguments(value) {
10685 return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
10688 var _baseIsArguments = baseIsArguments;
10690 /** Used for built-in method references. */
10692 var objectProto$2 = Object.prototype;
10693 /** Used to check objects for own properties. */
10695 var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
10696 /** Built-in value references. */
10698 var propertyIsEnumerable = objectProto$2.propertyIsEnumerable;
10700 * Checks if `value` is likely an `arguments` object.
10706 * @param {*} value The value to check.
10707 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
10711 * _.isArguments(function() { return arguments; }());
10714 * _.isArguments([1, 2, 3]);
10718 var isArguments = _baseIsArguments(function () {
10720 }()) ? _baseIsArguments : function (value) {
10721 return isObjectLike_1(value) && hasOwnProperty$1.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
10723 var isArguments_1 = isArguments;
10726 * Checks if `value` is classified as an `Array` object.
10732 * @param {*} value The value to check.
10733 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
10736 * _.isArray([1, 2, 3]);
10739 * _.isArray(document.body.children);
10742 * _.isArray('abc');
10745 * _.isArray(_.noop);
10748 var isArray$1 = Array.isArray;
10749 var isArray_1 = isArray$1;
10751 /** Built-in value references. */
10753 var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
10755 * Checks if `value` is a flattenable `arguments` object or array.
10758 * @param {*} value The value to check.
10759 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
10762 function isFlattenable(value) {
10763 return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
10766 var _isFlattenable = isFlattenable;
10769 * The base implementation of `_.flatten` with support for restricting flattening.
10772 * @param {Array} array The array to flatten.
10773 * @param {number} depth The maximum recursion depth.
10774 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
10775 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
10776 * @param {Array} [result=[]] The initial result value.
10777 * @returns {Array} Returns the new flattened array.
10780 function baseFlatten(array, depth, predicate, isStrict, result) {
10782 length = array.length;
10783 predicate || (predicate = _isFlattenable);
10784 result || (result = []);
10786 while (++index < length) {
10787 var value = array[index];
10789 if (depth > 0 && predicate(value)) {
10791 // Recursively flatten arrays (susceptible to call stack limits).
10792 baseFlatten(value, depth - 1, predicate, isStrict, result);
10794 _arrayPush(result, value);
10796 } else if (!isStrict) {
10797 result[result.length] = value;
10804 var _baseFlatten = baseFlatten;
10807 * Flattens `array` a single level deep.
10813 * @param {Array} array The array to flatten.
10814 * @returns {Array} Returns the new flattened array.
10817 * _.flatten([1, [2, [3, [4]], 5]]);
10818 * // => [1, 2, [3, [4]], 5]
10821 function flatten(array) {
10822 var length = array == null ? 0 : array.length;
10823 return length ? _baseFlatten(array, 1) : [];
10826 var flatten_1 = flatten;
10828 const cliDescriptor = {
10829 key: key => key.length === 1 ? `-${key}` : `--${key}`,
10830 value: value => lib$1.apiDescriptor.value(value),
10834 }) => value === false ? `--no-${key}` : value === true ? cliDescriptor.key(key) : value === "" ? `${cliDescriptor.key(key)} without an argument` : `${cliDescriptor.key(key)}=${value}`
10837 class FlagSchema extends lib$1.ChoiceSchema {
10846 this._flags = flags.slice().sort();
10849 preprocess(value, utils) {
10850 if (typeof value === "string" && value.length !== 0 && !this._flags.includes(value)) {
10851 const suggestion = this._flags.find(flag => leven_1$1(flag, value) < 3);
10854 utils.logger.warn([`Unknown flag ${source.yellow(utils.descriptor.value(value))},`, `did you mean ${source.blue(utils.descriptor.value(suggestion))}?`].join(" "));
10868 let hasDeprecationWarned;
10870 function normalizeOptions(options, optionInfos, {
10873 passThrough = false
10875 const unknown = !passThrough ? (key, value, options) => {
10876 // Don't suggest `_` for unknown flags
10877 const _options$schemas = options.schemas,
10878 schemas = _objectWithoutPropertiesLoose(_options$schemas, ["_"]);
10880 return lib$1.levenUnknownHandler(key, value, Object.assign({}, options, {
10883 } : Array.isArray(passThrough) ? (key, value) => !passThrough.includes(key) ? undefined : {
10885 } : (key, value) => ({
10888 const descriptor = isCLI ? cliDescriptor : lib$1.apiDescriptor;
10889 const schemas = optionInfosToSchemas(optionInfos, {
10892 const normalizer = new lib$1.Normalizer(schemas, {
10897 const shouldSuppressDuplicateDeprecationWarnings = logger !== false;
10899 if (shouldSuppressDuplicateDeprecationWarnings && hasDeprecationWarned) {
10900 normalizer._hasDeprecationWarned = hasDeprecationWarned;
10903 const normalized = normalizer.normalize(options);
10905 if (shouldSuppressDuplicateDeprecationWarnings) {
10906 hasDeprecationWarned = normalizer._hasDeprecationWarned;
10912 function optionInfosToSchemas(optionInfos, {
10915 const schemas = [];
10918 schemas.push(lib$1.AnySchema.create({
10923 for (const optionInfo of optionInfos) {
10924 schemas.push(optionInfoToSchema(optionInfo, {
10929 if (optionInfo.alias && isCLI) {
10930 schemas.push(lib$1.AliasSchema.create({
10931 name: optionInfo.alias,
10932 sourceName: optionInfo.name
10940 function optionInfoToSchema(optionInfo, {
10944 let SchemaConstructor;
10945 const parameters = {
10946 name: optionInfo.name
10948 const handlers = {};
10950 switch (optionInfo.type) {
10952 SchemaConstructor = lib$1.IntegerSchema;
10955 parameters.preprocess = value => Number(value);
10961 SchemaConstructor = lib$1.StringSchema;
10965 SchemaConstructor = lib$1.ChoiceSchema;
10966 parameters.choices = optionInfo.choices.map(choiceInfo => typeof choiceInfo === "object" && choiceInfo.redirect ? Object.assign({}, choiceInfo, {
10969 key: optionInfo.name,
10970 value: choiceInfo.redirect
10977 SchemaConstructor = lib$1.BooleanSchema;
10981 SchemaConstructor = FlagSchema;
10982 parameters.flags = flatten_1(optionInfos.map(optionInfo => [optionInfo.alias, optionInfo.description && optionInfo.name, optionInfo.oppositeDescription && `no-${optionInfo.name}`].filter(Boolean)));
10986 SchemaConstructor = lib$1.StringSchema;
10990 /* istanbul ignore next */
10991 throw new Error(`Unexpected type ${optionInfo.type}`);
10994 if (optionInfo.exception) {
10995 parameters.validate = (value, schema, utils) => {
10996 return optionInfo.exception(value) || schema.validate(value, utils);
10999 parameters.validate = (value, schema, utils) => {
11000 return value === undefined || schema.validate(value, utils);
11003 /* istanbul ignore next */
11006 if (optionInfo.redirect) {
11007 handlers.redirect = value => !value ? undefined : {
11009 key: optionInfo.redirect.option,
11010 value: optionInfo.redirect.value
11014 /* istanbul ignore next */
11017 if (optionInfo.deprecated) {
11018 handlers.deprecated = true;
11019 } // allow CLI overriding, e.g., prettier package.json --tab-width 1 --tab-width 2
11022 if (isCLI && !optionInfo.array) {
11023 const originalPreprocess = parameters.preprocess || (x => x);
11025 parameters.preprocess = (value, schema, utils) => schema.preprocess(originalPreprocess(Array.isArray(value) ? value[value.length - 1] : value), utils);
11028 return optionInfo.array ? lib$1.ArraySchema.create(Object.assign({}, isCLI ? {
11029 preprocess: v => [].concat(v)
11030 } : {}, handlers, {
11031 valueSchema: SchemaConstructor.create(parameters)
11032 })) : SchemaConstructor.create(Object.assign({}, parameters, handlers));
11035 function normalizeApiOptions(options, optionInfos, opts) {
11036 return normalizeOptions(options, optionInfos, opts);
11039 function normalizeCliOptions(options, optionInfos, opts) {
11040 return normalizeOptions(options, optionInfos, Object.assign({
11045 var optionsNormalizer = {
11046 normalizeApiOptions,
11047 normalizeCliOptions
11051 * @typedef {import("./types/estree").Node} Node
11054 function locStart(node, opts) {
11057 } = opts || {}; // Handle nodes with decorators. They should start at the first decorator
11059 if (!ignoreDecorators) {
11060 const decorators = node.declaration && node.declaration.decorators || node.decorators;
11062 if (decorators && decorators.length > 0) {
11063 return locStart(decorators[0]);
11067 return node.range ? node.range[0] : node.start;
11070 function locEnd(node) {
11071 const end = node.range ? node.range[1] : node.end;
11072 return node.typeAnnotation ? Math.max(end, locEnd(node.typeAnnotation)) : end;
11075 * @param {Node} startNode
11076 * @param {Node | number} endNodeOrLength
11077 * @returns {number[]}
11081 function composeLoc(startNode, endNodeOrLength = startNode) {
11082 const start = locStart(startNode);
11083 const end = typeof endNodeOrLength === "number" ? start + endNodeOrLength : locEnd(endNodeOrLength);
11084 return [start, end];
11087 * @param {Node} nodeA
11088 * @param {Node} nodeB
11089 * @returns {boolean}
11093 function hasSameLocStart(nodeA, nodeB) {
11094 return locStart(nodeA) === locStart(nodeB);
11097 * @param {Node} nodeA
11098 * @param {Node} nodeB
11099 * @returns {boolean}
11103 function hasSameLocEnd(nodeA, nodeB) {
11104 return locEnd(nodeA) === locEnd(nodeB);
11107 * @param {Node} nodeA
11108 * @param {Node} nodeB
11109 * @returns {boolean}
11113 function hasSameLoc(nodeA, nodeB) {
11114 return hasSameLocStart(nodeA, nodeB) && hasSameLocEnd(nodeA, nodeB);
11125 var jsTokens = createCommonjsModule(function (module, exports) {
11126 // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell
11127 // License: MIT. (See LICENSE.)
11128 Object.defineProperty(exports, "__esModule", {
11130 }); // This regex comes from regex.coffee, and is inserted here by generate-index.js
11131 // (run `npm run build`).
11133 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;
11135 exports.matchToToken = function (match) {
11141 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";
11146 var identifier = createCommonjsModule(function (module, exports) {
11148 Object.defineProperty(exports, "__esModule", {
11151 exports.isIdentifierStart = isIdentifierStart;
11152 exports.isIdentifierChar = isIdentifierChar;
11153 exports.isIdentifierName = isIdentifierName;
11154 let nonASCIIidentifierStartChars = "\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\u0560-\u0588\u05d0-\u05ea\u05ef-\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\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\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\u09fc\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\u0d04-\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\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\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-\u1878\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\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\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-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\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-\uab69\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";
11155 let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
11156 const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
11157 const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
11158 nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
11159 const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
11160 const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
11162 function isInAstralSet(code, set) {
11165 for (let i = 0, length = set.length; i < length; i += 2) {
11167 if (pos > code) return false;
11169 if (pos >= code) return true;
11175 function isIdentifierStart(code) {
11176 if (code < 65) return code === 36;
11177 if (code <= 90) return true;
11178 if (code < 97) return code === 95;
11179 if (code <= 122) return true;
11181 if (code <= 0xffff) {
11182 return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
11185 return isInAstralSet(code, astralIdentifierStartCodes);
11188 function isIdentifierChar(code) {
11189 if (code < 48) return code === 36;
11190 if (code < 58) return true;
11191 if (code < 65) return false;
11192 if (code <= 90) return true;
11193 if (code < 97) return code === 95;
11194 if (code <= 122) return true;
11196 if (code <= 0xffff) {
11197 return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
11200 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
11203 function isIdentifierName(name) {
11204 let isFirst = true;
11206 for (let _i = 0, _Array$from = Array.from(name); _i < _Array$from.length; _i++) {
11207 const char = _Array$from[_i];
11208 const cp = char.codePointAt(0);
11211 if (!isIdentifierStart(cp)) {
11216 } else if (!isIdentifierChar(cp)) {
11225 var keyword = createCommonjsModule(function (module, exports) {
11227 Object.defineProperty(exports, "__esModule", {
11230 exports.isReservedWord = isReservedWord;
11231 exports.isStrictReservedWord = isStrictReservedWord;
11232 exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord;
11233 exports.isStrictBindReservedWord = isStrictBindReservedWord;
11234 exports.isKeyword = isKeyword;
11235 const reservedWords = {
11236 keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
11237 strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
11238 strictBind: ["eval", "arguments"]
11240 const keywords = new Set(reservedWords.keyword);
11241 const reservedWordsStrictSet = new Set(reservedWords.strict);
11242 const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
11244 function isReservedWord(word, inModule) {
11245 return inModule && word === "await" || word === "enum";
11248 function isStrictReservedWord(word, inModule) {
11249 return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
11252 function isStrictBindOnlyReservedWord(word) {
11253 return reservedWordsStrictBindSet.has(word);
11256 function isStrictBindReservedWord(word, inModule) {
11257 return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
11260 function isKeyword(word) {
11261 return keywords.has(word);
11265 var lib$2 = createCommonjsModule(function (module, exports) {
11267 Object.defineProperty(exports, "__esModule", {
11270 Object.defineProperty(exports, "isIdentifierName", {
11273 return identifier.isIdentifierName;
11276 Object.defineProperty(exports, "isIdentifierChar", {
11279 return identifier.isIdentifierChar;
11282 Object.defineProperty(exports, "isIdentifierStart", {
11285 return identifier.isIdentifierStart;
11288 Object.defineProperty(exports, "isReservedWord", {
11291 return keyword.isReservedWord;
11294 Object.defineProperty(exports, "isStrictBindOnlyReservedWord", {
11297 return keyword.isStrictBindOnlyReservedWord;
11300 Object.defineProperty(exports, "isStrictBindReservedWord", {
11303 return keyword.isStrictBindReservedWord;
11306 Object.defineProperty(exports, "isStrictReservedWord", {
11309 return keyword.isStrictReservedWord;
11312 Object.defineProperty(exports, "isKeyword", {
11315 return keyword.isKeyword;
11320 var matchOperatorsRe$1 = /[|\\{}()[\]^$+*?.]/g;
11322 var escapeStringRegexp$2 = function (str) {
11323 if (typeof str !== 'string') {
11324 throw new TypeError('Expected a string');
11327 return str.replace(matchOperatorsRe$1, '\\$&');
11330 var colorName$2 = {
11331 "aliceblue": [240, 248, 255],
11332 "antiquewhite": [250, 235, 215],
11333 "aqua": [0, 255, 255],
11334 "aquamarine": [127, 255, 212],
11335 "azure": [240, 255, 255],
11336 "beige": [245, 245, 220],
11337 "bisque": [255, 228, 196],
11338 "black": [0, 0, 0],
11339 "blanchedalmond": [255, 235, 205],
11340 "blue": [0, 0, 255],
11341 "blueviolet": [138, 43, 226],
11342 "brown": [165, 42, 42],
11343 "burlywood": [222, 184, 135],
11344 "cadetblue": [95, 158, 160],
11345 "chartreuse": [127, 255, 0],
11346 "chocolate": [210, 105, 30],
11347 "coral": [255, 127, 80],
11348 "cornflowerblue": [100, 149, 237],
11349 "cornsilk": [255, 248, 220],
11350 "crimson": [220, 20, 60],
11351 "cyan": [0, 255, 255],
11352 "darkblue": [0, 0, 139],
11353 "darkcyan": [0, 139, 139],
11354 "darkgoldenrod": [184, 134, 11],
11355 "darkgray": [169, 169, 169],
11356 "darkgreen": [0, 100, 0],
11357 "darkgrey": [169, 169, 169],
11358 "darkkhaki": [189, 183, 107],
11359 "darkmagenta": [139, 0, 139],
11360 "darkolivegreen": [85, 107, 47],
11361 "darkorange": [255, 140, 0],
11362 "darkorchid": [153, 50, 204],
11363 "darkred": [139, 0, 0],
11364 "darksalmon": [233, 150, 122],
11365 "darkseagreen": [143, 188, 143],
11366 "darkslateblue": [72, 61, 139],
11367 "darkslategray": [47, 79, 79],
11368 "darkslategrey": [47, 79, 79],
11369 "darkturquoise": [0, 206, 209],
11370 "darkviolet": [148, 0, 211],
11371 "deeppink": [255, 20, 147],
11372 "deepskyblue": [0, 191, 255],
11373 "dimgray": [105, 105, 105],
11374 "dimgrey": [105, 105, 105],
11375 "dodgerblue": [30, 144, 255],
11376 "firebrick": [178, 34, 34],
11377 "floralwhite": [255, 250, 240],
11378 "forestgreen": [34, 139, 34],
11379 "fuchsia": [255, 0, 255],
11380 "gainsboro": [220, 220, 220],
11381 "ghostwhite": [248, 248, 255],
11382 "gold": [255, 215, 0],
11383 "goldenrod": [218, 165, 32],
11384 "gray": [128, 128, 128],
11385 "green": [0, 128, 0],
11386 "greenyellow": [173, 255, 47],
11387 "grey": [128, 128, 128],
11388 "honeydew": [240, 255, 240],
11389 "hotpink": [255, 105, 180],
11390 "indianred": [205, 92, 92],
11391 "indigo": [75, 0, 130],
11392 "ivory": [255, 255, 240],
11393 "khaki": [240, 230, 140],
11394 "lavender": [230, 230, 250],
11395 "lavenderblush": [255, 240, 245],
11396 "lawngreen": [124, 252, 0],
11397 "lemonchiffon": [255, 250, 205],
11398 "lightblue": [173, 216, 230],
11399 "lightcoral": [240, 128, 128],
11400 "lightcyan": [224, 255, 255],
11401 "lightgoldenrodyellow": [250, 250, 210],
11402 "lightgray": [211, 211, 211],
11403 "lightgreen": [144, 238, 144],
11404 "lightgrey": [211, 211, 211],
11405 "lightpink": [255, 182, 193],
11406 "lightsalmon": [255, 160, 122],
11407 "lightseagreen": [32, 178, 170],
11408 "lightskyblue": [135, 206, 250],
11409 "lightslategray": [119, 136, 153],
11410 "lightslategrey": [119, 136, 153],
11411 "lightsteelblue": [176, 196, 222],
11412 "lightyellow": [255, 255, 224],
11413 "lime": [0, 255, 0],
11414 "limegreen": [50, 205, 50],
11415 "linen": [250, 240, 230],
11416 "magenta": [255, 0, 255],
11417 "maroon": [128, 0, 0],
11418 "mediumaquamarine": [102, 205, 170],
11419 "mediumblue": [0, 0, 205],
11420 "mediumorchid": [186, 85, 211],
11421 "mediumpurple": [147, 112, 219],
11422 "mediumseagreen": [60, 179, 113],
11423 "mediumslateblue": [123, 104, 238],
11424 "mediumspringgreen": [0, 250, 154],
11425 "mediumturquoise": [72, 209, 204],
11426 "mediumvioletred": [199, 21, 133],
11427 "midnightblue": [25, 25, 112],
11428 "mintcream": [245, 255, 250],
11429 "mistyrose": [255, 228, 225],
11430 "moccasin": [255, 228, 181],
11431 "navajowhite": [255, 222, 173],
11432 "navy": [0, 0, 128],
11433 "oldlace": [253, 245, 230],
11434 "olive": [128, 128, 0],
11435 "olivedrab": [107, 142, 35],
11436 "orange": [255, 165, 0],
11437 "orangered": [255, 69, 0],
11438 "orchid": [218, 112, 214],
11439 "palegoldenrod": [238, 232, 170],
11440 "palegreen": [152, 251, 152],
11441 "paleturquoise": [175, 238, 238],
11442 "palevioletred": [219, 112, 147],
11443 "papayawhip": [255, 239, 213],
11444 "peachpuff": [255, 218, 185],
11445 "peru": [205, 133, 63],
11446 "pink": [255, 192, 203],
11447 "plum": [221, 160, 221],
11448 "powderblue": [176, 224, 230],
11449 "purple": [128, 0, 128],
11450 "rebeccapurple": [102, 51, 153],
11451 "red": [255, 0, 0],
11452 "rosybrown": [188, 143, 143],
11453 "royalblue": [65, 105, 225],
11454 "saddlebrown": [139, 69, 19],
11455 "salmon": [250, 128, 114],
11456 "sandybrown": [244, 164, 96],
11457 "seagreen": [46, 139, 87],
11458 "seashell": [255, 245, 238],
11459 "sienna": [160, 82, 45],
11460 "silver": [192, 192, 192],
11461 "skyblue": [135, 206, 235],
11462 "slateblue": [106, 90, 205],
11463 "slategray": [112, 128, 144],
11464 "slategrey": [112, 128, 144],
11465 "snow": [255, 250, 250],
11466 "springgreen": [0, 255, 127],
11467 "steelblue": [70, 130, 180],
11468 "tan": [210, 180, 140],
11469 "teal": [0, 128, 128],
11470 "thistle": [216, 191, 216],
11471 "tomato": [255, 99, 71],
11472 "turquoise": [64, 224, 208],
11473 "violet": [238, 130, 238],
11474 "wheat": [245, 222, 179],
11475 "white": [255, 255, 255],
11476 "whitesmoke": [245, 245, 245],
11477 "yellow": [255, 255, 0],
11478 "yellowgreen": [154, 205, 50]
11481 var conversions$2 = createCommonjsModule(function (module) {
11483 // NOTE: conversions should only return primitive values (i.e. arrays, or
11484 // values that give correct `typeof` results).
11485 // do not use box values types (i.e. Number(), String(), etc.)
11486 var reverseKeywords = {};
11488 for (var key in colorName$2) {
11489 if (colorName$2.hasOwnProperty(key)) {
11490 reverseKeywords[colorName$2[key]] = key;
11494 var convert = module.exports = {
11533 labels: ['keyword']
11541 labels: ['ansi256']
11545 labels: ['h', 'c', 'g']
11549 labels: ['r16', 'g16', 'b16']
11555 }; // hide .channels and .labels properties
11557 for (var model in convert) {
11558 if (convert.hasOwnProperty(model)) {
11559 if (!('channels' in convert[model])) {
11560 throw new Error('missing channels property: ' + model);
11563 if (!('labels' in convert[model])) {
11564 throw new Error('missing channel labels property: ' + model);
11567 if (convert[model].labels.length !== convert[model].channels) {
11568 throw new Error('channel and label counts mismatch: ' + model);
11571 var channels = convert[model].channels;
11572 var labels = convert[model].labels;
11573 delete convert[model].channels;
11574 delete convert[model].labels;
11575 Object.defineProperty(convert[model], 'channels', {
11578 Object.defineProperty(convert[model], 'labels', {
11584 convert.rgb.hsl = function (rgb) {
11585 var r = rgb[0] / 255;
11586 var g = rgb[1] / 255;
11587 var b = rgb[2] / 255;
11588 var min = Math.min(r, g, b);
11589 var max = Math.max(r, g, b);
11590 var delta = max - min;
11597 } else if (r === max) {
11598 h = (g - b) / delta;
11599 } else if (g === max) {
11600 h = 2 + (b - r) / delta;
11601 } else if (b === max) {
11602 h = 4 + (r - g) / delta;
11605 h = Math.min(h * 60, 360);
11611 l = (min + max) / 2;
11615 } else if (l <= 0.5) {
11616 s = delta / (max + min);
11618 s = delta / (2 - max - min);
11621 return [h, s * 100, l * 100];
11624 convert.rgb.hsv = function (rgb) {
11630 var r = rgb[0] / 255;
11631 var g = rgb[1] / 255;
11632 var b = rgb[2] / 255;
11633 var v = Math.max(r, g, b);
11634 var diff = v - Math.min(r, g, b);
11636 var diffc = function (c) {
11637 return (v - c) / 6 / diff + 1 / 2;
11650 } else if (g === v) {
11651 h = 1 / 3 + rdif - bdif;
11652 } else if (b === v) {
11653 h = 2 / 3 + gdif - rdif;
11658 } else if (h > 1) {
11663 return [h * 360, s * 100, v * 100];
11666 convert.rgb.hwb = function (rgb) {
11670 var h = convert.rgb.hsl(rgb)[0];
11671 var w = 1 / 255 * Math.min(r, Math.min(g, b));
11672 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
11673 return [h, w * 100, b * 100];
11676 convert.rgb.cmyk = function (rgb) {
11677 var r = rgb[0] / 255;
11678 var g = rgb[1] / 255;
11679 var b = rgb[2] / 255;
11684 k = Math.min(1 - r, 1 - g, 1 - b);
11685 c = (1 - r - k) / (1 - k) || 0;
11686 m = (1 - g - k) / (1 - k) || 0;
11687 y = (1 - b - k) / (1 - k) || 0;
11688 return [c * 100, m * 100, y * 100, k * 100];
11691 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
11695 function comparativeDistance(x, y) {
11696 return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
11699 convert.rgb.keyword = function (rgb) {
11700 var reversed = reverseKeywords[rgb];
11706 var currentClosestDistance = Infinity;
11707 var currentClosestKeyword;
11709 for (var keyword in colorName$2) {
11710 if (colorName$2.hasOwnProperty(keyword)) {
11711 var value = colorName$2[keyword]; // Compute comparative distance
11713 var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
11715 if (distance < currentClosestDistance) {
11716 currentClosestDistance = distance;
11717 currentClosestKeyword = keyword;
11722 return currentClosestKeyword;
11725 convert.keyword.rgb = function (keyword) {
11726 return colorName$2[keyword];
11729 convert.rgb.xyz = function (rgb) {
11730 var r = rgb[0] / 255;
11731 var g = rgb[1] / 255;
11732 var b = rgb[2] / 255; // assume sRGB
11734 r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
11735 g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
11736 b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
11737 var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
11738 var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
11739 var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
11740 return [x * 100, y * 100, z * 100];
11743 convert.rgb.lab = function (rgb) {
11744 var xyz = convert.rgb.xyz(rgb);
11754 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
11755 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
11756 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
11763 convert.hsl.rgb = function (hsl) {
11764 var h = hsl[0] / 360;
11765 var s = hsl[1] / 100;
11766 var l = hsl[2] / 100;
11775 return [val, val, val];
11781 t2 = l + s - l * s;
11787 for (var i = 0; i < 3; i++) {
11788 t3 = h + 1 / 3 * -(i - 1);
11799 val = t1 + (t2 - t1) * 6 * t3;
11800 } else if (2 * t3 < 1) {
11802 } else if (3 * t3 < 2) {
11803 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
11808 rgb[i] = val * 255;
11814 convert.hsl.hsv = function (hsl) {
11816 var s = hsl[1] / 100;
11817 var l = hsl[2] / 100;
11819 var lmin = Math.max(l, 0.01);
11823 s *= l <= 1 ? l : 2 - l;
11824 smin *= lmin <= 1 ? lmin : 2 - lmin;
11826 sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
11827 return [h, sv * 100, v * 100];
11830 convert.hsv.rgb = function (hsv) {
11831 var h = hsv[0] / 60;
11832 var s = hsv[1] / 100;
11833 var v = hsv[2] / 100;
11834 var hi = Math.floor(h) % 6;
11835 var f = h - Math.floor(h);
11836 var p = 255 * v * (1 - s);
11837 var q = 255 * v * (1 - s * f);
11838 var t = 255 * v * (1 - s * (1 - f));
11862 convert.hsv.hsl = function (hsv) {
11864 var s = hsv[1] / 100;
11865 var v = hsv[2] / 100;
11866 var vmin = Math.max(v, 0.01);
11871 lmin = (2 - s) * vmin;
11873 sl /= lmin <= 1 ? lmin : 2 - lmin;
11876 return [h, sl * 100, l * 100];
11877 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
11880 convert.hwb.rgb = function (hwb) {
11881 var h = hwb[0] / 360;
11882 var wh = hwb[1] / 100;
11883 var bl = hwb[2] / 100;
11884 var ratio = wh + bl;
11888 var n; // wh + bl cant be > 1
11895 i = Math.floor(6 * h);
11899 if ((i & 0x01) !== 0) {
11903 n = wh + f * (v - wh); // linear interpolation
11949 return [r * 255, g * 255, b * 255];
11952 convert.cmyk.rgb = function (cmyk) {
11953 var c = cmyk[0] / 100;
11954 var m = cmyk[1] / 100;
11955 var y = cmyk[2] / 100;
11956 var k = cmyk[3] / 100;
11960 r = 1 - Math.min(1, c * (1 - k) + k);
11961 g = 1 - Math.min(1, m * (1 - k) + k);
11962 b = 1 - Math.min(1, y * (1 - k) + k);
11963 return [r * 255, g * 255, b * 255];
11966 convert.xyz.rgb = function (xyz) {
11967 var x = xyz[0] / 100;
11968 var y = xyz[1] / 100;
11969 var z = xyz[2] / 100;
11973 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
11974 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
11975 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
11977 r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
11978 g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
11979 b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
11980 r = Math.min(Math.max(0, r), 1);
11981 g = Math.min(Math.max(0, g), 1);
11982 b = Math.min(Math.max(0, b), 1);
11983 return [r * 255, g * 255, b * 255];
11986 convert.xyz.lab = function (xyz) {
11996 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
11997 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
11998 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
12005 convert.lab.xyz = function (lab) {
12012 y = (l + 16) / 116;
12015 var y2 = Math.pow(y, 3);
12016 var x2 = Math.pow(x, 3);
12017 var z2 = Math.pow(z, 3);
12018 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
12019 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
12020 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
12027 convert.lab.lch = function (lab) {
12034 hr = Math.atan2(b, a);
12035 h = hr * 360 / 2 / Math.PI;
12041 c = Math.sqrt(a * a + b * b);
12045 convert.lch.lab = function (lch) {
12052 hr = h / 360 * 2 * Math.PI;
12053 a = c * Math.cos(hr);
12054 b = c * Math.sin(hr);
12058 convert.rgb.ansi16 = function (args) {
12062 var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
12064 value = Math.round(value / 50);
12070 var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
12079 convert.hsv.ansi16 = function (args) {
12080 // optimization here; we already know the value and don't need to get
12081 // it converted for us.
12082 return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
12085 convert.rgb.ansi256 = function (args) {
12088 var b = args[2]; // we use the extended greyscale palette here, with the exception of
12089 // black and white. normal palette only has 4 greyscale shades.
12091 if (r === g && g === b) {
12100 return Math.round((r - 8) / 247 * 24) + 232;
12103 var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
12107 convert.ansi16.rgb = function (args) {
12108 var color = args % 10; // handle greyscale
12110 if (color === 0 || color === 7) {
12115 color = color / 10.5 * 255;
12116 return [color, color, color];
12119 var mult = (~~(args > 50) + 1) * 0.5;
12120 var r = (color & 1) * mult * 255;
12121 var g = (color >> 1 & 1) * mult * 255;
12122 var b = (color >> 2 & 1) * mult * 255;
12126 convert.ansi256.rgb = function (args) {
12127 // handle greyscale
12129 var c = (args - 232) * 10 + 8;
12135 var r = Math.floor(args / 36) / 5 * 255;
12136 var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
12137 var b = rem % 6 / 5 * 255;
12141 convert.rgb.hex = function (args) {
12142 var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
12143 var string = integer.toString(16).toUpperCase();
12144 return '000000'.substring(string.length) + string;
12147 convert.hex.rgb = function (args) {
12148 var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
12154 var colorString = match[0];
12156 if (match[0].length === 3) {
12157 colorString = colorString.split('').map(function (char) {
12158 return char + char;
12162 var integer = parseInt(colorString, 16);
12163 var r = integer >> 16 & 0xFF;
12164 var g = integer >> 8 & 0xFF;
12165 var b = integer & 0xFF;
12169 convert.rgb.hcg = function (rgb) {
12170 var r = rgb[0] / 255;
12171 var g = rgb[1] / 255;
12172 var b = rgb[2] / 255;
12173 var max = Math.max(Math.max(r, g), b);
12174 var min = Math.min(Math.min(r, g), b);
12175 var chroma = max - min;
12180 grayscale = min / (1 - chroma);
12187 } else if (max === r) {
12188 hue = (g - b) / chroma % 6;
12189 } else if (max === g) {
12190 hue = 2 + (b - r) / chroma;
12192 hue = 4 + (r - g) / chroma + 4;
12197 return [hue * 360, chroma * 100, grayscale * 100];
12200 convert.hsl.hcg = function (hsl) {
12201 var s = hsl[1] / 100;
12202 var l = hsl[2] / 100;
12209 c = 2.0 * s * (1.0 - l);
12213 f = (l - 0.5 * c) / (1.0 - c);
12216 return [hsl[0], c * 100, f * 100];
12219 convert.hsv.hcg = function (hsv) {
12220 var s = hsv[1] / 100;
12221 var v = hsv[2] / 100;
12226 f = (v - c) / (1 - c);
12229 return [hsv[0], c * 100, f * 100];
12232 convert.hcg.rgb = function (hcg) {
12233 var h = hcg[0] / 360;
12234 var c = hcg[1] / 100;
12235 var g = hcg[2] / 100;
12238 return [g * 255, g * 255, g * 255];
12241 var pure = [0, 0, 0];
12242 var hi = h % 1 * 6;
12247 switch (Math.floor(hi)) {
12284 mg = (1.0 - c) * g;
12285 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
12288 convert.hcg.hsv = function (hcg) {
12289 var c = hcg[1] / 100;
12290 var g = hcg[2] / 100;
12291 var v = c + g * (1.0 - c);
12298 return [hcg[0], f * 100, v * 100];
12301 convert.hcg.hsl = function (hcg) {
12302 var c = hcg[1] / 100;
12303 var g = hcg[2] / 100;
12304 var l = g * (1.0 - c) + 0.5 * c;
12307 if (l > 0.0 && l < 0.5) {
12309 } else if (l >= 0.5 && l < 1.0) {
12310 s = c / (2 * (1 - l));
12313 return [hcg[0], s * 100, l * 100];
12316 convert.hcg.hwb = function (hcg) {
12317 var c = hcg[1] / 100;
12318 var g = hcg[2] / 100;
12319 var v = c + g * (1.0 - c);
12320 return [hcg[0], (v - c) * 100, (1 - v) * 100];
12323 convert.hwb.hcg = function (hwb) {
12324 var w = hwb[1] / 100;
12325 var b = hwb[2] / 100;
12331 g = (v - c) / (1 - c);
12334 return [hwb[0], c * 100, g * 100];
12337 convert.apple.rgb = function (apple) {
12338 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
12341 convert.rgb.apple = function (rgb) {
12342 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
12345 convert.gray.rgb = function (args) {
12346 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
12349 convert.gray.hsl = convert.gray.hsv = function (args) {
12350 return [0, 0, args[0]];
12353 convert.gray.hwb = function (gray) {
12354 return [0, 100, gray[0]];
12357 convert.gray.cmyk = function (gray) {
12358 return [0, 0, 0, gray[0]];
12361 convert.gray.lab = function (gray) {
12362 return [gray[0], 0, 0];
12365 convert.gray.hex = function (gray) {
12366 var val = Math.round(gray[0] / 100 * 255) & 0xFF;
12367 var integer = (val << 16) + (val << 8) + val;
12368 var string = integer.toString(16).toUpperCase();
12369 return '000000'.substring(string.length) + string;
12372 convert.rgb.gray = function (rgb) {
12373 var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
12374 return [val / 255 * 100];
12379 this function routes a model to all other models.
12381 all functions that are routed have a property `.conversion` attached
12382 to the returned synthetic function. This property is an array
12383 of strings, each with the steps in between the 'from' and 'to'
12384 color models (inclusive).
12386 conversions that are not possible simply are not included.
12389 function buildGraph$2() {
12390 var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
12392 var models = Object.keys(conversions$2);
12394 for (var len = models.length, i = 0; i < len; i++) {
12395 graph[models[i]] = {
12396 // http://jsperf.com/1-vs-infinity
12397 // micro-opt, but this is simple.
12404 } // https://en.wikipedia.org/wiki/Breadth-first_search
12407 function deriveBFS$2(fromModel) {
12408 var graph = buildGraph$2();
12409 var queue = [fromModel]; // unshift -> queue -> pop
12411 graph[fromModel].distance = 0;
12413 while (queue.length) {
12414 var current = queue.pop();
12415 var adjacents = Object.keys(conversions$2[current]);
12417 for (var len = adjacents.length, i = 0; i < len; i++) {
12418 var adjacent = adjacents[i];
12419 var node = graph[adjacent];
12421 if (node.distance === -1) {
12422 node.distance = graph[current].distance + 1;
12423 node.parent = current;
12424 queue.unshift(adjacent);
12432 function link$2(from, to) {
12433 return function (args) {
12434 return to(from(args));
12438 function wrapConversion$2(toModel, graph) {
12439 var path = [graph[toModel].parent, toModel];
12440 var fn = conversions$2[graph[toModel].parent][toModel];
12441 var cur = graph[toModel].parent;
12443 while (graph[cur].parent) {
12444 path.unshift(graph[cur].parent);
12445 fn = link$2(conversions$2[graph[cur].parent][cur], fn);
12446 cur = graph[cur].parent;
12449 fn.conversion = path;
12453 var route$2 = function (fromModel) {
12454 var graph = deriveBFS$2(fromModel);
12455 var conversion = {};
12456 var models = Object.keys(graph);
12458 for (var len = models.length, i = 0; i < len; i++) {
12459 var toModel = models[i];
12460 var node = graph[toModel];
12462 if (node.parent === null) {
12463 // no possible conversion, or this node is the source model.
12467 conversion[toModel] = wrapConversion$2(toModel, graph);
12473 var convert$3 = {};
12474 var models$2 = Object.keys(conversions$2);
12476 function wrapRaw$2(fn) {
12477 var wrappedFn = function (args) {
12478 if (args === undefined || args === null) {
12482 if (arguments.length > 1) {
12483 args = Array.prototype.slice.call(arguments);
12487 }; // preserve .conversion property if there is one
12490 if ('conversion' in fn) {
12491 wrappedFn.conversion = fn.conversion;
12497 function wrapRounded$2(fn) {
12498 var wrappedFn = function (args) {
12499 if (args === undefined || args === null) {
12503 if (arguments.length > 1) {
12504 args = Array.prototype.slice.call(arguments);
12507 var result = fn(args); // we're assuming the result is an array here.
12508 // see notice in conversions.js; don't use box types
12509 // in conversion functions.
12511 if (typeof result === 'object') {
12512 for (var len = result.length, i = 0; i < len; i++) {
12513 result[i] = Math.round(result[i]);
12518 }; // preserve .conversion property if there is one
12521 if ('conversion' in fn) {
12522 wrappedFn.conversion = fn.conversion;
12528 models$2.forEach(function (fromModel) {
12529 convert$3[fromModel] = {};
12530 Object.defineProperty(convert$3[fromModel], 'channels', {
12531 value: conversions$2[fromModel].channels
12533 Object.defineProperty(convert$3[fromModel], 'labels', {
12534 value: conversions$2[fromModel].labels
12536 var routes = route$2(fromModel);
12537 var routeModels = Object.keys(routes);
12538 routeModels.forEach(function (toModel) {
12539 var fn = routes[toModel];
12540 convert$3[fromModel][toModel] = wrapRounded$2(fn);
12541 convert$3[fromModel][toModel].raw = wrapRaw$2(fn);
12544 var colorConvert$2 = convert$3;
12546 var ansiStyles$2 = createCommonjsModule(function (module) {
12548 const wrapAnsi16 = (fn, offset) => function () {
12549 const code = fn.apply(colorConvert$2, arguments);
12550 return `\u001B[${code + offset}m`;
12553 const wrapAnsi256 = (fn, offset) => function () {
12554 const code = fn.apply(colorConvert$2, arguments);
12555 return `\u001B[${38 + offset};5;${code}m`;
12558 const wrapAnsi16m = (fn, offset) => function () {
12559 const rgb = fn.apply(colorConvert$2, arguments);
12560 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
12563 function assembleStyles() {
12564 const codes = new Map();
12568 // 21 isn't widely supported and 22 does the same thing
12572 underline: [4, 24],
12575 strikethrough: [9, 29]
12588 redBright: [91, 39],
12589 greenBright: [92, 39],
12590 yellowBright: [93, 39],
12591 blueBright: [94, 39],
12592 magentaBright: [95, 39],
12593 cyanBright: [96, 39],
12594 whiteBright: [97, 39]
12600 bgYellow: [43, 49],
12602 bgMagenta: [45, 49],
12606 bgBlackBright: [100, 49],
12607 bgRedBright: [101, 49],
12608 bgGreenBright: [102, 49],
12609 bgYellowBright: [103, 49],
12610 bgBlueBright: [104, 49],
12611 bgMagentaBright: [105, 49],
12612 bgCyanBright: [106, 49],
12613 bgWhiteBright: [107, 49]
12617 styles.color.grey = styles.color.gray;
12619 for (const groupName of Object.keys(styles)) {
12620 const group = styles[groupName];
12622 for (const styleName of Object.keys(group)) {
12623 const style = group[styleName];
12624 styles[styleName] = {
12625 open: `\u001B[${style[0]}m`,
12626 close: `\u001B[${style[1]}m`
12628 group[styleName] = styles[styleName];
12629 codes.set(style[0], style[1]);
12632 Object.defineProperty(styles, groupName, {
12636 Object.defineProperty(styles, 'codes', {
12642 const ansi2ansi = n => n;
12644 const rgb2rgb = (r, g, b) => [r, g, b];
12646 styles.color.close = '\u001B[39m';
12647 styles.bgColor.close = '\u001B[49m';
12648 styles.color.ansi = {
12649 ansi: wrapAnsi16(ansi2ansi, 0)
12651 styles.color.ansi256 = {
12652 ansi256: wrapAnsi256(ansi2ansi, 0)
12654 styles.color.ansi16m = {
12655 rgb: wrapAnsi16m(rgb2rgb, 0)
12657 styles.bgColor.ansi = {
12658 ansi: wrapAnsi16(ansi2ansi, 10)
12660 styles.bgColor.ansi256 = {
12661 ansi256: wrapAnsi256(ansi2ansi, 10)
12663 styles.bgColor.ansi16m = {
12664 rgb: wrapAnsi16m(rgb2rgb, 10)
12667 for (let key of Object.keys(colorConvert$2)) {
12668 if (typeof colorConvert$2[key] !== 'object') {
12672 const suite = colorConvert$2[key];
12674 if (key === 'ansi16') {
12678 if ('ansi16' in suite) {
12679 styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
12680 styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
12683 if ('ansi256' in suite) {
12684 styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
12685 styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
12688 if ('rgb' in suite) {
12689 styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
12690 styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
12695 } // Make the export immutable
12698 Object.defineProperty(module, 'exports', {
12700 get: assembleStyles
12704 const env$2 = process.env;
12707 if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
12708 forceColor$2 = false;
12709 } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
12710 forceColor$2 = true;
12713 if ('FORCE_COLOR' in env$2) {
12714 forceColor$2 = env$2.FORCE_COLOR.length === 0 || parseInt(env$2.FORCE_COLOR, 10) !== 0;
12717 function translateLevel$2(level) {
12725 has256: level >= 2,
12730 function supportsColor$2(stream) {
12731 if (forceColor$2 === false) {
12735 if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
12739 if (hasFlag('color=256')) {
12743 if (stream && !stream.isTTY && forceColor$2 !== true) {
12747 const min = forceColor$2 ? 1 : 0;
12749 if (process.platform === 'win32') {
12750 // Node.js 7.5.0 is the first version of Node.js to include a patch to
12751 // libuv that enables 256 color output on Windows. Anything earlier and it
12752 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
12753 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
12754 // release that supports 256 colors. Windows 10 build 14931 is the first release
12755 // that supports 16m/TrueColor.
12756 const osRelease = os__default['default'].release().split('.');
12758 if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
12759 return Number(osRelease[2]) >= 14931 ? 3 : 2;
12765 if ('CI' in env$2) {
12766 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') {
12773 if ('TEAMCITY_VERSION' in env$2) {
12774 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0;
12777 if (env$2.COLORTERM === 'truecolor') {
12781 if ('TERM_PROGRAM' in env$2) {
12782 const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
12784 switch (env$2.TERM_PROGRAM) {
12786 return version >= 3 ? 3 : 2;
12788 case 'Apple_Terminal':
12794 if (/-256(color)?$/i.test(env$2.TERM)) {
12798 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) {
12802 if ('COLORTERM' in env$2) {
12806 if (env$2.TERM === 'dumb') {
12813 function getSupportLevel$2(stream) {
12814 const level = supportsColor$2(stream);
12815 return translateLevel$2(level);
12818 var supportsColor_1$2 = {
12819 supportsColor: getSupportLevel$2,
12820 stdout: getSupportLevel$2(process.stdout),
12821 stderr: getSupportLevel$2(process.stderr)
12824 const TEMPLATE_REGEX$2 = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
12825 const STYLE_REGEX$2 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
12826 const STRING_REGEX$2 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
12827 const ESCAPE_REGEX$2 = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
12828 const ESCAPES$2 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
12830 function unescape$2(c) {
12831 if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
12832 return String.fromCharCode(parseInt(c.slice(1), 16));
12835 return ESCAPES$2.get(c) || c;
12838 function parseArguments$2(name, args) {
12839 const results = [];
12840 const chunks = args.trim().split(/\s*,\s*/g);
12843 for (const chunk of chunks) {
12844 if (!isNaN(chunk)) {
12845 results.push(Number(chunk));
12846 } else if (matches = chunk.match(STRING_REGEX$2)) {
12847 results.push(matches[2].replace(ESCAPE_REGEX$2, (m, escape, chr) => escape ? unescape$2(escape) : chr));
12849 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
12856 function parseStyle$2(style) {
12857 STYLE_REGEX$2.lastIndex = 0;
12858 const results = [];
12861 while ((matches = STYLE_REGEX$2.exec(style)) !== null) {
12862 const name = matches[1];
12865 const args = parseArguments$2(name, matches[2]);
12866 results.push([name].concat(args));
12868 results.push([name]);
12875 function buildStyle$2(chalk, styles) {
12876 const enabled = {};
12878 for (const layer of styles) {
12879 for (const style of layer.styles) {
12880 enabled[style[0]] = layer.inverse ? null : style.slice(1);
12884 let current = chalk;
12886 for (const styleName of Object.keys(enabled)) {
12887 if (Array.isArray(enabled[styleName])) {
12888 if (!(styleName in current)) {
12889 throw new Error(`Unknown Chalk style: ${styleName}`);
12892 if (enabled[styleName].length > 0) {
12893 current = current[styleName].apply(current, enabled[styleName]);
12895 current = current[styleName];
12903 var templates$2 = (chalk, tmp) => {
12906 let chunk = []; // eslint-disable-next-line max-params
12908 tmp.replace(TEMPLATE_REGEX$2, (m, escapeChar, inverse, style, close, chr) => {
12910 chunk.push(unescape$2(escapeChar));
12911 } else if (style) {
12912 const str = chunk.join('');
12914 chunks.push(styles.length === 0 ? str : buildStyle$2(chalk, styles)(str));
12917 styles: parseStyle$2(style)
12919 } else if (close) {
12920 if (styles.length === 0) {
12921 throw new Error('Found extraneous } in Chalk template literal');
12924 chunks.push(buildStyle$2(chalk, styles)(chunk.join('')));
12931 chunks.push(chunk.join(''));
12933 if (styles.length > 0) {
12934 const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
12935 throw new Error(errMsg);
12938 return chunks.join('');
12941 var chalk$2 = createCommonjsModule(function (module) {
12943 const stdoutColor = supportsColor_1$2.stdout;
12944 const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
12946 const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
12948 const skipModels = new Set(['gray']);
12949 const styles = Object.create(null);
12951 function applyOptions(obj, options) {
12952 options = options || {}; // Detect level if not set manually
12954 const scLevel = stdoutColor ? stdoutColor.level : 0;
12955 obj.level = options.level === undefined ? scLevel : options.level;
12956 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
12959 function Chalk(options) {
12960 // We check for this.template here since calling `chalk.constructor()`
12961 // by itself will have a `this` of a previously constructed chalk object
12962 if (!this || !(this instanceof Chalk) || this.template) {
12964 applyOptions(chalk, options);
12966 chalk.template = function () {
12967 const args = [].slice.call(arguments);
12968 return chalkTag.apply(null, [chalk.template].concat(args));
12971 Object.setPrototypeOf(chalk, Chalk.prototype);
12972 Object.setPrototypeOf(chalk.template, chalk);
12973 chalk.template.constructor = Chalk;
12974 return chalk.template;
12977 applyOptions(this, options);
12978 } // Use bright blue on Windows as the normal blue color is illegible
12981 if (isSimpleWindowsTerm) {
12982 ansiStyles$2.blue.open = '\u001B[94m';
12985 for (const key of Object.keys(ansiStyles$2)) {
12986 ansiStyles$2[key].closeRe = new RegExp(escapeStringRegexp$2(ansiStyles$2[key].close), 'g');
12989 const codes = ansiStyles$2[key];
12990 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
12998 return build.call(this, this._styles || [], true, 'visible');
13002 ansiStyles$2.color.closeRe = new RegExp(escapeStringRegexp$2(ansiStyles$2.color.close), 'g');
13004 for (const model of Object.keys(ansiStyles$2.color.ansi)) {
13005 if (skipModels.has(model)) {
13011 const level = this.level;
13012 return function () {
13013 const open = ansiStyles$2.color[levelMapping[level]][model].apply(null, arguments);
13016 close: ansiStyles$2.color.close,
13017 closeRe: ansiStyles$2.color.closeRe
13019 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
13026 ansiStyles$2.bgColor.closeRe = new RegExp(escapeStringRegexp$2(ansiStyles$2.bgColor.close), 'g');
13028 for (const model of Object.keys(ansiStyles$2.bgColor.ansi)) {
13029 if (skipModels.has(model)) {
13033 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
13034 styles[bgModel] = {
13036 const level = this.level;
13037 return function () {
13038 const open = ansiStyles$2.bgColor[levelMapping[level]][model].apply(null, arguments);
13041 close: ansiStyles$2.bgColor.close,
13042 closeRe: ansiStyles$2.bgColor.closeRe
13044 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
13051 const proto = Object.defineProperties(() => {}, styles);
13053 function build(_styles, _empty, key) {
13054 const builder = function () {
13055 return applyStyle.apply(builder, arguments);
13058 builder._styles = _styles;
13059 builder._empty = _empty;
13061 Object.defineProperty(builder, 'level', {
13069 self.level = level;
13073 Object.defineProperty(builder, 'enabled', {
13077 return self.enabled;
13081 self.enabled = enabled;
13084 }); // See below for fix regarding invisible grey/dim combination on Windows
13086 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
13087 // no way to create a function with a different prototype
13089 builder.__proto__ = proto; // eslint-disable-line no-proto
13094 function applyStyle() {
13095 // Support varags, but simply cast to string in case there's only one arg
13096 const args = arguments;
13097 const argsLen = args.length;
13098 let str = String(arguments[0]);
13100 if (argsLen === 0) {
13105 // Don't slice `arguments`, it prevents V8 optimizations
13106 for (let a = 1; a < argsLen; a++) {
13107 str += ' ' + args[a];
13111 if (!this.enabled || this.level <= 0 || !str) {
13112 return this._empty ? '' : str;
13113 } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
13114 // see https://github.com/chalk/chalk/issues/58
13115 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
13118 const originalDim = ansiStyles$2.dim.open;
13120 if (isSimpleWindowsTerm && this.hasGrey) {
13121 ansiStyles$2.dim.open = '';
13124 for (const code of this._styles.slice().reverse()) {
13125 // Replace any instances already present with a re-opening code
13126 // otherwise only the part of the string until said closing code
13127 // will be colored, and the rest will simply be 'plain'.
13128 str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
13129 // after next line to fix a bleed issue on macOS
13130 // https://github.com/chalk/chalk/pull/92
13132 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
13133 } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
13136 ansiStyles$2.dim.open = originalDim;
13140 function chalkTag(chalk, strings) {
13141 if (!Array.isArray(strings)) {
13142 // If chalk() was called by itself or with a string,
13143 // return the string itself as a string.
13144 return [].slice.call(arguments, 1).join(' ');
13147 const args = [].slice.call(arguments, 2);
13148 const parts = [strings.raw[0]];
13150 for (let i = 1; i < strings.length; i++) {
13151 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
13152 parts.push(String(strings.raw[i]));
13155 return templates$2(chalk, parts.join(''));
13158 Object.defineProperties(Chalk.prototype, styles);
13159 module.exports = Chalk(); // eslint-disable-line new-cap
13161 module.exports.supportsColor = stdoutColor;
13162 module.exports.default = module.exports; // For TypeScript
13165 var lib$3 = createCommonjsModule(function (module, exports) {
13167 Object.defineProperty(exports, "__esModule", {
13170 exports.shouldHighlight = shouldHighlight;
13171 exports.getChalk = getChalk;
13172 exports.default = highlight;
13174 var _jsTokens = _interopRequireWildcard(jsTokens);
13176 var _chalk = _interopRequireDefault(chalk$2);
13178 function _interopRequireDefault(obj) {
13179 return obj && obj.__esModule ? obj : {
13184 function _getRequireWildcardCache() {
13185 if (typeof WeakMap !== "function") return null;
13186 var cache = new WeakMap();
13188 _getRequireWildcardCache = function () {
13195 function _interopRequireWildcard(obj) {
13196 if (obj && obj.__esModule) {
13200 if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
13206 var cache = _getRequireWildcardCache();
13208 if (cache && cache.has(obj)) {
13209 return cache.get(obj);
13213 var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
13215 for (var key in obj) {
13216 if (Object.prototype.hasOwnProperty.call(obj, key)) {
13217 var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
13219 if (desc && (desc.get || desc.set)) {
13220 Object.defineProperty(newObj, key, desc);
13222 newObj[key] = obj[key];
13227 newObj.default = obj;
13230 cache.set(obj, newObj);
13236 function getDefs(chalk) {
13238 keyword: chalk.cyan,
13239 capitalized: chalk.yellow,
13240 jsx_tag: chalk.yellow,
13241 punctuator: chalk.yellow,
13242 number: chalk.magenta,
13243 string: chalk.green,
13244 regex: chalk.magenta,
13245 comment: chalk.grey,
13246 invalid: chalk.white.bgRed.bold
13250 const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
13251 const JSX_TAG = /^[a-z][\w-]*$/i;
13252 const BRACKET = /^[()[\]{}]$/;
13254 function getTokenType(match) {
13255 const [offset, text] = match.slice(-2);
13256 const token = (0, _jsTokens.matchToToken)(match);
13258 if (token.type === "name") {
13259 if ((0, lib$2.isKeyword)(token.value) || (0, lib$2.isReservedWord)(token.value)) {
13263 if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
13267 if (token.value[0] !== token.value[0].toLowerCase()) {
13268 return "capitalized";
13272 if (token.type === "punctuator" && BRACKET.test(token.value)) {
13276 if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
13277 return "punctuator";
13283 function highlightTokens(defs, text) {
13284 return text.replace(_jsTokens.default, function (...args) {
13285 const type = getTokenType(args);
13286 const colorize = defs[type];
13289 return args[0].split(NEWLINE).map(str => colorize(str)).join("\n");
13296 function shouldHighlight(options) {
13297 return _chalk.default.supportsColor || options.forceColor;
13300 function getChalk(options) {
13301 let chalk = _chalk.default;
13303 if (options.forceColor) {
13304 chalk = new _chalk.default.constructor({
13313 function highlight(code, options = {}) {
13314 if (shouldHighlight(options)) {
13315 const chalk = getChalk(options);
13316 const defs = getDefs(chalk);
13317 return highlightTokens(defs, code);
13324 var lib$4 = createCommonjsModule(function (module, exports) {
13326 Object.defineProperty(exports, "__esModule", {
13329 exports.codeFrameColumns = codeFrameColumns;
13330 exports.default = _default;
13332 var _highlight = _interopRequireWildcard(lib$3);
13334 function _getRequireWildcardCache() {
13335 if (typeof WeakMap !== "function") return null;
13336 var cache = new WeakMap();
13338 _getRequireWildcardCache = function () {
13345 function _interopRequireWildcard(obj) {
13346 if (obj && obj.__esModule) {
13350 if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
13356 var cache = _getRequireWildcardCache();
13358 if (cache && cache.has(obj)) {
13359 return cache.get(obj);
13363 var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
13365 for (var key in obj) {
13366 if (Object.prototype.hasOwnProperty.call(obj, key)) {
13367 var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
13369 if (desc && (desc.get || desc.set)) {
13370 Object.defineProperty(newObj, key, desc);
13372 newObj[key] = obj[key];
13377 newObj.default = obj;
13380 cache.set(obj, newObj);
13386 let deprecationWarningShown = false;
13388 function getDefs(chalk) {
13390 gutter: chalk.grey,
13391 marker: chalk.red.bold,
13392 message: chalk.red.bold
13396 const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
13398 function getMarkerLines(loc, source, opts) {
13399 const startLoc = Object.assign({
13403 const endLoc = Object.assign({}, startLoc, loc.end);
13408 const startLine = startLoc.line;
13409 const startColumn = startLoc.column;
13410 const endLine = endLoc.line;
13411 const endColumn = endLoc.column;
13412 let start = Math.max(startLine - (linesAbove + 1), 0);
13413 let end = Math.min(source.length, endLine + linesBelow);
13415 if (startLine === -1) {
13419 if (endLine === -1) {
13420 end = source.length;
13423 const lineDiff = endLine - startLine;
13424 const markerLines = {};
13427 for (let i = 0; i <= lineDiff; i++) {
13428 const lineNumber = i + startLine;
13430 if (!startColumn) {
13431 markerLines[lineNumber] = true;
13432 } else if (i === 0) {
13433 const sourceLength = source[lineNumber - 1].length;
13434 markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
13435 } else if (i === lineDiff) {
13436 markerLines[lineNumber] = [0, endColumn];
13438 const sourceLength = source[lineNumber - i].length;
13439 markerLines[lineNumber] = [0, sourceLength];
13443 if (startColumn === endColumn) {
13445 markerLines[startLine] = [startColumn, 0];
13447 markerLines[startLine] = true;
13450 markerLines[startLine] = [startColumn, endColumn - startColumn];
13461 function codeFrameColumns(rawLines, loc, opts = {}) {
13462 const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts);
13463 const chalk = (0, _highlight.getChalk)(opts);
13464 const defs = getDefs(chalk);
13466 const maybeHighlight = (chalkFn, string) => {
13467 return highlighted ? chalkFn(string) : string;
13470 const lines = rawLines.split(NEWLINE);
13475 } = getMarkerLines(loc, lines, opts);
13476 const hasColumns = loc.start && typeof loc.start.column === "number";
13477 const numberMaxWidth = String(end).length;
13478 const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines;
13479 let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => {
13480 const number = start + 1 + index;
13481 const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
13482 const gutter = ` ${paddedNumber} | `;
13483 const hasMarker = markerLines[number];
13484 const lastMarkerLine = !markerLines[number + 1];
13487 let markerLine = "";
13489 if (Array.isArray(hasMarker)) {
13490 const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
13491 const numberOfMarkers = hasMarker[1] || 1;
13492 markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
13494 if (lastMarkerLine && opts.message) {
13495 markerLine += " " + maybeHighlight(defs.message, opts.message);
13499 return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
13501 return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;
13505 if (opts.message && !hasColumns) {
13506 frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
13510 return chalk.reset(frame);
13516 function _default(rawLines, lineNumber, colNumber, opts = {}) {
13517 if (!deprecationWarningShown) {
13518 deprecationWarningShown = true;
13519 const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
13521 if (process.emitWarning) {
13522 process.emitWarning(message, "DeprecationWarning");
13524 const deprecationError = new Error(message);
13525 deprecationError.name = "DeprecationWarning";
13526 console.warn(new Error(message));
13530 colNumber = Math.max(colNumber, 0);
13537 return codeFrameColumns(rawLines, location, opts);
13542 ConfigError: ConfigError$1
13545 locStart: locStart$1,
13547 } = loc; // Use defineProperties()/getOwnPropertyDescriptor() to prevent
13548 // triggering the parsers getters.
13550 const ownNames = Object.getOwnPropertyNames;
13551 const ownDescriptor = Object.getOwnPropertyDescriptor;
13553 function getParsers(options) {
13554 const parsers = {};
13556 for (const plugin of options.plugins) {
13557 // TODO: test this with plugins
13559 /* istanbul ignore next */
13560 if (!plugin.parsers) {
13564 for (const name of ownNames(plugin.parsers)) {
13565 Object.defineProperty(parsers, name, ownDescriptor(plugin.parsers, name));
13572 function resolveParser(opts, parsers) {
13573 parsers = parsers || getParsers(opts);
13575 if (typeof opts.parser === "function") {
13576 // Custom parser API always works with JavaScript.
13578 parse: opts.parser,
13579 astFormat: "estree",
13580 locStart: locStart$1,
13585 if (typeof opts.parser === "string") {
13586 if (Object.prototype.hasOwnProperty.call(parsers, opts.parser)) {
13587 return parsers[opts.parser];
13592 parse: require(path__default['default'].resolve(process.cwd(), opts.parser)),
13593 astFormat: "estree",
13594 locStart: locStart$1,
13598 /* istanbul ignore next */
13599 throw new ConfigError$1(`Couldn't resolve parser "${opts.parser}"`);
13604 function parse(text, opts) {
13605 const parsers = getParsers(opts); // Create a new object {parserName: parseFn}. Uses defineProperty() to only call
13606 // the parsers getters when actually calling the parser `parse` function.
13608 const parsersForCustomParserApi = Object.keys(parsers).reduce((object, parserName) => Object.defineProperty(object, parserName, {
13612 return parsers[parserName].parse;
13616 const parser = resolveParser(opts, parsers);
13619 if (parser.preprocess) {
13620 text = parser.preprocess(text, opts);
13625 ast: parser.parse(text, parsersForCustomParserApi, opts)
13636 error.codeFrame = codeFrameColumns(text, loc, {
13637 highlightCode: true
13639 error.message += "\n" + error.codeFrame;
13642 /* istanbul ignore next */
13655 UndefinedParserError: UndefinedParserError$1
13658 getSupportInfo: getSupportInfo$2
13661 resolveParser: resolveParser$1
13663 const hiddenDefaults = {
13664 astFormat: "estree",
13666 originalText: undefined,
13669 }; // Copy options and fill in default values.
13671 function normalize$1(options, opts) {
13673 const rawOptions = Object.assign({}, options);
13674 const supportOptions = getSupportInfo$2({
13675 plugins: options.plugins,
13676 showUnreleased: true,
13677 showDeprecated: true
13679 const defaults = Object.assign({}, hiddenDefaults, fromPairs_1(supportOptions.filter(optionInfo => optionInfo.default !== undefined).map(option => [option.name, option.default])));
13681 if (!rawOptions.parser) {
13682 if (!rawOptions.filepath) {
13683 const logger = opts.logger || console;
13684 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.");
13685 rawOptions.parser = "babel";
13687 rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins);
13689 if (!rawOptions.parser) {
13690 throw new UndefinedParserError$1(`No parser could be inferred for file: ${rawOptions.filepath}`);
13695 const parser = resolveParser$1(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(x => x.name === "parser")], {
13699 rawOptions.astFormat = parser.astFormat;
13700 rawOptions.locEnd = parser.locEnd;
13701 rawOptions.locStart = parser.locStart;
13702 const plugin = getPlugin(rawOptions);
13703 rawOptions.printer = plugin.printers[rawOptions.astFormat];
13704 const pluginDefaults = supportOptions.filter(optionInfo => optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name] !== undefined).reduce((reduced, optionInfo) => Object.assign(reduced, {
13705 [optionInfo.name]: optionInfo.pluginDefaults[plugin.name]
13707 const mixedDefaults = Object.assign({}, defaults, pluginDefaults);
13708 Object.keys(mixedDefaults).forEach(k => {
13709 if (rawOptions[k] == null) {
13710 rawOptions[k] = mixedDefaults[k];
13714 if (rawOptions.parser === "json") {
13715 rawOptions.trailingComma = "none";
13718 return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({
13719 passThrough: Object.keys(hiddenDefaults)
13723 function getPlugin(options) {
13726 } = options; // TODO: test this with plugins
13728 /* istanbul ignore next */
13731 throw new Error("getPlugin() requires astFormat to be set");
13734 const printerPlugin = options.plugins.find(plugin => plugin.printers && plugin.printers[astFormat]); // TODO: test this with plugins
13736 /* istanbul ignore next */
13738 if (!printerPlugin) {
13739 throw new Error(`Couldn't find plugin for AST format "${astFormat}"`);
13742 return printerPlugin;
13745 function getInterpreter(filepath) {
13746 /* istanbul ignore next */
13747 if (typeof filepath !== "string") {
13754 fd = fs__default['default'].openSync(filepath, "r");
13756 // istanbul ignore next
13761 const liner = new readlines(fd);
13762 const firstLine = liner.next().toString("utf8"); // #!/bin/env node, #!/usr/bin/env node
13764 const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/);
13768 } // #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node
13771 const m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/);
13779 // There are some weird cases where paths are missing, causing Jest
13780 // failures. It's unclear what these correspond to in the real world.
13782 /* istanbul ignore next */
13786 // There are some weird cases where paths are missing, causing Jest
13787 // failures. It's unclear what these correspond to in the real world.
13788 fs__default['default'].closeSync(fd);
13789 } catch (err) {// nop
13794 function inferParser(filepath, plugins) {
13795 const filename = path__default['default'].basename(filepath).toLowerCase();
13796 const languages = getSupportInfo$2({
13798 }).languages.filter(language => language.since !== null); // If the file has no extension, we can try to infer the language from the
13799 // interpreter in the shebang line, if any; but since this requires FS access,
13802 let language = languages.find(language => language.extensions && language.extensions.some(extension => filename.endsWith(extension)) || language.filenames && language.filenames.some(name => name.toLowerCase() === filename));
13804 if (!language && !filename.includes(".")) {
13805 const interpreter = getInterpreter(filepath);
13806 language = languages.find(language => language.interpreters && language.interpreters.includes(interpreter));
13809 return language && language.parsers[0];
13813 normalize: normalize$1,
13818 function massageAST(ast, options, parent) {
13819 if (Array.isArray(ast)) {
13820 return ast.map(e => massageAST(e, options, parent)).filter(Boolean);
13823 if (!ast || typeof ast !== "object") {
13827 const cleanFunction = options.printer.massageAstNode;
13828 let ignoredProperties;
13830 if (cleanFunction && cleanFunction.ignoredProperties) {
13831 ignoredProperties = cleanFunction.ignoredProperties;
13833 ignoredProperties = new Set();
13838 for (const key of Object.keys(ast)) {
13839 if (!ignoredProperties.has(key) && typeof ast[key] !== "function") {
13840 newObj[key] = massageAST(ast[key], options, ast);
13844 if (cleanFunction) {
13845 const result = cleanFunction(ast, newObj, parent);
13847 if (result === null) {
13859 var massageAst = massageAST;
13861 /** @type {import("assert")} */
13868 hardline: hardline$1,
13869 breakParent: breakParent$1,
13871 lineSuffix: lineSuffix$1,
13877 hasNewline: hasNewline$1,
13878 skipNewline: skipNewline$1,
13879 skipSpaces: skipSpaces$1,
13880 isPreviousLineEmpty: isPreviousLineEmpty$1,
13881 addLeadingComment: addLeadingComment$1,
13882 addDanglingComment: addDanglingComment$1,
13883 addTrailingComment: addTrailingComment$1
13885 const childNodesCacheKey = Symbol("child-nodes");
13887 function getSortedChildNodes(node, options, resultArray) {
13899 if (printer.canAttachComment && printer.canAttachComment(node)) {
13900 // This reverse insertion sort almost always takes constant
13901 // time because we almost always (maybe always?) append the
13902 // nodes in order anyway.
13905 for (i = resultArray.length - 1; i >= 0; --i) {
13906 if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) {
13911 resultArray.splice(i + 1, 0, node);
13914 } else if (node[childNodesCacheKey]) {
13915 return node[childNodesCacheKey];
13918 const childNodes = printer.getCommentChildNodes && printer.getCommentChildNodes(node, options) || typeof node === "object" && Object.keys(node).filter(n => n !== "enclosingNode" && n !== "precedingNode" && n !== "followingNode" && n !== "tokens" && n !== "comments").map(n => node[n]);
13924 if (!resultArray) {
13925 Object.defineProperty(node, childNodesCacheKey, {
13926 value: resultArray = [],
13931 childNodes.forEach(childNode => {
13932 getSortedChildNodes(childNode, options, resultArray);
13934 return resultArray;
13935 } // As efficiently as possible, decorate the comment object with
13936 // .precedingNode, .enclosingNode, and/or .followingNode properties, at
13937 // least one of which is guaranteed to be defined.
13940 function decorateComment(node, comment, options) {
13945 const commentStart = locStart(comment);
13946 const commentEnd = locEnd(comment);
13947 const childNodes = getSortedChildNodes(node, options);
13949 let followingNode; // Time to dust off the old binary search robes and wizard hat.
13952 let right = childNodes.length;
13954 while (left < right) {
13955 const middle = left + right >> 1;
13956 const child = childNodes[middle];
13957 const start = locStart(child);
13958 const end = locEnd(child);
13960 if (start <= commentStart && commentEnd <= end) {
13961 // The comment is completely contained by this child node.
13962 comment.enclosingNode = child;
13963 decorateComment(child, comment, options);
13964 return; // Abandon the binary search at this level.
13967 if (start <= commentStart) {
13968 // This child node falls completely before the comment.
13969 // Because we will never consider this node or any nodes
13970 // before it again, this node must be the closest preceding
13971 // node we have encountered so far.
13972 precedingNode = child;
13977 if (commentEnd <= start) {
13978 // This child node falls completely after the comment.
13979 // Because we will never consider this node or any nodes after
13980 // it again, this node must be the closest following node we
13981 // have encountered so far.
13982 followingNode = child;
13986 /* istanbul ignore next */
13989 throw new Error("Comment location overlaps with node location");
13990 } // We don't want comments inside of different expressions inside of the same
13991 // template literal to move to another expression.
13994 if (comment.enclosingNode && comment.enclosingNode.type === "TemplateLiteral") {
13997 } = comment.enclosingNode;
13998 const commentIndex = findExpressionIndexForComment(quasis, comment, options);
14000 if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) {
14001 precedingNode = null;
14004 if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) {
14005 followingNode = null;
14009 if (precedingNode) {
14010 comment.precedingNode = precedingNode;
14013 if (followingNode) {
14014 comment.followingNode = followingNode;
14018 function attach(comments, ast, text, options) {
14019 if (!Array.isArray(comments)) {
14023 const tiesToBreak = [];
14028 comments.forEach((comment, i) => {
14029 if (options.parser === "json" || options.parser === "json5" || options.parser === "__js_expression" || options.parser === "__vue_expression") {
14030 if (locStart(comment) - locStart(ast) <= 0) {
14031 addLeadingComment$1(ast, comment);
14035 if (locEnd(comment) - locEnd(ast) >= 0) {
14036 addTrailingComment$1(ast, comment);
14041 decorateComment(ast, comment, options);
14047 const pluginHandleOwnLineComment = options.printer.handleComments && options.printer.handleComments.ownLine ? options.printer.handleComments.ownLine : () => false;
14048 const pluginHandleEndOfLineComment = options.printer.handleComments && options.printer.handleComments.endOfLine ? options.printer.handleComments.endOfLine : () => false;
14049 const pluginHandleRemainingComment = options.printer.handleComments && options.printer.handleComments.remaining ? options.printer.handleComments.remaining : () => false;
14050 const isLastComment = comments.length - 1 === i;
14052 if (hasNewline$1(text, locStart(comment), {
14055 // If a comment exists on its own line, prefer a leading comment.
14056 // We also need to check if it's the first line of the file.
14057 if (pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)) ; else if (followingNode) {
14058 // Always a leading comment.
14059 addLeadingComment$1(followingNode, comment);
14060 } else if (precedingNode) {
14061 addTrailingComment$1(precedingNode, comment);
14062 } else if (enclosingNode) {
14063 addDanglingComment$1(enclosingNode, comment);
14065 // There are no nodes, let's attach it to the root of the ast
14067 /* istanbul ignore next */
14068 addDanglingComment$1(ast, comment);
14070 } else if (hasNewline$1(text, locEnd(comment))) {
14071 if (pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode) {
14072 // There is content before this comment on the same line, but
14073 // none after it, so prefer a trailing comment of the previous node.
14074 addTrailingComment$1(precedingNode, comment);
14075 } else if (followingNode) {
14076 addLeadingComment$1(followingNode, comment);
14077 } else if (enclosingNode) {
14078 addDanglingComment$1(enclosingNode, comment);
14080 // There are no nodes, let's attach it to the root of the ast
14082 /* istanbul ignore next */
14083 addDanglingComment$1(ast, comment);
14086 if (pluginHandleRemainingComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode && followingNode) {
14087 // Otherwise, text exists both before and after the comment on
14088 // the same line. If there is both a preceding and following
14089 // node, use a tie-breaking algorithm to determine if it should
14090 // be attached to the next or previous node. In the last case,
14091 // simply attach the right node;
14092 const tieCount = tiesToBreak.length;
14094 if (tieCount > 0) {
14095 const lastTie = tiesToBreak[tieCount - 1];
14097 if (lastTie.followingNode !== comment.followingNode) {
14098 breakTies(tiesToBreak, text, options);
14102 tiesToBreak.push(comment);
14103 } else if (precedingNode) {
14104 addTrailingComment$1(precedingNode, comment);
14105 } else if (followingNode) {
14106 addLeadingComment$1(followingNode, comment);
14107 } else if (enclosingNode) {
14108 addDanglingComment$1(enclosingNode, comment);
14110 // There are no nodes, let's attach it to the root of the ast
14112 /* istanbul ignore next */
14113 addDanglingComment$1(ast, comment);
14117 breakTies(tiesToBreak, text, options);
14118 comments.forEach(comment => {
14119 // These node references were useful for breaking ties, but we
14120 // don't need them anymore, and they create cycles in the AST that
14121 // may lead to infinite recursion if we don't delete them here.
14122 delete comment.precedingNode;
14123 delete comment.enclosingNode;
14124 delete comment.followingNode;
14128 function breakTies(tiesToBreak, text, options) {
14129 const tieCount = tiesToBreak.length;
14131 if (tieCount === 0) {
14139 } = tiesToBreak[0];
14140 const gapRegExp = options.printer.getGapRegex && options.printer.getGapRegex(enclosingNode) || /^[\s(]*$/;
14141 let gapEndPos = options.locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps
14142 // between the tied comments. In order to qualify as leading, a
14143 // comment must be separated from followingNode by an unbroken series of
14144 // gaps (or other comments). Gaps should only contain whitespace or open
14147 let indexOfFirstLeadingComment;
14149 for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) {
14150 const comment = tiesToBreak[indexOfFirstLeadingComment - 1];
14151 assert__default['default'].strictEqual(comment.precedingNode, precedingNode);
14152 assert__default['default'].strictEqual(comment.followingNode, followingNode);
14153 const gap = text.slice(options.locEnd(comment), gapEndPos);
14155 if (gapRegExp.test(gap)) {
14156 gapEndPos = options.locStart(comment);
14158 // The gap string contained something other than whitespace or open
14164 tiesToBreak.forEach((comment, i) => {
14165 if (i < indexOfFirstLeadingComment) {
14166 addTrailingComment$1(precedingNode, comment);
14168 addLeadingComment$1(followingNode, comment);
14172 for (const node of [precedingNode, followingNode]) {
14173 if (node.comments && node.comments.length > 1) {
14174 node.comments.sort((a, b) => options.locStart(a) - options.locStart(b));
14178 tiesToBreak.length = 0;
14181 function printComment(commentPath, options) {
14182 const comment = commentPath.getValue();
14183 comment.printed = true;
14184 return options.printer.printComment(commentPath, options);
14187 function findExpressionIndexForComment(quasis, comment, options) {
14188 const startPos = options.locStart(comment) - 1;
14190 for (let i = 1; i < quasis.length; ++i) {
14191 if (startPos < options.locStart(quasis[i])) {
14194 } // We haven't found it, it probably means that some of the locations are off.
14195 // Let's just return the first one.
14197 /* istanbul ignore next */
14203 function printLeadingComment(commentPath, options) {
14204 const comment = commentPath.getValue();
14205 const contents = printComment(commentPath, options);
14206 /* istanbul ignore next */
14212 const isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // Leading block comments should see if they need to stay on the
14213 // same line or not.
14216 const lineBreak = hasNewline$1(options.originalText, options.locEnd(comment)) ? hasNewline$1(options.originalText, options.locStart(comment), {
14218 }) ? hardline$1 : line$1 : " ";
14219 return concat$3([contents, lineBreak]);
14222 return concat$3([contents, hardline$1]);
14225 function printTrailingComment(commentPath, options) {
14226 const comment = commentPath.getValue();
14227 const contents = printComment(commentPath, options);
14228 /* istanbul ignore next */
14239 const isBlock = printer.isBlockComment && printer.isBlockComment(comment);
14241 if (hasNewline$1(originalText, locStart(comment), {
14244 // This allows comments at the end of nested structures:
14250 // Those kinds of comments are almost always leading comments, but
14251 // here it doesn't go "outside" the block and turns it into a
14252 // trailing comment for `2`. We can simulate the above by checking
14253 // if this a comment on its own line; normal trailing comments are
14254 // always at the end of another expression.
14255 const isLineBeforeEmpty = isPreviousLineEmpty$1(originalText, comment, locStart);
14256 return lineSuffix$1(concat$3([hardline$1, isLineBeforeEmpty ? hardline$1 : "", contents]));
14259 let printed = concat$3([" ", contents]); // Trailing block comments never need a newline
14262 printed = concat$3([lineSuffix$1(printed), breakParent$1]);
14268 function printDanglingComments(path, options, sameIndent, filter) {
14270 const node = path.getValue();
14272 if (!node || !node.comments) {
14276 path.each(commentPath => {
14277 const comment = commentPath.getValue();
14279 if (comment && !comment.leading && !comment.trailing && (!filter || filter(comment))) {
14280 parts.push(printComment(commentPath, options));
14284 if (parts.length === 0) {
14289 return join$1(hardline$1, parts);
14292 return indent$1(concat$3([hardline$1, join$1(hardline$1, parts)]));
14295 function prependCursorPlaceholder(path, options, printed) {
14296 if (path.getNode() === options.cursorNode && path.getValue()) {
14297 return concat$3([cursor$2, printed, cursor$2]);
14303 function printComments(path, print, options, needsSemi) {
14304 const value = path.getValue();
14305 const printed = print(path);
14306 const comments = value && value.comments;
14308 if (!comments || comments.length === 0) {
14309 return prependCursorPlaceholder(path, options, printed);
14312 const leadingParts = [];
14313 const trailingParts = [needsSemi ? ";" : "", printed];
14314 path.each(commentPath => {
14315 const comment = commentPath.getValue();
14322 const contents = printLeadingComment(commentPath, options);
14323 /* istanbul ignore next */
14329 leadingParts.push(contents);
14330 const text = options.originalText;
14331 const index = skipNewline$1(text, skipSpaces$1(text, options.locEnd(comment)));
14333 if (index !== false && hasNewline$1(text, index)) {
14334 leadingParts.push(hardline$1);
14336 } else if (trailing) {
14337 trailingParts.push(printTrailingComment(commentPath, options));
14340 return prependCursorPlaceholder(path, options, concat$3(leadingParts.concat(trailingParts)));
14343 function ensureAllCommentsPrinted(astComments) {
14344 if (!astComments) {
14348 astComments.forEach(comment => {
14349 if (!comment.printed) {
14350 throw new Error('Comment "' + comment.value.trim() + '" was not printed. Please report this error!');
14353 delete comment.printed;
14360 printDanglingComments,
14361 getSortedChildNodes,
14362 ensureAllCommentsPrinted
14365 function getNodeHelper(path, count) {
14366 const stackIndex = getNodeStackIndexHelper(path.stack, count);
14367 return stackIndex === -1 ? null : path.stack[stackIndex];
14370 function getNodeStackIndexHelper(stack, count) {
14371 for (let i = stack.length - 1; i >= 0; i -= 2) {
14372 const value = stack[i];
14374 if (value && !Array.isArray(value) && --count < 0) {
14383 constructor(value) {
14384 this.stack = [value];
14385 } // The name of the current property is always the penultimate element of
14386 // this.stack, and always a String.
14398 return stack[length - 2];
14399 } // Since the name is always a string, null is a safe sentinel value to
14400 // return if we do not know the name of the (root) value.
14402 /* istanbul ignore next */
14406 } // The value of the current property is always the final element of
14411 return getLast(this.stack);
14414 getNode(count = 0) {
14415 return getNodeHelper(this, count);
14418 getParentNode(count = 0) {
14419 return getNodeHelper(this, count + 1);
14420 } // Temporarily push properties named by string arguments given after the
14421 // callback function onto this.stack, then call the callback with a
14422 // reference to this (modified) FastPath object. Note that the stack will
14423 // be restored to its original state after the callback is finished, so it
14424 // is probably a mistake to retain a reference to the path.
14427 call(callback, ...names) {
14434 let value = getLast(stack);
14436 for (const name of names) {
14437 value = value[name];
14438 stack.push(name, value);
14441 const result = callback(this);
14442 stack.length = length;
14446 callParent(callback, count = 0) {
14447 const stackIndex = getNodeStackIndexHelper(this.stack, count + 1);
14448 const parentValues = this.stack.splice(stackIndex + 1);
14449 const result = callback(this);
14450 this.stack.push(...parentValues);
14452 } // Similar to FastPath.prototype.call, except that the value obtained by
14453 // accessing this.getValue()[name1][name2]... should be array. The
14454 // callback will be called with a reference to this path object for each
14455 // element of the array.
14458 each(callback, ...names) {
14465 let value = getLast(stack);
14467 for (const name of names) {
14468 value = value[name];
14469 stack.push(name, value);
14472 for (let i = 0; i < value.length; ++i) {
14473 stack.push(i, value[i]);
14478 stack.length = length;
14479 } // Similar to FastPath.prototype.each, except that the results of the
14480 // callback function invocations are stored in an array and returned at
14481 // the end of the iteration.
14484 map(callback, ...names) {
14486 this.each((path, index) => {
14487 result[index] = callback(path, index);
14493 * | ((node: any, name: string | null, number: number | null) => boolean)
14499 match(...predicates) {
14500 let stackPointer = this.stack.length - 1;
14502 let node = this.stack[stackPointer--];
14504 for (const predicate of predicates) {
14505 /* istanbul ignore next */
14506 if (node === undefined) {
14508 } // skip index/array
14513 if (typeof name === "number") {
14515 name = this.stack[stackPointer--];
14516 node = this.stack[stackPointer--];
14519 if (predicate && !predicate(node, name, number)) {
14523 name = this.stack[stackPointer--];
14524 node = this.stack[stackPointer--];
14532 var fastPath = FastPath;
14536 stripTrailingHardline: stripTrailingHardline$1
14540 normalize: normalize$2
14543 function printSubtree(path, print, options, printAstToDoc) {
14544 if (options.printer.embed && options.embeddedLanguageFormatting === "auto") {
14545 return options.printer.embed(path, print, (text, partialNextOptions, textToDocOptions) => textToDoc(text, partialNextOptions, options, printAstToDoc, textToDocOptions), options);
14549 function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc, // TODO: remove `stripTrailingHardline` in v3.0.0
14551 stripTrailingHardline: shouldStripTrailingHardline = false
14553 const nextOptions = normalize$2(Object.assign({}, parentOptions, partialNextOptions, {
14554 parentParser: parentOptions.parser,
14555 embeddedInHtml: !!(parentOptions.embeddedInHtml || parentOptions.parser === "html" || parentOptions.parser === "vue" || parentOptions.parser === "angular" || parentOptions.parser === "lwc"),
14560 const result = parser.parse(text, nextOptions);
14564 text = result.text;
14565 const astComments = ast.comments;
14566 delete ast.comments;
14567 comments.attach(astComments, ast, text, nextOptions);
14568 nextOptions[Symbol.for("comments")] = astComments || [];
14569 nextOptions[Symbol.for("tokens")] = ast.tokens || [];
14570 const doc = printAstToDoc(ast, nextOptions);
14571 comments.ensureAllCommentsPrinted(astComments);
14573 if (shouldStripTrailingHardline) {
14574 // TODO: move this to `stripTrailingHardline` function in `/src/document/doc-utils.js`
14575 if (typeof doc === "string") {
14576 return doc.replace(/(?:\r?\n)*$/, "");
14579 return stripTrailingHardline$1(doc, true);
14581 /* istanbul ignore next */
14587 var multiparser = {
14591 const doc = document;
14592 const docBuilders$1 = doc.builders;
14595 hardline: hardline$2,
14596 addAlignmentToDoc: addAlignmentToDoc$1
14598 const docUtils$1 = doc.utils;
14600 * Takes an abstract syntax tree (AST) and recursively converts it to a
14601 * document (series of printing primitives).
14603 * This is done by descending down the AST recursively. The recursion
14604 * involves two functions that call each other:
14606 * 1. printGenerically(), which is defined as an inner function here.
14607 * It basically takes care of node caching.
14608 * 2. callPluginPrintFunction(), which checks for some options, and
14609 * ultimately calls the print() function provided by the plugin.
14611 * The plugin function will call printGenerically() again for child nodes
14612 * of the current node, which will do its housekeeping, then call the
14613 * plugin function again, and so on.
14615 * All the while, these functions pass a "path" variable around, which
14616 * is a stack-like data structure (FastPath) that maintains the current
14617 * state of the recursion. It is called "path", because it represents
14618 * the path to the current node through the Abstract Syntax Tree.
14621 function printAstToDoc(ast, options, alignmentSize = 0) {
14626 if (printer.preprocess) {
14627 ast = printer.preprocess(ast, options);
14630 const cache = new Map();
14632 function printGenerically(path, args) {
14633 const node = path.getValue();
14634 const shouldCache = node && typeof node === "object" && args === undefined;
14636 if (shouldCache && cache.has(node)) {
14637 return cache.get(node);
14638 } // We let JSXElement print its comments itself because it adds () around
14639 // UnionTypeAnnotation has to align the child without the comments
14644 if (printer.willPrintOwnComments && printer.willPrintOwnComments(path, options)) {
14645 res = callPluginPrintFunction(path, options, printGenerically, args);
14647 // printComments will call the plugin print function and check for
14648 // comments to print
14649 res = comments.printComments(path, p => callPluginPrintFunction(p, options, printGenerically, args), options, args && args.needsSemi);
14653 cache.set(node, res);
14659 let doc = printGenerically(new fastPath(ast));
14661 if (alignmentSize > 0) {
14662 // Add a hardline to make the indents take effect
14663 // It should be removed in index.js format()
14664 doc = addAlignmentToDoc$1(concat$4([hardline$2, doc]), alignmentSize, options.tabWidth);
14667 docUtils$1.propagateBreaks(doc);
14671 function printPrettierIgnoredNode(node, options) {
14674 [Symbol.for("comments")]: comments,
14678 const start = locStart(node);
14679 const end = locEnd(node);
14681 for (const comment of comments) {
14682 if (locStart(comment) >= start && locEnd(comment) <= end) {
14683 comment.printed = true;
14687 return originalText.slice(start, end);
14690 function callPluginPrintFunction(path, options, printPath, args) {
14691 assert__default['default'].ok(path instanceof fastPath);
14692 const node = path.getValue();
14695 } = options; // Escape hatch
14697 if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path)) {
14698 return printPrettierIgnoredNode(node, options);
14703 // Potentially switch to a different parser
14704 const sub = multiparser.printSubtree(path, printPath, options, printAstToDoc);
14710 /* istanbul ignore if */
14711 if (process.env.PRETTIER_DEBUG) {
14713 } // Continue with current parser
14718 return printer.print(path, options, printPath, args);
14721 var astToDoc = printAstToDoc;
14723 function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) {
14724 let resultStartNode = startNodeAndParents.node;
14725 let resultEndNode = endNodeAndParents.node;
14727 if (resultStartNode === resultEndNode) {
14729 startNode: resultStartNode,
14730 endNode: resultEndNode
14734 for (const endParent of endNodeAndParents.parentNodes) {
14735 if (endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node)) {
14736 resultEndNode = endParent;
14742 for (const startParent of startNodeAndParents.parentNodes) {
14743 if (startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node)) {
14744 resultStartNode = startParent;
14751 startNode: resultStartNode,
14752 endNode: resultEndNode
14756 function findNodeAtOffset(node, offset, options, predicate, parentNodes = []) {
14757 if (offset < options.locStart(node) || offset > options.locEnd(node)) {
14761 for (const childNode of comments.getSortedChildNodes(node, options)) {
14762 const childResult = findNodeAtOffset(childNode, offset, options, predicate, [node, ...parentNodes]);
14765 return childResult;
14769 if (!predicate || predicate(node)) {
14775 } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5
14778 function isJsSourceElement(type) {
14779 return type === "Directive" || type === "TypeAlias" || type === "TSExportAssignment" || type.startsWith("Declare") || type.startsWith("TSDeclare") || type.endsWith("Statement") || type.endsWith("Declaration");
14782 const jsonSourceElements = new Set(["ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"]);
14783 const graphqlSourceElements = new Set(["OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition"]);
14785 function isSourceElement(opts, node) {
14786 /* istanbul ignore next */
14787 if (node == null) {
14791 switch (opts.parser) {
14799 return isJsSourceElement(node.type);
14802 return jsonSourceElements.has(node.type);
14805 return graphqlSourceElements.has(node.kind);
14808 return node.tag !== "root";
14814 function calculateRange(text, opts, ast) {
14815 // Contract the range so that it has non-whitespace characters at its endpoints.
14816 // This ensures we can format a range that doesn't end on a node.
14817 const rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd);
14818 const startNonWhitespace = Math.max(opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart);
14819 let endNonWhitespace;
14821 for (endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace) {
14822 if (/\S/.test(text[endNonWhitespace - 1])) {
14827 const startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace, opts, node => isSourceElement(opts, node));
14828 const endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace, opts, node => isSourceElement(opts, node));
14830 if (!startNodeAndParents || !endNodeAndParents) {
14840 } = findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts);
14842 rangeStart: Math.min(opts.locStart(startNode), opts.locStart(endNode)),
14843 rangeEnd: Math.max(opts.locEnd(startNode), opts.locEnd(endNode))
14854 printDocToString: printDocToString$1
14861 getAlignmentSize: getAlignmentSize$1
14864 guessEndOfLine: guessEndOfLine$1,
14865 convertEndOfLineToChars: convertEndOfLineToChars$2,
14866 countEndOfLineChars: countEndOfLineChars$1,
14867 normalizeEndOfLine: normalizeEndOfLine$1
14869 const normalizeOptions$1 = options$1.normalize;
14870 const BOM = "\uFEFF";
14871 const CURSOR = Symbol("cursor");
14873 function attachComments(text, ast, opts) {
14874 const astComments = ast.comments;
14877 delete ast.comments;
14878 comments.attach(astComments, ast, text, opts);
14881 opts[Symbol.for("comments")] = astComments || [];
14882 opts[Symbol.for("tokens")] = ast.tokens || [];
14883 opts.originalText = text;
14884 return astComments;
14887 function coreFormat(originalText, opts, addAlignmentSize) {
14888 if (!originalText || !originalText.trim().length) {
14895 addAlignmentSize = addAlignmentSize || 0;
14899 } = parser.parse(originalText, opts);
14901 if (opts.cursorOffset >= 0) {
14902 const nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts);
14904 if (nodeResult && nodeResult.node) {
14905 opts.cursorNode = nodeResult.node;
14909 const astComments = attachComments(text, ast, opts);
14910 const doc = astToDoc(ast, opts, addAlignmentSize);
14911 const result = printDocToString$1(doc, opts);
14912 comments.ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline
14914 if (addAlignmentSize > 0) {
14915 const trimmed = result.formatted.trim();
14917 if (result.cursorNodeStart !== undefined) {
14918 result.cursorNodeStart -= result.formatted.indexOf(trimmed);
14921 result.formatted = trimmed + convertEndOfLineToChars$2(opts.endOfLine);
14924 if (opts.cursorOffset >= 0) {
14925 let oldCursorNodeStart;
14926 let oldCursorNodeText;
14927 let cursorOffsetRelativeToOldCursorNode;
14928 let newCursorNodeStart;
14929 let newCursorNodeText;
14931 if (opts.cursorNode && result.cursorNodeText) {
14932 oldCursorNodeStart = opts.locStart(opts.cursorNode);
14933 oldCursorNodeText = text.slice(oldCursorNodeStart, opts.locEnd(opts.cursorNode));
14934 cursorOffsetRelativeToOldCursorNode = opts.cursorOffset - oldCursorNodeStart;
14935 newCursorNodeStart = result.cursorNodeStart;
14936 newCursorNodeText = result.cursorNodeText;
14938 oldCursorNodeStart = 0;
14939 oldCursorNodeText = text;
14940 cursorOffsetRelativeToOldCursorNode = opts.cursorOffset;
14941 newCursorNodeStart = 0;
14942 newCursorNodeText = result.formatted;
14945 if (oldCursorNodeText === newCursorNodeText) {
14947 formatted: result.formatted,
14948 cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode
14950 } // diff old and new cursor node texts, with a special cursor
14951 // symbol inserted to find out where it moves to
14954 const oldCursorNodeCharArray = oldCursorNodeText.split("");
14955 oldCursorNodeCharArray.splice(cursorOffsetRelativeToOldCursorNode, 0, CURSOR);
14956 const newCursorNodeCharArray = newCursorNodeText.split("");
14957 const cursorNodeDiff = index_es6.diffArrays(oldCursorNodeCharArray, newCursorNodeCharArray);
14958 let cursorOffset = newCursorNodeStart;
14960 for (const entry of cursorNodeDiff) {
14961 if (entry.removed) {
14962 if (entry.value.includes(CURSOR)) {
14966 cursorOffset += entry.count;
14971 formatted: result.formatted,
14977 formatted: result.formatted,
14982 function formatRange(originalText, opts) {
14986 } = parser.parse(originalText, opts);
14990 } = rangeUtil.calculateRange(text, opts, ast);
14991 const rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line.
14992 // This is so we can detect indentation correctly and restore it.
14993 // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0
14995 const rangeStart2 = Math.min(rangeStart, text.lastIndexOf("\n", rangeStart) + 1);
14996 const indentString = text.slice(rangeStart2, rangeStart).match(/^\s*/)[0];
14997 const alignmentSize = getAlignmentSize$1(indentString, opts.tabWidth);
14998 const rangeResult = coreFormat(rangeString, Object.assign({}, opts, {
15000 rangeEnd: Infinity,
15001 // Track the cursor offset only if it's within our range
15002 cursorOffset: opts.cursorOffset > rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart : -1,
15003 // Always use `lf` to format, we'll replace it later
15005 }), alignmentSize); // Since the range contracts to avoid trailing whitespace,
15006 // we need to remove the newline that was inserted by the `format` call.
15008 const rangeTrimmed = rangeResult.formatted.trimEnd();
15013 if (cursorOffset >= rangeEnd) {
15014 // handle the case where the cursor was past the end of the range
15015 cursorOffset = opts.cursorOffset + (rangeTrimmed.length - rangeString.length);
15016 } else if (rangeResult.cursorOffset >= 0) {
15017 // handle the case where the cursor was in the range
15018 cursorOffset = rangeResult.cursorOffset + rangeStart;
15019 } // keep the cursor as it was if it was before the start of the range
15022 let formatted = text.slice(0, rangeStart) + rangeTrimmed + text.slice(rangeEnd);
15024 if (opts.endOfLine !== "lf") {
15025 const eol = convertEndOfLineToChars$2(opts.endOfLine);
15027 if (cursorOffset >= 0 && eol === "\r\n") {
15028 cursorOffset += countEndOfLineChars$1(formatted.slice(0, cursorOffset), "\n");
15031 formatted = formatted.replace(/\n/g, eol);
15040 function ensureIndexInText(text, index, defaultValue) {
15041 if (typeof index !== "number" || isNaN(index) || index < 0 || index > text.length) {
15042 return defaultValue;
15048 function normalizeIndexes(text, options) {
15054 cursorOffset = ensureIndexInText(text, cursorOffset, -1);
15055 rangeStart = ensureIndexInText(text, rangeStart, 0);
15056 rangeEnd = ensureIndexInText(text, rangeEnd, text.length);
15057 return Object.assign({}, options, {
15064 function normalizeInputAndOptions(text, options) {
15070 } = normalizeIndexes(text, options);
15071 const hasBOM = text.charAt(0) === BOM;
15074 text = text.slice(1);
15080 if (endOfLine === "auto") {
15081 endOfLine = guessEndOfLine$1(text);
15082 } // get rid of CR/CRLF parsing
15085 if (text.includes("\r")) {
15086 const countCrlfBefore = index => countEndOfLineChars$1(text.slice(0, Math.max(index, 0)), "\r\n");
15088 cursorOffset -= countCrlfBefore(cursorOffset);
15089 rangeStart -= countCrlfBefore(rangeStart);
15090 rangeEnd -= countCrlfBefore(rangeEnd);
15091 text = normalizeEndOfLine$1(text);
15097 options: normalizeIndexes(text, Object.assign({}, options, {
15106 function format(originalText, originalOptions) {
15111 } = normalizeInputAndOptions(originalText, normalizeOptions$1(originalOptions));
15112 const selectedParser = parser.resolveParser(options);
15113 const hasPragma = !selectedParser.hasPragma || selectedParser.hasPragma(text);
15115 if (options.requirePragma && !hasPragma) {
15117 formatted: originalText,
15118 cursorOffset: originalOptions.cursorOffset
15124 if (options.rangeStart > 0 || options.rangeEnd < text.length) {
15125 result = formatRange(text, options);
15127 if (!hasPragma && options.insertPragma && options.printer.insertPragma) {
15128 text = options.printer.insertPragma(text);
15131 result = coreFormat(text, options);
15135 result.formatted = BOM + result.formatted;
15137 if (result.cursorOffset >= 0) {
15138 result.cursorOffset++;
15146 formatWithCursor: format,
15148 parse(originalText, originalOptions, massage) {
15152 } = normalizeInputAndOptions(originalText, normalizeOptions$1(originalOptions));
15153 const parsed = parser.parse(text, options);
15156 parsed.ast = massageAst(parsed.ast, options);
15162 formatAST(ast, options) {
15163 options = normalizeOptions$1(options);
15164 const doc = astToDoc(ast, options);
15165 return printDocToString$1(doc, options);
15168 // Doesn't handle shebang for now
15169 formatDoc(doc, options) {
15170 return format(printDocToDebug(doc), Object.assign({}, options, {
15175 printToDoc(originalText, options) {
15176 options = normalizeOptions$1(options);
15180 } = parser.parse(originalText, options);
15181 attachComments(text, ast, options);
15182 return astToDoc(ast, options);
15185 printDocToString(doc, options) {
15186 return printDocToString$1(doc, normalizeOptions$1(options));
15191 var concatMap = function (xs, fn) {
15194 for (var i = 0; i < xs.length; i++) {
15195 var x = fn(xs[i], i);
15196 if (isArray$2(x)) res.push.apply(res, x);else res.push(x);
15202 var isArray$2 = Array.isArray || function (xs) {
15203 return Object.prototype.toString.call(xs) === '[object Array]';
15206 var balancedMatch = balanced;
15208 function balanced(a, b, str) {
15209 if (a instanceof RegExp) a = maybeMatch(a, str);
15210 if (b instanceof RegExp) b = maybeMatch(b, str);
15211 var r = range(a, b, str);
15215 pre: str.slice(0, r[0]),
15216 body: str.slice(r[0] + a.length, r[1]),
15217 post: str.slice(r[1] + b.length)
15221 function maybeMatch(reg, str) {
15222 var m = str.match(reg);
15223 return m ? m[0] : null;
15226 balanced.range = range;
15228 function range(a, b, str) {
15229 var begs, beg, left, right, result;
15230 var ai = str.indexOf(a);
15231 var bi = str.indexOf(b, ai + 1);
15234 if (ai >= 0 && bi > 0) {
15238 while (i >= 0 && !result) {
15241 ai = str.indexOf(a, i + 1);
15242 } else if (begs.length == 1) {
15243 result = [begs.pop(), bi];
15252 bi = str.indexOf(b, i + 1);
15255 i = ai < bi && ai >= 0 ? ai : bi;
15259 result = [left, right];
15266 var braceExpansion = expandTop;
15267 var escSlash = '\0SLASH' + Math.random() + '\0';
15268 var escOpen = '\0OPEN' + Math.random() + '\0';
15269 var escClose = '\0CLOSE' + Math.random() + '\0';
15270 var escComma = '\0COMMA' + Math.random() + '\0';
15271 var escPeriod = '\0PERIOD' + Math.random() + '\0';
15273 function numeric$1(str) {
15274 return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
15277 function escapeBraces(str) {
15278 return str.split('\\\\').join(escSlash).split('\\{').join(escOpen).split('\\}').join(escClose).split('\\,').join(escComma).split('\\.').join(escPeriod);
15281 function unescapeBraces(str) {
15282 return str.split(escSlash).join('\\').split(escOpen).join('{').split(escClose).join('}').split(escComma).join(',').split(escPeriod).join('.');
15283 } // Basically just str.split(","), but handling cases
15284 // where we have nested braced sections, which should be
15285 // treated as individual members, like {a,{b,c},d}
15288 function parseCommaParts(str) {
15289 if (!str) return [''];
15291 var m = balancedMatch('{', '}', str);
15292 if (!m) return str.split(',');
15296 var p = pre.split(',');
15297 p[p.length - 1] += '{' + body + '}';
15298 var postParts = parseCommaParts(post);
15301 p[p.length - 1] += postParts.shift();
15302 p.push.apply(p, postParts);
15305 parts.push.apply(parts, p);
15309 function expandTop(str) {
15310 if (!str) return []; // I don't know why Bash 4.3 does this, but it does.
15311 // Anything starting with {} will have the first two bytes preserved
15312 // but *only* at the top level, so {},a}b will not expand to anything,
15313 // but a{},b}c will be expanded to [a}c,abc].
15314 // One could argue that this is a bug in Bash, but since the goal of
15315 // this module is to match Bash's rules, we escape a leading {}
15317 if (str.substr(0, 2) === '{}') {
15318 str = '\\{\\}' + str.substr(2);
15321 return expand(escapeBraces(str), true).map(unescapeBraces);
15324 function embrace(str) {
15325 return '{' + str + '}';
15328 function isPadded(el) {
15329 return /^-?0\d/.test(el);
15332 function lte(i, y) {
15336 function gte$1(i, y) {
15340 function expand(str, isTop) {
15341 var expansions = [];
15342 var m = balancedMatch('{', '}', str);
15343 if (!m || /\$$/.test(m.pre)) return [str];
15344 var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
15345 var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
15346 var isSequence = isNumericSequence || isAlphaSequence;
15347 var isOptions = m.body.indexOf(',') >= 0;
15349 if (!isSequence && !isOptions) {
15351 if (m.post.match(/,.*\}/)) {
15352 str = m.pre + '{' + m.body + escClose + m.post;
15353 return expand(str);
15362 n = m.body.split(/\.\./);
15364 n = parseCommaParts(m.body);
15366 if (n.length === 1) {
15367 // x{{a,b}}y ==> x{a}y x{b}y
15368 n = expand(n[0], false).map(embrace);
15370 if (n.length === 1) {
15371 var post = m.post.length ? expand(m.post, false) : [''];
15372 return post.map(function (p) {
15373 return m.pre + n[0] + p;
15377 } // at this point, n is the parts, and we know it's not a comma set
15378 // with a single entry.
15379 // no need to expand pre, since it is guaranteed to be free of brace-sets
15383 var post = m.post.length ? expand(m.post, false) : [''];
15387 var x = numeric$1(n[0]);
15388 var y = numeric$1(n[1]);
15389 var width = Math.max(n[0].length, n[1].length);
15390 var incr = n.length == 3 ? Math.abs(numeric$1(n[2])) : 1;
15392 var reverse = y < x;
15399 var pad = n.some(isPadded);
15402 for (var i = x; test(i, y); i += incr) {
15405 if (isAlphaSequence) {
15406 c = String.fromCharCode(i);
15407 if (c === '\\') c = '';
15412 var need = width - c.length;
15415 var z = new Array(need + 1).join('0');
15416 if (i < 0) c = '-' + z + c.slice(1);else c = z + c;
15424 N = concatMap(n, function (el) {
15425 return expand(el, false);
15429 for (var j = 0; j < N.length; j++) {
15430 for (var k = 0; k < post.length; k++) {
15431 var expansion = pre + N[j] + post[k];
15432 if (!isTop || isSequence || expansion) expansions.push(expansion);
15439 var minimatch_1 = minimatch;
15440 minimatch.Minimatch = Minimatch;
15446 path = path__default['default'];
15449 var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
15471 }; // any single thing other than /
15472 // don't need to escape / when using new RegExp()
15474 var qmark = '[^/]'; // * => any number of characters
15476 var star = qmark + '*?'; // ** when dots are allowed. Anything goes, except .. and .
15477 // not (^ or / followed by one or two dots followed by $ or /),
15478 // followed by anything, any number of times.
15480 var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; // not a ^ or / followed by a dot,
15481 // followed by anything, any number of times.
15483 var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; // characters that need to be escaped in RegExp.
15485 var reSpecials = charSet('().*{}+?[]^$\\!'); // "abc" -> { a:true, b:true, c:true }
15487 function charSet(s) {
15488 return s.split('').reduce(function (set, c) {
15492 } // normalizes slashes.
15495 var slashSplit = /\/+/;
15496 minimatch.filter = filter;
15498 function filter(pattern, options) {
15499 options = options || {};
15500 return function (p, i, list) {
15501 return minimatch(p, pattern, options);
15505 function ext(a, b) {
15509 Object.keys(b).forEach(function (k) {
15512 Object.keys(a).forEach(function (k) {
15518 minimatch.defaults = function (def) {
15519 if (!def || !Object.keys(def).length) return minimatch;
15520 var orig = minimatch;
15522 var m = function minimatch(p, pattern, options) {
15523 return orig.minimatch(p, pattern, ext(def, options));
15526 m.Minimatch = function Minimatch(pattern, options) {
15527 return new orig.Minimatch(pattern, ext(def, options));
15533 Minimatch.defaults = function (def) {
15534 if (!def || !Object.keys(def).length) return Minimatch;
15535 return minimatch.defaults(def).Minimatch;
15538 function minimatch(p, pattern, options) {
15539 if (typeof pattern !== 'string') {
15540 throw new TypeError('glob pattern string required');
15543 if (!options) options = {}; // shortcut: comments match nothing.
15545 if (!options.nocomment && pattern.charAt(0) === '#') {
15547 } // "" only matches ""
15550 if (pattern.trim() === '') return p === '';
15551 return new Minimatch(pattern, options).match(p);
15554 function Minimatch(pattern, options) {
15555 if (!(this instanceof Minimatch)) {
15556 return new Minimatch(pattern, options);
15559 if (typeof pattern !== 'string') {
15560 throw new TypeError('glob pattern string required');
15563 if (!options) options = {};
15564 pattern = pattern.trim(); // windows support: need to use /, not \
15566 if (path.sep !== '/') {
15567 pattern = pattern.split(path.sep).join('/');
15570 this.options = options;
15572 this.pattern = pattern;
15573 this.regexp = null;
15574 this.negate = false;
15575 this.comment = false;
15576 this.empty = false; // make the set of regexps etc.
15581 Minimatch.prototype.debug = function () {};
15583 Minimatch.prototype.make = make;
15586 // don't do it more than once.
15587 if (this._made) return;
15588 var pattern = this.pattern;
15589 var options = this.options; // empty patterns and comments match nothing.
15591 if (!options.nocomment && pattern.charAt(0) === '#') {
15592 this.comment = true;
15599 } // step 1: figure out negation, etc.
15602 this.parseNegate(); // step 2: expand braces
15604 var set = this.globSet = this.braceExpand();
15605 if (options.debug) this.debug = console.error;
15606 this.debug(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion
15607 // matching patterns.
15608 // These will be regexps, except in the case of "**", which is
15609 // set to the GLOBSTAR object for globstar behavior,
15610 // and will not contain any / characters
15612 set = this.globParts = set.map(function (s) {
15613 return s.split(slashSplit);
15615 this.debug(this.pattern, set); // glob --> regexps
15617 set = set.map(function (s, si, set) {
15618 return s.map(this.parse, this);
15620 this.debug(this.pattern, set); // filter out everything that didn't compile properly.
15622 set = set.filter(function (s) {
15623 return s.indexOf(false) === -1;
15625 this.debug(this.pattern, set);
15629 Minimatch.prototype.parseNegate = parseNegate;
15631 function parseNegate() {
15632 var pattern = this.pattern;
15633 var negate = false;
15634 var options = this.options;
15635 var negateOffset = 0;
15636 if (options.nonegate) return;
15638 for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === '!'; i++) {
15643 if (negateOffset) this.pattern = pattern.substr(negateOffset);
15644 this.negate = negate;
15645 } // Brace expansion:
15646 // a{b,c}d -> abd acd
15647 // a{b,}c -> abc ac
15648 // a{0..3}d -> a0d a1d a2d a3d
15649 // a{b,c{d,e}f}g -> abg acdfg acefg
15650 // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
15652 // Invalid sets are not expanded.
15653 // a{2..}b -> a{2..}b
15657 minimatch.braceExpand = function (pattern, options) {
15658 return braceExpand(pattern, options);
15661 Minimatch.prototype.braceExpand = braceExpand;
15663 function braceExpand(pattern, options) {
15665 if (this instanceof Minimatch) {
15666 options = this.options;
15672 pattern = typeof pattern === 'undefined' ? this.pattern : pattern;
15674 if (typeof pattern === 'undefined') {
15675 throw new TypeError('undefined pattern');
15678 if (options.nobrace || !pattern.match(/\{.*\}/)) {
15679 // shortcut. no need to expand.
15683 return braceExpansion(pattern);
15684 } // parse a component of the expanded set.
15685 // At this point, no pattern may contain "/" in it
15686 // so we're going to return a 2d array, where each entry is the full
15687 // pattern, split on '/', and then turned into a regular expression.
15688 // A regexp is made at the end which joins each array with an
15689 // escaped /, and another full one which joins each regexp with |.
15691 // Following the lead of Bash 4.1, note that "**" only has special meaning
15692 // when it is the *only* thing in a path portion. Otherwise, any series
15693 // of * is equivalent to a single *. Globstar behavior is enabled by
15694 // default, and can be disabled by setting options.noglobstar.
15697 Minimatch.prototype.parse = parse$1;
15700 function parse$1(pattern, isSub) {
15701 if (pattern.length > 1024 * 64) {
15702 throw new TypeError('pattern is too long');
15705 var options = this.options; // shortcuts
15707 if (!options.noglobstar && pattern === '**') return GLOBSTAR;
15708 if (pattern === '') return '';
15710 var hasMagic = !!options.nocase;
15711 var escaping = false; // ? => one single character
15713 var patternListStack = [];
15714 var negativeLists = [];
15716 var inClass = false;
15717 var reClassStart = -1;
15718 var classStart = -1; // . and .. never match anything that doesn't start with .,
15719 // even when options.dot is set.
15721 var patternStart = pattern.charAt(0) === '.' ? '' // anything
15722 // not (start or / followed by . or .. followed by / or end)
15723 : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)';
15726 function clearStateChar() {
15728 // we had some state-tracking character
15729 // that wasn't consumed by this pass.
15730 switch (stateChar) {
15742 re += '\\' + stateChar;
15746 self.debug('clearStateChar %j %j', stateChar, re);
15751 for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
15752 this.debug('%s\t%s %s %j', pattern, i, re, c); // skip over any that are escaped.
15754 if (escaping && reSpecials[c]) {
15762 // completely not allowed, even escaped.
15763 // Should already be path-split by now.
15770 // the various stateChar values
15771 // for the "extglob" stuff.
15778 this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); // all of those are literals inside a class, except that
15779 // the glob [!a] means [^a] in regexp
15782 this.debug(' in class');
15783 if (c === '!' && i === classStart + 1) c = '^';
15786 } // if we already have a stateChar, then it means
15787 // that there was something like ** or +? in there.
15788 // Handle the stateChar, then proceed with this one.
15791 self.debug('call clearStateChar %j', stateChar);
15793 stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
15794 // just clear the statechar *now*, rather than even diving into
15795 // the patternList stuff.
15797 if (options.noext) clearStateChar();
15811 patternListStack.push({
15814 reStart: re.length,
15815 open: plTypes[stateChar].open,
15816 close: plTypes[stateChar].close
15817 }); // negation is (?:(?!js)[^/]*)
15819 re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
15820 this.debug('plType %j %j', stateChar, re);
15825 if (inClass || !patternListStack.length) {
15832 var pl = patternListStack.pop(); // negation is (?:(?!js)[^/]*)
15833 // The others are (?:<pattern>)<type>
15837 if (pl.type === '!') {
15838 negativeLists.push(pl);
15841 pl.reEnd = re.length;
15845 if (inClass || !patternListStack.length || escaping) {
15854 // these are mostly the same in regexp and glob
15857 // swallow any state-tracking char before the [
15867 reClassStart = re.length;
15872 // a right bracket shall lose its special
15873 // meaning and represent itself in
15874 // a bracket expression if it occurs
15875 // first in the list. -- POSIX.2 2.8.3.2
15876 if (i === classStart + 1 || !inClass) {
15880 } // handle the case where we left a class open.
15881 // "[z-a]" is valid, equivalent to "\[z-a\]"
15885 // split where the last [ was, make sure we don't have
15886 // an invalid re. if so, re-walk the contents of the
15887 // would-be class to re-translate any characters that
15888 // were passed through as-is
15889 // TODO: It would probably be faster to determine this
15890 // without a try/catch and a new RegExp, but it's tricky
15891 // to do safely. For now, this is safe and works.
15892 var cs = pattern.substring(classStart + 1, i);
15895 RegExp('[' + cs + ']');
15897 // not a valid class!
15898 var sp = this.parse(cs, SUBPARSE);
15899 re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
15900 hasMagic = hasMagic || sp[1];
15904 } // finish up the class.
15913 // swallow any state char that wasn't consumed
15919 } else if (reSpecials[c] && !(c === '^' && inClass)) {
15927 // handle the case where we left a class open.
15928 // "[abc" is valid, equivalent to "\[abc"
15932 // split where the last [ was, and escape it
15933 // this is a huge pita. We now have to re-walk
15934 // the contents of the would-be class to re-translate
15935 // any characters that were passed through as-is
15936 cs = pattern.substr(classStart + 1);
15937 sp = this.parse(cs, SUBPARSE);
15938 re = re.substr(0, reClassStart) + '\\[' + sp[0];
15939 hasMagic = hasMagic || sp[1];
15940 } // handle the case where we had a +( thing at the *end*
15942 // each pattern list stack adds 3 chars, and we need to go through
15943 // and escape any | chars that were passed through as-is for the regexp.
15944 // Go through and escape them, taking care not to double-escape any
15945 // | chars that were already escaped.
15948 for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
15949 var tail = re.slice(pl.reStart + pl.open.length);
15950 this.debug('setting tail', re, pl); // maybe some even number of \, then maybe 1 \, followed by a |
15952 tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
15954 // the | isn't already escaped, so escape it.
15956 } // need to escape all those slashes *again*, without escaping the
15957 // one that we need for escaping the | character. As it works out,
15958 // escaping an even number of slashes can be done by simply repeating
15959 // it exactly after itself. That's why this trick works.
15961 // I am sorry that you have to see this.
15964 return $1 + $1 + $2 + '|';
15966 this.debug('tail=%j\n %s', tail, tail, pl, re);
15967 var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type;
15969 re = re.slice(0, pl.reStart) + t + '\\(' + tail;
15970 } // handle trailing things that only matter at the very end.
15978 } // only need to apply the nodot start if the re starts with
15979 // something that could conceivably capture a dot
15982 var addPatternStart = false;
15984 switch (re.charAt(0)) {
15988 addPatternStart = true;
15989 } // Hack to work around lack of negative lookbehind in JS
15990 // A pattern like: *.!(x).!(y|z) needs to ensure that a name
15991 // like 'a.xyz.yz' doesn't match. So, the first negative
15992 // lookahead, has to look ALL the way ahead, to the end of
15996 for (var n = negativeLists.length - 1; n > -1; n--) {
15997 var nl = negativeLists[n];
15998 var nlBefore = re.slice(0, nl.reStart);
15999 var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
16000 var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
16001 var nlAfter = re.slice(nl.reEnd);
16002 nlLast += nlAfter; // Handle nested stuff like *(*.js|!(*.json)), where open parens
16003 // mean that we should *not* include the ) in the bit that is considered
16004 // "after" the negated section.
16006 var openParensBefore = nlBefore.split('(').length - 1;
16007 var cleanAfter = nlAfter;
16009 for (i = 0; i < openParensBefore; i++) {
16010 cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
16013 nlAfter = cleanAfter;
16016 if (nlAfter === '' && isSub !== SUBPARSE) {
16020 var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
16022 } // if the re is not "" at this point, then we need to make sure
16023 // it doesn't match against an empty path part.
16024 // Otherwise a/* will match a/, which it should not.
16027 if (re !== '' && hasMagic) {
16031 if (addPatternStart) {
16032 re = patternStart + re;
16033 } // parsing just a piece of a larger pattern.
16036 if (isSub === SUBPARSE) {
16037 return [re, hasMagic];
16038 } // skip the regexp for non-magical patterns
16039 // unescape anything in it, though, so that it'll be
16040 // an exact match against a file etc.
16044 return globUnescape(pattern);
16047 var flags = options.nocase ? 'i' : '';
16050 var regExp = new RegExp('^' + re + '$', flags);
16052 // If it was an invalid regular expression, then it can't match
16053 // anything. This trick looks for a character after the end of
16054 // the string, which is of course impossible, except in multi-line
16055 // mode, but it's not a /m regex.
16056 return new RegExp('$.');
16059 regExp._glob = pattern;
16064 minimatch.makeRe = function (pattern, options) {
16065 return new Minimatch(pattern, options || {}).makeRe();
16068 Minimatch.prototype.makeRe = makeRe;
16070 function makeRe() {
16071 if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
16072 // pattern strings, or "**".
16074 // It's better to use .match(). This function shouldn't
16075 // be used, really, but it's pretty convenient sometimes,
16076 // when you just want to work with a regex.
16078 var set = this.set;
16081 this.regexp = false;
16082 return this.regexp;
16085 var options = this.options;
16086 var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
16087 var flags = options.nocase ? 'i' : '';
16088 var re = set.map(function (pattern) {
16089 return pattern.map(function (p) {
16090 return p === GLOBSTAR ? twoStar : typeof p === 'string' ? regExpEscape(p) : p._src;
16092 }).join('|'); // must match entire pattern
16093 // ending in a * or ** will make it less strict.
16095 re = '^(?:' + re + ')$'; // can match anything, as long as it's not this.
16097 if (this.negate) re = '^(?!' + re + ').*$';
16100 this.regexp = new RegExp(re, flags);
16102 this.regexp = false;
16105 return this.regexp;
16108 minimatch.match = function (list, pattern, options) {
16109 options = options || {};
16110 var mm = new Minimatch(pattern, options);
16111 list = list.filter(function (f) {
16112 return mm.match(f);
16115 if (mm.options.nonull && !list.length) {
16116 list.push(pattern);
16122 Minimatch.prototype.match = match;
16124 function match(f, partial) {
16125 this.debug('match', f, this.pattern); // short-circuit in the case of busted things.
16128 if (this.comment) return false;
16129 if (this.empty) return f === '';
16130 if (f === '/' && partial) return true;
16131 var options = this.options; // windows: need to use /, not \
16133 if (path.sep !== '/') {
16134 f = f.split(path.sep).join('/');
16135 } // treat the test path as a set of pathparts.
16138 f = f.split(slashSplit);
16139 this.debug(this.pattern, 'split', f); // just ONE of the pattern sets in this.set needs to match
16140 // in order for it to be valid. If negating, then just one
16141 // match means that we have failed.
16142 // Either way, return on the first hit.
16144 var set = this.set;
16145 this.debug(this.pattern, 'set', set); // Find the basename of the path by looking for the last non-empty segment
16150 for (i = f.length - 1; i >= 0; i--) {
16152 if (filename) break;
16155 for (i = 0; i < set.length; i++) {
16156 var pattern = set[i];
16159 if (options.matchBase && pattern.length === 1) {
16163 var hit = this.matchOne(file, pattern, partial);
16166 if (options.flipNegate) return true;
16167 return !this.negate;
16169 } // didn't get any hits. this is success if it's a negative
16170 // pattern, failure otherwise.
16173 if (options.flipNegate) return false;
16174 return this.negate;
16175 } // set partial to true to test if, for example,
16176 // "/a/b" matches the start of "/*/b/*/d"
16177 // Partial means, if you run out of file before you run
16178 // out of pattern, then that's fine, as long as all
16179 // the parts match.
16182 Minimatch.prototype.matchOne = function (file, pattern, partial) {
16183 var options = this.options;
16184 this.debug('matchOne', {
16189 this.debug('matchOne', file.length, pattern.length);
16191 for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
16192 this.debug('matchOne loop');
16193 var p = pattern[pi];
16195 this.debug(pattern, p, f); // should be impossible.
16196 // some invalid regexp stuff in the set.
16198 if (p === false) return false;
16200 if (p === GLOBSTAR) {
16201 this.debug('GLOBSTAR', [pattern, p, f]); // "**"
16202 // a/**/b/**/c would match the following:
16207 // To do this, take the rest of the pattern after
16208 // the **, and see if it would match the file remainder.
16209 // If so, return success.
16210 // If not, the ** "swallows" a segment, and try again.
16211 // This is recursively awful.
16213 // a/**/b/**/c matching a/b/x/y/z/c
16216 // - matchOne(b/x/y/z/c, b/**/c)
16219 // - matchOne(x/y/z/c, c) -> no
16220 // - matchOne(y/z/c, c) -> no
16221 // - matchOne(z/c, c) -> no
16222 // - matchOne(c, c) yes, hit
16228 this.debug('** at the end'); // a ** at the end will just swallow the rest.
16229 // We have found a match.
16230 // however, it will not swallow /.x, unless
16231 // options.dot is set.
16232 // . and .. are *never* matched by **, for explosively
16233 // exponential reasons.
16235 for (; fi < fl; fi++) {
16236 if (file[fi] === '.' || file[fi] === '..' || !options.dot && file[fi].charAt(0) === '.') return false;
16240 } // ok, let's see if we can swallow whatever we can.
16244 var swallowee = file[fr];
16245 this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); // XXX remove this slice. Just pass the start index.
16247 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
16248 this.debug('globstar found match!', fr, fl, swallowee); // found a match.
16252 // can't swallow "." or ".." ever.
16253 // can only swallow ".foo" when explicitly asked.
16254 if (swallowee === '.' || swallowee === '..' || !options.dot && swallowee.charAt(0) === '.') {
16255 this.debug('dot detected!', file, fr, pattern, pr);
16257 } // ** swallows a segment, and continue.
16260 this.debug('globstar swallow a segment, and continue');
16263 } // no match was found.
16264 // However, in partial mode, we can't say this is necessarily over.
16265 // If there's more *pattern* left, then
16270 this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
16271 if (fr === fl) return true;
16275 } // something other than **
16276 // non-magic patterns just have to match exactly
16277 // patterns with magic have been turned into regexps.
16282 if (typeof p === 'string') {
16283 if (options.nocase) {
16284 hit = f.toLowerCase() === p.toLowerCase();
16289 this.debug('string match', p, f, hit);
16292 this.debug('pattern match', p, f, hit);
16295 if (!hit) return false;
16296 } // Note: ending in / means that we'll get a final ""
16297 // at the end of the pattern. This can only match a
16298 // corresponding "" at the end of the file.
16299 // If the file ends in /, then it can only match a
16300 // a pattern that ends in /, unless the pattern just
16301 // doesn't have any more for it. But, a/b/ should *not*
16302 // match "a/b/*", even though "" matches against the
16303 // [^/]*? pattern, except in partial mode, where it might
16304 // simply not be reached yet.
16305 // However, a/b/ should still satisfy a/*
16306 // now either we fell off the end of the pattern, or we're done.
16309 if (fi === fl && pi === pl) {
16310 // ran out of pattern and filename at the same time.
16313 } else if (fi === fl) {
16314 // ran out of file, but still had pattern left.
16315 // this is ok if we're doing the match as part of
16316 // a glob fs traversal.
16318 } else if (pi === pl) {
16319 // ran out of pattern, still have file left.
16320 // this is only acceptable if we're on the very last
16321 // empty segment of a file with a trailing slash.
16322 // a/* should match a/b/
16323 var emptyFileEnd = fi === fl - 1 && file[fi] === '';
16324 return emptyFileEnd;
16325 } // should be unreachable.
16328 throw new Error('wtf?');
16329 }; // replace stuff like \* with *
16332 function globUnescape(s) {
16333 return s.replace(/\\(.)/g, '$1');
16336 function regExpEscape(s) {
16337 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
16340 const copyProperty = (to, from, property, ignoreNonConfigurable) => {
16341 // `Function#length` should reflect the parameters of `to` not `from` since we keep its body.
16342 // `Function#prototype` is non-writable and non-configurable so can never be modified.
16343 if (property === 'length' || property === 'prototype') {
16345 } // `Function#arguments` and `Function#caller` should not be copied. They were reported to be present in `Reflect.ownKeys` for some devices in React Native (#41), so we explicitly ignore them here.
16348 if (property === 'arguments' || property === 'caller') {
16352 const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
16353 const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
16355 if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {
16359 Object.defineProperty(to, property, fromDescriptor);
16360 }; // `Object.defineProperty()` throws if the property exists, is not configurable and either:
16361 // - one its descriptors is changed
16362 // - it is non-writable and its value is changed
16365 const canCopyProperty = function (toDescriptor, fromDescriptor) {
16366 return toDescriptor === undefined || toDescriptor.configurable || toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value);
16369 const changePrototype = (to, from) => {
16370 const fromPrototype = Object.getPrototypeOf(from);
16372 if (fromPrototype === Object.getPrototypeOf(to)) {
16376 Object.setPrototypeOf(to, fromPrototype);
16379 const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`;
16381 const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');
16382 const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name'); // We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected.
16383 // We use `bind()` instead of a closure for the same reason.
16384 // Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times.
16386 const changeToString = (to, from, name) => {
16387 const withName = name === '' ? '' : `with ${name.trim()}() `;
16388 const newToString = wrappedToString.bind(null, withName, from.toString()); // Ensure `to.toString.toString` is non-enumerable and has the same `same`
16390 Object.defineProperty(newToString, 'name', toStringName);
16391 Object.defineProperty(to, 'toString', Object.assign({}, toStringDescriptor, {
16396 const mimicFn = (to, from, {
16397 ignoreNonConfigurable = false
16403 for (const property of Reflect.ownKeys(from)) {
16404 copyProperty(to, from, property, ignoreNonConfigurable);
16407 changePrototype(to, from);
16408 changeToString(to, from, name);
16412 var mimicFn_1 = mimicFn;
16414 var pDefer = () => {
16416 ret.promise = new Promise((resolve, reject) => {
16417 ret.resolve = resolve;
16418 ret.reject = reject;
16423 var dist = createCommonjsModule(function (module, exports) {
16425 var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
16426 return new (P || (P = Promise))(function (resolve, reject) {
16427 function fulfilled(value) {
16429 step(generator.next(value));
16435 function rejected(value) {
16437 step(generator["throw"](value));
16443 function step(result) {
16444 result.done ? resolve(result.value) : new P(function (resolve) {
16445 resolve(result.value);
16446 }).then(fulfilled, rejected);
16449 step((generator = generator.apply(thisArg, _arguments || [])).next());
16453 var __importDefault = this && this.__importDefault || function (mod) {
16454 return mod && mod.__esModule ? mod : {
16459 Object.defineProperty(exports, "__esModule", {
16463 const p_defer_1 = __importDefault(pDefer);
16465 function mapAgeCleaner(map, property = 'maxAge') {
16467 let processingTimer;
16468 let processingDeferred;
16470 const cleanup = () => __awaiter(this, void 0, void 0, function* () {
16471 if (processingKey !== undefined) {
16472 // If we are already processing an item, we can safely exit
16476 const setupTimer = item => __awaiter(this, void 0, void 0, function* () {
16477 processingDeferred = p_defer_1.default();
16478 const delay = item[1][property] - Date.now();
16481 // Remove the item immediately if the delay is equal to or below 0
16482 map.delete(item[0]);
16483 processingDeferred.resolve();
16485 } // Keep track of the current processed key
16488 processingKey = item[0];
16489 processingTimer = setTimeout(() => {
16490 // Remove the item when the timeout fires
16491 map.delete(item[0]);
16493 if (processingDeferred) {
16494 processingDeferred.resolve();
16496 }, delay); // tslint:disable-next-line:strict-type-predicates
16498 if (typeof processingTimer.unref === 'function') {
16499 // Don't hold up the process from exiting
16500 processingTimer.unref();
16503 return processingDeferred.promise;
16507 for (const entry of map) {
16508 yield setupTimer(entry);
16510 } catch (_a) {// Do nothing if an error occurs, this means the timer was cleaned up and we should stop processing
16513 processingKey = undefined;
16516 const reset = () => {
16517 processingKey = undefined;
16519 if (processingTimer !== undefined) {
16520 clearTimeout(processingTimer);
16521 processingTimer = undefined;
16524 if (processingDeferred !== undefined) {
16525 // tslint:disable-line:early-exit
16526 processingDeferred.reject(undefined);
16527 processingDeferred = undefined;
16531 const originalSet = map.set.bind(map);
16533 map.set = (key, value) => {
16534 if (map.has(key)) {
16535 // If the key already exist, remove it so we can add it back at the end of the map.
16537 } // Call the original `map.set`
16540 const result = originalSet(key, value); // If we are already processing a key and the key added is the current processed key, stop processing it
16542 if (processingKey && processingKey === key) {
16544 } // Always run the cleanup method in case it wasn't started yet
16547 cleanup(); // tslint:disable-line:no-floating-promises
16552 cleanup(); // tslint:disable-line:no-floating-promises
16557 exports.default = mapAgeCleaner; // Add support for CJS
16559 module.exports = mapAgeCleaner;
16560 module.exports.default = mapAgeCleaner;
16563 const cacheStore = new WeakMap();
16565 [Memoize](https://en.wikipedia.org/wiki/Memoization) functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input.
16567 @param fn - Function to be memoized.
16571 import mem = require('mem');
16574 const counter = () => ++i;
16575 const memoized = mem(counter);
16580 // Cached as it's the same arguments
16584 // Not cached anymore as the arguments changed
16598 if (typeof maxAge === 'number') {
16599 // TODO: Drop after https://github.com/SamVerschueren/map-age-cleaner/issues/5
16600 // @ts-expect-error
16604 const memoized = function (...arguments_) {
16605 const key = cacheKey ? cacheKey(arguments_) : arguments_[0];
16606 const cacheItem = cache.get(key);
16609 return cacheItem.data;
16612 const result = fn.apply(this, arguments_);
16615 maxAge: maxAge ? Date.now() + maxAge : Infinity
16621 // The below call will throw in some host environments
16622 // See https://github.com/sindresorhus/mimic-fn/issues/10
16623 mimicFn_1(memoized, fn);
16626 cacheStore.set(memoized, cache);
16630 Clear all cached data of a memoized function.
16632 @param fn - Memoized function.
16636 mem.clear = fn => {
16637 const cache = cacheStore.get(fn);
16640 throw new TypeError('Can\'t clear a function that was not memoized!');
16643 if (typeof cache.clear !== 'function') {
16644 throw new TypeError('The cache Map can\'t be cleared!');
16652 var thirdParty = require("./third-party");
16654 const ParserEND = 0x110000;
16656 class ParserError extends Error {
16657 /* istanbul ignore next */
16658 constructor(msg, filename, linenumber) {
16659 super('[ParserError] ' + msg, filename, linenumber);
16660 this.name = 'ParserError';
16661 this.code = 'ParserError';
16662 if (Error.captureStackTrace) Error.captureStackTrace(this, ParserError);
16668 constructor(parser) {
16669 this.parser = parser;
16671 this.returned = null;
16672 this.result = null;
16673 this.resultTable = null;
16674 this.resultArr = null;
16685 this.ctx = this.obj;
16690 this.state = new State(this.parseStart);
16694 /* istanbul ignore next */
16695 if (str.length === 0 || str.length == null) return;
16696 this._buf = String(str);
16701 while (getNext === false || this.nextChar()) {
16702 getNext = this.runOne();
16709 if (this.char === 0x0A) {
16715 this.char = this._buf.codePointAt(this.ii);
16718 return this.haveBuffer();
16722 return this.ii < this._buf.length;
16726 return this.state.parser.call(this, this.state.returned);
16730 this.char = ParserEND;
16734 last = this.state.parser;
16736 } while (this.state.parser !== last);
16745 /* istanbul ignore next */
16746 if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn));
16747 this.state.parser = fn;
16752 return this.runOne();
16755 call(fn, returnWith) {
16756 if (returnWith) this.next(returnWith);
16757 this.stack.push(this.state);
16758 this.state = new State(fn);
16761 callNow(fn, returnWith) {
16762 this.call(fn, returnWith);
16763 return this.runOne();
16767 /* istanbul ignore next */
16768 if (this.stack.length === 0) throw this.error(new ParserError('Stack underflow'));
16769 if (value === undefined) value = this.state.buf;
16770 this.state = this.stack.pop();
16771 this.state.returned = value;
16775 this.return(value);
16776 return this.runOne();
16780 /* istanbul ignore next */
16781 if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer'));
16782 this.state.buf += this._buf[this.ii];
16786 err.line = this.line;
16787 err.col = this.col;
16788 err.pos = this.pos;
16791 /* istanbul ignore next */
16795 throw new ParserError('Must declare a parseStart method');
16800 Parser.END = ParserEND;
16801 Parser.Error = ParserError;
16802 var parser$1 = Parser;
16804 var createDatetime = value => {
16805 const date = new Date(value);
16806 /* istanbul ignore if */
16809 throw new TypeError('Invalid Datetime');
16815 var formatNum = (d, num) => {
16818 while (num.length < d) num = '0' + num;
16823 class FloatingDateTime extends Date {
16824 constructor(value) {
16825 super(value + 'Z');
16826 this.isFloating = true;
16830 const date = `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`;
16831 const time = `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`;
16832 return `${date}T${time}`;
16837 var createDatetimeFloat = value => {
16838 const date = new FloatingDateTime(value);
16839 /* istanbul ignore if */
16842 throw new TypeError('Invalid Datetime');
16848 const DateTime = global.Date;
16850 class Date$1 extends DateTime {
16851 constructor(value) {
16853 this.isDate = true;
16857 return `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`;
16862 var createDate = value => {
16863 const date = new Date$1(value);
16864 /* istanbul ignore if */
16867 throw new TypeError('Invalid Datetime');
16873 class Time extends Date {
16874 constructor(value) {
16875 super(`0000-01-01T${value}Z`);
16876 this.isTime = true;
16880 return `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`;
16885 var createTime = value => {
16886 const date = new Time(value);
16887 /* istanbul ignore if */
16890 throw new TypeError('Invalid Datetime');
16896 /* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */
16899 var tomlParser = makeParserClass(parser$1);
16900 var makeParserClass_1 = makeParserClass;
16902 class TomlError extends Error {
16905 this.name = 'TomlError';
16906 /* istanbul ignore next */
16908 if (Error.captureStackTrace) Error.captureStackTrace(this, TomlError);
16909 this.fromTOML = true;
16910 this.wrapped = null;
16915 TomlError.wrap = err => {
16916 const terr = new TomlError(err.message);
16917 terr.code = err.code;
16918 terr.wrapped = err;
16922 var TomlError_1 = TomlError;
16923 const CTRL_I = 0x09;
16924 const CTRL_J = 0x0A;
16925 const CTRL_M = 0x0D;
16926 const CTRL_CHAR_BOUNDARY = 0x1F; // the last non-character in the latin1 region of unicode, except DEL
16928 const CHAR_SP = 0x20;
16929 const CHAR_QUOT = 0x22;
16930 const CHAR_NUM = 0x23;
16931 const CHAR_APOS = 0x27;
16932 const CHAR_PLUS = 0x2B;
16933 const CHAR_COMMA = 0x2C;
16934 const CHAR_HYPHEN = 0x2D;
16935 const CHAR_PERIOD = 0x2E;
16936 const CHAR_0 = 0x30;
16937 const CHAR_1 = 0x31;
16938 const CHAR_7 = 0x37;
16939 const CHAR_9 = 0x39;
16940 const CHAR_COLON = 0x3A;
16941 const CHAR_EQUALS = 0x3D;
16942 const CHAR_A = 0x41;
16943 const CHAR_E = 0x45;
16944 const CHAR_F = 0x46;
16945 const CHAR_T = 0x54;
16946 const CHAR_U = 0x55;
16947 const CHAR_Z = 0x5A;
16948 const CHAR_LOWBAR = 0x5F;
16949 const CHAR_a = 0x61;
16950 const CHAR_b = 0x62;
16951 const CHAR_e = 0x65;
16952 const CHAR_f = 0x66;
16953 const CHAR_i = 0x69;
16954 const CHAR_l = 0x6C;
16955 const CHAR_n = 0x6E;
16956 const CHAR_o = 0x6F;
16957 const CHAR_r = 0x72;
16958 const CHAR_s = 0x73;
16959 const CHAR_t = 0x74;
16960 const CHAR_u = 0x75;
16961 const CHAR_x = 0x78;
16962 const CHAR_z = 0x7A;
16963 const CHAR_LCUB = 0x7B;
16964 const CHAR_RCUB = 0x7D;
16965 const CHAR_LSQB = 0x5B;
16966 const CHAR_BSOL = 0x5C;
16967 const CHAR_RSQB = 0x5D;
16968 const CHAR_DEL = 0x7F;
16969 const SURROGATE_FIRST = 0xD800;
16970 const SURROGATE_LAST = 0xDFFF;
16972 [CHAR_b]: '\u0008',
16973 [CHAR_t]: '\u0009',
16974 [CHAR_n]: '\u000A',
16975 [CHAR_f]: '\u000C',
16976 [CHAR_r]: '\u000D',
16977 [CHAR_QUOT]: '\u0022',
16978 [CHAR_BSOL]: '\u005C'
16981 function isDigit(cp) {
16982 return cp >= CHAR_0 && cp <= CHAR_9;
16985 function isHexit(cp) {
16986 return cp >= CHAR_A && cp <= CHAR_F || cp >= CHAR_a && cp <= CHAR_f || cp >= CHAR_0 && cp <= CHAR_9;
16989 function isBit(cp) {
16990 return cp === CHAR_1 || cp === CHAR_0;
16993 function isOctit(cp) {
16994 return cp >= CHAR_0 && cp <= CHAR_7;
16997 function isAlphaNumQuoteHyphen(cp) {
16998 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;
17001 function isAlphaNumHyphen(cp) {
17002 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;
17005 const _type = Symbol('type');
17007 const _declared = Symbol('declared');
17009 const hasOwnProperty$2 = Object.prototype.hasOwnProperty;
17010 const defineProperty = Object.defineProperty;
17011 const descriptor = {
17012 configurable: true,
17018 function hasKey(obj, key) {
17019 if (hasOwnProperty$2.call(obj, key)) return true;
17020 if (key === '__proto__') defineProperty(obj, '__proto__', descriptor);
17024 const INLINE_TABLE = Symbol('inline-table');
17026 function InlineTable() {
17027 return Object.defineProperties({}, {
17029 value: INLINE_TABLE
17034 function isInlineTable(obj) {
17035 if (obj === null || typeof obj !== 'object') return false;
17036 return obj[_type] === INLINE_TABLE;
17039 const TABLE = Symbol('table');
17042 return Object.defineProperties({}, {
17053 function isTable(obj) {
17054 if (obj === null || typeof obj !== 'object') return false;
17055 return obj[_type] === TABLE;
17058 const _contentType = Symbol('content-type');
17060 const INLINE_LIST = Symbol('inline-list');
17062 function InlineList(type) {
17063 return Object.defineProperties([], {
17073 function isInlineList(obj) {
17074 if (obj === null || typeof obj !== 'object') return false;
17075 return obj[_type] === INLINE_LIST;
17078 const LIST = Symbol('list');
17081 return Object.defineProperties([], {
17088 function isList(obj) {
17089 if (obj === null || typeof obj !== 'object') return false;
17090 return obj[_type] === LIST;
17091 } // in an eval, to let bundlers not slurp in a util proxy
17097 const utilInspect = util__default['default'].inspect;
17098 _custom = utilInspect.custom;
17100 /* eval require not available in transpiled bundle */
17102 /* istanbul ignore next */
17105 const _inspect = _custom || 'inspect';
17107 class BoxedBigInt {
17108 constructor(value) {
17110 this.value = global.BigInt.asIntN(64, value);
17112 /* istanbul ignore next */
17116 Object.defineProperty(this, _type, {
17122 return this.value === null;
17124 /* istanbul ignore next */
17128 return String(this.value);
17130 /* istanbul ignore next */
17134 return `[BigInt: ${this.toString()}]}`;
17143 const INTEGER = Symbol('integer');
17145 function Integer(value) {
17146 let num = Number(value); // -0 is a float thing, not an int thing
17148 if (Object.is(num, -0)) num = 0;
17149 /* istanbul ignore else */
17151 if (global.BigInt && !Number.isSafeInteger(num)) {
17152 return new BoxedBigInt(value);
17154 /* istanbul ignore next */
17155 return Object.defineProperties(new Number(num), {
17157 value: function () {
17158 return isNaN(this);
17165 value: () => `[Integer: ${value}]`
17171 function isInteger(obj) {
17172 if (obj === null || typeof obj !== 'object') return false;
17173 return obj[_type] === INTEGER;
17176 const FLOAT = Symbol('float');
17178 function Float(value) {
17179 /* istanbul ignore next */
17180 return Object.defineProperties(new Number(value), {
17185 value: () => `[Float: ${value}]`
17190 function isFloat(obj) {
17191 if (obj === null || typeof obj !== 'object') return false;
17192 return obj[_type] === FLOAT;
17195 function tomlType(value) {
17196 const type = typeof value;
17198 if (type === 'object') {
17199 /* istanbul ignore if */
17200 if (value === null) return 'null';
17201 if (value instanceof Date) return 'datetime';
17202 /* istanbul ignore else */
17204 if (_type in value) {
17205 switch (value[_type]) {
17207 return 'inline-table';
17210 return 'inline-list';
17212 /* istanbul ignore next */
17217 /* istanbul ignore next */
17234 function makeParserClass(Parser) {
17235 class TOMLParser extends Parser {
17238 this.ctx = this.obj = Table();
17244 return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine();
17248 return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M;
17252 if (this.char === Parser.END) {
17254 } else if (this.char === CHAR_LSQB) {
17255 return this.call(this.parseTableOrList);
17256 } else if (this.char === CHAR_NUM) {
17257 return this.call(this.parseComment);
17258 } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
17260 } else if (isAlphaNumQuoteHyphen(this.char)) {
17261 return this.callNow(this.parseAssignStatement);
17263 throw this.error(new TomlError(`Unknown character "${this.char}"`));
17265 } // HELPER, this strips any whitespace and comments to the end of the line
17266 // then RETURNS. Last state in a production.
17269 parseWhitespaceToEOL() {
17270 if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
17272 } else if (this.char === CHAR_NUM) {
17273 return this.goto(this.parseComment);
17274 } else if (this.char === Parser.END || this.char === CTRL_J) {
17275 return this.return();
17277 throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line'));
17280 /* ASSIGNMENT: key = value */
17283 parseAssignStatement() {
17284 return this.callNow(this.parseAssign, this.recordAssignStatement);
17287 recordAssignStatement(kv) {
17288 let target = this.ctx;
17289 let finalKey = kv.key.pop();
17291 for (let kw of kv.key) {
17292 if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
17293 throw this.error(new TomlError("Can't redefine existing key"));
17296 target = target[kw] = target[kw] || Table();
17299 if (hasKey(target, finalKey)) {
17300 throw this.error(new TomlError("Can't redefine existing key"));
17301 } // unbox our numbers
17304 if (isInteger(kv.value) || isFloat(kv.value)) {
17305 target[finalKey] = kv.value.valueOf();
17307 target[finalKey] = kv.value;
17310 return this.goto(this.parseWhitespaceToEOL);
17312 /* ASSSIGNMENT expression, key = value possibly inside an inline table */
17316 return this.callNow(this.parseKeyword, this.recordAssignKeyword);
17319 recordAssignKeyword(key) {
17320 if (this.state.resultTable) {
17321 this.state.resultTable.push(key);
17323 this.state.resultTable = [key];
17326 return this.goto(this.parseAssignKeywordPreDot);
17329 parseAssignKeywordPreDot() {
17330 if (this.char === CHAR_PERIOD) {
17331 return this.next(this.parseAssignKeywordPostDot);
17332 } else if (this.char !== CHAR_SP && this.char !== CTRL_I) {
17333 return this.goto(this.parseAssignEqual);
17337 parseAssignKeywordPostDot() {
17338 if (this.char !== CHAR_SP && this.char !== CTRL_I) {
17339 return this.callNow(this.parseKeyword, this.recordAssignKeyword);
17343 parseAssignEqual() {
17344 if (this.char === CHAR_EQUALS) {
17345 return this.next(this.parseAssignPreValue);
17347 throw this.error(new TomlError('Invalid character, expected "="'));
17351 parseAssignPreValue() {
17352 if (this.char === CHAR_SP || this.char === CTRL_I) {
17355 return this.callNow(this.parseValue, this.recordAssignValue);
17359 recordAssignValue(value) {
17360 return this.returnNow({
17361 key: this.state.resultTable,
17365 /* COMMENTS: #...eol */
17370 if (this.char === Parser.END || this.char === CTRL_J) {
17371 return this.return();
17373 } while (this.nextChar());
17375 /* TABLES AND LISTS, [foo] and [[foo]] */
17378 parseTableOrList() {
17379 if (this.char === CHAR_LSQB) {
17380 this.next(this.parseList);
17382 return this.goto(this.parseTable);
17385 /* TABLE [foo.bar.baz] */
17389 this.ctx = this.obj;
17390 return this.goto(this.parseTableNext);
17394 if (this.char === CHAR_SP || this.char === CTRL_I) {
17397 return this.callNow(this.parseKeyword, this.parseTableMore);
17401 parseTableMore(keyword) {
17402 if (this.char === CHAR_SP || this.char === CTRL_I) {
17404 } else if (this.char === CHAR_RSQB) {
17405 if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {
17406 throw this.error(new TomlError("Can't redefine existing key"));
17408 this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table();
17409 this.ctx[_declared] = true;
17412 return this.next(this.parseWhitespaceToEOL);
17413 } else if (this.char === CHAR_PERIOD) {
17414 if (!hasKey(this.ctx, keyword)) {
17415 this.ctx = this.ctx[keyword] = Table();
17416 } else if (isTable(this.ctx[keyword])) {
17417 this.ctx = this.ctx[keyword];
17418 } else if (isList(this.ctx[keyword])) {
17419 this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
17421 throw this.error(new TomlError("Can't redefine existing key"));
17424 return this.next(this.parseTableNext);
17426 throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
17429 /* LIST [[a.b.c]] */
17433 this.ctx = this.obj;
17434 return this.goto(this.parseListNext);
17438 if (this.char === CHAR_SP || this.char === CTRL_I) {
17441 return this.callNow(this.parseKeyword, this.parseListMore);
17445 parseListMore(keyword) {
17446 if (this.char === CHAR_SP || this.char === CTRL_I) {
17448 } else if (this.char === CHAR_RSQB) {
17449 if (!hasKey(this.ctx, keyword)) {
17450 this.ctx[keyword] = List();
17453 if (isInlineList(this.ctx[keyword])) {
17454 throw this.error(new TomlError("Can't extend an inline array"));
17455 } else if (isList(this.ctx[keyword])) {
17456 const next = Table();
17457 this.ctx[keyword].push(next);
17460 throw this.error(new TomlError("Can't redefine an existing key"));
17463 return this.next(this.parseListEnd);
17464 } else if (this.char === CHAR_PERIOD) {
17465 if (!hasKey(this.ctx, keyword)) {
17466 this.ctx = this.ctx[keyword] = Table();
17467 } else if (isInlineList(this.ctx[keyword])) {
17468 throw this.error(new TomlError("Can't extend an inline array"));
17469 } else if (isInlineTable(this.ctx[keyword])) {
17470 throw this.error(new TomlError("Can't extend an inline table"));
17471 } else if (isList(this.ctx[keyword])) {
17472 this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
17473 } else if (isTable(this.ctx[keyword])) {
17474 this.ctx = this.ctx[keyword];
17476 throw this.error(new TomlError("Can't redefine an existing key"));
17479 return this.next(this.parseListNext);
17481 throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
17485 parseListEnd(keyword) {
17486 if (this.char === CHAR_RSQB) {
17487 return this.next(this.parseWhitespaceToEOL);
17489 throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
17492 /* VALUE string, number, boolean, inline list, inline object */
17496 if (this.char === Parser.END) {
17497 throw this.error(new TomlError('Key without value'));
17498 } else if (this.char === CHAR_QUOT) {
17499 return this.next(this.parseDoubleString);
17502 if (this.char === CHAR_APOS) {
17503 return this.next(this.parseSingleString);
17504 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
17505 return this.goto(this.parseNumberSign);
17506 } else if (this.char === CHAR_i) {
17507 return this.next(this.parseInf);
17508 } else if (this.char === CHAR_n) {
17509 return this.next(this.parseNan);
17510 } else if (isDigit(this.char)) {
17511 return this.goto(this.parseNumberOrDateTime);
17512 } else if (this.char === CHAR_t || this.char === CHAR_f) {
17513 return this.goto(this.parseBoolean);
17514 } else if (this.char === CHAR_LSQB) {
17515 return this.call(this.parseInlineList, this.recordValue);
17516 } else if (this.char === CHAR_LCUB) {
17517 return this.call(this.parseInlineTable, this.recordValue);
17519 throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table'));
17523 recordValue(value) {
17524 return this.returnNow(value);
17528 if (this.char === CHAR_n) {
17529 return this.next(this.parseInf2);
17531 throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
17536 if (this.char === CHAR_f) {
17537 if (this.state.buf === '-') {
17538 return this.return(-Infinity);
17540 return this.return(Infinity);
17543 throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
17548 if (this.char === CHAR_a) {
17549 return this.next(this.parseNan2);
17551 throw this.error(new TomlError('Unexpected character, expected "nan"'));
17556 if (this.char === CHAR_n) {
17557 return this.return(NaN);
17559 throw this.error(new TomlError('Unexpected character, expected "nan"'));
17562 /* KEYS, barewords or basic, literal, or dotted */
17566 if (this.char === CHAR_QUOT) {
17567 return this.next(this.parseBasicString);
17568 } else if (this.char === CHAR_APOS) {
17569 return this.next(this.parseLiteralString);
17571 return this.goto(this.parseBareKey);
17574 /* KEYS: barewords */
17579 if (this.char === Parser.END) {
17580 throw this.error(new TomlError('Key ended without value'));
17581 } else if (isAlphaNumHyphen(this.char)) {
17583 } else if (this.state.buf.length === 0) {
17584 throw this.error(new TomlError('Empty bare keys are not allowed'));
17586 return this.returnNow();
17588 } while (this.nextChar());
17590 /* STRINGS, single quoted (literal) */
17593 parseSingleString() {
17594 if (this.char === CHAR_APOS) {
17595 return this.next(this.parseLiteralMultiStringMaybe);
17597 return this.goto(this.parseLiteralString);
17601 parseLiteralString() {
17603 if (this.char === CHAR_APOS) {
17604 return this.return();
17605 } else if (this.atEndOfLine()) {
17606 throw this.error(new TomlError('Unterminated string'));
17607 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
17608 throw this.errorControlCharInString();
17612 } while (this.nextChar());
17615 parseLiteralMultiStringMaybe() {
17616 if (this.char === CHAR_APOS) {
17617 return this.next(this.parseLiteralMultiString);
17619 return this.returnNow();
17623 parseLiteralMultiString() {
17624 if (this.char === CTRL_M) {
17626 } else if (this.char === CTRL_J) {
17627 return this.next(this.parseLiteralMultiStringContent);
17629 return this.goto(this.parseLiteralMultiStringContent);
17633 parseLiteralMultiStringContent() {
17635 if (this.char === CHAR_APOS) {
17636 return this.next(this.parseLiteralMultiEnd);
17637 } else if (this.char === Parser.END) {
17638 throw this.error(new TomlError('Unterminated multi-line string'));
17639 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
17640 throw this.errorControlCharInString();
17644 } while (this.nextChar());
17647 parseLiteralMultiEnd() {
17648 if (this.char === CHAR_APOS) {
17649 return this.next(this.parseLiteralMultiEnd2);
17651 this.state.buf += "'";
17652 return this.goto(this.parseLiteralMultiStringContent);
17656 parseLiteralMultiEnd2() {
17657 if (this.char === CHAR_APOS) {
17658 return this.return();
17660 this.state.buf += "''";
17661 return this.goto(this.parseLiteralMultiStringContent);
17664 /* STRINGS double quoted */
17667 parseDoubleString() {
17668 if (this.char === CHAR_QUOT) {
17669 return this.next(this.parseMultiStringMaybe);
17671 return this.goto(this.parseBasicString);
17675 parseBasicString() {
17677 if (this.char === CHAR_BSOL) {
17678 return this.call(this.parseEscape, this.recordEscapeReplacement);
17679 } else if (this.char === CHAR_QUOT) {
17680 return this.return();
17681 } else if (this.atEndOfLine()) {
17682 throw this.error(new TomlError('Unterminated string'));
17683 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
17684 throw this.errorControlCharInString();
17688 } while (this.nextChar());
17691 recordEscapeReplacement(replacement) {
17692 this.state.buf += replacement;
17693 return this.goto(this.parseBasicString);
17696 parseMultiStringMaybe() {
17697 if (this.char === CHAR_QUOT) {
17698 return this.next(this.parseMultiString);
17700 return this.returnNow();
17704 parseMultiString() {
17705 if (this.char === CTRL_M) {
17707 } else if (this.char === CTRL_J) {
17708 return this.next(this.parseMultiStringContent);
17710 return this.goto(this.parseMultiStringContent);
17714 parseMultiStringContent() {
17716 if (this.char === CHAR_BSOL) {
17717 return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement);
17718 } else if (this.char === CHAR_QUOT) {
17719 return this.next(this.parseMultiEnd);
17720 } else if (this.char === Parser.END) {
17721 throw this.error(new TomlError('Unterminated multi-line string'));
17722 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
17723 throw this.errorControlCharInString();
17727 } while (this.nextChar());
17730 errorControlCharInString() {
17731 let displayCode = '\\u00';
17733 if (this.char < 16) {
17734 displayCode += '0';
17737 displayCode += this.char.toString(16);
17738 return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`));
17741 recordMultiEscapeReplacement(replacement) {
17742 this.state.buf += replacement;
17743 return this.goto(this.parseMultiStringContent);
17747 if (this.char === CHAR_QUOT) {
17748 return this.next(this.parseMultiEnd2);
17750 this.state.buf += '"';
17751 return this.goto(this.parseMultiStringContent);
17756 if (this.char === CHAR_QUOT) {
17757 return this.return();
17759 this.state.buf += '""';
17760 return this.goto(this.parseMultiStringContent);
17764 parseMultiEscape() {
17765 if (this.char === CTRL_M || this.char === CTRL_J) {
17766 return this.next(this.parseMultiTrim);
17767 } else if (this.char === CHAR_SP || this.char === CTRL_I) {
17768 return this.next(this.parsePreMultiTrim);
17770 return this.goto(this.parseEscape);
17774 parsePreMultiTrim() {
17775 if (this.char === CHAR_SP || this.char === CTRL_I) {
17777 } else if (this.char === CTRL_M || this.char === CTRL_J) {
17778 return this.next(this.parseMultiTrim);
17780 throw this.error(new TomlError("Can't escape whitespace"));
17785 // explicitly whitespace here, END should follow the same path as chars
17786 if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
17789 return this.returnNow();
17794 if (this.char in escapes) {
17795 return this.return(escapes[this.char]);
17796 } else if (this.char === CHAR_u) {
17797 return this.call(this.parseSmallUnicode, this.parseUnicodeReturn);
17798 } else if (this.char === CHAR_U) {
17799 return this.call(this.parseLargeUnicode, this.parseUnicodeReturn);
17801 throw this.error(new TomlError('Unknown escape character: ' + this.char));
17805 parseUnicodeReturn(char) {
17807 const codePoint = parseInt(char, 16);
17809 if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {
17810 throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved'));
17813 return this.returnNow(String.fromCodePoint(codePoint));
17815 throw this.error(TomlError.wrap(err));
17819 parseSmallUnicode() {
17820 if (!isHexit(this.char)) {
17821 throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'));
17824 if (this.state.buf.length >= 4) return this.return();
17828 parseLargeUnicode() {
17829 if (!isHexit(this.char)) {
17830 throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'));
17833 if (this.state.buf.length >= 8) return this.return();
17839 parseNumberSign() {
17841 return this.next(this.parseMaybeSignedInfOrNan);
17844 parseMaybeSignedInfOrNan() {
17845 if (this.char === CHAR_i) {
17846 return this.next(this.parseInf);
17847 } else if (this.char === CHAR_n) {
17848 return this.next(this.parseNan);
17850 return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart);
17854 parseNumberIntegerStart() {
17855 if (this.char === CHAR_0) {
17857 return this.next(this.parseNumberIntegerExponentOrDecimal);
17859 return this.goto(this.parseNumberInteger);
17863 parseNumberIntegerExponentOrDecimal() {
17864 if (this.char === CHAR_PERIOD) {
17866 return this.call(this.parseNoUnder, this.parseNumberFloat);
17867 } else if (this.char === CHAR_E || this.char === CHAR_e) {
17869 return this.next(this.parseNumberExponentSign);
17871 return this.returnNow(Integer(this.state.buf));
17875 parseNumberInteger() {
17876 if (isDigit(this.char)) {
17878 } else if (this.char === CHAR_LOWBAR) {
17879 return this.call(this.parseNoUnder);
17880 } else if (this.char === CHAR_E || this.char === CHAR_e) {
17882 return this.next(this.parseNumberExponentSign);
17883 } else if (this.char === CHAR_PERIOD) {
17885 return this.call(this.parseNoUnder, this.parseNumberFloat);
17887 const result = Integer(this.state.buf);
17888 /* istanbul ignore if */
17890 if (result.isNaN()) {
17891 throw this.error(new TomlError('Invalid number'));
17893 return this.returnNow(result);
17899 if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) {
17900 throw this.error(new TomlError('Unexpected character, expected digit'));
17901 } else if (this.atEndOfWord()) {
17902 throw this.error(new TomlError('Incomplete number'));
17905 return this.returnNow();
17908 parseNoUnderHexOctBinLiteral() {
17909 if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD) {
17910 throw this.error(new TomlError('Unexpected character, expected digit'));
17911 } else if (this.atEndOfWord()) {
17912 throw this.error(new TomlError('Incomplete number'));
17915 return this.returnNow();
17918 parseNumberFloat() {
17919 if (this.char === CHAR_LOWBAR) {
17920 return this.call(this.parseNoUnder, this.parseNumberFloat);
17921 } else if (isDigit(this.char)) {
17923 } else if (this.char === CHAR_E || this.char === CHAR_e) {
17925 return this.next(this.parseNumberExponentSign);
17927 return this.returnNow(Float(this.state.buf));
17931 parseNumberExponentSign() {
17932 if (isDigit(this.char)) {
17933 return this.goto(this.parseNumberExponent);
17934 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
17936 this.call(this.parseNoUnder, this.parseNumberExponent);
17938 throw this.error(new TomlError('Unexpected character, expected -, + or digit'));
17942 parseNumberExponent() {
17943 if (isDigit(this.char)) {
17945 } else if (this.char === CHAR_LOWBAR) {
17946 return this.call(this.parseNoUnder);
17948 return this.returnNow(Float(this.state.buf));
17951 /* NUMBERS or DATETIMES */
17954 parseNumberOrDateTime() {
17955 if (this.char === CHAR_0) {
17957 return this.next(this.parseNumberBaseOrDateTime);
17959 return this.goto(this.parseNumberOrDateTimeOnly);
17963 parseNumberOrDateTimeOnly() {
17964 // note, if two zeros are in a row then it MUST be a date
17965 if (this.char === CHAR_LOWBAR) {
17966 return this.call(this.parseNoUnder, this.parseNumberInteger);
17967 } else if (isDigit(this.char)) {
17969 if (this.state.buf.length > 4) this.next(this.parseNumberInteger);
17970 } else if (this.char === CHAR_E || this.char === CHAR_e) {
17972 return this.next(this.parseNumberExponentSign);
17973 } else if (this.char === CHAR_PERIOD) {
17975 return this.call(this.parseNoUnder, this.parseNumberFloat);
17976 } else if (this.char === CHAR_HYPHEN) {
17977 return this.goto(this.parseDateTime);
17978 } else if (this.char === CHAR_COLON) {
17979 return this.goto(this.parseOnlyTimeHour);
17981 return this.returnNow(Integer(this.state.buf));
17985 parseDateTimeOnly() {
17986 if (this.state.buf.length < 4) {
17987 if (isDigit(this.char)) {
17988 return this.consume();
17989 } else if (this.char === CHAR_COLON) {
17990 return this.goto(this.parseOnlyTimeHour);
17992 throw this.error(new TomlError('Expected digit while parsing year part of a date'));
17995 if (this.char === CHAR_HYPHEN) {
17996 return this.goto(this.parseDateTime);
17998 throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date'));
18003 parseNumberBaseOrDateTime() {
18004 if (this.char === CHAR_b) {
18006 return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerBin);
18007 } else if (this.char === CHAR_o) {
18009 return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerOct);
18010 } else if (this.char === CHAR_x) {
18012 return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerHex);
18013 } else if (this.char === CHAR_PERIOD) {
18014 return this.goto(this.parseNumberInteger);
18015 } else if (isDigit(this.char)) {
18016 return this.goto(this.parseDateTimeOnly);
18018 return this.returnNow(Integer(this.state.buf));
18022 parseIntegerHex() {
18023 if (isHexit(this.char)) {
18025 } else if (this.char === CHAR_LOWBAR) {
18026 return this.call(this.parseNoUnderHexOctBinLiteral);
18028 const result = Integer(this.state.buf);
18029 /* istanbul ignore if */
18031 if (result.isNaN()) {
18032 throw this.error(new TomlError('Invalid number'));
18034 return this.returnNow(result);
18039 parseIntegerOct() {
18040 if (isOctit(this.char)) {
18042 } else if (this.char === CHAR_LOWBAR) {
18043 return this.call(this.parseNoUnderHexOctBinLiteral);
18045 const result = Integer(this.state.buf);
18046 /* istanbul ignore if */
18048 if (result.isNaN()) {
18049 throw this.error(new TomlError('Invalid number'));
18051 return this.returnNow(result);
18056 parseIntegerBin() {
18057 if (isBit(this.char)) {
18059 } else if (this.char === CHAR_LOWBAR) {
18060 return this.call(this.parseNoUnderHexOctBinLiteral);
18062 const result = Integer(this.state.buf);
18063 /* istanbul ignore if */
18065 if (result.isNaN()) {
18066 throw this.error(new TomlError('Invalid number'));
18068 return this.returnNow(result);
18076 // we enter here having just consumed the year and about to consume the hyphen
18077 if (this.state.buf.length < 4) {
18078 throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters'));
18081 this.state.result = this.state.buf;
18082 this.state.buf = '';
18083 return this.next(this.parseDateMonth);
18087 if (this.char === CHAR_HYPHEN) {
18088 if (this.state.buf.length < 2) {
18089 throw this.error(new TomlError('Months less than 10 must be zero padded to two characters'));
18092 this.state.result += '-' + this.state.buf;
18093 this.state.buf = '';
18094 return this.next(this.parseDateDay);
18095 } else if (isDigit(this.char)) {
18098 throw this.error(new TomlError('Incomplete datetime'));
18103 if (this.char === CHAR_T || this.char === CHAR_SP) {
18104 if (this.state.buf.length < 2) {
18105 throw this.error(new TomlError('Days less than 10 must be zero padded to two characters'));
18108 this.state.result += '-' + this.state.buf;
18109 this.state.buf = '';
18110 return this.next(this.parseStartTimeHour);
18111 } else if (this.atEndOfWord()) {
18112 return this.returnNow(createDate(this.state.result + '-' + this.state.buf));
18113 } else if (isDigit(this.char)) {
18116 throw this.error(new TomlError('Incomplete datetime'));
18120 parseStartTimeHour() {
18121 if (this.atEndOfWord()) {
18122 return this.returnNow(createDate(this.state.result));
18124 return this.goto(this.parseTimeHour);
18129 if (this.char === CHAR_COLON) {
18130 if (this.state.buf.length < 2) {
18131 throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'));
18134 this.state.result += 'T' + this.state.buf;
18135 this.state.buf = '';
18136 return this.next(this.parseTimeMin);
18137 } else if (isDigit(this.char)) {
18140 throw this.error(new TomlError('Incomplete datetime'));
18145 if (this.state.buf.length < 2 && isDigit(this.char)) {
18147 } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
18148 this.state.result += ':' + this.state.buf;
18149 this.state.buf = '';
18150 return this.next(this.parseTimeSec);
18152 throw this.error(new TomlError('Incomplete datetime'));
18157 if (isDigit(this.char)) {
18160 if (this.state.buf.length === 2) {
18161 this.state.result += ':' + this.state.buf;
18162 this.state.buf = '';
18163 return this.next(this.parseTimeZoneOrFraction);
18166 throw this.error(new TomlError('Incomplete datetime'));
18170 parseOnlyTimeHour() {
18171 /* istanbul ignore else */
18172 if (this.char === CHAR_COLON) {
18173 if (this.state.buf.length < 2) {
18174 throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'));
18177 this.state.result = this.state.buf;
18178 this.state.buf = '';
18179 return this.next(this.parseOnlyTimeMin);
18181 throw this.error(new TomlError('Incomplete time'));
18185 parseOnlyTimeMin() {
18186 if (this.state.buf.length < 2 && isDigit(this.char)) {
18188 } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
18189 this.state.result += ':' + this.state.buf;
18190 this.state.buf = '';
18191 return this.next(this.parseOnlyTimeSec);
18193 throw this.error(new TomlError('Incomplete time'));
18197 parseOnlyTimeSec() {
18198 if (isDigit(this.char)) {
18201 if (this.state.buf.length === 2) {
18202 return this.next(this.parseOnlyTimeFractionMaybe);
18205 throw this.error(new TomlError('Incomplete time'));
18209 parseOnlyTimeFractionMaybe() {
18210 this.state.result += ':' + this.state.buf;
18212 if (this.char === CHAR_PERIOD) {
18213 this.state.buf = '';
18214 this.next(this.parseOnlyTimeFraction);
18216 return this.return(createTime(this.state.result));
18220 parseOnlyTimeFraction() {
18221 if (isDigit(this.char)) {
18223 } else if (this.atEndOfWord()) {
18224 if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds'));
18225 return this.returnNow(createTime(this.state.result + '.' + this.state.buf));
18227 throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
18231 parseTimeZoneOrFraction() {
18232 if (this.char === CHAR_PERIOD) {
18234 this.next(this.parseDateTimeFraction);
18235 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
18237 this.next(this.parseTimeZoneHour);
18238 } else if (this.char === CHAR_Z) {
18240 return this.return(createDatetime(this.state.result + this.state.buf));
18241 } else if (this.atEndOfWord()) {
18242 return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf));
18244 throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
18248 parseDateTimeFraction() {
18249 if (isDigit(this.char)) {
18251 } else if (this.state.buf.length === 1) {
18252 throw this.error(new TomlError('Expected digit in milliseconds'));
18253 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
18255 this.next(this.parseTimeZoneHour);
18256 } else if (this.char === CHAR_Z) {
18258 return this.return(createDatetime(this.state.result + this.state.buf));
18259 } else if (this.atEndOfWord()) {
18260 return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf));
18262 throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
18266 parseTimeZoneHour() {
18267 if (isDigit(this.char)) {
18268 this.consume(); // FIXME: No more regexps
18270 if (/\d\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep);
18272 throw this.error(new TomlError('Unexpected character in datetime, expected digit'));
18276 parseTimeZoneSep() {
18277 if (this.char === CHAR_COLON) {
18279 this.next(this.parseTimeZoneMin);
18281 throw this.error(new TomlError('Unexpected character in datetime, expected colon'));
18285 parseTimeZoneMin() {
18286 if (isDigit(this.char)) {
18288 if (/\d\d$/.test(this.state.buf)) return this.return(createDatetime(this.state.result + this.state.buf));
18290 throw this.error(new TomlError('Unexpected character in datetime, expected digit'));
18297 /* istanbul ignore else */
18298 if (this.char === CHAR_t) {
18300 return this.next(this.parseTrue_r);
18301 } else if (this.char === CHAR_f) {
18303 return this.next(this.parseFalse_a);
18308 if (this.char === CHAR_r) {
18310 return this.next(this.parseTrue_u);
18312 throw this.error(new TomlError('Invalid boolean, expected true or false'));
18317 if (this.char === CHAR_u) {
18319 return this.next(this.parseTrue_e);
18321 throw this.error(new TomlError('Invalid boolean, expected true or false'));
18326 if (this.char === CHAR_e) {
18327 return this.return(true);
18329 throw this.error(new TomlError('Invalid boolean, expected true or false'));
18334 if (this.char === CHAR_a) {
18336 return this.next(this.parseFalse_l);
18338 throw this.error(new TomlError('Invalid boolean, expected true or false'));
18343 if (this.char === CHAR_l) {
18345 return this.next(this.parseFalse_s);
18347 throw this.error(new TomlError('Invalid boolean, expected true or false'));
18352 if (this.char === CHAR_s) {
18354 return this.next(this.parseFalse_e);
18356 throw this.error(new TomlError('Invalid boolean, expected true or false'));
18361 if (this.char === CHAR_e) {
18362 return this.return(false);
18364 throw this.error(new TomlError('Invalid boolean, expected true or false'));
18370 parseInlineList() {
18371 if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
18373 } else if (this.char === Parser.END) {
18374 throw this.error(new TomlError('Unterminated inline array'));
18375 } else if (this.char === CHAR_NUM) {
18376 return this.call(this.parseComment);
18377 } else if (this.char === CHAR_RSQB) {
18378 return this.return(this.state.resultArr || InlineList());
18380 return this.callNow(this.parseValue, this.recordInlineListValue);
18384 recordInlineListValue(value) {
18385 if (this.state.resultArr) {
18386 const listType = this.state.resultArr[_contentType];
18387 const valueType = tomlType(value);
18389 if (listType !== valueType) {
18390 throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`));
18393 this.state.resultArr = InlineList(tomlType(value));
18396 if (isFloat(value) || isInteger(value)) {
18397 // unbox now that we've verified they're ok
18398 this.state.resultArr.push(value.valueOf());
18400 this.state.resultArr.push(value);
18403 return this.goto(this.parseInlineListNext);
18406 parseInlineListNext() {
18407 if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
18409 } else if (this.char === CHAR_NUM) {
18410 return this.call(this.parseComment);
18411 } else if (this.char === CHAR_COMMA) {
18412 return this.next(this.parseInlineList);
18413 } else if (this.char === CHAR_RSQB) {
18414 return this.goto(this.parseInlineList);
18416 throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'));
18422 parseInlineTable() {
18423 if (this.char === CHAR_SP || this.char === CTRL_I) {
18425 } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
18426 throw this.error(new TomlError('Unterminated inline array'));
18427 } else if (this.char === CHAR_RCUB) {
18428 return this.return(this.state.resultTable || InlineTable());
18430 if (!this.state.resultTable) this.state.resultTable = InlineTable();
18431 return this.callNow(this.parseAssign, this.recordInlineTableValue);
18435 recordInlineTableValue(kv) {
18436 let target = this.state.resultTable;
18437 let finalKey = kv.key.pop();
18439 for (let kw of kv.key) {
18440 if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
18441 throw this.error(new TomlError("Can't redefine existing key"));
18444 target = target[kw] = target[kw] || Table();
18447 if (hasKey(target, finalKey)) {
18448 throw this.error(new TomlError("Can't redefine existing key"));
18451 if (isInteger(kv.value) || isFloat(kv.value)) {
18452 target[finalKey] = kv.value.valueOf();
18454 target[finalKey] = kv.value;
18457 return this.goto(this.parseInlineTableNext);
18460 parseInlineTableNext() {
18461 if (this.char === CHAR_SP || this.char === CTRL_I) {
18463 } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
18464 throw this.error(new TomlError('Unterminated inline array'));
18465 } else if (this.char === CHAR_COMMA) {
18466 return this.next(this.parseInlineTable);
18467 } else if (this.char === CHAR_RCUB) {
18468 return this.goto(this.parseInlineTable);
18470 throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'));
18478 tomlParser.makeParserClass = makeParserClass_1;
18479 tomlParser.TomlError = TomlError_1;
18481 var parsePrettyError = prettyError;
18483 function prettyError(err, buf) {
18484 /* istanbul ignore if */
18485 if (err.pos == null || err.line == null) return err;
18486 let msg = err.message;
18487 msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\n`;
18488 /* istanbul ignore else */
18490 if (buf && buf.split) {
18491 const lines = buf.split(/\n/);
18492 const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length;
18493 let linePadding = ' ';
18495 while (linePadding.length < lineNumWidth) linePadding += ' ';
18497 for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {
18498 let lineNum = String(ii + 1);
18499 if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum;
18501 if (err.line === ii) {
18502 msg += lineNum + '> ' + lines[ii] + '\n';
18503 msg += linePadding + ' ';
18505 for (let hh = 0; hh < err.col; ++hh) {
18511 msg += lineNum + ': ' + lines[ii] + '\n';
18516 err.message = msg + '\n';
18520 var parseString_1 = parseString;
18522 function parseString(str) {
18523 if (global.Buffer && global.Buffer.isBuffer(str)) {
18524 str = str.toString('utf8');
18527 const parser = new tomlParser();
18531 return parser.finish();
18533 throw parsePrettyError(err, str);
18537 var loadToml = function (filePath, content) {
18539 return parseString_1(content);
18541 error.message = `TOML Error in ${filePath}:\n${error.message}`;
18546 // This is a generated file. Do not edit.
18547 var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
18548 var ID_Start = /[\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\u0860-\u086A\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\u09FC\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-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\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\uDF2D-\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\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\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\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\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\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;
18549 var ID_Continue = /[\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\u0860-\u086A\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\u09FC\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-\u0AFF\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\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\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-\u1CF9\u1D00-\u1DF9\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\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-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\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\uDF2D-\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\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\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\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\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\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/;
18551 Space_Separator: Space_Separator,
18552 ID_Start: ID_Start,
18553 ID_Continue: ID_Continue
18556 isSpaceSeparator(c) {
18557 return typeof c === 'string' && unicode.Space_Separator.test(c);
18561 return typeof c === 'string' && (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c === '$' || c === '_' || unicode.ID_Start.test(c));
18564 isIdContinueChar(c) {
18565 return typeof c === 'string' && (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c === '$' || c === '_' || c === '\u200C' || c === '\u200D' || unicode.ID_Continue.test(c));
18569 return typeof c === 'string' && /[0-9]/.test(c);
18573 return typeof c === 'string' && /[0-9A-Fa-f]/.test(c);
18587 var parse$2 = function parse(text, reviver) {
18588 source$1 = String(text);
18589 parseState = 'start';
18596 root$1 = undefined;
18599 token = lex(); // This code is unreachable.
18600 // if (!parseStates[parseState]) {
18601 // throw invalidParseState()
18604 parseStates[parseState]();
18605 } while (token.type !== 'eof');
18607 if (typeof reviver === 'function') {
18608 return internalize({
18616 function internalize(holder, name, reviver) {
18617 const value = holder[name];
18619 if (value != null && typeof value === 'object') {
18620 for (const key in value) {
18621 const replacement = internalize(value, key, reviver);
18623 if (replacement === undefined) {
18626 value[key] = replacement;
18631 return reviver.call(holder, name, value);
18641 lexState = 'default';
18643 doubleQuote = false;
18647 c = peek(); // This code is unreachable.
18648 // if (!lexStates[lexState]) {
18649 // throw invalidLexState(lexState)
18652 const token = lexStates[lexState]();
18661 if (source$1[pos]) {
18662 return String.fromCodePoint(source$1.codePointAt(pos));
18673 column += c.length;
18685 const lexStates = {
18703 lexState = 'comment';
18708 return newToken('eof');
18711 if (util$2.isSpaceSeparator(c)) {
18714 } // This code is unreachable.
18715 // if (!lexStates[parseState]) {
18716 // throw invalidLexState(parseState)
18720 return lexStates[parseState]();
18727 lexState = 'multiLineComment';
18732 lexState = 'singleLineComment';
18736 throw invalidChar(read());
18739 multiLineComment() {
18743 lexState = 'multiLineCommentAsterisk';
18747 throw invalidChar(read());
18753 multiLineCommentAsterisk() {
18761 lexState = 'default';
18765 throw invalidChar(read());
18769 lexState = 'multiLineComment';
18772 singleLineComment() {
18779 lexState = 'default';
18784 return newToken('eof');
18794 return newToken('punctuator', read());
18799 return newToken('null', null);
18804 return newToken('boolean', true);
18809 return newToken('boolean', false);
18813 if (read() === '-') {
18822 lexState = 'decimalPointLeading';
18840 lexState = 'decimalInteger';
18845 literal('nfinity');
18846 return newToken('numeric', Infinity);
18851 return newToken('numeric', NaN);
18855 doubleQuote = read() === '"';
18857 lexState = 'string';
18861 throw invalidChar(read());
18864 identifierNameStartEscape() {
18866 throw invalidChar(read());
18870 const u = unicodeEscape();
18878 if (!util$2.isIdStartChar(u)) {
18879 throw invalidIdentifier();
18886 lexState = 'identifierName';
18900 lexState = 'identifierNameEscape';
18904 if (util$2.isIdContinueChar(c)) {
18909 return newToken('identifier', buffer);
18912 identifierNameEscape() {
18914 throw invalidChar(read());
18918 const u = unicodeEscape();
18928 if (!util$2.isIdContinueChar(u)) {
18929 throw invalidIdentifier();
18936 lexState = 'identifierName';
18943 lexState = 'decimalPointLeading';
18961 lexState = 'decimalInteger';
18966 literal('nfinity');
18967 return newToken('numeric', sign * Infinity);
18972 return newToken('numeric', NaN);
18975 throw invalidChar(read());
18982 lexState = 'decimalPoint';
18988 lexState = 'decimalExponent';
18994 lexState = 'hexadecimal';
18998 return newToken('numeric', sign * 0);
19005 lexState = 'decimalPoint';
19011 lexState = 'decimalExponent';
19015 if (util$2.isDigit(c)) {
19020 return newToken('numeric', sign * Number(buffer));
19023 decimalPointLeading() {
19024 if (util$2.isDigit(c)) {
19026 lexState = 'decimalFraction';
19030 throw invalidChar(read());
19038 lexState = 'decimalExponent';
19042 if (util$2.isDigit(c)) {
19044 lexState = 'decimalFraction';
19048 return newToken('numeric', sign * Number(buffer));
19051 decimalFraction() {
19056 lexState = 'decimalExponent';
19060 if (util$2.isDigit(c)) {
19065 return newToken('numeric', sign * Number(buffer));
19068 decimalExponent() {
19073 lexState = 'decimalExponentSign';
19077 if (util$2.isDigit(c)) {
19079 lexState = 'decimalExponentInteger';
19083 throw invalidChar(read());
19086 decimalExponentSign() {
19087 if (util$2.isDigit(c)) {
19089 lexState = 'decimalExponentInteger';
19093 throw invalidChar(read());
19096 decimalExponentInteger() {
19097 if (util$2.isDigit(c)) {
19102 return newToken('numeric', sign * Number(buffer));
19106 if (util$2.isHexDigit(c)) {
19108 lexState = 'hexadecimalInteger';
19112 throw invalidChar(read());
19115 hexadecimalInteger() {
19116 if (util$2.isHexDigit(c)) {
19121 return newToken('numeric', sign * Number(buffer));
19128 buffer += escape();
19134 return newToken('string', buffer);
19141 if (!doubleQuote) {
19143 return newToken('string', buffer);
19151 throw invalidChar(read());
19159 throw invalidChar(read());
19169 return newToken('punctuator', read());
19170 // This code is unreachable since the default lexState handles eof.
19172 // return newToken('eof')
19175 lexState = 'value';
19178 beforePropertyName() {
19183 lexState = 'identifierName';
19188 lexState = 'identifierNameStartEscape';
19192 return newToken('punctuator', read());
19196 doubleQuote = read() === '"';
19197 lexState = 'string';
19201 if (util$2.isIdStartChar(c)) {
19203 lexState = 'identifierName';
19207 throw invalidChar(read());
19210 afterPropertyName() {
19212 return newToken('punctuator', read());
19215 throw invalidChar(read());
19218 beforePropertyValue() {
19219 lexState = 'value';
19222 afterPropertyValue() {
19226 return newToken('punctuator', read());
19229 throw invalidChar(read());
19232 beforeArrayValue() {
19234 return newToken('punctuator', read());
19237 lexState = 'value';
19240 afterArrayValue() {
19244 return newToken('punctuator', read());
19247 throw invalidChar(read());
19251 // This code is unreachable since it's handled by the default lexState.
19252 // if (c === undefined) {
19254 // return newToken('eof')
19256 throw invalidChar(read());
19261 function newToken(type, value) {
19270 function literal(s) {
19271 for (const c of s) {
19275 throw invalidChar(read());
19282 function escape() {
19313 if (util$2.isDigit(peek())) {
19314 throw invalidChar(read());
19321 return hexEscape();
19325 return unicodeEscape();
19336 if (peek() === '\n') {
19351 throw invalidChar(read());
19354 throw invalidChar(read());
19360 function hexEscape() {
19364 if (!util$2.isHexDigit(c)) {
19365 throw invalidChar(read());
19371 if (!util$2.isHexDigit(c)) {
19372 throw invalidChar(read());
19376 return String.fromCodePoint(parseInt(buffer, 16));
19379 function unicodeEscape() {
19383 while (count-- > 0) {
19386 if (!util$2.isHexDigit(c)) {
19387 throw invalidChar(read());
19393 return String.fromCodePoint(parseInt(buffer, 16));
19396 const parseStates = {
19398 if (token.type === 'eof') {
19399 throw invalidEOF();
19405 beforePropertyName() {
19406 switch (token.type) {
19410 parseState = 'afterPropertyName';
19414 // This code is unreachable since it's handled by the lexState.
19415 // if (token.value !== '}') {
19416 // throw invalidToken()
19422 throw invalidEOF();
19423 } // This code is unreachable since it's handled by the lexState.
19424 // throw invalidToken()
19428 afterPropertyName() {
19429 // This code is unreachable since it's handled by the lexState.
19430 // if (token.type !== 'punctuator' || token.value !== ':') {
19431 // throw invalidToken()
19433 if (token.type === 'eof') {
19434 throw invalidEOF();
19437 parseState = 'beforePropertyValue';
19440 beforePropertyValue() {
19441 if (token.type === 'eof') {
19442 throw invalidEOF();
19448 beforeArrayValue() {
19449 if (token.type === 'eof') {
19450 throw invalidEOF();
19453 if (token.type === 'punctuator' && token.value === ']') {
19461 afterPropertyValue() {
19462 // This code is unreachable since it's handled by the lexState.
19463 // if (token.type !== 'punctuator') {
19464 // throw invalidToken()
19466 if (token.type === 'eof') {
19467 throw invalidEOF();
19470 switch (token.value) {
19472 parseState = 'beforePropertyName';
19477 } // This code is unreachable since it's handled by the lexState.
19478 // throw invalidToken()
19482 afterArrayValue() {
19483 // This code is unreachable since it's handled by the lexState.
19484 // if (token.type !== 'punctuator') {
19485 // throw invalidToken()
19487 if (token.type === 'eof') {
19488 throw invalidEOF();
19491 switch (token.value) {
19493 parseState = 'beforeArrayValue';
19498 } // This code is unreachable since it's handled by the lexState.
19499 // throw invalidToken()
19503 end() {// This code is unreachable since it's handled by the lexState.
19504 // if (token.type !== 'eof') {
19505 // throw invalidToken()
19514 switch (token.type) {
19516 switch (token.value) {
19532 value = token.value;
19534 // This code is unreachable.
19536 // throw invalidToken()
19539 if (root$1 === undefined) {
19542 const parent = stack[stack.length - 1];
19544 if (Array.isArray(parent)) {
19545 parent.push(value);
19547 parent[key] = value;
19551 if (value !== null && typeof value === 'object') {
19554 if (Array.isArray(value)) {
19555 parseState = 'beforeArrayValue';
19557 parseState = 'beforePropertyName';
19560 const current = stack[stack.length - 1];
19562 if (current == null) {
19563 parseState = 'end';
19564 } else if (Array.isArray(current)) {
19565 parseState = 'afterArrayValue';
19567 parseState = 'afterPropertyValue';
19574 const current = stack[stack.length - 1];
19576 if (current == null) {
19577 parseState = 'end';
19578 } else if (Array.isArray(current)) {
19579 parseState = 'afterArrayValue';
19581 parseState = 'afterPropertyValue';
19583 } // This code is unreachable.
19584 // function invalidParseState () {
19585 // return new Error(`JSON5: invalid parse state '${parseState}'`)
19587 // This code is unreachable.
19588 // function invalidLexState (state) {
19589 // return new Error(`JSON5: invalid lex state '${state}'`)
19593 function invalidChar(c) {
19594 if (c === undefined) {
19595 return syntaxError(`JSON5: invalid end of input at ${line$2}:${column}`);
19598 return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line$2}:${column}`);
19601 function invalidEOF() {
19602 return syntaxError(`JSON5: invalid end of input at ${line$2}:${column}`);
19603 } // This code is unreachable.
19604 // function invalidToken () {
19605 // if (token.type === 'eof') {
19606 // return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
19608 // const c = String.fromCodePoint(token.value.codePointAt(0))
19609 // return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
19613 function invalidIdentifier() {
19615 return syntaxError(`JSON5: invalid identifier character at ${line$2}:${column}`);
19618 function separatorChar(c) {
19619 console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`);
19622 function formatChar(c) {
19623 const replacements = {
19634 '\u2028': '\\u2028',
19635 '\u2029': '\\u2029'
19638 if (replacements[c]) {
19639 return replacements[c];
19643 const hexString = c.charCodeAt(0).toString(16);
19644 return '\\x' + ('00' + hexString).substring(hexString.length);
19650 function syntaxError(message) {
19651 const err = new SyntaxError(message);
19652 err.lineNumber = line$2;
19653 err.columnNumber = column;
19657 var stringify = function stringify(value, replacer, space) {
19665 if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
19666 space = replacer.space;
19667 quote = replacer.quote;
19668 replacer = replacer.replacer;
19671 if (typeof replacer === 'function') {
19672 replacerFunc = replacer;
19673 } else if (Array.isArray(replacer)) {
19676 for (const v of replacer) {
19679 if (typeof v === 'string') {
19681 } else if (typeof v === 'number' || v instanceof String || v instanceof Number) {
19685 if (item !== undefined && propertyList.indexOf(item) < 0) {
19686 propertyList.push(item);
19691 if (space instanceof Number) {
19692 space = Number(space);
19693 } else if (space instanceof String) {
19694 space = String(space);
19697 if (typeof space === 'number') {
19699 space = Math.min(10, Math.floor(space));
19700 gap = ' '.substr(0, space);
19702 } else if (typeof space === 'string') {
19703 gap = space.substr(0, 10);
19706 return serializeProperty('', {
19710 function serializeProperty(key, holder) {
19711 let value = holder[key];
19713 if (value != null) {
19714 if (typeof value.toJSON5 === 'function') {
19715 value = value.toJSON5(key);
19716 } else if (typeof value.toJSON === 'function') {
19717 value = value.toJSON(key);
19721 if (replacerFunc) {
19722 value = replacerFunc.call(holder, key, value);
19725 if (value instanceof Number) {
19726 value = Number(value);
19727 } else if (value instanceof String) {
19728 value = String(value);
19729 } else if (value instanceof Boolean) {
19730 value = value.valueOf();
19744 if (typeof value === 'string') {
19745 return quoteString(value);
19748 if (typeof value === 'number') {
19749 return String(value);
19752 if (typeof value === 'object') {
19753 return Array.isArray(value) ? serializeArray(value) : serializeObject(value);
19759 function quoteString(value) {
19764 const replacements = {
19775 '\u2028': '\\u2028',
19776 '\u2029': '\\u2029'
19780 for (let i = 0; i < value.length; i++) {
19781 const c = value[i];
19791 if (util$2.isDigit(value[i + 1])) {
19792 product += '\\x00';
19798 if (replacements[c]) {
19799 product += replacements[c];
19804 let hexString = c.charCodeAt(0).toString(16);
19805 product += '\\x' + ('00' + hexString).substring(hexString.length);
19812 const quoteChar = quote || Object.keys(quotes).reduce((a, b) => quotes[a] < quotes[b] ? a : b);
19813 product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]);
19814 return quoteChar + product + quoteChar;
19817 function serializeObject(value) {
19818 if (stack.indexOf(value) >= 0) {
19819 throw TypeError('Converting circular structure to JSON5');
19823 let stepback = indent;
19824 indent = indent + gap;
19825 let keys = propertyList || Object.keys(value);
19828 for (const key of keys) {
19829 const propertyString = serializeProperty(key, value);
19831 if (propertyString !== undefined) {
19832 let member = serializeKey(key) + ':';
19838 member += propertyString;
19839 partial.push(member);
19845 if (partial.length === 0) {
19851 properties = partial.join(',');
19852 final = '{' + properties + '}';
19854 let separator = ',\n' + indent;
19855 properties = partial.join(separator);
19856 final = '{\n' + indent + properties + ',\n' + stepback + '}';
19865 function serializeKey(key) {
19866 if (key.length === 0) {
19867 return quoteString(key);
19870 const firstChar = String.fromCodePoint(key.codePointAt(0));
19872 if (!util$2.isIdStartChar(firstChar)) {
19873 return quoteString(key);
19876 for (let i = firstChar.length; i < key.length; i++) {
19877 if (!util$2.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {
19878 return quoteString(key);
19885 function serializeArray(value) {
19886 if (stack.indexOf(value) >= 0) {
19887 throw TypeError('Converting circular structure to JSON5');
19891 let stepback = indent;
19892 indent = indent + gap;
19895 for (let i = 0; i < value.length; i++) {
19896 const propertyString = serializeProperty(String(i), value);
19897 partial.push(propertyString !== undefined ? propertyString : 'null');
19902 if (partial.length === 0) {
19906 let properties = partial.join(',');
19907 final = '[' + properties + ']';
19909 let separator = ',\n' + indent;
19910 let properties = partial.join(separator);
19911 final = '[\n' + indent + properties + ',\n' + stepback + ']';
19927 var dist$2 = /*#__PURE__*/Object.freeze({
19932 var require$$0$1 = /*@__PURE__*/getDefaultExportFromNamespaceIfPresent(dist$2);
19938 var loadJson5 = function (filePath, content) {
19940 return parse$3(content);
19942 error.message = `JSON5 Error in ${filePath}:\n${error.message}`;
19947 var caller = function () {
19948 // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
19949 var origPrepareStackTrace = Error.prepareStackTrace;
19951 Error.prepareStackTrace = function (_, stack) {
19955 var stack = new Error().stack;
19956 Error.prepareStackTrace = origPrepareStackTrace;
19957 return stack[2].getFileName();
19960 var pathParse = createCommonjsModule(function (module) {
19962 var isWindows = process.platform === 'win32'; // Regex to split a windows path into three parts: [*, device, slash,
19963 // tail] windows-only
19965 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; // Regex to split the tail part of the above into [*, dir, basename, ext]
19967 var splitTailRe = /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
19968 var win32 = {}; // Function to split a filename into [root, dir, basename, ext]
19970 function win32SplitPath(filename) {
19971 // Separate device+slash from tail
19972 var result = splitDeviceRe.exec(filename),
19973 device = (result[1] || '') + (result[2] || ''),
19974 tail = result[3] || ''; // Split the tail into dir, basename and extension
19976 var result2 = splitTailRe.exec(tail),
19978 basename = result2[2],
19980 return [device, dir, basename, ext];
19983 win32.parse = function (pathString) {
19984 if (typeof pathString !== 'string') {
19985 throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
19988 var allParts = win32SplitPath(pathString);
19990 if (!allParts || allParts.length !== 4) {
19991 throw new TypeError("Invalid path '" + pathString + "'");
19996 dir: allParts[0] + allParts[1].slice(0, -1),
19999 name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
20001 }; // Split a filename into [root, dir, basename, ext], unix version
20002 // 'root' is just a slash, or nothing.
20005 var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
20008 function posixSplitPath(filename) {
20009 return splitPathRe.exec(filename).slice(1);
20012 posix.parse = function (pathString) {
20013 if (typeof pathString !== 'string') {
20014 throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
20017 var allParts = posixSplitPath(pathString);
20019 if (!allParts || allParts.length !== 4) {
20020 throw new TypeError("Invalid path '" + pathString + "'");
20023 allParts[1] = allParts[1] || '';
20024 allParts[2] = allParts[2] || '';
20025 allParts[3] = allParts[3] || '';
20028 dir: allParts[0] + allParts[1].slice(0, -1),
20031 name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
20035 if (isWindows) module.exports = win32.parse;else
20037 module.exports = posix.parse;
20038 module.exports.posix = posix.parse;
20039 module.exports.win32 = win32.parse;
20042 var parse$4 = path__default['default'].parse || pathParse;
20044 var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) {
20047 if (/^([A-Za-z]:)/.test(absoluteStart)) {
20049 } else if (/^\\\\/.test(absoluteStart)) {
20053 var paths = [absoluteStart];
20054 var parsed = parse$4(absoluteStart);
20056 while (parsed.dir !== paths[paths.length - 1]) {
20057 paths.push(parsed.dir);
20058 parsed = parse$4(parsed.dir);
20061 return paths.reduce(function (dirs, aPath) {
20062 return dirs.concat(modules.map(function (moduleDir) {
20063 return path__default['default'].resolve(prefix, aPath, moduleDir);
20068 var nodeModulesPaths = function nodeModulesPaths(start, opts, request) {
20069 var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ['node_modules'];
20071 if (opts && typeof opts.paths === 'function') {
20072 return opts.paths(request, start, function () {
20073 return getNodeModulesDirs(start, modules);
20077 var dirs = getNodeModulesDirs(start, modules);
20078 return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
20081 var normalizeOptions$2 = function (x, opts) {
20083 * This file is purposefully a passthrough. It's expected that third-party
20084 * environments will override it at runtime in order to inject special logic
20085 * into `resolve` (by manipulating the options). One such example is the PnP
20086 * code path in Yarn.
20091 /* eslint no-invalid-this: 1 */
20093 var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
20094 var slice = Array.prototype.slice;
20095 var toStr = Object.prototype.toString;
20096 var funcType = '[object Function]';
20098 var implementation = function bind(that) {
20101 if (typeof target !== 'function' || toStr.call(target) !== funcType) {
20102 throw new TypeError(ERROR_MESSAGE + target);
20105 var args = slice.call(arguments, 1);
20108 var binder = function () {
20109 if (this instanceof bound) {
20110 var result = target.apply(this, args.concat(slice.call(arguments)));
20112 if (Object(result) === result) {
20118 return target.apply(that, args.concat(slice.call(arguments)));
20122 var boundLength = Math.max(0, target.length - args.length);
20123 var boundArgs = [];
20125 for (var i = 0; i < boundLength; i++) {
20126 boundArgs.push('$' + i);
20129 bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
20131 if (target.prototype) {
20132 var Empty = function Empty() {};
20134 Empty.prototype = target.prototype;
20135 bound.prototype = new Empty();
20136 Empty.prototype = null;
20142 var functionBind = Function.prototype.bind || implementation;
20144 var src = functionBind.call(Function.call, Object.prototype.hasOwnProperty);
20147 var async_hooks = ">= 8";
20148 var buffer_ieee754 = "< 0.9.7";
20149 var buffer$1 = true;
20150 var child_process = true;
20151 var cluster = true;
20152 var console$1 = true;
20153 var constants$1 = true;
20155 var _debug_agent = ">= 1 && < 8";
20156 var _debugger = "< 8";
20158 var diagnostics_channel = ">= 15.1";
20160 var domain = ">= 0.7.12";
20162 var freelist = "< 6";
20164 var _http_agent = ">= 0.11.1";
20165 var _http_client = ">= 0.11.1";
20166 var _http_common = ">= 0.11.1";
20167 var _http_incoming = ">= 0.11.1";
20168 var _http_outgoing = ">= 0.11.1";
20169 var _http_server = ">= 0.11.1";
20171 var http2 = ">= 8.8";
20173 var inspector = ">= 8.0.0";
20174 var _linklist = "< 8";
20175 var module$1 = true;
20179 var perf_hooks = ">= 8.5";
20180 var process$1 = ">= 1";
20181 var punycode = true;
20182 var querystring = true;
20183 var readline = true;
20185 var smalloc = ">= 0.11.5 && < 3";
20186 var _stream_duplex = ">= 0.9.4";
20187 var _stream_transform = ">= 0.9.4";
20188 var _stream_wrap = ">= 1.4.1";
20189 var _stream_passthrough = ">= 0.9.4";
20190 var _stream_readable = ">= 0.9.4";
20191 var _stream_writable = ">= 0.9.4";
20193 var string_decoder = true;
20199 var _tls_common = ">= 0.11.13";
20200 var _tls_legacy = ">= 0.11.3 && < 10";
20201 var _tls_wrap = ">= 0.11.3";
20203 var trace_events = ">= 10";
20209 var wasi = ">= 13.4 && < 13.5";
20210 var worker_threads = ">= 11.7";
20214 "assert/strict": ">= 15",
20215 async_hooks: async_hooks,
20216 buffer_ieee754: buffer_ieee754,
20218 child_process: child_process,
20220 console: console$1,
20221 constants: constants$1,
20223 _debug_agent: _debug_agent,
20224 _debugger: _debugger,
20226 diagnostics_channel: diagnostics_channel,
20228 "dns/promises": ">= 15",
20231 freelist: freelist,
20237 _http_agent: _http_agent,
20238 _http_client: _http_client,
20239 _http_common: _http_common,
20240 _http_incoming: _http_incoming,
20241 _http_outgoing: _http_outgoing,
20242 _http_server: _http_server,
20246 inspector: inspector,
20247 _linklist: _linklist,
20250 "node-inspect/lib/_inspect": ">= 7.6.0 && < 12",
20251 "node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12",
20252 "node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12",
20255 perf_hooks: perf_hooks,
20256 process: process$1,
20257 punycode: punycode,
20258 querystring: querystring,
20259 readline: readline,
20262 _stream_duplex: _stream_duplex,
20263 _stream_transform: _stream_transform,
20264 _stream_wrap: _stream_wrap,
20265 _stream_passthrough: _stream_passthrough,
20266 _stream_readable: _stream_readable,
20267 _stream_writable: _stream_writable,
20269 "stream/promises": ">= 15",
20270 string_decoder: string_decoder,
20273 "timers/promises": ">= 15",
20274 _tls_common: _tls_common,
20275 _tls_legacy: _tls_legacy,
20276 _tls_wrap: _tls_wrap,
20278 trace_events: trace_events,
20282 "v8/tools/arguments": ">= 10 && < 12",
20283 "v8/tools/codemap": [
20287 "v8/tools/consarray": [
20291 "v8/tools/csvparser": [
20295 "v8/tools/logreader": [
20299 "v8/tools/profile_view": [
20303 "v8/tools/splaytree": [
20310 worker_threads: worker_threads,
20314 function specifierIncluded(current, specifier) {
20315 var nodeParts = current.split('.');
20316 var parts = specifier.split(' ');
20317 var op = parts.length > 1 ? parts[0] : '=';
20318 var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.');
20320 for (var i = 0; i < 3; ++i) {
20321 var cur = parseInt(nodeParts[i] || 0, 10);
20322 var ver = parseInt(versionParts[i] || 0, 10);
20325 continue; // eslint-disable-line no-restricted-syntax, no-continue
20339 return op === '>=';
20342 function matchesRange(current, range) {
20343 var specifiers = range.split(/ ?&& ?/);
20345 if (specifiers.length === 0) {
20349 for (var i = 0; i < specifiers.length; ++i) {
20350 if (!specifierIncluded(current, specifiers[i])) {
20358 function versionIncluded(nodeVersion, specifierValue) {
20359 if (typeof specifierValue === 'boolean') {
20360 return specifierValue;
20363 var current = typeof nodeVersion === 'undefined' ? process.versions && process.versions.node && process.versions.node : nodeVersion;
20365 if (typeof current !== 'string') {
20366 throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required');
20369 if (specifierValue && typeof specifierValue === 'object') {
20370 for (var i = 0; i < specifierValue.length; ++i) {
20371 if (matchesRange(current, specifierValue[i])) {
20379 return matchesRange(current, specifierValue);
20382 var isCoreModule = function isCore(x, nodeVersion) {
20383 return src(data, x) && versionIncluded(nodeVersion, data[x]);
20386 var realpathFS = fs__default['default'].realpath && typeof fs__default['default'].realpath.native === 'function' ? fs__default['default'].realpath.native : fs__default['default'].realpath;
20388 var defaultIsFile = function isFile(file, cb) {
20389 fs__default['default'].stat(file, function (err, stat) {
20391 return cb(null, stat.isFile() || stat.isFIFO());
20394 if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
20399 var defaultIsDir = function isDirectory(dir, cb) {
20400 fs__default['default'].stat(dir, function (err, stat) {
20402 return cb(null, stat.isDirectory());
20405 if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
20410 var defaultRealpath = function realpath(x, cb) {
20411 realpathFS(x, function (realpathErr, realPath) {
20412 if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr);else cb(null, realpathErr ? x : realPath);
20416 var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) {
20417 if (opts && opts.preserveSymlinks === false) {
20424 var getPackageCandidates = function getPackageCandidates(x, start, opts) {
20425 var dirs = nodeModulesPaths(start, opts, x);
20427 for (var i = 0; i < dirs.length; i++) {
20428 dirs[i] = path__default['default'].join(dirs[i], x);
20434 var async = function resolve(x, options, callback) {
20436 var opts = options;
20438 if (typeof options === 'function') {
20443 if (typeof x !== 'string') {
20444 var err = new TypeError('Path must be a string.');
20445 return process.nextTick(function () {
20450 opts = normalizeOptions$2(x, opts);
20451 var isFile = opts.isFile || defaultIsFile;
20452 var isDirectory = opts.isDirectory || defaultIsDir;
20453 var readFile = opts.readFile || fs__default['default'].readFile;
20454 var realpath = opts.realpath || defaultRealpath;
20455 var packageIterator = opts.packageIterator;
20456 var extensions = opts.extensions || ['.js'];
20457 var includeCoreModules = opts.includeCoreModules !== false;
20458 var basedir = opts.basedir || path__default['default'].dirname(caller());
20459 var parent = opts.filename || basedir;
20460 opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
20462 var absoluteStart = path__default['default'].resolve(basedir);
20463 maybeRealpath(realpath, absoluteStart, opts, function (err, realStart) {
20464 if (err) cb(err);else init(realStart);
20468 function init(basedir) {
20469 if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
20470 res = path__default['default'].resolve(basedir, x);
20471 if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';
20473 if (/\/$/.test(x) && res === basedir) {
20474 loadAsDirectory(res, opts.package, onfile);
20475 } else loadAsFile(res, opts.package, onfile);
20476 } else if (includeCoreModules && isCoreModule(x)) {
20477 return cb(null, x);
20478 } else loadNodeModules(x, basedir, function (err, n, pkg) {
20479 if (err) cb(err);else if (n) {
20480 return maybeRealpath(realpath, n, opts, function (err, realN) {
20484 cb(null, realN, pkg);
20488 var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
20489 moduleError.code = 'MODULE_NOT_FOUND';
20495 function onfile(err, m, pkg) {
20496 if (err) cb(err);else if (m) cb(null, m, pkg);else loadAsDirectory(res, function (err, d, pkg) {
20497 if (err) cb(err);else if (d) {
20498 maybeRealpath(realpath, d, opts, function (err, realD) {
20502 cb(null, realD, pkg);
20506 var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
20507 moduleError.code = 'MODULE_NOT_FOUND';
20513 function loadAsFile(x, thePackage, callback) {
20514 var loadAsFilePackage = thePackage;
20517 if (typeof loadAsFilePackage === 'function') {
20518 cb = loadAsFilePackage;
20519 loadAsFilePackage = undefined;
20522 var exts = [''].concat(extensions);
20523 load(exts, x, loadAsFilePackage);
20525 function load(exts, x, loadPackage) {
20526 if (exts.length === 0) return cb(null, undefined, loadPackage);
20527 var file = x + exts[0];
20528 var pkg = loadPackage;
20529 if (pkg) onpkg(null, pkg);else loadpkg(path__default['default'].dirname(file), onpkg);
20531 function onpkg(err, pkg_, dir) {
20533 if (err) return cb(err);
20535 if (dir && pkg && opts.pathFilter) {
20536 var rfile = path__default['default'].relative(dir, file);
20537 var rel = rfile.slice(0, rfile.length - exts[0].length);
20538 var r = opts.pathFilter(pkg, x, rel);
20539 if (r) return load([''].concat(extensions.slice()), path__default['default'].resolve(dir, r), pkg);
20542 isFile(file, onex);
20545 function onex(err, ex) {
20546 if (err) return cb(err);
20547 if (ex) return cb(null, file, pkg);
20548 load(exts.slice(1), x, pkg);
20553 function loadpkg(dir, cb) {
20554 if (dir === '' || dir === '/') return cb(null);
20556 if (process.platform === 'win32' && /^\w:[/\\]*$/.test(dir)) {
20560 if (/[/\\]node_modules[/\\]*$/.test(dir)) return cb(null);
20561 maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) {
20562 if (unwrapErr) return loadpkg(path__default['default'].dirname(dir), cb);
20563 var pkgfile = path__default['default'].join(pkgdir, 'package.json');
20564 isFile(pkgfile, function (err, ex) {
20565 // on err, ex is false
20566 if (!ex) return loadpkg(path__default['default'].dirname(dir), cb);
20567 readFile(pkgfile, function (err, body) {
20571 var pkg = JSON.parse(body);
20572 } catch (jsonErr) {}
20574 if (pkg && opts.packageFilter) {
20575 pkg = opts.packageFilter(pkg, pkgfile);
20578 cb(null, pkg, dir);
20584 function loadAsDirectory(x, loadAsDirectoryPackage, callback) {
20586 var fpkg = loadAsDirectoryPackage;
20588 if (typeof fpkg === 'function') {
20590 fpkg = opts.package;
20593 maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) {
20594 if (unwrapErr) return cb(unwrapErr);
20595 var pkgfile = path__default['default'].join(pkgdir, 'package.json');
20596 isFile(pkgfile, function (err, ex) {
20597 if (err) return cb(err);
20598 if (!ex) return loadAsFile(path__default['default'].join(x, 'index'), fpkg, cb);
20599 readFile(pkgfile, function (err, body) {
20600 if (err) return cb(err);
20603 var pkg = JSON.parse(body);
20604 } catch (jsonErr) {}
20606 if (pkg && opts.packageFilter) {
20607 pkg = opts.packageFilter(pkg, pkgfile);
20610 if (pkg && pkg.main) {
20611 if (typeof pkg.main !== 'string') {
20612 var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
20613 mainError.code = 'INVALID_PACKAGE_MAIN';
20614 return cb(mainError);
20617 if (pkg.main === '.' || pkg.main === './') {
20618 pkg.main = 'index';
20621 loadAsFile(path__default['default'].resolve(x, pkg.main), pkg, function (err, m, pkg) {
20622 if (err) return cb(err);
20623 if (m) return cb(null, m, pkg);
20624 if (!pkg) return loadAsFile(path__default['default'].join(x, 'index'), pkg, cb);
20625 var dir = path__default['default'].resolve(x, pkg.main);
20626 loadAsDirectory(dir, pkg, function (err, n, pkg) {
20627 if (err) return cb(err);
20628 if (n) return cb(null, n, pkg);
20629 loadAsFile(path__default['default'].join(x, 'index'), pkg, cb);
20635 loadAsFile(path__default['default'].join(x, '/index'), pkg, cb);
20641 function processDirs(cb, dirs) {
20642 if (dirs.length === 0) return cb(null, undefined);
20644 isDirectory(path__default['default'].dirname(dir), isdir);
20646 function isdir(err, isdir) {
20647 if (err) return cb(err);
20648 if (!isdir) return processDirs(cb, dirs.slice(1));
20649 loadAsFile(dir, opts.package, onfile);
20652 function onfile(err, m, pkg) {
20653 if (err) return cb(err);
20654 if (m) return cb(null, m, pkg);
20655 loadAsDirectory(dir, opts.package, ondir);
20658 function ondir(err, n, pkg) {
20659 if (err) return cb(err);
20660 if (n) return cb(null, n, pkg);
20661 processDirs(cb, dirs.slice(1));
20665 function loadNodeModules(x, start, cb) {
20666 var thunk = function () {
20667 return getPackageCandidates(x, start, opts);
20670 processDirs(cb, packageIterator ? packageIterator(x, start, thunk, opts) : thunk());
20674 var assert$1 = true;
20675 var async_hooks$1 = ">= 8";
20676 var buffer_ieee754$1 = "< 0.9.7";
20677 var buffer$2 = true;
20678 var child_process$1 = true;
20679 var cluster$1 = true;
20680 var console$2 = true;
20681 var constants$2 = true;
20682 var crypto$1 = true;
20683 var _debug_agent$1 = ">= 1 && < 8";
20684 var _debugger$1 = "< 8";
20685 var dgram$1 = true;
20686 var diagnostics_channel$1 = ">= 15.1";
20688 var domain$1 = ">= 0.7.12";
20689 var events$1 = true;
20690 var freelist$1 = "< 6";
20692 var _http_agent$1 = ">= 0.11.1";
20693 var _http_client$1 = ">= 0.11.1";
20694 var _http_common$1 = ">= 0.11.1";
20695 var _http_incoming$1 = ">= 0.11.1";
20696 var _http_outgoing$1 = ">= 0.11.1";
20697 var _http_server$1 = ">= 0.11.1";
20699 var http2$1 = ">= 8.8";
20700 var https$1 = true;
20701 var inspector$1 = ">= 8.0.0";
20702 var _linklist$1 = "< 8";
20703 var module$2 = true;
20707 var perf_hooks$1 = ">= 8.5";
20708 var process$2 = ">= 1";
20709 var punycode$1 = true;
20710 var querystring$1 = true;
20711 var readline$1 = true;
20713 var smalloc$1 = ">= 0.11.5 && < 3";
20714 var _stream_duplex$1 = ">= 0.9.4";
20715 var _stream_transform$1 = ">= 0.9.4";
20716 var _stream_wrap$1 = ">= 1.4.1";
20717 var _stream_passthrough$1 = ">= 0.9.4";
20718 var _stream_readable$1 = ">= 0.9.4";
20719 var _stream_writable$1 = ">= 0.9.4";
20720 var stream$1 = true;
20721 var string_decoder$1 = true;
20726 var timers$1 = true;
20727 var _tls_common$1 = ">= 0.11.13";
20728 var _tls_legacy$1 = ">= 0.11.3 && < 10";
20729 var _tls_wrap$1 = ">= 0.11.3";
20731 var trace_events$1 = ">= 10";
20737 var wasi$1 = ">= 13.4 && < 13.5";
20738 var worker_threads$1 = ">= 11.7";
20742 "assert/strict": ">= 15",
20743 async_hooks: async_hooks$1,
20744 buffer_ieee754: buffer_ieee754$1,
20746 child_process: child_process$1,
20747 cluster: cluster$1,
20748 console: console$2,
20749 constants: constants$2,
20751 _debug_agent: _debug_agent$1,
20752 _debugger: _debugger$1,
20754 diagnostics_channel: diagnostics_channel$1,
20756 "dns/promises": ">= 15",
20759 freelist: freelist$1,
20765 _http_agent: _http_agent$1,
20766 _http_client: _http_client$1,
20767 _http_common: _http_common$1,
20768 _http_incoming: _http_incoming$1,
20769 _http_outgoing: _http_outgoing$1,
20770 _http_server: _http_server$1,
20774 inspector: inspector$1,
20775 _linklist: _linklist$1,
20778 "node-inspect/lib/_inspect": ">= 7.6.0 && < 12",
20779 "node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12",
20780 "node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12",
20783 perf_hooks: perf_hooks$1,
20784 process: process$2,
20785 punycode: punycode$1,
20786 querystring: querystring$1,
20787 readline: readline$1,
20789 smalloc: smalloc$1,
20790 _stream_duplex: _stream_duplex$1,
20791 _stream_transform: _stream_transform$1,
20792 _stream_wrap: _stream_wrap$1,
20793 _stream_passthrough: _stream_passthrough$1,
20794 _stream_readable: _stream_readable$1,
20795 _stream_writable: _stream_writable$1,
20797 "stream/promises": ">= 15",
20798 string_decoder: string_decoder$1,
20801 "timers/promises": ">= 15",
20802 _tls_common: _tls_common$1,
20803 _tls_legacy: _tls_legacy$1,
20804 _tls_wrap: _tls_wrap$1,
20806 trace_events: trace_events$1,
20810 "v8/tools/arguments": ">= 10 && < 12",
20811 "v8/tools/codemap": [
20815 "v8/tools/consarray": [
20819 "v8/tools/csvparser": [
20823 "v8/tools/logreader": [
20827 "v8/tools/profile_view": [
20831 "v8/tools/splaytree": [
20838 worker_threads: worker_threads$1,
20842 var current = process.versions && process.versions.node && process.versions.node.split('.') || [];
20844 function specifierIncluded$1(specifier) {
20845 var parts = specifier.split(' ');
20846 var op = parts.length > 1 ? parts[0] : '=';
20847 var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.');
20849 for (var i = 0; i < 3; ++i) {
20850 var cur = parseInt(current[i] || 0, 10);
20851 var ver = parseInt(versionParts[i] || 0, 10);
20854 continue; // eslint-disable-line no-restricted-syntax, no-continue
20859 } else if (op === '>=') {
20866 return op === '>=';
20869 function matchesRange$1(range) {
20870 var specifiers = range.split(/ ?&& ?/);
20872 if (specifiers.length === 0) {
20876 for (var i = 0; i < specifiers.length; ++i) {
20877 if (!specifierIncluded$1(specifiers[i])) {
20885 function versionIncluded$1(specifierValue) {
20886 if (typeof specifierValue === 'boolean') {
20887 return specifierValue;
20890 if (specifierValue && typeof specifierValue === 'object') {
20891 for (var i = 0; i < specifierValue.length; ++i) {
20892 if (matchesRange$1(specifierValue[i])) {
20900 return matchesRange$1(specifierValue);
20905 for (var mod in data$1) {
20906 // eslint-disable-line no-restricted-syntax
20907 if (Object.prototype.hasOwnProperty.call(data$1, mod)) {
20908 core$1[mod] = versionIncluded$1(data$1[mod]);
20912 var core_1 = core$1;
20914 var isCore = function isCore(x) {
20915 return isCoreModule(x);
20918 var realpathFS$1 = fs__default['default'].realpathSync && typeof fs__default['default'].realpathSync.native === 'function' ? fs__default['default'].realpathSync.native : fs__default['default'].realpathSync;
20920 var defaultIsFile$1 = function isFile(file) {
20922 var stat = fs__default['default'].statSync(file);
20924 if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
20928 return stat.isFile() || stat.isFIFO();
20931 var defaultIsDir$1 = function isDirectory(dir) {
20933 var stat = fs__default['default'].statSync(dir);
20935 if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
20939 return stat.isDirectory();
20942 var defaultRealpathSync = function realpathSync(x) {
20944 return realpathFS$1(x);
20945 } catch (realpathErr) {
20946 if (realpathErr.code !== 'ENOENT') {
20954 var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) {
20955 if (opts && opts.preserveSymlinks === false) {
20956 return realpathSync(x);
20962 var getPackageCandidates$1 = function getPackageCandidates(x, start, opts) {
20963 var dirs = nodeModulesPaths(start, opts, x);
20965 for (var i = 0; i < dirs.length; i++) {
20966 dirs[i] = path__default['default'].join(dirs[i], x);
20972 var sync = function resolveSync(x, options) {
20973 if (typeof x !== 'string') {
20974 throw new TypeError('Path must be a string.');
20977 var opts = normalizeOptions$2(x, options);
20978 var isFile = opts.isFile || defaultIsFile$1;
20979 var readFileSync = opts.readFileSync || fs__default['default'].readFileSync;
20980 var isDirectory = opts.isDirectory || defaultIsDir$1;
20981 var realpathSync = opts.realpathSync || defaultRealpathSync;
20982 var packageIterator = opts.packageIterator;
20983 var extensions = opts.extensions || ['.js'];
20984 var includeCoreModules = opts.includeCoreModules !== false;
20985 var basedir = opts.basedir || path__default['default'].dirname(caller());
20986 var parent = opts.filename || basedir;
20987 opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
20989 var absoluteStart = maybeRealpathSync(realpathSync, path__default['default'].resolve(basedir), opts);
20991 if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
20992 var res = path__default['default'].resolve(absoluteStart, x);
20993 if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/';
20994 var m = loadAsFileSync(res) || loadAsDirectorySync(res);
20995 if (m) return maybeRealpathSync(realpathSync, m, opts);
20996 } else if (includeCoreModules && isCoreModule(x)) {
20999 var n = loadNodeModulesSync(x, absoluteStart);
21000 if (n) return maybeRealpathSync(realpathSync, n, opts);
21003 var err = new Error("Cannot find module '" + x + "' from '" + parent + "'");
21004 err.code = 'MODULE_NOT_FOUND';
21007 function loadAsFileSync(x) {
21008 var pkg = loadpkg(path__default['default'].dirname(x));
21010 if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) {
21011 var rfile = path__default['default'].relative(pkg.dir, x);
21012 var r = opts.pathFilter(pkg.pkg, x, rfile);
21015 x = path__default['default'].resolve(pkg.dir, r); // eslint-disable-line no-param-reassign
21023 for (var i = 0; i < extensions.length; i++) {
21024 var file = x + extensions[i];
21026 if (isFile(file)) {
21032 function loadpkg(dir) {
21033 if (dir === '' || dir === '/') return;
21035 if (process.platform === 'win32' && /^\w:[/\\]*$/.test(dir)) {
21039 if (/[/\\]node_modules[/\\]*$/.test(dir)) return;
21040 var pkgfile = path__default['default'].join(maybeRealpathSync(realpathSync, dir, opts), 'package.json');
21042 if (!isFile(pkgfile)) {
21043 return loadpkg(path__default['default'].dirname(dir));
21046 var body = readFileSync(pkgfile);
21049 var pkg = JSON.parse(body);
21050 } catch (jsonErr) {}
21052 if (pkg && opts.packageFilter) {
21053 // v2 will pass pkgfile
21054 pkg = opts.packageFilter(pkg,
21056 dir); // eslint-disable-line spaced-comment
21065 function loadAsDirectorySync(x) {
21066 var pkgfile = path__default['default'].join(maybeRealpathSync(realpathSync, x, opts), '/package.json');
21068 if (isFile(pkgfile)) {
21070 var body = readFileSync(pkgfile, 'UTF8');
21071 var pkg = JSON.parse(body);
21074 if (pkg && opts.packageFilter) {
21075 // v2 will pass pkgfile
21076 pkg = opts.packageFilter(pkg,
21078 x); // eslint-disable-line spaced-comment
21081 if (pkg && pkg.main) {
21082 if (typeof pkg.main !== 'string') {
21083 var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
21084 mainError.code = 'INVALID_PACKAGE_MAIN';
21088 if (pkg.main === '.' || pkg.main === './') {
21089 pkg.main = 'index';
21093 var m = loadAsFileSync(path__default['default'].resolve(x, pkg.main));
21095 var n = loadAsDirectorySync(path__default['default'].resolve(x, pkg.main));
21101 return loadAsFileSync(path__default['default'].join(x, '/index'));
21104 function loadNodeModulesSync(x, start) {
21105 var thunk = function () {
21106 return getPackageCandidates$1(x, start, opts);
21109 var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk();
21111 for (var i = 0; i < dirs.length; i++) {
21114 if (isDirectory(path__default['default'].dirname(dir))) {
21115 var m = loadAsFileSync(dir);
21117 var n = loadAsDirectorySync(dir);
21124 async.core = core_1;
21125 async.isCore = isCore;
21127 var resolve = async;
21131 } = require; // In the VS Code and Atom extensions `require` is overridden and `require.resolve` doesn't support the 2nd argument.
21133 if (resolve$1.length === 1 || process.env.PRETTIER_FALLBACK_RESOLVE) {
21134 resolve$1 = (id, options) => {
21137 if (options && options.paths && options.paths.length === 1) {
21138 basedir = options.paths[0];
21141 return resolve.sync(id, {
21147 var resolve_1 = resolve$1;
21149 var semver$2 = createCommonjsModule(function (module, exports) {
21150 exports = module.exports = SemVer;
21152 /* istanbul ignore next */
21154 if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
21155 debug = function () {
21156 var args = Array.prototype.slice.call(arguments, 0);
21157 args.unshift('SEMVER');
21158 console.log.apply(console, args);
21161 debug = function () {};
21162 } // Note: this is the semver.org version of the spec that it implements
21163 // Not necessarily the package version of this code.
21166 exports.SEMVER_SPEC_VERSION = '2.0.0';
21167 var MAX_LENGTH = 256;
21168 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
21169 /* istanbul ignore next */
21170 9007199254740991; // Max safe segment length for coercion.
21172 var MAX_SAFE_COMPONENT_LENGTH = 16; // The actual regexps go on exports.re
21174 var re = exports.re = [];
21175 var src = exports.src = [];
21176 var R = 0; // The following Regular Expressions can be used for tokenizing,
21177 // validating, and parsing SemVer version strings.
21178 // ## Numeric Identifier
21179 // A single `0`, or a non-zero digit followed by zero or more digits.
21181 var NUMERICIDENTIFIER = R++;
21182 src[NUMERICIDENTIFIER] = '0|[1-9]\\d*';
21183 var NUMERICIDENTIFIERLOOSE = R++;
21184 src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier
21185 // Zero or more digits, followed by a letter or hyphen, and then zero or
21186 // more letters, digits, or hyphens.
21188 var NONNUMERICIDENTIFIER = R++;
21189 src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version
21190 // Three dot-separated numeric identifiers.
21192 var MAINVERSION = R++;
21193 src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')';
21194 var MAINVERSIONLOOSE = R++;
21195 src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier
21196 // A numeric identifier, or a non-numeric identifier.
21198 var PRERELEASEIDENTIFIER = R++;
21199 src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')';
21200 var PRERELEASEIDENTIFIERLOOSE = R++;
21201 src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version
21202 // Hyphen, followed by one or more dot-separated pre-release version
21205 var PRERELEASE = R++;
21206 src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))';
21207 var PRERELEASELOOSE = R++;
21208 src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier
21209 // Any combination of digits, letters, or hyphens.
21211 var BUILDIDENTIFIER = R++;
21212 src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata
21213 // Plus sign, followed by one or more period-separated build metadata
21217 src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; // ## Full Version String
21218 // A main version, followed optionally by a pre-release version and
21220 // Note that the only major, minor, patch, and pre-release sections of
21221 // the version string are capturing groups. The build metadata is not a
21222 // capturing group, because it should not ever be used in version
21226 var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?';
21227 src[FULL] = '^' + FULLPLAIN + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
21228 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
21229 // common in the npm registry.
21231 var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?';
21233 src[LOOSE] = '^' + LOOSEPLAIN + '$';
21235 src[GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x".
21236 // Note that "x.x" is a valid xRange identifer, meaning "any version"
21237 // Only the first item is strictly required.
21239 var XRANGEIDENTIFIERLOOSE = R++;
21240 src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
21241 var XRANGEIDENTIFIER = R++;
21242 src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*';
21243 var XRANGEPLAIN = R++;
21244 src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?';
21245 var XRANGEPLAINLOOSE = R++;
21246 src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?';
21248 src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$';
21249 var XRANGELOOSE = R++;
21250 src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; // Coercion.
21251 // Extract anything that could conceivably be a part of a valid semver
21254 src[COERCE] = '(?:^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])'; // Tilde ranges.
21255 // Meaning is "reasonably at or greater than"
21257 var LONETILDE = R++;
21258 src[LONETILDE] = '(?:~>?)';
21259 var TILDETRIM = R++;
21260 src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+';
21261 re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g');
21262 var tildeTrimReplace = '$1~';
21264 src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$';
21265 var TILDELOOSE = R++;
21266 src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; // Caret ranges.
21267 // Meaning is "at least and backwards compatible with"
21269 var LONECARET = R++;
21270 src[LONECARET] = '(?:\\^)';
21271 var CARETTRIM = R++;
21272 src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+';
21273 re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g');
21274 var caretTrimReplace = '$1^';
21276 src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$';
21277 var CARETLOOSE = R++;
21278 src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version"
21280 var COMPARATORLOOSE = R++;
21281 src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$';
21282 var COMPARATOR = R++;
21283 src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing
21284 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
21286 var COMPARATORTRIM = R++;
21287 src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; // this one has to use the /g flag
21289 re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g');
21290 var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
21291 // Note that these all use the loose form, because they'll be
21292 // checked against either the strict or loose comparator form
21295 var HYPHENRANGE = R++;
21296 src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$';
21297 var HYPHENRANGELOOSE = R++;
21298 src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all.
21301 src[STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects.
21302 // All are flag-free, unless they were created above with a flag.
21304 for (var i = 0; i < R; i++) {
21308 re[i] = new RegExp(src[i]);
21312 exports.parse = parse;
21314 function parse(version, options) {
21315 if (!options || typeof options !== 'object') {
21318 includePrerelease: false
21322 if (version instanceof SemVer) {
21326 if (typeof version !== 'string') {
21330 if (version.length > MAX_LENGTH) {
21334 var r = options.loose ? re[LOOSE] : re[FULL];
21336 if (!r.test(version)) {
21341 return new SemVer(version, options);
21347 exports.valid = valid;
21349 function valid(version, options) {
21350 var v = parse(version, options);
21351 return v ? v.version : null;
21354 exports.clean = clean;
21356 function clean(version, options) {
21357 var s = parse(version.trim().replace(/^[=v]+/, ''), options);
21358 return s ? s.version : null;
21361 exports.SemVer = SemVer;
21363 function SemVer(version, options) {
21364 if (!options || typeof options !== 'object') {
21367 includePrerelease: false
21371 if (version instanceof SemVer) {
21372 if (version.loose === options.loose) {
21375 version = version.version;
21377 } else if (typeof version !== 'string') {
21378 throw new TypeError('Invalid Version: ' + version);
21381 if (version.length > MAX_LENGTH) {
21382 throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters');
21385 if (!(this instanceof SemVer)) {
21386 return new SemVer(version, options);
21389 debug('SemVer', version, options);
21390 this.options = options;
21391 this.loose = !!options.loose;
21392 var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]);
21395 throw new TypeError('Invalid Version: ' + version);
21398 this.raw = version; // these are actually numbers
21400 this.major = +m[1];
21401 this.minor = +m[2];
21402 this.patch = +m[3];
21404 if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
21405 throw new TypeError('Invalid major version');
21408 if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
21409 throw new TypeError('Invalid minor version');
21412 if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
21413 throw new TypeError('Invalid patch version');
21414 } // numberify any prerelease numeric ids
21418 this.prerelease = [];
21420 this.prerelease = m[4].split('.').map(function (id) {
21421 if (/^[0-9]+$/.test(id)) {
21424 if (num >= 0 && num < MAX_SAFE_INTEGER) {
21433 this.build = m[5] ? m[5].split('.') : [];
21437 SemVer.prototype.format = function () {
21438 this.version = this.major + '.' + this.minor + '.' + this.patch;
21440 if (this.prerelease.length) {
21441 this.version += '-' + this.prerelease.join('.');
21444 return this.version;
21447 SemVer.prototype.toString = function () {
21448 return this.version;
21451 SemVer.prototype.compare = function (other) {
21452 debug('SemVer.compare', this.version, this.options, other);
21454 if (!(other instanceof SemVer)) {
21455 other = new SemVer(other, this.options);
21458 return this.compareMain(other) || this.comparePre(other);
21461 SemVer.prototype.compareMain = function (other) {
21462 if (!(other instanceof SemVer)) {
21463 other = new SemVer(other, this.options);
21466 return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
21469 SemVer.prototype.comparePre = function (other) {
21470 if (!(other instanceof SemVer)) {
21471 other = new SemVer(other, this.options);
21472 } // NOT having a prerelease is > having one
21475 if (this.prerelease.length && !other.prerelease.length) {
21477 } else if (!this.prerelease.length && other.prerelease.length) {
21479 } else if (!this.prerelease.length && !other.prerelease.length) {
21486 var a = this.prerelease[i];
21487 var b = other.prerelease[i];
21488 debug('prerelease compare', i, a, b);
21490 if (a === undefined && b === undefined) {
21492 } else if (b === undefined) {
21494 } else if (a === undefined) {
21496 } else if (a === b) {
21499 return compareIdentifiers(a, b);
21502 }; // preminor will bump the version up to the next minor release, and immediately
21503 // down to pre-release. premajor and prepatch work the same way.
21506 SemVer.prototype.inc = function (release, identifier) {
21509 this.prerelease.length = 0;
21513 this.inc('pre', identifier);
21517 this.prerelease.length = 0;
21520 this.inc('pre', identifier);
21524 // If this is already a prerelease, it will bump to the next version
21525 // drop any prereleases that might already exist, since they are not
21526 // relevant at this point.
21527 this.prerelease.length = 0;
21528 this.inc('patch', identifier);
21529 this.inc('pre', identifier);
21531 // If the input is a non-prerelease version, this acts the same as
21535 if (this.prerelease.length === 0) {
21536 this.inc('patch', identifier);
21539 this.inc('pre', identifier);
21543 // If this is a pre-major version, bump up to the same major version.
21544 // Otherwise increment major.
21545 // 1.0.0-5 bumps to 1.0.0
21546 // 1.1.0 bumps to 2.0.0
21547 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
21553 this.prerelease = [];
21557 // If this is a pre-minor version, bump up to the same minor version.
21558 // Otherwise increment minor.
21559 // 1.2.0-5 bumps to 1.2.0
21560 // 1.2.1 bumps to 1.3.0
21561 if (this.patch !== 0 || this.prerelease.length === 0) {
21566 this.prerelease = [];
21570 // If this is not a pre-release version, it will increment the patch.
21571 // If it is a pre-release it will bump up to the same patch version.
21572 // 1.2.0-5 patches to 1.2.0
21573 // 1.2.0 patches to 1.2.1
21574 if (this.prerelease.length === 0) {
21578 this.prerelease = [];
21580 // This probably shouldn't be used publicly.
21581 // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
21584 if (this.prerelease.length === 0) {
21585 this.prerelease = [0];
21587 var i = this.prerelease.length;
21590 if (typeof this.prerelease[i] === 'number') {
21591 this.prerelease[i]++;
21597 // didn't increment anything
21598 this.prerelease.push(0);
21603 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
21604 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
21605 if (this.prerelease[0] === identifier) {
21606 if (isNaN(this.prerelease[1])) {
21607 this.prerelease = [identifier, 0];
21610 this.prerelease = [identifier, 0];
21617 throw new Error('invalid increment argument: ' + release);
21621 this.raw = this.version;
21627 function inc(version, release, loose, identifier) {
21628 if (typeof loose === 'string') {
21629 identifier = loose;
21634 return new SemVer(version, loose).inc(release, identifier).version;
21640 exports.diff = diff;
21642 function diff(version1, version2) {
21643 if (eq(version1, version2)) {
21646 var v1 = parse(version1);
21647 var v2 = parse(version2);
21650 if (v1.prerelease.length || v2.prerelease.length) {
21652 var defaultResult = 'prerelease';
21655 for (var key in v1) {
21656 if (key === 'major' || key === 'minor' || key === 'patch') {
21657 if (v1[key] !== v2[key]) {
21658 return prefix + key;
21663 return defaultResult; // may be undefined
21667 exports.compareIdentifiers = compareIdentifiers;
21668 var numeric = /^[0-9]+$/;
21670 function compareIdentifiers(a, b) {
21671 var anum = numeric.test(a);
21672 var bnum = numeric.test(b);
21674 if (anum && bnum) {
21679 return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
21682 exports.rcompareIdentifiers = rcompareIdentifiers;
21684 function rcompareIdentifiers(a, b) {
21685 return compareIdentifiers(b, a);
21688 exports.major = major;
21690 function major(a, loose) {
21691 return new SemVer(a, loose).major;
21694 exports.minor = minor;
21696 function minor(a, loose) {
21697 return new SemVer(a, loose).minor;
21700 exports.patch = patch;
21702 function patch(a, loose) {
21703 return new SemVer(a, loose).patch;
21706 exports.compare = compare;
21708 function compare(a, b, loose) {
21709 return new SemVer(a, loose).compare(new SemVer(b, loose));
21712 exports.compareLoose = compareLoose;
21714 function compareLoose(a, b) {
21715 return compare(a, b, true);
21718 exports.rcompare = rcompare;
21720 function rcompare(a, b, loose) {
21721 return compare(b, a, loose);
21724 exports.sort = sort;
21726 function sort(list, loose) {
21727 return list.sort(function (a, b) {
21728 return exports.compare(a, b, loose);
21732 exports.rsort = rsort;
21734 function rsort(list, loose) {
21735 return list.sort(function (a, b) {
21736 return exports.rcompare(a, b, loose);
21742 function gt(a, b, loose) {
21743 return compare(a, b, loose) > 0;
21748 function lt(a, b, loose) {
21749 return compare(a, b, loose) < 0;
21754 function eq(a, b, loose) {
21755 return compare(a, b, loose) === 0;
21760 function neq(a, b, loose) {
21761 return compare(a, b, loose) !== 0;
21766 function gte(a, b, loose) {
21767 return compare(a, b, loose) >= 0;
21772 function lte(a, b, loose) {
21773 return compare(a, b, loose) <= 0;
21778 function cmp(a, op, b, loose) {
21781 if (typeof a === 'object') a = a.version;
21782 if (typeof b === 'object') b = b.version;
21786 if (typeof a === 'object') a = a.version;
21787 if (typeof b === 'object') b = b.version;
21793 return eq(a, b, loose);
21796 return neq(a, b, loose);
21799 return gt(a, b, loose);
21802 return gte(a, b, loose);
21805 return lt(a, b, loose);
21808 return lte(a, b, loose);
21811 throw new TypeError('Invalid operator: ' + op);
21815 exports.Comparator = Comparator;
21817 function Comparator(comp, options) {
21818 if (!options || typeof options !== 'object') {
21821 includePrerelease: false
21825 if (comp instanceof Comparator) {
21826 if (comp.loose === !!options.loose) {
21833 if (!(this instanceof Comparator)) {
21834 return new Comparator(comp, options);
21837 debug('comparator', comp, options);
21838 this.options = options;
21839 this.loose = !!options.loose;
21842 if (this.semver === ANY) {
21845 this.value = this.operator + this.semver.version;
21848 debug('comp', this);
21853 Comparator.prototype.parse = function (comp) {
21854 var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
21855 var m = comp.match(r);
21858 throw new TypeError('Invalid comparator: ' + comp);
21861 this.operator = m[1];
21863 if (this.operator === '=') {
21864 this.operator = '';
21865 } // if it literally is just '>' or '' then allow anything.
21871 this.semver = new SemVer(m[2], this.options.loose);
21875 Comparator.prototype.toString = function () {
21879 Comparator.prototype.test = function (version) {
21880 debug('Comparator.test', version, this.options.loose);
21882 if (this.semver === ANY) {
21886 if (typeof version === 'string') {
21887 version = new SemVer(version, this.options);
21890 return cmp(version, this.operator, this.semver, this.options);
21893 Comparator.prototype.intersects = function (comp, options) {
21894 if (!(comp instanceof Comparator)) {
21895 throw new TypeError('a Comparator is required');
21898 if (!options || typeof options !== 'object') {
21901 includePrerelease: false
21907 if (this.operator === '') {
21908 rangeTmp = new Range(comp.value, options);
21909 return satisfies(this.value, rangeTmp, options);
21910 } else if (comp.operator === '') {
21911 rangeTmp = new Range(this.value, options);
21912 return satisfies(comp.semver, rangeTmp, options);
21915 var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>');
21916 var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<');
21917 var sameSemVer = this.semver.version === comp.semver.version;
21918 var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=');
21919 var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<');
21920 var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>');
21921 return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
21924 exports.Range = Range;
21926 function Range(range, options) {
21927 if (!options || typeof options !== 'object') {
21930 includePrerelease: false
21934 if (range instanceof Range) {
21935 if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
21938 return new Range(range.raw, options);
21942 if (range instanceof Comparator) {
21943 return new Range(range.value, options);
21946 if (!(this instanceof Range)) {
21947 return new Range(range, options);
21950 this.options = options;
21951 this.loose = !!options.loose;
21952 this.includePrerelease = !!options.includePrerelease; // First, split based on boolean or ||
21955 this.set = range.split(/\s*\|\|\s*/).map(function (range) {
21956 return this.parseRange(range.trim());
21957 }, this).filter(function (c) {
21958 // throw out any that are not relevant for whatever reason
21962 if (!this.set.length) {
21963 throw new TypeError('Invalid SemVer Range: ' + range);
21969 Range.prototype.format = function () {
21970 this.range = this.set.map(function (comps) {
21971 return comps.join(' ').trim();
21972 }).join('||').trim();
21976 Range.prototype.toString = function () {
21980 Range.prototype.parseRange = function (range) {
21981 var loose = this.options.loose;
21982 range = range.trim(); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
21984 var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];
21985 range = range.replace(hr, hyphenReplace);
21986 debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
21988 range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);
21989 debug('comparator trim', range, re[COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3`
21991 range = range.replace(re[TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3`
21993 range = range.replace(re[CARETTRIM], caretTrimReplace); // normalize spaces
21995 range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and
21996 // ready to be split into comparators.
21998 var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
21999 var set = range.split(' ').map(function (comp) {
22000 return parseComparator(comp, this.options);
22001 }, this).join(' ').split(/\s+/);
22003 if (this.options.loose) {
22004 // in loose mode, throw out any that are not valid comparators
22005 set = set.filter(function (comp) {
22006 return !!comp.match(compRe);
22010 set = set.map(function (comp) {
22011 return new Comparator(comp, this.options);
22016 Range.prototype.intersects = function (range, options) {
22017 if (!(range instanceof Range)) {
22018 throw new TypeError('a Range is required');
22021 return this.set.some(function (thisComparators) {
22022 return thisComparators.every(function (thisComparator) {
22023 return range.set.some(function (rangeComparators) {
22024 return rangeComparators.every(function (rangeComparator) {
22025 return thisComparator.intersects(rangeComparator, options);
22030 }; // Mostly just for testing and legacy API reasons
22033 exports.toComparators = toComparators;
22035 function toComparators(range, options) {
22036 return new Range(range, options).set.map(function (comp) {
22037 return comp.map(function (c) {
22039 }).join(' ').trim().split(' ');
22041 } // comprised of xranges, tildes, stars, and gtlt's at this point.
22042 // already replaced the hyphen ranges
22043 // turn into a set of JUST comparators.
22046 function parseComparator(comp, options) {
22047 debug('comp', comp, options);
22048 comp = replaceCarets(comp, options);
22049 debug('caret', comp);
22050 comp = replaceTildes(comp, options);
22051 debug('tildes', comp);
22052 comp = replaceXRanges(comp, options);
22053 debug('xrange', comp);
22054 comp = replaceStars(comp, options);
22055 debug('stars', comp);
22060 return !id || id.toLowerCase() === 'x' || id === '*';
22061 } // ~, ~> --> * (any, kinda silly)
22062 // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
22063 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
22064 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
22065 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
22066 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
22069 function replaceTildes(comp, options) {
22070 return comp.trim().split(/\s+/).map(function (comp) {
22071 return replaceTilde(comp, options);
22075 function replaceTilde(comp, options) {
22076 var r = options.loose ? re[TILDELOOSE] : re[TILDE];
22077 return comp.replace(r, function (_, M, m, p, pr) {
22078 debug('tilde', comp, _, M, m, p, pr);
22083 } else if (isX(m)) {
22084 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
22085 } else if (isX(p)) {
22086 // ~1.2 == >=1.2.0 <1.3.0
22087 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
22089 debug('replaceTilde pr', pr);
22090 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0';
22092 // ~1.2.3 == >=1.2.3 <1.3.0
22093 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
22096 debug('tilde return', ret);
22099 } // ^ --> * (any, kinda silly)
22100 // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
22101 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
22102 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
22103 // ^1.2.3 --> >=1.2.3 <2.0.0
22104 // ^1.2.0 --> >=1.2.0 <2.0.0
22107 function replaceCarets(comp, options) {
22108 return comp.trim().split(/\s+/).map(function (comp) {
22109 return replaceCaret(comp, options);
22113 function replaceCaret(comp, options) {
22114 debug('caret', comp, options);
22115 var r = options.loose ? re[CARETLOOSE] : re[CARET];
22116 return comp.replace(r, function (_, M, m, p, pr) {
22117 debug('caret', comp, _, M, m, p, pr);
22122 } else if (isX(m)) {
22123 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
22124 } else if (isX(p)) {
22126 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
22128 ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
22131 debug('replaceCaret pr', pr);
22135 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1);
22137 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0';
22140 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0';
22147 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1);
22149 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
22152 ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0';
22156 debug('caret return', ret);
22161 function replaceXRanges(comp, options) {
22162 debug('replaceXRanges', comp, options);
22163 return comp.split(/\s+/).map(function (comp) {
22164 return replaceXRange(comp, options);
22168 function replaceXRange(comp, options) {
22169 comp = comp.trim();
22170 var r = options.loose ? re[XRANGELOOSE] : re[XRANGE];
22171 return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
22172 debug('xRange', comp, ret, gtlt, M, m, p, pr);
22174 var xm = xM || isX(m);
22175 var xp = xm || isX(p);
22178 if (gtlt === '=' && anyX) {
22183 if (gtlt === '>' || gtlt === '<') {
22184 // nothing is allowed
22187 // nothing is forbidden
22190 } else if (gtlt && anyX) {
22191 // we know patch is an x, because we have any x at all.
22192 // replace X with 0
22199 if (gtlt === '>') {
22202 // >1.2.3 => >= 1.2.4
22213 } else if (gtlt === '<=') {
22214 // <=0.7.x is actually <0.8.0, since any 0.7.x should
22215 // pass. Similarly, <=7.x is actually <8.0.0, etc.
22225 ret = gtlt + M + '.' + m + '.' + p;
22227 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
22229 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
22232 debug('xRange return', ret);
22235 } // Because * is AND-ed with everything else in the comparator,
22236 // and '' means "any version", just remove the *s entirely.
22239 function replaceStars(comp, options) {
22240 debug('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets!
22242 return comp.trim().replace(re[STAR], '');
22243 } // This function is passed to string.replace(re[HYPHENRANGE])
22244 // M, m, patch, prerelease, build
22245 // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
22246 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
22247 // 1.2 - 3.4 => >=1.2.0 <3.5.0
22250 function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
22253 } else if (isX(fm)) {
22254 from = '>=' + fM + '.0.0';
22255 } else if (isX(fp)) {
22256 from = '>=' + fM + '.' + fm + '.0';
22258 from = '>=' + from;
22263 } else if (isX(tm)) {
22264 to = '<' + (+tM + 1) + '.0.0';
22265 } else if (isX(tp)) {
22266 to = '<' + tM + '.' + (+tm + 1) + '.0';
22268 to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;
22273 return (from + ' ' + to).trim();
22274 } // if ANY of the sets match ALL of its comparators, then pass
22277 Range.prototype.test = function (version) {
22282 if (typeof version === 'string') {
22283 version = new SemVer(version, this.options);
22286 for (var i = 0; i < this.set.length; i++) {
22287 if (testSet(this.set[i], version, this.options)) {
22295 function testSet(set, version, options) {
22296 for (var i = 0; i < set.length; i++) {
22297 if (!set[i].test(version)) {
22302 if (version.prerelease.length && !options.includePrerelease) {
22303 // Find the set of versions that are allowed to have prereleases
22304 // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
22305 // That should allow `1.2.3-pr.2` to pass.
22306 // However, `1.2.4-alpha.notready` should NOT be allowed,
22307 // even though it's within the range set by the comparators.
22308 for (i = 0; i < set.length; i++) {
22309 debug(set[i].semver);
22311 if (set[i].semver === ANY) {
22315 if (set[i].semver.prerelease.length > 0) {
22316 var allowed = set[i].semver;
22318 if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
22322 } // Version has a -pre, but it's not one of the ones we like.
22331 exports.satisfies = satisfies;
22333 function satisfies(version, range, options) {
22335 range = new Range(range, options);
22340 return range.test(version);
22343 exports.maxSatisfying = maxSatisfying;
22345 function maxSatisfying(versions, range, options) {
22350 var rangeObj = new Range(range, options);
22355 versions.forEach(function (v) {
22356 if (rangeObj.test(v)) {
22357 // satisfies(v, range, options)
22358 if (!max || maxSV.compare(v) === -1) {
22359 // compare(max, v, true)
22361 maxSV = new SemVer(max, options);
22368 exports.minSatisfying = minSatisfying;
22370 function minSatisfying(versions, range, options) {
22375 var rangeObj = new Range(range, options);
22380 versions.forEach(function (v) {
22381 if (rangeObj.test(v)) {
22382 // satisfies(v, range, options)
22383 if (!min || minSV.compare(v) === 1) {
22384 // compare(min, v, true)
22386 minSV = new SemVer(min, options);
22393 exports.minVersion = minVersion;
22395 function minVersion(range, loose) {
22396 range = new Range(range, loose);
22397 var minver = new SemVer('0.0.0');
22399 if (range.test(minver)) {
22403 minver = new SemVer('0.0.0-0');
22405 if (range.test(minver)) {
22411 for (var i = 0; i < range.set.length; ++i) {
22412 var comparators = range.set[i];
22413 comparators.forEach(function (comparator) {
22414 // Clone to avoid manipulating the comparator's semver object.
22415 var compver = new SemVer(comparator.semver.version);
22417 switch (comparator.operator) {
22419 if (compver.prerelease.length === 0) {
22422 compver.prerelease.push(0);
22425 compver.raw = compver.format();
22431 if (!minver || gt(minver, compver)) {
22439 /* Ignore maximum versions */
22442 /* istanbul ignore next */
22445 throw new Error('Unexpected operation: ' + comparator.operator);
22450 if (minver && range.test(minver)) {
22457 exports.validRange = validRange;
22459 function validRange(range, options) {
22461 // Return '*' instead of '' so that truthiness works.
22462 // This will throw if it's invalid anyway
22463 return new Range(range, options).range || '*';
22467 } // Determine if version is less than all the versions possible in the range
22472 function ltr(version, range, options) {
22473 return outside(version, range, '<', options);
22474 } // Determine if version is greater than all the versions possible in the range.
22479 function gtr(version, range, options) {
22480 return outside(version, range, '>', options);
22483 exports.outside = outside;
22485 function outside(version, range, hilo, options) {
22486 version = new SemVer(version, options);
22487 range = new Range(range, options);
22488 var gtfn, ltefn, ltfn, comp, ecomp;
22508 throw new TypeError('Must provide a hilo val of "<" or ">"');
22509 } // If it satisifes the range it is not outside
22512 if (satisfies(version, range, options)) {
22514 } // From now on, variable terms are as if we're in "gtr" mode.
22515 // but note that everything is flipped for the "ltr" function.
22518 for (var i = 0; i < range.set.length; ++i) {
22519 var comparators = range.set[i];
22522 comparators.forEach(function (comparator) {
22523 if (comparator.semver === ANY) {
22524 comparator = new Comparator('>=0.0.0');
22527 high = high || comparator;
22528 low = low || comparator;
22530 if (gtfn(comparator.semver, high.semver, options)) {
22532 } else if (ltfn(comparator.semver, low.semver, options)) {
22535 }); // If the edge version comparator has a operator then our version
22536 // isn't outside it
22538 if (high.operator === comp || high.operator === ecomp) {
22540 } // If the lowest version comparator has an operator and our version
22541 // is less than it then it isn't higher than the range
22544 if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
22546 } else if (low.operator === ecomp && ltfn(version, low.semver)) {
22554 exports.prerelease = prerelease;
22556 function prerelease(version, options) {
22557 var parsed = parse(version, options);
22558 return parsed && parsed.prerelease.length ? parsed.prerelease : null;
22561 exports.intersects = intersects;
22563 function intersects(r1, r2, options) {
22564 r1 = new Range(r1, options);
22565 r2 = new Range(r2, options);
22566 return r1.intersects(r2);
22569 exports.coerce = coerce;
22571 function coerce(version) {
22572 if (version instanceof SemVer) {
22576 if (typeof version !== 'string') {
22580 var match = version.match(re[COERCE]);
22582 if (match == null) {
22586 return parse(match[1] + '.' + (match[2] || '0') + '.' + (match[3] || '0'));
22590 var hasOwnProperty$3 = Object.prototype.hasOwnProperty;
22591 var pseudomap = PseudoMap;
22593 function PseudoMap(set) {
22594 if (!(this instanceof PseudoMap)) // whyyyyyyy
22595 throw new TypeError("Constructor PseudoMap requires 'new'");
22599 if (set instanceof PseudoMap || typeof Map === 'function' && set instanceof Map) set.forEach(function (value, key) {
22600 this.set(key, value);
22601 }, this);else if (Array.isArray(set)) set.forEach(function (kv) {
22602 this.set(kv[0], kv[1]);
22603 }, this);else throw new TypeError('invalid argument');
22607 PseudoMap.prototype.forEach = function (fn, thisp) {
22608 thisp = thisp || this;
22609 Object.keys(this._data).forEach(function (k) {
22610 if (k !== 'size') fn.call(thisp, this._data[k].value, this._data[k].key);
22614 PseudoMap.prototype.has = function (k) {
22615 return !!find(this._data, k);
22618 PseudoMap.prototype.get = function (k) {
22619 var res = find(this._data, k);
22620 return res && res.value;
22623 PseudoMap.prototype.set = function (k, v) {
22624 set(this._data, k, v);
22627 PseudoMap.prototype.delete = function (k) {
22628 var res = find(this._data, k);
22631 delete this._data[res._index];
22636 PseudoMap.prototype.clear = function () {
22637 var data = Object.create(null);
22639 Object.defineProperty(this, '_data', {
22642 configurable: true,
22647 Object.defineProperty(PseudoMap.prototype, 'size', {
22649 return this._data.size;
22651 set: function (n) {},
22656 PseudoMap.prototype.values = PseudoMap.prototype.keys = PseudoMap.prototype.entries = function () {
22657 throw new Error('iterators are not implemented in this version');
22658 }; // Either identical, or both NaN
22661 function same(a, b) {
22662 return a === b || a !== a && b !== b;
22665 function Entry(k, v, i) {
22671 function find(data, k) {
22672 for (var i = 0, s = '_' + k, key = s; hasOwnProperty$3.call(data, key); key = s + i++) {
22673 if (same(data[key].key, k)) return data[key];
22677 function set(data, k, v) {
22678 for (var i = 0, s = '_' + k, key = s; hasOwnProperty$3.call(data, key); key = s + i++) {
22679 if (same(data[key].key, k)) {
22680 data[key].value = v;
22686 data[key] = new Entry(k, v, key);
22689 var map = createCommonjsModule(function (module) {
22690 if (process.env.npm_package_name === 'pseudomap' && process.env.npm_lifecycle_script === 'test') process.env.TEST_PSEUDOMAP = 'true';
22692 if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) {
22693 module.exports = Map;
22695 module.exports = pseudomap;
22699 var yallist = Yallist;
22700 Yallist.Node = Node;
22701 Yallist.create = Yallist;
22703 function Yallist(list) {
22706 if (!(self instanceof Yallist)) {
22707 self = new Yallist();
22714 if (list && typeof list.forEach === 'function') {
22715 list.forEach(function (item) {
22718 } else if (arguments.length > 0) {
22719 for (var i = 0, l = arguments.length; i < l; i++) {
22720 self.push(arguments[i]);
22727 Yallist.prototype.removeNode = function (node) {
22728 if (node.list !== this) {
22729 throw new Error('removing node which does not belong to this list');
22732 var next = node.next;
22733 var prev = node.prev;
22743 if (node === this.head) {
22747 if (node === this.tail) {
22751 node.list.length--;
22757 Yallist.prototype.unshiftNode = function (node) {
22758 if (node === this.head) {
22763 node.list.removeNode(node);
22766 var head = this.head;
22783 Yallist.prototype.pushNode = function (node) {
22784 if (node === this.tail) {
22789 node.list.removeNode(node);
22792 var tail = this.tail;
22809 Yallist.prototype.push = function () {
22810 for (var i = 0, l = arguments.length; i < l; i++) {
22811 push$1(this, arguments[i]);
22814 return this.length;
22817 Yallist.prototype.unshift = function () {
22818 for (var i = 0, l = arguments.length; i < l; i++) {
22819 unshift(this, arguments[i]);
22822 return this.length;
22825 Yallist.prototype.pop = function () {
22830 var res = this.tail.value;
22831 this.tail = this.tail.prev;
22834 this.tail.next = null;
22843 Yallist.prototype.shift = function () {
22848 var res = this.head.value;
22849 this.head = this.head.next;
22852 this.head.prev = null;
22861 Yallist.prototype.forEach = function (fn, thisp) {
22862 thisp = thisp || this;
22864 for (var walker = this.head, i = 0; walker !== null; i++) {
22865 fn.call(thisp, walker.value, i, this);
22866 walker = walker.next;
22870 Yallist.prototype.forEachReverse = function (fn, thisp) {
22871 thisp = thisp || this;
22873 for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
22874 fn.call(thisp, walker.value, i, this);
22875 walker = walker.prev;
22879 Yallist.prototype.get = function (n) {
22880 for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
22881 // abort out of the list early if we hit a cycle
22882 walker = walker.next;
22885 if (i === n && walker !== null) {
22886 return walker.value;
22890 Yallist.prototype.getReverse = function (n) {
22891 for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
22892 // abort out of the list early if we hit a cycle
22893 walker = walker.prev;
22896 if (i === n && walker !== null) {
22897 return walker.value;
22901 Yallist.prototype.map = function (fn, thisp) {
22902 thisp = thisp || this;
22903 var res = new Yallist();
22905 for (var walker = this.head; walker !== null;) {
22906 res.push(fn.call(thisp, walker.value, this));
22907 walker = walker.next;
22913 Yallist.prototype.mapReverse = function (fn, thisp) {
22914 thisp = thisp || this;
22915 var res = new Yallist();
22917 for (var walker = this.tail; walker !== null;) {
22918 res.push(fn.call(thisp, walker.value, this));
22919 walker = walker.prev;
22925 Yallist.prototype.reduce = function (fn, initial) {
22927 var walker = this.head;
22929 if (arguments.length > 1) {
22931 } else if (this.head) {
22932 walker = this.head.next;
22933 acc = this.head.value;
22935 throw new TypeError('Reduce of empty list with no initial value');
22938 for (var i = 0; walker !== null; i++) {
22939 acc = fn(acc, walker.value, i);
22940 walker = walker.next;
22946 Yallist.prototype.reduceReverse = function (fn, initial) {
22948 var walker = this.tail;
22950 if (arguments.length > 1) {
22952 } else if (this.tail) {
22953 walker = this.tail.prev;
22954 acc = this.tail.value;
22956 throw new TypeError('Reduce of empty list with no initial value');
22959 for (var i = this.length - 1; walker !== null; i--) {
22960 acc = fn(acc, walker.value, i);
22961 walker = walker.prev;
22967 Yallist.prototype.toArray = function () {
22968 var arr = new Array(this.length);
22970 for (var i = 0, walker = this.head; walker !== null; i++) {
22971 arr[i] = walker.value;
22972 walker = walker.next;
22978 Yallist.prototype.toArrayReverse = function () {
22979 var arr = new Array(this.length);
22981 for (var i = 0, walker = this.tail; walker !== null; i++) {
22982 arr[i] = walker.value;
22983 walker = walker.prev;
22989 Yallist.prototype.slice = function (from, to) {
22990 to = to || this.length;
22999 from += this.length;
23002 var ret = new Yallist();
23004 if (to < from || to < 0) {
23012 if (to > this.length) {
23016 for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
23017 walker = walker.next;
23020 for (; walker !== null && i < to; i++, walker = walker.next) {
23021 ret.push(walker.value);
23027 Yallist.prototype.sliceReverse = function (from, to) {
23028 to = to || this.length;
23037 from += this.length;
23040 var ret = new Yallist();
23042 if (to < from || to < 0) {
23050 if (to > this.length) {
23054 for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
23055 walker = walker.prev;
23058 for (; walker !== null && i > from; i--, walker = walker.prev) {
23059 ret.push(walker.value);
23065 Yallist.prototype.reverse = function () {
23066 var head = this.head;
23067 var tail = this.tail;
23069 for (var walker = head; walker !== null; walker = walker.prev) {
23070 var p = walker.prev;
23071 walker.prev = walker.next;
23080 function push$1(self, item) {
23081 self.tail = new Node(item, self.tail, null, self);
23084 self.head = self.tail;
23090 function unshift(self, item) {
23091 self.head = new Node(item, null, self.head, self);
23094 self.tail = self.head;
23100 function Node(value, prev, next, list) {
23101 if (!(this instanceof Node)) {
23102 return new Node(value, prev, next, list);
23106 this.value = value;
23123 var lruCache = LRUCache; // This will be a proper iterable 'Map' in engines that support it,
23124 // or a fakey-fake PseudoMap in older versions.
23125 // A linked list to keep track of recently-used-ness
23126 // use symbols if possible, otherwise just _props
23128 var hasSymbol = typeof Symbol === 'function' && process.env._nodeLRUCacheForceNoSymbol !== '1';
23132 makeSymbol = function (key) {
23133 return Symbol(key);
23136 makeSymbol = function (key) {
23141 var MAX = makeSymbol('max');
23142 var LENGTH = makeSymbol('length');
23143 var LENGTH_CALCULATOR = makeSymbol('lengthCalculator');
23144 var ALLOW_STALE = makeSymbol('allowStale');
23145 var MAX_AGE = makeSymbol('maxAge');
23146 var DISPOSE = makeSymbol('dispose');
23147 var NO_DISPOSE_ON_SET = makeSymbol('noDisposeOnSet');
23148 var LRU_LIST = makeSymbol('lruList');
23149 var CACHE = makeSymbol('cache');
23151 function naiveLength() {
23153 } // lruList is a yallist where the head is the youngest
23154 // item, and the tail is the oldest. the list contains the Hit
23155 // objects as the entries.
23156 // Each Hit object has a reference to its Yallist.Node. This
23159 // cache is a Map (or PseudoMap) that matches the keys to
23160 // the Yallist.Node object.
23163 function LRUCache(options) {
23164 if (!(this instanceof LRUCache)) {
23165 return new LRUCache(options);
23168 if (typeof options === 'number') {
23178 var max = this[MAX] = options.max; // Kind of weird to have a default max of Infinity, but oh well.
23180 if (!max || !(typeof max === 'number') || max <= 0) {
23181 this[MAX] = Infinity;
23184 var lc = options.length || naiveLength;
23186 if (typeof lc !== 'function') {
23190 this[LENGTH_CALCULATOR] = lc;
23191 this[ALLOW_STALE] = options.stale || false;
23192 this[MAX_AGE] = options.maxAge || 0;
23193 this[DISPOSE] = options.dispose;
23194 this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
23196 } // resize the cache when the max changes.
23199 Object.defineProperty(LRUCache.prototype, 'max', {
23200 set: function (mL) {
23201 if (!mL || !(typeof mL === 'number') || mL <= 0) {
23213 Object.defineProperty(LRUCache.prototype, 'allowStale', {
23214 set: function (allowStale) {
23215 this[ALLOW_STALE] = !!allowStale;
23218 return this[ALLOW_STALE];
23222 Object.defineProperty(LRUCache.prototype, 'maxAge', {
23223 set: function (mA) {
23224 if (!mA || !(typeof mA === 'number') || mA < 0) {
23228 this[MAX_AGE] = mA;
23232 return this[MAX_AGE];
23235 }); // resize the cache when the lengthCalculator changes.
23237 Object.defineProperty(LRUCache.prototype, 'lengthCalculator', {
23238 set: function (lC) {
23239 if (typeof lC !== 'function') {
23243 if (lC !== this[LENGTH_CALCULATOR]) {
23244 this[LENGTH_CALCULATOR] = lC;
23246 this[LRU_LIST].forEach(function (hit) {
23247 hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
23248 this[LENGTH] += hit.length;
23255 return this[LENGTH_CALCULATOR];
23259 Object.defineProperty(LRUCache.prototype, 'length', {
23261 return this[LENGTH];
23265 Object.defineProperty(LRUCache.prototype, 'itemCount', {
23267 return this[LRU_LIST].length;
23272 LRUCache.prototype.rforEach = function (fn, thisp) {
23273 thisp = thisp || this;
23275 for (var walker = this[LRU_LIST].tail; walker !== null;) {
23276 var prev = walker.prev;
23277 forEachStep(this, fn, walker, thisp);
23282 function forEachStep(self, fn, node, thisp) {
23283 var hit = node.value;
23285 if (isStale(self, hit)) {
23288 if (!self[ALLOW_STALE]) {
23294 fn.call(thisp, hit.value, hit.key, self);
23298 LRUCache.prototype.forEach = function (fn, thisp) {
23299 thisp = thisp || this;
23301 for (var walker = this[LRU_LIST].head; walker !== null;) {
23302 var next = walker.next;
23303 forEachStep(this, fn, walker, thisp);
23308 LRUCache.prototype.keys = function () {
23309 return this[LRU_LIST].toArray().map(function (k) {
23314 LRUCache.prototype.values = function () {
23315 return this[LRU_LIST].toArray().map(function (k) {
23320 LRUCache.prototype.reset = function () {
23321 if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) {
23322 this[LRU_LIST].forEach(function (hit) {
23323 this[DISPOSE](hit.key, hit.value);
23327 this[CACHE] = new map(); // hash of items by key
23329 this[LRU_LIST] = new yallist(); // list of items in order of use recency
23331 this[LENGTH] = 0; // length of items in the list
23334 LRUCache.prototype.dump = function () {
23335 return this[LRU_LIST].map(function (hit) {
23336 if (!isStale(this, hit)) {
23340 e: hit.now + (hit.maxAge || 0)
23343 }, this).toArray().filter(function (h) {
23348 LRUCache.prototype.dumpLru = function () {
23349 return this[LRU_LIST];
23351 /* istanbul ignore next */
23354 LRUCache.prototype.inspect = function (n, opts) {
23355 var str = 'LRUCache {';
23356 var extras = false;
23357 var as = this[ALLOW_STALE];
23360 str += '\n allowStale: true';
23364 var max = this[MAX];
23366 if (max && max !== Infinity) {
23371 str += '\n max: ' + util__default['default'].inspect(max, opts);
23375 var maxAge = this[MAX_AGE];
23382 str += '\n maxAge: ' + util__default['default'].inspect(maxAge, opts);
23386 var lc = this[LENGTH_CALCULATOR];
23388 if (lc && lc !== naiveLength) {
23393 str += '\n length: ' + util__default['default'].inspect(this[LENGTH], opts);
23397 var didFirst = false;
23398 this[LRU_LIST].forEach(function (item) {
23410 var key = util__default['default'].inspect(item.key).split('\n').join('\n ');
23415 if (item.maxAge !== maxAge) {
23416 val.maxAge = item.maxAge;
23419 if (lc !== naiveLength) {
23420 val.length = item.length;
23423 if (isStale(this, item)) {
23427 val = util__default['default'].inspect(val, opts).split('\n').join('\n ');
23428 str += key + ' => ' + val;
23431 if (didFirst || extras) {
23439 LRUCache.prototype.set = function (key, value, maxAge) {
23440 maxAge = maxAge || this[MAX_AGE];
23441 var now = maxAge ? Date.now() : 0;
23442 var len = this[LENGTH_CALCULATOR](value, key);
23444 if (this[CACHE].has(key)) {
23445 if (len > this[MAX]) {
23446 del(this, this[CACHE].get(key));
23450 var node = this[CACHE].get(key);
23451 var item = node.value; // dispose of the old one before overwriting
23452 // split out into 2 ifs for better coverage tracking
23454 if (this[DISPOSE]) {
23455 if (!this[NO_DISPOSE_ON_SET]) {
23456 this[DISPOSE](key, item.value);
23461 item.maxAge = maxAge;
23462 item.value = value;
23463 this[LENGTH] += len - item.length;
23470 var hit = new Entry$1(key, value, len, now, maxAge); // oversized objects fall out of cache automatically.
23472 if (hit.length > this[MAX]) {
23473 if (this[DISPOSE]) {
23474 this[DISPOSE](key, value);
23480 this[LENGTH] += hit.length;
23481 this[LRU_LIST].unshift(hit);
23482 this[CACHE].set(key, this[LRU_LIST].head);
23487 LRUCache.prototype.has = function (key) {
23488 if (!this[CACHE].has(key)) return false;
23489 var hit = this[CACHE].get(key).value;
23491 if (isStale(this, hit)) {
23498 LRUCache.prototype.get = function (key) {
23499 return get(this, key, true);
23502 LRUCache.prototype.peek = function (key) {
23503 return get(this, key, false);
23506 LRUCache.prototype.pop = function () {
23507 var node = this[LRU_LIST].tail;
23508 if (!node) return null;
23513 LRUCache.prototype.del = function (key) {
23514 del(this, this[CACHE].get(key));
23517 LRUCache.prototype.load = function (arr) {
23520 var now = Date.now(); // A previous serialized cache has the most recent items first
23522 for (var l = arr.length - 1; l >= 0; l--) {
23524 var expiresAt = hit.e || 0;
23526 if (expiresAt === 0) {
23527 // the item was created without expiration in a non aged cache
23528 this.set(hit.k, hit.v);
23530 var maxAge = expiresAt - now; // dont add already expired items
23533 this.set(hit.k, hit.v, maxAge);
23539 LRUCache.prototype.prune = function () {
23541 this[CACHE].forEach(function (value, key) {
23542 get(self, key, false);
23546 function get(self, key, doUse) {
23547 var node = self[CACHE].get(key);
23550 var hit = node.value;
23552 if (isStale(self, hit)) {
23554 if (!self[ALLOW_STALE]) hit = undefined;
23557 self[LRU_LIST].unshiftNode(node);
23561 if (hit) hit = hit.value;
23567 function isStale(self, hit) {
23568 if (!hit || !hit.maxAge && !self[MAX_AGE]) {
23573 var diff = Date.now() - hit.now;
23576 stale = diff > hit.maxAge;
23578 stale = self[MAX_AGE] && diff > self[MAX_AGE];
23584 function trim$2(self) {
23585 if (self[LENGTH] > self[MAX]) {
23586 for (var walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) {
23587 // We know that we're about to delete this one, and also
23588 // what the next least recently used key will be, so just
23589 // go ahead and set it now.
23590 var prev = walker.prev;
23597 function del(self, node) {
23599 var hit = node.value;
23601 if (self[DISPOSE]) {
23602 self[DISPOSE](hit.key, hit.value);
23605 self[LENGTH] -= hit.length;
23606 self[CACHE].delete(hit.key);
23607 self[LRU_LIST].removeNode(node);
23609 } // classy, since V8 prefers predictable objects.
23612 function Entry$1(key, value, length, now, maxAge) {
23614 this.value = value;
23615 this.length = length;
23617 this.maxAge = maxAge || 0;
23620 var sigmund_1 = sigmund;
23622 function sigmund(subject, maxSessions) {
23623 maxSessions = maxSessions || 10;
23628 function psychoAnalyze(subject, session) {
23629 if (session > maxSessions) return;
23631 if (typeof subject === 'function' || typeof subject === 'undefined') {
23635 if (typeof subject !== 'object' || !subject || subject instanceof RE) {
23636 analysis += subject;
23640 if (notes.indexOf(subject) !== -1 || session === maxSessions) return;
23641 notes.push(subject);
23643 Object.keys(subject).forEach(function (issue, _, __) {
23644 // pseudo-private values. skip those.
23645 if (issue.charAt(0) === '_') return;
23646 var to = typeof subject[issue];
23647 if (to === 'function' || to === 'undefined') return;
23649 psychoAnalyze(subject[issue], session + 1);
23653 psychoAnalyze(subject, 0);
23655 } // vim: set softtabstop=4 shiftwidth=4:
23657 var fnmatch = createCommonjsModule(function (module, exports) {
23658 // Based on minimatch.js by isaacs <https://npmjs.org/package/minimatch>
23659 var platform = typeof process === "object" ? process.platform : "win32";
23660 if (module) module.exports = minimatch;else exports.minimatch = minimatch;
23661 minimatch.Minimatch = Minimatch;
23662 var cache = minimatch.cache = new lruCache({
23665 GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
23666 var qmark = "[^/]" // * => any number of characters
23668 star = qmark + "*?" // ** when dots are allowed. Anything goes, except .. and .
23669 // not (^ or / followed by one or two dots followed by $ or /),
23670 // followed by anything, any number of times.
23672 twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" // not a ^ or / followed by a dot,
23673 // followed by anything, any number of times.
23675 twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" // characters that need to be escaped in RegExp.
23677 reSpecials = charSet("().*{}+?[]^$\\!"); // "abc" -> { a:true, b:true, c:true }
23679 function charSet(s) {
23680 return s.split("").reduce(function (set, c) {
23684 } // normalizes slashes.
23687 var slashSplit = /\/+/;
23688 minimatch.monkeyPatch = monkeyPatch;
23690 function monkeyPatch() {
23691 var desc = Object.getOwnPropertyDescriptor(String.prototype, "match");
23692 var orig = desc.value;
23694 desc.value = function (p) {
23695 if (p instanceof Minimatch) return p.match(this);
23696 return orig.call(this, p);
23699 Object.defineProperty(String.prototype, desc);
23702 minimatch.filter = filter;
23704 function filter(pattern, options) {
23705 options = options || {};
23706 return function (p, i, list) {
23707 return minimatch(p, pattern, options);
23711 function ext(a, b) {
23715 Object.keys(b).forEach(function (k) {
23718 Object.keys(a).forEach(function (k) {
23724 minimatch.defaults = function (def) {
23725 if (!def || !Object.keys(def).length) return minimatch;
23726 var orig = minimatch;
23728 var m = function minimatch(p, pattern, options) {
23729 return orig.minimatch(p, pattern, ext(def, options));
23732 m.Minimatch = function Minimatch(pattern, options) {
23733 return new orig.Minimatch(pattern, ext(def, options));
23739 Minimatch.defaults = function (def) {
23740 if (!def || !Object.keys(def).length) return Minimatch;
23741 return minimatch.defaults(def).Minimatch;
23744 function minimatch(p, pattern, options) {
23745 if (typeof pattern !== "string") {
23746 throw new TypeError("glob pattern string required");
23749 if (!options) options = {}; // shortcut: comments match nothing.
23751 if (!options.nocomment && pattern.charAt(0) === "#") {
23753 } // "" only matches ""
23756 if (pattern.trim() === "") return p === "";
23757 return new Minimatch(pattern, options).match(p);
23760 function Minimatch(pattern, options) {
23761 if (!(this instanceof Minimatch)) {
23762 return new Minimatch(pattern, options, cache);
23765 if (typeof pattern !== "string") {
23766 throw new TypeError("glob pattern string required");
23769 if (!options) options = {}; // windows: need to use /, not \
23770 // On other platforms, \ is a valid (albeit bad) filename char.
23772 if (platform === "win32") {
23773 pattern = pattern.split("\\").join("/");
23775 // these things aren't particularly big, but walking down the string
23776 // and turning it into a regexp can get pretty costly.
23779 var cacheKey = pattern + "\n" + sigmund_1(options);
23780 var cached = minimatch.cache.get(cacheKey);
23781 if (cached) return cached;
23782 minimatch.cache.set(cacheKey, this);
23783 this.options = options;
23785 this.pattern = pattern;
23786 this.regexp = null;
23787 this.negate = false;
23788 this.comment = false;
23789 this.empty = false; // make the set of regexps etc.
23794 Minimatch.prototype.make = make;
23797 // don't do it more than once.
23798 if (this._made) return;
23799 var pattern = this.pattern;
23800 var options = this.options; // empty patterns and comments match nothing.
23802 if (!options.nocomment && pattern.charAt(0) === "#") {
23803 this.comment = true;
23810 } // step 1: figure out negation, etc.
23813 this.parseNegate(); // step 2: expand braces
23815 var set = this.globSet = this.braceExpand();
23816 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
23817 // matching patterns.
23818 // These will be regexps, except in the case of "**", which is
23819 // set to the GLOBSTAR object for globstar behavior,
23820 // and will not contain any / characters
23822 set = this.globParts = set.map(function (s) {
23823 return s.split(slashSplit);
23825 if (options.debug) console.error(this.pattern, set); // glob --> regexps
23827 set = set.map(function (s, si, set) {
23828 return s.map(this.parse, this);
23830 if (options.debug) console.error(this.pattern, set); // filter out everything that didn't compile properly.
23832 set = set.filter(function (s) {
23833 return -1 === s.indexOf(false);
23835 if (options.debug) console.error(this.pattern, set);
23839 Minimatch.prototype.parseNegate = parseNegate;
23841 function parseNegate() {
23842 var pattern = this.pattern,
23844 options = this.options,
23846 if (options.nonegate) return;
23848 for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) {
23853 if (negateOffset) this.pattern = pattern.substr(negateOffset);
23854 this.negate = negate;
23855 } // Brace expansion:
23856 // a{b,c}d -> abd acd
23857 // a{b,}c -> abc ac
23858 // a{0..3}d -> a0d a1d a2d a3d
23859 // a{b,c{d,e}f}g -> abg acdfg acefg
23860 // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
23862 // Invalid sets are not expanded.
23863 // a{2..}b -> a{2..}b
23867 minimatch.braceExpand = function (pattern, options) {
23868 return new Minimatch(pattern, options).braceExpand();
23871 Minimatch.prototype.braceExpand = braceExpand;
23873 function braceExpand(pattern, options) {
23874 options = options || this.options;
23875 pattern = typeof pattern === "undefined" ? this.pattern : pattern;
23877 if (typeof pattern === "undefined") {
23878 throw new Error("undefined pattern");
23881 if (options.nobrace || !pattern.match(/\{.*\}/)) {
23882 // shortcut. no need to expand.
23886 var escaping = false; // examples and comments refer to this crazy pattern:
23887 // a{b,c{d,e},{f,g}h}x{y,z}
23899 // everything before the first \{ is just a prefix.
23900 // So, we pluck that off, and work with the rest,
23901 // and then prepend it to everything we find.
23903 if (pattern.charAt(0) !== "{") {
23904 // console.error(pattern)
23907 for (var i = 0, l = pattern.length; i < l; i++) {
23908 var c = pattern.charAt(i); // console.error(i, c)
23911 escaping = !escaping;
23912 } else if (c === "{" && !escaping) {
23913 prefix = pattern.substr(0, i);
23916 } // actually no sets, all { were escaped.
23919 if (prefix === null) {
23920 // console.error("no sets")
23924 var tail = braceExpand(pattern.substr(i), options);
23925 return tail.map(function (t) {
23928 } // now we have something like:
23929 // {b,c{d,e},{f,g}h}x{y,z}
23930 // walk through the set, expanding each part, until
23931 // the set ends. then, we'll expand the suffix.
23932 // If the set only has a single member, then'll put the {} back
23933 // first, handle numeric sets, since they're easier
23936 var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/);
23939 // console.error("numset", numset[1], numset[2])
23940 var suf = braceExpand(pattern.substr(numset[0].length), options),
23941 start = +numset[1],
23943 inc = start > end ? -1 : 1,
23946 for (var i = start; i != end + inc; i += inc) {
23947 // append all the suffixes
23948 for (var ii = 0, ll = suf.length; ii < ll; ii++) {
23949 set.push(i + suf[ii]);
23954 } // ok, walk through the set
23955 // We hope, somewhat optimistically, that there
23956 // will be a } at the end.
23957 // If the closing brace isn't found, then the pattern is
23958 // interpreted as braceExpand("\\" + pattern) so that
23959 // the leading \{ will be interpreted literally.
23962 var i = 1 // skip the \{
23969 function addMember() {
23972 } // console.error("Entering for")
23975 FOR: for (i = 1, l = pattern.length; i < l; i++) {
23976 var c = pattern.charAt(i); // console.error("", i, c)
23980 member += "\\" + c;
23993 depth--; // if this closes the actual set, then we're done
23996 addMember(); // pluck off the close-brace
24022 // now we've either finished the set, and the suffix is
24023 // pattern.substr(i), or we have *not* closed the set,
24024 // and need to escape the leading brace
24028 // console.error("didn't close", pattern)
24029 return braceExpand("\\" + pattern, options);
24030 } // x{y,z} -> ["xy", "xz"]
24031 // console.error("set", set)
24032 // console.error("suffix", pattern.substr(i))
24035 var suf = braceExpand(pattern.substr(i), options); // ["b", "c{d,e}","{f,g}h"] ->
24036 // [["b"], ["cd", "ce"], ["fh", "gh"]]
24038 var addBraces = set.length === 1; // console.error("set pre-expanded", set)
24040 set = set.map(function (p) {
24041 return braceExpand(p, options);
24042 }); // console.error("set expanded", set)
24043 // [["b"], ["cd", "ce"], ["fh", "gh"]] ->
24044 // ["b", "cd", "ce", "fh", "gh"]
24046 set = set.reduce(function (l, r) {
24047 return l.concat(r);
24051 set = set.map(function (s) {
24052 return "{" + s + "}";
24054 } // now attach the suffixes.
24059 for (var i = 0, l = set.length; i < l; i++) {
24060 for (var ii = 0, ll = suf.length; ii < ll; ii++) {
24061 ret.push(set[i] + suf[ii]);
24066 } // parse a component of the expanded set.
24067 // At this point, no pattern may contain "/" in it
24068 // so we're going to return a 2d array, where each entry is the full
24069 // pattern, split on '/', and then turned into a regular expression.
24070 // A regexp is made at the end which joins each array with an
24071 // escaped /, and another full one which joins each regexp with |.
24073 // Following the lead of Bash 4.1, note that "**" only has special meaning
24074 // when it is the *only* thing in a path portion. Otherwise, any series
24075 // of * is equivalent to a single *. Globstar behavior is enabled by
24076 // default, and can be disabled by setting options.noglobstar.
24079 Minimatch.prototype.parse = parse;
24082 function parse(pattern, isSub) {
24083 var options = this.options; // shortcuts
24085 if (!options.noglobstar && pattern === "**") return GLOBSTAR;
24086 if (pattern === "") return "";
24088 hasMagic = !!options.nocase,
24089 escaping = false // ? => one single character
24091 patternListStack = [],
24096 classStart = -1 // . and .. never match anything that doesn't start with .,
24097 // even when options.dot is set.
24099 patternStart = pattern.charAt(0) === "." ? "" // anything
24100 // not (start or / followed by . or .. followed by / or end)
24101 : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" : "(?!\\.)";
24103 function clearStateChar() {
24105 // we had some state-tracking character
24106 // that wasn't consumed by this pass.
24107 switch (stateChar) {
24119 re += "\\" + stateChar;
24127 for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
24128 if (options.debug) {
24129 console.error("%s\t%s %s %j", pattern, i, re, c);
24130 } // skip over any that are escaped.
24133 if (escaping && reSpecials[c]) {
24141 // completely not allowed, even escaped.
24142 // Should already be path-split by now.
24149 // the various stateChar values
24150 // for the "extglob" stuff.
24157 if (options.debug) {
24158 console.error("%s\t%s %s %j <-- stateChar", pattern, i, re, c);
24159 } // all of those are literals inside a class, except that
24160 // the glob [!a] means [^a] in regexp
24164 if (c === "!" && i === classStart + 1) c = "^";
24167 } // if we already have a stateChar, then it means
24168 // that there was something like ** or +? in there.
24169 // Handle the stateChar, then proceed with this one.
24173 stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
24174 // just clear the statechar *now*, rather than even diving into
24175 // the patternList stuff.
24177 if (options.noext) clearStateChar();
24191 plType = stateChar;
24192 patternListStack.push({
24196 }); // negation is (?:(?!js)[^/]*)
24198 re += stateChar === "!" ? "(?:(?!" : "(?:";
24203 if (inClass || !patternListStack.length) {
24210 plType = patternListStack.pop().type; // negation is (?:(?!js)[^/]*)
24211 // The others are (?:<pattern>)<type>
24222 // the default anyway
24228 if (inClass || !patternListStack.length || escaping) {
24236 // these are mostly the same in regexp and glob
24239 // swallow any state-tracking char before the [
24249 reClassStart = re.length;
24254 // a right bracket shall lose its special
24255 // meaning and represent itself in
24256 // a bracket expression if it occurs
24257 // first in the list. -- POSIX.2 2.8.3.2
24258 if (i === classStart + 1 || !inClass) {
24262 } // finish up the class.
24271 // swallow any state char that wasn't consumed
24277 } else if (reSpecials[c] && !(c === "^" && inClass)) {
24285 // handle the case where we left a class open.
24286 // "[abc" is valid, equivalent to "\[abc"
24290 // split where the last [ was, and escape it
24291 // this is a huge pita. We now have to re-walk
24292 // the contents of the would-be class to re-translate
24293 // any characters that were passed through as-is
24294 var cs = pattern.substr(classStart + 1),
24295 sp = this.parse(cs, SUBPARSE);
24296 re = re.substr(0, reClassStart) + "\\[" + sp[0];
24297 hasMagic = hasMagic || sp[1];
24298 } // handle the case where we had a +( thing at the *end*
24300 // each pattern list stack adds 3 chars, and we need to go through
24301 // and escape any | chars that were passed through as-is for the regexp.
24302 // Go through and escape them, taking care not to double-escape any
24303 // | chars that were already escaped.
24308 while (pl = patternListStack.pop()) {
24309 var tail = re.slice(pl.reStart + 3); // maybe some even number of \, then maybe 1 \, followed by a |
24311 tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {
24313 // the | isn't already escaped, so escape it.
24315 } // need to escape all those slashes *again*, without escaping the
24316 // one that we need for escaping the | character. As it works out,
24317 // escaping an even number of slashes can be done by simply repeating
24318 // it exactly after itself. That's why this trick works.
24320 // I am sorry that you have to see this.
24323 return $1 + $1 + $2 + "|";
24324 }); // console.error("tail=%j\n %s", tail, tail)
24326 var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
24328 re = re.slice(0, pl.reStart) + t + "\\(" + tail;
24329 } // handle trailing things that only matter at the very end.
24337 } // only need to apply the nodot start if the re starts with
24338 // something that could conceivably capture a dot
24341 var addPatternStart = false;
24343 switch (re.charAt(0)) {
24347 addPatternStart = true;
24348 } // if the re is not "" at this point, then we need to make sure
24349 // it doesn't match against an empty path part.
24350 // Otherwise a/* will match a/, which it should not.
24353 if (re !== "" && hasMagic) re = "(?=.)" + re;
24354 if (addPatternStart) re = patternStart + re; // parsing just a piece of a larger pattern.
24356 if (isSub === SUBPARSE) {
24357 return [re, hasMagic];
24358 } // skip the regexp for non-magical patterns
24359 // unescape anything in it, though, so that it'll be
24360 // an exact match against a file etc.
24364 return globUnescape(pattern);
24367 var flags = options.nocase ? "i" : "",
24368 regExp = new RegExp("^" + re + "$", flags);
24369 regExp._glob = pattern;
24374 minimatch.makeRe = function (pattern, options) {
24375 return new Minimatch(pattern, options || {}).makeRe();
24378 Minimatch.prototype.makeRe = makeRe;
24380 function makeRe() {
24381 if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
24382 // pattern strings, or "**".
24384 // It's better to use .match(). This function shouldn't
24385 // be used, really, but it's pretty convenient sometimes,
24386 // when you just want to work with a regex.
24388 var set = this.set;
24389 if (!set.length) return this.regexp = false;
24390 var options = this.options;
24391 var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot,
24392 flags = options.nocase ? "i" : "";
24393 var re = set.map(function (pattern) {
24394 return pattern.map(function (p) {
24395 return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src;
24397 }).join("|"); // must match entire pattern
24398 // ending in a * or ** will make it less strict.
24400 re = "^(?:" + re + ")$"; // can match anything, as long as it's not this.
24402 if (this.negate) re = "^(?!" + re + ").*$";
24405 return this.regexp = new RegExp(re, flags);
24407 return this.regexp = false;
24411 minimatch.match = function (list, pattern, options) {
24412 var mm = new Minimatch(pattern, options);
24413 list = list.filter(function (f) {
24414 return mm.match(f);
24417 if (options.nonull && !list.length) {
24418 list.push(pattern);
24424 Minimatch.prototype.match = match;
24426 function match(f, partial) {
24427 // console.error("match", f, this.pattern)
24428 // short-circuit in the case of busted things.
24430 if (this.comment) return false;
24431 if (this.empty) return f === "";
24432 if (f === "/" && partial) return true;
24433 var options = this.options; // windows: need to use /, not \
24434 // On other platforms, \ is a valid (albeit bad) filename char.
24436 if (platform === "win32") {
24437 f = f.split("\\").join("/");
24438 } // treat the test path as a set of pathparts.
24441 f = f.split(slashSplit);
24443 if (options.debug) {
24444 console.error(this.pattern, "split", f);
24445 } // just ONE of the pattern sets in this.set needs to match
24446 // in order for it to be valid. If negating, then just one
24447 // match means that we have failed.
24448 // Either way, return on the first hit.
24451 var set = this.set; // console.error(this.pattern, "set", set)
24453 for (var i = 0, l = set.length; i < l; i++) {
24454 var pattern = set[i];
24455 var hit = this.matchOne(f, pattern, partial);
24458 if (options.flipNegate) return true;
24459 return !this.negate;
24461 } // didn't get any hits. this is success if it's a negative
24462 // pattern, failure otherwise.
24465 if (options.flipNegate) return false;
24466 return this.negate;
24467 } // set partial to true to test if, for example,
24468 // "/a/b" matches the start of "/*/b/*/d"
24469 // Partial means, if you run out of file before you run
24470 // out of pattern, then that's fine, as long as all
24471 // the parts match.
24474 Minimatch.prototype.matchOne = function (file, pattern, partial) {
24475 var options = this.options;
24477 if (options.debug) {
24478 console.error("matchOne", {
24485 if (options.matchBase && pattern.length === 1) {
24486 file = path__default['default'].basename(file.join("/")).split("/");
24489 if (options.debug) {
24490 console.error("matchOne", file.length, pattern.length);
24493 for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
24494 if (options.debug) {
24495 console.error("matchOne loop");
24498 var p = pattern[pi],
24501 if (options.debug) {
24502 console.error(pattern, p, f);
24503 } // should be impossible.
24504 // some invalid regexp stuff in the set.
24507 if (p === false) return false;
24509 if (p === GLOBSTAR) {
24510 if (options.debug) console.error('GLOBSTAR', [pattern, p, f]); // "**"
24511 // a/**/b/**/c would match the following:
24516 // To do this, take the rest of the pattern after
24517 // the **, and see if it would match the file remainder.
24518 // If so, return success.
24519 // If not, the ** "swallows" a segment, and try again.
24520 // This is recursively awful.
24522 // a/**/b/**/c matching a/b/x/y/z/c
24525 // - matchOne(b/x/y/z/c, b/**/c)
24528 // - matchOne(x/y/z/c, c) -> no
24529 // - matchOne(y/z/c, c) -> no
24530 // - matchOne(z/c, c) -> no
24531 // - matchOne(c, c) yes, hit
24537 if (options.debug) console.error('** at the end'); // a ** at the end will just swallow the rest.
24538 // We have found a match.
24539 // however, it will not swallow /.x, unless
24540 // options.dot is set.
24541 // . and .. are *never* matched by **, for explosively
24542 // exponential reasons.
24544 for (; fi < fl; fi++) {
24545 if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
24549 } // ok, let's see if we can swallow whatever we can.
24552 WHILE: while (fr < fl) {
24553 var swallowee = file[fr];
24555 if (options.debug) {
24556 console.error('\nglobstar while', file, fr, pattern, pr, swallowee);
24557 } // XXX remove this slice. Just pass the start index.
24560 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
24561 if (options.debug) console.error('globstar found match!', fr, fl, swallowee); // found a match.
24565 // can't swallow "." or ".." ever.
24566 // can only swallow ".foo" when explicitly asked.
24567 if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
24568 if (options.debug) console.error("dot detected!", file, fr, pattern, pr);
24570 } // ** swallows a segment, and continue.
24573 if (options.debug) console.error('globstar swallow a segment, and continue');
24576 } // no match was found.
24577 // However, in partial mode, we can't say this is necessarily over.
24578 // If there's more *pattern* left, then
24583 // console.error("\n>>> no match, partial?", file, fr, pattern, pr)
24584 if (fr === fl) return true;
24588 } // something other than **
24589 // non-magic patterns just have to match exactly
24590 // patterns with magic have been turned into regexps.
24595 if (typeof p === "string") {
24596 if (options.nocase) {
24597 hit = f.toLowerCase() === p.toLowerCase();
24602 if (options.debug) {
24603 console.error("string match", p, f, hit);
24608 if (options.debug) {
24609 console.error("pattern match", p, f, hit);
24613 if (!hit) return false;
24614 } // Note: ending in / means that we'll get a final ""
24615 // at the end of the pattern. This can only match a
24616 // corresponding "" at the end of the file.
24617 // If the file ends in /, then it can only match a
24618 // a pattern that ends in /, unless the pattern just
24619 // doesn't have any more for it. But, a/b/ should *not*
24620 // match "a/b/*", even though "" matches against the
24621 // [^/]*? pattern, except in partial mode, where it might
24622 // simply not be reached yet.
24623 // However, a/b/ should still satisfy a/*
24624 // now either we fell off the end of the pattern, or we're done.
24627 if (fi === fl && pi === pl) {
24628 // ran out of pattern and filename at the same time.
24631 } else if (fi === fl) {
24632 // ran out of file, but still had pattern left.
24633 // this is ok if we're doing the match as part of
24634 // a glob fs traversal.
24636 } else if (pi === pl) {
24637 // ran out of pattern, still have file left.
24638 // this is only acceptable if we're on the very last
24639 // empty segment of a file with a trailing slash.
24640 // a/* should match a/b/
24641 var emptyFileEnd = fi === fl - 1 && file[fi] === "";
24642 return emptyFileEnd;
24643 } // should be unreachable.
24646 throw new Error("wtf?");
24647 }; // replace stuff like \* with *
24650 function globUnescape(s) {
24651 return s.replace(/\\(.)/g, "$1");
24654 function regExpEscape(s) {
24655 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
24659 var ini = createCommonjsModule(function (module, exports) {
24661 var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
24662 return new (P || (P = Promise))(function (resolve, reject) {
24663 function fulfilled(value) {
24665 step(generator.next(value));
24671 function rejected(value) {
24673 step(generator["throw"](value));
24679 function step(result) {
24680 result.done ? resolve(result.value) : new P(function (resolve) {
24681 resolve(result.value);
24682 }).then(fulfilled, rejected);
24685 step((generator = generator.apply(thisArg, _arguments || [])).next());
24689 var __generator = this && this.__generator || function (thisArg, body) {
24692 sent: function () {
24693 if (t[0] & 1) throw t[1];
24707 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
24712 return function (v) {
24713 return step([n, v]);
24717 function step(op) {
24718 if (f) throw new TypeError("Generator is already executing.");
24721 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;
24722 if (y = 0, t) op = [op[0] & 2, t.value];
24751 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
24756 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
24761 if (op[0] === 6 && _.label < t[1]) {
24767 if (t && _.label < t[2]) {
24775 if (t[2]) _.ops.pop();
24782 op = body.call(thisArg, _);
24790 if (op[0] & 5) throw op[1];
24792 value: op[0] ? op[1] : void 0,
24798 var __importStar = this && this.__importStar || function (mod) {
24799 if (mod && mod.__esModule) return mod;
24801 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
24802 result["default"] = mod;
24806 Object.defineProperty(exports, "__esModule", {
24810 var fs = __importStar(fs__default['default']);
24812 * define the possible values:
\r
24813 * section: [section]
\r
24814 * param: key=value
\r
24815 * comment: ;this is a comment
\r
24820 section: /^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$/,
24821 param: /^\s*([\w\.\-\_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$/,
24822 comment: /^\s*[#;].*$/
24825 * Parses an .ini file
\r
24826 * @param file The location of the .ini file
\r
24829 function parse(file) {
24830 return __awaiter(this, void 0, void 0, function () {
24831 return __generator(this, function (_a) {
24834 , new Promise(function (resolve, reject) {
24835 fs.readFile(file, 'utf8', function (err, data) {
24841 resolve(parseString(data));
24848 exports.parse = parse;
24850 function parseSync(file) {
24851 return parseString(fs.readFileSync(file, 'utf8'));
24854 exports.parseSync = parseSync;
24856 function parseString(data) {
24857 var sectionBody = {};
24858 var sectionName = null;
24859 var value = [[sectionName, sectionBody]];
24860 var lines = data.split(/\r\n|\r|\n/);
24861 lines.forEach(function (line) {
24864 if (regex.comment.test(line)) {
24868 if (regex.param.test(line)) {
24869 match = line.match(regex.param);
24870 sectionBody[match[1]] = match[2];
24871 } else if (regex.section.test(line)) {
24872 match = line.match(regex.section);
24873 sectionName = match[1];
24875 value.push([sectionName, sectionBody]);
24881 exports.parseString = parseString;
24884 var name$1 = "editorconfig";
24885 var version$1 = "0.15.3";
24886 var description$1 = "EditorConfig File Locator and Interpreter for Node.js";
24891 var main$1 = "src/index.js";
24892 var contributors = [
24893 "Hong Xu (topbug.net)",
24894 "Jed Mao (https://github.com/jedmao/)",
24895 "Trey Hunner (http://treyhunner.com)"
24897 var directories = {
24902 clean: "rimraf dist",
24903 prebuild: "npm run clean",
24905 pretest: "npm run lint && npm run build && npm run copy && cmake .",
24907 "pretest:ci": "npm run pretest",
24908 "test:ci": "ctest -VV --output-on-failure .",
24909 lint: "npm run eclint && npm run tslint",
24910 eclint: "eclint check --indent_size ignore \"src/**\"",
24911 tslint: "tslint --project tsconfig.json --exclude package.json",
24912 copy: "cpy .npmignore LICENSE README.md CHANGELOG.md dist && cpy bin/* dist/bin && cpy src/lib/fnmatch*.* dist/src/lib",
24913 prepub: "npm run lint && npm run build && npm run copy",
24914 pub: "npm publish ./dist"
24916 var repository$1 = {
24918 url: "git://github.com/editorconfig/editorconfig-core-js.git"
24920 var bugs = "https://github.com/editorconfig/editorconfig-core-js/issues";
24921 var author$1 = "EditorConfig Team";
24922 var license$1 = "MIT";
24923 var dependencies$1 = {
24924 commander: "^2.19.0",
24925 "lru-cache": "^4.1.5",
24929 var devDependencies$1 = {
24930 "@types/mocha": "^5.2.6",
24931 "@types/node": "^10.12.29",
24932 "@types/semver": "^5.5.0",
24933 "cpy-cli": "^2.0.0",
24939 typescript: "^3.3.3333"
24943 version: version$1,
24944 description: description$1,
24945 keywords: keywords,
24947 contributors: contributors,
24948 directories: directories,
24949 scripts: scripts$1,
24950 repository: repository$1,
24953 license: license$1,
24954 dependencies: dependencies$1,
24955 devDependencies: devDependencies$1
24958 var src$1 = createCommonjsModule(function (module, exports) {
24960 var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
24961 return new (P || (P = Promise))(function (resolve, reject) {
24962 function fulfilled(value) {
24964 step(generator.next(value));
24970 function rejected(value) {
24972 step(generator["throw"](value));
24978 function step(result) {
24979 result.done ? resolve(result.value) : new P(function (resolve) {
24980 resolve(result.value);
24981 }).then(fulfilled, rejected);
24984 step((generator = generator.apply(thisArg, _arguments || [])).next());
24988 var __generator = this && this.__generator || function (thisArg, body) {
24991 sent: function () {
24992 if (t[0] & 1) throw t[1];
25006 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
25011 return function (v) {
25012 return step([n, v]);
25016 function step(op) {
25017 if (f) throw new TypeError("Generator is already executing.");
25020 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;
25021 if (y = 0, t) op = [op[0] & 2, t.value];
25050 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
25055 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
25060 if (op[0] === 6 && _.label < t[1]) {
25066 if (t && _.label < t[2]) {
25074 if (t[2]) _.ops.pop();
25081 op = body.call(thisArg, _);
25089 if (op[0] & 5) throw op[1];
25091 value: op[0] ? op[1] : void 0,
25097 var __importStar = this && this.__importStar || function (mod) {
25098 if (mod && mod.__esModule) return mod;
25100 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
25101 result["default"] = mod;
25105 var __importDefault = this && this.__importDefault || function (mod) {
25106 return mod && mod.__esModule ? mod : {
25111 Object.defineProperty(exports, "__esModule", {
25115 var fs = __importStar(fs__default['default']);
25117 var path = __importStar(path__default['default']);
25119 var semver = __importStar(semver$2);
25121 var fnmatch_1 = __importDefault(fnmatch);
25123 exports.parseString = ini.parseString;
25125 var package_json_1 = __importDefault(require$$4);
25129 indent_style: true,
25131 insert_final_newline: true,
25132 trim_trailing_whitespace: true,
25136 function fnmatch$1(filepath, glob) {
25137 var matchOptions = {
25142 glob = glob.replace(/\*\*/g, '{*,**/**/**}');
25143 return fnmatch_1.default(filepath, glob, matchOptions);
25146 function getConfigFileNames(filepath, options) {
25150 filepath = path.dirname(filepath);
25151 paths.push(path.join(filepath, options.config));
25152 } while (filepath !== options.root);
25157 function processMatches(matches, version) {
25158 // Set indent_size to 'tab' if indent_size is unspecified and
25159 // indent_style is set to 'tab'.
25160 if ('indent_style' in matches && matches.indent_style === 'tab' && !('indent_size' in matches) && semver.gte(version, '0.10.0')) {
25161 matches.indent_size = 'tab';
25162 } // Set tab_width to indent_size if indent_size is specified and
25163 // tab_width is unspecified
25166 if ('indent_size' in matches && !('tab_width' in matches) && matches.indent_size !== 'tab') {
25167 matches.tab_width = matches.indent_size;
25168 } // Set indent_size to tab_width if indent_size is 'tab'
25171 if ('indent_size' in matches && 'tab_width' in matches && matches.indent_size === 'tab') {
25172 matches.indent_size = matches.tab_width;
25178 function processOptions(options, filepath) {
25179 if (options === void 0) {
25184 config: options.config || '.editorconfig',
25185 version: options.version || package_json_1.default.version,
25186 root: path.resolve(options.root || path.parse(filepath).root)
25190 function buildFullGlob(pathPrefix, glob) {
25191 switch (glob.indexOf('/')) {
25193 glob = '**/' + glob;
25197 glob = glob.substring(1);
25201 return path.join(pathPrefix, glob);
25204 function extendProps(props, options) {
25205 if (props === void 0) {
25209 if (options === void 0) {
25213 for (var key in options) {
25214 if (options.hasOwnProperty(key)) {
25215 var value = options[key];
25216 var key2 = key.toLowerCase();
25217 var value2 = value;
25219 if (knownProps[key2]) {
25220 value2 = value.toLowerCase();
25224 value2 = JSON.parse(value);
25227 if (typeof value === 'undefined' || value === null) {
25228 // null and undefined are values specific to JSON (no special meaning
25229 // in editorconfig) & should just be returned as regular strings.
25230 value2 = String(value);
25233 props[key2] = value2;
25240 function parseFromConfigs(configs, filepath, options) {
25241 return processMatches(configs.reverse().reduce(function (matches, file) {
25242 var pathPrefix = path.dirname(file.name);
25243 file.contents.forEach(function (section) {
25244 var glob = section[0];
25245 var options2 = section[1];
25251 var fullGlob = buildFullGlob(pathPrefix, glob);
25253 if (!fnmatch$1(filepath, fullGlob)) {
25257 matches = extendProps(matches, options2);
25260 }, {}), options.version);
25263 function getConfigsForFiles(files) {
25266 for (var i in files) {
25267 if (files.hasOwnProperty(i)) {
25268 var file = files[i];
25269 var contents = ini.parseString(file.contents);
25275 if ((contents[0][1].root || '').toLowerCase() === 'true') {
25284 function readConfigFiles(filepaths) {
25285 return __awaiter(this, void 0, void 0, function () {
25286 return __generator(this, function (_a) {
25289 , Promise.all(filepaths.map(function (name) {
25290 return new Promise(function (resolve) {
25291 fs.readFile(name, 'utf8', function (err, data) {
25294 contents: err ? '' : data
25303 function readConfigFilesSync(filepaths) {
25306 filepaths.forEach(function (filepath) {
25308 file = fs.readFileSync(filepath, 'utf8');
25321 function opts(filepath, options) {
25322 if (options === void 0) {
25326 var resolvedFilePath = path.resolve(filepath);
25327 return [resolvedFilePath, processOptions(options, resolvedFilePath)];
25330 function parseFromFiles(filepath, files, options) {
25331 if (options === void 0) {
25335 return __awaiter(this, void 0, void 0, function () {
25336 var _a, resolvedFilePath, processedOptions;
25338 return __generator(this, function (_b) {
25339 _a = opts(filepath, options), resolvedFilePath = _a[0], processedOptions = _a[1];
25342 , files.then(getConfigsForFiles).then(function (configs) {
25343 return parseFromConfigs(configs, resolvedFilePath, processedOptions);
25349 exports.parseFromFiles = parseFromFiles;
25351 function parseFromFilesSync(filepath, files, options) {
25352 if (options === void 0) {
25356 var _a = opts(filepath, options),
25357 resolvedFilePath = _a[0],
25358 processedOptions = _a[1];
25360 return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
25363 exports.parseFromFilesSync = parseFromFilesSync;
25365 function parse(_filepath, _options) {
25366 if (_options === void 0) {
25370 return __awaiter(this, void 0, void 0, function () {
25371 var _a, resolvedFilePath, processedOptions, filepaths;
25373 return __generator(this, function (_b) {
25374 _a = opts(_filepath, _options), resolvedFilePath = _a[0], processedOptions = _a[1];
25375 filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
25378 , readConfigFiles(filepaths).then(getConfigsForFiles).then(function (configs) {
25379 return parseFromConfigs(configs, resolvedFilePath, processedOptions);
25385 exports.parse = parse;
25387 function parseSync(_filepath, _options) {
25388 if (_options === void 0) {
25392 var _a = opts(_filepath, _options),
25393 resolvedFilePath = _a[0],
25394 processedOptions = _a[1];
25396 var filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
25397 var files = readConfigFilesSync(filepaths);
25398 return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
25401 exports.parseSync = parseSync;
25404 var editorconfigToPrettier = editorConfigToPrettier;
25406 function removeUnset(editorConfig) {
25408 const keys = Object.keys(editorConfig);
25410 for (let i = 0; i < keys.length; i++) {
25411 const key = keys[i];
25413 if (editorConfig[key] === "unset") {
25417 result[key] = editorConfig[key];
25423 function editorConfigToPrettier(editorConfig) {
25424 if (!editorConfig) {
25428 editorConfig = removeUnset(editorConfig);
25430 if (Object.keys(editorConfig).length === 0) {
25436 if (editorConfig.indent_style) {
25437 result.useTabs = editorConfig.indent_style === "tab";
25440 if (editorConfig.indent_size === "tab") {
25441 result.useTabs = true;
25444 if (result.useTabs && editorConfig.tab_width) {
25445 result.tabWidth = editorConfig.tab_width;
25446 } else if (editorConfig.indent_style === "space" && editorConfig.indent_size && editorConfig.indent_size !== "tab") {
25447 result.tabWidth = editorConfig.indent_size;
25448 } else if (editorConfig.tab_width !== undefined) {
25449 result.tabWidth = editorConfig.tab_width;
25452 if (editorConfig.max_line_length && editorConfig.max_line_length !== "off") {
25453 result.printWidth = editorConfig.max_line_length;
25456 if (editorConfig.quote_type === "single") {
25457 result.singleQuote = true;
25458 } else if (editorConfig.quote_type === "double") {
25459 result.singleQuote = false;
25462 if (["cr", "crlf", "lf"].indexOf(editorConfig.end_of_line) !== -1) {
25463 result.endOfLine = editorConfig.end_of_line;
25466 if (editorConfig.insert_final_newline === false || editorConfig.insert_final_newline === true) {
25467 result.insertFinalNewline = editorConfig.insert_final_newline;
25473 // https://github.com/kirstein/find-project-root/blob/master/index.js
25476 const MARKERS = [".git", ".hg"];
25478 const markerExists = directory => MARKERS.some(mark => fs__default['default'].existsSync(path__default['default'].join(directory, mark)));
25480 function findProjectRoot(directory) {
25481 while (!markerExists(directory)) {
25482 const parentDirectory = path__default['default'].resolve(directory, "..");
25484 if (parentDirectory === directory) {
25488 directory = parentDirectory;
25494 var findProjectRoot_1 = findProjectRoot;
25496 const jsonStringifyMem = fn => dist$1(fn, {
25497 cacheKey: JSON.stringify
25500 const maybeParse = (filePath, parse) => filePath && parse(filePath, {
25501 root: findProjectRoot_1(path__default['default'].dirname(path__default['default'].resolve(filePath)))
25504 const editorconfigAsyncNoCache = async (filePath) => editorconfigToPrettier(await maybeParse(filePath, src$1.parse));
25506 const editorconfigAsyncWithCache = jsonStringifyMem(editorconfigAsyncNoCache);
25508 const editorconfigSyncNoCache = filePath => editorconfigToPrettier(maybeParse(filePath, src$1.parseSync));
25510 const editorconfigSyncWithCache = jsonStringifyMem(editorconfigSyncNoCache);
25512 function getLoadFunction(opts) {
25513 if (!opts.editorconfig) {
25518 return opts.cache ? editorconfigSyncWithCache : editorconfigSyncNoCache;
25521 return opts.cache ? editorconfigAsyncWithCache : editorconfigAsyncNoCache;
25524 function clearCache() {
25525 dist$1.clear(editorconfigSyncWithCache);
25526 dist$1.clear(editorconfigAsyncWithCache);
25529 var resolveConfigEditorconfig = {
25534 const getExplorerMemoized = dist$1(opts => {
25535 const cosmiconfig = thirdParty["cosmiconfig" + (opts.sync ? "Sync" : "")];
25536 const explorer = cosmiconfig("prettier", {
25538 transform: result => {
25539 if (result && result.config) {
25540 if (typeof result.config === "string") {
25541 const dir = path__default['default'].dirname(result.filepath);
25542 const modulePath = resolve_1(result.config, {
25545 result.config = require(modulePath);
25548 if (typeof result.config !== "object") {
25549 throw new Error("Config is only allowed to be an object, " + `but received ${typeof result.config} in "${result.filepath}"`);
25552 delete result.config.$schema;
25557 searchPlaces: ["package.json", ".prettierrc", ".prettierrc.json", ".prettierrc.yaml", ".prettierrc.yml", ".prettierrc.json5", ".prettierrc.js", ".prettierrc.cjs", "prettier.config.js", "prettier.config.cjs", ".prettierrc.toml"],
25560 ".json5": loadJson5
25565 cacheKey: JSON.stringify
25567 /** @param {{ cache: boolean, sync: boolean }} opts */
25569 function getExplorer(opts) {
25570 // Normalize opts before passing to a memoized function
25571 opts = Object.assign({
25575 return getExplorerMemoized(opts);
25578 function _resolveConfig(filePath, opts, sync) {
25579 opts = Object.assign({
25583 cache: !!opts.useCache,
25585 editorconfig: !!opts.editorconfig
25590 } = getExplorer(loadOpts);
25591 const loadEditorConfig = resolveConfigEditorconfig.getLoadFunction(loadOpts);
25592 const arr = [opts.config ? load(opts.config) : search(filePath), loadEditorConfig(filePath)];
25594 const unwrapAndMerge = ([result, editorConfigured]) => {
25595 const merged = Object.assign({}, editorConfigured, mergeOverrides(result, filePath));
25596 ["plugins", "pluginSearchDirs"].forEach(optionName => {
25597 if (Array.isArray(merged[optionName])) {
25598 merged[optionName] = merged[optionName].map(value => typeof value === "string" && value.startsWith(".") // relative path
25599 ? path__default['default'].resolve(path__default['default'].dirname(result.filepath), value) : value);
25603 if (!result && !editorConfigured) {
25605 } // We are not using this option
25608 delete merged.insertFinalNewline;
25612 if (loadOpts.sync) {
25613 return unwrapAndMerge(arr);
25616 return Promise.all(arr).then(unwrapAndMerge);
25619 const resolveConfig = (filePath, opts) => _resolveConfig(filePath, opts, false);
25621 resolveConfig.sync = (filePath, opts) => _resolveConfig(filePath, opts, true);
25623 function clearCache$1() {
25624 dist$1.clear(getExplorerMemoized);
25625 resolveConfigEditorconfig.clearCache();
25628 async function resolveConfigFile(filePath) {
25634 const result = await search(filePath);
25635 return result ? result.filepath : null;
25638 resolveConfigFile.sync = filePath => {
25644 const result = search(filePath);
25645 return result ? result.filepath : null;
25648 function mergeOverrides(configResult, filePath) {
25651 filepath: configPath
25652 } = configResult || {};
25654 const _ref = config || {},
25658 options = _objectWithoutPropertiesLoose(_ref, ["overrides"]);
25660 if (filePath && overrides) {
25661 const relativeFilePath = path__default['default'].relative(path__default['default'].dirname(configPath), filePath);
25663 for (const override of overrides) {
25664 if (pathMatchesGlobs(relativeFilePath, override.files, override.excludeFiles)) {
25665 Object.assign(options, override.options);
25671 } // Based on eslint: https://github.com/eslint/eslint/blob/master/lib/config/config-ops.js
25674 function pathMatchesGlobs(filePath, patterns, excludedPatterns) {
25675 const patternList = [].concat(patterns);
25676 const excludedPatternList = [].concat(excludedPatterns || []);
25681 return patternList.some(pattern => minimatch_1(filePath, pattern, opts)) && !excludedPatternList.some(excludedPattern => minimatch_1(filePath, excludedPattern, opts));
25684 var resolveConfig_1 = {
25687 clearCache: clearCache$1
25690 // A simple implementation of make-array
25691 function make_array(subject) {
25692 return Array.isArray(subject) ? subject : [subject];
25695 const REGEX_BLANK_LINE = /^\s+$/;
25696 const REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
25697 const REGEX_LEADING_EXCAPED_HASH = /^\\#/;
25699 const KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
25700 /* istanbul ignore next */
25703 const define = (object, key, value) => Object.defineProperty(object, key, {
25707 const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression
25708 // The cases are complicated, see test cases for details
25710 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
25711 // fatal for JavaScript regular expression, so eliminate it.
25712 : ''); // > If the pattern ends with a slash,
25713 // > it is removed for the purpose of the following description,
25714 // > but it would only find a match with a directory.
25715 // > In other words, foo/ will match a directory foo and paths underneath it,
25716 // > but will not match a regular file or a symbolic link foo
25717 // > (this is consistent with the way how pathspec works in general in Git).
25718 // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
25719 // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
25720 // you could use option `mark: true` with `glob`
25721 // '`foo/`' should not continue with the '`..`'
25724 const DEFAULT_REPLACER_PREFIX = [// > Trailing spaces are ignored unless they are quoted with backslash ("\")
25728 /\\?\s+$/, match => match.indexOf('\\') === 0 ? ' ' : ''], // replace (\ ) with ' '
25729 [/\\\s/g, () => ' '], // Escape metacharacters
25730 // which is written down by users but means special for regular expressions.
25731 // > There are 12 characters with special meanings:
25732 // > - the backslash \,
25733 // > - the caret ^,
25734 // > - the dollar sign $,
25735 // > - the period or dot .,
25736 // > - the vertical bar or pipe symbol |,
25737 // > - the question mark ?,
25738 // > - the asterisk or star *,
25739 // > - the plus sign +,
25740 // > - the opening parenthesis (,
25741 // > - the closing parenthesis ),
25742 // > - and the opening square bracket [,
25743 // > - the opening curly brace {,
25744 // > These special characters are often called "metacharacters".
25745 [/[\\^$.|*+(){]/g, match => `\\${match}`], [// > [abc] matches any character inside the brackets
25746 // > (in this case a, b, or c);
25747 /\[([^\]/]*)($|\])/g, (match, p1, p2) => p2 === ']' ? `[${sanitizeRange(p1)}]` : `\\${match}`], [// > a question mark (?) matches a single character
25748 /(?!\\)\?/g, () => '[^/]'], // leading slash
25749 [// > A leading slash matches the beginning of the pathname.
25750 // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
25751 // A leading slash matches the beginning of the pathname
25752 /^\//, () => '^'], // replace special metacharacter slash after the leading slash
25753 [/\//g, () => '\\/'], [// > A leading "**" followed by a slash means match in all directories.
25754 // > For example, "**/foo" matches file or directory "foo" anywhere,
25755 // > the same as pattern "foo".
25756 // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
25757 // > under directory "foo".
25758 // Notice that the '*'s have been replaced as '\\*'
25759 /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo'
25760 () => '^(?:.*\\/)?']];
25761 const DEFAULT_REPLACER_SUFFIX = [// starting
25762 [// there will be no leading '/'
25763 // (which has been replaced by section "leading slash")
25764 // If starts with '**', adding a '^' to the regular expression also works
25765 /^(?=[^^])/, function startingReplacer() {
25766 return !/\/(?!$)/.test(this) // > If the pattern does not contain a slash /,
25767 // > Git treats it as a shell glob pattern
25768 // Actually, if there is only a trailing slash,
25769 // git also treats it as a shell glob pattern
25770 ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for
25771 // > consumption by fnmatch(3)
25773 }], // two globstars
25774 [// Use lookahead assertions so that we could match more than one `'/**'`
25775 /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories
25776 // should not use '*', or it will be replaced by the next replacer
25777 // Check if it is not the last `'/**'`
25778 (match, index, str) => index + 6 < str.length // case: /**/
25779 // > A slash followed by two consecutive asterisks then a slash matches
25780 // > zero or more directories.
25781 // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
25783 ? '(?:\\/[^\\/]+)*' // case: /**
25784 // > A trailing `"/**"` matches everything inside.
25785 // #21: everything inside but it should not include the current folder
25786 : '\\/.+'], // intermediate wildcards
25787 [// Never replace escaped '*'
25788 // ignore rule '\*' will match the path '*'
25790 // 'abc.*' -> skip this rule
25791 /(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js'
25792 // '*.js' doesn't match 'abc'
25793 (match, p1) => `${p1}[^\\/]*`], // trailing wildcard
25794 [/(\^|\\\/)?\\\*$/, (match, p1) => {
25795 const prefix = p1 // '\^':
25796 // '/*' does not match ''
25797 // '/*' does not match everything
25799 // 'abc/*' does not match 'abc/'
25800 ? `${p1}[^/]+` // 'a*' matches 'a'
25801 // 'a*' matches 'aa'
25803 return `${prefix}(?=$|\\/$)`;
25805 /\\\\\\/g, () => '\\']];
25806 const POSITIVE_REPLACERS = [...DEFAULT_REPLACER_PREFIX, // 'f'
25818 [// 'js' will not match 'js.'
25819 // 'ab' will not match 'abc'
25820 /(?:[^*/])$/, // 'js*' will not match 'a.js'
25821 // 'js/' will not match 'a.js'
25822 // 'js' will match 'a.js' and 'a.js/'
25823 match => `${match}(?=$|\\/)`], ...DEFAULT_REPLACER_SUFFIX];
25824 const NEGATIVE_REPLACERS = [...DEFAULT_REPLACER_PREFIX, // #24, #38
25825 // The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore)
25826 // A negative pattern without a trailing wildcard should not
25827 // re-include the things inside that directory.
25829 // ['node_modules/*', '!node_modules']
25830 // should ignore `node_modules/a.js`
25831 [/(?:[^*])$/, match => `${match}(?=$|\\/$)`], ...DEFAULT_REPLACER_SUFFIX]; // A simple cache, because an ignore rule only has only one certain meaning
25833 const cache = Object.create(null); // @param {pattern}
25835 const make_regex = (pattern, negative, ignorecase) => {
25836 const r = cache[pattern];
25842 const replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS;
25843 const source = replacers.reduce((prev, current) => prev.replace(current[0], current[1].bind(pattern)), pattern);
25844 return cache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source);
25845 }; // > A blank line matches no files, so it can serve as a separator for readability.
25848 const checkPattern = pattern => pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment.
25849 && pattern.indexOf('#') !== 0;
25851 const createRule = (pattern, ignorecase) => {
25852 const origin = pattern;
25853 let negative = false; // > An optional prefix "!" which negates the pattern;
25855 if (pattern.indexOf('!') === 0) {
25857 pattern = pattern.substr(1);
25860 pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that
25861 // > begin with a literal "!", for example, `"\!important!.txt"`.
25862 .replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that
25863 // > begin with a hash.
25864 .replace(REGEX_LEADING_EXCAPED_HASH, '#');
25865 const regex = make_regex(pattern, negative, ignorecase);
25879 this._ignorecase = ignorecase;
25880 define(this, KEY_IGNORE, true);
25886 this._cache = Object.create(null);
25887 } // @param {Array.<string>|string|Ignore} pattern
25891 this._added = false;
25893 if (typeof pattern === 'string') {
25894 pattern = pattern.split(/\r?\n/g);
25897 make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore,
25898 // making the behavior changed.
25908 addPattern(pattern) {
25909 return this.add(pattern);
25912 _addPattern(pattern) {
25914 if (pattern && pattern[KEY_IGNORE]) {
25915 this._rules = this._rules.concat(pattern._rules);
25916 this._added = true;
25920 if (checkPattern(pattern)) {
25921 const rule = createRule(pattern, this._ignorecase);
25922 this._added = true;
25924 this._rules.push(rule);
25929 return make_array(paths).filter(path => this._filter(path));
25933 return path => this._filter(path);
25937 return !this._filter(path);
25938 } // @returns `Boolean` true if the `path` is NOT ignored
25941 _filter(path, slices) {
25946 if (path in this._cache) {
25947 return this._cache[path];
25952 // ['path', 'to', 'a.js']
25953 slices = path.split(SLASH);
25957 return this._cache[path] = slices.length // > It is not possible to re-include a file if a parent directory of
25958 // > that file is excluded.
25959 // If the path contains a parent directory, check the parent first
25960 ? this._filter(slices.join(SLASH) + SLASH, slices) && this._test(path) // Or only test the path
25961 : this._test(path);
25962 } // @returns {Boolean} true if a file is NOT ignored
25966 // Explicitly define variable type by setting matched to `0`
25969 this._rules.forEach(rule => {
25970 // if matched = true, then we only test negative rules
25971 // if matched = false, then we test non-negative rules
25972 if (!(matched ^ rule.negative)) {
25973 matched = rule.negative ^ rule.regex.test(path);
25981 // --------------------------------------------------------------
25983 /* istanbul ignore if */
25986 if ( // Detect `process` so that it can run in browsers.
25987 typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
25988 const filter = IgnoreBase.prototype._filter;
25989 /* eslint no-control-regex: "off" */
25991 const make_posix = str => /^\\\\\?\\/.test(str) || /[^\x00-\x80]+/.test(str) ? str : str.replace(/\\/g, '/');
25993 IgnoreBase.prototype._filter = function filterWin32(path, slices) {
25994 path = make_posix(path);
25995 return filter.call(this, path, slices);
25999 var ignore = options => new IgnoreBase(options);
26002 * @param {string} filename
26003 * @returns {Promise<null | string>}
26007 function getFileContentOrNull(filename) {
26008 return new Promise((resolve, reject) => {
26009 fs__default['default'].readFile(filename, "utf8", (error, data) => {
26010 if (error && error.code !== "ENOENT") {
26011 reject(createError(filename, error));
26013 resolve(error ? null : data);
26019 * @param {string} filename
26020 * @returns {null | string}
26024 getFileContentOrNull.sync = function (filename) {
26026 return fs__default['default'].readFileSync(filename, "utf8");
26028 if (error && error.code === "ENOENT") {
26032 throw createError(filename, error);
26036 function createError(filename, error) {
26037 return new Error(`Unable to read ${filename}: ${error.message}`);
26040 var getFileContentOrNull_1 = getFileContentOrNull;
26043 * @param {string?} ignorePath
26044 * @param {boolean?} withNodeModules
26048 async function createIgnorer(ignorePath, withNodeModules) {
26049 const ignoreContent = ignorePath ? await getFileContentOrNull_1(path__default['default'].resolve(ignorePath)) : null;
26050 return _createIgnorer(ignoreContent, withNodeModules);
26053 * @param {string?} ignorePath
26054 * @param {boolean?} withNodeModules
26058 createIgnorer.sync = function (ignorePath, withNodeModules) {
26059 const ignoreContent = !ignorePath ? null : getFileContentOrNull_1.sync(path__default['default'].resolve(ignorePath));
26060 return _createIgnorer(ignoreContent, withNodeModules);
26063 * @param {null | string} ignoreContent
26064 * @param {boolean?} withNodeModules
26068 function _createIgnorer(ignoreContent, withNodeModules) {
26069 const ignorer = ignore().add(ignoreContent || "");
26071 if (!withNodeModules) {
26072 ignorer.add("node_modules");
26078 var createIgnorer_1 = createIgnorer;
26081 * @typedef {{ ignorePath?: string, withNodeModules?: boolean, plugins: object }} FileInfoOptions
26082 * @typedef {{ ignored: boolean, inferredParser: string | null }} FileInfoResult
26086 * @param {string} filePath
26087 * @param {FileInfoOptions} opts
26088 * @returns {Promise<FileInfoResult>}
26090 * Please note that prettier.getFileInfo() expects opts.plugins to be an array of paths,
26091 * not an object. A transformation from this array to an object is automatically done
26092 * internally by the method wrapper. See withPlugins() in index.js.
26096 async function getFileInfo(filePath, opts) {
26097 if (typeof filePath !== "string") {
26098 throw new TypeError(`expect \`filePath\` to be a string, got \`${typeof filePath}\``);
26101 const ignorer = await createIgnorer_1(opts.ignorePath, opts.withNodeModules);
26102 return _getFileInfo({
26105 plugins: opts.plugins,
26106 resolveConfig: opts.resolveConfig,
26107 ignorePath: opts.ignorePath,
26112 * @param {string} filePath
26113 * @param {FileInfoOptions} opts
26114 * @returns {FileInfoResult}
26118 getFileInfo.sync = function (filePath, opts) {
26119 if (typeof filePath !== "string") {
26120 throw new TypeError(`expect \`filePath\` to be a string, got \`${typeof filePath}\``);
26123 const ignorer = createIgnorer_1.sync(opts.ignorePath, opts.withNodeModules);
26124 return _getFileInfo({
26127 plugins: opts.plugins,
26128 resolveConfig: opts.resolveConfig,
26129 ignorePath: opts.ignorePath,
26134 function getFileParser(resolvedConfig, filePath, plugins) {
26135 if (resolvedConfig && resolvedConfig.parser) {
26136 return resolvedConfig.parser;
26139 const inferredParser = options$1.inferParser(filePath, plugins);
26141 if (inferredParser) {
26142 return inferredParser;
26148 function _getFileInfo({
26152 resolveConfig = false,
26156 const normalizedFilePath = normalizeFilePath(filePath, ignorePath);
26158 ignored: ignorer.ignores(normalizedFilePath),
26159 inferredParser: null
26162 if (fileInfo.ignored) {
26166 let resolvedConfig;
26168 if (resolveConfig) {
26170 resolvedConfig = resolveConfig_1.resolveConfig.sync(filePath);
26172 return resolveConfig_1.resolveConfig(filePath).then(resolvedConfig => {
26173 fileInfo.inferredParser = getFileParser(resolvedConfig, filePath, plugins);
26179 fileInfo.inferredParser = getFileParser(resolvedConfig, filePath, plugins);
26183 function normalizeFilePath(filePath, ignorePath) {
26184 return ignorePath ? path__default['default'].relative(path__default['default'].dirname(ignorePath), filePath) : filePath;
26187 var getFileInfo_1 = getFileInfo;
26190 getMaxContinuousCount: getMaxContinuousCount$1,
26191 getStringWidth: getStringWidth$2,
26192 getAlignmentSize: getAlignmentSize$2,
26193 getIndentSize: getIndentSize$1,
26195 skipWhitespace: skipWhitespace$1,
26196 skipSpaces: skipSpaces$2,
26197 skipNewline: skipNewline$2,
26198 skipToLineEnd: skipToLineEnd$1,
26199 skipEverythingButNewLine: skipEverythingButNewLine$1,
26200 skipInlineComment: skipInlineComment$1,
26201 skipTrailingComment: skipTrailingComment$1,
26202 hasNewline: hasNewline$2,
26203 hasNewlineInRange: hasNewlineInRange$1,
26204 hasSpaces: hasSpaces$1,
26205 isNextLineEmpty: isNextLineEmpty$1,
26206 isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1,
26207 isPreviousLineEmpty: isPreviousLineEmpty$2,
26208 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1,
26209 makeString: makeString$1,
26210 addLeadingComment: addLeadingComment$2,
26211 addDanglingComment: addDanglingComment$2,
26212 addTrailingComment: addTrailingComment$2
26215 getMaxContinuousCount: getMaxContinuousCount$1,
26216 getStringWidth: getStringWidth$2,
26217 getAlignmentSize: getAlignmentSize$2,
26218 getIndentSize: getIndentSize$1,
26220 skipWhitespace: skipWhitespace$1,
26221 skipSpaces: skipSpaces$2,
26222 skipNewline: skipNewline$2,
26223 skipToLineEnd: skipToLineEnd$1,
26224 skipEverythingButNewLine: skipEverythingButNewLine$1,
26225 skipInlineComment: skipInlineComment$1,
26226 skipTrailingComment: skipTrailingComment$1,
26227 hasNewline: hasNewline$2,
26228 hasNewlineInRange: hasNewlineInRange$1,
26229 hasSpaces: hasSpaces$1,
26230 isNextLineEmpty: isNextLineEmpty$1,
26231 isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1,
26232 isPreviousLineEmpty: isPreviousLineEmpty$2,
26233 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1,
26234 makeString: makeString$1,
26235 addLeadingComment: addLeadingComment$2,
26236 addDanglingComment: addDanglingComment$2,
26237 addTrailingComment: addTrailingComment$2
26241 * Removes all key-value entries from the list cache.
26245 * @memberOf ListCache
26247 function listCacheClear() {
26248 this.__data__ = [];
26252 var _listCacheClear = listCacheClear;
26256 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
26257 * comparison between two values to determine if they are equivalent.
26263 * @param {*} value The value to compare.
26264 * @param {*} other The other value to compare.
26265 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
26268 * var object = { 'a': 1 };
26269 * var other = { 'a': 1 };
26271 * _.eq(object, object);
26274 * _.eq(object, other);
26280 * _.eq('a', Object('a'));
26286 function eq(value, other) {
26287 return value === other || value !== value && other !== other;
26293 * Gets the index at which the `key` is found in `array` of key-value pairs.
26296 * @param {Array} array The array to inspect.
26297 * @param {*} key The key to search for.
26298 * @returns {number} Returns the index of the matched value, else `-1`.
26301 function assocIndexOf(array, key) {
26302 var length = array.length;
26305 if (eq_1(array[length][0], key)) {
26313 var _assocIndexOf = assocIndexOf;
26315 /** Used for built-in method references. */
26317 var arrayProto = Array.prototype;
26318 /** Built-in value references. */
26320 var splice = arrayProto.splice;
26322 * Removes `key` and its value from the list cache.
26326 * @memberOf ListCache
26327 * @param {string} key The key of the value to remove.
26328 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
26331 function listCacheDelete(key) {
26332 var data = this.__data__,
26333 index = _assocIndexOf(data, key);
26339 var lastIndex = data.length - 1;
26341 if (index == lastIndex) {
26344 splice.call(data, index, 1);
26351 var _listCacheDelete = listCacheDelete;
26354 * Gets the list cache value for `key`.
26358 * @memberOf ListCache
26359 * @param {string} key The key of the value to get.
26360 * @returns {*} Returns the entry value.
26363 function listCacheGet(key) {
26364 var data = this.__data__,
26365 index = _assocIndexOf(data, key);
26366 return index < 0 ? undefined : data[index][1];
26369 var _listCacheGet = listCacheGet;
26372 * Checks if a list cache value for `key` exists.
26376 * @memberOf ListCache
26377 * @param {string} key The key of the entry to check.
26378 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
26381 function listCacheHas(key) {
26382 return _assocIndexOf(this.__data__, key) > -1;
26385 var _listCacheHas = listCacheHas;
26388 * Sets the list cache `key` to `value`.
26392 * @memberOf ListCache
26393 * @param {string} key The key of the value to set.
26394 * @param {*} value The value to set.
26395 * @returns {Object} Returns the list cache instance.
26398 function listCacheSet(key, value) {
26399 var data = this.__data__,
26400 index = _assocIndexOf(data, key);
26404 data.push([key, value]);
26406 data[index][1] = value;
26412 var _listCacheSet = listCacheSet;
26415 * Creates an list cache object.
26419 * @param {Array} [entries] The key-value pairs to cache.
26422 function ListCache(entries) {
26424 length = entries == null ? 0 : entries.length;
26427 while (++index < length) {
26428 var entry = entries[index];
26429 this.set(entry[0], entry[1]);
26431 } // Add methods to `ListCache`.
26434 ListCache.prototype.clear = _listCacheClear;
26435 ListCache.prototype['delete'] = _listCacheDelete;
26436 ListCache.prototype.get = _listCacheGet;
26437 ListCache.prototype.has = _listCacheHas;
26438 ListCache.prototype.set = _listCacheSet;
26439 var _ListCache = ListCache;
26442 * Removes all key-value entries from the stack.
26449 function stackClear() {
26450 this.__data__ = new _ListCache();
26454 var _stackClear = stackClear;
26457 * Removes `key` and its value from the stack.
26462 * @param {string} key The key of the value to remove.
26463 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
26465 function stackDelete(key) {
26466 var data = this.__data__,
26467 result = data['delete'](key);
26468 this.size = data.size;
26472 var _stackDelete = stackDelete;
26475 * Gets the stack value for `key`.
26480 * @param {string} key The key of the value to get.
26481 * @returns {*} Returns the entry value.
26483 function stackGet(key) {
26484 return this.__data__.get(key);
26487 var _stackGet = stackGet;
26490 * Checks if a stack value for `key` exists.
26495 * @param {string} key The key of the entry to check.
26496 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
26498 function stackHas(key) {
26499 return this.__data__.has(key);
26502 var _stackHas = stackHas;
26505 * Checks if `value` is the
26506 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
26507 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
26513 * @param {*} value The value to check.
26514 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
26520 * _.isObject([1, 2, 3]);
26523 * _.isObject(_.noop);
26526 * _.isObject(null);
26529 function isObject(value) {
26530 var type = typeof value;
26531 return value != null && (type == 'object' || type == 'function');
26534 var isObject_1 = isObject;
26536 /** `Object#toString` result references. */
26538 var asyncTag = '[object AsyncFunction]',
26539 funcTag = '[object Function]',
26540 genTag = '[object GeneratorFunction]',
26541 proxyTag = '[object Proxy]';
26543 * Checks if `value` is classified as a `Function` object.
26549 * @param {*} value The value to check.
26550 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
26556 * _.isFunction(/abc/);
26560 function isFunction(value) {
26561 if (!isObject_1(value)) {
26563 } // The use of `Object#toString` avoids issues with the `typeof` operator
26564 // in Safari 9 which returns 'object' for typed arrays and other constructors.
26567 var tag = _baseGetTag(value);
26568 return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
26571 var isFunction_1 = isFunction;
26573 /** Used to detect overreaching core-js shims. */
26575 var coreJsData = _root['__core-js_shared__'];
26576 var _coreJsData = coreJsData;
26578 /** Used to detect methods masquerading as native. */
26580 var maskSrcKey = function () {
26581 var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
26582 return uid ? 'Symbol(src)_1.' + uid : '';
26585 * Checks if `func` has its source masked.
26588 * @param {Function} func The function to check.
26589 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
26593 function isMasked(func) {
26594 return !!maskSrcKey && maskSrcKey in func;
26597 var _isMasked = isMasked;
26599 /** Used for built-in method references. */
26600 var funcProto = Function.prototype;
26601 /** Used to resolve the decompiled source of functions. */
26603 var funcToString = funcProto.toString;
26605 * Converts `func` to its source code.
26608 * @param {Function} func The function to convert.
26609 * @returns {string} Returns the source code.
26612 function toSource(func) {
26613 if (func != null) {
26615 return funcToString.call(func);
26626 var _toSource = toSource;
26629 * Used to match `RegExp`
26630 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
26633 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
26634 /** Used to detect host constructors (Safari). */
26636 var reIsHostCtor = /^\[object .+?Constructor\]$/;
26637 /** Used for built-in method references. */
26639 var funcProto$1 = Function.prototype,
26640 objectProto$3 = Object.prototype;
26641 /** Used to resolve the decompiled source of functions. */
26643 var funcToString$1 = funcProto$1.toString;
26644 /** Used to check objects for own properties. */
26646 var hasOwnProperty$4 = objectProto$3.hasOwnProperty;
26647 /** Used to detect if a method is native. */
26649 var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$4).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
26651 * The base implementation of `_.isNative` without bad shim checks.
26654 * @param {*} value The value to check.
26655 * @returns {boolean} Returns `true` if `value` is a native function,
26659 function baseIsNative(value) {
26660 if (!isObject_1(value) || _isMasked(value)) {
26664 var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
26665 return pattern.test(_toSource(value));
26668 var _baseIsNative = baseIsNative;
26671 * Gets the value at `key` of `object`.
26674 * @param {Object} [object] The object to query.
26675 * @param {string} key The key of the property to get.
26676 * @returns {*} Returns the property value.
26678 function getValue(object, key) {
26679 return object == null ? undefined : object[key];
26682 var _getValue = getValue;
26685 * Gets the native function at `key` of `object`.
26688 * @param {Object} object The object to query.
26689 * @param {string} key The key of the method to get.
26690 * @returns {*} Returns the function if it's native, else `undefined`.
26693 function getNative(object, key) {
26694 var value = _getValue(object, key);
26695 return _baseIsNative(value) ? value : undefined;
26698 var _getNative = getNative;
26700 /* Built-in method references that are verified to be native. */
26702 var Map$1 = _getNative(_root, 'Map');
26705 /* Built-in method references that are verified to be native. */
26707 var nativeCreate = _getNative(Object, 'create');
26708 var _nativeCreate = nativeCreate;
26711 * Removes all key-value entries from the hash.
26718 function hashClear() {
26719 this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
26723 var _hashClear = hashClear;
26726 * Removes `key` and its value from the hash.
26731 * @param {Object} hash The hash to modify.
26732 * @param {string} key The key of the value to remove.
26733 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
26735 function hashDelete(key) {
26736 var result = this.has(key) && delete this.__data__[key];
26737 this.size -= result ? 1 : 0;
26741 var _hashDelete = hashDelete;
26743 /** Used to stand-in for `undefined` hash values. */
26745 var HASH_UNDEFINED = '__lodash_hash_undefined__';
26746 /** Used for built-in method references. */
26748 var objectProto$4 = Object.prototype;
26749 /** Used to check objects for own properties. */
26751 var hasOwnProperty$5 = objectProto$4.hasOwnProperty;
26753 * Gets the hash value for `key`.
26758 * @param {string} key The key of the value to get.
26759 * @returns {*} Returns the entry value.
26762 function hashGet(key) {
26763 var data = this.__data__;
26765 if (_nativeCreate) {
26766 var result = data[key];
26767 return result === HASH_UNDEFINED ? undefined : result;
26770 return hasOwnProperty$5.call(data, key) ? data[key] : undefined;
26773 var _hashGet = hashGet;
26775 /** Used for built-in method references. */
26777 var objectProto$5 = Object.prototype;
26778 /** Used to check objects for own properties. */
26780 var hasOwnProperty$6 = objectProto$5.hasOwnProperty;
26782 * Checks if a hash value for `key` exists.
26787 * @param {string} key The key of the entry to check.
26788 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
26791 function hashHas(key) {
26792 var data = this.__data__;
26793 return _nativeCreate ? data[key] !== undefined : hasOwnProperty$6.call(data, key);
26796 var _hashHas = hashHas;
26798 /** Used to stand-in for `undefined` hash values. */
26800 var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
26802 * Sets the hash `key` to `value`.
26807 * @param {string} key The key of the value to set.
26808 * @param {*} value The value to set.
26809 * @returns {Object} Returns the hash instance.
26812 function hashSet(key, value) {
26813 var data = this.__data__;
26814 this.size += this.has(key) ? 0 : 1;
26815 data[key] = _nativeCreate && value === undefined ? HASH_UNDEFINED$1 : value;
26819 var _hashSet = hashSet;
26822 * Creates a hash object.
26826 * @param {Array} [entries] The key-value pairs to cache.
26829 function Hash(entries) {
26831 length = entries == null ? 0 : entries.length;
26834 while (++index < length) {
26835 var entry = entries[index];
26836 this.set(entry[0], entry[1]);
26838 } // Add methods to `Hash`.
26841 Hash.prototype.clear = _hashClear;
26842 Hash.prototype['delete'] = _hashDelete;
26843 Hash.prototype.get = _hashGet;
26844 Hash.prototype.has = _hashHas;
26845 Hash.prototype.set = _hashSet;
26849 * Removes all key-value entries from the map.
26853 * @memberOf MapCache
26856 function mapCacheClear() {
26859 'hash': new _Hash(),
26860 'map': new (_Map || _ListCache)(),
26861 'string': new _Hash()
26865 var _mapCacheClear = mapCacheClear;
26868 * Checks if `value` is suitable for use as unique object key.
26871 * @param {*} value The value to check.
26872 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
26874 function isKeyable(value) {
26875 var type = typeof value;
26876 return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
26879 var _isKeyable = isKeyable;
26882 * Gets the data for `map`.
26885 * @param {Object} map The map to query.
26886 * @param {string} key The reference key.
26887 * @returns {*} Returns the map data.
26890 function getMapData(map, key) {
26891 var data = map.__data__;
26892 return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
26895 var _getMapData = getMapData;
26898 * Removes `key` and its value from the map.
26902 * @memberOf MapCache
26903 * @param {string} key The key of the value to remove.
26904 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
26907 function mapCacheDelete(key) {
26908 var result = _getMapData(this, key)['delete'](key);
26909 this.size -= result ? 1 : 0;
26913 var _mapCacheDelete = mapCacheDelete;
26916 * Gets the map value for `key`.
26920 * @memberOf MapCache
26921 * @param {string} key The key of the value to get.
26922 * @returns {*} Returns the entry value.
26925 function mapCacheGet(key) {
26926 return _getMapData(this, key).get(key);
26929 var _mapCacheGet = mapCacheGet;
26932 * Checks if a map value for `key` exists.
26936 * @memberOf MapCache
26937 * @param {string} key The key of the entry to check.
26938 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
26941 function mapCacheHas(key) {
26942 return _getMapData(this, key).has(key);
26945 var _mapCacheHas = mapCacheHas;
26948 * Sets the map `key` to `value`.
26952 * @memberOf MapCache
26953 * @param {string} key The key of the value to set.
26954 * @param {*} value The value to set.
26955 * @returns {Object} Returns the map cache instance.
26958 function mapCacheSet(key, value) {
26959 var data = _getMapData(this, key),
26961 data.set(key, value);
26962 this.size += data.size == size ? 0 : 1;
26966 var _mapCacheSet = mapCacheSet;
26969 * Creates a map cache object to store key-value pairs.
26973 * @param {Array} [entries] The key-value pairs to cache.
26976 function MapCache(entries) {
26978 length = entries == null ? 0 : entries.length;
26981 while (++index < length) {
26982 var entry = entries[index];
26983 this.set(entry[0], entry[1]);
26985 } // Add methods to `MapCache`.
26988 MapCache.prototype.clear = _mapCacheClear;
26989 MapCache.prototype['delete'] = _mapCacheDelete;
26990 MapCache.prototype.get = _mapCacheGet;
26991 MapCache.prototype.has = _mapCacheHas;
26992 MapCache.prototype.set = _mapCacheSet;
26993 var _MapCache = MapCache;
26995 /** Used as the size to enable large array optimizations. */
26997 var LARGE_ARRAY_SIZE = 200;
26999 * Sets the stack `key` to `value`.
27004 * @param {string} key The key of the value to set.
27005 * @param {*} value The value to set.
27006 * @returns {Object} Returns the stack cache instance.
27009 function stackSet(key, value) {
27010 var data = this.__data__;
27012 if (data instanceof _ListCache) {
27013 var pairs = data.__data__;
27015 if (!_Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
27016 pairs.push([key, value]);
27017 this.size = ++data.size;
27021 data = this.__data__ = new _MapCache(pairs);
27024 data.set(key, value);
27025 this.size = data.size;
27029 var _stackSet = stackSet;
27032 * Creates a stack cache object to store key-value pairs.
27036 * @param {Array} [entries] The key-value pairs to cache.
27039 function Stack(entries) {
27040 var data = this.__data__ = new _ListCache(entries);
27041 this.size = data.size;
27042 } // Add methods to `Stack`.
27045 Stack.prototype.clear = _stackClear;
27046 Stack.prototype['delete'] = _stackDelete;
27047 Stack.prototype.get = _stackGet;
27048 Stack.prototype.has = _stackHas;
27049 Stack.prototype.set = _stackSet;
27050 var _Stack = Stack;
27052 /** Used to stand-in for `undefined` hash values. */
27053 var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
27055 * Adds `value` to the array cache.
27059 * @memberOf SetCache
27061 * @param {*} value The value to cache.
27062 * @returns {Object} Returns the cache instance.
27065 function setCacheAdd(value) {
27066 this.__data__.set(value, HASH_UNDEFINED$2);
27071 var _setCacheAdd = setCacheAdd;
27074 * Checks if `value` is in the array cache.
27078 * @memberOf SetCache
27079 * @param {*} value The value to search for.
27080 * @returns {number} Returns `true` if `value` is found, else `false`.
27082 function setCacheHas(value) {
27083 return this.__data__.has(value);
27086 var _setCacheHas = setCacheHas;
27090 * Creates an array cache object to store unique values.
27094 * @param {Array} [values] The values to cache.
27097 function SetCache(values) {
27099 length = values == null ? 0 : values.length;
27100 this.__data__ = new _MapCache();
27102 while (++index < length) {
27103 this.add(values[index]);
27105 } // Add methods to `SetCache`.
27108 SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
27109 SetCache.prototype.has = _setCacheHas;
27110 var _SetCache = SetCache;
27113 * A specialized version of `_.some` for arrays without support for iteratee
27117 * @param {Array} [array] The array to iterate over.
27118 * @param {Function} predicate The function invoked per iteration.
27119 * @returns {boolean} Returns `true` if any element passes the predicate check,
27122 function arraySome(array, predicate) {
27124 length = array == null ? 0 : array.length;
27126 while (++index < length) {
27127 if (predicate(array[index], index, array)) {
27135 var _arraySome = arraySome;
27138 * Checks if a `cache` value for `key` exists.
27141 * @param {Object} cache The cache to query.
27142 * @param {string} key The key of the entry to check.
27143 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
27145 function cacheHas(cache, key) {
27146 return cache.has(key);
27149 var _cacheHas = cacheHas;
27151 /** Used to compose bitmasks for value comparisons. */
27153 var COMPARE_PARTIAL_FLAG = 1,
27154 COMPARE_UNORDERED_FLAG = 2;
27156 * A specialized version of `baseIsEqualDeep` for arrays with support for
27157 * partial deep comparisons.
27160 * @param {Array} array The array to compare.
27161 * @param {Array} other The other array to compare.
27162 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
27163 * @param {Function} customizer The function to customize comparisons.
27164 * @param {Function} equalFunc The function to determine equivalents of values.
27165 * @param {Object} stack Tracks traversed `array` and `other` objects.
27166 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
27169 function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
27170 var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
27171 arrLength = array.length,
27172 othLength = other.length;
27174 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
27176 } // Check that cyclic values are equal.
27179 var arrStacked = stack.get(array);
27180 var othStacked = stack.get(other);
27182 if (arrStacked && othStacked) {
27183 return arrStacked == other && othStacked == array;
27188 seen = bitmask & COMPARE_UNORDERED_FLAG ? new _SetCache() : undefined;
27189 stack.set(array, other);
27190 stack.set(other, array); // Ignore non-index properties.
27192 while (++index < arrLength) {
27193 var arrValue = array[index],
27194 othValue = other[index];
27197 var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
27200 if (compared !== undefined) {
27207 } // Recursively compare arrays (susceptible to call stack limits).
27211 if (!_arraySome(other, function (othValue, othIndex) {
27212 if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
27213 return seen.push(othIndex);
27219 } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
27225 stack['delete'](array);
27226 stack['delete'](other);
27230 var _equalArrays = equalArrays;
27232 /** Built-in value references. */
27234 var Uint8Array = _root.Uint8Array;
27235 var _Uint8Array = Uint8Array;
27238 * Converts `map` to its key-value pairs.
27241 * @param {Object} map The map to convert.
27242 * @returns {Array} Returns the key-value pairs.
27244 function mapToArray(map) {
27246 result = Array(map.size);
27247 map.forEach(function (value, key) {
27248 result[++index] = [key, value];
27253 var _mapToArray = mapToArray;
27256 * Converts `set` to an array of its values.
27259 * @param {Object} set The set to convert.
27260 * @returns {Array} Returns the values.
27262 function setToArray(set) {
27264 result = Array(set.size);
27265 set.forEach(function (value) {
27266 result[++index] = value;
27271 var _setToArray = setToArray;
27273 /** Used to compose bitmasks for value comparisons. */
27275 var COMPARE_PARTIAL_FLAG$1 = 1,
27276 COMPARE_UNORDERED_FLAG$1 = 2;
27277 /** `Object#toString` result references. */
27279 var boolTag = '[object Boolean]',
27280 dateTag = '[object Date]',
27281 errorTag = '[object Error]',
27282 mapTag = '[object Map]',
27283 numberTag = '[object Number]',
27284 regexpTag = '[object RegExp]',
27285 setTag = '[object Set]',
27286 stringTag = '[object String]',
27287 symbolTag = '[object Symbol]';
27288 var arrayBufferTag = '[object ArrayBuffer]',
27289 dataViewTag = '[object DataView]';
27290 /** Used to convert symbols to primitives and strings. */
27292 var symbolProto = _Symbol ? _Symbol.prototype : undefined,
27293 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
27295 * A specialized version of `baseIsEqualDeep` for comparing objects of
27296 * the same `toStringTag`.
27298 * **Note:** This function only supports comparing values with tags of
27299 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
27302 * @param {Object} object The object to compare.
27303 * @param {Object} other The other object to compare.
27304 * @param {string} tag The `toStringTag` of the objects to compare.
27305 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
27306 * @param {Function} customizer The function to customize comparisons.
27307 * @param {Function} equalFunc The function to determine equivalents of values.
27308 * @param {Object} stack Tracks traversed `object` and `other` objects.
27309 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
27312 function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
27315 if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
27319 object = object.buffer;
27320 other = other.buffer;
27322 case arrayBufferTag:
27323 if (object.byteLength != other.byteLength || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
27332 // Coerce booleans to `1` or `0` and dates to milliseconds.
27333 // Invalid dates are coerced to `NaN`.
27334 return eq_1(+object, +other);
27337 return object.name == other.name && object.message == other.message;
27341 // Coerce regexes to strings and treat strings, primitives and objects,
27342 // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
27343 // for more details.
27344 return object == other + '';
27347 var convert = _mapToArray;
27350 var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;
27351 convert || (convert = _setToArray);
27353 if (object.size != other.size && !isPartial) {
27355 } // Assume cyclic values are equal.
27358 var stacked = stack.get(object);
27361 return stacked == other;
27364 bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits).
27366 stack.set(object, other);
27367 var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
27368 stack['delete'](object);
27372 if (symbolValueOf) {
27373 return symbolValueOf.call(object) == symbolValueOf.call(other);
27381 var _equalByTag = equalByTag;
27384 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
27385 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
27386 * symbols of `object`.
27389 * @param {Object} object The object to query.
27390 * @param {Function} keysFunc The function to get the keys of `object`.
27391 * @param {Function} symbolsFunc The function to get the symbols of `object`.
27392 * @returns {Array} Returns the array of property names and symbols.
27395 function baseGetAllKeys(object, keysFunc, symbolsFunc) {
27396 var result = keysFunc(object);
27397 return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
27400 var _baseGetAllKeys = baseGetAllKeys;
27403 * A specialized version of `_.filter` for arrays without support for
27404 * iteratee shorthands.
27407 * @param {Array} [array] The array to iterate over.
27408 * @param {Function} predicate The function invoked per iteration.
27409 * @returns {Array} Returns the new filtered array.
27411 function arrayFilter(array, predicate) {
27413 length = array == null ? 0 : array.length,
27417 while (++index < length) {
27418 var value = array[index];
27420 if (predicate(value, index, array)) {
27421 result[resIndex++] = value;
27428 var _arrayFilter = arrayFilter;
27431 * This method returns a new empty array.
27437 * @returns {Array} Returns the new empty array.
27440 * var arrays = _.times(2, _.stubArray);
27442 * console.log(arrays);
27445 * console.log(arrays[0] === arrays[1]);
27448 function stubArray() {
27452 var stubArray_1 = stubArray;
27454 /** Used for built-in method references. */
27456 var objectProto$6 = Object.prototype;
27457 /** Built-in value references. */
27459 var propertyIsEnumerable$1 = objectProto$6.propertyIsEnumerable;
27460 /* Built-in method references for those with the same name as other `lodash` methods. */
27462 var nativeGetSymbols = Object.getOwnPropertySymbols;
27464 * Creates an array of the own enumerable symbols of `object`.
27467 * @param {Object} object The object to query.
27468 * @returns {Array} Returns the array of symbols.
27471 var getSymbols = !nativeGetSymbols ? stubArray_1 : function (object) {
27472 if (object == null) {
27476 object = Object(object);
27477 return _arrayFilter(nativeGetSymbols(object), function (symbol) {
27478 return propertyIsEnumerable$1.call(object, symbol);
27481 var _getSymbols = getSymbols;
27484 * The base implementation of `_.times` without support for iteratee shorthands
27485 * or max array length checks.
27488 * @param {number} n The number of times to invoke `iteratee`.
27489 * @param {Function} iteratee The function invoked per iteration.
27490 * @returns {Array} Returns the array of results.
27492 function baseTimes(n, iteratee) {
27496 while (++index < n) {
27497 result[index] = iteratee(index);
27503 var _baseTimes = baseTimes;
27506 * This method returns `false`.
27512 * @returns {boolean} Returns `false`.
27515 * _.times(2, _.stubFalse);
27516 * // => [false, false]
27518 function stubFalse() {
27522 var stubFalse_1 = stubFalse;
27524 var isBuffer_1 = createCommonjsModule(function (module, exports) {
27525 /** Detect free variable `exports`. */
27526 var freeExports = exports && !exports.nodeType && exports;
27527 /** Detect free variable `module`. */
27529 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
27530 /** Detect the popular CommonJS extension `module.exports`. */
27532 var moduleExports = freeModule && freeModule.exports === freeExports;
27533 /** Built-in value references. */
27535 var Buffer = moduleExports ? _root.Buffer : undefined;
27536 /* Built-in method references for those with the same name as other `lodash` methods. */
27538 var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
27540 * Checks if `value` is a buffer.
27546 * @param {*} value The value to check.
27547 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
27550 * _.isBuffer(new Buffer(2));
27553 * _.isBuffer(new Uint8Array(2));
27557 var isBuffer = nativeIsBuffer || stubFalse_1;
27558 module.exports = isBuffer;
27561 /** Used as references for various `Number` constants. */
27562 var MAX_SAFE_INTEGER$2 = 9007199254740991;
27563 /** Used to detect unsigned integer values. */
27565 var reIsUint = /^(?:0|[1-9]\d*)$/;
27567 * Checks if `value` is a valid array-like index.
27570 * @param {*} value The value to check.
27571 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
27572 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
27575 function isIndex(value, length) {
27576 var type = typeof value;
27577 length = length == null ? MAX_SAFE_INTEGER$2 : length;
27578 return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
27581 var _isIndex = isIndex;
27583 /** Used as references for various `Number` constants. */
27584 var MAX_SAFE_INTEGER$3 = 9007199254740991;
27586 * Checks if `value` is a valid array-like length.
27588 * **Note:** This method is loosely based on
27589 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
27595 * @param {*} value The value to check.
27596 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
27602 * _.isLength(Number.MIN_VALUE);
27605 * _.isLength(Infinity);
27612 function isLength(value) {
27613 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$3;
27616 var isLength_1 = isLength;
27618 /** `Object#toString` result references. */
27620 var argsTag$1 = '[object Arguments]',
27621 arrayTag = '[object Array]',
27622 boolTag$1 = '[object Boolean]',
27623 dateTag$1 = '[object Date]',
27624 errorTag$1 = '[object Error]',
27625 funcTag$1 = '[object Function]',
27626 mapTag$1 = '[object Map]',
27627 numberTag$1 = '[object Number]',
27628 objectTag = '[object Object]',
27629 regexpTag$1 = '[object RegExp]',
27630 setTag$1 = '[object Set]',
27631 stringTag$1 = '[object String]',
27632 weakMapTag = '[object WeakMap]';
27633 var arrayBufferTag$1 = '[object ArrayBuffer]',
27634 dataViewTag$1 = '[object DataView]',
27635 float32Tag = '[object Float32Array]',
27636 float64Tag = '[object Float64Array]',
27637 int8Tag = '[object Int8Array]',
27638 int16Tag = '[object Int16Array]',
27639 int32Tag = '[object Int32Array]',
27640 uint8Tag = '[object Uint8Array]',
27641 uint8ClampedTag = '[object Uint8ClampedArray]',
27642 uint16Tag = '[object Uint16Array]',
27643 uint32Tag = '[object Uint32Array]';
27644 /** Used to identify `toStringTag` values of typed arrays. */
27646 var typedArrayTags = {};
27647 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
27648 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;
27650 * The base implementation of `_.isTypedArray` without Node.js optimizations.
27653 * @param {*} value The value to check.
27654 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
27657 function baseIsTypedArray(value) {
27658 return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
27661 var _baseIsTypedArray = baseIsTypedArray;
27664 * The base implementation of `_.unary` without support for storing metadata.
27667 * @param {Function} func The function to cap arguments for.
27668 * @returns {Function} Returns the new capped function.
27670 function baseUnary(func) {
27671 return function (value) {
27672 return func(value);
27676 var _baseUnary = baseUnary;
27678 var _nodeUtil = createCommonjsModule(function (module, exports) {
27679 /** Detect free variable `exports`. */
27680 var freeExports = exports && !exports.nodeType && exports;
27681 /** Detect free variable `module`. */
27683 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
27684 /** Detect the popular CommonJS extension `module.exports`. */
27686 var moduleExports = freeModule && freeModule.exports === freeExports;
27687 /** Detect free variable `process` from Node.js. */
27689 var freeProcess = moduleExports && _freeGlobal.process;
27690 /** Used to access faster Node.js helpers. */
27692 var nodeUtil = function () {
27694 // Use `util.types` for Node.js 10+.
27695 var types = freeModule && freeModule.require && freeModule.require('util').types;
27699 } // Legacy `process.binding('util')` for Node.js < 10.
27702 return freeProcess && freeProcess.binding && freeProcess.binding('util');
27706 module.exports = nodeUtil;
27709 /* Node.js helper references. */
27711 var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
27713 * Checks if `value` is classified as a typed array.
27719 * @param {*} value The value to check.
27720 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
27723 * _.isTypedArray(new Uint8Array);
27726 * _.isTypedArray([]);
27730 var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
27731 var isTypedArray_1 = isTypedArray;
27733 /** Used for built-in method references. */
27735 var objectProto$7 = Object.prototype;
27736 /** Used to check objects for own properties. */
27738 var hasOwnProperty$7 = objectProto$7.hasOwnProperty;
27740 * Creates an array of the enumerable property names of the array-like `value`.
27743 * @param {*} value The value to query.
27744 * @param {boolean} inherited Specify returning inherited property names.
27745 * @returns {Array} Returns the array of property names.
27748 function arrayLikeKeys(value, inherited) {
27749 var isArr = isArray_1(value),
27750 isArg = !isArr && isArguments_1(value),
27751 isBuff = !isArr && !isArg && isBuffer_1(value),
27752 isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
27753 skipIndexes = isArr || isArg || isBuff || isType,
27754 result = skipIndexes ? _baseTimes(value.length, String) : [],
27755 length = result.length;
27757 for (var key in value) {
27758 if ((inherited || hasOwnProperty$7.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode.
27759 key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers.
27760 isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays.
27761 isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties.
27762 _isIndex(key, length)))) {
27770 var _arrayLikeKeys = arrayLikeKeys;
27772 /** Used for built-in method references. */
27773 var objectProto$8 = Object.prototype;
27775 * Checks if `value` is likely a prototype object.
27778 * @param {*} value The value to check.
27779 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
27782 function isPrototype(value) {
27783 var Ctor = value && value.constructor,
27784 proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$8;
27785 return value === proto;
27788 var _isPrototype = isPrototype;
27791 * Creates a unary function that invokes `func` with its argument transformed.
27794 * @param {Function} func The function to wrap.
27795 * @param {Function} transform The argument transform.
27796 * @returns {Function} Returns the new function.
27798 function overArg(func, transform) {
27799 return function (arg) {
27800 return func(transform(arg));
27804 var _overArg = overArg;
27806 /* Built-in method references for those with the same name as other `lodash` methods. */
27808 var nativeKeys = _overArg(Object.keys, Object);
27809 var _nativeKeys = nativeKeys;
27811 /** Used for built-in method references. */
27813 var objectProto$9 = Object.prototype;
27814 /** Used to check objects for own properties. */
27816 var hasOwnProperty$8 = objectProto$9.hasOwnProperty;
27818 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
27821 * @param {Object} object The object to query.
27822 * @returns {Array} Returns the array of property names.
27825 function baseKeys(object) {
27826 if (!_isPrototype(object)) {
27827 return _nativeKeys(object);
27832 for (var key in Object(object)) {
27833 if (hasOwnProperty$8.call(object, key) && key != 'constructor') {
27841 var _baseKeys = baseKeys;
27844 * Checks if `value` is array-like. A value is considered array-like if it's
27845 * not a function and has a `value.length` that's an integer greater than or
27846 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
27852 * @param {*} value The value to check.
27853 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
27856 * _.isArrayLike([1, 2, 3]);
27859 * _.isArrayLike(document.body.children);
27862 * _.isArrayLike('abc');
27865 * _.isArrayLike(_.noop);
27869 function isArrayLike(value) {
27870 return value != null && isLength_1(value.length) && !isFunction_1(value);
27873 var isArrayLike_1 = isArrayLike;
27876 * Creates an array of the own enumerable property names of `object`.
27878 * **Note:** Non-object values are coerced to objects. See the
27879 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
27880 * for more details.
27886 * @param {Object} object The object to query.
27887 * @returns {Array} Returns the array of property names.
27895 * Foo.prototype.c = 3;
27898 * // => ['a', 'b'] (iteration order is not guaranteed)
27904 function keys(object) {
27905 return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
27911 * Creates an array of own enumerable property names and symbols of `object`.
27914 * @param {Object} object The object to query.
27915 * @returns {Array} Returns the array of property names and symbols.
27918 function getAllKeys(object) {
27919 return _baseGetAllKeys(object, keys_1, _getSymbols);
27922 var _getAllKeys = getAllKeys;
27924 /** Used to compose bitmasks for value comparisons. */
27926 var COMPARE_PARTIAL_FLAG$2 = 1;
27927 /** Used for built-in method references. */
27929 var objectProto$a = Object.prototype;
27930 /** Used to check objects for own properties. */
27932 var hasOwnProperty$9 = objectProto$a.hasOwnProperty;
27934 * A specialized version of `baseIsEqualDeep` for objects with support for
27935 * partial deep comparisons.
27938 * @param {Object} object The object to compare.
27939 * @param {Object} other The other object to compare.
27940 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
27941 * @param {Function} customizer The function to customize comparisons.
27942 * @param {Function} equalFunc The function to determine equivalents of values.
27943 * @param {Object} stack Tracks traversed `object` and `other` objects.
27944 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
27947 function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
27948 var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,
27949 objProps = _getAllKeys(object),
27950 objLength = objProps.length,
27951 othProps = _getAllKeys(other),
27952 othLength = othProps.length;
27954 if (objLength != othLength && !isPartial) {
27958 var index = objLength;
27961 var key = objProps[index];
27963 if (!(isPartial ? key in other : hasOwnProperty$9.call(other, key))) {
27966 } // Check that cyclic values are equal.
27969 var objStacked = stack.get(object);
27970 var othStacked = stack.get(other);
27972 if (objStacked && othStacked) {
27973 return objStacked == other && othStacked == object;
27977 stack.set(object, other);
27978 stack.set(other, object);
27979 var skipCtor = isPartial;
27981 while (++index < objLength) {
27982 key = objProps[index];
27983 var objValue = object[key],
27984 othValue = other[key];
27987 var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
27988 } // Recursively compare objects (susceptible to call stack limits).
27991 if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
27996 skipCtor || (skipCtor = key == 'constructor');
27999 if (result && !skipCtor) {
28000 var objCtor = object.constructor,
28001 othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal.
28003 if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
28008 stack['delete'](object);
28009 stack['delete'](other);
28013 var _equalObjects = equalObjects;
28015 /* Built-in method references that are verified to be native. */
28017 var DataView = _getNative(_root, 'DataView');
28018 var _DataView = DataView;
28020 /* Built-in method references that are verified to be native. */
28022 var Promise$1 = _getNative(_root, 'Promise');
28023 var _Promise = Promise$1;
28025 /* Built-in method references that are verified to be native. */
28027 var Set$1 = _getNative(_root, 'Set');
28030 /* Built-in method references that are verified to be native. */
28032 var WeakMap$1 = _getNative(_root, 'WeakMap');
28033 var _WeakMap = WeakMap$1;
28035 /** `Object#toString` result references. */
28037 var mapTag$2 = '[object Map]',
28038 objectTag$1 = '[object Object]',
28039 promiseTag = '[object Promise]',
28040 setTag$2 = '[object Set]',
28041 weakMapTag$1 = '[object WeakMap]';
28042 var dataViewTag$2 = '[object DataView]';
28043 /** Used to detect maps, sets, and weakmaps. */
28045 var dataViewCtorString = _toSource(_DataView),
28046 mapCtorString = _toSource(_Map),
28047 promiseCtorString = _toSource(_Promise),
28048 setCtorString = _toSource(_Set),
28049 weakMapCtorString = _toSource(_WeakMap);
28051 * Gets the `toStringTag` of `value`.
28054 * @param {*} value The value to query.
28055 * @returns {string} Returns the `toStringTag`.
28058 var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
28060 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) {
28061 getTag = function (value) {
28062 var result = _baseGetTag(value),
28063 Ctor = result == objectTag$1 ? value.constructor : undefined,
28064 ctorString = Ctor ? _toSource(Ctor) : '';
28067 switch (ctorString) {
28068 case dataViewCtorString:
28069 return dataViewTag$2;
28071 case mapCtorString:
28074 case promiseCtorString:
28077 case setCtorString:
28080 case weakMapCtorString:
28081 return weakMapTag$1;
28089 var _getTag = getTag;
28091 /** Used to compose bitmasks for value comparisons. */
28093 var COMPARE_PARTIAL_FLAG$3 = 1;
28094 /** `Object#toString` result references. */
28096 var argsTag$2 = '[object Arguments]',
28097 arrayTag$1 = '[object Array]',
28098 objectTag$2 = '[object Object]';
28099 /** Used for built-in method references. */
28101 var objectProto$b = Object.prototype;
28102 /** Used to check objects for own properties. */
28104 var hasOwnProperty$a = objectProto$b.hasOwnProperty;
28106 * A specialized version of `baseIsEqual` for arrays and objects which performs
28107 * deep comparisons and tracks traversed objects enabling objects with circular
28108 * references to be compared.
28111 * @param {Object} object The object to compare.
28112 * @param {Object} other The other object to compare.
28113 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
28114 * @param {Function} customizer The function to customize comparisons.
28115 * @param {Function} equalFunc The function to determine equivalents of values.
28116 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
28117 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
28120 function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
28121 var objIsArr = isArray_1(object),
28122 othIsArr = isArray_1(other),
28123 objTag = objIsArr ? arrayTag$1 : _getTag(object),
28124 othTag = othIsArr ? arrayTag$1 : _getTag(other);
28125 objTag = objTag == argsTag$2 ? objectTag$2 : objTag;
28126 othTag = othTag == argsTag$2 ? objectTag$2 : othTag;
28127 var objIsObj = objTag == objectTag$2,
28128 othIsObj = othTag == objectTag$2,
28129 isSameTag = objTag == othTag;
28131 if (isSameTag && isBuffer_1(object)) {
28132 if (!isBuffer_1(other)) {
28140 if (isSameTag && !objIsObj) {
28141 stack || (stack = new _Stack());
28142 return objIsArr || isTypedArray_1(object) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
28145 if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {
28146 var objIsWrapped = objIsObj && hasOwnProperty$a.call(object, '__wrapped__'),
28147 othIsWrapped = othIsObj && hasOwnProperty$a.call(other, '__wrapped__');
28149 if (objIsWrapped || othIsWrapped) {
28150 var objUnwrapped = objIsWrapped ? object.value() : object,
28151 othUnwrapped = othIsWrapped ? other.value() : other;
28152 stack || (stack = new _Stack());
28153 return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
28161 stack || (stack = new _Stack());
28162 return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
28165 var _baseIsEqualDeep = baseIsEqualDeep;
28168 * The base implementation of `_.isEqual` which supports partial comparisons
28169 * and tracks traversed objects.
28172 * @param {*} value The value to compare.
28173 * @param {*} other The other value to compare.
28174 * @param {boolean} bitmask The bitmask flags.
28175 * 1 - Unordered comparison
28176 * 2 - Partial comparison
28177 * @param {Function} [customizer] The function to customize comparisons.
28178 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
28179 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
28182 function baseIsEqual(value, other, bitmask, customizer, stack) {
28183 if (value === other) {
28187 if (value == null || other == null || !isObjectLike_1(value) && !isObjectLike_1(other)) {
28188 return value !== value && other !== other;
28191 return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
28194 var _baseIsEqual = baseIsEqual;
28196 /** Used to compose bitmasks for value comparisons. */
28198 var COMPARE_PARTIAL_FLAG$4 = 1,
28199 COMPARE_UNORDERED_FLAG$2 = 2;
28201 * The base implementation of `_.isMatch` without support for iteratee shorthands.
28204 * @param {Object} object The object to inspect.
28205 * @param {Object} source The object of property values to match.
28206 * @param {Array} matchData The property names, values, and compare flags to match.
28207 * @param {Function} [customizer] The function to customize comparisons.
28208 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
28211 function baseIsMatch(object, source, matchData, customizer) {
28212 var index = matchData.length,
28214 noCustomizer = !customizer;
28216 if (object == null) {
28220 object = Object(object);
28223 var data = matchData[index];
28225 if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
28230 while (++index < length) {
28231 data = matchData[index];
28233 objValue = object[key],
28234 srcValue = data[1];
28236 if (noCustomizer && data[2]) {
28237 if (objValue === undefined && !(key in object)) {
28241 var stack = new _Stack();
28244 var result = customizer(objValue, srcValue, key, object, source, stack);
28247 if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result)) {
28256 var _baseIsMatch = baseIsMatch;
28259 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
28262 * @param {*} value The value to check.
28263 * @returns {boolean} Returns `true` if `value` if suitable for strict
28264 * equality comparisons, else `false`.
28267 function isStrictComparable(value) {
28268 return value === value && !isObject_1(value);
28271 var _isStrictComparable = isStrictComparable;
28274 * Gets the property names, values, and compare flags of `object`.
28277 * @param {Object} object The object to query.
28278 * @returns {Array} Returns the match data of `object`.
28281 function getMatchData(object) {
28282 var result = keys_1(object),
28283 length = result.length;
28286 var key = result[length],
28287 value = object[key];
28288 result[length] = [key, value, _isStrictComparable(value)];
28294 var _getMatchData = getMatchData;
28297 * A specialized version of `matchesProperty` for source values suitable
28298 * for strict equality comparisons, i.e. `===`.
28301 * @param {string} key The key of the property to get.
28302 * @param {*} srcValue The value to match.
28303 * @returns {Function} Returns the new spec function.
28305 function matchesStrictComparable(key, srcValue) {
28306 return function (object) {
28307 if (object == null) {
28311 return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
28315 var _matchesStrictComparable = matchesStrictComparable;
28318 * The base implementation of `_.matches` which doesn't clone `source`.
28321 * @param {Object} source The object of property values to match.
28322 * @returns {Function} Returns the new spec function.
28325 function baseMatches(source) {
28326 var matchData = _getMatchData(source);
28328 if (matchData.length == 1 && matchData[0][2]) {
28329 return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
28332 return function (object) {
28333 return object === source || _baseIsMatch(object, source, matchData);
28337 var _baseMatches = baseMatches;
28339 /** `Object#toString` result references. */
28341 var symbolTag$1 = '[object Symbol]';
28343 * Checks if `value` is classified as a `Symbol` primitive or object.
28349 * @param {*} value The value to check.
28350 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
28353 * _.isSymbol(Symbol.iterator);
28356 * _.isSymbol('abc');
28360 function isSymbol(value) {
28361 return typeof value == 'symbol' || isObjectLike_1(value) && _baseGetTag(value) == symbolTag$1;
28364 var isSymbol_1 = isSymbol;
28366 /** Used to match property names within property paths. */
28368 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
28369 reIsPlainProp = /^\w*$/;
28371 * Checks if `value` is a property name and not a property path.
28374 * @param {*} value The value to check.
28375 * @param {Object} [object] The object to query keys on.
28376 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
28379 function isKey(value, object) {
28380 if (isArray_1(value)) {
28384 var type = typeof value;
28386 if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) {
28390 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
28393 var _isKey = isKey;
28395 /** Error message constants. */
28397 var FUNC_ERROR_TEXT = 'Expected a function';
28399 * Creates a function that memoizes the result of `func`. If `resolver` is
28400 * provided, it determines the cache key for storing the result based on the
28401 * arguments provided to the memoized function. By default, the first argument
28402 * provided to the memoized function is used as the map cache key. The `func`
28403 * is invoked with the `this` binding of the memoized function.
28405 * **Note:** The cache is exposed as the `cache` property on the memoized
28406 * function. Its creation may be customized by replacing the `_.memoize.Cache`
28407 * constructor with one whose instances implement the
28408 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
28409 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
28414 * @category Function
28415 * @param {Function} func The function to have its output memoized.
28416 * @param {Function} [resolver] The function to resolve the cache key.
28417 * @returns {Function} Returns the new memoized function.
28420 * var object = { 'a': 1, 'b': 2 };
28421 * var other = { 'c': 3, 'd': 4 };
28423 * var values = _.memoize(_.values);
28434 * // Modify the result cache.
28435 * values.cache.set(object, ['a', 'b']);
28439 * // Replace `_.memoize.Cache`.
28440 * _.memoize.Cache = WeakMap;
28443 function memoize(func, resolver) {
28444 if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
28445 throw new TypeError(FUNC_ERROR_TEXT);
28448 var memoized = function () {
28449 var args = arguments,
28450 key = resolver ? resolver.apply(this, args) : args[0],
28451 cache = memoized.cache;
28453 if (cache.has(key)) {
28454 return cache.get(key);
28457 var result = func.apply(this, args);
28458 memoized.cache = cache.set(key, result) || cache;
28462 memoized.cache = new (memoize.Cache || _MapCache)();
28464 } // Expose `MapCache`.
28467 memoize.Cache = _MapCache;
28468 var memoize_1 = memoize;
28470 /** Used as the maximum memoize cache size. */
28472 var MAX_MEMOIZE_SIZE = 500;
28474 * A specialized version of `_.memoize` which clears the memoized function's
28475 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
28478 * @param {Function} func The function to have its output memoized.
28479 * @returns {Function} Returns the new memoized function.
28482 function memoizeCapped(func) {
28483 var result = memoize_1(func, function (key) {
28484 if (cache.size === MAX_MEMOIZE_SIZE) {
28490 var cache = result.cache;
28494 var _memoizeCapped = memoizeCapped;
28496 /** Used to match property names within property paths. */
28498 var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
28499 /** Used to match backslashes in property paths. */
28501 var reEscapeChar = /\\(\\)?/g;
28503 * Converts `string` to a property path array.
28506 * @param {string} string The string to convert.
28507 * @returns {Array} Returns the property path array.
28510 var stringToPath = _memoizeCapped(function (string) {
28513 if (string.charCodeAt(0) === 46
28519 string.replace(rePropName, function (match, number, quote, subString) {
28520 result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
28524 var _stringToPath = stringToPath;
28527 * A specialized version of `_.map` for arrays without support for iteratee
28531 * @param {Array} [array] The array to iterate over.
28532 * @param {Function} iteratee The function invoked per iteration.
28533 * @returns {Array} Returns the new mapped array.
28535 function arrayMap(array, iteratee) {
28537 length = array == null ? 0 : array.length,
28538 result = Array(length);
28540 while (++index < length) {
28541 result[index] = iteratee(array[index], index, array);
28547 var _arrayMap = arrayMap;
28549 /** Used as references for various `Number` constants. */
28551 var INFINITY = 1 / 0;
28552 /** Used to convert symbols to primitives and strings. */
28554 var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
28555 symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined;
28557 * The base implementation of `_.toString` which doesn't convert nullish
28558 * values to empty strings.
28561 * @param {*} value The value to process.
28562 * @returns {string} Returns the string.
28565 function baseToString(value) {
28566 // Exit early for strings to avoid a performance hit in some environments.
28567 if (typeof value == 'string') {
28571 if (isArray_1(value)) {
28572 // Recursively convert values (susceptible to call stack limits).
28573 return _arrayMap(value, baseToString) + '';
28576 if (isSymbol_1(value)) {
28577 return symbolToString ? symbolToString.call(value) : '';
28580 var result = value + '';
28581 return result == '0' && 1 / value == -INFINITY ? '-0' : result;
28584 var _baseToString = baseToString;
28587 * Converts `value` to a string. An empty string is returned for `null`
28588 * and `undefined` values. The sign of `-0` is preserved.
28594 * @param {*} value The value to convert.
28595 * @returns {string} Returns the converted string.
28598 * _.toString(null);
28604 * _.toString([1, 2, 3]);
28608 function toString(value) {
28609 return value == null ? '' : _baseToString(value);
28612 var toString_1 = toString;
28615 * Casts `value` to a path array if it's not one.
28618 * @param {*} value The value to inspect.
28619 * @param {Object} [object] The object to query keys on.
28620 * @returns {Array} Returns the cast property path array.
28623 function castPath(value, object) {
28624 if (isArray_1(value)) {
28628 return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
28631 var _castPath = castPath;
28633 /** Used as references for various `Number` constants. */
28635 var INFINITY$1 = 1 / 0;
28637 * Converts `value` to a string key if it's not a string or symbol.
28640 * @param {*} value The value to inspect.
28641 * @returns {string|symbol} Returns the key.
28644 function toKey(value) {
28645 if (typeof value == 'string' || isSymbol_1(value)) {
28649 var result = value + '';
28650 return result == '0' && 1 / value == -INFINITY$1 ? '-0' : result;
28653 var _toKey = toKey;
28656 * The base implementation of `_.get` without support for default values.
28659 * @param {Object} object The object to query.
28660 * @param {Array|string} path The path of the property to get.
28661 * @returns {*} Returns the resolved value.
28664 function baseGet(object, path) {
28665 path = _castPath(path, object);
28667 length = path.length;
28669 while (object != null && index < length) {
28670 object = object[_toKey(path[index++])];
28673 return index && index == length ? object : undefined;
28676 var _baseGet = baseGet;
28679 * Gets the value at `path` of `object`. If the resolved value is
28680 * `undefined`, the `defaultValue` is returned in its place.
28686 * @param {Object} object The object to query.
28687 * @param {Array|string} path The path of the property to get.
28688 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
28689 * @returns {*} Returns the resolved value.
28692 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
28694 * _.get(object, 'a[0].b.c');
28697 * _.get(object, ['a', '0', 'b', 'c']);
28700 * _.get(object, 'a.b.c', 'default');
28704 function get$1(object, path, defaultValue) {
28705 var result = object == null ? undefined : _baseGet(object, path);
28706 return result === undefined ? defaultValue : result;
28712 * The base implementation of `_.hasIn` without support for deep paths.
28715 * @param {Object} [object] The object to query.
28716 * @param {Array|string} key The key to check.
28717 * @returns {boolean} Returns `true` if `key` exists, else `false`.
28719 function baseHasIn(object, key) {
28720 return object != null && key in Object(object);
28723 var _baseHasIn = baseHasIn;
28726 * Checks if `path` exists on `object`.
28729 * @param {Object} object The object to query.
28730 * @param {Array|string} path The path to check.
28731 * @param {Function} hasFunc The function to check properties.
28732 * @returns {boolean} Returns `true` if `path` exists, else `false`.
28735 function hasPath(object, path, hasFunc) {
28736 path = _castPath(path, object);
28738 length = path.length,
28741 while (++index < length) {
28742 var key = _toKey(path[index]);
28744 if (!(result = object != null && hasFunc(object, key))) {
28748 object = object[key];
28751 if (result || ++index != length) {
28755 length = object == null ? 0 : object.length;
28756 return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object));
28759 var _hasPath = hasPath;
28762 * Checks if `path` is a direct or inherited property of `object`.
28768 * @param {Object} object The object to query.
28769 * @param {Array|string} path The path to check.
28770 * @returns {boolean} Returns `true` if `path` exists, else `false`.
28773 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
28775 * _.hasIn(object, 'a');
28778 * _.hasIn(object, 'a.b');
28781 * _.hasIn(object, ['a', 'b']);
28784 * _.hasIn(object, 'b');
28788 function hasIn(object, path) {
28789 return object != null && _hasPath(object, path, _baseHasIn);
28792 var hasIn_1 = hasIn;
28794 /** Used to compose bitmasks for value comparisons. */
28796 var COMPARE_PARTIAL_FLAG$5 = 1,
28797 COMPARE_UNORDERED_FLAG$3 = 2;
28799 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
28802 * @param {string} path The path of the property to get.
28803 * @param {*} srcValue The value to match.
28804 * @returns {Function} Returns the new spec function.
28807 function baseMatchesProperty(path, srcValue) {
28808 if (_isKey(path) && _isStrictComparable(srcValue)) {
28809 return _matchesStrictComparable(_toKey(path), srcValue);
28812 return function (object) {
28813 var objValue = get_1(object, path);
28814 return objValue === undefined && objValue === srcValue ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);
28818 var _baseMatchesProperty = baseMatchesProperty;
28821 * This method returns the first argument it receives.
28827 * @param {*} value Any value.
28828 * @returns {*} Returns `value`.
28831 * var object = { 'a': 1 };
28833 * console.log(_.identity(object) === object);
28836 function identity(value) {
28840 var identity_1 = identity;
28843 * The base implementation of `_.property` without support for deep paths.
28846 * @param {string} key The key of the property to get.
28847 * @returns {Function} Returns the new accessor function.
28849 function baseProperty(key) {
28850 return function (object) {
28851 return object == null ? undefined : object[key];
28855 var _baseProperty = baseProperty;
28858 * A specialized version of `baseProperty` which supports deep paths.
28861 * @param {Array|string} path The path of the property to get.
28862 * @returns {Function} Returns the new accessor function.
28865 function basePropertyDeep(path) {
28866 return function (object) {
28867 return _baseGet(object, path);
28871 var _basePropertyDeep = basePropertyDeep;
28874 * Creates a function that returns the value at `path` of a given object.
28880 * @param {Array|string} path The path of the property to get.
28881 * @returns {Function} Returns the new accessor function.
28885 * { 'a': { 'b': 2 } },
28886 * { 'a': { 'b': 1 } }
28889 * _.map(objects, _.property('a.b'));
28892 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
28896 function property(path) {
28897 return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
28900 var property_1 = property;
28903 * The base implementation of `_.iteratee`.
28906 * @param {*} [value=_.identity] The value to convert to an iteratee.
28907 * @returns {Function} Returns the iteratee.
28910 function baseIteratee(value) {
28911 // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
28912 // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
28913 if (typeof value == 'function') {
28917 if (value == null) {
28921 if (typeof value == 'object') {
28922 return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value);
28925 return property_1(value);
28928 var _baseIteratee = baseIteratee;
28931 * The base implementation of `_.findIndex` and `_.findLastIndex` without
28932 * support for iteratee shorthands.
28935 * @param {Array} array The array to inspect.
28936 * @param {Function} predicate The function invoked per iteration.
28937 * @param {number} fromIndex The index to search from.
28938 * @param {boolean} [fromRight] Specify iterating from right to left.
28939 * @returns {number} Returns the index of the matched value, else `-1`.
28941 function baseFindIndex(array, predicate, fromIndex, fromRight) {
28942 var length = array.length,
28943 index = fromIndex + (fromRight ? 1 : -1);
28945 while (fromRight ? index-- : ++index < length) {
28946 if (predicate(array[index], index, array)) {
28954 var _baseFindIndex = baseFindIndex;
28957 * The base implementation of `_.isNaN` without support for number objects.
28960 * @param {*} value The value to check.
28961 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
28963 function baseIsNaN(value) {
28964 return value !== value;
28967 var _baseIsNaN = baseIsNaN;
28970 * A specialized version of `_.indexOf` which performs strict equality
28971 * comparisons of values, i.e. `===`.
28974 * @param {Array} array The array to inspect.
28975 * @param {*} value The value to search for.
28976 * @param {number} fromIndex The index to search from.
28977 * @returns {number} Returns the index of the matched value, else `-1`.
28979 function strictIndexOf(array, value, fromIndex) {
28980 var index = fromIndex - 1,
28981 length = array.length;
28983 while (++index < length) {
28984 if (array[index] === value) {
28992 var _strictIndexOf = strictIndexOf;
28995 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
28998 * @param {Array} array The array to inspect.
28999 * @param {*} value The value to search for.
29000 * @param {number} fromIndex The index to search from.
29001 * @returns {number} Returns the index of the matched value, else `-1`.
29004 function baseIndexOf(array, value, fromIndex) {
29005 return value === value ? _strictIndexOf(array, value, fromIndex) : _baseFindIndex(array, _baseIsNaN, fromIndex);
29008 var _baseIndexOf = baseIndexOf;
29011 * A specialized version of `_.includes` for arrays without support for
29012 * specifying an index to search from.
29015 * @param {Array} [array] The array to inspect.
29016 * @param {*} target The value to search for.
29017 * @returns {boolean} Returns `true` if `target` is found, else `false`.
29020 function arrayIncludes(array, value) {
29021 var length = array == null ? 0 : array.length;
29022 return !!length && _baseIndexOf(array, value, 0) > -1;
29025 var _arrayIncludes = arrayIncludes;
29028 * This function is like `arrayIncludes` except that it accepts a comparator.
29031 * @param {Array} [array] The array to inspect.
29032 * @param {*} target The value to search for.
29033 * @param {Function} comparator The comparator invoked per element.
29034 * @returns {boolean} Returns `true` if `target` is found, else `false`.
29036 function arrayIncludesWith(array, value, comparator) {
29038 length = array == null ? 0 : array.length;
29040 while (++index < length) {
29041 if (comparator(value, array[index])) {
29049 var _arrayIncludesWith = arrayIncludesWith;
29052 * This method returns `undefined`.
29060 * _.times(2, _.noop);
29061 * // => [undefined, undefined]
29063 function noop() {// No operation performed.
29068 /** Used as references for various `Number` constants. */
29070 var INFINITY$2 = 1 / 0;
29072 * Creates a set object of `values`.
29075 * @param {Array} values The values to add to the set.
29076 * @returns {Object} Returns the new set.
29079 var createSet = !(_Set && 1 / _setToArray(new _Set([, -0]))[1] == INFINITY$2) ? noop_1 : function (values) {
29080 return new _Set(values);
29082 var _createSet = createSet;
29084 /** Used as the size to enable large array optimizations. */
29086 var LARGE_ARRAY_SIZE$1 = 200;
29088 * The base implementation of `_.uniqBy` without support for iteratee shorthands.
29091 * @param {Array} array The array to inspect.
29092 * @param {Function} [iteratee] The iteratee invoked per element.
29093 * @param {Function} [comparator] The comparator invoked per element.
29094 * @returns {Array} Returns the new duplicate free array.
29097 function baseUniq(array, iteratee, comparator) {
29099 includes = _arrayIncludes,
29100 length = array.length,
29107 includes = _arrayIncludesWith;
29108 } else if (length >= LARGE_ARRAY_SIZE$1) {
29109 var set = iteratee ? null : _createSet(array);
29112 return _setToArray(set);
29116 includes = _cacheHas;
29117 seen = new _SetCache();
29119 seen = iteratee ? [] : result;
29122 outer: while (++index < length) {
29123 var value = array[index],
29124 computed = iteratee ? iteratee(value) : value;
29125 value = comparator || value !== 0 ? value : 0;
29127 if (isCommon && computed === computed) {
29128 var seenIndex = seen.length;
29130 while (seenIndex--) {
29131 if (seen[seenIndex] === computed) {
29137 seen.push(computed);
29140 result.push(value);
29141 } else if (!includes(seen, computed, comparator)) {
29142 if (seen !== result) {
29143 seen.push(computed);
29146 result.push(value);
29153 var _baseUniq = baseUniq;
29156 * This method is like `_.uniq` except that it accepts `iteratee` which is
29157 * invoked for each element in `array` to generate the criterion by which
29158 * uniqueness is computed. The order of result values is determined by the
29159 * order they occur in the array. The iteratee is invoked with one argument:
29166 * @param {Array} array The array to inspect.
29167 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
29168 * @returns {Array} Returns the new duplicate free array.
29171 * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
29174 * // The `_.property` iteratee shorthand.
29175 * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
29176 * // => [{ 'x': 1 }, { 'x': 2 }]
29179 function uniqBy(array, iteratee) {
29180 return array && array.length ? _baseUniq(array, _baseIteratee(iteratee)) : [];
29183 var uniqBy_1 = uniqBy;
29186 * A specialized version of `baseAggregator` for arrays.
29189 * @param {Array} [array] The array to iterate over.
29190 * @param {Function} setter The function to set `accumulator` values.
29191 * @param {Function} iteratee The iteratee to transform keys.
29192 * @param {Object} accumulator The initial aggregated object.
29193 * @returns {Function} Returns `accumulator`.
29195 function arrayAggregator(array, setter, iteratee, accumulator) {
29197 length = array == null ? 0 : array.length;
29199 while (++index < length) {
29200 var value = array[index];
29201 setter(accumulator, value, iteratee(value), array);
29204 return accumulator;
29207 var _arrayAggregator = arrayAggregator;
29210 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
29213 * @param {boolean} [fromRight] Specify iterating from right to left.
29214 * @returns {Function} Returns the new base function.
29216 function createBaseFor(fromRight) {
29217 return function (object, iteratee, keysFunc) {
29219 iterable = Object(object),
29220 props = keysFunc(object),
29221 length = props.length;
29224 var key = props[fromRight ? length : ++index];
29226 if (iteratee(iterable[key], key, iterable) === false) {
29235 var _createBaseFor = createBaseFor;
29238 * The base implementation of `baseForOwn` which iterates over `object`
29239 * properties returned by `keysFunc` and invokes `iteratee` for each property.
29240 * Iteratee functions may exit iteration early by explicitly returning `false`.
29243 * @param {Object} object The object to iterate over.
29244 * @param {Function} iteratee The function invoked per iteration.
29245 * @param {Function} keysFunc The function to get the keys of `object`.
29246 * @returns {Object} Returns `object`.
29249 var baseFor = _createBaseFor();
29250 var _baseFor = baseFor;
29253 * The base implementation of `_.forOwn` without support for iteratee shorthands.
29256 * @param {Object} object The object to iterate over.
29257 * @param {Function} iteratee The function invoked per iteration.
29258 * @returns {Object} Returns `object`.
29261 function baseForOwn(object, iteratee) {
29262 return object && _baseFor(object, iteratee, keys_1);
29265 var _baseForOwn = baseForOwn;
29268 * Creates a `baseEach` or `baseEachRight` function.
29271 * @param {Function} eachFunc The function to iterate over a collection.
29272 * @param {boolean} [fromRight] Specify iterating from right to left.
29273 * @returns {Function} Returns the new base function.
29276 function createBaseEach(eachFunc, fromRight) {
29277 return function (collection, iteratee) {
29278 if (collection == null) {
29282 if (!isArrayLike_1(collection)) {
29283 return eachFunc(collection, iteratee);
29286 var length = collection.length,
29287 index = fromRight ? length : -1,
29288 iterable = Object(collection);
29290 while (fromRight ? index-- : ++index < length) {
29291 if (iteratee(iterable[index], index, iterable) === false) {
29300 var _createBaseEach = createBaseEach;
29303 * The base implementation of `_.forEach` without support for iteratee shorthands.
29306 * @param {Array|Object} collection The collection to iterate over.
29307 * @param {Function} iteratee The function invoked per iteration.
29308 * @returns {Array|Object} Returns `collection`.
29311 var baseEach = _createBaseEach(_baseForOwn);
29312 var _baseEach = baseEach;
29315 * Aggregates elements of `collection` on `accumulator` with keys transformed
29316 * by `iteratee` and values set by `setter`.
29319 * @param {Array|Object} collection The collection to iterate over.
29320 * @param {Function} setter The function to set `accumulator` values.
29321 * @param {Function} iteratee The iteratee to transform keys.
29322 * @param {Object} accumulator The initial aggregated object.
29323 * @returns {Function} Returns `accumulator`.
29326 function baseAggregator(collection, setter, iteratee, accumulator) {
29327 _baseEach(collection, function (value, key, collection) {
29328 setter(accumulator, value, iteratee(value), collection);
29330 return accumulator;
29333 var _baseAggregator = baseAggregator;
29336 * Creates a function like `_.groupBy`.
29339 * @param {Function} setter The function to set accumulator values.
29340 * @param {Function} [initializer] The accumulator object initializer.
29341 * @returns {Function} Returns the new aggregator function.
29344 function createAggregator(setter, initializer) {
29345 return function (collection, iteratee) {
29346 var func = isArray_1(collection) ? _arrayAggregator : _baseAggregator,
29347 accumulator = initializer ? initializer() : {};
29348 return func(collection, setter, _baseIteratee(iteratee), accumulator);
29352 var _createAggregator = createAggregator;
29355 * Creates an array of elements split into two groups, the first of which
29356 * contains elements `predicate` returns truthy for, the second of which
29357 * contains elements `predicate` returns falsey for. The predicate is
29358 * invoked with one argument: (value).
29363 * @category Collection
29364 * @param {Array|Object} collection The collection to iterate over.
29365 * @param {Function} [predicate=_.identity] The function invoked per iteration.
29366 * @returns {Array} Returns the array of grouped elements.
29370 * { 'user': 'barney', 'age': 36, 'active': false },
29371 * { 'user': 'fred', 'age': 40, 'active': true },
29372 * { 'user': 'pebbles', 'age': 1, 'active': false }
29375 * _.partition(users, function(o) { return o.active; });
29376 * // => objects for [['fred'], ['barney', 'pebbles']]
29378 * // The `_.matches` iteratee shorthand.
29379 * _.partition(users, { 'age': 1, 'active': false });
29380 * // => objects for [['pebbles'], ['barney', 'fred']]
29382 * // The `_.matchesProperty` iteratee shorthand.
29383 * _.partition(users, ['active', false]);
29384 * // => objects for [['barney', 'pebbles'], ['fred']]
29386 * // The `_.property` iteratee shorthand.
29387 * _.partition(users, 'active');
29388 * // => objects for [['fred'], ['barney', 'pebbles']]
29391 var partition = _createAggregator(function (result, value, key) {
29392 result[key ? 0 : 1].push(value);
29396 var partition_1 = partition;
29398 var arrayUnion = (...arguments_) => {
29399 return [...new Set([].concat(...arguments_))];
29404 * https://github.com/teambition/merge2
29406 * Copyright (c) 2014-2020 Teambition
29407 * Licensed under the MIT license.
29411 const PassThrough = stream_1__default['default'].PassThrough;
29412 const slice$1 = Array.prototype.slice;
29413 var merge2_1 = merge2;
29415 function merge2() {
29416 const streamsQueue = [];
29417 const args = slice$1.call(arguments);
29418 let merging = false;
29419 let options = args[args.length - 1];
29421 if (options && !Array.isArray(options) && options.pipe == null) {
29427 const doEnd = options.end !== false;
29428 const doPipeError = options.pipeError === true;
29430 if (options.objectMode == null) {
29431 options.objectMode = true;
29434 if (options.highWaterMark == null) {
29435 options.highWaterMark = 64 * 1024;
29438 const mergedStream = PassThrough(options);
29440 function addStream() {
29441 for (let i = 0, len = arguments.length; i < len; i++) {
29442 streamsQueue.push(pauseStreams(arguments[i], options));
29449 function mergeStream() {
29455 let streams = streamsQueue.shift();
29458 process.nextTick(endStream);
29462 if (!Array.isArray(streams)) {
29463 streams = [streams];
29466 let pipesCount = streams.length + 1;
29469 if (--pipesCount > 0) {
29477 function pipe(stream) {
29479 stream.removeListener('merge2UnpipeEnd', onend);
29480 stream.removeListener('end', onend);
29483 stream.removeListener('error', onerror);
29489 function onerror(err) {
29490 mergedStream.emit('error', err);
29491 } // skip ended stream
29494 if (stream._readableState.endEmitted) {
29498 stream.on('merge2UnpipeEnd', onend);
29499 stream.on('end', onend);
29502 stream.on('error', onerror);
29505 stream.pipe(mergedStream, {
29507 }); // compatible for old stream
29512 for (let i = 0; i < streams.length; i++) {
29519 function endStream() {
29520 merging = false; // emit 'queueDrain' when all streams merged.
29522 mergedStream.emit('queueDrain');
29525 mergedStream.end();
29529 mergedStream.setMaxListeners(0);
29530 mergedStream.add = addStream;
29531 mergedStream.on('unpipe', function (stream) {
29532 stream.emit('merge2UnpipeEnd');
29536 addStream.apply(null, args);
29539 return mergedStream;
29540 } // check and pause streams for pipe.
29543 function pauseStreams(streams, options) {
29544 if (!Array.isArray(streams)) {
29545 // Backwards-compat with old-style streams
29546 if (!streams._readableState && streams.pipe) {
29547 streams = streams.pipe(PassThrough(options));
29550 if (!streams._readableState || !streams.pause || !streams.pipe) {
29551 throw new Error('Only readable stream can be merged.');
29556 for (let i = 0, len = streams.length; i < len; i++) {
29557 streams[i] = pauseStreams(streams[i], options);
29564 var array$2 = createCommonjsModule(function (module, exports) {
29566 Object.defineProperty(exports, "__esModule", {
29569 exports.splitWhen = exports.flatten = void 0;
29571 function flatten(items) {
29572 return items.reduce((collection, item) => [].concat(collection, item), []);
29575 exports.flatten = flatten;
29577 function splitWhen(items, predicate) {
29578 const result = [[]];
29579 let groupIndex = 0;
29581 for (const item of items) {
29582 if (predicate(item)) {
29584 result[groupIndex] = [];
29586 result[groupIndex].push(item);
29593 exports.splitWhen = splitWhen;
29596 var errno = createCommonjsModule(function (module, exports) {
29598 Object.defineProperty(exports, "__esModule", {
29601 exports.isEnoentCodeError = void 0;
29603 function isEnoentCodeError(error) {
29604 return error.code === 'ENOENT';
29607 exports.isEnoentCodeError = isEnoentCodeError;
29610 var fs$2 = createCommonjsModule(function (module, exports) {
29612 Object.defineProperty(exports, "__esModule", {
29615 exports.createDirentFromStats = void 0;
29617 class DirentFromStats {
29618 constructor(name, stats) {
29620 this.isBlockDevice = stats.isBlockDevice.bind(stats);
29621 this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
29622 this.isDirectory = stats.isDirectory.bind(stats);
29623 this.isFIFO = stats.isFIFO.bind(stats);
29624 this.isFile = stats.isFile.bind(stats);
29625 this.isSocket = stats.isSocket.bind(stats);
29626 this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
29631 function createDirentFromStats(name, stats) {
29632 return new DirentFromStats(name, stats);
29635 exports.createDirentFromStats = createDirentFromStats;
29638 var path_1 = createCommonjsModule(function (module, exports) {
29640 Object.defineProperty(exports, "__esModule", {
29643 exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0;
29644 const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
29646 const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
29648 * Designed to work only with simple paths: `dir\\file`.
\r
29651 function unixify(filepath) {
29652 return filepath.replace(/\\/g, '/');
29655 exports.unixify = unixify;
29657 function makeAbsolute(cwd, filepath) {
29658 return path__default['default'].resolve(cwd, filepath);
29661 exports.makeAbsolute = makeAbsolute;
29663 function escape(pattern) {
29664 return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
29667 exports.escape = escape;
29669 function removeLeadingDotSegment(entry) {
29670 // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
29671 // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
29672 if (entry.charAt(0) === '.') {
29673 const secondCharactery = entry.charAt(1);
29675 if (secondCharactery === '/' || secondCharactery === '\\') {
29676 return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
29683 exports.removeLeadingDotSegment = removeLeadingDotSegment;
29687 * is-extglob <https://github.com/jonschlinkert/is-extglob>
29689 * Copyright (c) 2014-2016, Jon Schlinkert.
29690 * Licensed under the MIT License.
29692 var isExtglob = function isExtglob(str) {
29693 if (typeof str !== 'string' || str === '') {
29699 while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
29700 if (match[2]) return true;
29701 str = str.slice(match.index + match[0].length);
29708 * is-glob <https://github.com/jonschlinkert/is-glob>
29710 * Copyright (c) 2014-2017, Jon Schlinkert.
29711 * Released under the MIT License.
29719 var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
29720 var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
29722 var isGlob = function isGlob(str, options) {
29723 if (typeof str !== 'string' || str === '') {
29727 if (isExtglob(str)) {
29731 var regex = strictRegex;
29732 var match; // optionally relax regex
29734 if (options && options.strict === false) {
29735 regex = relaxedRegex;
29738 while (match = regex.exec(str)) {
29739 if (match[2]) return true;
29740 var idx = match.index + match[0].length; // if an open bracket/brace/paren is escaped,
29741 // set the index to the next closing character
29743 var open = match[1];
29744 var close = open ? chars[open] : null;
29746 if (open && close) {
29747 var n = str.indexOf(close, idx);
29754 str = str.slice(idx);
29760 var pathPosixDirname = path__default['default'].posix.dirname;
29761 var isWin32 = os__default['default'].platform() === 'win32';
29763 var backslash = /\\/g;
29764 var enclosure = /[\{\[].*[\/]*.*[\}\]]$/;
29765 var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
29766 var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
29768 * @param {string} str
29769 * @param {Object} opts
29770 * @param {boolean} [opts.flipBackslashes=true]
29773 var globParent = function globParent(str, opts) {
29774 var options = Object.assign({
29775 flipBackslashes: true
29776 }, opts); // flip windows path separators
29778 if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
29779 str = str.replace(backslash, slash);
29780 } // special case for strings ending in enclosure containing path separator
29783 if (enclosure.test(str)) {
29785 } // preserves full path in case of trailing path separator
29788 str += 'a'; // remove path parts that are globby
29791 str = pathPosixDirname(str);
29792 } while (isGlob(str) || globby.test(str)); // remove escape chars and return result
29795 return str.replace(escaped, '$1');
29798 var utils$1 = createCommonjsModule(function (module, exports) {
29800 exports.isInteger = num => {
29801 if (typeof num === 'number') {
29802 return Number.isInteger(num);
29805 if (typeof num === 'string' && num.trim() !== '') {
29806 return Number.isInteger(Number(num));
29812 * Find a node of the given type
29816 exports.find = (node, type) => node.nodes.find(node => node.type === type);
29818 * Find a node of the given type
29822 exports.exceedsLimit = (min, max, step = 1, limit) => {
29823 if (limit === false) return false;
29824 if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
29825 return (Number(max) - Number(min)) / Number(step) >= limit;
29828 * Escape the given node with '\\' before node.value
29832 exports.escapeNode = (block, n = 0, type) => {
29833 let node = block.nodes[n];
29836 if (type && node.type === type || node.type === 'open' || node.type === 'close') {
29837 if (node.escaped !== true) {
29838 node.value = '\\' + node.value;
29839 node.escaped = true;
29844 * Returns true if the given brace node should be enclosed in literal braces
29848 exports.encloseBrace = node => {
29849 if (node.type !== 'brace') return false;
29851 if (node.commas >> 0 + node.ranges >> 0 === 0) {
29852 node.invalid = true;
29859 * Returns true if a brace node is invalid.
29863 exports.isInvalidBrace = block => {
29864 if (block.type !== 'brace') return false;
29865 if (block.invalid === true || block.dollar) return true;
29867 if (block.commas >> 0 + block.ranges >> 0 === 0) {
29868 block.invalid = true;
29872 if (block.open !== true || block.close !== true) {
29873 block.invalid = true;
29880 * Returns true if a node is an open or close node
29884 exports.isOpenOrClose = node => {
29885 if (node.type === 'open' || node.type === 'close') {
29889 return node.open === true || node.close === true;
29892 * Reduce an array of text nodes.
29896 exports.reduce = nodes => nodes.reduce((acc, node) => {
29897 if (node.type === 'text') acc.push(node.value);
29898 if (node.type === 'range') node.type = 'text';
29906 exports.flatten = (...args) => {
29909 const flat = arr => {
29910 for (let i = 0; i < arr.length; i++) {
29912 Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
29923 var stringify$1 = (ast, options = {}) => {
29924 let stringify = (node, parent = {}) => {
29925 let invalidBlock = options.escapeInvalid && utils$1.isInvalidBrace(parent);
29926 let invalidNode = node.invalid === true && options.escapeInvalid === true;
29930 if ((invalidBlock || invalidNode) && utils$1.isOpenOrClose(node)) {
29931 return '\\' + node.value;
29942 for (let child of node.nodes) {
29943 output += stringify(child);
29950 return stringify(ast);
29954 * is-number <https://github.com/jonschlinkert/is-number>
29956 * Copyright (c) 2014-present, Jon Schlinkert.
29957 * Released under the MIT License.
29960 var isNumber = function (num) {
29961 if (typeof num === 'number') {
29962 return num - num === 0;
29965 if (typeof num === 'string' && num.trim() !== '') {
29966 return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
29972 const toRegexRange = (min, max, options) => {
29973 if (isNumber(min) === false) {
29974 throw new TypeError('toRegexRange: expected the first argument to be a number');
29977 if (max === void 0 || min === max) {
29978 return String(min);
29981 if (isNumber(max) === false) {
29982 throw new TypeError('toRegexRange: expected the second argument to be a number.');
29985 let opts = Object.assign({
29989 if (typeof opts.strictZeros === 'boolean') {
29990 opts.relaxZeros = opts.strictZeros === false;
29993 let relax = String(opts.relaxZeros);
29994 let shorthand = String(opts.shorthand);
29995 let capture = String(opts.capture);
29996 let wrap = String(opts.wrap);
29997 let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
29999 if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
30000 return toRegexRange.cache[cacheKey].result;
30003 let a = Math.min(min, max);
30004 let b = Math.max(min, max);
30006 if (Math.abs(a - b) === 1) {
30007 let result = min + '|' + max;
30009 if (opts.capture) {
30010 return `(${result})`;
30013 if (opts.wrap === false) {
30017 return `(?:${result})`;
30020 let isPadded = hasPadding(min) || hasPadding(max);
30027 let positives = [];
30028 let negatives = [];
30031 state.isPadded = isPadded;
30032 state.maxLen = String(state.max).length;
30036 let newMin = b < 0 ? Math.abs(b) : 1;
30037 negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
30042 positives = splitToPatterns(a, b, state, opts);
30045 state.negatives = negatives;
30046 state.positives = positives;
30047 state.result = collatePatterns(negatives, positives);
30049 if (opts.capture === true) {
30050 state.result = `(${state.result})`;
30051 } else if (opts.wrap !== false && positives.length + negatives.length > 1) {
30052 state.result = `(?:${state.result})`;
30055 toRegexRange.cache[cacheKey] = state;
30056 return state.result;
30059 function collatePatterns(neg, pos, options) {
30060 let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
30061 let onlyPositive = filterPatterns(pos, neg, '', false) || [];
30062 let intersected = filterPatterns(neg, pos, '-?', true) || [];
30063 let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
30064 return subpatterns.join('|');
30067 function splitToRanges(min, max) {
30070 let stop = countNines(min, nines);
30071 let stops = new Set([max]);
30073 while (min <= stop && stop <= max) {
30076 stop = countNines(min, nines);
30079 stop = countZeros(max + 1, zeros) - 1;
30081 while (min < stop && stop <= max) {
30084 stop = countZeros(max + 1, zeros) - 1;
30087 stops = [...stops];
30088 stops.sort(compare$1);
30092 * Convert a range to a regex pattern
30093 * @param {Number} `start`
30094 * @param {Number} `stop`
30099 function rangeToPattern(start, stop, options) {
30100 if (start === stop) {
30108 let zipped = zip(start, stop);
30109 let digits = zipped.length;
30113 for (let i = 0; i < digits; i++) {
30114 let [startDigit, stopDigit] = zipped[i];
30116 if (startDigit === stopDigit) {
30117 pattern += startDigit;
30118 } else if (startDigit !== '0' || stopDigit !== '9') {
30119 pattern += toCharacterClass(startDigit, stopDigit);
30126 pattern += options.shorthand === true ? '\\d' : '[0-9]';
30136 function splitToPatterns(min, max, tok, options) {
30137 let ranges = splitToRanges(min, max);
30142 for (let i = 0; i < ranges.length; i++) {
30143 let max = ranges[i];
30144 let obj = rangeToPattern(String(start), String(max), options);
30147 if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
30148 if (prev.count.length > 1) {
30152 prev.count.push(obj.count[0]);
30153 prev.string = prev.pattern + toQuantifier(prev.count);
30158 if (tok.isPadded) {
30159 zeros = padZeros(max, tok, options);
30162 obj.string = zeros + obj.pattern + toQuantifier(obj.count);
30171 function filterPatterns(arr, comparison, prefix, intersection, options) {
30174 for (let ele of arr) {
30177 } = ele; // only push if _both_ are negative...
30179 if (!intersection && !contains(comparison, 'string', string)) {
30180 result.push(prefix + string);
30181 } // or _both_ are positive
30184 if (intersection && contains(comparison, 'string', string)) {
30185 result.push(prefix + string);
30196 function zip(a, b) {
30199 for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
30204 function compare$1(a, b) {
30205 return a > b ? 1 : b > a ? -1 : 0;
30208 function contains(arr, key, val) {
30209 return arr.some(ele => ele[key] === val);
30212 function countNines(min, len) {
30213 return Number(String(min).slice(0, -len) + '9'.repeat(len));
30216 function countZeros(integer, zeros) {
30217 return integer - integer % Math.pow(10, zeros);
30220 function toQuantifier(digits) {
30221 let [start = 0, stop = ''] = digits;
30223 if (stop || start > 1) {
30224 return `{${start + (stop ? ',' + stop : '')}}`;
30230 function toCharacterClass(a, b, options) {
30231 return `[${a}${b - a === 1 ? '' : '-'}${b}]`;
30234 function hasPadding(str) {
30235 return /^-?(0+)\d/.test(str);
30238 function padZeros(value, tok, options) {
30239 if (!tok.isPadded) {
30243 let diff = Math.abs(tok.maxLen - String(value).length);
30244 let relax = options.relaxZeros !== false;
30251 return relax ? '0?' : '0';
30254 return relax ? '0{0,2}' : '00';
30258 return relax ? `0{0,${diff}}` : `0{${diff}}`;
30267 toRegexRange.cache = {};
30269 toRegexRange.clearCache = () => toRegexRange.cache = {};
30271 * Expose `toRegexRange`
30275 var toRegexRange_1 = toRegexRange;
30277 const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
30279 const transform = toNumber => {
30280 return value => toNumber === true ? Number(value) : String(value);
30283 const isValidValue = value => {
30284 return typeof value === 'number' || typeof value === 'string' && value !== '';
30287 const isNumber$1 = num => Number.isInteger(+num);
30289 const zeros = input => {
30290 let value = `${input}`;
30292 if (value[0] === '-') value = value.slice(1);
30293 if (value === '0') return false;
30295 while (value[++index] === '0');
30300 const stringify$2 = (start, end, options) => {
30301 if (typeof start === 'string' || typeof end === 'string') {
30305 return options.stringify === true;
30308 const pad = (input, maxLength, toNumber) => {
30309 if (maxLength > 0) {
30310 let dash = input[0] === '-' ? '-' : '';
30311 if (dash) input = input.slice(1);
30312 input = dash + input.padStart(dash ? maxLength - 1 : maxLength, '0');
30315 if (toNumber === false) {
30316 return String(input);
30322 const toMaxLen = (input, maxLength) => {
30323 let negative = input[0] === '-' ? '-' : '';
30326 input = input.slice(1);
30330 while (input.length < maxLength) input = '0' + input;
30332 return negative ? '-' + input : input;
30335 const toSequence = (parts, options) => {
30336 parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
30337 parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
30338 let prefix = options.capture ? '' : '?:';
30339 let positives = '';
30340 let negatives = '';
30343 if (parts.positives.length) {
30344 positives = parts.positives.join('|');
30347 if (parts.negatives.length) {
30348 negatives = `-(${prefix}${parts.negatives.join('|')})`;
30351 if (positives && negatives) {
30352 result = `${positives}|${negatives}`;
30354 result = positives || negatives;
30357 if (options.wrap) {
30358 return `(${prefix}${result})`;
30364 const toRange = (a, b, isNumbers, options) => {
30366 return toRegexRange_1(a, b, Object.assign({
30371 let start = String.fromCharCode(a);
30372 if (a === b) return start;
30373 let stop = String.fromCharCode(b);
30374 return `[${start}-${stop}]`;
30377 const toRegex = (start, end, options) => {
30378 if (Array.isArray(start)) {
30379 let wrap = options.wrap === true;
30380 let prefix = options.capture ? '' : '?:';
30381 return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
30384 return toRegexRange_1(start, end, options);
30387 const rangeError = (...args) => {
30388 return new RangeError('Invalid range arguments: ' + util__default['default'].inspect(...args));
30391 const invalidRange = (start, end, options) => {
30392 if (options.strictRanges === true) throw rangeError([start, end]);
30396 const invalidStep = (step, options) => {
30397 if (options.strictRanges === true) {
30398 throw new TypeError(`Expected step "${step}" to be a number`);
30404 const fillNumbers = (start, end, step = 1, options = {}) => {
30405 let a = Number(start);
30406 let b = Number(end);
30408 if (!Number.isInteger(a) || !Number.isInteger(b)) {
30409 if (options.strictRanges === true) throw rangeError([start, end]);
30411 } // fix negative zero
30414 if (a === 0) a = 0;
30415 if (b === 0) b = 0;
30416 let descending = a > b;
30417 let startString = String(start);
30418 let endString = String(end);
30419 let stepString = String(step);
30420 step = Math.max(Math.abs(step), 1);
30421 let padded = zeros(startString) || zeros(endString) || zeros(stepString);
30422 let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
30423 let toNumber = padded === false && stringify$2(start, end, options) === false;
30424 let format = options.transform || transform(toNumber);
30426 if (options.toRegex && step === 1) {
30427 return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
30435 let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
30440 while (descending ? a >= b : a <= b) {
30441 if (options.toRegex === true && step > 1) {
30444 range.push(pad(format(a, index), maxLen, toNumber));
30447 a = descending ? a - step : a + step;
30451 if (options.toRegex === true) {
30452 return step > 1 ? toSequence(parts, options) : toRegex(range, null, Object.assign({
30460 const fillLetters = (start, end, step = 1, options = {}) => {
30461 if (!isNumber$1(start) && start.length > 1 || !isNumber$1(end) && end.length > 1) {
30462 return invalidRange(start, end, options);
30465 let format = options.transform || (val => String.fromCharCode(val));
30467 let a = `${start}`.charCodeAt(0);
30468 let b = `${end}`.charCodeAt(0);
30469 let descending = a > b;
30470 let min = Math.min(a, b);
30471 let max = Math.max(a, b);
30473 if (options.toRegex && step === 1) {
30474 return toRange(min, max, false, options);
30480 while (descending ? a >= b : a <= b) {
30481 range.push(format(a, index));
30482 a = descending ? a - step : a + step;
30486 if (options.toRegex === true) {
30487 return toRegex(range, null, {
30496 const fill$2 = (start, end, step, options = {}) => {
30497 if (end == null && isValidValue(start)) {
30501 if (!isValidValue(start) || !isValidValue(end)) {
30502 return invalidRange(start, end, options);
30505 if (typeof step === 'function') {
30506 return fill$2(start, end, 1, {
30511 if (isObject$1(step)) {
30512 return fill$2(start, end, 0, step);
30515 let opts = Object.assign({}, options);
30516 if (opts.capture === true) opts.wrap = true;
30517 step = step || opts.step || 1;
30519 if (!isNumber$1(step)) {
30520 if (step != null && !isObject$1(step)) return invalidStep(step, opts);
30521 return fill$2(start, end, 1, step);
30524 if (isNumber$1(start) && isNumber$1(end)) {
30525 return fillNumbers(start, end, step, opts);
30528 return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
30531 var fillRange = fill$2;
30533 const compile = (ast, options = {}) => {
30534 let walk = (node, parent = {}) => {
30535 let invalidBlock = utils$1.isInvalidBrace(parent);
30536 let invalidNode = node.invalid === true && options.escapeInvalid === true;
30537 let invalid = invalidBlock === true || invalidNode === true;
30538 let prefix = options.escapeInvalid === true ? '\\' : '';
30541 if (node.isOpen === true) {
30542 return prefix + node.value;
30545 if (node.isClose === true) {
30546 return prefix + node.value;
30549 if (node.type === 'open') {
30550 return invalid ? prefix + node.value : '(';
30553 if (node.type === 'close') {
30554 return invalid ? prefix + node.value : ')';
30557 if (node.type === 'comma') {
30558 return node.prev.type === 'comma' ? '' : invalid ? node.value : '|';
30565 if (node.nodes && node.ranges > 0) {
30566 let args = utils$1.reduce(node.nodes);
30567 let range = fillRange(...args, Object.assign({}, options, {
30572 if (range.length !== 0) {
30573 return args.length > 1 && range.length > 1 ? `(${range})` : range;
30578 for (let child of node.nodes) {
30579 output += walk(child, node);
30589 var compile_1 = compile;
30591 const append = (queue = '', stash = '', enclose = false) => {
30593 queue = [].concat(queue);
30594 stash = [].concat(stash);
30595 if (!stash.length) return queue;
30597 if (!queue.length) {
30598 return enclose ? utils$1.flatten(stash).map(ele => `{${ele}}`) : stash;
30601 for (let item of queue) {
30602 if (Array.isArray(item)) {
30603 for (let value of item) {
30604 result.push(append(value, stash, enclose));
30607 for (let ele of stash) {
30608 if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
30609 result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
30614 return utils$1.flatten(result);
30617 const expand$1 = (ast, options = {}) => {
30618 let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
30620 let walk = (node, parent = {}) => {
30623 let q = parent.queue;
30625 while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
30630 if (node.invalid || node.dollar) {
30631 q.push(append(q.pop(), stringify$1(node, options)));
30635 if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
30636 q.push(append(q.pop(), ['{}']));
30640 if (node.nodes && node.ranges > 0) {
30641 let args = utils$1.reduce(node.nodes);
30643 if (utils$1.exceedsLimit(...args, options.step, rangeLimit)) {
30644 throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
30647 let range = fillRange(...args, options);
30649 if (range.length === 0) {
30650 range = stringify$1(node, options);
30653 q.push(append(q.pop(), range));
30658 let enclose = utils$1.encloseBrace(node);
30659 let queue = node.queue;
30662 while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
30663 block = block.parent;
30664 queue = block.queue;
30667 for (let i = 0; i < node.nodes.length; i++) {
30668 let child = node.nodes[i];
30670 if (child.type === 'comma' && node.type === 'brace') {
30671 if (i === 1) queue.push('');
30676 if (child.type === 'close') {
30677 q.push(append(q.pop(), queue, enclose));
30681 if (child.value && child.type !== 'open') {
30682 queue.push(append(queue.pop(), child.value));
30694 return utils$1.flatten(walk(ast));
30697 var expand_1 = expand$1;
30699 var constants$3 = {
30700 MAX_LENGTH: 1024 * 64,
30709 CHAR_UPPERCASE_A: 'A',
30712 CHAR_LOWERCASE_A: 'a',
30715 CHAR_UPPERCASE_Z: 'Z',
30718 CHAR_LOWERCASE_Z: 'z',
30721 CHAR_LEFT_PARENTHESES: '(',
30724 CHAR_RIGHT_PARENTHESES: ')',
30727 CHAR_ASTERISK: '*',
30730 // Non-alphabetic chars.
30731 CHAR_AMPERSAND: '&',
30737 CHAR_BACKSLASH: '\\',
30740 CHAR_BACKTICK: '`',
30743 CHAR_CARRIAGE_RETURN: '\r',
30746 CHAR_CIRCUMFLEX_ACCENT: '^',
30761 CHAR_DOUBLE_QUOTE: '"',
30767 CHAR_EXCLAMATION_MARK: '!',
30770 CHAR_FORM_FEED: '\f',
30773 CHAR_FORWARD_SLASH: '/',
30779 CHAR_HYPHEN_MINUS: '-',
30782 CHAR_LEFT_ANGLE_BRACKET: '<',
30785 CHAR_LEFT_CURLY_BRACE: '{',
30788 CHAR_LEFT_SQUARE_BRACKET: '[',
30791 CHAR_LINE_FEED: '\n',
30794 CHAR_NO_BREAK_SPACE: '\u00A0',
30803 CHAR_QUESTION_MARK: '?',
30806 CHAR_RIGHT_ANGLE_BRACKET: '>',
30809 CHAR_RIGHT_CURLY_BRACE: '}',
30812 CHAR_RIGHT_SQUARE_BRACKET: ']',
30815 CHAR_SEMICOLON: ';',
30818 CHAR_SINGLE_QUOTE: '\'',
30827 CHAR_UNDERSCORE: '_',
30830 CHAR_VERTICAL_LINE: '|',
30833 CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF'
30844 MAX_LENGTH: MAX_LENGTH$2,
30851 CHAR_COMMA: CHAR_COMMA$1,
30857 CHAR_LEFT_PARENTHESES,
30860 CHAR_RIGHT_PARENTHESES,
30863 CHAR_LEFT_CURLY_BRACE,
30866 CHAR_RIGHT_CURLY_BRACE,
30869 CHAR_LEFT_SQUARE_BRACKET,
30872 CHAR_RIGHT_SQUARE_BRACKET,
30881 CHAR_NO_BREAK_SPACE,
30882 CHAR_ZERO_WIDTH_NOBREAK_SPACE
30888 const parse$5 = (input, options = {}) => {
30889 if (typeof input !== 'string') {
30890 throw new TypeError('Expected a string');
30893 let opts = options || {};
30894 let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$2, opts.maxLength) : MAX_LENGTH$2;
30896 if (input.length > max) {
30897 throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
30909 let length = input.length;
30917 const advance = () => input[index++];
30919 const push = node => {
30920 if (node.type === 'text' && prev.type === 'dot') {
30921 prev.type = 'text';
30924 if (prev && prev.type === 'text' && node.type === 'text') {
30925 prev.value += node.value;
30929 block.nodes.push(node);
30930 node.parent = block;
30940 while (index < length) {
30941 block = stack[stack.length - 1];
30947 if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
30955 if (value === CHAR_BACKSLASH) {
30958 value: (options.keepEscaping ? value : '') + advance()
30963 * Right square bracket (literal): ']'
30967 if (value === CHAR_RIGHT_SQUARE_BRACKET) {
30970 value: '\\' + value
30975 * Left square bracket: '['
30979 if (value === CHAR_LEFT_SQUARE_BRACKET) {
30983 while (index < length && (next = advance())) {
30986 if (next === CHAR_LEFT_SQUARE_BRACKET) {
30991 if (next === CHAR_BACKSLASH) {
30992 value += advance();
30996 if (next === CHAR_RIGHT_SQUARE_BRACKET) {
30999 if (brackets === 0) {
31016 if (value === CHAR_LEFT_PARENTHESES) {
31029 if (value === CHAR_RIGHT_PARENTHESES) {
31030 if (block.type !== 'paren') {
31038 block = stack.pop();
31043 block = stack[stack.length - 1];
31051 if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
31055 if (options.keepQuotes !== true) {
31059 while (index < length && (next = advance())) {
31060 if (next === CHAR_BACKSLASH) {
31061 value += next + advance();
31065 if (next === open) {
31066 if (options.keepQuotes === true) value += next;
31080 * Left curly brace: '{'
31084 if (value === CHAR_LEFT_CURLY_BRACE) {
31086 let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
31097 block = push(brace);
31106 * Right curly brace: '}'
31110 if (value === CHAR_RIGHT_CURLY_BRACE) {
31111 if (block.type !== 'brace') {
31119 let type = 'close';
31120 block = stack.pop();
31121 block.close = true;
31127 block = stack[stack.length - 1];
31135 if (value === CHAR_COMMA$1 && depth > 0) {
31136 if (block.ranges > 0) {
31138 let open = block.nodes.shift();
31139 block.nodes = [open, {
31141 value: stringify$1(block)
31157 if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
31158 let siblings = block.nodes;
31160 if (depth === 0 || siblings.length === 0) {
31168 if (prev.type === 'dot') {
31170 prev.value += value;
31171 prev.type = 'range';
31173 if (block.nodes.length !== 3 && block.nodes.length !== 5) {
31174 block.invalid = true;
31176 prev.type = 'text';
31185 if (prev.type === 'range') {
31187 let before = siblings[siblings.length - 1];
31188 before.value += prev.value + value;
31209 } // Mark imbalanced braces and brackets as invalid
31213 block = stack.pop();
31215 if (block.type !== 'root') {
31216 block.nodes.forEach(node => {
31218 if (node.type === 'open') node.isOpen = true;
31219 if (node.type === 'close') node.isClose = true;
31220 if (!node.nodes) node.type = 'text';
31221 node.invalid = true;
31223 }); // get the location of the block on parent.nodes (block's siblings)
31225 let parent = stack[stack.length - 1];
31226 let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes
31228 parent.nodes.splice(index, 1, ...block.nodes);
31230 } while (stack.length > 0);
31238 var parse_1 = parse$5;
31241 * Expand the given pattern or create a regex-compatible string.
31244 * const braces = require('braces');
31245 * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
31246 * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
31248 * @param {String} `str`
31249 * @param {Object} `options`
31255 const braces = (input, options = {}) => {
31258 if (Array.isArray(input)) {
31259 for (let pattern of input) {
31260 let result = braces.create(pattern, options);
31262 if (Array.isArray(result)) {
31263 output.push(...result);
31265 output.push(result);
31269 output = [].concat(braces.create(input, options));
31272 if (options && options.expand === true && options.nodupes === true) {
31273 output = [...new Set(output)];
31279 * Parse the given `str` with the given `options`.
31282 * // braces.parse(pattern, [, options]);
31283 * const ast = braces.parse('a/{b,c}/d');
31284 * console.log(ast);
31286 * @param {String} pattern Brace pattern to parse
31287 * @param {Object} options
31288 * @return {Object} Returns an AST
31293 braces.parse = (input, options = {}) => parse_1(input, options);
31295 * Creates a braces string from an AST, or an AST node.
31298 * const braces = require('braces');
31299 * let ast = braces.parse('foo/{a,b}/bar');
31300 * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
31302 * @param {String} `input` Brace pattern or AST.
31303 * @param {Object} `options`
31304 * @return {Array} Returns an array of expanded values.
31309 braces.stringify = (input, options = {}) => {
31310 if (typeof input === 'string') {
31311 return stringify$1(braces.parse(input, options), options);
31314 return stringify$1(input, options);
31317 * Compiles a brace pattern into a regex-compatible, optimized string.
31318 * This method is called by the main [braces](#braces) function by default.
31321 * const braces = require('braces');
31322 * console.log(braces.compile('a/{b,c}/d'));
31323 * //=> ['a/(b|c)/d']
31325 * @param {String} `input` Brace pattern or AST.
31326 * @param {Object} `options`
31327 * @return {Array} Returns an array of expanded values.
31332 braces.compile = (input, options = {}) => {
31333 if (typeof input === 'string') {
31334 input = braces.parse(input, options);
31337 return compile_1(input, options);
31340 * Expands a brace pattern into an array. This method is called by the
31341 * main [braces](#braces) function when `options.expand` is true. Before
31342 * using this method it's recommended that you read the [performance notes](#performance))
31343 * and advantages of using [.compile](#compile) instead.
31346 * const braces = require('braces');
31347 * console.log(braces.expand('a/{b,c}/d'));
31348 * //=> ['a/b/d', 'a/c/d'];
31350 * @param {String} `pattern` Brace pattern
31351 * @param {Object} `options`
31352 * @return {Array} Returns an array of expanded values.
31357 braces.expand = (input, options = {}) => {
31358 if (typeof input === 'string') {
31359 input = braces.parse(input, options);
31362 let result = expand_1(input, options); // filter out empty strings if specified
31364 if (options.noempty === true) {
31365 result = result.filter(Boolean);
31366 } // filter out duplicates if specified
31369 if (options.nodupes === true) {
31370 result = [...new Set(result)];
31376 * Processes a brace pattern and returns either an expanded array
31377 * (if `options.expand` is true), a highly optimized regex-compatible string.
31378 * This method is called by the main [braces](#braces) function.
31381 * const braces = require('braces');
31382 * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
31383 * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
31385 * @param {String} `pattern` Brace pattern
31386 * @param {Object} `options`
31387 * @return {Array} Returns an array of expanded values.
31392 braces.create = (input, options = {}) => {
31393 if (input === '' || input.length < 3) {
31397 return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options);
31404 var braces_1 = braces;
31406 const WIN_SLASH = '\\\\/';
31407 const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
31412 const DOT_LITERAL = '\\.';
31413 const PLUS_LITERAL = '\\+';
31414 const QMARK_LITERAL = '\\?';
31415 const SLASH_LITERAL = '\\/';
31416 const ONE_CHAR = '(?=.)';
31417 const QMARK = '[^/]';
31418 const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
31419 const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
31420 const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
31421 const NO_DOT = `(?!${DOT_LITERAL})`;
31422 const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
31423 const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
31424 const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
31425 const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
31426 const STAR = `${QMARK}*?`;
31427 const POSIX_CHARS = {
31445 * Windows glob regex
31448 const WINDOWS_CHARS = Object.assign({}, POSIX_CHARS, {
31449 SLASH_LITERAL: `[${WIN_SLASH}]`,
31450 QMARK: WIN_NO_SLASH,
31451 STAR: `${WIN_NO_SLASH}*?`,
31452 DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
31453 NO_DOT: `(?!${DOT_LITERAL})`,
31454 NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
31455 NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
31456 NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
31457 QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
31458 START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
31459 END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
31462 * POSIX Bracket Regex
31465 const POSIX_REGEX_SOURCE = {
31466 alnum: 'a-zA-Z0-9',
31468 ascii: '\\x00-\\x7F',
31470 cntrl: '\\x00-\\x1F\\x7F',
31472 graph: '\\x21-\\x7E',
31474 print: '\\x20-\\x7E ',
31475 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
31476 space: ' \\t\\r\\n\\v\\f',
31478 word: 'A-Za-z0-9_',
31479 xdigit: 'A-Fa-f0-9'
31481 var constants$4 = {
31482 MAX_LENGTH: 1024 * 64,
31483 POSIX_REGEX_SOURCE,
31484 // regular expressions
31485 REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
31486 REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
31487 REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
31488 REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
31489 REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
31490 REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
31491 // Replace globs with equivalent patterns to reduce parsing time.
31505 CHAR_UPPERCASE_A: 65,
31508 CHAR_LOWERCASE_A: 97,
31511 CHAR_UPPERCASE_Z: 90,
31514 CHAR_LOWERCASE_Z: 122,
31517 CHAR_LEFT_PARENTHESES: 40,
31520 CHAR_RIGHT_PARENTHESES: 41,
31526 // Non-alphabetic chars.
31527 CHAR_AMPERSAND: 38,
31533 CHAR_BACKWARD_SLASH: 92,
31536 CHAR_CARRIAGE_RETURN: 13,
31539 CHAR_CIRCUMFLEX_ACCENT: 94,
31551 CHAR_DOUBLE_QUOTE: 34,
31557 CHAR_EXCLAMATION_MARK: 33,
31560 CHAR_FORM_FEED: 12,
31563 CHAR_FORWARD_SLASH: 47,
31566 CHAR_GRAVE_ACCENT: 96,
31572 CHAR_HYPHEN_MINUS: 45,
31575 CHAR_LEFT_ANGLE_BRACKET: 60,
31578 CHAR_LEFT_CURLY_BRACE: 123,
31581 CHAR_LEFT_SQUARE_BRACKET: 91,
31584 CHAR_LINE_FEED: 10,
31587 CHAR_NO_BREAK_SPACE: 160,
31596 CHAR_QUESTION_MARK: 63,
31599 CHAR_RIGHT_ANGLE_BRACKET: 62,
31602 CHAR_RIGHT_CURLY_BRACE: 125,
31605 CHAR_RIGHT_SQUARE_BRACKET: 93,
31608 CHAR_SEMICOLON: 59,
31611 CHAR_SINGLE_QUOTE: 39,
31620 CHAR_UNDERSCORE: 95,
31623 CHAR_VERTICAL_LINE: 124,
31626 CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
31629 SEP: path__default['default'].sep,
31632 * Create EXTGLOB_CHARS
31634 extglobChars(chars) {
31639 close: `))${chars.STAR})`
31665 * Create GLOB_CHARS
31668 return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
31673 var utils$2 = createCommonjsModule(function (module, exports) {
31675 const win32 = process.platform === 'win32';
31678 REGEX_REMOVE_BACKSLASH,
31679 REGEX_SPECIAL_CHARS,
31680 REGEX_SPECIAL_CHARS_GLOBAL
31683 exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
31685 exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
31687 exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
31689 exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
31691 exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
31693 exports.removeBackslashes = str => {
31694 return str.replace(REGEX_REMOVE_BACKSLASH, match => {
31695 return match === '\\' ? '' : match;
31699 exports.supportsLookbehinds = () => {
31700 const segs = process.version.slice(1).split('.').map(Number);
31702 if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) {
31709 exports.isWindows = options => {
31710 if (options && typeof options.windows === 'boolean') {
31711 return options.windows;
31714 return win32 === true || path__default['default'].sep === '\\';
31717 exports.escapeLast = (input, char, lastIdx) => {
31718 const idx = input.lastIndexOf(char, lastIdx);
31719 if (idx === -1) return input;
31720 if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
31721 return `${input.slice(0, idx)}\\${input.slice(idx)}`;
31724 exports.removePrefix = (input, state = {}) => {
31725 let output = input;
31727 if (output.startsWith('./')) {
31728 output = output.slice(2);
31729 state.prefix = './';
31735 exports.wrapOutput = (input, state = {}, options = {}) => {
31736 const prepend = options.contains ? '' : '^';
31737 const append = options.contains ? '' : '$';
31738 let output = `${prepend}(?:${input})${append}`;
31740 if (state.negated === true) {
31741 output = `(?:^(?!${output}).*$)`;
31755 CHAR_BACKWARD_SLASH,
31758 CHAR_COMMA: CHAR_COMMA$2,
31761 CHAR_DOT: CHAR_DOT$1,
31764 CHAR_EXCLAMATION_MARK,
31767 CHAR_FORWARD_SLASH,
31770 CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1,
31773 CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1,
31776 CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1,
31779 CHAR_PLUS: CHAR_PLUS$1,
31782 CHAR_QUESTION_MARK,
31785 CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1,
31788 CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1,
31791 CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1
31796 const isPathSeparator = code => {
31797 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
31800 const depth = token => {
31801 if (token.isPrefix !== true) {
31802 token.depth = token.isGlobstar ? Infinity : 1;
31806 * Quickly scans a glob pattern and returns an object with a handful of
31807 * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
31808 * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
31811 * const pm = require('picomatch');
31812 * console.log(pm.scan('foo/bar/*.js'));
31813 * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
31815 * @param {String} `str`
31816 * @param {Object} `options`
31817 * @return {Object} Returns an object with tokens and regex source string.
31822 const scan = (input, options) => {
31823 const opts = options || {};
31824 const length = input.length - 1;
31825 const scanToEnd = opts.parts === true || opts.scanToEnd === true;
31826 const slashes = [];
31833 let isBrace = false;
31834 let isBracket = false;
31835 let isGlob = false;
31836 let isExtglob = false;
31837 let isGlobstar = false;
31838 let braceEscaped = false;
31839 let backslashes = false;
31840 let negated = false;
31841 let finished = false;
31851 const eos = () => index >= length;
31853 const peek = () => str.charCodeAt(index + 1);
31855 const advance = () => {
31857 return str.charCodeAt(++index);
31860 while (index < length) {
31864 if (code === CHAR_BACKWARD_SLASH) {
31865 backslashes = token.backslashes = true;
31868 if (code === CHAR_LEFT_CURLY_BRACE$1) {
31869 braceEscaped = true;
31875 if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
31878 while (eos() !== true && (code = advance())) {
31879 if (code === CHAR_BACKWARD_SLASH) {
31880 backslashes = token.backslashes = true;
31885 if (code === CHAR_LEFT_CURLY_BRACE$1) {
31890 if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {
31891 isBrace = token.isBrace = true;
31892 isGlob = token.isGlob = true;
31895 if (scanToEnd === true) {
31902 if (braceEscaped !== true && code === CHAR_COMMA$2) {
31903 isBrace = token.isBrace = true;
31904 isGlob = token.isGlob = true;
31907 if (scanToEnd === true) {
31914 if (code === CHAR_RIGHT_CURLY_BRACE$1) {
31917 if (braces === 0) {
31918 braceEscaped = false;
31919 isBrace = token.isBrace = true;
31926 if (scanToEnd === true) {
31933 if (code === CHAR_FORWARD_SLASH) {
31934 slashes.push(index);
31935 tokens.push(token);
31941 if (finished === true) continue;
31943 if (prev === CHAR_DOT$1 && index === start + 1) {
31948 lastIndex = index + 1;
31952 if (opts.noext !== true) {
31953 const isExtglobChar = code === CHAR_PLUS$1 || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
31955 if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {
31956 isGlob = token.isGlob = true;
31957 isExtglob = token.isExtglob = true;
31960 if (scanToEnd === true) {
31961 while (eos() !== true && (code = advance())) {
31962 if (code === CHAR_BACKWARD_SLASH) {
31963 backslashes = token.backslashes = true;
31968 if (code === CHAR_RIGHT_PARENTHESES$1) {
31969 isGlob = token.isGlob = true;
31982 if (code === CHAR_ASTERISK) {
31983 if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
31984 isGlob = token.isGlob = true;
31987 if (scanToEnd === true) {
31994 if (code === CHAR_QUESTION_MARK) {
31995 isGlob = token.isGlob = true;
31998 if (scanToEnd === true) {
32005 if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
32006 while (eos() !== true && (next = advance())) {
32007 if (next === CHAR_BACKWARD_SLASH) {
32008 backslashes = token.backslashes = true;
32013 if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
32014 isBracket = token.isBracket = true;
32015 isGlob = token.isGlob = true;
32018 if (scanToEnd === true) {
32027 if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
32028 negated = token.negated = true;
32033 if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {
32034 isGlob = token.isGlob = true;
32036 if (scanToEnd === true) {
32037 while (eos() !== true && (code = advance())) {
32038 if (code === CHAR_LEFT_PARENTHESES$1) {
32039 backslashes = token.backslashes = true;
32044 if (code === CHAR_RIGHT_PARENTHESES$1) {
32056 if (isGlob === true) {
32059 if (scanToEnd === true) {
32067 if (opts.noext === true) {
32077 prefix = str.slice(0, start);
32078 str = str.slice(start);
32079 lastIndex -= start;
32082 if (base && isGlob === true && lastIndex > 0) {
32083 base = str.slice(0, lastIndex);
32084 glob = str.slice(lastIndex);
32085 } else if (isGlob === true) {
32092 if (base && base !== '' && base !== '/' && base !== str) {
32093 if (isPathSeparator(base.charCodeAt(base.length - 1))) {
32094 base = base.slice(0, -1);
32098 if (opts.unescape === true) {
32099 if (glob) glob = utils$2.removeBackslashes(glob);
32101 if (base && backslashes === true) {
32102 base = utils$2.removeBackslashes(base);
32120 if (opts.tokens === true) {
32121 state.maxDepth = 0;
32123 if (!isPathSeparator(code)) {
32124 tokens.push(token);
32127 state.tokens = tokens;
32130 if (opts.parts === true || opts.tokens === true) {
32133 for (let idx = 0; idx < slashes.length; idx++) {
32134 const n = prevIndex ? prevIndex + 1 : start;
32135 const i = slashes[idx];
32136 const value = input.slice(n, i);
32139 if (idx === 0 && start !== 0) {
32140 tokens[idx].isPrefix = true;
32141 tokens[idx].value = prefix;
32143 tokens[idx].value = value;
32146 depth(tokens[idx]);
32147 state.maxDepth += tokens[idx].depth;
32150 if (idx !== 0 || value !== '') {
32157 if (prevIndex && prevIndex + 1 < input.length) {
32158 const value = input.slice(prevIndex + 1);
32162 tokens[tokens.length - 1].value = value;
32163 depth(tokens[tokens.length - 1]);
32164 state.maxDepth += tokens[tokens.length - 1].depth;
32168 state.slashes = slashes;
32169 state.parts = parts;
32183 MAX_LENGTH: MAX_LENGTH$3,
32184 POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
32185 REGEX_NON_SPECIAL_CHARS,
32186 REGEX_SPECIAL_CHARS_BACKREF,
32193 const expandRange = (args, options) => {
32194 if (typeof options.expandRange === 'function') {
32195 return options.expandRange(...args, options);
32199 const value = `[${args.join('-')}]`;
32202 /* eslint-disable-next-line no-new */
32205 return args.map(v => utils$2.escapeRegex(v)).join('..');
32211 * Create the message for a syntax error
32215 const syntaxError$1 = (type, char) => {
32216 return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
32219 * Parse the given input string.
32220 * @param {String} input
32221 * @param {Object} options
32226 const parse$6 = (input, options) => {
32227 if (typeof input !== 'string') {
32228 throw new TypeError('Expected a string');
32231 input = REPLACEMENTS[input] || input;
32232 const opts = Object.assign({}, options);
32233 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$3, opts.maxLength) : MAX_LENGTH$3;
32234 let len = input.length;
32237 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
32243 output: opts.prepend || ''
32245 const tokens = [bos];
32246 const capture = opts.capture ? '' : '?:';
32247 const win32 = utils$2.isWindows(options); // create constants based on platform, for windows or posix
32249 const PLATFORM_CHARS = constants$4.globChars(win32);
32250 const EXTGLOB_CHARS = constants$4.extglobChars(PLATFORM_CHARS);
32264 } = PLATFORM_CHARS;
32266 const globstar = opts => {
32267 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
32270 const nodot = opts.dot ? '' : NO_DOT;
32271 const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
32272 let star = opts.bash === true ? globstar(opts) : STAR;
32274 if (opts.capture) {
32275 star = `(${star})`;
32276 } // minimatch options support
32279 if (typeof opts.noext === 'boolean') {
32280 opts.noextglob = opts.noext;
32287 dot: opts.dot === true,
32300 input = utils$2.removePrefix(input, state);
32301 len = input.length;
32302 const extglobs = [];
32308 * Tokenizing helpers
32311 const eos = () => state.index === len - 1;
32313 const peek = state.peek = (n = 1) => input[state.index + n];
32315 const advance = state.advance = () => input[++state.index];
32317 const remaining = () => input.slice(state.index + 1);
32319 const consume = (value = '', num = 0) => {
32320 state.consumed += value;
32321 state.index += num;
32324 const append = token => {
32325 state.output += token.output != null ? token.output : token.value;
32326 consume(token.value);
32329 const negate = () => {
32332 while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
32338 if (count % 2 === 0) {
32342 state.negated = true;
32347 const increment = type => {
32352 const decrement = type => {
32357 * Push tokens onto the tokens array. This helper speeds up
32358 * tokenizing by 1) helping us avoid backtracking as much as possible,
32359 * and 2) helping us avoid creating extra tokens when consecutive
32360 * characters are plain text. This improves performance and simplifies
32365 const push = tok => {
32366 if (prev.type === 'globstar') {
32367 const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
32368 const isExtglob = tok.extglob === true || extglobs.length && (tok.type === 'pipe' || tok.type === 'paren');
32370 if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
32371 state.output = state.output.slice(0, -prev.output.length);
32372 prev.type = 'star';
32374 prev.output = star;
32375 state.output += prev.output;
32379 if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
32380 extglobs[extglobs.length - 1].inner += tok.value;
32383 if (tok.value || tok.output) append(tok);
32385 if (prev && prev.type === 'text' && tok.type === 'text') {
32386 prev.value += tok.value;
32387 prev.output = (prev.output || '') + tok.value;
32396 const extglobOpen = (type, value) => {
32397 const token = Object.assign({}, EXTGLOB_CHARS[value], {
32402 token.parens = state.parens;
32403 token.output = state.output;
32404 const output = (opts.capture ? '(' : '') + token.open;
32405 increment('parens');
32409 output: state.output ? '' : ONE_CHAR
32417 extglobs.push(token);
32420 const extglobClose = token => {
32421 let output = token.close + (opts.capture ? ')' : '');
32423 if (token.type === 'negate') {
32424 let extglobStar = star;
32426 if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
32427 extglobStar = globstar(opts);
32430 if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
32431 output = token.close = `)$))${extglobStar}`;
32434 if (token.prev.type === 'bos' && eos()) {
32435 state.negatedExtglob = true;
32445 decrement('parens');
32452 if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
32453 let backslashes = false;
32454 let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
32455 if (first === '\\') {
32456 backslashes = true;
32460 if (first === '?') {
32462 return esc + first + (rest ? QMARK.repeat(rest.length) : '');
32466 return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
32469 return QMARK.repeat(chars.length);
32472 if (first === '.') {
32473 return DOT_LITERAL.repeat(chars.length);
32476 if (first === '*') {
32478 return esc + first + (rest ? star : '');
32484 return esc ? m : `\\${m}`;
32487 if (backslashes === true) {
32488 if (opts.unescape === true) {
32489 output = output.replace(/\\/g, '');
32491 output = output.replace(/\\+/g, m => {
32492 return m.length % 2 === 0 ? '\\\\' : m ? '\\' : '';
32497 if (output === input && opts.contains === true) {
32498 state.output = input;
32502 state.output = utils$2.wrapOutput(output, state, options);
32506 * Tokenize input until we reach end-of-string
32513 if (value === '\u0000') {
32517 * Escaped characters
32521 if (value === '\\') {
32522 const next = peek();
32524 if (next === '/' && opts.bash !== true) {
32528 if (next === '.' || next === ';') {
32539 } // collapse slashes to reduce potential for exploits
32542 const match = /^\\+/.exec(remaining());
32545 if (match && match[0].length > 2) {
32546 slashes = match[0].length;
32547 state.index += slashes;
32549 if (slashes % 2 !== 0) {
32554 if (opts.unescape === true) {
32555 value = advance() || '';
32557 value += advance() || '';
32560 if (state.brackets === 0) {
32569 * If we're inside a regex character class, continue
32570 * until we reach the closing bracket.
32574 if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
32575 if (opts.posix !== false && value === ':') {
32576 const inner = prev.value.slice(1);
32578 if (inner.includes('[')) {
32581 if (inner.includes(':')) {
32582 const idx = prev.value.lastIndexOf('[');
32583 const pre = prev.value.slice(0, idx);
32584 const rest = prev.value.slice(idx + 2);
32585 const posix = POSIX_REGEX_SOURCE$1[rest];
32588 prev.value = pre + posix;
32589 state.backtrack = true;
32592 if (!bos.output && tokens.indexOf(prev) === 1) {
32593 bos.output = ONE_CHAR;
32602 if (value === '[' && peek() !== ':' || value === '-' && peek() === ']') {
32603 value = `\\${value}`;
32606 if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
32607 value = `\\${value}`;
32610 if (opts.posix === true && value === '!' && prev.value === '[') {
32614 prev.value += value;
32621 * If we're inside a quoted string, continue
32622 * until we reach the closing double quote.
32626 if (state.quotes === 1 && value !== '"') {
32627 value = utils$2.escapeRegex(value);
32628 prev.value += value;
32639 if (value === '"') {
32640 state.quotes = state.quotes === 1 ? 0 : 1;
32642 if (opts.keepQuotes === true) {
32656 if (value === '(') {
32657 increment('parens');
32665 if (value === ')') {
32666 if (state.parens === 0 && opts.strictBrackets === true) {
32667 throw new SyntaxError(syntaxError$1('opening', '('));
32670 const extglob = extglobs[extglobs.length - 1];
32672 if (extglob && state.parens === extglob.parens + 1) {
32673 extglobClose(extglobs.pop());
32680 output: state.parens ? ')' : '\\)'
32682 decrement('parens');
32690 if (value === '[') {
32691 if (opts.nobracket === true || !remaining().includes(']')) {
32692 if (opts.nobracket !== true && opts.strictBrackets === true) {
32693 throw new SyntaxError(syntaxError$1('closing', ']'));
32696 value = `\\${value}`;
32698 increment('brackets');
32708 if (value === ']') {
32709 if (opts.nobracket === true || prev && prev.type === 'bracket' && prev.value.length === 1) {
32713 output: `\\${value}`
32718 if (state.brackets === 0) {
32719 if (opts.strictBrackets === true) {
32720 throw new SyntaxError(syntaxError$1('opening', '['));
32726 output: `\\${value}`
32731 decrement('brackets');
32732 const prevValue = prev.value.slice(1);
32734 if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
32735 value = `/${value}`;
32738 prev.value += value;
32741 }); // when literal brackets are explicitly disabled
32742 // assume we should match with a regex character class
32744 if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) {
32748 const escaped = utils$2.escapeRegex(prev.value);
32749 state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled
32750 // assume we should escape the brackets to match literal characters
32752 if (opts.literalBrackets === true) {
32753 state.output += escaped;
32754 prev.value = escaped;
32756 } // when the user specifies nothing, try to match both
32759 prev.value = `(${capture}${escaped}|${prev.value})`;
32760 state.output += prev.value;
32768 if (value === '{' && opts.nobrace !== true) {
32769 increment('braces');
32774 outputIndex: state.output.length,
32775 tokensIndex: state.tokens.length
32782 if (value === '}') {
32783 const brace = braces[braces.length - 1];
32785 if (opts.nobrace === true || !brace) {
32796 if (brace.dots === true) {
32797 const arr = tokens.slice();
32800 for (let i = arr.length - 1; i >= 0; i--) {
32803 if (arr[i].type === 'brace') {
32807 if (arr[i].type !== 'dots') {
32808 range.unshift(arr[i].value);
32812 output = expandRange(range, opts);
32813 state.backtrack = true;
32816 if (brace.comma !== true && brace.dots !== true) {
32817 const out = state.output.slice(0, brace.outputIndex);
32818 const toks = state.tokens.slice(brace.tokensIndex);
32819 brace.value = brace.output = '\\{';
32820 value = output = '\\}';
32821 state.output = out;
32823 for (const t of toks) {
32824 state.output += t.output || t.value;
32833 decrement('braces');
32842 if (value === '|') {
32843 if (extglobs.length > 0) {
32844 extglobs[extglobs.length - 1].conditions++;
32858 if (value === ',') {
32859 let output = value;
32860 const brace = braces[braces.length - 1];
32862 if (brace && stack[stack.length - 1] === 'braces') {
32863 brace.comma = true;
32879 if (value === '/') {
32880 // if the beginning of the glob is "./", advance the start
32881 // to the current index, and don't add the "./" characters
32882 // to the state. This greatly simplifies lookbehinds when
32883 // checking for BOS characters like "!" and "." (not "./")
32884 if (prev.type === 'dot' && state.index === state.start + 1) {
32885 state.start = state.index + 1;
32886 state.consumed = '';
32889 prev = bos; // reset "prev" to the first token
32897 output: SLASH_LITERAL
32906 if (value === '.') {
32907 if (state.braces > 0 && prev.type === 'dot') {
32908 if (prev.value === '.') prev.output = DOT_LITERAL;
32909 const brace = braces[braces.length - 1];
32910 prev.type = 'dots';
32911 prev.output += value;
32912 prev.value += value;
32917 if (state.braces + state.parens === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
32921 output: DOT_LITERAL
32929 output: DOT_LITERAL
32938 if (value === '?') {
32939 const isGroup = prev && prev.value === '(';
32941 if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
32942 extglobOpen('qmark', value);
32946 if (prev && prev.type === 'paren') {
32947 const next = peek();
32948 let output = value;
32950 if (next === '<' && !utils$2.supportsLookbehinds()) {
32951 throw new Error('Node.js v10 or higher is required for regex lookbehinds');
32954 if (prev.value === '(' && !/[!=<:]/.test(next) || next === '<' && !/<([!=]|\w+>)/.test(remaining())) {
32955 output = `\\${value}`;
32966 if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
32970 output: QMARK_NO_DOT
32987 if (value === '!') {
32988 if (opts.noextglob !== true && peek() === '(') {
32989 if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
32990 extglobOpen('negate', value);
32995 if (opts.nonegate !== true && state.index === 0) {
33005 if (value === '+') {
33006 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
33007 extglobOpen('plus', value);
33011 if (prev && prev.value === '(' || opts.regex === false) {
33015 output: PLUS_LITERAL
33020 if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace') || state.parens > 0) {
33030 value: PLUS_LITERAL
33039 if (value === '@') {
33040 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
33061 if (value !== '*') {
33062 if (value === '$' || value === '^') {
33063 value = `\\${value}`;
33066 const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
33070 state.index += match[0].length;
33084 if (prev && (prev.type === 'globstar' || prev.star === true)) {
33085 prev.type = 'star';
33087 prev.value += value;
33088 prev.output = star;
33089 state.backtrack = true;
33090 state.globstar = true;
33095 let rest = remaining();
33097 if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
33098 extglobOpen('star', value);
33102 if (prev.type === 'star') {
33103 if (opts.noglobstar === true) {
33108 const prior = prev.prev;
33109 const before = prior.prev;
33110 const isStart = prior.type === 'slash' || prior.type === 'bos';
33111 const afterStar = before && (before.type === 'star' || before.type === 'globstar');
33113 if (opts.bash === true && (!isStart || rest[0] && rest[0] !== '/')) {
33122 const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
33123 const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
33125 if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
33132 } // strip consecutive `/**/`
33135 while (rest.slice(0, 3) === '/**') {
33136 const after = input[state.index + 4];
33138 if (after && after !== '/') {
33142 rest = rest.slice(3);
33146 if (prior.type === 'bos' && eos()) {
33147 prev.type = 'globstar';
33148 prev.value += value;
33149 prev.output = globstar(opts);
33150 state.output = prev.output;
33151 state.globstar = true;
33156 if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
33157 state.output = state.output.slice(0, -(prior.output + prev.output).length);
33158 prior.output = `(?:${prior.output}`;
33159 prev.type = 'globstar';
33160 prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
33161 prev.value += value;
33162 state.globstar = true;
33163 state.output += prior.output + prev.output;
33168 if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
33169 const end = rest[1] !== void 0 ? '|$' : '';
33170 state.output = state.output.slice(0, -(prior.output + prev.output).length);
33171 prior.output = `(?:${prior.output}`;
33172 prev.type = 'globstar';
33173 prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
33174 prev.value += value;
33175 state.output += prior.output + prev.output;
33176 state.globstar = true;
33177 consume(value + advance());
33186 if (prior.type === 'bos' && rest[0] === '/') {
33187 prev.type = 'globstar';
33188 prev.value += value;
33189 prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
33190 state.output = prev.output;
33191 state.globstar = true;
33192 consume(value + advance());
33199 } // remove single star from output
33202 state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar
33204 prev.type = 'globstar';
33205 prev.output = globstar(opts);
33206 prev.value += value; // reset output with globstar
33208 state.output += prev.output;
33209 state.globstar = true;
33220 if (opts.bash === true) {
33221 token.output = '.*?';
33223 if (prev.type === 'bos' || prev.type === 'slash') {
33224 token.output = nodot + token.output;
33231 if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
33232 token.output = value;
33237 if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
33238 if (prev.type === 'dot') {
33239 state.output += NO_DOT_SLASH;
33240 prev.output += NO_DOT_SLASH;
33241 } else if (opts.dot === true) {
33242 state.output += NO_DOTS_SLASH;
33243 prev.output += NO_DOTS_SLASH;
33245 state.output += nodot;
33246 prev.output += nodot;
33249 if (peek() !== '*') {
33250 state.output += ONE_CHAR;
33251 prev.output += ONE_CHAR;
33258 while (state.brackets > 0) {
33259 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ']'));
33260 state.output = utils$2.escapeLast(state.output, '[');
33261 decrement('brackets');
33264 while (state.parens > 0) {
33265 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ')'));
33266 state.output = utils$2.escapeLast(state.output, '(');
33267 decrement('parens');
33270 while (state.braces > 0) {
33271 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', '}'));
33272 state.output = utils$2.escapeLast(state.output, '{');
33273 decrement('braces');
33276 if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
33278 type: 'maybe_slash',
33280 output: `${SLASH_LITERAL}?`
33282 } // rebuild the output if we had to backtrack at any point
33285 if (state.backtrack === true) {
33288 for (const token of state.tokens) {
33289 state.output += token.output != null ? token.output : token.value;
33291 if (token.suffix) {
33292 state.output += token.suffix;
33300 * Fast paths for creating regular expressions for common glob patterns.
33301 * This can significantly speed up processing and has very little downside
33302 * impact when none of the fast paths match.
33306 parse$6.fastpaths = (input, options) => {
33307 const opts = Object.assign({}, options);
33308 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$3, opts.maxLength) : MAX_LENGTH$3;
33309 const len = input.length;
33312 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
33315 input = REPLACEMENTS[input] || input;
33316 const win32 = utils$2.isWindows(options); // create constants based on platform, for windows or posix
33328 } = constants$4.globChars(win32);
33329 const nodot = opts.dot ? NO_DOTS : NO_DOT;
33330 const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
33331 const capture = opts.capture ? '' : '?:';
33336 let star = opts.bash === true ? '.*?' : STAR;
33338 if (opts.capture) {
33339 star = `(${star})`;
33342 const globstar = opts => {
33343 if (opts.noglobstar === true) return star;
33344 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
33347 const create = str => {
33350 return `${nodot}${ONE_CHAR}${star}`;
33353 return `${DOT_LITERAL}${ONE_CHAR}${star}`;
33356 return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
33359 return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
33362 return nodot + globstar(opts);
33365 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
33368 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
33371 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
33375 const match = /^(.*?)\.(\w+)$/.exec(str);
33376 if (!match) return;
33377 const source = create(match[1]);
33378 if (!source) return;
33379 return source + DOT_LITERAL + match[2];
33384 const output = utils$2.removePrefix(input, state);
33385 let source = create(output);
33387 if (source && opts.strictSlashes !== true) {
33388 source += `${SLASH_LITERAL}?`;
33394 var parse_1$1 = parse$6;
33396 const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val);
33398 * Creates a matcher function from one or more glob patterns. The
33399 * returned function takes a string to match as its first argument,
33400 * and returns true if the string is a match. The returned matcher
33401 * function also takes a boolean as the second argument that, when true,
33402 * returns an object with additional information.
33405 * const picomatch = require('picomatch');
33406 * // picomatch(glob[, options]);
33408 * const isMatch = picomatch('*.!(*a)');
33409 * console.log(isMatch('a.a')); //=> false
33410 * console.log(isMatch('a.b')); //=> true
33413 * @param {String|Array} `globs` One or more glob patterns.
33414 * @param {Object=} `options`
33415 * @return {Function=} Returns a matcher function.
33420 const picomatch = (glob, options, returnState = false) => {
33421 if (Array.isArray(glob)) {
33422 const fns = glob.map(input => picomatch(input, options, returnState));
33424 const arrayMatcher = str => {
33425 for (const isMatch of fns) {
33426 const state = isMatch(str);
33427 if (state) return state;
33433 return arrayMatcher;
33436 const isState = isObject$2(glob) && glob.tokens && glob.input;
33438 if (glob === '' || typeof glob !== 'string' && !isState) {
33439 throw new TypeError('Expected pattern to be a non-empty string');
33442 const opts = options || {};
33443 const posix = utils$2.isWindows(options);
33444 const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true);
33445 const state = regex.state;
33446 delete regex.state;
33448 let isIgnored = () => false;
33451 const ignoreOpts = Object.assign({}, options, {
33456 isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
33459 const matcher = (input, returnObject = false) => {
33464 } = picomatch.test(input, regex, options, {
33479 if (typeof opts.onResult === 'function') {
33480 opts.onResult(result);
33483 if (isMatch === false) {
33484 result.isMatch = false;
33485 return returnObject ? result : false;
33488 if (isIgnored(input)) {
33489 if (typeof opts.onIgnore === 'function') {
33490 opts.onIgnore(result);
33493 result.isMatch = false;
33494 return returnObject ? result : false;
33497 if (typeof opts.onMatch === 'function') {
33498 opts.onMatch(result);
33501 return returnObject ? result : true;
33505 matcher.state = state;
33511 * Test `input` with the given `regex`. This is used by the main
33512 * `picomatch()` function to test the input string.
33515 * const picomatch = require('picomatch');
33516 * // picomatch.test(input, regex[, options]);
33518 * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
33519 * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
33521 * @param {String} `input` String to test.
33522 * @param {RegExp} `regex`
33523 * @return {Object} Returns an object with matching info.
33528 picomatch.test = (input, regex, options, {
33532 if (typeof input !== 'string') {
33533 throw new TypeError('Expected input to be a string');
33536 if (input === '') {
33543 const opts = options || {};
33544 const format = opts.format || (posix ? utils$2.toPosixSlashes : null);
33545 let match = input === glob;
33546 let output = match && format ? format(input) : input;
33548 if (match === false) {
33549 output = format ? format(input) : input;
33550 match = output === glob;
33553 if (match === false || opts.capture === true) {
33554 if (opts.matchBase === true || opts.basename === true) {
33555 match = picomatch.matchBase(input, regex, options, posix);
33557 match = regex.exec(output);
33562 isMatch: Boolean(match),
33568 * Match the basename of a filepath.
33571 * const picomatch = require('picomatch');
33572 * // picomatch.matchBase(input, glob[, options]);
33573 * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
33575 * @param {String} `input` String to test.
33576 * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
33577 * @return {Boolean}
33582 picomatch.matchBase = (input, glob, options, posix = utils$2.isWindows(options)) => {
33583 const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
33584 return regex.test(path__default['default'].basename(input));
33587 * Returns true if **any** of the given glob `patterns` match the specified `string`.
33590 * const picomatch = require('picomatch');
33591 * // picomatch.isMatch(string, patterns[, options]);
33593 * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
33594 * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
33596 * @param {String|Array} str The string to test.
33597 * @param {String|Array} patterns One or more glob patterns to use for matching.
33598 * @param {Object} [options] See available [options](#options).
33599 * @return {Boolean} Returns true if any patterns match `str`
33604 picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
33606 * Parse a glob pattern to create the source string for a regular
33610 * const picomatch = require('picomatch');
33611 * const result = picomatch.parse(pattern[, options]);
33613 * @param {String} `pattern`
33614 * @param {Object} `options`
33615 * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
33620 picomatch.parse = (pattern, options) => {
33621 if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
33622 return parse_1$1(pattern, Object.assign({}, options, {
33627 * Scan a glob pattern to separate the pattern into segments.
33630 * const picomatch = require('picomatch');
33631 * // picomatch.scan(input[, options]);
33633 * const result = picomatch.scan('!./foo/*.js');
33634 * console.log(result);
33636 * input: '!./foo/*.js',
33641 * isBracket: false,
33643 * isExtglob: false,
33644 * isGlobstar: false,
33647 * @param {String} `input` Glob pattern to scan.
33648 * @param {Object} `options`
33649 * @return {Object} Returns an object with
33654 picomatch.scan = (input, options) => scan_1(input, options);
33656 * Create a regular expression from a parsed glob pattern.
33659 * const picomatch = require('picomatch');
33660 * const state = picomatch.parse('*.js');
33661 * // picomatch.compileRe(state[, options]);
33663 * console.log(picomatch.compileRe(state));
33664 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
33666 * @param {String} `state` The object returned from the `.parse` method.
33667 * @param {Object} `options`
33668 * @return {RegExp} Returns a regex created from the given pattern.
33673 picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => {
33674 if (returnOutput === true) {
33675 return parsed.output;
33678 const opts = options || {};
33679 const prepend = opts.contains ? '' : '^';
33680 const append = opts.contains ? '' : '$';
33681 let source = `${prepend}(?:${parsed.output})${append}`;
33683 if (parsed && parsed.negated === true) {
33684 source = `^(?!${source}).*$`;
33687 const regex = picomatch.toRegex(source, options);
33689 if (returnState === true) {
33690 regex.state = parsed;
33696 picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
33697 if (!input || typeof input !== 'string') {
33698 throw new TypeError('Expected a non-empty string');
33701 const opts = options || {};
33709 if (input.startsWith('./')) {
33710 input = input.slice(2);
33711 prefix = parsed.prefix = './';
33714 if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
33715 output = parse_1$1.fastpaths(input, options);
33718 if (output === undefined) {
33719 parsed = parse_1$1(input, options);
33720 parsed.prefix = prefix + (parsed.prefix || '');
33722 parsed.output = output;
33725 return picomatch.compileRe(parsed, options, returnOutput, returnState);
33728 * Create a regular expression from the given regex source string.
33731 * const picomatch = require('picomatch');
33732 * // picomatch.toRegex(source[, options]);
33734 * const { output } = picomatch.parse('*.js');
33735 * console.log(picomatch.toRegex(output));
33736 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
33738 * @param {String} `source` Regular expression source string.
33739 * @param {Object} `options`
33745 picomatch.toRegex = (source, options) => {
33747 const opts = options || {};
33748 return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
33750 if (options && options.debug === true) throw err;
33755 * Picomatch constants.
33760 picomatch.constants = constants$4;
33762 * Expose "picomatch"
33765 var picomatch_1 = picomatch;
33767 var picomatch$1 = picomatch_1;
33769 const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');
33771 * Returns an array of strings that match one or more glob patterns.
33774 * const mm = require('micromatch');
33775 * // mm(list, patterns[, options]);
33777 * console.log(mm(['a.js', 'a.txt'], ['*.js']));
33780 * @param {String|Array<string>} list List of strings to match.
33781 * @param {String|Array<string>} patterns One or more glob patterns to use for matching.
33782 * @param {Object} options See available [options](#options)
33783 * @return {Array} Returns an array of matches
33789 const micromatch = (list, patterns, options) => {
33790 patterns = [].concat(patterns);
33791 list = [].concat(list);
33792 let omit = new Set();
33793 let keep = new Set();
33794 let items = new Set();
33797 let onResult = state => {
33798 items.add(state.output);
33800 if (options && options.onResult) {
33801 options.onResult(state);
33805 for (let i = 0; i < patterns.length; i++) {
33806 let isMatch = picomatch$1(String(patterns[i]), Object.assign({}, options, {
33809 let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
33810 if (negated) negatives++;
33812 for (let item of list) {
33813 let matched = isMatch(item, true);
33814 let match = negated ? !matched.isMatch : matched.isMatch;
33815 if (!match) continue;
33818 omit.add(matched.output);
33820 omit.delete(matched.output);
33821 keep.add(matched.output);
33826 let result = negatives === patterns.length ? [...items] : [...keep];
33827 let matches = result.filter(item => !omit.has(item));
33829 if (options && matches.length === 0) {
33830 if (options.failglob === true) {
33831 throw new Error(`No matches found for "${patterns.join(', ')}"`);
33834 if (options.nonull === true || options.nullglob === true) {
33835 return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
33842 * Backwards compatibility
33846 micromatch.match = micromatch;
33848 * Returns a matcher function from the given glob `pattern` and `options`.
33849 * The returned function takes a string to match as its only argument and returns
33850 * true if the string is a match.
33853 * const mm = require('micromatch');
33854 * // mm.matcher(pattern[, options]);
33856 * const isMatch = mm.matcher('*.!(*a)');
33857 * console.log(isMatch('a.a')); //=> false
33858 * console.log(isMatch('a.b')); //=> true
33860 * @param {String} `pattern` Glob pattern
33861 * @param {Object} `options`
33862 * @return {Function} Returns a matcher function.
33866 micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);
33868 * Returns true if **any** of the given glob `patterns` match the specified `string`.
33871 * const mm = require('micromatch');
33872 * // mm.isMatch(string, patterns[, options]);
33874 * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
33875 * console.log(mm.isMatch('a.a', 'b.*')); //=> false
33877 * @param {String} str The string to test.
33878 * @param {String|Array} patterns One or more glob patterns to use for matching.
33879 * @param {Object} [options] See available [options](#options).
33880 * @return {Boolean} Returns true if any patterns match `str`
33885 micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
33887 * Backwards compatibility
33891 micromatch.any = micromatch.isMatch;
33893 * Returns a list of strings that _**do not match any**_ of the given `patterns`.
33896 * const mm = require('micromatch');
33897 * // mm.not(list, patterns[, options]);
33899 * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
33900 * //=> ['b.b', 'c.c']
33902 * @param {Array} `list` Array of strings to match.
33903 * @param {String|Array} `patterns` One or more glob pattern to use for matching.
33904 * @param {Object} `options` See available [options](#options) for changing how matches are performed
33905 * @return {Array} Returns an array of strings that **do not match** the given patterns.
33909 micromatch.not = (list, patterns, options = {}) => {
33910 patterns = [].concat(patterns).map(String);
33911 let result = new Set();
33914 let onResult = state => {
33915 if (options.onResult) options.onResult(state);
33916 items.push(state.output);
33919 let matches = micromatch(list, patterns, Object.assign({}, options, {
33923 for (let item of items) {
33924 if (!matches.includes(item)) {
33929 return [...result];
33932 * Returns true if the given `string` contains the given pattern. Similar
33933 * to [.isMatch](#isMatch) but the pattern can match any part of the string.
33936 * var mm = require('micromatch');
33937 * // mm.contains(string, pattern[, options]);
33939 * console.log(mm.contains('aa/bb/cc', '*b'));
33941 * console.log(mm.contains('aa/bb/cc', '*d'));
33944 * @param {String} `str` The string to match.
33945 * @param {String|Array} `patterns` Glob pattern to use for matching.
33946 * @param {Object} `options` See available [options](#options) for changing how matches are performed
33947 * @return {Boolean} Returns true if the patter matches any part of `str`.
33952 micromatch.contains = (str, pattern, options) => {
33953 if (typeof str !== 'string') {
33954 throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`);
33957 if (Array.isArray(pattern)) {
33958 return pattern.some(p => micromatch.contains(str, p, options));
33961 if (typeof pattern === 'string') {
33962 if (isEmptyString(str) || isEmptyString(pattern)) {
33966 if (str.includes(pattern) || str.startsWith('./') && str.slice(2).includes(pattern)) {
33971 return micromatch.isMatch(str, pattern, Object.assign({}, options, {
33976 * Filter the keys of the given object with the given `glob` pattern
33977 * and `options`. Does not attempt to match nested keys. If you need this feature,
33978 * use [glob-object][] instead.
33981 * const mm = require('micromatch');
33982 * // mm.matchKeys(object, patterns[, options]);
33984 * const obj = { aa: 'a', ab: 'b', ac: 'c' };
33985 * console.log(mm.matchKeys(obj, '*b'));
33988 * @param {Object} `object` The object with keys to filter.
33989 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
33990 * @param {Object} `options` See available [options](#options) for changing how matches are performed
33991 * @return {Object} Returns an object with only keys that match the given patterns.
33996 micromatch.matchKeys = (obj, patterns, options) => {
33997 if (!utils$2.isObject(obj)) {
33998 throw new TypeError('Expected the first argument to be an object');
34001 let keys = micromatch(Object.keys(obj), patterns, options);
34004 for (let key of keys) res[key] = obj[key];
34009 * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
34012 * const mm = require('micromatch');
34013 * // mm.some(list, patterns[, options]);
34015 * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
34017 * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
34020 * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
34021 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
34022 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34023 * @return {Boolean} Returns true if any patterns match `str`
34028 micromatch.some = (list, patterns, options) => {
34029 let items = [].concat(list);
34031 for (let pattern of [].concat(patterns)) {
34032 let isMatch = picomatch$1(String(pattern), options);
34034 if (items.some(item => isMatch(item))) {
34042 * Returns true if every string in the given `list` matches
34043 * any of the given glob `patterns`.
34046 * const mm = require('micromatch');
34047 * // mm.every(list, patterns[, options]);
34049 * console.log(mm.every('foo.js', ['foo.js']));
34051 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
34053 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
34055 * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
34058 * @param {String|Array} `list` The string or array of strings to test.
34059 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
34060 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34061 * @return {Boolean} Returns true if any patterns match `str`
34066 micromatch.every = (list, patterns, options) => {
34067 let items = [].concat(list);
34069 for (let pattern of [].concat(patterns)) {
34070 let isMatch = picomatch$1(String(pattern), options);
34072 if (!items.every(item => isMatch(item))) {
34080 * Returns true if **all** of the given `patterns` match
34081 * the specified string.
34084 * const mm = require('micromatch');
34085 * // mm.all(string, patterns[, options]);
34087 * console.log(mm.all('foo.js', ['foo.js']));
34090 * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
34093 * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
34096 * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
34099 * @param {String|Array} `str` The string to test.
34100 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
34101 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34102 * @return {Boolean} Returns true if any patterns match `str`
34107 micromatch.all = (str, patterns, options) => {
34108 if (typeof str !== 'string') {
34109 throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`);
34112 return [].concat(patterns).every(p => picomatch$1(p, options)(str));
34115 * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
34118 * const mm = require('micromatch');
34119 * // mm.capture(pattern, string[, options]);
34121 * console.log(mm.capture('test/*.js', 'test/foo.js'));
34123 * console.log(mm.capture('test/*.js', 'foo/bar.css'));
34126 * @param {String} `glob` Glob pattern to use for matching.
34127 * @param {String} `input` String to match
34128 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34129 * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
34134 micromatch.capture = (glob, input, options) => {
34135 let posix = utils$2.isWindows(options);
34136 let regex = picomatch$1.makeRe(String(glob), Object.assign({}, options, {
34139 let match = regex.exec(posix ? utils$2.toPosixSlashes(input) : input);
34142 return match.slice(1).map(v => v === void 0 ? '' : v);
34146 * Create a regular expression from the given glob `pattern`.
34149 * const mm = require('micromatch');
34150 * // mm.makeRe(pattern[, options]);
34152 * console.log(mm.makeRe('*.js'));
34153 * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
34155 * @param {String} `pattern` A glob pattern to convert to regex.
34156 * @param {Object} `options`
34157 * @return {RegExp} Returns a regex created from the given pattern.
34162 micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);
34164 * Scan a glob pattern to separate the pattern into segments. Used
34165 * by the [split](#split) method.
34168 * const mm = require('micromatch');
34169 * const state = mm.scan(pattern[, options]);
34171 * @param {String} `pattern`
34172 * @param {Object} `options`
34173 * @return {Object} Returns an object with
34178 micromatch.scan = (...args) => picomatch$1.scan(...args);
34180 * Parse a glob pattern to create the source string for a regular
34184 * const mm = require('micromatch');
34185 * const state = mm(pattern[, options]);
34187 * @param {String} `glob`
34188 * @param {Object} `options`
34189 * @return {Object} Returns an object with useful properties and output to be used as regex source string.
34194 micromatch.parse = (patterns, options) => {
34197 for (let pattern of [].concat(patterns || [])) {
34198 for (let str of braces_1(String(pattern), options)) {
34199 res.push(picomatch$1.parse(str, options));
34206 * Process the given brace `pattern`.
34209 * const { braces } = require('micromatch');
34210 * console.log(braces('foo/{a,b,c}/bar'));
34211 * //=> [ 'foo/(a|b|c)/bar' ]
34213 * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
34214 * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
34216 * @param {String} `pattern` String with brace pattern to process.
34217 * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
34223 micromatch.braces = (pattern, options) => {
34224 if (typeof pattern !== 'string') throw new TypeError('Expected a string');
34226 if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) {
34230 return braces_1(pattern, options);
34237 micromatch.braceExpand = (pattern, options) => {
34238 if (typeof pattern !== 'string') throw new TypeError('Expected a string');
34239 return micromatch.braces(pattern, Object.assign({}, options, {
34244 * Expose micromatch
34248 var micromatch_1 = micromatch;
34250 var pattern = createCommonjsModule(function (module, exports) {
34252 Object.defineProperty(exports, "__esModule", {
34255 exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0;
34256 const GLOBSTAR = '**';
34257 const ESCAPE_SYMBOL = '\\';
34258 const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
34259 const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/;
34260 const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/;
34261 const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/;
34262 const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/;
34264 function isStaticPattern(pattern, options = {}) {
34265 return !isDynamicPattern(pattern, options);
34268 exports.isStaticPattern = isStaticPattern;
34270 function isDynamicPattern(pattern, options = {}) {
34272 * A special case with an empty string is necessary for matching patterns that start with a forward slash.
\r
34273 * An empty string cannot be a dynamic pattern.
\r
34274 * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
\r
34276 if (pattern === '') {
34280 * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
\r
34281 * filepath directly (without read directory).
\r
34285 if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
34289 if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
34293 if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
34297 if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) {
34304 exports.isDynamicPattern = isDynamicPattern;
34306 function convertToPositivePattern(pattern) {
34307 return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
34310 exports.convertToPositivePattern = convertToPositivePattern;
34312 function convertToNegativePattern(pattern) {
34313 return '!' + pattern;
34316 exports.convertToNegativePattern = convertToNegativePattern;
34318 function isNegativePattern(pattern) {
34319 return pattern.startsWith('!') && pattern[1] !== '(';
34322 exports.isNegativePattern = isNegativePattern;
34324 function isPositivePattern(pattern) {
34325 return !isNegativePattern(pattern);
34328 exports.isPositivePattern = isPositivePattern;
34330 function getNegativePatterns(patterns) {
34331 return patterns.filter(isNegativePattern);
34334 exports.getNegativePatterns = getNegativePatterns;
34336 function getPositivePatterns(patterns) {
34337 return patterns.filter(isPositivePattern);
34340 exports.getPositivePatterns = getPositivePatterns;
34342 function getBaseDirectory(pattern) {
34343 return globParent(pattern, {
34344 flipBackslashes: false
34348 exports.getBaseDirectory = getBaseDirectory;
34350 function hasGlobStar(pattern) {
34351 return pattern.includes(GLOBSTAR);
34354 exports.hasGlobStar = hasGlobStar;
34356 function endsWithSlashGlobStar(pattern) {
34357 return pattern.endsWith('/' + GLOBSTAR);
34360 exports.endsWithSlashGlobStar = endsWithSlashGlobStar;
34362 function isAffectDepthOfReadingPattern(pattern) {
34363 const basename = path__default['default'].basename(pattern);
34364 return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
34367 exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
34369 function expandPatternsWithBraceExpansion(patterns) {
34370 return patterns.reduce((collection, pattern) => {
34371 return collection.concat(expandBraceExpansion(pattern));
34375 exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
34377 function expandBraceExpansion(pattern) {
34378 return micromatch_1.braces(pattern, {
34384 exports.expandBraceExpansion = expandBraceExpansion;
34386 function getPatternParts(pattern, options) {
34389 } = picomatch$1.scan(pattern, Object.assign(Object.assign({}, options), {
34393 * The scan method returns an empty array in some cases.
\r
34394 * See micromatch/picomatch#58 for more details.
\r
34397 if (parts.length === 0) {
34401 * The scan method does not return an empty part for the pattern with a forward slash.
\r
34402 * This is another part of micromatch/picomatch#58.
\r
34406 if (parts[0].startsWith('/')) {
34407 parts[0] = parts[0].slice(1);
34414 exports.getPatternParts = getPatternParts;
34416 function makeRe(pattern, options) {
34417 return micromatch_1.makeRe(pattern, options);
34420 exports.makeRe = makeRe;
34422 function convertPatternsToRe(patterns, options) {
34423 return patterns.map(pattern => makeRe(pattern, options));
34426 exports.convertPatternsToRe = convertPatternsToRe;
34428 function matchAny(entry, patternsRe) {
34429 return patternsRe.some(patternRe => patternRe.test(entry));
34432 exports.matchAny = matchAny;
34435 var stream$2 = createCommonjsModule(function (module, exports) {
34437 Object.defineProperty(exports, "__esModule", {
34440 exports.merge = void 0;
34442 function merge(streams) {
34443 const mergedStream = merge2_1(streams);
34444 streams.forEach(stream => {
34445 stream.once('error', error => mergedStream.emit('error', error));
34447 mergedStream.once('close', () => propagateCloseEventToSources(streams));
34448 mergedStream.once('end', () => propagateCloseEventToSources(streams));
34449 return mergedStream;
34452 exports.merge = merge;
34454 function propagateCloseEventToSources(streams) {
34455 streams.forEach(stream => stream.emit('close'));
34459 var string$1 = createCommonjsModule(function (module, exports) {
34461 Object.defineProperty(exports, "__esModule", {
34464 exports.isEmpty = exports.isString = void 0;
34466 function isString(input) {
34467 return typeof input === 'string';
34470 exports.isString = isString;
34472 function isEmpty(input) {
34473 return input === '';
34476 exports.isEmpty = isEmpty;
34479 var utils$3 = createCommonjsModule(function (module, exports) {
34481 Object.defineProperty(exports, "__esModule", {
34484 exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0;
34485 exports.array = array$2;
34486 exports.errno = errno;
34488 exports.path = path_1;
34489 exports.pattern = pattern;
34490 exports.stream = stream$2;
34491 exports.string = string$1;
34494 var tasks = createCommonjsModule(function (module, exports) {
34496 Object.defineProperty(exports, "__esModule", {
34499 exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0;
34501 function generate(patterns, settings) {
34502 const positivePatterns = getPositivePatterns(patterns);
34503 const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
34504 const staticPatterns = positivePatterns.filter(pattern => utils$3.pattern.isStaticPattern(pattern, settings));
34505 const dynamicPatterns = positivePatterns.filter(pattern => utils$3.pattern.isDynamicPattern(pattern, settings));
34506 const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns,
34509 const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns,
34512 return staticTasks.concat(dynamicTasks);
34515 exports.generate = generate;
34517 function convertPatternsToTasks(positive, negative, dynamic) {
34518 const positivePatternsGroup = groupPatternsByBaseDirectory(positive); // When we have a global group – there is no reason to divide the patterns into independent tasks.
34519 // In this case, the global task covers the rest.
34521 if ('.' in positivePatternsGroup) {
34522 const task = convertPatternGroupToTask('.', positive, negative, dynamic);
34526 return convertPatternGroupsToTasks(positivePatternsGroup, negative, dynamic);
34529 exports.convertPatternsToTasks = convertPatternsToTasks;
34531 function getPositivePatterns(patterns) {
34532 return utils$3.pattern.getPositivePatterns(patterns);
34535 exports.getPositivePatterns = getPositivePatterns;
34537 function getNegativePatternsAsPositive(patterns, ignore) {
34538 const negative = utils$3.pattern.getNegativePatterns(patterns).concat(ignore);
34539 const positive = negative.map(utils$3.pattern.convertToPositivePattern);
34543 exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
34545 function groupPatternsByBaseDirectory(patterns) {
34547 return patterns.reduce((collection, pattern) => {
34548 const base = utils$3.pattern.getBaseDirectory(pattern);
34550 if (base in collection) {
34551 collection[base].push(pattern);
34553 collection[base] = [pattern];
34560 exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
34562 function convertPatternGroupsToTasks(positive, negative, dynamic) {
34563 return Object.keys(positive).map(base => {
34564 return convertPatternGroupToTask(base, positive[base], negative, dynamic);
34568 exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
34570 function convertPatternGroupToTask(base, positive, negative, dynamic) {
34576 patterns: [].concat(positive, negative.map(utils$3.pattern.convertToNegativePattern))
34580 exports.convertPatternGroupToTask = convertPatternGroupToTask;
34583 var async$1 = createCommonjsModule(function (module, exports) {
34585 Object.defineProperty(exports, "__esModule", {
34589 function read(path, settings, callback) {
34590 settings.fs.lstat(path, (lstatError, lstat) => {
34591 if (lstatError !== null) {
34592 return callFailureCallback(callback, lstatError);
34595 if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
34596 return callSuccessCallback(callback, lstat);
34599 settings.fs.stat(path, (statError, stat) => {
34600 if (statError !== null) {
34601 if (settings.throwErrorOnBrokenSymbolicLink) {
34602 return callFailureCallback(callback, statError);
34605 return callSuccessCallback(callback, lstat);
34608 if (settings.markSymbolicLink) {
34609 stat.isSymbolicLink = () => true;
34612 callSuccessCallback(callback, stat);
34617 exports.read = read;
34619 function callFailureCallback(callback, error) {
34623 function callSuccessCallback(callback, result) {
34624 callback(null, result);
34628 var sync$1 = createCommonjsModule(function (module, exports) {
34630 Object.defineProperty(exports, "__esModule", {
34634 function read(path, settings) {
34635 const lstat = settings.fs.lstatSync(path);
34637 if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
34642 const stat = settings.fs.statSync(path);
34644 if (settings.markSymbolicLink) {
34645 stat.isSymbolicLink = () => true;
34650 if (!settings.throwErrorOnBrokenSymbolicLink) {
34658 exports.read = read;
34661 var fs_1 = createCommonjsModule(function (module, exports) {
34663 Object.defineProperty(exports, "__esModule", {
34666 exports.FILE_SYSTEM_ADAPTER = {
34667 lstat: fs__default['default'].lstat,
34668 stat: fs__default['default'].stat,
34669 lstatSync: fs__default['default'].lstatSync,
34670 statSync: fs__default['default'].statSync
34673 function createFileSystemAdapter(fsMethods) {
34674 if (fsMethods === undefined) {
34675 return exports.FILE_SYSTEM_ADAPTER;
34678 return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
34681 exports.createFileSystemAdapter = createFileSystemAdapter;
34684 var settings = createCommonjsModule(function (module, exports) {
34686 Object.defineProperty(exports, "__esModule", {
34691 constructor(_options = {}) {
34692 this._options = _options;
34693 this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
34694 this.fs = fs_1.createFileSystemAdapter(this._options.fs);
34695 this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
34696 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
34699 _getValue(option, value) {
34700 return option === undefined ? value : option;
34705 exports.default = Settings;
34708 var out = createCommonjsModule(function (module, exports) {
34710 Object.defineProperty(exports, "__esModule", {
34713 exports.Settings = settings.default;
34715 function stat(path, optionsOrSettingsOrCallback, callback) {
34716 if (typeof optionsOrSettingsOrCallback === 'function') {
34717 return async$1.read(path, getSettings(), optionsOrSettingsOrCallback);
34720 async$1.read(path, getSettings(optionsOrSettingsOrCallback), callback);
34723 exports.stat = stat;
34725 function statSync(path, optionsOrSettings) {
34726 const settings = getSettings(optionsOrSettings);
34727 return sync$1.read(path, settings);
34730 exports.statSync = statSync;
34732 function getSettings(settingsOrOptions = {}) {
34733 if (settingsOrOptions instanceof settings.default) {
34734 return settingsOrOptions;
34737 return new settings.default(settingsOrOptions);
34741 var runParallel_1 = runParallel;
34743 function runParallel(tasks, cb) {
34744 var results, pending, keys;
34747 if (Array.isArray(tasks)) {
34749 pending = tasks.length;
34751 keys = Object.keys(tasks);
34753 pending = keys.length;
34756 function done(err) {
34758 if (cb) cb(err, results);
34762 if (isSync) process.nextTick(end);else end();
34765 function each(i, err, result) {
34766 results[i] = result;
34768 if (--pending === 0 || err) {
34778 keys.forEach(function (key) {
34779 tasks[key](function (err, result) {
34780 each(key, err, result);
34785 tasks.forEach(function (task, i) {
34786 task(function (err, result) {
34787 each(i, err, result);
34795 var constants$5 = createCommonjsModule(function (module, exports) {
34797 Object.defineProperty(exports, "__esModule", {
34800 const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
34801 const MAJOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
34802 const MINOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
34803 const SUPPORTED_MAJOR_VERSION = 10;
34804 const SUPPORTED_MINOR_VERSION = 10;
34805 const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
34806 const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
34808 * IS `true` for Node.js 10.10 and greater.
\r
34811 exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
34814 var fs$3 = createCommonjsModule(function (module, exports) {
34816 Object.defineProperty(exports, "__esModule", {
34820 class DirentFromStats {
34821 constructor(name, stats) {
34823 this.isBlockDevice = stats.isBlockDevice.bind(stats);
34824 this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
34825 this.isDirectory = stats.isDirectory.bind(stats);
34826 this.isFIFO = stats.isFIFO.bind(stats);
34827 this.isFile = stats.isFile.bind(stats);
34828 this.isSocket = stats.isSocket.bind(stats);
34829 this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
34834 function createDirentFromStats(name, stats) {
34835 return new DirentFromStats(name, stats);
34838 exports.createDirentFromStats = createDirentFromStats;
34841 var utils$4 = createCommonjsModule(function (module, exports) {
34843 Object.defineProperty(exports, "__esModule", {
34849 var async$2 = createCommonjsModule(function (module, exports) {
34851 Object.defineProperty(exports, "__esModule", {
34855 function read(directory, settings, callback) {
34856 if (!settings.stats && constants$5.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
34857 return readdirWithFileTypes(directory, settings, callback);
34860 return readdir(directory, settings, callback);
34863 exports.read = read;
34865 function readdirWithFileTypes(directory, settings, callback) {
34866 settings.fs.readdir(directory, {
34867 withFileTypes: true
34868 }, (readdirError, dirents) => {
34869 if (readdirError !== null) {
34870 return callFailureCallback(callback, readdirError);
34873 const entries = dirents.map(dirent => ({
34876 path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
34879 if (!settings.followSymbolicLinks) {
34880 return callSuccessCallback(callback, entries);
34883 const tasks = entries.map(entry => makeRplTaskEntry(entry, settings));
34884 runParallel_1(tasks, (rplError, rplEntries) => {
34885 if (rplError !== null) {
34886 return callFailureCallback(callback, rplError);
34889 callSuccessCallback(callback, rplEntries);
34894 exports.readdirWithFileTypes = readdirWithFileTypes;
34896 function makeRplTaskEntry(entry, settings) {
34898 if (!entry.dirent.isSymbolicLink()) {
34899 return done(null, entry);
34902 settings.fs.stat(entry.path, (statError, stats) => {
34903 if (statError !== null) {
34904 if (settings.throwErrorOnBrokenSymbolicLink) {
34905 return done(statError);
34908 return done(null, entry);
34911 entry.dirent = utils$4.fs.createDirentFromStats(entry.name, stats);
34912 return done(null, entry);
34917 function readdir(directory, settings, callback) {
34918 settings.fs.readdir(directory, (readdirError, names) => {
34919 if (readdirError !== null) {
34920 return callFailureCallback(callback, readdirError);
34923 const filepaths = names.map(name => `${directory}${settings.pathSegmentSeparator}${name}`);
34924 const tasks = filepaths.map(filepath => {
34925 return done => out.stat(filepath, settings.fsStatSettings, done);
34927 runParallel_1(tasks, (rplError, results) => {
34928 if (rplError !== null) {
34929 return callFailureCallback(callback, rplError);
34932 const entries = [];
34933 names.forEach((name, index) => {
34934 const stats = results[index];
34937 path: filepaths[index],
34938 dirent: utils$4.fs.createDirentFromStats(name, stats)
34941 if (settings.stats) {
34942 entry.stats = stats;
34945 entries.push(entry);
34947 callSuccessCallback(callback, entries);
34952 exports.readdir = readdir;
34954 function callFailureCallback(callback, error) {
34958 function callSuccessCallback(callback, result) {
34959 callback(null, result);
34963 var sync$2 = createCommonjsModule(function (module, exports) {
34965 Object.defineProperty(exports, "__esModule", {
34969 function read(directory, settings) {
34970 if (!settings.stats && constants$5.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
34971 return readdirWithFileTypes(directory, settings);
34974 return readdir(directory, settings);
34977 exports.read = read;
34979 function readdirWithFileTypes(directory, settings) {
34980 const dirents = settings.fs.readdirSync(directory, {
34981 withFileTypes: true
34983 return dirents.map(dirent => {
34987 path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
34990 if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
34992 const stats = settings.fs.statSync(entry.path);
34993 entry.dirent = utils$4.fs.createDirentFromStats(entry.name, stats);
34995 if (settings.throwErrorOnBrokenSymbolicLink) {
35005 exports.readdirWithFileTypes = readdirWithFileTypes;
35007 function readdir(directory, settings) {
35008 const names = settings.fs.readdirSync(directory);
35009 return names.map(name => {
35010 const entryPath = `${directory}${settings.pathSegmentSeparator}${name}`;
35011 const stats = out.statSync(entryPath, settings.fsStatSettings);
35015 dirent: utils$4.fs.createDirentFromStats(name, stats)
35018 if (settings.stats) {
35019 entry.stats = stats;
35026 exports.readdir = readdir;
35029 var fs_1$1 = createCommonjsModule(function (module, exports) {
35031 Object.defineProperty(exports, "__esModule", {
35034 exports.FILE_SYSTEM_ADAPTER = {
35035 lstat: fs__default['default'].lstat,
35036 stat: fs__default['default'].stat,
35037 lstatSync: fs__default['default'].lstatSync,
35038 statSync: fs__default['default'].statSync,
35039 readdir: fs__default['default'].readdir,
35040 readdirSync: fs__default['default'].readdirSync
35043 function createFileSystemAdapter(fsMethods) {
35044 if (fsMethods === undefined) {
35045 return exports.FILE_SYSTEM_ADAPTER;
35048 return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
35051 exports.createFileSystemAdapter = createFileSystemAdapter;
35054 var settings$1 = createCommonjsModule(function (module, exports) {
35056 Object.defineProperty(exports, "__esModule", {
35061 constructor(_options = {}) {
35062 this._options = _options;
35063 this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
35064 this.fs = fs_1$1.createFileSystemAdapter(this._options.fs);
35065 this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep);
35066 this.stats = this._getValue(this._options.stats, false);
35067 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
35068 this.fsStatSettings = new out.Settings({
35069 followSymbolicLink: this.followSymbolicLinks,
35071 throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
35075 _getValue(option, value) {
35076 return option === undefined ? value : option;
35081 exports.default = Settings;
35084 var out$1 = createCommonjsModule(function (module, exports) {
35086 Object.defineProperty(exports, "__esModule", {
35089 exports.Settings = settings$1.default;
35091 function scandir(path, optionsOrSettingsOrCallback, callback) {
35092 if (typeof optionsOrSettingsOrCallback === 'function') {
35093 return async$2.read(path, getSettings(), optionsOrSettingsOrCallback);
35096 async$2.read(path, getSettings(optionsOrSettingsOrCallback), callback);
35099 exports.scandir = scandir;
35101 function scandirSync(path, optionsOrSettings) {
35102 const settings = getSettings(optionsOrSettings);
35103 return sync$2.read(path, settings);
35106 exports.scandirSync = scandirSync;
35108 function getSettings(settingsOrOptions = {}) {
35109 if (settingsOrOptions instanceof settings$1.default) {
35110 return settingsOrOptions;
35113 return new settings$1.default(settingsOrOptions);
35117 function reusify(Constructor) {
35118 var head = new Constructor();
35122 var current = head;
35124 if (current.next) {
35125 head = current.next;
35127 head = new Constructor();
35131 current.next = null;
35135 function release(obj) {
35146 var reusify_1 = reusify;
35148 function fastqueue(context, worker, concurrency) {
35149 if (typeof context === 'function') {
35150 concurrency = worker;
35155 var cache = reusify_1(Task);
35156 var queueHead = null;
35157 var queueTail = null;
35165 concurrency: concurrency,
35170 getQueue: getQueue,
35174 killAndDrain: killAndDrain
35178 function running() {
35183 self.paused = true;
35186 function length() {
35187 var current = queueHead;
35191 current = current.next;
35198 function getQueue() {
35199 var current = queueHead;
35203 tasks.push(current.value);
35204 current = current.next;
35210 function resume() {
35211 if (!self.paused) return;
35212 self.paused = false;
35214 for (var i = 0; i < self.concurrency; i++) {
35221 return _running === 0 && self.length() === 0;
35224 function push(value, done) {
35225 var current = cache.get();
35226 current.context = context;
35227 current.release = release;
35228 current.value = value;
35229 current.callback = done || noop$1;
35231 if (_running === self.concurrency || self.paused) {
35233 queueTail.next = current;
35234 queueTail = current;
35236 queueHead = current;
35237 queueTail = current;
35242 worker.call(context, current.value, current.worked);
35246 function unshift(value, done) {
35247 var current = cache.get();
35248 current.context = context;
35249 current.release = release;
35250 current.value = value;
35251 current.callback = done || noop$1;
35253 if (_running === self.concurrency || self.paused) {
35255 current.next = queueHead;
35256 queueHead = current;
35258 queueHead = current;
35259 queueTail = current;
35264 worker.call(context, current.value, current.worked);
35268 function release(holder) {
35270 cache.release(holder);
35273 var next = queueHead;
35276 if (!self.paused) {
35277 if (queueTail === queueHead) {
35281 queueHead = next.next;
35283 worker.call(context, next.value, next.worked);
35285 if (queueTail === null) {
35291 } else if (--_running === 0) {
35299 self.drain = noop$1;
35302 function killAndDrain() {
35306 self.drain = noop$1;
35310 function noop$1() {}
35314 this.callback = noop$1;
35316 this.release = noop$1;
35317 this.context = null;
35320 this.worked = function worked(err, result) {
35321 var callback = self.callback;
35323 self.callback = noop$1;
35324 callback.call(self.context, err, result);
35325 self.release(self);
35329 var queue = fastqueue;
35331 var common$2 = createCommonjsModule(function (module, exports) {
35333 Object.defineProperty(exports, "__esModule", {
35337 function isFatalError(settings, error) {
35338 if (settings.errorFilter === null) {
35342 return !settings.errorFilter(error);
35345 exports.isFatalError = isFatalError;
35347 function isAppliedFilter(filter, value) {
35348 return filter === null || filter(value);
35351 exports.isAppliedFilter = isAppliedFilter;
35353 function replacePathSegmentSeparator(filepath, separator) {
35354 return filepath.split(/[\\/]/).join(separator);
35357 exports.replacePathSegmentSeparator = replacePathSegmentSeparator;
35359 function joinPathSegments(a, b, separator) {
35364 return a + separator + b;
35367 exports.joinPathSegments = joinPathSegments;
35370 var reader = createCommonjsModule(function (module, exports) {
35372 Object.defineProperty(exports, "__esModule", {
35377 constructor(_root, _settings) {
35378 this._root = _root;
35379 this._settings = _settings;
35380 this._root = common$2.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
35385 exports.default = Reader;
35388 var async$3 = createCommonjsModule(function (module, exports) {
35390 Object.defineProperty(exports, "__esModule", {
35394 class AsyncReader extends reader.default {
35395 constructor(_root, _settings) {
35396 super(_root, _settings);
35397 this._settings = _settings;
35398 this._scandir = out$1.scandir;
35399 this._emitter = new events_1__default['default'].EventEmitter();
35400 this._queue = queue(this._worker.bind(this), this._settings.concurrency);
35401 this._isFatalError = false;
35402 this._isDestroyed = false;
35404 this._queue.drain = () => {
35405 if (!this._isFatalError) {
35406 this._emitter.emit('end');
35412 this._isFatalError = false;
35413 this._isDestroyed = false;
35414 setImmediate(() => {
35415 this._pushToQueue(this._root, this._settings.basePath);
35417 return this._emitter;
35421 if (this._isDestroyed) {
35422 throw new Error('The reader is already destroyed');
35425 this._isDestroyed = true;
35427 this._queue.killAndDrain();
35430 onEntry(callback) {
35431 this._emitter.on('entry', callback);
35434 onError(callback) {
35435 this._emitter.once('error', callback);
35439 this._emitter.once('end', callback);
35442 _pushToQueue(directory, base) {
35443 const queueItem = {
35448 this._queue.push(queueItem, error => {
35449 if (error !== null) {
35450 this._handleError(error);
35455 _worker(item, done) {
35456 this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
35457 if (error !== null) {
35458 return done(error, undefined);
35461 for (const entry of entries) {
35462 this._handleEntry(entry, item.base);
35465 done(null, undefined);
35469 _handleError(error) {
35470 if (!common$2.isFatalError(this._settings, error)) {
35474 this._isFatalError = true;
35475 this._isDestroyed = true;
35477 this._emitter.emit('error', error);
35480 _handleEntry(entry, base) {
35481 if (this._isDestroyed || this._isFatalError) {
35485 const fullpath = entry.path;
35487 if (base !== undefined) {
35488 entry.path = common$2.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
35491 if (common$2.isAppliedFilter(this._settings.entryFilter, entry)) {
35492 this._emitEntry(entry);
35495 if (entry.dirent.isDirectory() && common$2.isAppliedFilter(this._settings.deepFilter, entry)) {
35496 this._pushToQueue(fullpath, entry.path);
35500 _emitEntry(entry) {
35501 this._emitter.emit('entry', entry);
35506 exports.default = AsyncReader;
35509 var async$4 = createCommonjsModule(function (module, exports) {
35511 Object.defineProperty(exports, "__esModule", {
35515 class AsyncProvider {
35516 constructor(_root, _settings) {
35517 this._root = _root;
35518 this._settings = _settings;
35519 this._reader = new async$3.default(this._root, this._settings);
35520 this._storage = new Set();
35524 this._reader.onError(error => {
35525 callFailureCallback(callback, error);
35528 this._reader.onEntry(entry => {
35529 this._storage.add(entry);
35532 this._reader.onEnd(() => {
35533 callSuccessCallback(callback, [...this._storage]);
35536 this._reader.read();
35541 exports.default = AsyncProvider;
35543 function callFailureCallback(callback, error) {
35547 function callSuccessCallback(callback, entries) {
35548 callback(null, entries);
35552 var stream$3 = createCommonjsModule(function (module, exports) {
35554 Object.defineProperty(exports, "__esModule", {
35558 class StreamProvider {
35559 constructor(_root, _settings) {
35560 this._root = _root;
35561 this._settings = _settings;
35562 this._reader = new async$3.default(this._root, this._settings);
35563 this._stream = new stream_1__default['default'].Readable({
35566 destroy: this._reader.destroy.bind(this._reader)
35571 this._reader.onError(error => {
35572 this._stream.emit('error', error);
35575 this._reader.onEntry(entry => {
35576 this._stream.push(entry);
35579 this._reader.onEnd(() => {
35580 this._stream.push(null);
35583 this._reader.read();
35585 return this._stream;
35590 exports.default = StreamProvider;
35593 var sync$3 = createCommonjsModule(function (module, exports) {
35595 Object.defineProperty(exports, "__esModule", {
35599 class SyncReader extends reader.default {
35601 super(...arguments);
35602 this._scandir = out$1.scandirSync;
35603 this._storage = new Set();
35604 this._queue = new Set();
35608 this._pushToQueue(this._root, this._settings.basePath);
35610 this._handleQueue();
35612 return [...this._storage];
35615 _pushToQueue(directory, base) {
35623 for (const item of this._queue.values()) {
35624 this._handleDirectory(item.directory, item.base);
35628 _handleDirectory(directory, base) {
35630 const entries = this._scandir(directory, this._settings.fsScandirSettings);
35632 for (const entry of entries) {
35633 this._handleEntry(entry, base);
35636 this._handleError(error);
35640 _handleError(error) {
35641 if (!common$2.isFatalError(this._settings, error)) {
35648 _handleEntry(entry, base) {
35649 const fullpath = entry.path;
35651 if (base !== undefined) {
35652 entry.path = common$2.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
35655 if (common$2.isAppliedFilter(this._settings.entryFilter, entry)) {
35656 this._pushToStorage(entry);
35659 if (entry.dirent.isDirectory() && common$2.isAppliedFilter(this._settings.deepFilter, entry)) {
35660 this._pushToQueue(fullpath, entry.path);
35664 _pushToStorage(entry) {
35665 this._storage.add(entry);
35670 exports.default = SyncReader;
35673 var sync$4 = createCommonjsModule(function (module, exports) {
35675 Object.defineProperty(exports, "__esModule", {
35679 class SyncProvider {
35680 constructor(_root, _settings) {
35681 this._root = _root;
35682 this._settings = _settings;
35683 this._reader = new sync$3.default(this._root, this._settings);
35687 return this._reader.read();
35692 exports.default = SyncProvider;
35695 var settings$2 = createCommonjsModule(function (module, exports) {
35697 Object.defineProperty(exports, "__esModule", {
35702 constructor(_options = {}) {
35703 this._options = _options;
35704 this.basePath = this._getValue(this._options.basePath, undefined);
35705 this.concurrency = this._getValue(this._options.concurrency, Infinity);
35706 this.deepFilter = this._getValue(this._options.deepFilter, null);
35707 this.entryFilter = this._getValue(this._options.entryFilter, null);
35708 this.errorFilter = this._getValue(this._options.errorFilter, null);
35709 this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep);
35710 this.fsScandirSettings = new out$1.Settings({
35711 followSymbolicLinks: this._options.followSymbolicLinks,
35712 fs: this._options.fs,
35713 pathSegmentSeparator: this._options.pathSegmentSeparator,
35714 stats: this._options.stats,
35715 throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
35719 _getValue(option, value) {
35720 return option === undefined ? value : option;
35725 exports.default = Settings;
35728 var out$2 = createCommonjsModule(function (module, exports) {
35730 Object.defineProperty(exports, "__esModule", {
35733 exports.Settings = settings$2.default;
35735 function walk(directory, optionsOrSettingsOrCallback, callback) {
35736 if (typeof optionsOrSettingsOrCallback === 'function') {
35737 return new async$4.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
35740 new async$4.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
35743 exports.walk = walk;
35745 function walkSync(directory, optionsOrSettings) {
35746 const settings = getSettings(optionsOrSettings);
35747 const provider = new sync$4.default(directory, settings);
35748 return provider.read();
35751 exports.walkSync = walkSync;
35753 function walkStream(directory, optionsOrSettings) {
35754 const settings = getSettings(optionsOrSettings);
35755 const provider = new stream$3.default(directory, settings);
35756 return provider.read();
35759 exports.walkStream = walkStream;
35761 function getSettings(settingsOrOptions = {}) {
35762 if (settingsOrOptions instanceof settings$2.default) {
35763 return settingsOrOptions;
35766 return new settings$2.default(settingsOrOptions);
35770 var reader$1 = createCommonjsModule(function (module, exports) {
35772 Object.defineProperty(exports, "__esModule", {
35777 constructor(_settings) {
35778 this._settings = _settings;
35779 this._fsStatSettings = new out.Settings({
35780 followSymbolicLink: this._settings.followSymbolicLinks,
35781 fs: this._settings.fs,
35782 throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
35786 _getFullEntryPath(filepath) {
35787 return path__default['default'].resolve(this._settings.cwd, filepath);
35790 _makeEntry(stats, pattern) {
35794 dirent: utils$3.fs.createDirentFromStats(pattern, stats)
35797 if (this._settings.stats) {
35798 entry.stats = stats;
35804 _isFatalError(error) {
35805 return !utils$3.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
35810 exports.default = Reader;
35813 var stream$4 = createCommonjsModule(function (module, exports) {
35815 Object.defineProperty(exports, "__esModule", {
35819 class ReaderStream extends reader$1.default {
35821 super(...arguments);
35822 this._walkStream = out$2.walkStream;
35823 this._stat = out.stat;
35826 dynamic(root, options) {
35827 return this._walkStream(root, options);
35830 static(patterns, options) {
35831 const filepaths = patterns.map(this._getFullEntryPath, this);
35832 const stream = new stream_1__default['default'].PassThrough({
35836 stream._write = (index, _enc, done) => {
35837 return this._getEntry(filepaths[index], patterns[index], options).then(entry => {
35838 if (entry !== null && options.entryFilter(entry)) {
35839 stream.push(entry);
35842 if (index === filepaths.length - 1) {
35850 for (let i = 0; i < filepaths.length; i++) {
35857 _getEntry(filepath, pattern, options) {
35858 return this._getStat(filepath).then(stats => this._makeEntry(stats, pattern)).catch(error => {
35859 if (options.errorFilter(error)) {
35867 _getStat(filepath) {
35868 return new Promise((resolve, reject) => {
35869 this._stat(filepath, this._fsStatSettings, (error, stats) => {
35870 return error === null ? resolve(stats) : reject(error);
35877 exports.default = ReaderStream;
35880 var matcher = createCommonjsModule(function (module, exports) {
35882 Object.defineProperty(exports, "__esModule", {
35887 constructor(_patterns, _settings, _micromatchOptions) {
35888 this._patterns = _patterns;
35889 this._settings = _settings;
35890 this._micromatchOptions = _micromatchOptions;
35891 this._storage = [];
35893 this._fillStorage();
35898 * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
\r
35899 * So, before expand patterns with brace expansion into separated patterns.
\r
35901 const patterns = utils$3.pattern.expandPatternsWithBraceExpansion(this._patterns);
35903 for (const pattern of patterns) {
35904 const segments = this._getPatternSegments(pattern);
35906 const sections = this._splitSegmentsIntoSections(segments);
35908 this._storage.push({
35909 complete: sections.length <= 1,
35917 _getPatternSegments(pattern) {
35918 const parts = utils$3.pattern.getPatternParts(pattern, this._micromatchOptions);
35919 return parts.map(part => {
35920 const dynamic = utils$3.pattern.isDynamicPattern(part, this._settings);
35932 patternRe: utils$3.pattern.makeRe(part, this._micromatchOptions)
35937 _splitSegmentsIntoSections(segments) {
35938 return utils$3.array.splitWhen(segments, segment => segment.dynamic && utils$3.pattern.hasGlobStar(segment.pattern));
35943 exports.default = Matcher;
35946 var partial = createCommonjsModule(function (module, exports) {
35948 Object.defineProperty(exports, "__esModule", {
35952 class PartialMatcher extends matcher.default {
35954 const parts = filepath.split('/');
35955 const levels = parts.length;
35957 const patterns = this._storage.filter(info => !info.complete || info.segments.length > levels);
35959 for (const pattern of patterns) {
35960 const section = pattern.sections[0];
35962 * In this case, the pattern has a globstar and we must read all directories unconditionally,
\r
35963 * but only if the level has reached the end of the first group.
\r
35965 * fixtures/{a,b}/**
\r
35966 * ^ true/false ^ always true
\r
35969 if (!pattern.complete && levels > section.length) {
35973 const match = parts.every((part, index) => {
35974 const segment = pattern.segments[index];
35976 if (segment.dynamic && segment.patternRe.test(part)) {
35980 if (!segment.dynamic && segment.pattern === part) {
35997 exports.default = PartialMatcher;
36000 var deep = createCommonjsModule(function (module, exports) {
36002 Object.defineProperty(exports, "__esModule", {
36007 constructor(_settings, _micromatchOptions) {
36008 this._settings = _settings;
36009 this._micromatchOptions = _micromatchOptions;
36012 getFilter(basePath, positive, negative) {
36013 const matcher = this._getMatcher(positive);
36015 const negativeRe = this._getNegativePatternsRe(negative);
36017 return entry => this._filter(basePath, entry, matcher, negativeRe);
36020 _getMatcher(patterns) {
36021 return new partial.default(patterns, this._settings, this._micromatchOptions);
36024 _getNegativePatternsRe(patterns) {
36025 const affectDepthOfReadingPatterns = patterns.filter(utils$3.pattern.isAffectDepthOfReadingPattern);
36026 return utils$3.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
36029 _filter(basePath, entry, matcher, negativeRe) {
36030 if (this._isSkippedByDeep(basePath, entry.path)) {
36034 if (this._isSkippedSymbolicLink(entry)) {
36038 const filepath = utils$3.path.removeLeadingDotSegment(entry.path);
36040 if (this._isSkippedByPositivePatterns(filepath, matcher)) {
36044 return this._isSkippedByNegativePatterns(filepath, negativeRe);
36047 _isSkippedByDeep(basePath, entryPath) {
36049 * Avoid unnecessary depth calculations when it doesn't matter.
\r
36051 if (this._settings.deep === Infinity) {
36055 return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
36058 _getEntryLevel(basePath, entryPath) {
36059 const entryPathDepth = entryPath.split('/').length;
36061 if (basePath === '') {
36062 return entryPathDepth;
36065 const basePathDepth = basePath.split('/').length;
36066 return entryPathDepth - basePathDepth;
36069 _isSkippedSymbolicLink(entry) {
36070 return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
36073 _isSkippedByPositivePatterns(entryPath, matcher) {
36074 return !this._settings.baseNameMatch && !matcher.match(entryPath);
36077 _isSkippedByNegativePatterns(entryPath, patternsRe) {
36078 return !utils$3.pattern.matchAny(entryPath, patternsRe);
36083 exports.default = DeepFilter;
36086 var entry = createCommonjsModule(function (module, exports) {
36088 Object.defineProperty(exports, "__esModule", {
36092 class EntryFilter {
36093 constructor(_settings, _micromatchOptions) {
36094 this._settings = _settings;
36095 this._micromatchOptions = _micromatchOptions;
36096 this.index = new Map();
36099 getFilter(positive, negative) {
36100 const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions);
36101 const negativeRe = utils$3.pattern.convertPatternsToRe(negative, this._micromatchOptions);
36102 return entry => this._filter(entry, positiveRe, negativeRe);
36105 _filter(entry, positiveRe, negativeRe) {
36106 if (this._settings.unique && this._isDuplicateEntry(entry)) {
36110 if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
36114 if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
36118 const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
36119 const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
36121 if (this._settings.unique && isMatched) {
36122 this._createIndexRecord(entry);
36128 _isDuplicateEntry(entry) {
36129 return this.index.has(entry.path);
36132 _createIndexRecord(entry) {
36133 this.index.set(entry.path, undefined);
36136 _onlyFileFilter(entry) {
36137 return this._settings.onlyFiles && !entry.dirent.isFile();
36140 _onlyDirectoryFilter(entry) {
36141 return this._settings.onlyDirectories && !entry.dirent.isDirectory();
36144 _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
36145 if (!this._settings.absolute) {
36149 const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath);
36150 return utils$3.pattern.matchAny(fullpath, patternsRe);
36153 _isMatchToPatterns(entryPath, patternsRe) {
36154 const filepath = utils$3.path.removeLeadingDotSegment(entryPath);
36155 return utils$3.pattern.matchAny(filepath, patternsRe);
36160 exports.default = EntryFilter;
36163 var error = createCommonjsModule(function (module, exports) {
36165 Object.defineProperty(exports, "__esModule", {
36169 class ErrorFilter {
36170 constructor(_settings) {
36171 this._settings = _settings;
36175 return error => this._isNonFatalError(error);
36178 _isNonFatalError(error) {
36179 return utils$3.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
36184 exports.default = ErrorFilter;
36187 var entry$1 = createCommonjsModule(function (module, exports) {
36189 Object.defineProperty(exports, "__esModule", {
36193 class EntryTransformer {
36194 constructor(_settings) {
36195 this._settings = _settings;
36199 return entry => this._transform(entry);
36202 _transform(entry) {
36203 let filepath = entry.path;
36205 if (this._settings.absolute) {
36206 filepath = utils$3.path.makeAbsolute(this._settings.cwd, filepath);
36207 filepath = utils$3.path.unixify(filepath);
36210 if (this._settings.markDirectories && entry.dirent.isDirectory()) {
36214 if (!this._settings.objectMode) {
36218 return Object.assign(Object.assign({}, entry), {
36225 exports.default = EntryTransformer;
36228 var provider = createCommonjsModule(function (module, exports) {
36230 Object.defineProperty(exports, "__esModule", {
36235 constructor(_settings) {
36236 this._settings = _settings;
36237 this.errorFilter = new error.default(this._settings);
36238 this.entryFilter = new entry.default(this._settings, this._getMicromatchOptions());
36239 this.deepFilter = new deep.default(this._settings, this._getMicromatchOptions());
36240 this.entryTransformer = new entry$1.default(this._settings);
36243 _getRootDirectory(task) {
36244 return path__default['default'].resolve(this._settings.cwd, task.base);
36247 _getReaderOptions(task) {
36248 const basePath = task.base === '.' ? '' : task.base;
36251 pathSegmentSeparator: '/',
36252 concurrency: this._settings.concurrency,
36253 deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
36254 entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
36255 errorFilter: this.errorFilter.getFilter(),
36256 followSymbolicLinks: this._settings.followSymbolicLinks,
36257 fs: this._settings.fs,
36258 stats: this._settings.stats,
36259 throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
36260 transform: this.entryTransformer.getTransformer()
36264 _getMicromatchOptions() {
36266 dot: this._settings.dot,
36267 matchBase: this._settings.baseNameMatch,
36268 nobrace: !this._settings.braceExpansion,
36269 nocase: !this._settings.caseSensitiveMatch,
36270 noext: !this._settings.extglob,
36271 noglobstar: !this._settings.globstar,
36273 strictSlashes: false
36279 exports.default = Provider;
36282 var async$5 = createCommonjsModule(function (module, exports) {
36284 Object.defineProperty(exports, "__esModule", {
36288 class ProviderAsync extends provider.default {
36290 super(...arguments);
36291 this._reader = new stream$4.default(this._settings);
36295 const root = this._getRootDirectory(task);
36297 const options = this._getReaderOptions(task);
36299 const entries = [];
36300 return new Promise((resolve, reject) => {
36301 const stream = this.api(root, task, options);
36302 stream.once('error', reject);
36303 stream.on('data', entry => entries.push(options.transform(entry)));
36304 stream.once('end', () => resolve(entries));
36308 api(root, task, options) {
36309 if (task.dynamic) {
36310 return this._reader.dynamic(root, options);
36313 return this._reader.static(task.patterns, options);
36318 exports.default = ProviderAsync;
36321 var stream$5 = createCommonjsModule(function (module, exports) {
36323 Object.defineProperty(exports, "__esModule", {
36327 class ProviderStream extends provider.default {
36329 super(...arguments);
36330 this._reader = new stream$4.default(this._settings);
36334 const root = this._getRootDirectory(task);
36336 const options = this._getReaderOptions(task);
36338 const source = this.api(root, task, options);
36339 const destination = new stream_1__default['default'].Readable({
36343 source.once('error', error => destination.emit('error', error)).on('data', entry => destination.emit('data', options.transform(entry))).once('end', () => destination.emit('end'));
36344 destination.once('close', () => source.destroy());
36345 return destination;
36348 api(root, task, options) {
36349 if (task.dynamic) {
36350 return this._reader.dynamic(root, options);
36353 return this._reader.static(task.patterns, options);
36358 exports.default = ProviderStream;
36361 var sync$5 = createCommonjsModule(function (module, exports) {
36363 Object.defineProperty(exports, "__esModule", {
36367 class ReaderSync extends reader$1.default {
36369 super(...arguments);
36370 this._walkSync = out$2.walkSync;
36371 this._statSync = out.statSync;
36374 dynamic(root, options) {
36375 return this._walkSync(root, options);
36378 static(patterns, options) {
36379 const entries = [];
36381 for (const pattern of patterns) {
36382 const filepath = this._getFullEntryPath(pattern);
36384 const entry = this._getEntry(filepath, pattern, options);
36386 if (entry === null || !options.entryFilter(entry)) {
36390 entries.push(entry);
36396 _getEntry(filepath, pattern, options) {
36398 const stats = this._getStat(filepath);
36400 return this._makeEntry(stats, pattern);
36402 if (options.errorFilter(error)) {
36410 _getStat(filepath) {
36411 return this._statSync(filepath, this._fsStatSettings);
36416 exports.default = ReaderSync;
36419 var sync$6 = createCommonjsModule(function (module, exports) {
36421 Object.defineProperty(exports, "__esModule", {
36425 class ProviderSync extends provider.default {
36427 super(...arguments);
36428 this._reader = new sync$5.default(this._settings);
36432 const root = this._getRootDirectory(task);
36434 const options = this._getReaderOptions(task);
36436 const entries = this.api(root, task, options);
36437 return entries.map(options.transform);
36440 api(root, task, options) {
36441 if (task.dynamic) {
36442 return this._reader.dynamic(root, options);
36445 return this._reader.static(task.patterns, options);
36450 exports.default = ProviderSync;
36453 var settings$3 = createCommonjsModule(function (module, exports) {
36455 Object.defineProperty(exports, "__esModule", {
36458 exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
36459 const CPU_COUNT = os__default['default'].cpus().length;
36460 exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
36461 lstat: fs__default['default'].lstat,
36462 lstatSync: fs__default['default'].lstatSync,
36463 stat: fs__default['default'].stat,
36464 statSync: fs__default['default'].statSync,
36465 readdir: fs__default['default'].readdir,
36466 readdirSync: fs__default['default'].readdirSync
36470 constructor(_options = {}) {
36471 this._options = _options;
36472 this.absolute = this._getValue(this._options.absolute, false);
36473 this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
36474 this.braceExpansion = this._getValue(this._options.braceExpansion, true);
36475 this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
36476 this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
36477 this.cwd = this._getValue(this._options.cwd, process.cwd());
36478 this.deep = this._getValue(this._options.deep, Infinity);
36479 this.dot = this._getValue(this._options.dot, false);
36480 this.extglob = this._getValue(this._options.extglob, true);
36481 this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
36482 this.fs = this._getFileSystemMethods(this._options.fs);
36483 this.globstar = this._getValue(this._options.globstar, true);
36484 this.ignore = this._getValue(this._options.ignore, []);
36485 this.markDirectories = this._getValue(this._options.markDirectories, false);
36486 this.objectMode = this._getValue(this._options.objectMode, false);
36487 this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
36488 this.onlyFiles = this._getValue(this._options.onlyFiles, true);
36489 this.stats = this._getValue(this._options.stats, false);
36490 this.suppressErrors = this._getValue(this._options.suppressErrors, false);
36491 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
36492 this.unique = this._getValue(this._options.unique, true);
36494 if (this.onlyDirectories) {
36495 this.onlyFiles = false;
36499 this.objectMode = true;
36503 _getValue(option, value) {
36504 return option === undefined ? value : option;
36507 _getFileSystemMethods(methods = {}) {
36508 return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
36513 exports.default = Settings;
36516 async function FastGlob(source, options) {
36517 assertPatternsInput(source);
36518 const works = getWorks(source, async$5.default, options);
36519 const result = await Promise.all(works);
36520 return utils$3.array.flatten(result);
36521 } // https://github.com/typescript-eslint/typescript-eslint/issues/60
36522 // eslint-disable-next-line no-redeclare
36525 (function (FastGlob) {
36526 function sync(source, options) {
36527 assertPatternsInput(source);
36528 const works = getWorks(source, sync$6.default, options);
36529 return utils$3.array.flatten(works);
36532 FastGlob.sync = sync;
36534 function stream(source, options) {
36535 assertPatternsInput(source);
36536 const works = getWorks(source, stream$5.default, options);
36538 * The stream returned by the provider cannot work with an asynchronous iterator.
\r
36539 * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
\r
36540 * This affects performance (+25%). I don't see best solution right now.
\r
36543 return utils$3.stream.merge(works);
36546 FastGlob.stream = stream;
36548 function generateTasks(source, options) {
36549 assertPatternsInput(source);
36550 const patterns = [].concat(source);
36551 const settings = new settings$3.default(options);
36552 return tasks.generate(patterns, settings);
36555 FastGlob.generateTasks = generateTasks;
36557 function isDynamicPattern(source, options) {
36558 assertPatternsInput(source);
36559 const settings = new settings$3.default(options);
36560 return utils$3.pattern.isDynamicPattern(source, settings);
36563 FastGlob.isDynamicPattern = isDynamicPattern;
36565 function escapePath(source) {
36566 assertPatternsInput(source);
36567 return utils$3.path.escape(source);
36570 FastGlob.escapePath = escapePath;
36571 })(FastGlob || (FastGlob = {}));
36573 function getWorks(source, _Provider, options) {
36574 const patterns = [].concat(source);
36575 const settings = new settings$3.default(options);
36576 const tasks$1 = tasks.generate(patterns, settings);
36577 const provider = new _Provider(settings);
36578 return tasks$1.map(provider.read, provider);
36581 function assertPatternsInput(input) {
36582 const source = [].concat(input);
36583 const isValidSource = source.every(item => utils$3.string.isString(item) && !utils$3.string.isEmpty(item));
36585 if (!isValidSource) {
36586 throw new TypeError('Patterns must be a string (non empty) or an array of strings');
36590 var out$3 = FastGlob;
36594 } = util__default['default'];
36596 async function isType(fsStatType, statsMethodName, filePath) {
36597 if (typeof filePath !== 'string') {
36598 throw new TypeError(`Expected a string, got ${typeof filePath}`);
36602 const stats = await promisify(fs__default['default'][fsStatType])(filePath);
36603 return stats[statsMethodName]();
36605 if (error.code === 'ENOENT') {
36613 function isTypeSync(fsStatType, statsMethodName, filePath) {
36614 if (typeof filePath !== 'string') {
36615 throw new TypeError(`Expected a string, got ${typeof filePath}`);
36619 return fs__default['default'][fsStatType](filePath)[statsMethodName]();
36621 if (error.code === 'ENOENT') {
36629 var isFile = isType.bind(null, 'stat', 'isFile');
36630 var isDirectory = isType.bind(null, 'stat', 'isDirectory');
36631 var isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink');
36632 var isFileSync = isTypeSync.bind(null, 'statSync', 'isFile');
36633 var isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory');
36634 var isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink');
36637 isDirectory: isDirectory,
36638 isSymlink: isSymlink,
36639 isFileSync: isFileSync,
36640 isDirectorySync: isDirectorySync,
36641 isSymlinkSync: isSymlinkSync
36644 const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0];
36646 const getPath = (filepath, cwd) => {
36647 const pth = filepath[0] === '!' ? filepath.slice(1) : filepath;
36648 return path__default['default'].isAbsolute(pth) ? pth : path__default['default'].join(cwd, pth);
36651 const addExtensions = (file, extensions) => {
36652 if (path__default['default'].extname(file)) {
36653 return `**/${file}`;
36656 return `**/${file}.${getExtensions(extensions)}`;
36659 const getGlob = (directory, options) => {
36660 if (options.files && !Array.isArray(options.files)) {
36661 throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``);
36664 if (options.extensions && !Array.isArray(options.extensions)) {
36665 throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``);
36668 if (options.files && options.extensions) {
36669 return options.files.map(x => path__default['default'].posix.join(directory, addExtensions(x, options.extensions)));
36672 if (options.files) {
36673 return options.files.map(x => path__default['default'].posix.join(directory, `**/${x}`));
36676 if (options.extensions) {
36677 return [path__default['default'].posix.join(directory, `**/*.${getExtensions(options.extensions)}`)];
36680 return [path__default['default'].posix.join(directory, '**')];
36683 var dirGlob = async (input, options) => {
36684 options = Object.assign({
36688 if (typeof options.cwd !== 'string') {
36689 throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);
36692 const globs = await Promise.all([].concat(input).map(async x => {
36693 const isDirectory = await pathType.isDirectory(getPath(x, options.cwd));
36694 return isDirectory ? getGlob(x, options) : x;
36696 return [].concat.apply([], globs); // eslint-disable-line prefer-spread
36699 var sync$7 = (input, options) => {
36700 options = Object.assign({
36704 if (typeof options.cwd !== 'string') {
36705 throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``);
36708 const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x);
36709 return [].concat.apply([], globs); // eslint-disable-line prefer-spread
36711 dirGlob.sync = sync$7;
36713 // A simple implementation of make-array
36714 function makeArray(subject) {
36715 return Array.isArray(subject) ? subject : [subject];
36720 const ESCAPE = '\\';
36721 const REGEX_TEST_BLANK_LINE = /^\s+$/;
36722 const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
36723 const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
36724 const REGEX_SPLITALL_CRLF = /\r?\n/g; // /foo,
36730 const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
36731 const SLASH$1 = '/';
36732 const KEY_IGNORE$1 = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
36733 /* istanbul ignore next */
36736 const define$1 = (object, key, value) => Object.defineProperty(object, key, {
36740 const REGEX_REGEXP_RANGE$1 = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression
36741 // The cases are complicated, see test cases for details
36743 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
36744 // fatal for JavaScript regular expression, so eliminate it.
36745 : EMPTY); // See fixtures #59
36748 const cleanRangeBackSlash = slashes => {
36752 return slashes.slice(0, length - length % 2);
36753 }; // > If the pattern ends with a slash,
36754 // > it is removed for the purpose of the following description,
36755 // > but it would only find a match with a directory.
36756 // > In other words, foo/ will match a directory foo and paths underneath it,
36757 // > but will not match a regular file or a symbolic link foo
36758 // > (this is consistent with the way how pathspec works in general in Git).
36759 // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
36760 // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
36761 // you could use option `mark: true` with `glob`
36762 // '`foo/`' should not continue with the '`..`'
36765 const REPLACERS = [// > Trailing spaces are ignored unless they are quoted with backslash ("\")
36769 /\\?\s+$/, match => match.indexOf('\\') === 0 ? SPACE : EMPTY], // replace (\ ) with ' '
36770 [/\\\s/g, () => SPACE], // Escape metacharacters
36771 // which is written down by users but means special for regular expressions.
36772 // > There are 12 characters with special meanings:
36773 // > - the backslash \,
36774 // > - the caret ^,
36775 // > - the dollar sign $,
36776 // > - the period or dot .,
36777 // > - the vertical bar or pipe symbol |,
36778 // > - the question mark ?,
36779 // > - the asterisk or star *,
36780 // > - the plus sign +,
36781 // > - the opening parenthesis (,
36782 // > - the closing parenthesis ),
36783 // > - and the opening square bracket [,
36784 // > - the opening curly brace {,
36785 // > These special characters are often called "metacharacters".
36786 [/[\\$.|*+(){^]/g, match => `\\${match}`], [// > a question mark (?) matches a single character
36787 /(?!\\)\?/g, () => '[^/]'], // leading slash
36788 [// > A leading slash matches the beginning of the pathname.
36789 // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
36790 // A leading slash matches the beginning of the pathname
36791 /^\//, () => '^'], // replace special metacharacter slash after the leading slash
36792 [/\//g, () => '\\/'], [// > A leading "**" followed by a slash means match in all directories.
36793 // > For example, "**/foo" matches file or directory "foo" anywhere,
36794 // > the same as pattern "foo".
36795 // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
36796 // > under directory "foo".
36797 // Notice that the '*'s have been replaced as '\\*'
36798 /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo'
36799 () => '^(?:.*\\/)?'], // starting
36800 [// there will be no leading '/'
36801 // (which has been replaced by section "leading slash")
36802 // If starts with '**', adding a '^' to the regular expression also works
36803 /^(?=[^^])/, function startingReplacer() {
36804 // If has a slash `/` at the beginning or middle
36805 return !/\/(?!$)/.test(this) // > Prior to 2.22.1
36806 // > If the pattern does not contain a slash /,
36807 // > Git treats it as a shell glob pattern
36808 // Actually, if there is only a trailing slash,
36809 // git also treats it as a shell glob pattern
36810 // After 2.22.1 (compatible but clearer)
36811 // > If there is a separator at the beginning or middle (or both)
36812 // > of the pattern, then the pattern is relative to the directory
36813 // > level of the particular .gitignore file itself.
36814 // > Otherwise the pattern may also match at any level below
36815 // > the .gitignore level.
36816 ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for
36817 // > consumption by fnmatch(3)
36819 }], // two globstars
36820 [// Use lookahead assertions so that we could match more than one `'/**'`
36821 /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories
36822 // should not use '*', or it will be replaced by the next replacer
36823 // Check if it is not the last `'/**'`
36824 (_, index, str) => index + 6 < str.length // case: /**/
36825 // > A slash followed by two consecutive asterisks then a slash matches
36826 // > zero or more directories.
36827 // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
36829 ? '(?:\\/[^\\/]+)*' // case: /**
36830 // > A trailing `"/**"` matches everything inside.
36831 // #21: everything inside but it should not include the current folder
36832 : '\\/.+'], // intermediate wildcards
36833 [// Never replace escaped '*'
36834 // ignore rule '\*' will match the path '*'
36836 // 'abc.*' -> skip this rule
36837 /(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js'
36838 // '*.js' doesn't match 'abc'
36839 (_, p1) => `${p1}[^\\/]*`], [// unescape, revert step 3 except for back slash
36840 // For example, if a user escape a '\\*',
36841 // after step 3, the result will be '\\\\\\*'
36842 /\\\\\\(?=[$.|*+(){^])/g, () => ESCAPE], [// '\\\\' -> '\\'
36843 /\\\\/g, () => ESCAPE], [// > The range notation, e.g. [a-zA-Z],
36844 // > can be used to match one of the characters in a range.
36845 // `\` is escaped by step 3
36846 /(\\)?\[([^\]/]*?)(\\*)($|\])/g, (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE // '\\[bar]' -> '\\\\[bar\\]'
36847 ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === ']' ? endEscape.length % 2 === 0 // A normal case, and it is a range notation
36850 ? `[${sanitizeRange$1(range)}${endEscape}]` // Invalid range notaton
36851 // '[bar\\]' -> '[bar\\\\]'
36852 : '[]' : '[]'], // ending
36853 [// 'js' will not match 'js.'
36854 // 'ab' will not match 'abc'
36855 /(?:[^*])$/, // WTF!
36856 // https://git-scm.com/docs/gitignore
36857 // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
36858 // which re-fixes #24, #38
36859 // > If there is a separator at the end of the pattern then the pattern
36860 // > will only match directories, otherwise the pattern can match both
36861 // > files and directories.
36862 // 'js*' will not match 'a.js'
36863 // 'js/' will not match 'a.js'
36864 // 'js' will match 'a.js' and 'a.js/'
36865 match => /\/$/.test(match) // foo/ will not match 'foo'
36866 ? `${match}$` // foo matches 'foo' and 'foo/'
36867 : `${match}(?=$|\\/$)`], // trailing wildcard
36868 [/(\^|\\\/)?\\\*$/, (_, p1) => {
36869 const prefix = p1 // '\^':
36870 // '/*' does not match EMPTY
36871 // '/*' does not match everything
36873 // 'abc/*' does not match 'abc/'
36874 ? `${p1}[^/]+` // 'a*' matches 'a'
36875 // 'a*' matches 'aa'
36877 return `${prefix}(?=$|\\/$)`;
36878 }]]; // A simple cache, because an ignore rule only has only one certain meaning
36880 const regexCache = Object.create(null); // @param {pattern}
36882 const makeRegex = (pattern, negative, ignorecase) => {
36883 const r = regexCache[pattern];
36887 } // const replacers = negative
36888 // ? NEGATIVE_REPLACERS
36889 // : POSITIVE_REPLACERS
36892 const source = REPLACERS.reduce((prev, current) => prev.replace(current[0], current[1].bind(pattern)), pattern);
36893 return regexCache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source);
36896 const isString = subject => typeof subject === 'string'; // > A blank line matches no files, so it can serve as a separator for readability.
36899 const checkPattern$1 = pattern => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment.
36900 && pattern.indexOf('#') !== 0;
36902 const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF);
36905 constructor(origin, pattern, negative, regex) {
36906 this.origin = origin;
36907 this.pattern = pattern;
36908 this.negative = negative;
36909 this.regex = regex;
36914 const createRule$1 = (pattern, ignorecase) => {
36915 const origin = pattern;
36916 let negative = false; // > An optional prefix "!" which negates the pattern;
36918 if (pattern.indexOf('!') === 0) {
36920 pattern = pattern.substr(1);
36923 pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that
36924 // > begin with a literal "!", for example, `"\!important!.txt"`.
36925 .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that
36926 // > begin with a hash.
36927 .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#');
36928 const regex = makeRegex(pattern, negative, ignorecase);
36929 return new IgnoreRule(origin, pattern, negative, regex);
36932 const throwError = (message, Ctor) => {
36933 throw new Ctor(message);
36936 const checkPath = (path, originalPath, doThrow) => {
36937 if (!isString(path)) {
36938 return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
36939 } // We don't know if we should ignore EMPTY, so throw
36943 return doThrow(`path must not be empty`, TypeError);
36944 } // Check if it is a relative path
36947 if (checkPath.isNotRelative(path)) {
36948 const r = '`path.relative()`d';
36949 return doThrow(`path should be a ${r} string, but got "${originalPath}"`, RangeError);
36955 const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path);
36957 checkPath.isNotRelative = isNotRelative;
36959 checkPath.convert = p => p;
36966 this._ignorecase = ignorecase;
36967 define$1(this, KEY_IGNORE$1, true);
36973 this._ignoreCache = Object.create(null);
36974 this._testCache = Object.create(null);
36977 _addPattern(pattern) {
36979 if (pattern && pattern[KEY_IGNORE$1]) {
36980 this._rules = this._rules.concat(pattern._rules);
36981 this._added = true;
36985 if (checkPattern$1(pattern)) {
36986 const rule = createRule$1(pattern, this._ignorecase);
36987 this._added = true;
36989 this._rules.push(rule);
36991 } // @param {Array<string> | string | Ignore} pattern
36995 this._added = false;
36996 makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore,
36997 // making the behavior changed.
37007 addPattern(pattern) {
37008 return this.add(pattern);
37009 } // | ignored : unignored
37010 // negative | 0:0 | 0:1 | 1:0 | 1:1
37011 // -------- | ------- | ------- | ------- | --------
37012 // 0 | TEST | TEST | SKIP | X
37013 // 1 | TESTIF | SKIP | TEST | X
37014 // - SKIP: always skip
37015 // - TEST: always test
37016 // - TESTIF: only test if checkUnignored
37017 // - X: that never happen
37018 // @param {boolean} whether should check if the path is unignored,
37019 // setting `checkUnignored` to `false` could reduce additional
37021 // @returns {TestResult} true if a file is ignored
37024 _testOne(path, checkUnignored) {
37025 let ignored = false;
37026 let unignored = false;
37028 this._rules.forEach(rule => {
37033 if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
37037 const matched = rule.regex.test(path);
37040 ignored = !negative;
37041 unignored = negative;
37049 } // @returns {TestResult}
37052 _test(originalPath, cache, checkUnignored, slices) {
37053 const path = originalPath // Supports nullable path
37054 && checkPath.convert(originalPath);
37055 checkPath(path, originalPath, throwError);
37056 return this._t(path, cache, checkUnignored, slices);
37059 _t(path, cache, checkUnignored, slices) {
37060 if (path in cache) {
37061 return cache[path];
37066 // ['path', 'to', 'a.js']
37067 slices = path.split(SLASH$1);
37070 slices.pop(); // If the path has no parent directory, just test it
37072 if (!slices.length) {
37073 return cache[path] = this._testOne(path, checkUnignored);
37076 const parent = this._t(slices.join(SLASH$1) + SLASH$1, cache, checkUnignored, slices); // If the path contains a parent directory, check the parent first
37079 return cache[path] = parent.ignored // > It is not possible to re-include a file if a parent directory of
37080 // > that file is excluded.
37081 ? parent : this._testOne(path, checkUnignored);
37085 return this._test(path, this._ignoreCache, false).ignored;
37089 return path => !this.ignores(path);
37093 return makeArray(paths).filter(this.createFilter());
37094 } // @returns {TestResult}
37098 return this._test(path, this._testCache, true);
37103 const factory = options => new Ignore(options);
37105 const returnFalse = () => false;
37107 const isPathValid = path => checkPath(path && checkPath.convert(path), path, returnFalse);
37109 factory.isPathValid = isPathValid; // Fixes typescript
37111 factory.default = factory;
37112 var ignore$1 = factory; // Windows
37113 // --------------------------------------------------------------
37115 /* istanbul ignore if */
37117 if ( // Detect `process` so that it can run in browsers.
37118 typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
37119 /* eslint no-control-regex: "off" */
37120 const makePosix = str => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, '/');
37122 checkPath.convert = makePosix; // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/'
37125 const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
37127 checkPath.isNotRelative = path => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);
37130 var slash$1 = path => {
37131 const isExtendedLengthPath = /^\\\\\?\\/.test(path);
37132 const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex
37134 if (isExtendedLengthPath || hasNonAscii) {
37138 return path.replace(/\\/g, '/');
37142 promisify: promisify$1
37143 } = util__default['default'];
37144 const DEFAULT_IGNORE = ['**/node_modules/**', '**/flow-typed/**', '**/coverage/**', '**/.git'];
37145 const readFileP = promisify$1(fs__default['default'].readFile);
37147 const mapGitIgnorePatternTo = base => ignore => {
37148 if (ignore.startsWith('!')) {
37149 return '!' + path__default['default'].posix.join(base, ignore.slice(1));
37152 return path__default['default'].posix.join(base, ignore);
37155 const parseGitIgnore = (content, options) => {
37156 const base = slash$1(path__default['default'].relative(options.cwd, path__default['default'].dirname(options.fileName)));
37157 return content.split(/\r?\n/).filter(Boolean).filter(line => !line.startsWith('#')).map(mapGitIgnorePatternTo(base));
37160 const reduceIgnore = files => {
37161 return files.reduce((ignores, file) => {
37162 ignores.add(parseGitIgnore(file.content, {
37164 fileName: file.filePath
37170 const ensureAbsolutePathForCwd = (cwd, p) => {
37171 cwd = slash$1(cwd);
37173 if (path__default['default'].isAbsolute(p)) {
37174 if (p.startsWith(cwd)) {
37178 throw new Error(`Path ${p} is not in cwd ${cwd}`);
37181 return path__default['default'].join(cwd, p);
37184 const getIsIgnoredPredecate = (ignores, cwd) => {
37185 return p => ignores.ignores(slash$1(path__default['default'].relative(cwd, ensureAbsolutePathForCwd(cwd, p))));
37188 const getFile = async (file, cwd) => {
37189 const filePath = path__default['default'].join(cwd, file);
37190 const content = await readFileP(filePath, 'utf8');
37198 const getFileSync = (file, cwd) => {
37199 const filePath = path__default['default'].join(cwd, file);
37200 const content = fs__default['default'].readFileSync(filePath, 'utf8');
37208 const normalizeOptions$3 = ({
37210 cwd = slash$1(process.cwd())
37218 var gitignore = async options => {
37219 options = normalizeOptions$3(options);
37220 const paths = await out$3('**/.gitignore', {
37221 ignore: DEFAULT_IGNORE.concat(options.ignore),
37224 const files = await Promise.all(paths.map(file => getFile(file, options.cwd)));
37225 const ignores = reduceIgnore(files);
37226 return getIsIgnoredPredecate(ignores, options.cwd);
37229 var sync$8 = options => {
37230 options = normalizeOptions$3(options);
37231 const paths = out$3.sync('**/.gitignore', {
37232 ignore: DEFAULT_IGNORE.concat(options.ignore),
37235 const files = paths.map(file => getFileSync(file, options.cwd));
37236 const ignores = reduceIgnore(files);
37237 return getIsIgnoredPredecate(ignores, options.cwd);
37239 gitignore.sync = sync$8;
37243 } = stream_1__default['default'];
37245 class ObjectTransform extends Transform {
37254 class FilterStream extends ObjectTransform {
37255 constructor(filter) {
37257 this._filter = filter;
37260 _transform(data, encoding, callback) {
37261 if (this._filter(data)) {
37270 class UniqueStream extends ObjectTransform {
37273 this._pushed = new Set();
37276 _transform(data, encoding, callback) {
37277 if (!this._pushed.has(data)) {
37280 this._pushed.add(data);
37288 var streamUtils = {
37294 FilterStream: FilterStream$1,
37295 UniqueStream: UniqueStream$1
37298 const DEFAULT_FILTER = () => false;
37300 const isNegative = pattern => pattern[0] === '!';
37302 const assertPatternsInput$1 = patterns => {
37303 if (!patterns.every(pattern => typeof pattern === 'string')) {
37304 throw new TypeError('Patterns must be a string or an array of strings');
37308 const checkCwdOption = (options = {}) => {
37309 if (!options.cwd) {
37316 stat = fs__default['default'].statSync(options.cwd);
37321 if (!stat.isDirectory()) {
37322 throw new Error('The `cwd` option must be a path to a directory');
37326 const getPathString = p => p.stats instanceof fs__default['default'].Stats ? p.path : p;
37328 const generateGlobTasks = (patterns, taskOptions) => {
37329 patterns = arrayUnion([].concat(patterns));
37330 assertPatternsInput$1(patterns);
37331 checkCwdOption(taskOptions);
37332 const globTasks = [];
37333 taskOptions = Object.assign({
37335 expandDirectories: true
37338 for (const [index, pattern] of patterns.entries()) {
37339 if (isNegative(pattern)) {
37343 const ignore = patterns.slice(index).filter(isNegative).map(pattern => pattern.slice(1));
37344 const options = Object.assign({}, taskOptions, {
37345 ignore: taskOptions.ignore.concat(ignore)
37356 const globDirs = (task, fn) => {
37359 if (task.options.cwd) {
37360 options.cwd = task.options.cwd;
37363 if (Array.isArray(task.options.expandDirectories)) {
37364 options = Object.assign({}, options, {
37365 files: task.options.expandDirectories
37367 } else if (typeof task.options.expandDirectories === 'object') {
37368 options = Object.assign({}, options, task.options.expandDirectories);
37371 return fn(task.pattern, options);
37374 const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern];
37376 const getFilterSync = options => {
37377 return options && options.gitignore ? gitignore.sync({
37379 ignore: options.ignore
37380 }) : DEFAULT_FILTER;
37383 const globToTask = task => glob => {
37388 if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) {
37389 options.ignore = dirGlob.sync(options.ignore);
37398 var globby$1 = async (patterns, options) => {
37399 const globTasks = generateGlobTasks(patterns, options);
37401 const getFilter = async () => {
37402 return options && options.gitignore ? gitignore({
37404 ignore: options.ignore
37405 }) : DEFAULT_FILTER;
37408 const getTasks = async () => {
37409 const tasks = await Promise.all(globTasks.map(async task => {
37410 const globs = await getPattern(task, dirGlob);
37411 return Promise.all(globs.map(globToTask(task)));
37413 return arrayUnion(...tasks);
37416 const [filter, tasks] = await Promise.all([getFilter(), getTasks()]);
37417 const paths = await Promise.all(tasks.map(task => out$3(task.pattern, task.options)));
37418 return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_)));
37421 var sync$9 = (patterns, options) => {
37422 const globTasks = generateGlobTasks(patterns, options);
37423 const tasks = globTasks.reduce((tasks, task) => {
37424 const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
37425 return tasks.concat(newTask);
37427 const filter = getFilterSync(options);
37428 return tasks.reduce((matches, task) => arrayUnion(matches, out$3.sync(task.pattern, task.options)), []).filter(path_ => !filter(path_));
37431 var stream$6 = (patterns, options) => {
37432 const globTasks = generateGlobTasks(patterns, options);
37433 const tasks = globTasks.reduce((tasks, task) => {
37434 const newTask = getPattern(task, dirGlob.sync).map(globToTask(task));
37435 return tasks.concat(newTask);
37437 const filter = getFilterSync(options);
37438 const filterStream = new FilterStream$1(p => !filter(p));
37439 const uniqueStream = new UniqueStream$1();
37440 return merge2_1(tasks.map(task => out$3.stream(task.pattern, task.options))).pipe(filterStream).pipe(uniqueStream);
37443 var generateGlobTasks_1 = generateGlobTasks;
37445 var hasMagic = (patterns, options) => [].concat(patterns).some(pattern => out$3.isDynamicPattern(pattern, options));
37447 var gitignore_1 = gitignore;
37448 globby$1.sync = sync$9;
37449 globby$1.stream = stream$6;
37450 globby$1.generateGlobTasks = generateGlobTasks_1;
37451 globby$1.hasMagic = hasMagic;
37452 globby$1.gitignore = gitignore_1;
37454 var createLanguage = function (linguistData, override) {
37458 rest = _objectWithoutPropertiesLoose(linguistData, ["languageId"]);
37460 return Object.assign({
37461 linguistLanguageId: languageId
37462 }, rest, override(linguistData));
37465 var ast = createCommonjsModule(function (module) {
37467 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
37469 Redistribution and use in source and binary forms, with or without
37470 modification, are permitted provided that the following conditions are met:
37472 * Redistributions of source code must retain the above copyright
37473 notice, this list of conditions and the following disclaimer.
37474 * Redistributions in binary form must reproduce the above copyright
37475 notice, this list of conditions and the following disclaimer in the
37476 documentation and/or other materials provided with the distribution.
37478 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
37479 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37480 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
37481 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
37482 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
37483 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37484 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
37485 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37486 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37487 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37491 function isExpression(node) {
37492 if (node == null) {
37496 switch (node.type) {
37497 case 'ArrayExpression':
37498 case 'AssignmentExpression':
37499 case 'BinaryExpression':
37500 case 'CallExpression':
37501 case 'ConditionalExpression':
37502 case 'FunctionExpression':
37505 case 'LogicalExpression':
37506 case 'MemberExpression':
37507 case 'NewExpression':
37508 case 'ObjectExpression':
37509 case 'SequenceExpression':
37510 case 'ThisExpression':
37511 case 'UnaryExpression':
37512 case 'UpdateExpression':
37519 function isIterationStatement(node) {
37520 if (node == null) {
37524 switch (node.type) {
37525 case 'DoWhileStatement':
37526 case 'ForInStatement':
37527 case 'ForStatement':
37528 case 'WhileStatement':
37535 function isStatement(node) {
37536 if (node == null) {
37540 switch (node.type) {
37541 case 'BlockStatement':
37542 case 'BreakStatement':
37543 case 'ContinueStatement':
37544 case 'DebuggerStatement':
37545 case 'DoWhileStatement':
37546 case 'EmptyStatement':
37547 case 'ExpressionStatement':
37548 case 'ForInStatement':
37549 case 'ForStatement':
37550 case 'IfStatement':
37551 case 'LabeledStatement':
37552 case 'ReturnStatement':
37553 case 'SwitchStatement':
37554 case 'ThrowStatement':
37555 case 'TryStatement':
37556 case 'VariableDeclaration':
37557 case 'WhileStatement':
37558 case 'WithStatement':
37565 function isSourceElement(node) {
37566 return isStatement(node) || node != null && node.type === 'FunctionDeclaration';
37569 function trailingStatement(node) {
37570 switch (node.type) {
37571 case 'IfStatement':
37572 if (node.alternate != null) {
37573 return node.alternate;
37576 return node.consequent;
37578 case 'LabeledStatement':
37579 case 'ForStatement':
37580 case 'ForInStatement':
37581 case 'WhileStatement':
37582 case 'WithStatement':
37589 function isProblematicIfStatement(node) {
37592 if (node.type !== 'IfStatement') {
37596 if (node.alternate == null) {
37600 current = node.consequent;
37603 if (current.type === 'IfStatement') {
37604 if (current.alternate == null) {
37609 current = trailingStatement(current);
37616 isExpression: isExpression,
37617 isStatement: isStatement,
37618 isIterationStatement: isIterationStatement,
37619 isSourceElement: isSourceElement,
37620 isProblematicIfStatement: isProblematicIfStatement,
37621 trailingStatement: trailingStatement
37624 /* vim: set sw=4 ts=4 et tw=80 : */
37628 var code = createCommonjsModule(function (module) {
37630 Copyright (C) 2013-2014 Yusuke Suzuki <utatane.tea@gmail.com>
37631 Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
37633 Redistribution and use in source and binary forms, with or without
37634 modification, are permitted provided that the following conditions are met:
37636 * Redistributions of source code must retain the above copyright
37637 notice, this list of conditions and the following disclaimer.
37638 * Redistributions in binary form must reproduce the above copyright
37639 notice, this list of conditions and the following disclaimer in the
37640 documentation and/or other materials provided with the distribution.
37642 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
37643 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37644 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
37645 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
37646 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
37647 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37648 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
37649 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37650 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37651 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37655 var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`.
37658 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart:
37659 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]/,
37660 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart:
37661 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]/
37664 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart:
37665 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]/,
37666 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart:
37667 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]/
37670 function isDecimalDigit(ch) {
37671 return 0x30 <= ch && ch <= 0x39; // 0..9
37674 function isHexDigit(ch) {
37675 return 0x30 <= ch && ch <= 0x39 || // 0..9
37676 0x61 <= ch && ch <= 0x66 || // a..f
37677 0x41 <= ch && ch <= 0x46; // A..F
37680 function isOctalDigit(ch) {
37681 return ch >= 0x30 && ch <= 0x37; // 0..7
37682 } // 7.2 White Space
37685 NON_ASCII_WHITESPACES = [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF];
37687 function isWhiteSpace(ch) {
37688 return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
37689 } // 7.3 Line Terminators
37692 function isLineTerminator(ch) {
37693 return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;
37694 } // 7.6 Identifier Names and Identifiers
37697 function fromCodePoint(cp) {
37698 if (cp <= 0xFFFF) {
37699 return String.fromCharCode(cp);
37702 var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800);
37703 var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00);
37707 IDENTIFIER_START = new Array(0x80);
37709 for (ch = 0; ch < 0x80; ++ch) {
37710 IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
37711 ch >= 0x41 && ch <= 0x5A || // A..Z
37712 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
37715 IDENTIFIER_PART = new Array(0x80);
37717 for (ch = 0; ch < 0x80; ++ch) {
37718 IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
37719 ch >= 0x41 && ch <= 0x5A || // A..Z
37720 ch >= 0x30 && ch <= 0x39 || // 0..9
37721 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
37724 function isIdentifierStartES5(ch) {
37725 return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
37728 function isIdentifierPartES5(ch) {
37729 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
37732 function isIdentifierStartES6(ch) {
37733 return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
37736 function isIdentifierPartES6(ch) {
37737 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
37741 isDecimalDigit: isDecimalDigit,
37742 isHexDigit: isHexDigit,
37743 isOctalDigit: isOctalDigit,
37744 isWhiteSpace: isWhiteSpace,
37745 isLineTerminator: isLineTerminator,
37746 isIdentifierStartES5: isIdentifierStartES5,
37747 isIdentifierPartES5: isIdentifierPartES5,
37748 isIdentifierStartES6: isIdentifierStartES6,
37749 isIdentifierPartES6: isIdentifierPartES6
37752 /* vim: set sw=4 ts=4 et tw=80 : */
37756 var keyword$1 = createCommonjsModule(function (module) {
37758 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
37760 Redistribution and use in source and binary forms, with or without
37761 modification, are permitted provided that the following conditions are met:
37763 * Redistributions of source code must retain the above copyright
37764 notice, this list of conditions and the following disclaimer.
37765 * Redistributions in binary form must reproduce the above copyright
37766 notice, this list of conditions and the following disclaimer in the
37767 documentation and/or other materials provided with the distribution.
37769 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
37770 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37771 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
37772 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
37773 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
37774 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37775 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
37776 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37777 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37778 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37784 function isStrictModeReservedWordES6(id) {
37801 function isKeywordES5(id, strict) {
37802 // yield should not be treated as keyword under non-strict mode.
37803 if (!strict && id === 'yield') {
37807 return isKeywordES6(id, strict);
37810 function isKeywordES6(id, strict) {
37811 if (strict && isStrictModeReservedWordES6(id)) {
37815 switch (id.length) {
37817 return id === 'if' || id === 'in' || id === 'do';
37820 return id === 'var' || id === 'for' || id === 'new' || id === 'try';
37823 return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum';
37826 return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super';
37829 return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import';
37832 return id === 'default' || id === 'finally' || id === 'extends';
37835 return id === 'function' || id === 'continue' || id === 'debugger';
37838 return id === 'instanceof';
37845 function isReservedWordES5(id, strict) {
37846 return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict);
37849 function isReservedWordES6(id, strict) {
37850 return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict);
37853 function isRestrictedWord(id) {
37854 return id === 'eval' || id === 'arguments';
37857 function isIdentifierNameES5(id) {
37860 if (id.length === 0) {
37864 ch = id.charCodeAt(0);
37866 if (!code$1.isIdentifierStartES5(ch)) {
37870 for (i = 1, iz = id.length; i < iz; ++i) {
37871 ch = id.charCodeAt(i);
37873 if (!code$1.isIdentifierPartES5(ch)) {
37881 function decodeUtf16(lead, trail) {
37882 return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
37885 function isIdentifierNameES6(id) {
37886 var i, iz, ch, lowCh, check;
37888 if (id.length === 0) {
37892 check = code$1.isIdentifierStartES6;
37894 for (i = 0, iz = id.length; i < iz; ++i) {
37895 ch = id.charCodeAt(i);
37897 if (0xD800 <= ch && ch <= 0xDBFF) {
37904 lowCh = id.charCodeAt(i);
37906 if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) {
37910 ch = decodeUtf16(ch, lowCh);
37917 check = code$1.isIdentifierPartES6;
37923 function isIdentifierES5(id, strict) {
37924 return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
37927 function isIdentifierES6(id, strict) {
37928 return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
37932 isKeywordES5: isKeywordES5,
37933 isKeywordES6: isKeywordES6,
37934 isReservedWordES5: isReservedWordES5,
37935 isReservedWordES6: isReservedWordES6,
37936 isRestrictedWord: isRestrictedWord,
37937 isIdentifierNameES5: isIdentifierNameES5,
37938 isIdentifierNameES6: isIdentifierNameES6,
37939 isIdentifierES5: isIdentifierES5,
37940 isIdentifierES6: isIdentifierES6
37943 /* vim: set sw=4 ts=4 et tw=80 : */
37947 var utils$5 = createCommonjsModule(function (module, exports) {
37949 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
37951 Redistribution and use in source and binary forms, with or without
37952 modification, are permitted provided that the following conditions are met:
37954 * Redistributions of source code must retain the above copyright
37955 notice, this list of conditions and the following disclaimer.
37956 * Redistributions in binary form must reproduce the above copyright
37957 notice, this list of conditions and the following disclaimer in the
37958 documentation and/or other materials provided with the distribution.
37960 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
37961 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37962 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
37963 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
37964 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
37965 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37966 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
37967 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37968 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37969 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37974 exports.code = code;
37975 exports.keyword = keyword$1;
37977 /* vim: set sw=4 ts=4 et tw=80 : */
37981 const isIdentifierName = utils$5.keyword.isIdentifierNameES5;
37983 getLast: getLast$1,
37984 hasNewline: hasNewline$3,
37985 hasNewlineInRange: hasNewlineInRange$2,
37986 skipWhitespace: skipWhitespace$2
37989 locStart: locStart$2,
37991 hasSameLocStart: hasSameLocStart$1
37994 * @typedef {import("./types/estree").Node} Node
37995 * @typedef {import("./types/estree").TemplateLiteral} TemplateLiteral
37996 * @typedef {import("./types/estree").Comment} Comment
37997 * @typedef {import("./types/estree").MemberExpression} MemberExpression
37998 * @typedef {import("./types/estree").OptionalMemberExpression} OptionalMemberExpression
37999 * @typedef {import("./types/estree").CallExpression} CallExpression
38000 * @typedef {import("./types/estree").OptionalCallExpression} OptionalCallExpression
38001 * @typedef {import("./types/estree").Expression} Expression
38002 * @typedef {import("./types/estree").Property} Property
38003 * @typedef {import("./types/estree").ObjectTypeProperty} ObjectTypeProperty
38004 * @typedef {import("./types/estree").JSXElement} JSXElement
38005 * @typedef {import("./types/estree").TaggedTemplateExpression} TaggedTemplateExpression
38006 * @typedef {import("./types/estree").Literal} Literal
38008 * @typedef {import("../common/fast-path")} FastPath
38010 // We match any whitespace except line terminators because
38011 // Flow annotation comments cannot be split across lines. For example:
38014 // : any */).foo = 5;
38016 // is not picked up by Flow (see https://github.com/facebook/flow/issues/7050), so
38017 // removing the newline would create a type annotation that the user did not intend
38020 const NON_LINE_TERMINATING_WHITE_SPACE = "(?:(?=.)\\s)";
38021 const FLOW_SHORTHAND_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*:`);
38022 const FLOW_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*::`);
38024 * @param {Node} node
38025 * @returns {boolean}
38028 function hasFlowShorthandAnnotationComment(node) {
38029 // https://flow.org/en/docs/types/comments/
38030 // Syntax example: const r = new (window.Request /*: Class<Request> */)("");
38031 return node.extra && node.extra.parenthesized && node.trailingComments && isBlockComment(node.trailingComments[0]) && FLOW_SHORTHAND_ANNOTATION.test(node.trailingComments[0].value);
38034 * @param {Comment[]} comments
38035 * @returns {boolean}
38039 function hasFlowAnnotationComment(comments) {
38040 return comments && isBlockComment(comments[0]) && FLOW_ANNOTATION.test(comments[0].value);
38043 * @param {Node} node
38044 * @param {(Node) => boolean} fn
38045 * @returns {boolean}
38049 function hasNode(node, fn) {
38050 if (!node || typeof node !== "object") {
38054 if (Array.isArray(node)) {
38055 return node.some(value => hasNode(value, fn));
38058 const result = fn(node);
38059 return typeof result === "boolean" ? result : Object.keys(node).some(key => hasNode(node[key], fn));
38062 * @param {Node} node
38063 * @returns {boolean}
38067 function hasNakedLeftSide(node) {
38068 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";
38071 function getLeftSide(node) {
38072 if (node.expressions) {
38073 return node.expressions[0];
38076 return node.left || node.test || node.callee || node.object || node.tag || node.argument || node.expression;
38079 function getLeftSidePathName(path, node) {
38080 if (node.expressions) {
38081 return ["expressions", 0];
38104 if (node.argument) {
38105 return ["argument"];
38108 if (node.expression) {
38109 return ["expression"];
38112 throw new Error("Unexpected node has no left side.");
38115 * @param {Comment} comment
38116 * @returns {boolean}
38120 function isBlockComment(comment) {
38121 return comment.type === "Block" || comment.type === "CommentBlock" || // `meriyah`
38122 comment.type === "MultiLine";
38125 * @param {Comment} comment
38126 * @returns {boolean}
38130 function isLineComment(comment) {
38131 return comment.type === "Line" || comment.type === "CommentLine" || // `meriyah` has `SingleLine`, `HashbangComment`, `HTMLOpen`, and `HTMLClose`
38132 comment.type === "SingleLine" || comment.type === "HashbangComment" || comment.type === "HTMLOpen" || comment.type === "HTMLClose";
38135 const exportDeclarationTypes = new Set(["ExportDefaultDeclaration", "ExportDefaultSpecifier", "DeclareExportDeclaration", "ExportNamedDeclaration", "ExportAllDeclaration"]);
38137 * @param {Node} node
38138 * @returns {boolean}
38141 function isExportDeclaration(node) {
38142 return node && exportDeclarationTypes.has(node.type);
38145 * @param {FastPath} path
38146 * @returns {Node | null}
38150 function getParentExportDeclaration(path) {
38151 const parentNode = path.getParentNode();
38153 if (path.getName() === "declaration" && isExportDeclaration(parentNode)) {
38160 * @param {Node} node
38161 * @returns {boolean}
38165 function isLiteral(node) {
38166 return node.type === "BooleanLiteral" || node.type === "DirectiveLiteral" || node.type === "Literal" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "BigIntLiteral" || node.type === "DecimalLiteral" || node.type === "RegExpLiteral" || node.type === "StringLiteral" || node.type === "TemplateLiteral" || node.type === "TSTypeLiteral" || node.type === "JSXText";
38169 * @param {Node} node
38170 * @returns {boolean}
38174 function isNumericLiteral(node) {
38175 return node.type === "NumericLiteral" || node.type === "Literal" && typeof node.value === "number";
38178 * @param {Node} node
38179 * @returns {boolean}
38183 function isStringLiteral(node) {
38184 return node.type === "StringLiteral" || node.type === "Literal" && typeof node.value === "string";
38187 * @param {Node} node
38188 * @returns {boolean}
38192 function isObjectType(node) {
38193 return node.type === "ObjectTypeAnnotation" || node.type === "TSTypeLiteral";
38196 * @param {Node} node
38197 * @returns {boolean}
38201 function isFunctionOrArrowExpression(node) {
38202 return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
38205 * @param {Node} node
38206 * @returns {boolean}
38210 function isFunctionOrArrowExpressionWithBody(node) {
38211 return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement";
38214 * @param {Node} node
38215 * @returns {boolean}
38219 function isTemplateLiteral(node) {
38220 return node.type === "TemplateLiteral";
38223 * Note: `inject` is used in AngularJS 1.x, `async` in Angular 2+
38224 * example: https://docs.angularjs.org/guide/unit-testing#using-beforeall-
38226 * @param {Node} node
38227 * @returns {boolean}
38231 function isAngularTestWrapper(node) {
38232 return (node.type === "CallExpression" || node.type === "OptionalCallExpression") && node.callee.type === "Identifier" && (node.callee.name === "async" || node.callee.name === "inject" || node.callee.name === "fakeAsync");
38235 * @param {Node} node
38236 * @returns {boolean}
38240 function isJSXNode(node) {
38241 return node.type === "JSXElement" || node.type === "JSXFragment";
38244 function isTheOnlyJSXElementInMarkdown(options, path) {
38245 if (options.parentParser !== "markdown" && options.parentParser !== "mdx") {
38249 const node = path.getNode();
38251 if (!node.expression || !isJSXNode(node.expression)) {
38255 const parent = path.getParentNode();
38256 return parent.type === "Program" && parent.body.length === 1;
38257 } // Detect an expression node representing `{" "}`
38260 function isJSXWhitespaceExpression(node) {
38261 return node.type === "JSXExpressionContainer" && isLiteral(node.expression) && node.expression.value === " " && !node.expression.comments;
38264 * @param {Node} node
38265 * @returns {boolean}
38269 function isMemberExpressionChain(node) {
38270 if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") {
38274 if (node.object.type === "Identifier") {
38278 return isMemberExpressionChain(node.object);
38281 function isGetterOrSetter(node) {
38282 return node.kind === "get" || node.kind === "set";
38283 } // TODO: This is a bad hack and we need a better way to distinguish between
38284 // arrow functions and otherwise
38287 function isFunctionNotation(node) {
38288 return isGetterOrSetter(node) || hasSameLocStart$1(node, node.value);
38289 } // Hack to differentiate between the following two which have the same ast
38290 // type T = { method: () => void };
38291 // type T = { method(): void };
38294 * @param {Node} node
38295 * @returns {boolean}
38299 function isObjectTypePropertyAFunction(node) {
38300 return (node.type === "ObjectTypeProperty" || node.type === "ObjectTypeInternalSlot") && node.value.type === "FunctionTypeAnnotation" && !node.static && !isFunctionNotation(node);
38301 } // Hack to differentiate between the following two which have the same ast
38302 // declare function f(a): void;
38303 // var f: (a) => void;
38306 function isTypeAnnotationAFunction(node) {
38307 return (node.type === "TypeAnnotation" || node.type === "TSTypeAnnotation") && node.typeAnnotation.type === "FunctionTypeAnnotation" && !node.static && !hasSameLocStart$1(node, node.typeAnnotation);
38310 const binaryishNodeTypes = new Set(["BinaryExpression", "LogicalExpression", "NGPipeExpression"]);
38312 * @param {Node} node
38313 * @returns {boolean}
38316 function isBinaryish(node) {
38317 return binaryishNodeTypes.has(node.type);
38320 * @param {Node} node
38321 * @returns {boolean}
38325 function isMemberish(node) {
38326 return node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "BindExpression" && Boolean(node.object);
38329 const simpleTypeAnnotations = new Set([// `any`
38330 "AnyTypeAnnotation", "TSAnyKeyword", // `null`
38331 "NullLiteralTypeAnnotation", "TSNullKeyword", // `this`
38332 "ThisTypeAnnotation", "TSThisType", // `number`
38333 "NumberTypeAnnotation", "TSNumberKeyword", // `void`
38334 "VoidTypeAnnotation", "TSVoidKeyword", // `boolean`
38335 "BooleanTypeAnnotation", "TSBooleanKeyword", // `bigint`
38336 "BigIntTypeAnnotation", "TSBigIntKeyword", // `symbol`
38337 "SymbolTypeAnnotation", "TSSymbolKeyword", // `string`
38338 "StringTypeAnnotation", "TSStringKeyword", // literals
38339 "BooleanLiteralTypeAnnotation", "StringLiteralTypeAnnotation", "BigIntLiteralTypeAnnotation", "NumberLiteralTypeAnnotation", "TSLiteralType", "TSTemplateLiteralType", // flow only, `empty`, `mixed`
38340 "EmptyTypeAnnotation", "MixedTypeAnnotation", // typescript only, `never`, `object`, `undefined`, `unknown`
38341 "TSNeverKeyword", "TSObjectKeyword", "TSUndefinedKeyword", "TSUnknownKeyword"]);
38343 * @param {Node} node
38344 * @returns {boolean}
38347 function isSimpleType(node) {
38352 if ((node.type === "GenericTypeAnnotation" || node.type === "TSTypeReference") && !node.typeParameters) {
38356 if (simpleTypeAnnotations.has(node.type)) {
38363 const unitTestRe = /^(skip|[fx]?(it|describe|test))$/;
38365 * @param {CallExpression} node
38366 * @returns {boolean}
38369 function isSkipOrOnlyBlock(node) {
38370 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");
38373 * @param {CallExpression} node
38374 * @returns {boolean}
38378 function isUnitTestSetUp(node) {
38379 const unitTestSetUpRe = /^(before|after)(Each|All)$/;
38380 return node.callee.type === "Identifier" && unitTestSetUpRe.test(node.callee.name) && node.arguments.length === 1;
38381 } // eg; `describe("some string", (done) => {})`
38384 function isTestCall(n, parent) {
38385 if (n.type !== "CallExpression") {
38389 if (n.arguments.length === 1) {
38390 if (isAngularTestWrapper(n) && parent && isTestCall(parent)) {
38391 return isFunctionOrArrowExpression(n.arguments[0]);
38394 if (isUnitTestSetUp(n)) {
38395 return isAngularTestWrapper(n.arguments[0]);
38397 } else if (n.arguments.length === 2 || n.arguments.length === 3) {
38398 if ((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name) || isSkipOrOnlyBlock(n)) && (isTemplateLiteral(n.arguments[0]) || isStringLiteral(n.arguments[0]))) {
38399 // it("name", () => { ... }, 2500)
38400 if (n.arguments[2] && !isNumericLiteral(n.arguments[2])) {
38404 return (n.arguments.length === 2 ? isFunctionOrArrowExpression(n.arguments[1]) : isFunctionOrArrowExpressionWithBody(n.arguments[1]) && getFunctionParameters(n.arguments[1]).length <= 1) || isAngularTestWrapper(n.arguments[1]);
38411 * @param {Node} node
38412 * @returns {boolean}
38416 function hasLeadingComment(node) {
38417 return node.comments && node.comments.some(comment => comment.leading);
38420 * @param {Node} node
38421 * @returns {boolean}
38425 function hasTrailingComment(node) {
38426 return node.comments && node.comments.some(comment => comment.trailing);
38429 * @param {Node} node
38430 * @returns {boolean}
38434 function hasTrailingLineComment(node) {
38435 return node.comments && node.comments.some(comment => comment.trailing && !isBlockComment(comment));
38438 * @param {CallExpression | OptionalCallExpression} node
38439 * @returns {boolean}
38443 function isCallOrOptionalCallExpression(node) {
38444 return node.type === "CallExpression" || node.type === "OptionalCallExpression";
38447 * @param {Node} node
38448 * @returns {boolean}
38452 function hasDanglingComments(node) {
38453 return node.comments && node.comments.some(comment => !comment.leading && !comment.trailing);
38455 /** identify if an angular expression seems to have side effects */
38458 * @param {FastPath} path
38459 * @returns {boolean}
38463 function hasNgSideEffect(path) {
38464 return hasNode(path.getValue(), node => {
38465 switch (node.type) {
38469 case "CallExpression":
38470 case "OptionalCallExpression":
38471 case "AssignmentExpression":
38477 function isNgForOf(node, index, parentNode) {
38478 return node.type === "NGMicrosyntaxKeyedExpression" && node.key.name === "of" && index === 1 && parentNode.body[0].type === "NGMicrosyntaxLet" && parentNode.body[0].value === null;
38482 * @param {any} node
38483 * @returns {boolean}
38487 function isSimpleTemplateLiteral(node) {
38488 let expressionsKey = "expressions";
38490 if (node.type === "TSTemplateLiteralType") {
38491 expressionsKey = "types";
38494 const expressions = node[expressionsKey];
38496 if (expressions.length === 0) {
38500 return expressions.every(expr => {
38501 // Disallow comments since printDocToString can't print them here
38502 if (expr.comments) {
38504 } // Allow `x` and `this`
38507 if (expr.type === "Identifier" || expr.type === "ThisExpression") {
38509 } // Allow `a.b.c`, `a.b[c]`, and `this.x.y`
38512 if (expr.type === "MemberExpression" || expr.type === "OptionalMemberExpression") {
38515 while (head.type === "MemberExpression" || head.type === "OptionalMemberExpression") {
38516 if (head.property.type !== "Identifier" && head.property.type !== "Literal" && head.property.type !== "StringLiteral" && head.property.type !== "NumericLiteral") {
38520 head = head.object;
38522 if (head.comments) {
38527 if (head.type === "Identifier" || head.type === "ThisExpression") {
38538 * @param {FastPath} path
38539 * @returns {boolean}
38543 function classPropMayCauseASIProblems(path) {
38544 const node = path.getNode();
38546 if (node.type !== "ClassProperty" && node.type !== "FieldDefinition") {
38550 const name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today
38551 // so isn't properly tested yet.
38553 if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) {
38558 function classChildNeedsASIProtection(node) {
38563 if (node.static || node.accessibility // TypeScript
38568 if (!node.computed) {
38569 const name = node.key && node.key.name;
38571 if (name === "in" || name === "instanceof") {
38576 switch (node.type) {
38577 case "ClassProperty":
38578 case "FieldDefinition":
38579 case "TSAbstractClassProperty":
38580 return node.computed;
38582 case "MethodDefinition": // Flow
38584 case "TSAbstractMethodDefinition": // TypeScript
38586 case "ClassMethod":
38587 case "ClassPrivateMethod":
38590 const isAsync = node.value ? node.value.async : node.async;
38591 const isGenerator = node.value ? node.value.generator : node.generator;
38593 if (isAsync || node.kind === "get" || node.kind === "set") {
38597 if (node.computed || isGenerator) {
38604 case "TSIndexSignature":
38608 /* istanbul ignore next */
38613 * @param {string} tokenNode
38614 * @param {string} keyword
38615 * @returns {string}
38619 function getTypeScriptMappedTypeModifier(tokenNode, keyword) {
38620 if (tokenNode === "+") {
38621 return "+" + keyword;
38622 } else if (tokenNode === "-") {
38623 return "-" + keyword;
38629 function hasNewlineBetweenOrAfterDecorators(node, options) {
38630 return hasNewlineInRange$2(options.originalText, locStart$2(node.decorators[0]), locEnd$2(getLast$1(node.decorators))) || hasNewline$3(options.originalText, locEnd$2(getLast$1(node.decorators)));
38631 } // Only space, newline, carriage return, and tab are treated as whitespace
38635 const jsxWhitespaceChars = " \n\r\t";
38636 const matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)");
38637 const containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]"); // Meaningful if it contains non-whitespace characters,
38638 // or it contains whitespace without a new line.
38641 * @param {Node} node
38642 * @returns {boolean}
38645 function isMeaningfulJSXText(node) {
38646 return isLiteral(node) && (containsNonJsxWhitespaceRegex.test(rawText(node)) || !/\n/.test(rawText(node)));
38649 * @param {FastPath} path
38650 * @returns {boolean}
38654 function hasJsxIgnoreComment(path) {
38655 const node = path.getValue();
38656 const parent = path.getParentNode();
38658 if (!parent || !node || !isJSXNode(node) || !isJSXNode(parent)) {
38660 } // Lookup the previous sibling, ignoring any empty JSXText elements
38663 const index = parent.children.indexOf(node);
38664 let prevSibling = null;
38666 for (let i = index; i > 0; i--) {
38667 const candidate = parent.children[i - 1];
38669 if (candidate.type === "JSXText" && !isMeaningfulJSXText(candidate)) {
38673 prevSibling = candidate;
38677 return prevSibling && prevSibling.type === "JSXExpressionContainer" && prevSibling.expression.type === "JSXEmptyExpression" && prevSibling.expression.comments && prevSibling.expression.comments.some(comment => isPrettierIgnoreComment(comment));
38680 * @param {JSXElement} node
38681 * @returns {boolean}
38685 function isEmptyJSXElement(node) {
38686 if (node.children.length === 0) {
38690 if (node.children.length > 1) {
38692 } // if there is one text child and does not contain any meaningful text
38693 // we can treat the element as empty.
38696 const child = node.children[0];
38697 return isLiteral(child) && !isMeaningfulJSXText(child);
38700 * @param {FastPath} path
38701 * @returns {boolean}
38705 function hasPrettierIgnore(path) {
38706 return hasIgnoreComment(path) || hasJsxIgnoreComment(path);
38709 * @param {FastPath} path
38710 * @returns {boolean}
38714 function isLastStatement(path) {
38715 const parent = path.getParentNode();
38721 const node = path.getValue();
38722 const body = (parent.body || parent.consequent).filter(stmt => stmt.type !== "EmptyStatement");
38723 return body[body.length - 1] === node;
38726 * @param {string} text
38727 * @param {Node} typeAnnotation
38728 * @returns {boolean}
38732 function isFlowAnnotationComment(text, typeAnnotation) {
38733 const start = locStart$2(typeAnnotation);
38734 const end = skipWhitespace$2(text, locEnd$2(typeAnnotation));
38735 return end !== false && text.slice(start, start + 2) === "/*" && text.slice(end, end + 2) === "*/";
38738 * @param {string} text
38739 * @param {Node} node
38740 * @returns {boolean}
38744 function hasLeadingOwnLineComment(text, node) {
38745 if (isJSXNode(node)) {
38746 return hasNodeIgnoreComment(node);
38749 const res = node.comments && node.comments.some(comment => comment.leading && hasNewline$3(text, locEnd$2(comment)));
38751 } // This recurses the return argument, looking for the first token
38752 // (the leftmost leaf node) and, if it (or its parents) has any
38753 // leadingComments, returns true (so it can be wrapped in parens).
38756 function returnArgumentHasLeadingComment(options, argument) {
38757 if (hasLeadingOwnLineComment(options.originalText, argument)) {
38761 if (hasNakedLeftSide(argument)) {
38762 let leftMost = argument;
38765 while (newLeftMost = getLeftSide(leftMost)) {
38766 leftMost = newLeftMost;
38768 if (hasLeadingOwnLineComment(options.originalText, leftMost)) {
38775 } // Note: Quoting/unquoting numbers in TypeScript is not safe.
38777 // let a = { 1: 1, 2: 2 }
38778 // let b = { '1': 1, '2': 2 }
38780 // declare let aa: keyof typeof a;
38781 // declare let bb: keyof typeof b;
38785 // Type '"1" | "2"' is not assignable to type '1 | 2'.
38786 // Type '"1"' is not assignable to type '1 | 2'.(2322)
38788 // And in Flow, you get:
38792 // ^ Non-string literal property keys not supported. [unsupported-syntax]
38795 // Angular does not support unquoted numbers in expressions.
38797 // So we play it safe and only unquote numbers for the JavaScript parsers.
38798 // (Vue supports unquoted numbers in expressions, but let’s keep it simple.)
38800 // Identifiers can be unquoted in more circumstances, though.
38803 function isStringPropSafeToUnquote(node, options) {
38804 return options.parser !== "json" && isStringLiteral(node.key) && rawText(node.key).slice(1, -1) === node.key.value && (isIdentifierName(node.key.value) && // With `--strictPropertyInitialization`, TS treats properties with quoted names differently than unquoted ones.
38805 // See https://github.com/microsoft/TypeScript/pull/20075
38806 !((options.parser === "typescript" || options.parser === "babel-ts") && node.type === "ClassProperty") || isSimpleNumber(node.key.value) && String(Number(node.key.value)) === node.key.value && (options.parser === "babel" || options.parser === "espree" || options.parser === "meriyah"));
38807 } // Matches “simple” numbers like `123` and `2.5` but not `1_000`, `1e+100` or `0b10`.
38810 function isSimpleNumber(numberString) {
38811 return /^(\d+|\d+\.\d+)$/.test(numberString);
38814 * @param {Node} node
38815 * @param {Node} parentNode
38816 * @returns {boolean}
38820 function isJestEachTemplateLiteral(node, parentNode) {
38822 * describe.each`table`(name, fn)
38823 * describe.only.each`table`(name, fn)
38824 * describe.skip.each`table`(name, fn)
38825 * test.each`table`(name, fn)
38826 * test.only.each`table`(name, fn)
38827 * test.skip.each`table`(name, fn)
38829 * Ref: https://github.com/facebook/jest/pull/6102
38831 const jestEachTriggerRegex = /^[fx]?(describe|it|test)$/;
38832 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));
38835 * @param {TemplateLiteral} template
38836 * @returns {boolean}
38840 function templateLiteralHasNewLines(template) {
38841 return template.quasis.some(quasi => quasi.value.raw.includes("\n"));
38844 * @param {TemplateLiteral | TaggedTemplateExpression} n
38845 * @param {string} text
38846 * @returns {boolean}
38850 function isTemplateOnItsOwnLine(n, text) {
38851 return (n.type === "TemplateLiteral" && templateLiteralHasNewLines(n) || n.type === "TaggedTemplateExpression" && templateLiteralHasNewLines(n.quasi)) && !hasNewline$3(text, locStart$2(n), {
38856 * @param {Node} node
38857 * @returns {boolean}
38861 function needsHardlineAfterDanglingComment(node) {
38862 if (!node.comments) {
38866 const lastDanglingComment = getLast$1(node.comments.filter(comment => !comment.leading && !comment.trailing));
38867 return lastDanglingComment && !isBlockComment(lastDanglingComment);
38868 } // Logic to check for args with multiple anonymous functions. For instance,
38869 // the following call should be split on multiple lines for readability:
38870 // source.pipe(map((x) => x + x), filter((x) => x % 2 === 0))
38873 function isFunctionCompositionArgs(args) {
38874 if (args.length <= 1) {
38880 for (const arg of args) {
38881 if (isFunctionOrArrowExpression(arg)) {
38887 } else if (isCallOrOptionalCallExpression(arg)) {
38888 for (const childArg of arg.arguments) {
38889 if (isFunctionOrArrowExpression(childArg)) {
38897 } // Logic to determine if a call is a “long curried function call”.
38898 // See https://github.com/prettier/prettier/issues/1420.
38900 // `connect(a, b, c)(d)`
38901 // In the above call expression, the second call is the parent node and the
38902 // first call is the current node.
38905 * @param {FastPath} path
38906 * @returns {boolean}
38910 function isLongCurriedCallExpression(path) {
38911 const node = path.getValue();
38912 const parent = path.getParentNode();
38913 return isCallOrOptionalCallExpression(node) && isCallOrOptionalCallExpression(parent) && parent.callee === node && node.arguments.length > parent.arguments.length && parent.arguments.length > 0;
38916 * @param {any} node
38917 * @param {number} depth
38918 * @returns {boolean}
38922 function isSimpleCallArgument(node, depth) {
38927 const isChildSimple = child => isSimpleCallArgument(child, depth + 1);
38929 const regexpPattern = node.type === "Literal" && "regex" in node && node.regex.pattern || node.type === "RegExpLiteral" && node.pattern;
38931 if (regexpPattern && regexpPattern.length > 5) {
38935 if (node.type === "Literal" || node.type === "BigIntLiteral" || node.type === "DecimalLiteral" || node.type === "BooleanLiteral" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "RegExpLiteral" || node.type === "StringLiteral" || node.type === "Identifier" || node.type === "ThisExpression" || node.type === "Super" || node.type === "PrivateName" || node.type === "ArgumentPlaceholder" || node.type === "Import") {
38939 if (node.type === "TemplateLiteral") {
38940 return node.expressions.every(isChildSimple);
38943 if (node.type === "ObjectExpression") {
38944 return node.properties.every(p => !p.computed && (p.shorthand || p.value && isChildSimple(p.value)));
38947 if (node.type === "ArrayExpression") {
38948 return node.elements.every(x => x === null || isChildSimple(x));
38951 if (node.type === "ImportExpression") {
38952 return isChildSimple(node.source);
38955 if (node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "NewExpression") {
38956 return isSimpleCallArgument(node.callee, depth) && node.arguments.every(isChildSimple);
38959 if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
38960 return isSimpleCallArgument(node.object, depth) && isSimpleCallArgument(node.property, depth);
38963 if (node.type === "UnaryExpression" && (node.operator === "!" || node.operator === "-")) {
38964 return isSimpleCallArgument(node.argument, depth);
38967 if (node.type === "TSNonNullExpression") {
38968 return isSimpleCallArgument(node.expression, depth);
38974 function rawText(node) {
38975 return node.extra ? node.extra.raw : node.raw;
38978 function identity$1(x) {
38982 function isTSXFile(options) {
38983 return options.filepath && /\.tsx$/i.test(options.filepath);
38986 * @param {any} options
38987 * @param {("es5" | "all")} [level]
38988 * @returns {boolean}
38992 function shouldPrintComma(options, level = "es5") {
38993 return options.trailingComma === "es5" && level === "es5" || options.trailingComma === "all" && (level === "all" || level === "es5");
38996 * Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr
38997 * holds) `function`, `class`, or `do {}`. Will be overzealous if there's
38998 * already necessary grouping parentheses.
39000 * @param {Node} node
39001 * @param {boolean} forbidFunctionClassAndDoExpr
39002 * @returns {boolean}
39006 function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) {
39007 node = getLeftMost(node);
39009 switch (node.type) {
39010 case "FunctionExpression":
39011 case "ClassExpression":
39012 case "DoExpression":
39013 return forbidFunctionClassAndDoExpr;
39015 case "ObjectExpression":
39018 case "MemberExpression":
39019 case "OptionalMemberExpression":
39020 return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
39022 case "TaggedTemplateExpression":
39023 if (node.tag.type === "FunctionExpression") {
39024 // IIFEs are always already parenthesized
39028 return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr);
39030 case "CallExpression":
39031 case "OptionalCallExpression":
39032 if (node.callee.type === "FunctionExpression") {
39033 // IIFEs are always already parenthesized
39037 return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr);
39039 case "ConditionalExpression":
39040 return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr);
39042 case "UpdateExpression":
39043 return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr);
39045 case "BindExpression":
39046 return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
39048 case "SequenceExpression":
39049 return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr);
39051 case "TSAsExpression":
39052 return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr);
39059 const equalityOperators = {
39065 const multiplicativeOperators = {
39070 const bitshiftOperators = {
39076 function shouldFlatten(parentOp, nodeOp) {
39077 if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) {
39079 } // ** is right-associative
39080 // x ** y ** z --> x ** (y ** z)
39083 if (parentOp === "**") {
39085 } // x == y == z --> (x == y) == z
39088 if (equalityOperators[parentOp] && equalityOperators[nodeOp]) {
39090 } // x * y % z --> (x * y) % z
39093 if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) {
39095 } // x * y / z --> (x * y) / z
39096 // x / y * z --> (x / y) * z
39099 if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) {
39101 } // x << y << z --> (x << y) << z
39104 if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) {
39111 const PRECEDENCE = {};
39112 [["|>"], ["??"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach((tier, i) => {
39113 tier.forEach(op => {
39114 PRECEDENCE[op] = i;
39118 function getPrecedence(op) {
39119 return PRECEDENCE[op];
39122 function getLeftMost(node) {
39123 while (node.left) {
39130 function isBitwiseOperator(operator) {
39131 return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&";
39134 function hasRestParameter(node) {
39139 const parameters = getFunctionParameters(node);
39140 return parameters.length > 0 && getLast$1(parameters).type === "RestElement";
39143 const functionParametersCache = new WeakMap();
39145 function getFunctionParameters(node) {
39146 if (functionParametersCache.has(node)) {
39147 return functionParametersCache.get(node);
39150 const parameters = [];
39153 parameters.push(node.this);
39154 } // `params` vs `parameters` - see https://github.com/babel/babel/issues/9231
39157 if (Array.isArray(node.parameters)) {
39158 parameters.push(...node.parameters);
39159 } else if (Array.isArray(node.params)) {
39160 parameters.push(...node.params);
39164 parameters.push(node.rest);
39167 functionParametersCache.set(node, parameters);
39171 function iterateFunctionParametersPath(path, iteratee) {
39172 const node = path.getValue();
39175 const callback = childPath => iteratee(childPath, index++);
39178 path.call(callback, "this");
39181 if (Array.isArray(node.parameters)) {
39182 path.each(callback, "parameters");
39183 } else if (Array.isArray(node.params)) {
39184 path.each(callback, "params");
39188 path.call(callback, "rest");
39192 const callArgumentsCache = new WeakMap();
39194 function getCallArguments(node) {
39195 if (callArgumentsCache.has(node)) {
39196 return callArgumentsCache.get(node);
39199 const args = node.type === "ImportExpression" ? // No parser except `babel` supports `import("./foo.json", { assert: { type: "json" } })` yet,
39200 // And `babel` parser it as `CallExpression`
39201 // We need add the second argument here
39202 [node.source] : node.arguments;
39203 callArgumentsCache.set(node, args);
39207 function iterateCallArgumentsPath(path, iteratee) {
39208 const node = path.getValue(); // See comment in `getCallArguments`
39210 if (node.type === "ImportExpression") {
39211 path.call(sourcePath => iteratee(sourcePath, 0), "source");
39213 path.each(iteratee, "arguments");
39217 function isPrettierIgnoreComment(comment) {
39218 return comment.value.trim() === "prettier-ignore";
39221 function hasNodeIgnoreComment(node) {
39222 return node && (node.comments && node.comments.length > 0 && node.comments.some(comment => isPrettierIgnoreComment(comment) && !comment.unignore) || node.prettierIgnore);
39225 function hasIgnoreComment(path) {
39226 const node = path.getValue();
39227 return hasNodeIgnoreComment(node);
39231 classChildNeedsASIProtection,
39232 classPropMayCauseASIProblems,
39233 getFunctionParameters,
39234 iterateFunctionParametersPath,
39236 iterateCallArgumentsPath,
39238 getLeftSidePathName,
39239 getParentExportDeclaration,
39240 getTypeScriptMappedTypeModifier,
39241 hasDanglingComments,
39242 hasFlowAnnotationComment,
39243 hasFlowShorthandAnnotationComment,
39245 hasLeadingOwnLineComment,
39247 hasNewlineBetweenOrAfterDecorators,
39251 hasTrailingComment,
39252 hasTrailingLineComment,
39254 hasNodeIgnoreComment,
39255 identity: identity$1,
39259 isPrettierIgnoreComment,
39260 isCallOrOptionalCallExpression,
39262 isExportDeclaration,
39263 isFlowAnnotationComment,
39264 isFunctionCompositionArgs,
39265 isFunctionNotation,
39266 isFunctionOrArrowExpression,
39268 isJestEachTemplateLiteral,
39270 isJSXWhitespaceExpression,
39273 isLongCurriedCallExpression,
39274 isSimpleCallArgument,
39275 isMeaningfulJSXText,
39276 isMemberExpressionChain,
39281 isObjectTypePropertyAFunction,
39284 isSimpleTemplateLiteral,
39286 isStringPropSafeToUnquote,
39287 isTemplateOnItsOwnLine,
39289 isTheOnlyJSXElementInMarkdown,
39291 isTypeAnnotationAFunction,
39292 matchJsxWhitespaceRegex,
39293 needsHardlineAfterDanglingComment,
39295 returnArgumentHasLeadingComment,
39299 startsWithNoLookaheadToken,
39304 getLast: getLast$2,
39305 hasNewline: hasNewline$4,
39306 getNextNonSpaceNonCommentCharacterIndexWithStartIndex: getNextNonSpaceNonCommentCharacterIndexWithStartIndex$1,
39307 getNextNonSpaceNonCommentCharacter: getNextNonSpaceNonCommentCharacter$1,
39308 hasNewlineInRange: hasNewlineInRange$3,
39309 addLeadingComment: addLeadingComment$3,
39310 addTrailingComment: addTrailingComment$3,
39311 addDanglingComment: addDanglingComment$3,
39312 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$2
39315 isBlockComment: isBlockComment$1,
39316 getFunctionParameters: getFunctionParameters$1,
39317 isPrettierIgnoreComment: isPrettierIgnoreComment$1,
39318 isJSXNode: isJSXNode$1,
39319 hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$1,
39320 hasFlowAnnotationComment: hasFlowAnnotationComment$1,
39321 hasIgnoreComment: hasIgnoreComment$1
39324 locStart: locStart$3,
39328 function handleOwnLineComment(comment, text, options, ast, isLastComment) {
39329 return handleIgnoreComments(comment) || handleLastFunctionArgComments(comment, text) || handleMemberExpressionComments(comment) || handleIfStatementComments(comment, text) || handleWhileComments(comment, text) || handleTryStatementComments(comment) || handleClassComments(comment) || handleImportSpecifierComments(comment) || handleForComments(comment) || handleUnionTypeComments(comment) || handleOnlyComments(comment, ast, isLastComment) || handleImportDeclarationComments(comment, text) || handleAssignmentPatternComments(comment) || handleMethodNameComments(comment, text) || handleLabeledStatementComments(comment);
39332 function handleEndOfLineComment(comment, text, options, ast, isLastComment) {
39333 return handleClosureTypeCastComments(comment) || handleLastFunctionArgComments(comment, text) || handleConditionalExpressionComments(comment, text) || handleImportSpecifierComments(comment) || handleIfStatementComments(comment, text) || handleWhileComments(comment, text) || handleTryStatementComments(comment) || handleClassComments(comment) || handleLabeledStatementComments(comment) || handleCallExpressionComments(comment) || handlePropertyComments(comment) || handleOnlyComments(comment, ast, isLastComment) || handleTypeAliasComments(comment) || handleVariableDeclaratorComments(comment);
39336 function handleRemainingComment(comment, text, options, ast, isLastComment) {
39337 if (handleIgnoreComments(comment) || handleIfStatementComments(comment, text) || handleWhileComments(comment, text) || handleObjectPropertyAssignment(comment) || handleCommentInEmptyParens(comment, text) || handleMethodNameComments(comment, text) || handleOnlyComments(comment, ast, isLastComment) || handleCommentAfterArrowParams(comment, text) || handleFunctionNameComments(comment, text) || handleTSMappedTypeComments(comment) || handleBreakAndContinueStatementComments(comment) || handleTSFunctionTrailingComments(comment, text)) {
39344 function addBlockStatementFirstComment(node, comment) {
39345 const firstNonEmptyNode = (node.body || node.properties).find(({
39347 }) => type !== "EmptyStatement");
39349 if (firstNonEmptyNode) {
39350 addLeadingComment$3(firstNonEmptyNode, comment);
39352 addDanglingComment$3(node, comment);
39356 function addBlockOrNotComment(node, comment) {
39357 if (node.type === "BlockStatement") {
39358 addBlockStatementFirstComment(node, comment);
39360 addLeadingComment$3(node, comment);
39364 function handleClosureTypeCastComments(comment) {
39369 if (followingNode && isTypeCastComment(comment)) {
39370 addLeadingComment$3(followingNode, comment);
39375 } // There are often comments before the else clause of if statements like
39381 // They are being attached as leading comments of the BlockExpression which
39382 // is not well printed. What we want is to instead move the comment inside
39383 // of the block and make it leadingComment of the first element of the block
39384 // or dangling comment of the block if there is nothing inside
39393 function handleIfStatementComments(comment, text) {
39400 if (!enclosingNode || enclosingNode.type !== "IfStatement" || !followingNode) {
39402 } // We unfortunately have no way using the AST or location of nodes to know
39403 // if the comment is positioned before the condition parenthesis:
39404 // if (a /* comment */) {}
39405 // The only workaround I found is to look at the next character to see if
39409 const nextCharacter = getNextNonSpaceNonCommentCharacter$1(text, comment, locEnd$3);
39411 if (nextCharacter === ")") {
39412 addTrailingComment$3(precedingNode, comment);
39414 } // Comments before `else`:
39415 // - treat as trailing comments of the consequent, if it's a BlockStatement
39416 // - treat as a dangling comment otherwise
39419 if (precedingNode === enclosingNode.consequent && followingNode === enclosingNode.alternate) {
39420 if (precedingNode.type === "BlockStatement") {
39421 addTrailingComment$3(precedingNode, comment);
39423 addDanglingComment$3(enclosingNode, comment);
39429 if (followingNode.type === "BlockStatement") {
39430 addBlockStatementFirstComment(followingNode, comment);
39434 if (followingNode.type === "IfStatement") {
39435 addBlockOrNotComment(followingNode.consequent, comment);
39437 } // For comments positioned after the condition parenthesis in an if statement
39438 // before the consequent without brackets on, such as
39439 // if (a) /* comment */ true,
39440 // we look at the next character to see if the following node
39441 // is the consequent for the if statement
39444 if (enclosingNode.consequent === followingNode) {
39445 addLeadingComment$3(followingNode, comment);
39452 function handleWhileComments(comment, text) {
39459 if (!enclosingNode || enclosingNode.type !== "WhileStatement" || !followingNode) {
39461 } // We unfortunately have no way using the AST or location of nodes to know
39462 // if the comment is positioned before the condition parenthesis:
39463 // while (a /* comment */) {}
39464 // The only workaround I found is to look at the next character to see if
39468 const nextCharacter = getNextNonSpaceNonCommentCharacter$1(text, comment, locEnd$3);
39470 if (nextCharacter === ")") {
39471 addTrailingComment$3(precedingNode, comment);
39475 if (followingNode.type === "BlockStatement") {
39476 addBlockStatementFirstComment(followingNode, comment);
39480 if (enclosingNode.body === followingNode) {
39481 addLeadingComment$3(followingNode, comment);
39486 } // Same as IfStatement but for TryStatement
39489 function handleTryStatementComments(comment) {
39496 if (!enclosingNode || enclosingNode.type !== "TryStatement" && enclosingNode.type !== "CatchClause" || !followingNode) {
39500 if (enclosingNode.type === "CatchClause" && precedingNode) {
39501 addTrailingComment$3(precedingNode, comment);
39505 if (followingNode.type === "BlockStatement") {
39506 addBlockStatementFirstComment(followingNode, comment);
39510 if (followingNode.type === "TryStatement") {
39511 addBlockOrNotComment(followingNode.finalizer, comment);
39515 if (followingNode.type === "CatchClause") {
39516 addBlockOrNotComment(followingNode.body, comment);
39523 function handleMemberExpressionComments(comment) {
39529 if (enclosingNode && (enclosingNode.type === "MemberExpression" || enclosingNode.type === "OptionalMemberExpression") && followingNode && followingNode.type === "Identifier") {
39530 addLeadingComment$3(enclosingNode, comment);
39537 function handleConditionalExpressionComments(comment, text) {
39543 const isSameLineAsPrecedingNode = precedingNode && !hasNewlineInRange$3(text, locEnd$3(precedingNode), locStart$3(comment));
39545 if ((!precedingNode || !isSameLineAsPrecedingNode) && enclosingNode && (enclosingNode.type === "ConditionalExpression" || enclosingNode.type === "TSConditionalType") && followingNode) {
39546 addLeadingComment$3(followingNode, comment);
39553 function handleObjectPropertyAssignment(comment) {
39559 if (enclosingNode && (enclosingNode.type === "ObjectProperty" || enclosingNode.type === "Property") && enclosingNode.shorthand && enclosingNode.key === precedingNode && enclosingNode.value.type === "AssignmentPattern") {
39560 addTrailingComment$3(enclosingNode.value.left, comment);
39567 function handleClassComments(comment) {
39574 if (enclosingNode && (enclosingNode.type === "ClassDeclaration" || enclosingNode.type === "ClassExpression" || enclosingNode.type === "DeclareClass" || enclosingNode.type === "DeclareInterface" || enclosingNode.type === "InterfaceDeclaration" || enclosingNode.type === "TSInterfaceDeclaration")) {
39575 if (enclosingNode.decorators && enclosingNode.decorators.length > 0 && !(followingNode && followingNode.type === "Decorator")) {
39576 addTrailingComment$3(enclosingNode.decorators[enclosingNode.decorators.length - 1], comment);
39580 if (enclosingNode.body && followingNode === enclosingNode.body) {
39581 addBlockStatementFirstComment(enclosingNode.body, comment);
39583 } // Don't add leading comments to `implements`, `extends`, `mixins` to
39584 // avoid printing the comment after the keyword.
39587 if (followingNode) {
39588 for (const prop of ["implements", "extends", "mixins"]) {
39589 if (enclosingNode[prop] && followingNode === enclosingNode[prop][0]) {
39590 if (precedingNode && (precedingNode === enclosingNode.id || precedingNode === enclosingNode.typeParameters || precedingNode === enclosingNode.superClass)) {
39591 addTrailingComment$3(precedingNode, comment);
39593 addDanglingComment$3(enclosingNode, comment, prop);
39605 function handleMethodNameComments(comment, text) {
39609 } = comment; // This is only needed for estree parsers (flow, typescript) to attach
39610 // after a method name:
39611 // obj = { fn /*comment*/() {} };
39613 if (enclosingNode && precedingNode && ( // "MethodDefinition" is handled in getCommentChildNodes
39614 enclosingNode.type === "Property" || enclosingNode.type === "TSDeclareMethod" || enclosingNode.type === "TSAbstractMethodDefinition") && precedingNode.type === "Identifier" && enclosingNode.key === precedingNode && // special Property case: { key: /*comment*/(value) };
39615 // comment should be attached to value instead of key
39616 getNextNonSpaceNonCommentCharacter$1(text, precedingNode, locEnd$3) !== ":") {
39617 addTrailingComment$3(precedingNode, comment);
39619 } // Print comments between decorators and class methods as a trailing comment
39620 // on the decorator node instead of the method node
39623 if (precedingNode && enclosingNode && precedingNode.type === "Decorator" && (enclosingNode.type === "ClassMethod" || enclosingNode.type === "ClassProperty" || enclosingNode.type === "FieldDefinition" || enclosingNode.type === "TSAbstractClassProperty" || enclosingNode.type === "TSAbstractMethodDefinition" || enclosingNode.type === "TSDeclareMethod" || enclosingNode.type === "MethodDefinition")) {
39624 addTrailingComment$3(precedingNode, comment);
39631 function handleFunctionNameComments(comment, text) {
39632 if (getNextNonSpaceNonCommentCharacter$1(text, comment, locEnd$3) !== "(") {
39641 if (precedingNode && enclosingNode && (enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ClassMethod" || enclosingNode.type === "MethodDefinition" || enclosingNode.type === "ObjectMethod")) {
39642 addTrailingComment$3(precedingNode, comment);
39649 function handleCommentAfterArrowParams(comment, text) {
39654 if (!(enclosingNode && enclosingNode.type === "ArrowFunctionExpression")) {
39658 const index = getNextNonSpaceNonCommentCharacterIndex$2(text, comment, locEnd$3);
39660 if (index !== false && text.slice(index, index + 2) === "=>") {
39661 addDanglingComment$3(enclosingNode, comment);
39668 function handleCommentInEmptyParens(comment, text) {
39669 if (getNextNonSpaceNonCommentCharacter$1(text, comment, locEnd$3) !== ")") {
39675 } = comment; // Only add dangling comments to fix the case when no params are present,
39676 // i.e. a function without any argument.
39678 if (enclosingNode && (isRealFunctionLikeNode(enclosingNode) && getFunctionParameters$1(enclosingNode).length === 0 || (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression" || enclosingNode.type === "NewExpression") && enclosingNode.arguments.length === 0)) {
39679 addDanglingComment$3(enclosingNode, comment);
39683 if (enclosingNode && enclosingNode.type === "MethodDefinition" && getFunctionParameters$1(enclosingNode.value).length === 0) {
39684 addDanglingComment$3(enclosingNode.value, comment);
39691 function handleLastFunctionArgComments(comment, text) {
39696 } = comment; // Flow function type definitions
39698 if (precedingNode && precedingNode.type === "FunctionTypeParam" && enclosingNode && enclosingNode.type === "FunctionTypeAnnotation" && followingNode && followingNode.type !== "FunctionTypeParam") {
39699 addTrailingComment$3(precedingNode, comment);
39701 } // Real functions and TypeScript function type definitions
39704 if (precedingNode && (precedingNode.type === "Identifier" || precedingNode.type === "AssignmentPattern") && enclosingNode && isRealFunctionLikeNode(enclosingNode) && getNextNonSpaceNonCommentCharacter$1(text, comment, locEnd$3) === ")") {
39705 addTrailingComment$3(precedingNode, comment);
39709 if (enclosingNode && enclosingNode.type === "FunctionDeclaration" && followingNode && followingNode.type === "BlockStatement") {
39710 const functionParamRightParenIndex = (() => {
39711 const parameters = getFunctionParameters$1(enclosingNode);
39713 if (parameters.length !== 0) {
39714 return getNextNonSpaceNonCommentCharacterIndexWithStartIndex$1(text, locEnd$3(getLast$2(parameters)));
39717 const functionParamLeftParenIndex = getNextNonSpaceNonCommentCharacterIndexWithStartIndex$1(text, locEnd$3(enclosingNode.id));
39718 return functionParamLeftParenIndex !== false && getNextNonSpaceNonCommentCharacterIndexWithStartIndex$1(text, functionParamLeftParenIndex + 1);
39721 if (locStart$3(comment) > functionParamRightParenIndex) {
39722 addBlockStatementFirstComment(followingNode, comment);
39730 function handleImportSpecifierComments(comment) {
39735 if (enclosingNode && enclosingNode.type === "ImportSpecifier") {
39736 addLeadingComment$3(enclosingNode, comment);
39743 function handleLabeledStatementComments(comment) {
39748 if (enclosingNode && enclosingNode.type === "LabeledStatement") {
39749 addLeadingComment$3(enclosingNode, comment);
39756 function handleBreakAndContinueStatementComments(comment) {
39761 if (enclosingNode && (enclosingNode.type === "ContinueStatement" || enclosingNode.type === "BreakStatement") && !enclosingNode.label) {
39762 addTrailingComment$3(enclosingNode, comment);
39769 function handleCallExpressionComments(comment) {
39775 if (enclosingNode && (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression") && precedingNode && enclosingNode.callee === precedingNode && enclosingNode.arguments.length > 0) {
39776 addLeadingComment$3(enclosingNode.arguments[0], comment);
39783 function handleUnionTypeComments(comment) {
39790 if (enclosingNode && (enclosingNode.type === "UnionTypeAnnotation" || enclosingNode.type === "TSUnionType")) {
39791 if (isPrettierIgnoreComment$1(comment)) {
39792 followingNode.prettierIgnore = true;
39793 comment.unignore = true;
39796 if (precedingNode) {
39797 addTrailingComment$3(precedingNode, comment);
39804 if (followingNode && (followingNode.type === "UnionTypeAnnotation" || followingNode.type === "TSUnionType") && isPrettierIgnoreComment$1(comment)) {
39805 followingNode.types[0].prettierIgnore = true;
39806 comment.unignore = true;
39812 function handlePropertyComments(comment) {
39817 if (enclosingNode && (enclosingNode.type === "Property" || enclosingNode.type === "ObjectProperty")) {
39818 addLeadingComment$3(enclosingNode, comment);
39825 function handleOnlyComments(comment, ast, isLastComment) {
39828 } = comment; // With Flow the enclosingNode is undefined so use the AST instead.
39830 if (ast && ast.body && ast.body.length === 0) {
39831 if (isLastComment) {
39832 addDanglingComment$3(ast, comment);
39834 addLeadingComment$3(ast, comment);
39838 } else if (enclosingNode && enclosingNode.type === "Program" && enclosingNode.body.length === 0 && enclosingNode.directives && enclosingNode.directives.length === 0) {
39839 if (isLastComment) {
39840 addDanglingComment$3(enclosingNode, comment);
39842 addLeadingComment$3(enclosingNode, comment);
39851 function handleForComments(comment) {
39856 if (enclosingNode && (enclosingNode.type === "ForInStatement" || enclosingNode.type === "ForOfStatement")) {
39857 addLeadingComment$3(enclosingNode, comment);
39864 function handleImportDeclarationComments(comment, text) {
39870 if (precedingNode && precedingNode.type === "ImportSpecifier" && enclosingNode && enclosingNode.type === "ImportDeclaration" && hasNewline$4(text, locEnd$3(comment))) {
39871 addTrailingComment$3(precedingNode, comment);
39878 function handleAssignmentPatternComments(comment) {
39883 if (enclosingNode && enclosingNode.type === "AssignmentPattern") {
39884 addLeadingComment$3(enclosingNode, comment);
39891 function handleTypeAliasComments(comment) {
39896 if (enclosingNode && enclosingNode.type === "TypeAlias") {
39897 addLeadingComment$3(enclosingNode, comment);
39904 function handleVariableDeclaratorComments(comment) {
39910 if (enclosingNode && (enclosingNode.type === "VariableDeclarator" || enclosingNode.type === "AssignmentExpression") && followingNode && (followingNode.type === "ObjectExpression" || followingNode.type === "ArrayExpression" || followingNode.type === "TemplateLiteral" || followingNode.type === "TaggedTemplateExpression" || isBlockComment$1(comment))) {
39911 addLeadingComment$3(followingNode, comment);
39918 function handleTSFunctionTrailingComments(comment, text) {
39924 if (!followingNode && enclosingNode && (enclosingNode.type === "TSMethodSignature" || enclosingNode.type === "TSDeclareFunction" || enclosingNode.type === "TSAbstractMethodDefinition") && getNextNonSpaceNonCommentCharacter$1(text, comment, locEnd$3) === ";") {
39925 addTrailingComment$3(enclosingNode, comment);
39932 function handleIgnoreComments(comment) {
39938 if (isPrettierIgnoreComment$1(comment) && enclosingNode && enclosingNode.type === "TSMappedType" && followingNode && followingNode.type === "TSTypeParameter" && followingNode.constraint) {
39939 enclosingNode.prettierIgnore = true;
39940 comment.unignore = true;
39945 function handleTSMappedTypeComments(comment) {
39952 if (!enclosingNode || enclosingNode.type !== "TSMappedType") {
39956 if (followingNode && followingNode.type === "TSTypeParameter" && followingNode.name) {
39957 addLeadingComment$3(followingNode.name, comment);
39961 if (precedingNode && precedingNode.type === "TSTypeParameter" && precedingNode.constraint) {
39962 addTrailingComment$3(precedingNode.constraint, comment);
39969 * @param {any} node
39970 * @param {(comment: any) => boolean} fn
39975 function hasLeadingComment$1(node, fn = () => true) {
39976 if (node.leadingComments) {
39977 return node.leadingComments.some(fn);
39980 if (node.comments) {
39981 return node.comments.some(comment => comment.leading && fn(comment));
39987 function isRealFunctionLikeNode(node) {
39988 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 === "TSMethodSignature" || node.type === "TSConstructorType" || node.type === "TSFunctionType" || node.type === "TSDeclareMethod";
39991 function getGapRegex(enclosingNode) {
39992 if (enclosingNode && enclosingNode.type !== "BinaryExpression" && enclosingNode.type !== "LogicalExpression") {
39993 // Support degenerate single-element unions and intersections.
39994 // E.g.: `type A = /* 1 */ & B`
39995 return /^[\s&(|]*$/;
39999 function getCommentChildNodes(node, options) {
40000 // Prevent attaching comments to FunctionExpression in this case:
40002 // bar() // comment
40007 if ((options.parser === "typescript" || options.parser === "flow" || options.parser === "espree" || options.parser === "meriyah") && node.type === "MethodDefinition" && node.value && node.value.type === "FunctionExpression" && getFunctionParameters$1(node.value).length === 0 && !node.value.returnType && (!node.value.typeParameters || node.value.typeParameters.length === 0) && node.value.body) {
40008 return [...(node.decorators || []), node.key, node.value.body];
40012 function isTypeCastComment(comment) {
40013 return isBlockComment$1(comment) && comment.value[0] === "*" && // TypeScript expects the type to be enclosed in curly brackets, however
40014 // Closure Compiler accepts types in parens and even without any delimiters at all.
40015 // That's why we just search for "@type".
40016 /@type\b/.test(comment.value);
40019 function willPrintOwnComments(path
40022 const node = path.getValue();
40023 const parent = path.getParentNode();
40024 return (node && (isJSXNode$1(node) || hasFlowShorthandAnnotationComment$1(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$1(path) || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType");
40028 handleOwnLineComment,
40029 handleEndOfLineComment,
40030 handleRemainingComment,
40031 hasLeadingComment: hasLeadingComment$1,
40034 getCommentChildNodes,
40035 willPrintOwnComments
40039 getStringWidth: getStringWidth$3,
40040 getIndentSize: getIndentSize$2
40046 hardline: hardline$3,
40047 softline: softline$1,
40051 lineSuffixBoundary: lineSuffixBoundary$1,
40052 addAlignmentToDoc: addAlignmentToDoc$2
40055 printDocToString: printDocToString$2
40062 isBinaryish: isBinaryish$1,
40063 isJestEachTemplateLiteral: isJestEachTemplateLiteral$1,
40064 isSimpleTemplateLiteral: isSimpleTemplateLiteral$1
40067 function printTemplateLiteral(path, print, options) {
40068 const node = path.getValue();
40069 const isTemplateLiteral = node.type === "TemplateLiteral";
40071 if (isTemplateLiteral && isJestEachTemplateLiteral$1(node, path.getParentNode())) {
40072 const printed = printJestEachTemplateLiteral(path, options, print);
40079 let expressionsKey = "expressions";
40081 if (node.type === "TSTemplateLiteralType") {
40082 expressionsKey = "types";
40086 let expressions = path.map(print, expressionsKey);
40087 const isSimple = isSimpleTemplateLiteral$1(node);
40090 expressions = expressions.map(doc => printDocToString$2(doc, Object.assign({}, options, {
40091 printWidth: Infinity
40095 parts.push(lineSuffixBoundary$1, "`");
40096 path.each(childPath => {
40097 const i = childPath.getName();
40098 parts.push(print(childPath));
40100 if (i < expressions.length) {
40101 // For a template literal of the following form:
40108 // the expression is on its own line (there is a \n in the previous
40109 // quasi literal), therefore we want to indent the JavaScript
40110 // expression inside at the beginning of ${ instead of the beginning
40115 const quasi = childPath.getValue();
40116 const indentSize = getIndentSize$2(quasi.value.raw, tabWidth);
40117 let printed = expressions[i];
40120 const expression = node[expressionsKey][i]; // Breaks at the template element boundaries (${ and }) are preferred to breaking
40121 // in the middle of a MemberExpression
40123 if (expression.comments && expression.comments.length || expression.type === "MemberExpression" || expression.type === "OptionalMemberExpression" || expression.type === "ConditionalExpression" || expression.type === "SequenceExpression" || expression.type === "TSAsExpression" || isBinaryish$1(expression)) {
40124 printed = concat$5([indent$2(concat$5([softline$1, printed])), softline$1]);
40128 const aligned = indentSize === 0 && quasi.value.raw.endsWith("\n") ? align$1(-Infinity, printed) : addAlignmentToDoc$2(printed, indentSize, tabWidth);
40129 parts.push(group$1(concat$5(["${", aligned, lineSuffixBoundary$1, "}"])));
40133 return concat$5(parts);
40136 function printJestEachTemplateLiteral(path, options, print) {
40139 * ${1} | ${1} | ${2}
40140 * ${1} | ${2} | ${3}
40141 * ${2} | ${1} | ${3}
40143 const node = path.getNode();
40144 const headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/);
40146 if (headerNames.length > 1 || headerNames.some(headerName => headerName.length !== 0)) {
40147 options.__inJestEach = true;
40148 const expressions = path.map(print, "expressions");
40149 options.__inJestEach = false;
40151 const stringifiedExpressions = expressions.map(doc => "${" + printDocToString$2(doc, Object.assign({}, options, {
40152 printWidth: Infinity,
40154 })).formatted + "}");
40155 const tableBody = [{
40156 hasLineBreak: false,
40160 for (let i = 1; i < node.quasis.length; i++) {
40161 const row = tableBody[tableBody.length - 1];
40162 const correspondingExpression = stringifiedExpressions[i - 1];
40163 row.cells.push(correspondingExpression);
40165 if (correspondingExpression.includes("\n")) {
40166 row.hasLineBreak = true;
40169 if (node.quasis[i].value.raw.includes("\n")) {
40171 hasLineBreak: false,
40177 const maxColumnCount = Math.max(headerNames.length, ...tableBody.map(row => row.cells.length));
40178 const maxColumnWidths = Array.from({
40179 length: maxColumnCount
40183 }, ...tableBody.filter(row => row.cells.length !== 0)];
40187 } of table.filter(row => !row.hasLineBreak)) {
40188 cells.forEach((cell, index) => {
40189 maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$3(cell));
40193 parts.push(lineSuffixBoundary$1, "`", indent$2(concat$5([hardline$3, join$2(hardline$3, table.map(row => join$2(" | ", row.cells.map((cell, index) => row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$3(cell))))))])), hardline$3, "`");
40194 return concat$5(parts);
40198 function printTemplateExpression(path, print) {
40199 const node = path.getValue();
40200 let printed = print(path);
40202 if (node.comments && node.comments.length) {
40203 printed = group$1(concat$5([indent$2(concat$5([softline$1, printed])), softline$1]));
40206 return concat$5(["${", printed, lineSuffixBoundary$1, "}"]);
40209 function printTemplateExpressions(path, print) {
40210 return path.map(path => printTemplateExpression(path, print), "expressions");
40213 function escapeTemplateCharacters(doc, raw) {
40214 return mapDoc$1(doc, currentDoc => {
40215 if (!currentDoc.parts) {
40219 const parts = currentDoc.parts.map(part => {
40220 if (typeof part === "string") {
40221 return raw ? part.replace(/(\\*)`/g, "$1$1\\`") : uncookTemplateElementValue(part);
40226 return Object.assign({}, currentDoc, {
40232 function uncookTemplateElementValue(cookedValue) {
40233 return cookedValue.replace(/([\\`]|\${)/g, "\\$1");
40236 var templateLiteral = {
40237 printTemplateLiteral,
40238 printTemplateExpressions,
40239 escapeTemplateCharacters,
40240 uncookTemplateElementValue
40246 softline: softline$2,
40247 literalline: literalline$2,
40249 dedentToRoot: dedentToRoot$1
40253 escapeTemplateCharacters: escapeTemplateCharacters$1
40254 } = templateLiteral;
40256 function format$1(path, print, textToDoc) {
40257 const node = path.getValue();
40258 let text = node.quasis[0].value.raw.replace(/((?:\\\\)*)\\`/g, (_, backslashes) => "\\".repeat(backslashes.length / 2) + "`");
40259 const indentation = getIndentation(text);
40260 const hasIndent = indentation !== "";
40263 text = text.replace(new RegExp(`^${indentation}`, "gm"), "");
40266 const doc = escapeTemplateCharacters$1(textToDoc(text, {
40267 parser: "markdown",
40268 __inJsTemplate: true
40270 stripTrailingHardline: true
40272 return concat$6(["`", hasIndent ? indent$3(concat$6([softline$2, doc])) : concat$6([literalline$2, dedentToRoot$1(doc)]), softline$2, "`"]);
40275 function getIndentation(str) {
40276 const firstMatchedIndent = str.match(/^([^\S\n]*)\S/m);
40277 return firstMatchedIndent === null ? "" : firstMatchedIndent[1];
40280 var markdown = format$1;
40285 hardline: hardline$4,
40286 softline: softline$3,
40291 replaceNewlinesWithLiterallines: replaceNewlinesWithLiterallines$1
40295 printTemplateExpressions: printTemplateExpressions$1
40296 } = templateLiteral;
40298 function format$2(path, print, textToDoc) {
40299 const node = path.getValue(); // Get full template literal with expressions replaced by placeholders
40301 const rawQuasis = node.quasis.map(q => q.value.raw);
40302 let placeholderID = 0;
40303 const text = rawQuasis.reduce((prevVal, currVal, idx) => {
40304 return idx === 0 ? currVal : prevVal + "@prettier-placeholder-" + placeholderID++ + "-id" + currVal;
40306 const doc = textToDoc(text, {
40309 stripTrailingHardline: true
40311 const expressionDocs = printTemplateExpressions$1(path, print);
40312 return transformCssDoc(doc, node, expressionDocs);
40315 function transformCssDoc(quasisDoc, parentNode, expressionDocs) {
40316 const isEmpty = parentNode.quasis.length === 1 && !parentNode.quasis[0].value.raw.trim();
40322 const newDoc = replacePlaceholders(quasisDoc, expressionDocs);
40323 /* istanbul ignore if */
40326 throw new Error("Couldn't insert all the expressions");
40329 return concat$7(["`", indent$4(concat$7([hardline$4, newDoc])), softline$3, "`"]);
40330 } // Search all the placeholders in the quasisDoc tree
40331 // and replace them with the expression docs one by one
40332 // returns a new doc with all the placeholders replaced,
40333 // or null if it couldn't replace any expression
40336 function replacePlaceholders(quasisDoc, expressionDocs) {
40337 if (!expressionDocs || !expressionDocs.length) {
40341 let replaceCounter = 0;
40342 const newDoc = mapDoc$2(quasisDoc, doc => {
40343 if (!doc || !doc.parts || !doc.parts.length) {
40350 const atIndex = parts.indexOf("@");
40351 const placeholderIndex = atIndex + 1;
40353 if (atIndex > -1 && typeof parts[placeholderIndex] === "string" && parts[placeholderIndex].startsWith("prettier-placeholder")) {
40354 // If placeholder is split, join it
40355 const at = parts[atIndex];
40356 const placeholder = parts[placeholderIndex];
40357 const rest = parts.slice(placeholderIndex + 1);
40358 parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest);
40361 const replacedParts = [];
40362 parts.forEach(part => {
40363 if (typeof part !== "string" || !part.includes("@prettier-placeholder")) {
40364 replacedParts.push(part);
40366 } // When we have multiple placeholders in one line, like:
40367 // ${Child}${Child2}:not(:first-child)
40370 part.split(/@prettier-placeholder-(\d+)-id/).forEach((component, idx) => {
40371 // The placeholder is always at odd indices
40372 if (idx % 2 === 0) {
40373 replacedParts.push(replaceNewlinesWithLiterallines$1(component));
40375 } // The component will always be a number at odd index
40378 replacedParts.push(expressionDocs[component]);
40382 return Object.assign({}, doc, {
40383 parts: replacedParts
40386 return expressionDocs.length === replaceCounter ? newDoc : null;
40389 var css = format$2;
40395 hardline: hardline$5,
40400 escapeTemplateCharacters: escapeTemplateCharacters$2,
40401 printTemplateExpressions: printTemplateExpressions$2
40402 } = templateLiteral;
40404 function format$3(path, print, textToDoc) {
40405 const node = path.getValue();
40406 const numQuasis = node.quasis.length;
40408 if (numQuasis === 1 && node.quasis[0].value.raw.trim() === "") {
40412 const expressionDocs = printTemplateExpressions$2(path, print);
40415 for (let i = 0; i < numQuasis; i++) {
40416 const templateElement = node.quasis[i];
40417 const isFirst = i === 0;
40418 const isLast = i === numQuasis - 1;
40419 const text = templateElement.value.cooked;
40420 const lines = text.split("\n");
40421 const numLines = lines.length;
40422 const expressionDoc = expressionDocs[i];
40423 const startsWithBlankLine = numLines > 2 && lines[0].trim() === "" && lines[1].trim() === "";
40424 const endsWithBlankLine = numLines > 2 && lines[numLines - 1].trim() === "" && lines[numLines - 2].trim() === "";
40425 const commentsAndWhitespaceOnly = lines.every(line => /^\s*(?:#[^\n\r]*)?$/.test(line)); // Bail out if an interpolation occurs within a comment.
40427 if (!isLast && /#[^\n\r]*$/.test(lines[numLines - 1])) {
40433 if (commentsAndWhitespaceOnly) {
40434 doc = printGraphqlComments(lines);
40436 doc = textToDoc(text, {
40439 stripTrailingHardline: true
40444 doc = escapeTemplateCharacters$2(doc, false);
40446 if (!isFirst && startsWithBlankLine) {
40452 if (!isLast && endsWithBlankLine) {
40455 } else if (!isFirst && !isLast && startsWithBlankLine) {
40459 if (expressionDoc) {
40460 parts.push(expressionDoc);
40464 return concat$8(["`", indent$5(concat$8([hardline$5, join$3(hardline$5, parts)])), hardline$5, "`"]);
40467 function printGraphqlComments(lines) {
40469 let seenComment = false;
40470 lines.map(textLine => textLine.trim()).forEach((textLine, i, array) => {
40471 // Lines are either whitespace only, or a comment (with potential whitespace
40472 // around it). Drop whitespace-only lines.
40473 if (textLine === "") {
40477 if (array[i - 1] === "" && seenComment) {
40478 // If a non-first comment is preceded by a blank (whitespace only) line,
40479 // add in a blank line.
40480 parts.push(concat$8([hardline$5, textLine]));
40482 parts.push(textLine);
40485 seenComment = true;
40486 }); // If `lines` was whitespace only, return `null`.
40488 return parts.length === 0 ? null : join$3(hardline$5, parts);
40491 var graphql = format$3;
40497 hardline: hardline$6,
40506 printTemplateExpressions: printTemplateExpressions$3,
40507 uncookTemplateElementValue: uncookTemplateElementValue$1
40508 } = templateLiteral; // The counter is needed to distinguish nested embeds.
40510 let htmlTemplateLiteralCounter = 0;
40512 function format$4(path, print, textToDoc, options, {
40515 const node = path.getValue();
40516 const counter = htmlTemplateLiteralCounter;
40517 htmlTemplateLiteralCounter = htmlTemplateLiteralCounter + 1 >>> 0;
40519 const composePlaceholder = index => `PRETTIER_HTML_PLACEHOLDER_${index}_${counter}_IN_JS`;
40521 const text = node.quasis.map((quasi, index, quasis) => index === quasis.length - 1 ? quasi.value.cooked : quasi.value.cooked + composePlaceholder(index)).join("");
40522 const expressionDocs = printTemplateExpressions$3(path, print);
40524 if (expressionDocs.length === 0 && text.trim().length === 0) {
40528 const placeholderRegex = new RegExp(composePlaceholder("(\\d+)"), "g");
40529 let topLevelCount = 0;
40530 const doc = textToDoc(text, {
40533 __onHtmlRoot(root) {
40534 topLevelCount = root.children.length;
40538 stripTrailingHardline: true
40540 const contentDoc = mapDoc$3(doc, doc => {
40541 if (typeof doc !== "string") {
40546 const components = doc.split(placeholderRegex);
40548 for (let i = 0; i < components.length; i++) {
40549 let component = components[i];
40553 component = uncookTemplateElementValue$1(component);
40555 if (options.embeddedInHtml) {
40556 component = component.replace(/<\/(script)\b/gi, "<\\/$1");
40559 parts.push(component);
40565 const placeholderIndex = +component;
40566 parts.push(expressionDocs[placeholderIndex]);
40569 return concat$9(parts);
40571 const leadingWhitespace = /^\s/.test(text) ? " " : "";
40572 const trailingWhitespace = /\s$/.test(text) ? " " : "";
40573 const linebreak = options.htmlWhitespaceSensitivity === "ignore" ? hardline$6 : leadingWhitespace && trailingWhitespace ? line$3 : null;
40576 return group$2(concat$9(["`", indent$6(concat$9([linebreak, group$2(contentDoc)])), linebreak, "`"]));
40579 return group$2(concat$9(["`", leadingWhitespace, topLevelCount > 1 ? indent$6(group$2(contentDoc)) : group$2(contentDoc), trailingWhitespace, "`"]));
40582 var html = format$4;
40585 isBlockComment: isBlockComment$2
40588 hasLeadingComment: hasLeadingComment$2
40591 function getLanguage(path) {
40592 if (isStyledJsx(path) || isStyledComponents(path) || isCssProp(path) || isAngularComponentStyles(path)) {
40596 if (isGraphQL(path)) {
40600 if (isHtml(path)) {
40604 if (isAngularComponentTemplate(path)) {
40608 if (isMarkdown(path)) {
40613 function embed(path, print, textToDoc, options) {
40614 const node = path.getValue();
40616 if (node.type !== "TemplateLiteral" || // Bail out if any of the quasis have an invalid escape sequence
40617 // (which would make the `cooked` value be `null`)
40618 hasInvalidCookedValue(node)) {
40622 const language = getLanguage(path);
40628 if (language === "markdown") {
40629 return markdown(path, print, textToDoc);
40632 if (language === "css") {
40633 return css(path, print, textToDoc);
40636 if (language === "graphql") {
40637 return graphql(path, print, textToDoc);
40640 if (language === "html" || language === "angular") {
40641 return html(path, print, textToDoc, options, {
40652 function isMarkdown(path) {
40653 const node = path.getValue();
40654 const parent = path.getParentNode();
40655 return parent && parent.type === "TaggedTemplateExpression" && node.quasis.length === 1 && parent.tag.type === "Identifier" && (parent.tag.name === "md" || parent.tag.name === "markdown");
40658 * Template literal in these contexts:
40659 * <style jsx>{`div{color:red}`}</style>
40666 function isStyledJsx(path) {
40667 const node = path.getValue();
40668 const parent = path.getParentNode();
40669 const parentParent = path.getParentNode(1);
40670 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");
40673 * Angular Components can have:
40674 * - Inline HTML template
40675 * - Inline CSS styles
40677 * ...which are both within template literals somewhere
40678 * inside of the Component decorator factory.
40682 * template: `<div>...</div>`,
40683 * styles: [`h1 { color: blue; }`]
40688 function isAngularComponentStyles(path) {
40689 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);
40692 function isAngularComponentTemplate(path) {
40693 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);
40696 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"];
40698 * styled-components template literals
40701 function isStyledComponents(path) {
40702 const parent = path.getParentNode();
40704 if (!parent || parent.type !== "TaggedTemplateExpression") {
40712 switch (tag.type) {
40713 case "MemberExpression":
40714 return (// styled.foo``
40715 isStyledIdentifier(tag.object) || // Component.extend``
40716 isStyledExtend(tag)
40719 case "CallExpression":
40720 return (// styled(Component)``
40721 isStyledIdentifier(tag.callee) || tag.callee.type === "MemberExpression" && (tag.callee.object.type === "MemberExpression" && ( // styled.foo.attrs({})``
40722 isStyledIdentifier(tag.callee.object.object) || // Component.extend.attrs({})``
40723 isStyledExtend(tag.callee.object)) || // styled(Component).attrs({})``
40724 tag.callee.object.type === "CallExpression" && isStyledIdentifier(tag.callee.object.callee))
40729 return tag.name === "css";
40736 * JSX element with CSS prop
40740 function isCssProp(path) {
40741 const parent = path.getParentNode();
40742 const parentParent = path.getParentNode(1);
40743 return parentParent && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" && parentParent.name.type === "JSXIdentifier" && parentParent.name.name === "css";
40746 function isStyledIdentifier(node) {
40747 return node.type === "Identifier" && node.name === "styled";
40750 function isStyledExtend(node) {
40751 return /^[A-Z]/.test(node.object.name) && node.property.name === "extend";
40754 * react-relay and graphql-tag
40756 * graphql.experimental`...`
40758 * GraphQL comment block
40760 * This intentionally excludes Relay Classic tags, as Prettier does not
40761 * support Relay Classic formatting.
40765 function isGraphQL(path) {
40766 const node = path.getValue();
40767 const parent = path.getParentNode();
40768 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");
40771 function hasLanguageComment(node, languageName) {
40772 // This checks for a leading comment that is exactly `/* GraphQL */`
40773 // In order to be in line with other implementations of this comment tag
40774 // we will not trim the comment value and we will expect exactly one space on
40775 // either side of the GraphQL string
40776 // Also see ./clean.js
40777 return hasLeadingComment$2(node, comment => isBlockComment$2(comment) && comment.value === ` ${languageName} `);
40781 * - HTML comment block
40785 function isHtml(path) {
40786 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");
40789 function hasInvalidCookedValue({
40792 return quasis.some(({
40796 }) => cooked === null);
40799 var embed_1 = embed;
40802 isBlockComment: isBlockComment$3
40804 const ignoredProperties = new Set(["range", "raw", "comments", "leadingComments", "trailingComments", "innerComments", "extra", "start", "end", "loc", "flags", "errors", "tokens"]);
40806 function clean(ast, newObj, parent) {
40807 if (ast.type === "Program") {
40808 delete newObj.sourceType;
40811 if (ast.type === "BigIntLiteral" || ast.type === "BigIntLiteralTypeAnnotation") {
40812 if (newObj.value) {
40813 newObj.value = newObj.value.toLowerCase();
40817 if (ast.type === "BigIntLiteral" || ast.type === "Literal") {
40818 if (newObj.bigint) {
40819 newObj.bigint = newObj.bigint.toLowerCase();
40823 if (ast.type === "DecimalLiteral") {
40824 newObj.value = Number(newObj.value);
40825 } // We remove extra `;` and add them when needed
40828 if (ast.type === "EmptyStatement") {
40830 } // We move text around, including whitespaces and add {" "}
40833 if (ast.type === "JSXText") {
40837 if (ast.type === "JSXExpressionContainer" && (ast.expression.type === "Literal" || ast.expression.type === "StringLiteral") && ast.expression.value === " ") {
40839 } // We change {'key': value} into {key: value}.
40840 // And {key: value} into {'key': value}.
40841 // Also for (some) number keys.
40844 if ((ast.type === "Property" || ast.type === "ObjectProperty" || ast.type === "MethodDefinition" || ast.type === "ClassProperty" || ast.type === "ClassMethod" || ast.type === "FieldDefinition" || ast.type === "TSDeclareMethod" || ast.type === "TSPropertySignature" || ast.type === "ObjectTypeProperty") && typeof ast.key === "object" && ast.key && (ast.key.type === "Literal" || ast.key.type === "NumericLiteral" || ast.key.type === "StringLiteral" || ast.key.type === "Identifier")) {
40848 if (ast.type === "OptionalMemberExpression" && ast.optional === false) {
40849 newObj.type = "MemberExpression";
40850 delete newObj.optional;
40851 } // Remove raw and cooked values from TemplateElement when it's CSS
40855 if (ast.type === "JSXElement" && ast.openingElement.name.name === "style" && ast.openingElement.attributes.some(attr => attr.name.name === "jsx")) {
40856 const templateLiterals = newObj.children.filter(child => child.type === "JSXExpressionContainer" && child.expression.type === "TemplateLiteral").map(container => container.expression);
40857 const quasis = templateLiterals.reduce((quasis, templateLiteral) => quasis.concat(templateLiteral.quasis), []);
40858 quasis.forEach(q => delete q.value);
40859 } // CSS template literals in css prop
40862 if (ast.type === "JSXAttribute" && ast.name.name === "css" && ast.value.type === "JSXExpressionContainer" && ast.value.expression.type === "TemplateLiteral") {
40863 newObj.value.expression.quasis.forEach(q => delete q.value);
40864 } // We change quotes
40867 if (ast.type === "JSXAttribute" && ast.value && ast.value.type === "Literal" && /["']|"|'/.test(ast.value.value)) {
40868 newObj.value.value = newObj.value.value.replace(/["']|"|'/g, '"');
40869 } // Angular Components: Inline HTML template and Inline CSS styles
40872 const expression = ast.expression || ast.callee;
40874 if (ast.type === "Decorator" && expression.type === "CallExpression" && expression.callee.name === "Component" && expression.arguments.length === 1) {
40875 const astProps = ast.expression.arguments[0].properties;
40876 newObj.expression.arguments[0].properties.forEach((prop, index) => {
40877 let templateLiteral = null;
40879 switch (astProps[index].key.name) {
40881 if (prop.value.type === "ArrayExpression") {
40882 templateLiteral = prop.value.elements[0];
40888 if (prop.value.type === "TemplateLiteral") {
40889 templateLiteral = prop.value;
40895 if (templateLiteral) {
40896 templateLiteral.quasis.forEach(q => delete q.value);
40899 } // styled-components, graphql, markdown
40902 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")) {
40903 newObj.quasi.quasis.forEach(quasi => delete quasi.value);
40906 if (ast.type === "TemplateLiteral") {
40907 // This checks for a leading comment that is exactly `/* GraphQL */`
40908 // In order to be in line with other implementations of this comment tag
40909 // we will not trim the comment value and we will expect exactly one space on
40910 // either side of the GraphQL string
40911 // Also see ./embed.js
40912 const hasLanguageComment = ast.leadingComments && ast.leadingComments.some(comment => isBlockComment$3(comment) && ["GraphQL", "HTML"].some(languageName => comment.value === ` ${languageName} `));
40914 if (hasLanguageComment || parent.type === "CallExpression" && parent.callee.name === "graphql") {
40915 newObj.quasis.forEach(quasi => delete quasi.value);
40916 } // TODO: check parser
40917 // `flow` and `typescript` don't have `leadingComments`
40920 if (!ast.leadingComments) {
40921 newObj.quasis.forEach(quasi => {
40923 delete quasi.value.cooked;
40929 if (ast.type === "InterpreterDirective") {
40930 newObj.value = newObj.value.trimEnd();
40934 clean.ignoredProperties = ignoredProperties;
40935 var clean_1 = clean;
40937 const detectNewline = string => {
40938 if (typeof string !== 'string') {
40939 throw new TypeError('Expected a string');
40942 const newlines = string.match(/(?:\r?\n)/g) || [];
40944 if (newlines.length === 0) {
40948 const crlf = newlines.filter(newline => newline === '\r\n').length;
40949 const lf = newlines.length - crlf;
40950 return crlf > lf ? '\r\n' : '\n';
40953 var detectNewline_1 = detectNewline;
40955 var graceful = string => typeof string === 'string' && detectNewline(string) || '\n';
40956 detectNewline_1.graceful = graceful;
40958 var build = createCommonjsModule(function (module, exports) {
40960 Object.defineProperty(exports, '__esModule', {
40963 exports.extract = extract;
40964 exports.strip = strip;
40965 exports.parse = parse;
40966 exports.parseWithComments = parseWithComments;
40967 exports.print = print;
40970 const data = os__default['default'];
40972 _os = function () {
40979 function _detectNewline() {
40980 const data = _interopRequireDefault(detectNewline_1);
40982 _detectNewline = function () {
40989 function _interopRequireDefault(obj) {
40990 return obj && obj.__esModule ? obj : {
40995 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
40997 * This source code is licensed under the MIT license found in the
40998 * LICENSE file in the root directory of this source tree.
41002 const commentEndRe = /\*\/$/;
41003 const commentStartRe = /^\/\*\*/;
41004 const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/;
41005 const lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g;
41006 const ltrimNewlineRe = /^(\r?\n)+/;
41007 const multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
41008 const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
41009 const stringStartRe = /(\r?\n|^) *\* ?/g;
41010 const STRING_ARRAY = [];
41012 function extract(contents) {
41013 const match = contents.match(docblockRe);
41014 return match ? match[0].trimLeft() : '';
41017 function strip(contents) {
41018 const match = contents.match(docblockRe);
41019 return match && match[0] ? contents.substring(match[0].length) : contents;
41022 function parse(docblock) {
41023 return parseWithComments(docblock).pragmas;
41026 function parseWithComments(docblock) {
41027 const line = (0, _detectNewline().default)(docblock) || _os().EOL;
41029 docblock = docblock.replace(commentStartRe, '').replace(commentEndRe, '').replace(stringStartRe, '$1'); // Normalize multi-line directives
41033 while (prev !== docblock) {
41035 docblock = docblock.replace(multilineRe, `${line}$1 $2${line}`);
41038 docblock = docblock.replace(ltrimNewlineRe, '').trimRight();
41039 const result = Object.create(null);
41040 const comments = docblock.replace(propertyRe, '').replace(ltrimNewlineRe, '').trimRight();
41043 while (match = propertyRe.exec(docblock)) {
41044 // strip linecomments from pragmas
41045 const nextPragma = match[2].replace(lineCommentRe, '');
41047 if (typeof result[match[1]] === 'string' || Array.isArray(result[match[1]])) {
41048 result[match[1]] = STRING_ARRAY.concat(result[match[1]], nextPragma);
41050 result[match[1]] = nextPragma;
41064 const line = (0, _detectNewline().default)(comments) || _os().EOL;
41066 const head = '/**';
41067 const start = ' *';
41068 const tail = ' */';
41069 const keys = Object.keys(pragmas);
41070 const printedObject = keys.map(key => printKeyValues(key, pragmas[key])).reduce((arr, next) => arr.concat(next), []).map(keyValue => start + ' ' + keyValue + line).join('');
41073 if (keys.length === 0) {
41077 if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) {
41078 const value = pragmas[keys[0]];
41079 return `${head} ${printKeyValues(keys[0], value)[0]}${tail}`;
41083 const printedComments = comments.split(line).map(textLine => `${start} ${textLine}`).join(line) + line;
41084 return head + line + (comments ? printedComments : '') + (comments && keys.length ? start + line : '') + printedObject + tail;
41087 function printKeyValues(key, valueOrArray) {
41088 return STRING_ARRAY.concat(valueOrArray).map(value => `@${key} ${value}`.trim());
41099 getShebang: getShebang$1
41102 normalizeEndOfLine: normalizeEndOfLine$2
41105 function parseDocBlock(text) {
41106 const shebang = getShebang$1(text);
41109 text = text.slice(shebang.length + 1);
41112 const docBlock = extract(text);
41116 } = parseWithComments(docBlock);
41125 function hasPragma(text) {
41126 const pragmas = Object.keys(parseDocBlock(text).pragmas);
41127 return pragmas.includes("prettier") || pragmas.includes("format");
41130 function insertPragma(originalText) {
41136 } = parseDocBlock(originalText);
41137 const strippedText = strip(text);
41138 const docBlock = print({
41139 pragmas: Object.assign({
41142 comments: comments.trimStart()
41144 return (shebang ? `${shebang}\n` : "") + // normalise newlines (mitigate use of os.EOL by jest-docblock)
41145 normalizeEndOfLine$2(docBlock) + (strippedText.startsWith("\n") ? "\n" : "\n\n") + strippedText;
41154 getFunctionParameters: getFunctionParameters$2,
41155 getLeftSidePathName: getLeftSidePathName$1,
41156 hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$2,
41157 hasNakedLeftSide: hasNakedLeftSide$1,
41158 hasNode: hasNode$1,
41159 isBitwiseOperator: isBitwiseOperator$1,
41160 startsWithNoLookaheadToken: startsWithNoLookaheadToken$1,
41161 shouldFlatten: shouldFlatten$1,
41162 getPrecedence: getPrecedence$1
41165 function needsParens(path, options) {
41166 const parent = path.getParentNode();
41172 const name = path.getName();
41173 const node = path.getNode(); // to avoid unexpected `}}` in HTML interpolations
41175 if (options.__isInHtmlInterpolation && !options.bracketSpacing && endsWithRightBracket(node) && isFollowedByRightBracket(path)) {
41177 } // Only statements don't need parentheses.
41180 if (isStatement(node)) {
41184 if ( // Preserve parens if we have a Flow annotation comment, unless we're using the Flow
41185 // parser. The Flow parser turns Flow comments into type annotation nodes in its
41186 // AST, which we handle separately.
41187 options.parser !== "flow" && hasFlowShorthandAnnotationComment$2(path.getValue())) {
41189 } // Identifiers never need parentheses.
41192 if (node.type === "Identifier") {
41193 // ...unless those identifiers are embed placeholders. They might be substituted by complex
41194 // expressions, so the parens around them should not be dropped. Example (JS-in-HTML-in-JS):
41195 // let tpl = html`<script> f((${expr}) / 2); </script>`;
41196 // If the inner JS formatter removes the parens, the expression might change its meaning:
41197 // f((a + b) / 2) vs f(a + b / 2)
41198 if (node.extra && node.extra.parenthesized && /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(node.name)) {
41205 switch (parent.type) {
41206 case "ParenthesizedExpression":
41209 case "ClassDeclaration":
41210 case "ClassExpression":
41212 // Add parens around the extends clause of a class. It is needed for almost
41213 // all expressions.
41214 if (name === "superClass" && (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")) {
41221 case "ExportDefaultDeclaration":
41223 return (// `export default function` or `export default class` can't be followed by
41224 // anything after. So an expression like `export default (function(){}).toString()`
41225 // needs to be followed by a parentheses
41226 shouldWrapFunctionForExportDefault(path, options) || // `export default (foo, bar)` also needs parentheses
41227 node.type === "SequenceExpression"
41233 if (name === "expression") {
41234 let hasCallExpression = false;
41235 let hasMemberExpression = false;
41236 let current = node;
41239 switch (current.type) {
41240 case "MemberExpression":
41241 hasMemberExpression = true;
41242 current = current.object;
41245 case "CallExpression":
41248 hasMemberExpression ||
41250 hasCallExpression) {
41254 hasCallExpression = true;
41255 current = current.callee;
41272 case "ExpressionStatement":
41274 if (startsWithNoLookaheadToken$1(node,
41275 /* forbidFunctionClassAndDoExpr */
41283 case "ArrowFunctionExpression":
41285 if (name === "body" && node.type !== "SequenceExpression" && // these have parens added anyway
41286 startsWithNoLookaheadToken$1(node,
41287 /* forbidFunctionClassAndDoExpr */
41296 switch (node.type) {
41297 case "SpreadElement":
41298 case "SpreadProperty":
41299 return name === "object" && parent.type === "MemberExpression";
41301 case "UpdateExpression":
41302 if (parent.type === "UnaryExpression") {
41303 return node.prefix && (node.operator === "++" && parent.operator === "+" || node.operator === "--" && parent.operator === "-");
41306 // else fallthrough
41308 case "UnaryExpression":
41309 switch (parent.type) {
41310 case "UnaryExpression":
41311 return node.operator === parent.operator && (node.operator === "+" || node.operator === "-");
41313 case "BindExpression":
41316 case "MemberExpression":
41317 case "OptionalMemberExpression":
41318 return name === "object";
41320 case "TaggedTemplateExpression":
41323 case "NewExpression":
41324 case "CallExpression":
41325 case "OptionalCallExpression":
41326 return name === "callee";
41328 case "BinaryExpression":
41329 return name === "left" && parent.operator === "**";
41331 case "TSNonNullExpression":
41338 case "BinaryExpression":
41340 if (parent.type === "UpdateExpression" || parent.type === "PipelineTopicExpression" && node.operator === "|>") {
41342 } // We add parentheses to any `a in b` inside `ForStatement` initializer
41343 // https://github.com/prettier/prettier/issues/907#issuecomment-284304321
41346 if (node.operator === "in" && isPathInForStatementInitializer(path)) {
41350 if (node.operator === "|>" && node.extra && node.extra.parenthesized) {
41351 const grandParent = path.getParentNode(1);
41353 if (grandParent.type === "BinaryExpression" && grandParent.operator === "|>") {
41360 case "TSTypeAssertion":
41361 case "TSAsExpression":
41362 case "LogicalExpression":
41363 switch (parent.type) {
41364 case "ConditionalExpression":
41365 return node.type === "TSAsExpression";
41367 case "CallExpression":
41368 case "NewExpression":
41369 case "OptionalCallExpression":
41370 return name === "callee";
41372 case "ClassExpression":
41373 case "ClassDeclaration":
41374 return name === "superClass";
41376 case "TSTypeAssertion":
41377 case "TaggedTemplateExpression":
41378 case "UnaryExpression":
41379 case "JSXSpreadAttribute":
41380 case "SpreadElement":
41381 case "SpreadProperty":
41382 case "BindExpression":
41383 case "AwaitExpression":
41384 case "TSAsExpression":
41385 case "TSNonNullExpression":
41386 case "UpdateExpression":
41389 case "MemberExpression":
41390 case "OptionalMemberExpression":
41391 return name === "object";
41393 case "AssignmentExpression":
41394 return name === "left" && (node.type === "TSTypeAssertion" || node.type === "TSAsExpression");
41396 case "LogicalExpression":
41397 if (node.type === "LogicalExpression") {
41398 return parent.operator !== node.operator;
41401 // else fallthrough
41403 case "BinaryExpression":
41410 if (!operator && type !== "TSTypeAssertion") {
41414 const precedence = getPrecedence$1(operator);
41415 const parentOperator = parent.operator;
41416 const parentPrecedence = getPrecedence$1(parentOperator);
41418 if (parentPrecedence > precedence) {
41422 if (name === "right" && parentPrecedence === precedence) {
41426 if (parentPrecedence === precedence && !shouldFlatten$1(parentOperator, operator)) {
41430 if (parentPrecedence < precedence && operator === "%") {
41431 return parentOperator === "+" || parentOperator === "-";
41432 } // Add parenthesis when working with bitwise operators
41433 // It's not strictly needed but helps with code understanding
41436 if (isBitwiseOperator$1(parentOperator)) {
41447 case "SequenceExpression":
41448 switch (parent.type) {
41449 case "ReturnStatement":
41452 case "ForStatement":
41453 // Although parentheses wouldn't hurt around sequence
41454 // expressions in the head of for loops, traditional style
41455 // dictates that e.g. i++, j++ should not be wrapped with
41459 case "ExpressionStatement":
41460 return name !== "expression";
41462 case "ArrowFunctionExpression":
41463 // We do need parentheses, but SequenceExpressions are handled
41464 // specially when printing bodies of arrow functions.
41465 return name !== "body";
41468 // Otherwise err on the side of overparenthesization, adding
41469 // explicit exceptions above if this proves overzealous.
41473 case "YieldExpression":
41474 if (parent.type === "UnaryExpression" || parent.type === "AwaitExpression" || parent.type === "TSAsExpression" || parent.type === "TSNonNullExpression") {
41478 // else fallthrough
41480 case "AwaitExpression":
41481 switch (parent.type) {
41482 case "TaggedTemplateExpression":
41483 case "UnaryExpression":
41484 case "LogicalExpression":
41485 case "SpreadElement":
41486 case "SpreadProperty":
41487 case "TSAsExpression":
41488 case "TSNonNullExpression":
41489 case "BindExpression":
41492 case "MemberExpression":
41493 case "OptionalMemberExpression":
41494 return name === "object";
41496 case "NewExpression":
41497 case "CallExpression":
41498 case "OptionalCallExpression":
41499 return name === "callee";
41501 case "ConditionalExpression":
41502 return name === "test";
41504 case "BinaryExpression":
41506 if (!node.argument && parent.operator === "|>") {
41517 case "TSJSDocFunctionType":
41518 case "TSConditionalType":
41519 if (name === "extendsType" && parent.type === "TSConditionalType") {
41525 case "TSFunctionType":
41526 case "TSConstructorType":
41527 if (name === "checkType" && parent.type === "TSConditionalType") {
41533 case "TSUnionType":
41534 case "TSIntersectionType":
41535 if (parent.type === "TSUnionType" || parent.type === "TSIntersectionType") {
41541 case "TSInferType":
41542 if (node.type === "TSInferType" && parent.type === "TSRestType") {
41548 case "TSTypeOperator":
41549 return parent.type === "TSArrayType" || parent.type === "TSOptionalType" || parent.type === "TSRestType" || name === "objectType" && parent.type === "TSIndexedAccessType" || parent.type === "TSTypeOperator" || parent.type === "TSTypeAnnotation" && /^TSJSDoc/.test(path.getParentNode(1).type);
41551 case "ArrayTypeAnnotation":
41552 return parent.type === "NullableTypeAnnotation";
41554 case "IntersectionTypeAnnotation":
41555 case "UnionTypeAnnotation":
41556 return parent.type === "ArrayTypeAnnotation" || parent.type === "NullableTypeAnnotation" || parent.type === "IntersectionTypeAnnotation" || parent.type === "UnionTypeAnnotation";
41558 case "NullableTypeAnnotation":
41559 return parent.type === "ArrayTypeAnnotation";
41561 case "FunctionTypeAnnotation":
41563 const ancestor = parent.type === "NullableTypeAnnotation" ? path.getParentNode(1) : parent;
41564 return ancestor.type === "UnionTypeAnnotation" || ancestor.type === "IntersectionTypeAnnotation" || ancestor.type === "ArrayTypeAnnotation" || // We should check ancestor's parent to know whether the parentheses
41565 // are really needed, but since ??T doesn't make sense this check
41566 // will almost never be true.
41567 ancestor.type === "NullableTypeAnnotation" || // See #5283
41568 parent.type === "FunctionTypeParam" && parent.name === null && getFunctionParameters$2(node).some(param => param.typeAnnotation && param.typeAnnotation.type === "NullableTypeAnnotation");
41571 case "StringLiteral":
41572 case "NumericLiteral":
41574 if (typeof node.value === "string" && parent.type === "ExpressionStatement" && !parent.directive) {
41575 // To avoid becoming a directive
41576 const grandParent = path.getParentNode(1);
41577 return grandParent.type === "Program" || grandParent.type === "BlockStatement";
41580 return name === "object" && parent.type === "MemberExpression" && typeof node.value === "number";
41582 case "AssignmentExpression":
41584 const grandParent = path.getParentNode(1);
41586 if (name === "body" && parent.type === "ArrowFunctionExpression") {
41588 } else if (name === "key" && (parent.type === "ClassProperty" || parent.type === "FieldDefinition") && parent.computed) {
41590 } else if ((name === "init" || name === "update") && parent.type === "ForStatement") {
41592 } else if (parent.type === "ExpressionStatement") {
41593 return node.left.type === "ObjectPattern";
41594 } else if (name === "key" && parent.type === "TSPropertySignature") {
41596 } else if (parent.type === "AssignmentExpression") {
41598 } else if (parent.type === "SequenceExpression" && grandParent && grandParent.type === "ForStatement" && (grandParent.init === parent || grandParent.update === parent)) {
41600 } else if (name === "value" && parent.type === "Property" && grandParent && grandParent.type === "ObjectPattern" && grandParent.properties.includes(parent)) {
41602 } else if (parent.type === "NGChainedExpression") {
41609 case "ConditionalExpression":
41610 switch (parent.type) {
41611 case "TaggedTemplateExpression":
41612 case "UnaryExpression":
41613 case "SpreadElement":
41614 case "SpreadProperty":
41615 case "BinaryExpression":
41616 case "LogicalExpression":
41617 case "NGPipeExpression":
41618 case "ExportDefaultDeclaration":
41619 case "AwaitExpression":
41620 case "JSXSpreadAttribute":
41621 case "TSTypeAssertion":
41622 case "TypeCastExpression":
41623 case "TSAsExpression":
41624 case "TSNonNullExpression":
41627 case "NewExpression":
41628 case "CallExpression":
41629 case "OptionalCallExpression":
41630 return name === "callee";
41632 case "ConditionalExpression":
41633 return name === "test";
41635 case "MemberExpression":
41636 case "OptionalMemberExpression":
41637 return name === "object";
41643 case "FunctionExpression":
41644 switch (parent.type) {
41645 case "NewExpression":
41646 case "CallExpression":
41647 case "OptionalCallExpression":
41648 // Not always necessary, but it's clearer to the reader if IIFEs are wrapped in parentheses.
41649 // Is necessary if it is `expression` of `ExpressionStatement`.
41650 return name === "callee";
41652 case "TaggedTemplateExpression":
41654 // This is basically a kind of IIFE.
41660 case "ArrowFunctionExpression":
41661 switch (parent.type) {
41662 case "PipelineTopicExpression":
41663 return !!(node.extra && node.extra.parenthesized);
41665 case "BinaryExpression":
41666 return parent.operator !== "|>" || node.extra && node.extra.parenthesized;
41668 case "NewExpression":
41669 case "CallExpression":
41670 case "OptionalCallExpression":
41671 return name === "callee";
41673 case "MemberExpression":
41674 case "OptionalMemberExpression":
41675 return name === "object";
41677 case "TSAsExpression":
41678 case "BindExpression":
41679 case "TaggedTemplateExpression":
41680 case "UnaryExpression":
41681 case "LogicalExpression":
41682 case "AwaitExpression":
41683 case "TSTypeAssertion":
41686 case "ConditionalExpression":
41687 return name === "test";
41693 case "ClassExpression":
41694 switch (parent.type) {
41695 case "NewExpression":
41696 return name === "callee";
41702 case "OptionalMemberExpression":
41703 case "OptionalCallExpression":
41705 const parentParent = path.getParentNode(1);
41707 if (name === "object" && parent.type === "MemberExpression" || name === "callee" && (parent.type === "CallExpression" || parent.type === "NewExpression") || parent.type === "TSNonNullExpression" && parentParent.type === "MemberExpression" && parentParent.object === parent) {
41713 case "CallExpression":
41714 case "MemberExpression":
41715 case "TaggedTemplateExpression":
41716 case "TSNonNullExpression":
41717 if (name === "callee" && (parent.type === "BindExpression" || parent.type === "NewExpression")) {
41721 switch (object.type) {
41722 case "CallExpression":
41723 case "OptionalCallExpression":
41726 case "MemberExpression":
41727 case "OptionalMemberExpression":
41728 case "BindExpression":
41729 object = object.object;
41731 // tagged templates are basically member expressions from a grammar perspective
41732 // see https://tc39.github.io/ecma262/#prod-MemberExpression
41734 case "TaggedTemplateExpression":
41735 object = object.tag;
41738 case "TSNonNullExpression":
41739 object = object.expression;
41750 case "BindExpression":
41751 return name === "callee" && (parent.type === "BindExpression" || parent.type === "NewExpression") || name === "object" && (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression");
41753 case "NGPipeExpression":
41754 if (parent.type === "NGRoot" || parent.type === "NGMicrosyntaxExpression" || parent.type === "ObjectProperty" && // Preserve parens for compatibility with AngularJS expressions
41755 !(node.extra && node.extra.parenthesized) || parent.type === "ArrayExpression" || (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.arguments[name] === node || name === "right" && parent.type === "NGPipeExpression" || name === "property" && parent.type === "MemberExpression" || parent.type === "AssignmentExpression") {
41761 case "JSXFragment":
41763 return name === "callee" || name === "left" && parent.type === "BinaryExpression" && parent.operator === "<" || 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";
41765 case "TypeAnnotation":
41766 return name === "returnType" && parent.type === "ArrowFunctionExpression" && includesFunctionTypeInObjectType(node);
41772 function isStatement(node) {
41773 return node.type === "BlockStatement" || node.type === "BreakStatement" || node.type === "ClassBody" || node.type === "ClassDeclaration" || node.type === "ClassMethod" || node.type === "ClassProperty" || node.type === "FieldDefinition" || 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";
41776 function isPathInForStatementInitializer(path) {
41778 let node = path.getValue();
41781 const parent = path.getParentNode(i++);
41783 if (parent && parent.type === "ForStatement" && parent.init === node) {
41793 function includesFunctionTypeInObjectType(node) {
41794 return hasNode$1(node, n1 => n1.type === "ObjectTypeAnnotation" && hasNode$1(n1, n2 => n2.type === "FunctionTypeAnnotation" || undefined) || undefined);
41797 function endsWithRightBracket(node) {
41798 switch (node.type) {
41799 case "ObjectExpression":
41807 function isFollowedByRightBracket(path) {
41808 const node = path.getValue();
41809 const parent = path.getParentNode();
41810 const name = path.getName();
41812 switch (parent.type) {
41813 case "NGPipeExpression":
41814 if (typeof name === "number" && parent.arguments[name] === node && parent.arguments.length - 1 === name) {
41815 return path.callParent(isFollowedByRightBracket);
41820 case "ObjectProperty":
41821 if (name === "value") {
41822 const parentParent = path.getParentNode(1);
41823 return parentParent.properties[parentParent.properties.length - 1] === parent;
41828 case "BinaryExpression":
41829 case "LogicalExpression":
41830 if (name === "right") {
41831 return path.callParent(isFollowedByRightBracket);
41836 case "ConditionalExpression":
41837 if (name === "alternate") {
41838 return path.callParent(isFollowedByRightBracket);
41843 case "UnaryExpression":
41844 if (parent.prefix) {
41845 return path.callParent(isFollowedByRightBracket);
41854 function shouldWrapFunctionForExportDefault(path, options) {
41855 const node = path.getValue();
41856 const parent = path.getParentNode();
41858 if (node.type === "FunctionExpression" || node.type === "ClassExpression") {
41859 return parent.type === "ExportDefaultDeclaration" || // in some cases the function is already wrapped
41860 // (e.g. `export default (function() {})();`)
41861 // in this case we don't need to add extra parens
41862 !needsParens(path, options);
41865 if (!hasNakedLeftSide$1(node) || parent.type !== "ExportDefaultDeclaration" && needsParens(path, options)) {
41869 return path.call(childPath => shouldWrapFunctionForExportDefault(childPath, options), ...getLeftSidePathName$1(path, node));
41872 var needsParens_1 = needsParens;
41880 softline: softline$4,
41885 function printHtmlBinding(path, options, print) {
41886 const node = path.getValue();
41888 if (options.__onHtmlBindingRoot && path.getName() === null) {
41889 options.__onHtmlBindingRoot(node, options);
41892 if (node.type !== "File") {
41896 if (options.__isVueForBindingLeft) {
41897 return path.call(functionDeclarationPath => {
41898 const printed = join$4(concat$a([",", line$4]), functionDeclarationPath.map(print, "params"));
41901 } = functionDeclarationPath.getValue();
41903 if (params.length === 1) {
41907 return concat$a(["(", indent$7(concat$a([softline$4, group$3(printed)])), softline$4, ")"]);
41908 }, "program", "body", 0);
41911 if (options.__isVueBindings) {
41912 return path.call(functionDeclarationPath => join$4(concat$a([",", line$4]), functionDeclarationPath.map(print, "params")), "program", "body", 0);
41914 } // based on https://github.com/prettier/prettier/blob/master/src/language-html/syntax-vue.js isVueEventBindingExpression()
41917 function isVueEventBindingExpression(node) {
41918 switch (node.type) {
41919 case "MemberExpression":
41920 switch (node.property.type) {
41922 case "NumericLiteral":
41923 case "StringLiteral":
41924 return isVueEventBindingExpression(node.object);
41937 var htmlBinding = {
41938 isVueEventBindingExpression,
41942 function preprocess(ast, options) {
41943 switch (options.parser) {
41946 case "json-stringify":
41947 case "__js_expression":
41948 case "__vue_expression":
41949 return Object.assign({}, ast, {
41950 type: options.parser.startsWith("__") ? "JsExpressionRoot" : "JsonRoot",
41953 rootMarker: options.rootMarker
41961 var printPreprocess = preprocess;
41963 /** @type {import("assert")} */
41973 hardline: hardline$7
41977 hasNewlineBetweenOrAfterDecorators: hasNewlineBetweenOrAfterDecorators$1,
41978 getParentExportDeclaration: getParentExportDeclaration$1
41981 function printOptionalToken(path) {
41982 const node = path.getValue();
41984 if (!node.optional || // It's an optional computed method parsed by typescript-estree.
41985 // "?" is printed in `printMethod`.
41986 node.type === "Identifier" && node === path.getParentNode().key) {
41990 if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) {
41997 function printFunctionTypeParameters(path, options, print) {
41998 const fun = path.getValue();
42000 if (fun.typeArguments) {
42001 return path.call(print, "typeArguments");
42004 if (fun.typeParameters) {
42005 return path.call(print, "typeParameters");
42011 function printBindExpressionCallee(path, options, print) {
42012 return concat$b(["::", path.call(print, "callee")]);
42015 function printTypeScriptModifiers(path, options, print) {
42016 const n = path.getValue();
42018 if (!n.modifiers || !n.modifiers.length) {
42022 return concat$b([join$5(" ", path.map(print, "modifiers")), " "]);
42025 function printDecorators(path, options, print) {
42026 const node = path.getValue();
42027 return group$4(concat$b([join$5(line$5, path.map(print, "decorators")), hasNewlineBetweenOrAfterDecorators$1(node, options) ? hardline$7 : line$5]));
42030 function printFlowDeclaration(path, printed) {
42031 const parentExportDecl = getParentExportDeclaration$1(path);
42033 if (parentExportDecl) {
42034 assert__default['default'].strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
42036 } // If the parent node has type DeclareExportDeclaration, then it
42037 // will be responsible for printing the "declare" token. Otherwise
42038 // it needs to be printed with this non-exported declaration node.
42041 return concat$b(["declare ", printed]);
42044 function adjustClause(node, clause, forceSpace) {
42045 if (node.type === "EmptyStatement") {
42049 if (node.type === "BlockStatement" || forceSpace) {
42050 return concat$b([" ", clause]);
42053 return indent$8(concat$b([line$5, clause]));
42057 printOptionalToken,
42058 printFunctionTypeParameters,
42059 printBindExpressionCallee,
42060 printTypeScriptModifiers,
42062 printFlowDeclaration,
42069 softline: softline$5,
42074 ifBreak: ifBreak$1,
42075 hardline: hardline$8
42079 printDanglingComments: printDanglingComments$1
42082 hasDanglingComments: hasDanglingComments$1,
42083 shouldPrintComma: shouldPrintComma$1,
42084 needsHardlineAfterDanglingComment: needsHardlineAfterDanglingComment$1
42087 locStart: locStart$4,
42088 hasSameLoc: hasSameLoc$1
42091 * @typedef {import("../../document").Doc} Doc
42094 function printImportDeclaration(path, options, print) {
42095 const node = path.getValue();
42096 const semi = options.semi ? ";" : "";
42097 /** @type{Doc[]} */
42103 parts.push("import");
42105 if (importKind && importKind !== "value") {
42106 parts.push(" ", importKind);
42109 parts.push(printModuleSpecifiers(path, options, print), printModuleSource(path, options, print), printImportAssertions(path, options, print));
42111 return concat$c(parts);
42114 function printExportDeclaration(path, options, print) {
42115 const node = path.getValue();
42116 /** @type{Doc[]} */
42125 if (type === "DeclareExportDeclaration") {
42126 parts.push("declare ");
42129 parts.push("export");
42130 const isDefaultExport = node.default || type === "ExportDefaultDeclaration";
42132 if (isDefaultExport) {
42133 parts.push(" default");
42136 if (hasDanglingComments$1(node)) {
42137 parts.push(" ", printDanglingComments$1(path, options,
42141 if (needsHardlineAfterDanglingComment$1(node)) {
42142 parts.push(hardline$8);
42147 parts.push(" ", path.call(print, "declaration"));
42149 parts.push(exportKind === "type" ? " type" : "", printModuleSpecifiers(path, options, print), printModuleSource(path, options, print), printImportAssertions(path, options, print));
42152 if (shouldExportDeclarationPrintSemi(node, options)) {
42156 return concat$c(parts);
42159 function printExportAllDeclaration(path, options, print) {
42160 const node = path.getValue();
42161 let semi = options.semi ? ";" : "";
42162 /** @type{Doc[]} */
42171 if (type === "DeclareExportAllDeclaration") {
42172 parts.push("declare ");
42176 parts.push("export");
42178 if (exportKind === "type") {
42179 parts.push(" type");
42185 parts.push(" as ", path.call(print, "exported"));
42188 parts.push(printModuleSource(path, options, print), printImportAssertions(path, options, print), semi);
42189 return concat$c(parts);
42192 function shouldExportDeclarationPrintSemi(node, options) {
42193 if (!options.semi) {
42201 const isDefaultExport = node.default || type === "ExportDefaultDeclaration";
42203 if (!declaration) {
42208 type: declarationType
42211 if (isDefaultExport && declarationType !== "ClassDeclaration" && declarationType !== "FunctionDeclaration" && declarationType !== "TSInterfaceDeclaration" && declarationType !== "DeclareClass" && declarationType !== "DeclareFunction" && declarationType !== "TSDeclareFunction" && declarationType !== "EnumDeclaration") {
42218 function printModuleSource(path, options, print) {
42219 const node = path.getValue();
42221 if (!node.source) {
42224 /** @type{Doc[]} */
42229 if (!shouldNotPrintSpecifiers(node, options)) {
42230 parts.push(" from");
42233 parts.push(" ", path.call(print, "source"));
42234 return concat$c(parts);
42237 function printModuleSpecifiers(path, options, print) {
42238 const node = path.getValue();
42240 if (shouldNotPrintSpecifiers(node, options)) {
42243 /** @type{Doc[]} */
42246 const parts = [" "];
42248 if (node.specifiers && node.specifiers.length > 0) {
42249 const standaloneSpecifiers = [];
42250 const groupedSpecifiers = [];
42251 path.each(specifierPath => {
42252 const specifierType = path.getValue().type;
42254 if (specifierType === "ExportNamespaceSpecifier" || specifierType === "ExportDefaultSpecifier" || specifierType === "ImportNamespaceSpecifier" || specifierType === "ImportDefaultSpecifier") {
42255 standaloneSpecifiers.push(print(specifierPath));
42256 } else if (specifierType === "ExportSpecifier" || specifierType === "ImportSpecifier") {
42257 groupedSpecifiers.push(print(specifierPath));
42259 /* istanbul ignore next */
42260 throw new Error(`Unknown specifier type ${JSON.stringify(specifierType)}`);
42263 parts.push(join$6(", ", standaloneSpecifiers));
42265 if (groupedSpecifiers.length !== 0) {
42266 if (standaloneSpecifiers.length !== 0) {
42270 const canBreak = groupedSpecifiers.length > 1 || standaloneSpecifiers.length > 0 || node.specifiers.some(node => node.comments);
42273 parts.push(group$5(concat$c(["{", indent$9(concat$c([options.bracketSpacing ? line$6 : softline$5, join$6(concat$c([",", line$6]), groupedSpecifiers)])), ifBreak$1(shouldPrintComma$1(options) ? "," : ""), options.bracketSpacing ? line$6 : softline$5, "}"])));
42275 parts.push(concat$c(["{", options.bracketSpacing ? " " : "", concat$c(groupedSpecifiers), options.bracketSpacing ? " " : "", "}"]));
42282 return concat$c(parts);
42285 function shouldNotPrintSpecifiers(node, options) {
42293 if (type !== "ImportDeclaration" || Array.isArray(specifiers) && specifiers.length > 0 || importKind === "type") {
42295 } // TODO: check tokens
42298 return !/{\s*}/.test(options.originalText.slice(locStart$4(node), locStart$4(source)));
42301 function printImportAssertions(path, options, print) {
42302 const node = path.getNode();
42304 if (Array.isArray(node.assertions) && node.assertions.length !== 0) {
42305 return concat$c([" assert {", options.bracketSpacing ? " " : "", join$6(", ", path.map(print, "assertions")), options.bracketSpacing ? " " : "", "}"]);
42311 function printModuleSpecifier(path, options, print) {
42312 const node = path.getNode();
42317 /** @type{Doc[]} */
42321 if (type === "ImportSpecifier" && importKind) {
42322 parts.push(importKind, " ");
42325 const isImport = type.startsWith("Import");
42326 const leftSideProperty = isImport ? "imported" : "local";
42327 const rightSideProperty = isImport ? "local" : "exported";
42331 if (type === "ExportNamespaceSpecifier" || type === "ImportNamespaceSpecifier") {
42333 } else if (node[leftSideProperty]) {
42334 left = path.call(print, leftSideProperty);
42337 if (node[rightSideProperty] && (!node[leftSideProperty] || // import {a as a} from '.'
42338 !hasSameLoc$1(node[leftSideProperty], node[rightSideProperty]))) {
42339 right = path.call(print, rightSideProperty);
42342 parts.push(left, left && right ? " as " : "", right);
42343 return concat$c(parts);
42347 printImportDeclaration,
42348 printExportDeclaration,
42349 printExportAllDeclaration,
42350 printModuleSpecifier
42354 hasNewlineInRange: hasNewlineInRange$4
42357 isJSXNode: isJSXNode$2,
42358 isBlockComment: isBlockComment$4
42361 locStart: locStart$5,
42368 softline: softline$6,
42372 ifBreak: ifBreak$2,
42374 breakParent: breakParent$2
42378 * @typedef {import("../../document").Doc} Doc
42379 * @typedef {import("../../common/fast-path")} FastPath
42381 * @typedef {any} Options - Prettier options (TBD ...)
42383 * @typedef {Object} OperatorOptions
42384 * @property {() => Array<string | Doc>} beforeParts - Parts to print before the `?`.
42385 * @property {(breakClosingParen: boolean) => Array<string | Doc>} afterParts - Parts to print after the conditional expression.
42386 * @property {boolean} shouldCheckJsx - Whether to check for and print in JSX mode.
42387 * @property {string} conditionalNodeType - The type of the conditional expression node, ie "ConditionalExpression" or "TSConditionalType".
42388 * @property {string} consequentNodePropertyName - The property at which the consequent node can be found on the main node, eg "consequent".
42389 * @property {string} alternateNodePropertyName - The property at which the alternate node can be found on the main node, eg "alternate".
42390 * @property {string[]} testNodePropertyNames - The properties at which the test nodes can be found on the main node, eg "test".
42392 // If we have nested conditional expressions, we want to print them in JSX mode
42393 // if there's at least one JSXElement somewhere in the tree.
42395 // A conditional expression chain like this should be printed in normal mode,
42396 // because there aren't JSXElements anywhere in it:
42398 // isA ? "A" : isB ? "B" : isC ? "C" : "Unknown";
42400 // But a conditional expression chain like this should be printed in JSX mode,
42401 // because there is a JSXElement in the last ConditionalExpression:
42403 // isA ? "A" : isB ? "B" : isC ? "C" : <span className="warning">Unknown</span>;
42405 // This type of ConditionalExpression chain is structured like this in the AST:
42407 // ConditionalExpression {
42409 // consequent: ...,
42410 // alternate: ConditionalExpression {
42412 // consequent: ...,
42413 // alternate: ConditionalExpression {
42415 // consequent: ...,
42421 // We want to traverse over that shape and convert it into a flat structure so
42422 // that we can find if there's a JSXElement somewhere inside.
42424 function getConditionalChainContents(node) {
42425 // Given this code:
42427 // // Using a ConditionalExpression as the consequent is uncommon, but should
42429 // A ? B : C ? D : E ? F ? G : H : I
42431 // which has this AST:
42433 // ConditionalExpression {
42434 // test: Identifier(A),
42435 // consequent: Identifier(B),
42436 // alternate: ConditionalExpression {
42437 // test: Identifier(C),
42438 // consequent: Identifier(D),
42439 // alternate: ConditionalExpression {
42440 // test: Identifier(E),
42441 // consequent: ConditionalExpression {
42442 // test: Identifier(F),
42443 // consequent: Identifier(G),
42444 // alternate: Identifier(H),
42446 // alternate: Identifier(I),
42451 // we should return this Array:
42465 // This loses the information about whether each node was the test,
42466 // consequent, or alternate, but we don't care about that here- we are only
42467 // flattening this structure to find if there's any JSXElements inside.
42468 const nonConditionalExpressions = [];
42470 function recurse(node) {
42471 if (node.type === "ConditionalExpression") {
42472 recurse(node.test);
42473 recurse(node.consequent);
42474 recurse(node.alternate);
42476 nonConditionalExpressions.push(node);
42481 return nonConditionalExpressions;
42484 function conditionalExpressionChainContainsJSX(node) {
42485 return getConditionalChainContents(node).some(isJSXNode$2);
42488 * The following is the shared logic for
42489 * ternary operators, namely ConditionalExpression
42490 * and TSConditionalType
42491 * @param {FastPath} path - The path to the ConditionalExpression/TSConditionalType node.
42492 * @param {Options} options - Prettier options
42493 * @param {Function} print - Print function to call recursively
42494 * @param {OperatorOptions} operatorOptions
42499 function printTernaryOperator(path, options, print, operatorOptions) {
42500 const node = path.getValue();
42501 const consequentNode = node[operatorOptions.consequentNodePropertyName];
42502 const alternateNode = node[operatorOptions.alternateNodePropertyName];
42503 const parts = []; // We print a ConditionalExpression in either "JSX mode" or "normal mode".
42504 // See tests/jsx/conditional-expression.js for more info.
42506 let jsxMode = false;
42507 const parent = path.getParentNode();
42508 const isParentTest = parent.type === operatorOptions.conditionalNodeType && operatorOptions.testNodePropertyNames.some(prop => parent[prop] === node);
42509 let forceNoIndent = parent.type === operatorOptions.conditionalNodeType && !isParentTest; // Find the outermost non-ConditionalExpression parent, and the outermost
42510 // ConditionalExpression parent. We'll use these to determine if we should
42511 // print in JSX mode.
42514 let previousParent;
42518 previousParent = currentParent || node;
42519 currentParent = path.getParentNode(i);
42521 } while (currentParent && currentParent.type === operatorOptions.conditionalNodeType && operatorOptions.testNodePropertyNames.every(prop => currentParent[prop] !== previousParent));
42523 const firstNonConditionalParent = currentParent || parent;
42524 const lastConditionalParent = previousParent;
42526 if (operatorOptions.shouldCheckJsx && (isJSXNode$2(node[operatorOptions.testNodePropertyNames[0]]) || isJSXNode$2(consequentNode) || isJSXNode$2(alternateNode) || conditionalExpressionChainContainsJSX(lastConditionalParent))) {
42528 forceNoIndent = true; // Even though they don't need parens, we wrap (almost) everything in
42529 // parens when using ?: within JSX, because the parens are analogous to
42530 // curly braces in an if statement.
42532 const wrap = doc => concat$d([ifBreak$2("(", ""), indent$a(concat$d([softline$6, doc])), softline$6, ifBreak$2(")", "")]); // The only things we don't wrap are:
42533 // * Nested conditional expressions in alternates
42538 const isNil = node => node.type === "NullLiteral" || node.type === "Literal" && node.value === null || node.type === "Identifier" && node.name === "undefined";
42540 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)));
42543 const part = concat$d([line$7, "? ", consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$2("", "(") : "", align$2(2, path.call(print, operatorOptions.consequentNodePropertyName)), consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$2("", ")") : "", line$7, ": ", alternateNode.type === operatorOptions.conditionalNodeType ? path.call(print, operatorOptions.alternateNodePropertyName) : align$2(2, path.call(print, operatorOptions.alternateNodePropertyName))]);
42544 parts.push(parent.type !== operatorOptions.conditionalNodeType || parent[operatorOptions.alternateNodePropertyName] === node || isParentTest ? part : options.useTabs ? dedent$1(indent$a(part)) : align$2(Math.max(0, options.tabWidth - 2), part));
42545 } // We want a whole chain of ConditionalExpressions to all
42546 // break if any of them break. That means we should only group around the
42547 // outer-most ConditionalExpression.
42550 const comments = flatten_1([...operatorOptions.testNodePropertyNames.map(propertyName => node[propertyName].comments), consequentNode.comments, alternateNode.comments]).filter(Boolean);
42551 const shouldBreak = comments.some(comment => isBlockComment$4(comment) && hasNewlineInRange$4(options.originalText, locStart$5(comment), locEnd$4(comment)));
42553 const maybeGroup = doc => parent === firstNonConditionalParent ? group$6(doc, {
42555 }) : shouldBreak ? concat$d([doc, breakParent$2]) : doc; // Break the closing paren to keep the chain right after it:
42562 const breakClosingParen = !jsxMode && (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression" || parent.type === "NGPipeExpression" && parent.left === node) && !parent.computed;
42563 const result = maybeGroup(concat$d([].concat((testDoc =>
42574 parent.type === operatorOptions.conditionalNodeType && parent[operatorOptions.alternateNodePropertyName] === node ? align$2(2, testDoc) : testDoc)(concat$d(operatorOptions.beforeParts())), forceNoIndent ? concat$d(parts) : indent$a(concat$d(parts)), operatorOptions.afterParts(breakClosingParen))));
42575 return isParentTest ? group$6(concat$d([indent$a(concat$d([softline$6, result])), softline$6])) : result;
42578 var ternary = printTernaryOperator;
42581 getNextNonSpaceNonCommentCharacter: getNextNonSpaceNonCommentCharacter$2,
42582 isNextLineEmpty: isNextLineEmpty$2
42585 printDanglingComments: printDanglingComments$2
42591 hardline: hardline$9,
42592 softline: softline$7,
42598 removeLines: removeLines$1
42602 getFunctionParameters: getFunctionParameters$3,
42603 iterateFunctionParametersPath: iterateFunctionParametersPath$1,
42604 isSimpleType: isSimpleType$1,
42605 isTestCall: isTestCall$1,
42606 isTypeAnnotationAFunction: isTypeAnnotationAFunction$1,
42607 isObjectType: isObjectType$1,
42608 isObjectTypePropertyAFunction: isObjectTypePropertyAFunction$1,
42609 hasRestParameter: hasRestParameter$1,
42610 shouldPrintComma: shouldPrintComma$2
42616 printFunctionTypeParameters: printFunctionTypeParameters$1
42619 function printFunctionParameters(path, print, options, expandArg, printTypeParams) {
42620 const functionNode = path.getValue();
42621 const parameters = getFunctionParameters$3(functionNode);
42622 const typeParams = printTypeParams ? printFunctionTypeParameters$1(path, options, print) : "";
42624 if (parameters.length === 0) {
42625 return concat$e([typeParams, "(", printDanglingComments$2(path, options,
42627 true, comment => getNextNonSpaceNonCommentCharacter$2(options.originalText, comment, locEnd$5) === ")"), ")"]);
42630 const parent = path.getParentNode();
42631 const isParametersInTestCall = isTestCall$1(parent);
42632 const shouldHugParameters = shouldHugFunctionParameters(functionNode);
42633 const shouldExpandParameters = expandArg && !parameters.some(node => node.comments);
42634 const printed = [];
42635 iterateFunctionParametersPath$1(path, (parameterPath, index) => {
42636 const isLastParameter = index === parameters.length - 1;
42638 if (isLastParameter && functionNode.rest) {
42639 printed.push("...");
42642 printed.push(parameterPath.call(print));
42644 if (isLastParameter) {
42650 if (isParametersInTestCall || shouldHugParameters || shouldExpandParameters) {
42652 } else if (isNextLineEmpty$2(options.originalText, parameters[index], locEnd$5)) {
42653 printed.push(hardline$9, hardline$9);
42655 printed.push(line$8);
42657 }); // If the parent is a call with the first/last argument expansion and this is the
42658 // params of the first/last argument, we don't want the arguments to break and instead
42659 // want the whole expression to be on a new line.
42662 // verylongcall( verylongcall((
42668 if (shouldExpandParameters) {
42669 return group$7(concat$e([removeLines$1(typeParams), "(", concat$e(printed.map(removeLines$1)), ")"]));
42670 } // Single object destructuring should hug
42679 const hasNotParameterDecorator = parameters.every(node => !node.decorators);
42681 if (shouldHugParameters && hasNotParameterDecorator) {
42682 return concat$e([typeParams, "(", concat$e(printed), ")"]);
42683 } // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
42686 if (isParametersInTestCall) {
42687 return concat$e([typeParams, "(", concat$e(printed), ")"]);
42690 const isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction$1(parent) || isTypeAnnotationAFunction$1(parent) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === functionNode) && parameters.length === 1 && parameters[0].name === null && // `type q = (this: string) => void;`
42691 functionNode.this !== parameters[0] && parameters[0].typeAnnotation && functionNode.typeParameters === null && isSimpleType$1(parameters[0].typeAnnotation) && !functionNode.rest;
42693 if (isFlowShorthandWithOneArg) {
42694 if (options.arrowParens === "always") {
42695 return concat$e(["(", concat$e(printed), ")"]);
42698 return concat$e(printed);
42701 return concat$e([typeParams, "(", indent$b(concat$e([softline$7, concat$e(printed)])), ifBreak$3(!hasRestParameter$1(functionNode) && shouldPrintComma$2(options, "all") ? "," : ""), softline$7, ")"]);
42704 function shouldHugFunctionParameters(node) {
42709 const parameters = getFunctionParameters$3(node);
42711 if (parameters.length !== 1) {
42715 const [parameter] = parameters;
42716 return !parameter.comments && (parameter.type === "ObjectPattern" || parameter.type === "ArrayPattern" || parameter.type === "Identifier" && parameter.typeAnnotation && (parameter.typeAnnotation.type === "TypeAnnotation" || parameter.typeAnnotation.type === "TSTypeAnnotation") && isObjectType$1(parameter.typeAnnotation.typeAnnotation) || parameter.type === "FunctionTypeParam" && isObjectType$1(parameter.typeAnnotation) || parameter.type === "AssignmentPattern" && (parameter.left.type === "ObjectPattern" || parameter.left.type === "ArrayPattern") && (parameter.right.type === "Identifier" || parameter.right.type === "ObjectExpression" && parameter.right.properties.length === 0 || parameter.right.type === "ArrayExpression" && parameter.right.elements.length === 0));
42719 var functionParameters = {
42720 printFunctionParameters,
42721 shouldHugFunctionParameters
42730 isFlowAnnotationComment: isFlowAnnotationComment$1,
42731 isSimpleType: isSimpleType$2,
42732 isObjectType: isObjectType$2
42735 function printTypeAnnotation(path, options, print) {
42736 const node = path.getValue();
42738 if (!node.typeAnnotation) {
42742 const parentNode = path.getParentNode();
42743 const isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite;
42744 const isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node;
42746 if (isFlowAnnotationComment$1(options.originalText, node.typeAnnotation)) {
42747 return concat$f([" /*: ", path.call(print, "typeAnnotation"), " */"]);
42750 return concat$f([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path.call(print, "typeAnnotation")]);
42753 function shouldHugType(node) {
42754 if (isSimpleType$2(node) || isObjectType$2(node)) {
42758 if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") {
42759 const voidCount = node.types.filter(n => n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword").length;
42760 const hasObject = node.types.some(n => n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}>
42761 n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference");
42763 if (node.types.length - 1 === voidCount && hasObject) {
42771 var typeAnnotation = {
42772 printTypeAnnotation,
42777 printDanglingComments: printDanglingComments$3
42783 softline: softline$8,
42790 getLast: getLast$3,
42791 isNextLineEmpty: isNextLineEmpty$3
42794 hasDanglingComments: hasDanglingComments$2,
42795 shouldPrintComma: shouldPrintComma$3
42801 printOptionalToken: printOptionalToken$1
42804 printTypeAnnotation: printTypeAnnotation$1
42805 } = typeAnnotation;
42806 /** @typedef {import("../../document").Doc} Doc */
42808 function printArray(path, options, print) {
42809 const n = path.getValue();
42810 /** @type{Doc[]} */
42813 const openBracket = n.type === "TupleExpression" ? "#[" : "[";
42814 const closeBracket = "]";
42816 if (n.elements.length === 0) {
42817 if (!hasDanglingComments$2(n)) {
42818 parts.push(openBracket, closeBracket);
42820 parts.push(group$8(concat$g([openBracket, printDanglingComments$3(path, options), softline$8, closeBracket])));
42823 const lastElem = getLast$3(n.elements);
42824 const canHaveTrailingComma = !(lastElem && lastElem.type === "RestElement"); // JavaScript allows you to have empty elements in an array which
42825 // changes its length based on the number of commas. The algorithm
42826 // is that if the last argument is null, we need to force insert
42827 // a comma to ensure JavaScript recognizes it.
42828 // [,].length === 1
42829 // [1,].length === 1
42830 // [1,,].length === 2
42832 // Note that getLast returns null if the array is empty, but
42833 // we already check for an empty array just above so we are safe
42835 const needsForcedTrailingComma = canHaveTrailingComma && lastElem === null;
42836 const shouldBreak = !options.__inJestEach && n.elements.length > 1 && n.elements.every((element, i, elements) => {
42837 const elementType = element && element.type;
42839 if (elementType !== "ArrayExpression" && elementType !== "ObjectExpression") {
42843 const nextElement = elements[i + 1];
42845 if (nextElement && elementType !== nextElement.type) {
42849 const itemsKey = elementType === "ArrayExpression" ? "elements" : "properties";
42850 return element[itemsKey] && element[itemsKey].length > 1;
42852 parts.push(group$8(concat$g([openBracket, indent$c(concat$g([softline$8, printArrayItems(path, options, "elements", print)])), needsForcedTrailingComma ? "," : "", ifBreak$4(canHaveTrailingComma && !needsForcedTrailingComma && shouldPrintComma$3(options) ? "," : ""), printDanglingComments$3(path, options,
42854 true), softline$8, closeBracket]), {
42859 parts.push(printOptionalToken$1(path), printTypeAnnotation$1(path, options, print));
42860 return concat$g(parts);
42863 function printArrayItems(path, options, printPath, print) {
42864 const printedElements = [];
42865 let separatorParts = [];
42866 path.each(childPath => {
42867 printedElements.push(concat$g(separatorParts));
42868 printedElements.push(group$8(print(childPath)));
42869 separatorParts = [",", line$9];
42871 if (childPath.getValue() && isNextLineEmpty$3(options.originalText, childPath.getValue(), locEnd$6)) {
42872 separatorParts.push(softline$8);
42875 return concat$g(printedElements);
42884 printDanglingComments: printDanglingComments$4
42890 softline: softline$9,
42893 ifBreak: ifBreak$5,
42894 hardline: hardline$a
42898 getLast: getLast$4,
42899 isNextLineEmpty: isNextLineEmpty$4,
42900 hasNewlineInRange: hasNewlineInRange$5,
42901 hasNewline: hasNewline$5
42904 hasDanglingComments: hasDanglingComments$3,
42905 shouldPrintComma: shouldPrintComma$4,
42906 hasNodeIgnoreComment: hasNodeIgnoreComment$1,
42907 isBlockComment: isBlockComment$5
42910 locStart: locStart$6,
42914 printOptionalToken: printOptionalToken$2
42917 shouldHugFunctionParameters: shouldHugFunctionParameters$1
42918 } = functionParameters;
42920 printTypeAnnotation: printTypeAnnotation$2,
42921 shouldHugType: shouldHugType$1
42922 } = typeAnnotation;
42923 /** @typedef {import("../../document").Doc} Doc */
42925 function printObject(path, options, print) {
42926 const semi = options.semi ? ";" : "";
42927 const n = path.getValue();
42928 let propertiesField;
42930 if (n.type === "TSTypeLiteral") {
42931 propertiesField = "members";
42932 } else if (n.type === "TSInterfaceBody") {
42933 propertiesField = "body";
42935 propertiesField = "properties";
42938 const isTypeAnnotation = n.type === "ObjectTypeAnnotation";
42941 if (isTypeAnnotation) {
42942 fields.push("indexers", "callProperties", "internalSlots");
42945 fields.push(propertiesField);
42946 const firstProperty = fields.map(field => n[field][0]).sort((a, b) => locStart$6(a) - locStart$6(b))[0];
42947 const parent = path.getParentNode(0);
42948 const isFlowInterfaceLikeBody = isTypeAnnotation && parent && (parent.type === "InterfaceDeclaration" || parent.type === "DeclareInterface" || parent.type === "DeclareClass") && path.getName() === "body";
42949 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$5(options.originalText, locStart$6(n), locStart$6(firstProperty));
42950 const separator = isFlowInterfaceLikeBody ? ";" : n.type === "TSInterfaceBody" || n.type === "TSTypeLiteral" ? ifBreak$5(semi, ";") : ",";
42951 const leftBrace = n.type === "RecordExpression" ? "#{" : n.exact ? "{|" : "{";
42952 const rightBrace = n.exact ? "|}" : "}"; // Unfortunately, things are grouped together in the ast can be
42953 // interleaved in the source code. So we need to reorder them before
42956 const propsAndLoc = [];
42957 fields.forEach(field => {
42958 path.each(childPath => {
42959 const node = childPath.getValue();
42962 printed: print(childPath),
42963 loc: locStart$6(node)
42967 let separatorParts = [];
42968 const props = propsAndLoc.sort((a, b) => a.loc - b.loc).map(prop => {
42969 const result = concat$h(separatorParts.concat(group$9(prop.printed)));
42970 separatorParts = [separator, line$a];
42972 if ((prop.node.type === "TSPropertySignature" || prop.node.type === "TSMethodSignature" || prop.node.type === "TSConstructSignatureDeclaration") && hasNodeIgnoreComment$1(prop.node)) {
42973 separatorParts.shift();
42976 if (isNextLineEmpty$4(options.originalText, prop.node, locEnd$7)) {
42977 separatorParts.push(hardline$a);
42986 if (hasDanglingComments$3(n)) {
42987 const hasLineComments = !n.comments.every(comment => isBlockComment$5(comment));
42988 const printedDanglingComments = printDanglingComments$4(path, options,
42991 printed = concat$h([printedDanglingComments, hasLineComments || hasNewline$5(options.originalText, locEnd$7(n.comments[n.comments.length - 1])) ? hardline$a : line$a, "..."]);
42996 props.push(concat$h(separatorParts.concat(printed)));
42999 const lastElem = getLast$4(n[propertiesField]);
43000 const canHaveTrailingSeparator = !(n.inexact || lastElem && lastElem.type === "RestElement" || lastElem && (lastElem.type === "TSPropertySignature" || lastElem.type === "TSCallSignatureDeclaration" || lastElem.type === "TSMethodSignature" || lastElem.type === "TSConstructSignatureDeclaration") && hasNodeIgnoreComment$1(lastElem));
43003 if (props.length === 0) {
43004 if (!hasDanglingComments$3(n)) {
43005 return concat$h([leftBrace, rightBrace, printTypeAnnotation$2(path, options, print)]);
43008 content = group$9(concat$h([leftBrace, printDanglingComments$4(path, options), softline$9, rightBrace, printOptionalToken$2(path), printTypeAnnotation$2(path, options, print)]));
43010 content = concat$h([leftBrace, indent$d(concat$h([options.bracketSpacing ? line$a : softline$9, concat$h(props)])), ifBreak$5(canHaveTrailingSeparator && (separator !== "," || shouldPrintComma$4(options)) ? separator : ""), concat$h([options.bracketSpacing ? line$a : softline$9, rightBrace]), printOptionalToken$2(path), printTypeAnnotation$2(path, options, print)]);
43011 } // If we inline the object as first argument of the parent, we don't want
43012 // to create another group so that the object breaks before the return
43016 if (path.match(node => node.type === "ObjectPattern" && !node.decorators, (node, name, number) => shouldHugFunctionParameters$1(node) && (name === "params" || name === "parameters" || name === "this" || name === "rest") && number === 0) || path.match(shouldHugType$1, (node, name) => name === "typeAnnotation", (node, name) => name === "typeAnnotation", (node, name, number) => shouldHugFunctionParameters$1(node) && (name === "params" || name === "parameters" || name === "this" || name === "rest") && number === 0)) {
43020 return group$9(content, {
43030 printComments: printComments$1,
43031 printDanglingComments: printDanglingComments$5
43037 hardline: hardline$b,
43038 softline: softline$a,
43041 conditionalGroup: conditionalGroup$1,
43043 ifBreak: ifBreak$6,
43044 lineSuffixBoundary: lineSuffixBoundary$2
43047 willBreak: willBreak$1,
43048 isLineNext: isLineNext$1,
43053 getLast: getLast$5,
43054 getPreferredQuote: getPreferredQuote$1
43057 hasTrailingComment: hasTrailingComment$1,
43058 isEmptyJSXElement: isEmptyJSXElement$1,
43059 isJSXWhitespaceExpression: isJSXWhitespaceExpression$1,
43060 isJSXNode: isJSXNode$3,
43061 isMeaningfulJSXText: isMeaningfulJSXText$1,
43062 matchJsxWhitespaceRegex: matchJsxWhitespaceRegex$1,
43063 rawText: rawText$1,
43064 isLiteral: isLiteral$1,
43065 isCallOrOptionalCallExpression: isCallOrOptionalCallExpression$1,
43066 isStringLiteral: isStringLiteral$1,
43067 isBinaryish: isBinaryish$2,
43068 isBlockComment: isBlockComment$6
43071 willPrintOwnComments: willPrintOwnComments$1
43072 } = comments$1; // JSX expands children from the inside-out, instead of the outside-in.
43073 // This is both to break children before attributes,
43074 // and to ensure that when children break, their parents do as well.
43076 // Any element that is written without any newlines and fits on a single line
43077 // is left that way.
43078 // Not only that, any user-written-line containing multiple JSX siblings
43079 // should also be kept on one line if possible,
43080 // so each user-written-line is wrapped in its own group.
43082 // Elements that contain newlines or don't fit on a single line (recursively)
43083 // are fully-split, using hardline and shouldBreak: true.
43085 // To support that case properly, all leading and trailing spaces
43086 // are stripped from the list of children, and replaced with a single hardline.
43088 function printJsxElementInternal(path, options, print) {
43089 const n = path.getValue();
43091 if (n.type === "JSXElement" && isEmptyJSXElement$1(n)) {
43092 return concat$i([path.call(print, "openingElement"), path.call(print, "closingElement")]);
43095 const openingLines = n.type === "JSXElement" ? path.call(print, "openingElement") : path.call(print, "openingFragment");
43096 const closingLines = n.type === "JSXElement" ? path.call(print, "closingElement") : path.call(print, "closingFragment");
43098 if (n.children.length === 1 && n.children[0].type === "JSXExpressionContainer" && (n.children[0].expression.type === "TemplateLiteral" || n.children[0].expression.type === "TaggedTemplateExpression")) {
43099 return concat$i([openingLines, concat$i(path.map(print, "children")), closingLines]);
43100 } // Convert `{" "}` to text nodes containing a space.
43101 // This makes it easy to turn them into `jsxWhitespace` which
43102 // can then print as either a space or `{" "}` when breaking.
43105 n.children = n.children.map(child => {
43106 if (isJSXWhitespaceExpression$1(child)) {
43116 const containsTag = n.children.filter(isJSXNode$3).length > 0;
43117 const containsMultipleExpressions = n.children.filter(child => child.type === "JSXExpressionContainer").length > 1;
43118 const containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true.
43120 let forcedBreak = willBreak$1(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions;
43121 const isMdxBlock = path.getParentNode().rootMarker === "mdx";
43122 const rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}';
43123 const jsxWhitespace = isMdxBlock ? concat$i([" "]) : ifBreak$6(concat$i([rawJsxWhitespace, softline$a]), " ");
43124 const isFacebookTranslationTag = n.openingElement && n.openingElement.name && n.openingElement.name.name === "fbt";
43125 const children = printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag);
43126 const containsText = n.children.some(child => isMeaningfulJSXText$1(child)); // We can end up we multiple whitespace elements with empty string
43127 // content between them.
43128 // We need to remove empty whitespace and softlines before JSX whitespace
43129 // to get the correct output.
43131 for (let i = children.length - 2; i >= 0; i--) {
43132 const isPairOfEmptyStrings = children[i] === "" && children[i + 1] === "";
43133 const isPairOfHardlines = children[i] === hardline$b && children[i + 1] === "" && children[i + 2] === hardline$b;
43134 const isLineFollowedByJSXWhitespace = (children[i] === softline$a || children[i] === hardline$b) && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
43135 const isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$a || children[i + 2] === hardline$b);
43136 const isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
43137 const isPairOfHardOrSoftLines = children[i] === softline$a && children[i + 1] === "" && children[i + 2] === hardline$b || children[i] === hardline$b && children[i + 1] === "" && children[i + 2] === softline$a;
43139 if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace || isPairOfHardOrSoftLines) {
43140 children.splice(i, 2);
43141 } else if (isJSXWhitespaceFollowedByLine) {
43142 children.splice(i + 1, 2);
43144 } // Trim trailing lines (or empty strings)
43147 while (children.length && (isLineNext$1(getLast$5(children)) || isEmpty$1(getLast$5(children)))) {
43149 } // Trim leading lines (or empty strings)
43152 while (children.length && (isLineNext$1(children[0]) || isEmpty$1(children[0])) && (isLineNext$1(children[1]) || isEmpty$1(children[1]))) {
43155 } // Tweak how we format children if outputting this element over multiple lines.
43156 // Also detect whether we will force this element to output over multiple lines.
43159 const multilineChildren = [];
43160 children.forEach((child, i) => {
43161 // There are a number of situations where we need to ensure we display
43162 // whitespace as `{" "}` when outputting this element over multiple lines.
43163 if (child === jsxWhitespace) {
43164 if (i === 1 && children[i - 1] === "") {
43165 if (children.length === 2) {
43166 // Solitary whitespace
43167 multilineChildren.push(rawJsxWhitespace);
43169 } // Leading whitespace
43172 multilineChildren.push(concat$i([rawJsxWhitespace, hardline$b]));
43174 } else if (i === children.length - 1) {
43175 // Trailing whitespace
43176 multilineChildren.push(rawJsxWhitespace);
43178 } else if (children[i - 1] === "" && children[i - 2] === hardline$b) {
43179 // Whitespace after line break
43180 multilineChildren.push(rawJsxWhitespace);
43185 multilineChildren.push(child);
43187 if (willBreak$1(child)) {
43188 forcedBreak = true;
43190 }); // If there is text we use `fill` to fit as much onto each line as possible.
43191 // When there is no text (just tags and expressions) we use `group`
43192 // to output each on a separate line.
43194 const content = containsText ? fill$3(multilineChildren) : group$a(concat$i(multilineChildren), {
43202 const multiLineElem = group$a(concat$i([openingLines, indent$e(concat$i([hardline$b, content])), hardline$b, closingLines]));
43205 return multiLineElem;
43208 return conditionalGroup$1([group$a(concat$i([openingLines, concat$i(children), closingLines])), multiLineElem]);
43209 } // JSX Children are strange, mostly for two reasons:
43210 // 1. JSX reads newlines into string values, instead of skipping them like JS
43211 // 2. up to one whitespace between elements within a line is significant,
43212 // but not between lines.
43214 // Leading, trailing, and lone whitespace all need to
43215 // turn themselves into the rather ugly `{' '}` when breaking.
43217 // We print JSX using the `fill` doc primitive.
43218 // This requires that we give it an array of alternating
43219 // content and whitespace elements.
43220 // To ensure this we add dummy `""` content elements as needed.
43223 function printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag) {
43224 const n = path.getValue();
43225 const children = [];
43226 path.each((childPath, i) => {
43227 const child = childPath.getValue();
43229 if (isLiteral$1(child)) {
43230 const text = rawText$1(child); // Contains a non-whitespace character
43232 if (isMeaningfulJSXText$1(child)) {
43233 const words = text.split(matchJsxWhitespaceRegex$1); // Starts with whitespace
43235 if (words[0] === "") {
43239 if (/\n/.test(words[0])) {
43240 const next = n.children[i + 1];
43241 children.push(separatorWithWhitespace(isFacebookTranslationTag, words[1], child, next));
43243 children.push(jsxWhitespace);
43249 let endWhitespace; // Ends with whitespace
43251 if (getLast$5(words) === "") {
43253 endWhitespace = words.pop();
43254 } // This was whitespace only without a new line.
43257 if (words.length === 0) {
43261 words.forEach((word, i) => {
43263 children.push(line$b);
43265 children.push(word);
43269 if (endWhitespace !== undefined) {
43270 if (/\n/.test(endWhitespace)) {
43271 const next = n.children[i + 1];
43272 children.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$5(children), child, next));
43274 children.push(jsxWhitespace);
43277 const next = n.children[i + 1];
43278 children.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$5(children), child, next));
43280 } else if (/\n/.test(text)) {
43281 // Keep (up to one) blank line between tags/expressions/text.
43282 // Note: We don't keep blank lines between text elements.
43283 if (text.match(/\n/g).length > 1) {
43285 children.push(hardline$b);
43289 children.push(jsxWhitespace);
43292 const printedChild = print(childPath);
43293 children.push(printedChild);
43294 const next = n.children[i + 1];
43295 const directlyFollowedByMeaningfulText = next && isMeaningfulJSXText$1(next);
43297 if (directlyFollowedByMeaningfulText) {
43298 const firstWord = rawText$1(next).trim().split(matchJsxWhitespaceRegex$1)[0];
43299 children.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord, child, next));
43301 children.push(hardline$b);
43308 function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
43309 if (isFacebookTranslationTag) {
43313 if (childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement) {
43314 return child.length === 1 ? softline$a : hardline$b;
43320 function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
43321 if (isFacebookTranslationTag) {
43325 if (child.length === 1) {
43326 return childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement ? hardline$b : softline$a;
43332 function maybeWrapJSXElementInParens(path, elem, options) {
43333 const parent = path.getParentNode();
43334 /* istanbul ignore next */
43340 const NO_WRAP_PARENTS = {
43341 ArrayExpression: true,
43342 JSXAttribute: true,
43344 JSXExpressionContainer: true,
43346 ExpressionStatement: true,
43347 CallExpression: true,
43348 OptionalCallExpression: true,
43349 ConditionalExpression: true,
43350 JsExpressionRoot: true
43353 if (NO_WRAP_PARENTS[parent.type]) {
43357 const shouldBreak = path.match(undefined, node => node.type === "ArrowFunctionExpression", isCallOrOptionalCallExpression$1, node => node.type === "JSXExpressionContainer");
43358 const needsParens = needsParens_1(path, options);
43359 return group$a(concat$i([needsParens ? "" : ifBreak$6("("), indent$e(concat$i([softline$a, elem])), softline$a, needsParens ? "" : ifBreak$6(")")]), {
43364 function printJsxAttribute(path, options, print) {
43365 const n = path.getValue();
43367 parts.push(path.call(print, "name"));
43372 if (isStringLiteral$1(n.value)) {
43373 const raw = rawText$1(n.value); // Unescape all quotes so we get an accurate preferred quote
43375 let final = raw.replace(/'/g, "'").replace(/"/g, '"');
43376 const quote = getPreferredQuote$1(final, options.jsxSingleQuote ? "'" : '"');
43377 const escape = quote === "'" ? "'" : """;
43378 final = final.slice(1, -1).replace(new RegExp(quote, "g"), escape);
43379 res = concat$i([quote, final, quote]);
43381 res = path.call(print, "value");
43384 parts.push("=", res);
43387 return concat$i(parts);
43390 function printJsxExpressionContainer(path, options, print) {
43391 const n = path.getValue();
43392 const parent = path.getParentNode(0);
43393 const hasComments = n.expression.comments && n.expression.comments.length > 0;
43394 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$3(parent) && (n.expression.type === "ConditionalExpression" || isBinaryish$2(n.expression)));
43396 if (shouldInline) {
43397 return group$a(concat$i(["{", path.call(print, "expression"), lineSuffixBoundary$2, "}"]));
43400 return group$a(concat$i(["{", indent$e(concat$i([softline$a, path.call(print, "expression")])), softline$a, lineSuffixBoundary$2, "}"]));
43403 function printJsxOpeningElement(path, options, print) {
43404 const n = path.getValue();
43405 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
43407 if (n.selfClosing && !n.attributes.length && !nameHasComments) {
43408 return concat$i(["<", path.call(print, "name"), path.call(print, "typeParameters"), " />"]);
43409 } // don't break up opening elements with a single long text attribute
43412 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:
43421 !nameHasComments && (!n.attributes[0].comments || !n.attributes[0].comments.length)) {
43422 return group$a(concat$i(["<", path.call(print, "name"), path.call(print, "typeParameters"), " ", concat$i(path.map(print, "attributes")), n.selfClosing ? " />" : ">"]));
43425 const lastAttrHasTrailingComments = n.attributes.length && hasTrailingComment$1(getLast$5(n.attributes));
43426 const bracketSameLine = // Simple tags (no attributes and no comment in tag name) should be
43427 // kept unbroken regardless of `jsxBracketSameLine`
43428 !n.attributes.length && !nameHasComments || options.jsxBracketSameLine && ( // We should print the bracket in a new line for the following cases:
43435 !nameHasComments || n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a
43436 // string literal with newlines
43438 const shouldBreak = n.attributes && n.attributes.some(attr => attr.value && isStringLiteral$1(attr.value) && attr.value.value.includes("\n"));
43439 return group$a(concat$i(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$i([indent$e(concat$i(path.map(attr => concat$i([line$b, print(attr)]), "attributes"))), n.selfClosing ? line$b : bracketSameLine ? ">" : softline$a]), n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), {
43444 function printJsxClosingElement(path, options, print) {
43445 return concat$i(["</", path.call(print, "name"), ">"]);
43448 function printJsxOpeningClosingFragment(path, options
43451 const n = path.getValue();
43452 const hasComment = n.comments && n.comments.length;
43453 const hasOwnLineComment = hasComment && !n.comments.every(comment => isBlockComment$6(comment));
43454 const isOpeningFragment = n.type === "JSXOpeningFragment";
43455 return concat$i([isOpeningFragment ? "<" : "</", indent$e(concat$i([hasOwnLineComment ? hardline$b : hasComment && !isOpeningFragment ? " " : "", printDanglingComments$5(path, options, true)])), hasOwnLineComment ? hardline$b : "", ">"]);
43458 function printJsxElement(path, options, print) {
43459 const elem = printComments$1(path, () => printJsxElementInternal(path, options, print), options);
43460 return maybeWrapJSXElementInParens(path, elem, options);
43463 function printJsxEmptyExpression(path, options
43466 const n = path.getValue();
43467 const requiresHardline = n.comments && !n.comments.every(comment => isBlockComment$6(comment));
43468 return concat$i([printDanglingComments$5(path, options,
43470 !requiresHardline), requiresHardline ? hardline$b : ""]);
43471 } // `JSXSpreadAttribute` and `JSXSpreadChild`
43474 function printJsxSpreadAttribute(path, options, print) {
43475 const n = path.getValue();
43476 return concat$i(["{", path.call(p => {
43477 const printed = concat$i(["...", print(p)]);
43478 const n = p.getValue();
43480 if (!n.comments || !n.comments.length || !willPrintOwnComments$1(p)) {
43484 return concat$i([indent$e(concat$i([softline$a, printComments$1(p, () => printed, options)])), softline$a]);
43485 }, n.type === "JSXSpreadAttribute" ? "argument" : "expression"), "}"]);
43491 printJsxOpeningElement,
43492 printJsxClosingElement,
43493 printJsxOpeningClosingFragment,
43494 printJsxExpressionContainer,
43495 printJsxEmptyExpression,
43496 printJsxSpreadAttribute,
43498 printJsxSpreadChild: printJsxSpreadAttribute
43502 printDanglingComments: printDanglingComments$6
43509 hardline: hardline$c,
43510 softline: softline$b,
43517 hasDanglingComments: hasDanglingComments$4,
43518 isTestCall: isTestCall$2,
43519 isBlockComment: isBlockComment$7,
43520 shouldPrintComma: shouldPrintComma$5
43523 shouldHugType: shouldHugType$2
43524 } = typeAnnotation;
43525 const typeParametersGroupIds = new WeakMap();
43527 function getTypeParametersGroupId(node) {
43528 if (!typeParametersGroupIds.has(node)) {
43529 typeParametersGroupIds.set(node, Symbol("typeParameters"));
43532 return typeParametersGroupIds.get(node);
43535 function printTypeParameters(path, options, print, paramsKey) {
43536 const n = path.getValue();
43538 if (!n[paramsKey]) {
43540 } // for TypeParameterDeclaration typeParameters is a single node
43543 if (!Array.isArray(n[paramsKey])) {
43544 return path.call(print, paramsKey);
43547 const grandparent = path.getNode(2);
43548 const isParameterInTestCall = grandparent != null && isTestCall$2(grandparent);
43549 const shouldInline = isParameterInTestCall || n[paramsKey].length === 0 || n[paramsKey].length === 1 && (shouldHugType$2(n[paramsKey][0]) || n[paramsKey][0].type === "GenericTypeAnnotation" && shouldHugType$2(n[paramsKey][0].id) || n[paramsKey][0].type === "TSTypeReference" && shouldHugType$2(n[paramsKey][0].typeName) || n[paramsKey][0].type === "NullableTypeAnnotation");
43551 if (shouldInline) {
43552 return concat$j(["<", join$7(", ", path.map(print, paramsKey)), printDanglingCommentsForInline(path, options), ">"]);
43555 return group$b(concat$j(["<", indent$f(concat$j([softline$b, join$7(concat$j([",", line$c]), path.map(print, paramsKey))])), ifBreak$7(options.parser !== "typescript" && options.parser !== "babel-ts" && shouldPrintComma$5(options, "all") ? "," : ""), softline$b, ">"]), {
43556 id: getTypeParametersGroupId(n)
43560 function printDanglingCommentsForInline(path, options) {
43561 const n = path.getValue();
43563 if (!hasDanglingComments$4(n)) {
43567 const hasOnlyBlockComments = n.comments.every(comment => isBlockComment$7(comment));
43568 const printed = printDanglingComments$6(path, options,
43570 hasOnlyBlockComments);
43572 if (hasOnlyBlockComments) {
43576 return concat$j([printed, hardline$c]);
43579 var typeParameters = {
43580 printTypeParameters,
43581 getTypeParametersGroupId
43585 printComments: printComments$2
43588 printString: printString$1,
43589 printNumber: printNumber$1
43597 isNumericLiteral: isNumericLiteral$1,
43598 isSimpleNumber: isSimpleNumber$1,
43599 isStringLiteral: isStringLiteral$2,
43600 isStringPropSafeToUnquote: isStringPropSafeToUnquote$1,
43603 const needsQuoteProps = new WeakMap();
43605 function printPropertyKey(path, options, print) {
43606 const node = path.getNode();
43608 if (node.computed) {
43609 return concat$k(["[", path.call(print, "key"), "]"]);
43612 const parent = path.getParentNode();
43617 if (node.type === "ClassPrivateProperty" && // flow has `Identifier` key, and babel has `PrivateName` key
43618 key.type === "Identifier") {
43619 return concat$k(["#", path.call(print, "key")]);
43622 if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) {
43623 const objectHasStringProp = (parent.properties || parent.body || parent.members).some(prop => !prop.computed && prop.key && isStringLiteral$2(prop.key) && !isStringPropSafeToUnquote$1(prop, options));
43624 needsQuoteProps.set(parent, objectHasStringProp);
43627 if ((key.type === "Identifier" || isNumericLiteral$1(key) && isSimpleNumber$1(printNumber$1(rawText$2(key))) && // Avoid converting 999999999999999999999 to 1e+21, 0.99999999999999999 to 1 and 1.0 to 1.
43628 String(key.value) === printNumber$1(rawText$2(key)) && // Quoting number keys is safe in JS and Flow, but not in TypeScript (as
43629 // mentioned in `isStringPropSafeToUnquote`).
43630 !(options.parser === "typescript" || options.parser === "babel-ts")) && (options.parser === "json" || options.quoteProps === "consistent" && needsQuoteProps.get(parent))) {
43634 const prop = printString$1(JSON.stringify(key.type === "Identifier" ? key.name : key.value.toString()), options);
43635 return path.call(keyPath => printComments$2(keyPath, () => prop, options), "key");
43638 if (isStringPropSafeToUnquote$1(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) {
43642 return path.call(keyPath => printComments$2(keyPath, () => /^\d/.test(key.value) ? printNumber$1(key.value) : key.value, options), "key");
43645 return path.call(print, "key");
43652 /** @type {import("assert")} */
43656 printDanglingComments: printDanglingComments$7
43659 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$3
43665 softline: softline$c,
43668 ifBreak: ifBreak$8,
43669 hardline: hardline$d
43673 getFunctionParameters: getFunctionParameters$4,
43674 hasDanglingComments: hasDanglingComments$5,
43675 hasLeadingOwnLineComment: hasLeadingOwnLineComment$1,
43676 isFlowAnnotationComment: isFlowAnnotationComment$2,
43677 isJSXNode: isJSXNode$4,
43678 isTemplateOnItsOwnLine: isTemplateOnItsOwnLine$1,
43679 shouldPrintComma: shouldPrintComma$6,
43680 startsWithNoLookaheadToken: startsWithNoLookaheadToken$2,
43681 returnArgumentHasLeadingComment: returnArgumentHasLeadingComment$1,
43682 isBinaryish: isBinaryish$3,
43683 isLineComment: isLineComment$1
43689 printFunctionParameters: printFunctionParameters$1
43690 } = functionParameters;
43692 printPropertyKey: printPropertyKey$1
43695 printFunctionTypeParameters: printFunctionTypeParameters$2
43698 function printFunctionDeclaration(path, print, options, expandArg) {
43699 const n = path.getValue();
43703 parts.push("async ");
43707 parts.push("function* ");
43709 parts.push("function ");
43713 parts.push(path.call(print, "id"));
43716 parts.push(printFunctionTypeParameters$2(path, options, print), group$c(concat$l([printFunctionParameters$1(path, print, options, expandArg), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body"));
43717 return concat$l(parts);
43720 function printMethod(path, options, print) {
43721 const node = path.getNode();
43725 const value = node.value || node;
43728 if (!kind || kind === "init" || kind === "method" || kind === "constructor") {
43730 parts.push("async ");
43733 assert__default['default'].ok(kind === "get" || kind === "set");
43734 parts.push(kind, " ");
43735 } // A `getter`/`setter` can't be a generator, but it's recoverable
43738 if (value.generator) {
43742 parts.push(printPropertyKey$1(path, options, print), node.optional || node.key.optional ? "?" : "", node === value ? printMethodInternal(path, options, print) : path.call(path => printMethodInternal(path, options, print), "value"));
43743 return concat$l(parts);
43746 function printMethodInternal(path, options, print) {
43747 const parts = [printFunctionTypeParameters$2(path, options, print), group$c(concat$l([printFunctionParameters$1(path, print, options), printReturnType(path, print, options)]))];
43749 if (path.getNode().body) {
43750 parts.push(" ", path.call(print, "body"));
43752 parts.push(options.semi ? ";" : "");
43755 return concat$l(parts);
43758 function printArrowFunctionExpression(path, options, print, args) {
43759 const n = path.getValue();
43763 parts.push("async ");
43766 if (shouldPrintParamsWithoutParens(path, options)) {
43767 parts.push(path.call(print, "params", 0));
43769 parts.push(group$c(concat$l([printFunctionParameters$1(path, print, options,
43771 args && (args.expandLastArg || args.expandFirstArg),
43772 /* printTypeParams */
43773 true), printReturnType(path, print, options)])));
43776 const dangling = printDanglingComments$7(path, options,
43779 const nextCharacter = getNextNonSpaceNonCommentCharacterIndex$3(options.originalText, comment, locEnd$8);
43780 return nextCharacter !== false && options.originalText.slice(nextCharacter, nextCharacter + 2) === "=>";
43784 parts.push(" ", dangling);
43788 const body = path.call(bodyPath => print(bodyPath, args), "body"); // We want to always keep these types of nodes on the same line
43791 if (!hasLeadingOwnLineComment$1(options.originalText, n.body) && (n.body.type === "ArrayExpression" || n.body.type === "ObjectExpression" || n.body.type === "BlockStatement" || isJSXNode$4(n.body) || isTemplateOnItsOwnLine$1(n.body, options.originalText) || n.body.type === "ArrowFunctionExpression" || n.body.type === "DoExpression")) {
43792 return group$c(concat$l([concat$l(parts), " ", body]));
43793 } // We handle sequence expressions as the body of arrows specially,
43794 // so that the required parentheses end up on their own lines.
43797 if (n.body.type === "SequenceExpression") {
43798 return group$c(concat$l([concat$l(parts), group$c(concat$l([" (", indent$g(concat$l([softline$c, body])), softline$c, ")"]))]));
43799 } // if the arrow function is expanded as last argument, we are adding a
43800 // level of indentation and need to add a softline to align the closing )
43801 // with the opening (, or if it's inside a JSXExpression (e.g. an attribute)
43802 // we should align the expression's closing } with the line with the opening {.
43805 const shouldAddSoftLine = (args && args.expandLastArg || path.getParentNode().type === "JSXExpressionContainer") && !(n.comments && n.comments.length);
43806 const printTrailingComma = args && args.expandLastArg && shouldPrintComma$6(options, "all"); // In order to avoid confusion between
43810 const shouldAddParens = n.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken$2(n.body,
43811 /* forbidFunctionAndClass */
43813 return group$c(concat$l([concat$l(parts), group$c(concat$l([indent$g(concat$l([line$d, shouldAddParens ? ifBreak$8("", "(") : "", body, shouldAddParens ? ifBreak$8("", ")") : ""])), shouldAddSoftLine ? concat$l([ifBreak$8(printTrailingComma ? "," : ""), softline$c]) : ""]))]));
43816 function canPrintParamsWithoutParens(node) {
43817 const parameters = getFunctionParameters$4(node);
43818 return parameters.length === 1 && !node.typeParameters && !hasDanglingComments$5(node) && parameters[0].type === "Identifier" && !parameters[0].typeAnnotation && !parameters[0].comments && !parameters[0].optional && !node.predicate && !node.returnType;
43821 function shouldPrintParamsWithoutParens(path, options) {
43822 if (options.arrowParens === "always") {
43826 if (options.arrowParens === "avoid") {
43827 const node = path.getValue();
43828 return canPrintParamsWithoutParens(node);
43829 } // Fallback default; should be unreachable
43831 /* istanbul ignore next */
43837 function printReturnType(path, print, options) {
43838 const n = path.getValue();
43839 const returnType = path.call(print, "returnType");
43841 if (n.returnType && isFlowAnnotationComment$2(options.originalText, n.returnType)) {
43842 return concat$l([" /*: ", returnType, " */"]);
43845 const parts = [returnType]; // prepend colon to TypeScript type annotation
43847 if (n.returnType && n.returnType.typeAnnotation) {
43848 parts.unshift(": ");
43852 // The return type will already add the colon, but otherwise we
43853 // need to do it ourselves
43854 parts.push(n.returnType ? " " : ": ", path.call(print, "predicate"));
43857 return concat$l(parts);
43858 } // `ReturnStatement` and `ThrowStatement`
43861 function printReturnAndThrowArgument(path, options, print) {
43862 const node = path.getValue();
43863 const semi = options.semi ? ";" : "";
43866 if (node.argument) {
43867 if (returnArgumentHasLeadingComment$1(options, node.argument)) {
43868 parts.push(concat$l([" (", indent$g(concat$l([hardline$d, path.call(print, "argument")])), hardline$d, ")"]));
43869 } else if (isBinaryish$3(node.argument) || node.argument.type === "SequenceExpression") {
43870 parts.push(group$c(concat$l([ifBreak$8(" (", " "), indent$g(concat$l([softline$c, path.call(print, "argument")])), softline$c, ifBreak$8(")")])));
43872 parts.push(" ", path.call(print, "argument"));
43876 const lastComment = Array.isArray(node.comments) && node.comments[node.comments.length - 1];
43877 const isLastCommentLine = lastComment && isLineComment$1(lastComment);
43879 if (isLastCommentLine) {
43883 if (hasDanglingComments$5(node)) {
43884 parts.push(" ", printDanglingComments$7(path, options,
43889 if (!isLastCommentLine) {
43893 return concat$l(parts);
43897 printFunctionDeclaration,
43898 printArrowFunctionExpression,
43900 printReturnAndThrowArgument,
43901 shouldPrintParamsWithoutParens
43905 printComments: printComments$3,
43906 printDanglingComments: printDanglingComments$8
43913 hardline: hardline$e,
43914 softline: softline$d,
43921 hasTrailingComment: hasTrailingComment$2,
43922 hasTrailingLineComment: hasTrailingLineComment$1
43925 getTypeParametersGroupId: getTypeParametersGroupId$1
43926 } = typeParameters;
43928 printMethod: printMethod$1
43931 printDecorators: printDecorators$1
43934 function printClass(path, options, print) {
43935 const n = path.getValue();
43939 parts.push("abstract ");
43942 parts.push("class"); // Keep old behaviour of extends in same line
43943 // If there is only on extends and there are not comments
43945 const groupMode = n.id && hasTrailingComment$2(n.id) || n.superClass && n.superClass.comments && n.superClass.comments.length !== 0 || n.extends && n.extends.length !== 0 || // DeclareClass
43946 n.mixins && n.mixins.length !== 0 || n.implements && n.implements.length !== 0;
43947 const partsGroup = [];
43948 const extendsParts = [];
43951 partsGroup.push(" ", path.call(print, "id"));
43954 partsGroup.push(path.call(print, "typeParameters"));
43956 if (n.superClass) {
43957 const printed = concat$m(["extends ", printSuperClass(path, options, print), path.call(print, "superTypeParameters")]);
43958 const printedWithComments = path.call(superClass => printComments$3(superClass, () => printed, options), "superClass");
43961 extendsParts.push(line$e, group$d(printedWithComments));
43963 extendsParts.push(" ", printedWithComments);
43966 extendsParts.push(printList(path, options, print, "extends"));
43969 extendsParts.push(printList(path, options, print, "mixins"));
43970 extendsParts.push(printList(path, options, print, "implements"));
43973 const printedExtends = concat$m(extendsParts);
43975 if (shouldIndentOnlyHeritageClauses(n)) {
43976 parts.push(group$d(concat$m(partsGroup.concat(ifBreak$9(indent$h(printedExtends), printedExtends)))));
43978 parts.push(group$d(indent$h(concat$m(partsGroup.concat(printedExtends)))));
43981 parts.push(...partsGroup, ...extendsParts);
43984 parts.push(" ", path.call(print, "body"));
43985 return concat$m(parts);
43988 function hasMultipleHeritage(node) {
43989 return ["superClass", "extends", "mixins", "implements"].filter(key => !!node[key]).length > 1;
43992 function shouldIndentOnlyHeritageClauses(node) {
43993 return node.typeParameters && !hasTrailingLineComment$1(node.typeParameters) && !hasMultipleHeritage(node);
43996 function printList(path, options, print, listName) {
43997 const n = path.getValue();
43999 if (!n[listName] || n[listName].length === 0) {
44003 const printedLeadingComments = printDanglingComments$8(path, options,
44007 }) => marker === listName);
44008 return concat$m([shouldIndentOnlyHeritageClauses(n) ? ifBreak$9(" ", line$e, {
44009 groupId: getTypeParametersGroupId$1(n.typeParameters)
44010 }) : line$e, printedLeadingComments, printedLeadingComments && hardline$e, listName, group$d(indent$h(concat$m([line$e, join$8(concat$m([",", line$e]), path.map(print, listName))])))]);
44013 function printSuperClass(path, options, print) {
44014 const printed = path.call(print, "superClass");
44015 const parent = path.getParentNode();
44017 if (parent.type === "AssignmentExpression") {
44018 return group$d(ifBreak$9(concat$m(["(", indent$h(concat$m([softline$d, printed])), softline$d, ")"]), printed));
44024 function printClassMethod(path, options, print) {
44025 const n = path.getValue();
44028 if (n.decorators && n.decorators.length !== 0) {
44029 parts.push(printDecorators$1(path, options, print));
44032 if (n.accessibility) {
44033 parts.push(n.accessibility + " ");
44037 parts.push("static ");
44040 if (n.type === "TSAbstractMethodDefinition" || n.abstract) {
44041 parts.push("abstract ");
44044 parts.push(printMethod$1(path, options, print));
44045 return concat$m(parts);
44054 getLast: getLast$6,
44055 getPenultimate: getPenultimate$1,
44056 isNextLineEmpty: isNextLineEmpty$5
44059 getFunctionParameters: getFunctionParameters$5,
44060 iterateFunctionParametersPath: iterateFunctionParametersPath$2,
44061 hasLeadingComment: hasLeadingComment$3,
44062 hasTrailingComment: hasTrailingComment$3,
44063 isFunctionCompositionArgs: isFunctionCompositionArgs$1,
44064 isJSXNode: isJSXNode$5,
44065 isLongCurriedCallExpression: isLongCurriedCallExpression$1,
44066 shouldPrintComma: shouldPrintComma$7,
44067 getCallArguments: getCallArguments$1,
44068 iterateCallArgumentsPath: iterateCallArgumentsPath$1
44077 hardline: hardline$f,
44078 softline: softline$e,
44081 conditionalGroup: conditionalGroup$2,
44082 ifBreak: ifBreak$a,
44083 breakParent: breakParent$3
44086 willBreak: willBreak$2
44090 function printCallArguments(path, options, print) {
44091 const node = path.getValue();
44092 const isDynamicImport = node.type === "ImportExpression";
44093 const args = getCallArguments$1(node);
44095 if (args.length === 0) {
44096 return concat$n(["(", comments.printDanglingComments(path, options,
44099 } // useEffect(() => { ... }, [foo, bar, baz])
44102 if (args.length === 2 && args[0].type === "ArrowFunctionExpression" && getFunctionParameters$5(args[0]).length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && !args.some(arg => arg.comments)) {
44103 return concat$n(["(", path.call(print, "arguments", 0), ", ", path.call(print, "arguments", 1), ")"]);
44113 function shouldBreakForArrowFunctionInArguments(arg, argPath) {
44114 if (!arg || arg.type !== "ArrowFunctionExpression" || !arg.body || arg.body.type !== "BlockStatement" || getFunctionParameters$5(arg).length === 0) {
44118 let shouldBreak = false;
44119 iterateFunctionParametersPath$2(argPath, parameterPath => {
44120 shouldBreak = shouldBreak || willBreak$2(concat$n([print(parameterPath)]));
44122 return shouldBreak;
44125 let anyArgEmptyLine = false;
44126 let shouldBreakForArrowFunction = false;
44127 let hasEmptyLineFollowingFirstArg = false;
44128 const lastArgIndex = args.length - 1;
44129 const printedArguments = [];
44130 iterateCallArgumentsPath$1(path, (argPath, index) => {
44131 const arg = argPath.getNode();
44132 const parts = [print(argPath)];
44134 if (index === lastArgIndex) ; else if (isNextLineEmpty$5(options.originalText, arg, locEnd$9)) {
44136 hasEmptyLineFollowingFirstArg = true;
44139 anyArgEmptyLine = true;
44140 parts.push(",", hardline$f, hardline$f);
44142 parts.push(",", line$f);
44145 shouldBreakForArrowFunction = shouldBreakForArrowFunctionInArguments(arg, argPath);
44146 printedArguments.push(concat$n(parts));
44148 const maybeTrailingComma = // Dynamic imports cannot have trailing commas
44149 !(isDynamicImport || node.callee && node.callee.type === "Import") && shouldPrintComma$7(options, "all") ? "," : "";
44151 function allArgsBrokenOut() {
44152 return group$e(concat$n(["(", indent$i(concat$n([line$f, concat$n(printedArguments)])), maybeTrailingComma, line$f, ")"]), {
44157 if (path.getParentNode().type !== "Decorator" && isFunctionCompositionArgs$1(args)) {
44158 return allArgsBrokenOut();
44161 const shouldGroupFirst = shouldGroupFirstArg(args);
44162 const shouldGroupLast = shouldGroupLastArg(args);
44164 if (shouldGroupFirst || shouldGroupLast) {
44165 const shouldBreak = (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$2) : printedArguments.slice(0, -1).some(willBreak$2)) || anyArgEmptyLine || shouldBreakForArrowFunction; // We want to print the last argument with a special flag
44167 let printedExpanded = [];
44168 iterateCallArgumentsPath$1(path, (argPath, i) => {
44169 if (shouldGroupFirst && i === 0) {
44170 printedExpanded = [concat$n([argPath.call(p => print(p, {
44171 expandFirstArg: true
44172 })), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$f : line$f, hasEmptyLineFollowingFirstArg ? hardline$f : ""])].concat(printedArguments.slice(1));
44175 if (shouldGroupLast && i === args.length - 1) {
44176 printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(p => print(p, {
44177 expandLastArg: true
44181 const somePrintedArgumentsWillBreak = printedArguments.some(willBreak$2);
44182 const simpleConcat = concat$n(["(", concat$n(printedExpanded), ")"]);
44183 return concat$n([somePrintedArgumentsWillBreak ? breakParent$3 : "", conditionalGroup$2([!somePrintedArgumentsWillBreak && !node.typeArguments && !node.typeParameters ? simpleConcat : ifBreak$a(allArgsBrokenOut(), simpleConcat), shouldGroupFirst ? concat$n(["(", group$e(printedExpanded[0], {
44185 }), concat$n(printedExpanded.slice(1)), ")"]) : concat$n(["(", concat$n(printedArguments.slice(0, -1)), group$e(getLast$6(printedExpanded), {
44187 }), ")"]), allArgsBrokenOut()], {
44192 const contents = concat$n(["(", indent$i(concat$n([softline$e, concat$n(printedArguments)])), ifBreak$a(maybeTrailingComma), softline$e, ")"]);
44194 if (isLongCurriedCallExpression$1(path)) {
44195 // By not wrapping the arguments in a group, the printer prioritizes
44196 // breaking up these arguments rather than the args of the parent call.
44200 return group$e(contents, {
44201 shouldBreak: printedArguments.some(willBreak$2) || anyArgEmptyLine
44205 function couldGroupArg(arg) {
44206 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
44207 // https://github.com/prettier/prettier/issues/4070
44208 // export class Thing implements OtherThing {
44209 // do: (type: Type) => Provider<Prop> = memoize(
44210 // (type: ObjectType): Provider<Opts> => {}
44213 // https://github.com/prettier/prettier/issues/6099
44214 // app.get("/", (req, res): void => {
44215 // res.send("Hello World!");
44217 !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$5(arg.body));
44220 function shouldGroupLastArg(args) {
44221 const lastArg = getLast$6(args);
44222 const penultimateArg = getPenultimate$1(args);
44223 return !hasLeadingComment$3(lastArg) && !hasTrailingComment$3(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type,
44224 // disable last element expansion.
44225 !penultimateArg || penultimateArg.type !== lastArg.type);
44228 function shouldGroupFirstArg(args) {
44229 if (args.length !== 2) {
44233 const [firstArg, secondArg] = args;
44234 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);
44237 var callArguments = printCallArguments;
44242 softline: softline$f,
44248 isNumericLiteral: isNumericLiteral$2
44251 printOptionalToken: printOptionalToken$3
44254 function printMemberExpression(path, options, print) {
44255 const n = path.getValue();
44256 const parent = path.getParentNode();
44257 let firstNonMemberParent;
44261 firstNonMemberParent = path.getParentNode(i);
44263 } while (firstNonMemberParent && (firstNonMemberParent.type === "MemberExpression" || firstNonMemberParent.type === "OptionalMemberExpression" || firstNonMemberParent.type === "TSNonNullExpression"));
44265 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";
44266 return concat$o([path.call(print, "object"), shouldInline ? printMemberLookup(path, options, print) : group$f(indent$j(concat$o([softline$f, printMemberLookup(path, options, print)])))]);
44269 function printMemberLookup(path, options, print) {
44270 const property = path.call(print, "property");
44271 const n = path.getValue();
44272 const optional = printOptionalToken$3(path);
44275 return concat$o([optional, ".", property]);
44278 if (!n.property || isNumericLiteral$2(n.property)) {
44279 return concat$o([optional, "[", property, "]"]);
44282 return group$f(concat$o([optional, "[", indent$j(concat$o([softline$f, property])), softline$f, "]"]));
44286 printMemberExpression,
44291 getLast: getLast$7,
44292 isNextLineEmpty: isNextLineEmpty$6,
44293 isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$2,
44294 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$4
44297 hasLeadingComment: hasLeadingComment$4,
44298 hasTrailingComment: hasTrailingComment$4,
44299 isCallOrOptionalCallExpression: isCallOrOptionalCallExpression$2,
44300 isFunctionOrArrowExpression: isFunctionOrArrowExpression$1,
44301 isLongCurriedCallExpression: isLongCurriedCallExpression$2,
44302 isMemberish: isMemberish$1,
44303 isNumericLiteral: isNumericLiteral$3,
44304 isSimpleCallArgument: isSimpleCallArgument$1
44313 hardline: hardline$g,
44316 conditionalGroup: conditionalGroup$3,
44317 breakParent: breakParent$4
44320 willBreak: willBreak$3
44324 printMemberLookup: printMemberLookup$1
44327 printOptionalToken: printOptionalToken$4,
44328 printFunctionTypeParameters: printFunctionTypeParameters$3,
44329 printBindExpressionCallee: printBindExpressionCallee$1
44330 } = misc; // We detect calls on member expressions specially to format a
44331 // common pattern better. The pattern we are looking for is this:
44334 // .map(x => x + 1)
44335 // .filter(x => x > 10)
44336 // .some(x => x % 2)
44338 // The way it is structured in the AST is via a nested sequence of
44339 // MemberExpression and CallExpression. We need to traverse the AST
44340 // and make groups out of it to print it in the desired way.
44342 function printMemberChain(path, options, print) {
44343 const parent = path.getParentNode();
44344 const isExpressionStatement = !parent || parent.type === "ExpressionStatement"; // The first phase is to linearize the AST by traversing it down.
44347 // has the following AST structure:
44348 // CallExpression(MemberExpression(CallExpression(Identifier)))
44349 // and we transform it into
44350 // [Identifier, CallExpression, MemberExpression, CallExpression]
44352 const printedNodes = []; // Here we try to retain one typed empty line after each call expression or
44353 // the first group whether it is in parentheses or not
44355 function shouldInsertEmptyLineAfter(node) {
44359 const nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$4(originalText, node, locEnd$a);
44360 const nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty
44361 // line after that parenthesis
44363 if (nextChar === ")") {
44364 return nextCharIndex !== false && isNextLineEmptyAfterIndex$2(originalText, nextCharIndex + 1);
44367 return isNextLineEmpty$6(originalText, node, locEnd$a);
44370 function rec(path) {
44371 const node = path.getValue();
44373 if (isCallOrOptionalCallExpression$2(node) && (isMemberish$1(node.callee) || isCallOrOptionalCallExpression$2(node.callee))) {
44374 printedNodes.unshift({
44376 printed: concat$p([comments.printComments(path, () => concat$p([printOptionalToken$4(path), printFunctionTypeParameters$3(path, options, print), callArguments(path, options, print)]), options), shouldInsertEmptyLineAfter(node) ? hardline$g : ""])
44378 path.call(callee => rec(callee), "callee");
44379 } else if (isMemberish$1(node)) {
44380 printedNodes.unshift({
44382 needsParens: needsParens_1(path, options),
44383 printed: comments.printComments(path, () => node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup$1(path, options, print) : printBindExpressionCallee$1(path, options, print), options)
44385 path.call(object => rec(object), "object");
44386 } else if (node.type === "TSNonNullExpression") {
44387 printedNodes.unshift({
44389 printed: comments.printComments(path, () => "!", options)
44391 path.call(expression => rec(expression), "expression");
44393 printedNodes.unshift({
44395 printed: path.call(print)
44398 } // Note: the comments of the root node have already been printed, so we
44399 // need to extract this first call without printing them as they would
44400 // if handled inside of the recursive call.
44403 const node = path.getValue();
44404 printedNodes.unshift({
44406 printed: concat$p([printOptionalToken$4(path), printFunctionTypeParameters$3(path, options, print), callArguments(path, options, print)])
44410 path.call(callee => rec(callee), "callee");
44411 } // Once we have a linear list of printed nodes, we want to create groups out
44415 // will be grouped as
44417 // [Identifier, CallExpression],
44418 // [MemberExpression, MemberExpression, CallExpression],
44419 // [MemberExpression, CallExpression],
44420 // [MemberExpression],
44422 // so that we can print it as
44427 // The first group is the first node followed by
44428 // - as many CallExpression as possible
44429 // < fn()()() >.something()
44430 // - as many array accessors as possible
44431 // < fn()[0][1][2] >.something()
44432 // - then, as many MemberExpression as possible but the last one
44433 // < this.items >.something()
44437 let currentGroup = [printedNodes[0]];
44440 for (; i < printedNodes.length; ++i) {
44441 if (printedNodes[i].node.type === "TSNonNullExpression" || isCallOrOptionalCallExpression$2(printedNodes[i].node) || (printedNodes[i].node.type === "MemberExpression" || printedNodes[i].node.type === "OptionalMemberExpression") && printedNodes[i].node.computed && isNumericLiteral$3(printedNodes[i].node.property)) {
44442 currentGroup.push(printedNodes[i]);
44448 if (!isCallOrOptionalCallExpression$2(printedNodes[0].node)) {
44449 for (; i + 1 < printedNodes.length; ++i) {
44450 if (isMemberish$1(printedNodes[i].node) && isMemberish$1(printedNodes[i + 1].node)) {
44451 currentGroup.push(printedNodes[i]);
44458 groups.push(currentGroup);
44459 currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by
44460 // a sequence of CallExpression. To compute it, we keep adding things to the
44461 // group until we has seen a CallExpression in the past and reach a
44462 // MemberExpression
44464 let hasSeenCallExpression = false;
44466 for (; i < printedNodes.length; ++i) {
44467 if (hasSeenCallExpression && isMemberish$1(printedNodes[i].node)) {
44468 // [0] should be appended at the end of the group instead of the
44469 // beginning of the next one
44470 if (printedNodes[i].node.computed && isNumericLiteral$3(printedNodes[i].node.property)) {
44471 currentGroup.push(printedNodes[i]);
44475 groups.push(currentGroup);
44477 hasSeenCallExpression = false;
44480 if (isCallOrOptionalCallExpression$2(printedNodes[i].node) || printedNodes[i].node.type === "ImportExpression") {
44481 hasSeenCallExpression = true;
44484 currentGroup.push(printedNodes[i]);
44486 if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(comment => comment.trailing)) {
44487 groups.push(currentGroup);
44489 hasSeenCallExpression = false;
44493 if (currentGroup.length > 0) {
44494 groups.push(currentGroup);
44495 } // There are cases like Object.keys(), Observable.of(), _.values() where
44496 // they are the subject of all the chained calls and therefore should
44497 // be kept on the same line:
44499 // Object.keys(items)
44503 // In order to detect those cases, we use an heuristic: if the first
44504 // node is an identifier with the name starting with a capital
44505 // letter or just a sequence of _$. The rationale is that they are
44506 // likely to be factories.
44509 function isFactory(name) {
44510 return /^[A-Z]|^[$_]+$/.test(name);
44511 } // In case the Identifier is shorter than tab width, we can keep the
44512 // first call in a single line, if it's an ExpressionStatement.
44514 // d3.scaleLinear()
44515 // .domain([0, 100])
44516 // .range([0, width]);
44520 function isShort(name) {
44521 return name.length <= options.tabWidth;
44524 function shouldNotWrap(groups) {
44525 const hasComputed = groups[1].length && groups[1][0].node.computed;
44527 if (groups[0].length === 1) {
44528 const firstNode = groups[0][0].node;
44529 return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpressionStatement && isShort(firstNode.name) || hasComputed);
44532 const lastNode = getLast$7(groups[0]).node;
44533 return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed);
44536 const shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups);
44538 function printGroup(printedGroup) {
44539 const printed = printedGroup.map(tuple => tuple.printed); // Checks if the last node (i.e. the parent node) needs parens and print
44542 if (printedGroup.length > 0 && printedGroup[printedGroup.length - 1].needsParens) {
44543 return concat$p(["(", ...printed, ")"]);
44546 return concat$p(printed);
44549 function printIndentedGroup(groups) {
44550 /* istanbul ignore next */
44551 if (groups.length === 0) {
44555 return indent$k(group$g(concat$p([hardline$g, join$9(hardline$g, groups.map(printGroup))])));
44558 const printedGroups = groups.map(printGroup);
44559 const oneLine = concat$p(printedGroups);
44560 const cutoff = shouldMerge ? 3 : 2;
44561 const flatGroups = flatten_1(groups);
44562 const hasComment = flatGroups.slice(1, -1).some(node => hasLeadingComment$4(node.node)) || flatGroups.slice(0, -1).some(node => hasTrailingComment$4(node.node)) || groups[cutoff] && hasLeadingComment$4(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just
44563 // render everything concatenated together.
44565 if (groups.length <= cutoff && !hasComment) {
44566 if (isLongCurriedCallExpression$2(path)) {
44570 return group$g(oneLine);
44571 } // Find out the last node in the first group and check if it has an
44572 // empty line after
44575 const lastNodeBeforeIndent = getLast$7(groups[shouldMerge ? 1 : 0]).node;
44576 const shouldHaveEmptyLineBeforeIndent = !isCallOrOptionalCallExpression$2(lastNodeBeforeIndent) && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
44577 const expanded = concat$p([printGroup(groups[0]), shouldMerge ? concat$p(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$g : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]);
44578 const callExpressions = printedNodes.map(({
44580 }) => node).filter(isCallOrOptionalCallExpression$2);
44582 function lastGroupWillBreakAndOtherCallsHaveFunctionArguments() {
44583 const lastGroupNode = getLast$7(getLast$7(groups)).node;
44584 const lastGroupDoc = getLast$7(printedGroups);
44585 return isCallOrOptionalCallExpression$2(lastGroupNode) && willBreak$3(lastGroupDoc) && callExpressions.slice(0, -1).some(n => n.arguments.some(isFunctionOrArrowExpression$1));
44586 } // We don't want to print in one line if at least one of these conditions occurs:
44587 // * the chain has comments,
44588 // * the chain is an expression statement and all the arguments are literal-like ("fluent configuration" pattern),
44589 // * the chain is longer than 2 calls and has non-trivial arguments or more than 2 arguments in any call but the first one,
44590 // * any group but the last one has a hard line,
44591 // * the last call's arguments have a hard line and other calls have non-trivial arguments.
44594 if (hasComment || callExpressions.length > 2 && callExpressions.some(expr => !expr.arguments.every(arg => isSimpleCallArgument$1(arg, 0))) || printedGroups.slice(0, -1).some(willBreak$3) || lastGroupWillBreakAndOtherCallsHaveFunctionArguments()) {
44595 return group$g(expanded);
44598 return concat$p([// We only need to check `oneLine` because if `expanded` is chosen
44599 // that means that the parent group has already been broken
44601 willBreak$3(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$4 : "", conditionalGroup$3([oneLine, expanded])]);
44604 var memberChain = printMemberChain;
44614 getCallArguments: getCallArguments$2,
44615 hasFlowAnnotationComment: hasFlowAnnotationComment$2,
44616 isCallOrOptionalCallExpression: isCallOrOptionalCallExpression$3,
44617 isMemberish: isMemberish$2,
44618 isTemplateOnItsOwnLine: isTemplateOnItsOwnLine$2,
44619 isTestCall: isTestCall$3,
44620 iterateCallArgumentsPath: iterateCallArgumentsPath$2
44623 printOptionalToken: printOptionalToken$5,
44624 printFunctionTypeParameters: printFunctionTypeParameters$4
44627 function printCallExpression(path, options, print) {
44628 const n = path.getValue();
44629 const isNew = n.type === "NewExpression";
44630 const isDynamicImport = n.type === "ImportExpression";
44631 const optional = printOptionalToken$5(path);
44632 const args = getCallArguments$2(n);
44634 if ( // Dangling comments not handled, all these special cases should has argument #9668
44635 args.length > 0 && ( // We want to keep CommonJS- and AMD-style require calls, and AMD-style
44636 // define calls, as a unit.
44637 // e.g. `define(["some/lib", (lib) => {`
44638 !isDynamicImport && !isNew && n.callee.type === "Identifier" && (n.callee.name === "require" || n.callee.name === "define") || // Template literals as single arguments
44639 args.length === 1 && isTemplateOnItsOwnLine$2(args[0], options.originalText) || // Keep test declarations on a single line
44640 // e.g. `it('long name', () => {`
44641 !isNew && isTestCall$3(n, path.getParentNode()))) {
44642 const printed = [];
44643 iterateCallArgumentsPath$2(path, argPath => {
44644 printed.push(print(argPath));
44646 return concat$q([isNew ? "new " : "", path.call(print, "callee"), optional, printFunctionTypeParameters$4(path, options, print), concat$q(["(", join$a(", ", printed), ")"])]);
44647 } // Inline Flow annotation comments following Identifiers in Call nodes need to
44648 // stay with the Identifier. For example:
44650 // foo /*:: <SomeGeneric> */(bar);
44652 // Here, we ensure that such comments stay between the Identifier and the Callee.
44655 const isIdentifierWithFlowAnnotation = (options.parser === "babel" || options.parser === "babel-flow") && n.callee && n.callee.type === "Identifier" && hasFlowAnnotationComment$2(n.callee.trailingComments);
44657 if (isIdentifierWithFlowAnnotation) {
44658 n.callee.trailingComments[0].printed = true;
44659 } // We detect calls on member lookups and possibly print them in a
44660 // special chain format. See `printMemberChain` for more info.
44663 if (!isDynamicImport && !isNew && isMemberish$2(n.callee) && !path.call(path => needsParens_1(path, options), "callee")) {
44664 return memberChain(path, options, print);
44667 const contents = concat$q([isNew ? "new " : "", isDynamicImport ? "import" : path.call(print, "callee"), optional, isIdentifierWithFlowAnnotation ? `/*:: ${n.callee.trailingComments[0].value.slice(2).trim()} */` : "", printFunctionTypeParameters$4(path, options, print), callArguments(path, options, print)]); // We group here when the callee is itself a call expression.
44668 // See `isLongCurriedCallExpression` for more info.
44670 if (isDynamicImport || isCallOrOptionalCallExpression$3(n.callee)) {
44671 return group$h(contents);
44677 var callExpression = {
44678 printCallExpression
44692 hasTrailingComment: hasTrailingComment$5,
44693 hasTrailingLineComment: hasTrailingLineComment$2,
44694 identity: identity$2
44697 getTypeParametersGroupId: getTypeParametersGroupId$2
44698 } = typeParameters;
44700 printTypeScriptModifiers: printTypeScriptModifiers$1
44703 function printInterface(path, options, print) {
44704 const n = path.getValue();
44707 if (n.type === "DeclareInterface" || n.declare) {
44708 parts.push("declare ");
44711 if (n.type === "TSInterfaceDeclaration") {
44712 parts.push(n.abstract ? "abstract " : "", printTypeScriptModifiers$1(path, options, print));
44715 parts.push("interface");
44716 const partsGroup = [];
44717 const extendsParts = [];
44719 if (n.type !== "InterfaceTypeAnnotation") {
44720 partsGroup.push(" ", path.call(print, "id"), path.call(print, "typeParameters"));
44723 const shouldIndentOnlyHeritageClauses = n.typeParameters && !hasTrailingLineComment$2(n.typeParameters);
44725 if (n.extends && n.extends.length !== 0) {
44726 extendsParts.push(shouldIndentOnlyHeritageClauses ? ifBreak$b(" ", line$g, {
44727 groupId: getTypeParametersGroupId$2(n.typeParameters)
44728 }) : line$g, "extends ", (n.extends.length === 1 ? identity$2 : indent$l)(join$b(concat$r([",", line$g]), path.map(print, "extends"))));
44731 if (n.id && hasTrailingComment$5(n.id) || n.extends && n.extends.length !== 0) {
44732 const printedExtends = concat$r(extendsParts);
44734 if (shouldIndentOnlyHeritageClauses) {
44735 parts.push(group$i(concat$r(partsGroup.concat(ifBreak$b(indent$l(printedExtends), printedExtends)))));
44737 parts.push(group$i(indent$l(concat$r(partsGroup.concat(printedExtends)))));
44740 parts.push(...partsGroup, ...extendsParts);
44743 parts.push(" ", path.call(print, "body"));
44744 return group$i(concat$r(parts));
44752 printComments: printComments$4
44762 softline: softline$g,
44769 normalizeParts: normalizeParts$1
44773 hasLeadingOwnLineComment: hasLeadingOwnLineComment$2,
44774 hasTrailingLineComment: hasTrailingLineComment$3,
44775 isBinaryish: isBinaryish$4,
44776 isJSXNode: isJSXNode$6,
44777 shouldFlatten: shouldFlatten$2
44779 /** @typedef {import("../../document").Doc} Doc */
44783 function printBinaryishExpression(path, options, print) {
44784 const n = path.getValue();
44785 const parent = path.getParentNode();
44786 const parentParent = path.getParentNode(1);
44787 const isInsideParenthesis = n !== parent.body && (parent.type === "IfStatement" || parent.type === "WhileStatement" || parent.type === "SwitchStatement" || parent.type === "DoWhileStatement");
44788 const parts = printBinaryishExpressions(path, print, options,
44790 false, isInsideParenthesis); // if (
44791 // this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft
44794 // looks super weird, we want to break the children if the parent breaks
44797 // this.hasPlugin("dynamicImports") &&
44798 // this.lookahead().type === tt.parenLeft
44801 if (isInsideParenthesis) {
44802 return concat$s(parts);
44803 } // Break between the parens in
44804 // unaries or in a member or specific call expression, i.e.
44813 if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || parent.type === "UnaryExpression" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && !parent.computed) {
44814 return group$j(concat$s([indent$m(concat$s([softline$g, concat$s(parts)])), softline$g]));
44815 } // Avoid indenting sub-expressions in some cases where the first sub-expression is already
44816 // indented accordingly. We should indent sub-expressions where the first case isn't indented.
44819 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";
44820 const shouldIndentIfInlining = parent.type === "AssignmentExpression" || parent.type === "VariableDeclarator" || parent.type === "ClassProperty" || parent.type === "FieldDefinition" || parent.type === "TSAbstractClassProperty" || parent.type === "ClassPrivateProperty" || parent.type === "ObjectProperty" || parent.type === "Property";
44821 const samePrecedenceSubExpression = isBinaryish$4(n.left) && shouldFlatten$2(n.operator, n.left.operator);
44823 if (shouldNotIndent || shouldInlineLogicalExpression(n) && !samePrecedenceSubExpression || !shouldInlineLogicalExpression(n) && shouldIndentIfInlining) {
44824 return group$j(concat$s(parts));
44827 if (parts.length === 0) {
44829 } // If the right part is a JSX node, we include it in a separate group to
44830 // prevent it breaking the whole chain, so we can print the expression like:
44839 const hasJSX = isJSXNode$6(n.right);
44840 const firstGroupIndex = parts.findIndex(part => typeof part !== "string" && part.type === "group"); // Separate the leftmost expression, possibly with its leading comments.
44842 const headParts = parts.slice(0, firstGroupIndex === -1 ? 1 : firstGroupIndex + 1);
44843 const rest = concat$s(parts.slice(headParts.length, hasJSX ? -1 : undefined));
44844 const groupId = Symbol("logicalChain-" + ++uid);
44845 const chain = group$j(concat$s([// Don't include the initial expression in the indentation
44846 // level. The first item is guaranteed to be the first
44847 // left-most expression.
44848 ...headParts, indent$m(rest)]), {
44856 const jsxPart = getLast$8(parts);
44857 return group$j(concat$s([chain, ifBreak$c(indent$m(jsxPart), jsxPart, {
44860 } // For binary expressions to be consistent, we need to group
44861 // subsequent operators with the same precedence level under a single
44862 // group. Otherwise they will be nested such that some of them break
44863 // onto new lines but not all. Operators with the same precedence
44864 // level should either all break or not. Because we group them by
44865 // precedence level and the AST is structured based on precedence
44866 // level, things are naturally broken up correctly, i.e. `&&` is
44867 // broken before `+`.
44870 function printBinaryishExpressions(path, print, options, isNested, isInsideParenthesis) {
44871 /** @type{Doc[]} */
44873 const node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same.
44875 if (isBinaryish$4(node)) {
44876 // Put all operators with the same precedence level in the same
44877 // group. The reason we only need to do this with the `left`
44878 // expression is because given an expression like `1 + 2 - 3`, it
44879 // is always parsed like `((1 + 2) - 3)`, meaning the `left` side
44880 // is where the rest of the expression will exist. Binary
44881 // expressions on the right side mean they have a difference
44882 // precedence level and should be treated as a separate group, so
44883 // print them normally. (This doesn't hold for the `**` operator,
44884 // which is unique in that it is right-associative.)
44885 if (shouldFlatten$2(node.operator, node.left.operator)) {
44886 // Flatten them out by recursively calling this function.
44887 parts = parts.concat(path.call(left => printBinaryishExpressions(left, print, options,
44889 true, isInsideParenthesis), "left"));
44891 parts.push(group$j(path.call(print, "left")));
44894 const shouldInline = shouldInlineLogicalExpression(node);
44895 const lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment$2(options.originalText, node.right);
44896 const operator = node.type === "NGPipeExpression" ? "|" : node.operator;
44897 const rightSuffix = node.type === "NGPipeExpression" && node.arguments.length !== 0 ? group$j(indent$m(concat$s([softline$g, ": ", join$c(concat$s([softline$g, ":", ifBreak$c(" ")]), path.map(print, "arguments").map(arg => align$3(2, group$j(arg))))]))) : "";
44898 const right = shouldInline ? concat$s([operator, " ", path.call(print, "right"), rightSuffix]) : concat$s([lineBeforeOperator ? line$h : "", operator, lineBeforeOperator ? " " : line$h, path.call(print, "right"), rightSuffix]); // If there's only a single binary expression, we want to create a group
44899 // in order to avoid having a small right part like -1 be on its own line.
44901 const parent = path.getParentNode();
44902 const shouldBreak = hasTrailingLineComment$3(node.left);
44903 const shouldGroup = shouldBreak || !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type;
44904 parts.push(lineBeforeOperator ? "" : " ", shouldGroup ? group$j(right, {
44906 }) : right); // The root comments are already printed, but we need to manually print
44907 // the other ones since we don't call the normal print on BinaryExpression,
44908 // only for the left and right parts
44910 if (isNested && node.comments) {
44911 parts = normalizeParts$1(printComments$4(path, () => concat$s(parts), options).parts);
44914 // Our stopping case. Simply print the node normally.
44915 parts.push(group$j(path.call(print)));
44921 function shouldInlineLogicalExpression(node) {
44922 if (node.type !== "LogicalExpression") {
44926 if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) {
44930 if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) {
44934 if (isJSXNode$6(node.right)) {
44942 printBinaryishExpression,
44943 shouldInlineLogicalExpression
44955 hasLeadingOwnLineComment: hasLeadingOwnLineComment$3,
44956 isBinaryish: isBinaryish$5,
44957 isMemberExpressionChain: isMemberExpressionChain$1,
44958 isStringLiteral: isStringLiteral$3
44961 shouldInlineLogicalExpression: shouldInlineLogicalExpression$1
44964 function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) {
44966 return printedLeft;
44969 const printed = printAssignmentRight(leftNode, rightNode, printedRight, options);
44970 return group$k(concat$t([printedLeft, operator, printed]));
44973 function printAssignmentExpression(path, options, print) {
44974 const n = path.getValue();
44975 return printAssignment(n.left, path.call(print, "left"), concat$t([" ", n.operator]), n.right, path.call(print, "right"), options);
44978 function printVariableDeclarator(path, options, print) {
44979 const n = path.getValue();
44980 return printAssignment(n.id, path.call(print, "id"), " =", n.init, n.init && path.call(print, "init"), options);
44983 function printAssignmentRight(leftNode, rightNode, printedRight, options) {
44984 if (hasLeadingOwnLineComment$3(options.originalText, rightNode)) {
44985 return indent$n(concat$t([line$i, printedRight]));
44988 const canBreak = isBinaryish$5(rightNode) && !shouldInlineLogicalExpression$1(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish$5(rightNode.test) && !shouldInlineLogicalExpression$1(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || rightNode.type === "ClassExpression" && rightNode.decorators && rightNode.decorators.length || (leftNode.type === "Identifier" || isStringLiteral$3(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral$3(rightNode) || isMemberExpressionChain$1(rightNode)) && // do not put values on a separate line from the key in json
44989 options.parser !== "json" && options.parser !== "json5" || rightNode.type === "SequenceExpression";
44992 return group$k(indent$n(concat$t([line$i, printedRight])));
44995 return concat$t([" ", printedRight]);
44999 printVariableDeclarator,
45000 printAssignmentExpression,
45002 printAssignmentRight
45006 isNextLineEmpty: isNextLineEmpty$7
45012 hardline: hardline$h
45016 classChildNeedsASIProtection: classChildNeedsASIProtection$1,
45017 classPropMayCauseASIProblems: classPropMayCauseASIProblems$1,
45018 getLeftSidePathName: getLeftSidePathName$2,
45019 hasNakedLeftSide: hasNakedLeftSide$2,
45020 isJSXNode: isJSXNode$7,
45021 isLastStatement: isLastStatement$1,
45022 isTheOnlyJSXElementInMarkdown: isTheOnlyJSXElementInMarkdown$1
45028 shouldPrintParamsWithoutParens: shouldPrintParamsWithoutParens$1
45030 /** @typedef {import("../../document").Doc} Doc */
45032 function printStatement({
45037 }, options, print) {
45038 const node = path.getValue(); // Just in case the AST has been modified to contain falsy
45039 // "statements," it's safer simply to skip them.
45041 /* istanbul ignore if */
45045 } // Skip printing EmptyStatement nodes to avoid leaving stray
45046 // semicolons lying around.
45049 if (node.type === "EmptyStatement") {
45053 const printed = print(path);
45054 const text = options.originalText;
45055 const parts = []; // in no-semi mode, prepend statement with semicolon if it might break ASI
45056 // don't prepend the only JSX element in a program with semicolon
45058 if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown$1(options, path) && statementNeedsASIProtection(path, options)) {
45059 if (node.comments && node.comments.some(comment => comment.leading)) {
45060 parts.push(print(path, {
45064 parts.push(";", printed);
45067 parts.push(printed);
45070 if (!options.semi && isClass) {
45071 if (classPropMayCauseASIProblems$1(path)) {
45073 } else if (node.type === "ClassProperty" || node.type === "FieldDefinition") {
45074 const nextChild = bodyNode.body[index + 1];
45076 if (classChildNeedsASIProtection$1(nextChild)) {
45082 if (isNextLineEmpty$7(text, node, locEnd$b) && !isLastStatement$1(path)) {
45083 parts.push(hardline$h);
45086 return concat$u(parts);
45089 function printStatementSequence(path, options, print) {
45090 const bodyNode = path.getNode();
45091 const isClass = bodyNode.type === "ClassBody";
45092 const printed = path.map((statementPath, index) => printStatement({
45097 }, options, print)).filter(Boolean);
45098 return join$d(hardline$h, printed);
45101 function statementNeedsASIProtection(path, options) {
45102 const node = path.getNode();
45104 if (node.type !== "ExpressionStatement") {
45108 return path.call(childPath => expressionNeedsASIProtection(childPath, options), "expression");
45111 function expressionNeedsASIProtection(path, options) {
45112 const node = path.getValue();
45113 const maybeASIProblem = needsParens_1(path, options) || node.type === "ParenthesizedExpression" || node.type === "TypeCastExpression" || node.type === "ArrowFunctionExpression" && !shouldPrintParamsWithoutParens$1(path, options) || node.type === "ArrayExpression" || node.type === "ArrayPattern" || node.type === "UnaryExpression" && node.prefix && (node.operator === "+" || node.operator === "-") || node.type === "TemplateLiteral" || node.type === "TemplateElement" || isJSXNode$7(node) || node.type === "BindExpression" && !node.object || node.type === "RegExpLiteral" || node.type === "Literal" && node.pattern || node.type === "Literal" && node.regex;
45115 if (maybeASIProblem) {
45119 if (!hasNakedLeftSide$2(node)) {
45123 return path.call(childPath => expressionNeedsASIProtection(childPath, options), ...getLeftSidePathName$2(path, node));
45127 printStatementSequence
45131 printDanglingComments: printDanglingComments$9
45134 isNextLineEmpty: isNextLineEmpty$8
45139 hardline: hardline$i,
45144 hasDanglingComments: hasDanglingComments$6
45150 printStatementSequence: printStatementSequence$1
45152 /** @typedef {import("../../document").Doc} Doc */
45154 function printBlock(path, options, print) {
45155 const n = path.getValue();
45157 const semi = options.semi ? ";" : "";
45158 const naked = path.call(bodyPath => {
45159 return printStatementSequence$1(bodyPath, options, print);
45162 if (n.type === "StaticBlock") {
45163 parts.push("static ");
45166 const hasContent = n.body.some(node => node.type !== "EmptyStatement");
45167 const hasDirectives = n.directives && n.directives.length > 0;
45168 const parent = path.getParentNode();
45169 const parentParent = path.getParentNode(1);
45171 if (!hasContent && !hasDirectives && !hasDanglingComments$6(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" || parent.type === "TSDeclareFunction" || n.type === "StaticBlock")) {
45172 return concat$v([...parts, "{}"]);
45175 parts.push("{"); // Babel 6
45177 if (hasDirectives) {
45178 path.each(childPath => {
45179 parts.push(indent$o(concat$v([hardline$i, print(childPath), semi])));
45181 if (isNextLineEmpty$8(options.originalText, childPath.getValue(), locEnd$c)) {
45182 parts.push(hardline$i);
45188 parts.push(indent$o(concat$v([hardline$i, naked])));
45191 parts.push(printDanglingComments$9(path, options));
45192 parts.push(hardline$i, "}");
45193 return concat$v(parts);
45201 hasNewline: hasNewline$6
45207 hardline: hardline$j
45211 isLineComment: isLineComment$2,
45212 isBlockComment: isBlockComment$8
45215 locStart: locStart$7,
45219 function printComment$1(commentPath, options) {
45220 const comment = commentPath.getValue();
45222 if (isLineComment$2(comment)) {
45223 // Supports `//`, `#!`, `<!--`, and `-->`
45224 return options.originalText.slice(locStart$7(comment), locEnd$d(comment)).trimEnd();
45227 if (isBlockComment$8(comment)) {
45228 if (isIndentableBlockComment(comment)) {
45229 const printed = printIndentableBlockComment(comment); // We need to prevent an edge case of a previous trailing comment
45230 // printed as a `lineSuffix` which causes the comments to be
45231 // interleaved. See https://github.com/prettier/prettier/issues/4412
45233 if (comment.trailing && !hasNewline$6(options.originalText, locStart$7(comment), {
45236 return concat$w([hardline$j, printed]);
45242 const commentEnd = locEnd$d(comment);
45243 const isInsideFlowComment = options.originalText.slice(commentEnd - 3, commentEnd) === "*-/";
45244 return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/");
45246 /* istanbul ignore next */
45249 throw new Error("Not a comment: " + JSON.stringify(comment));
45252 function isIndentableBlockComment(comment) {
45253 // If the comment has multiple lines and every line starts with a star
45254 // we can fix the indentation of each line. The stars in the `/*` and
45255 // `*/` delimiters are not included in the comment value, so add them
45257 const lines = `*${comment.value}*`.split("\n");
45258 return lines.length > 1 && lines.every(line => line.trim()[0] === "*");
45261 function printIndentableBlockComment(comment) {
45262 const lines = comment.value.split("\n");
45263 return concat$w(["/*", join$e(hardline$j, lines.map((line, index) => index === 0 ? line.trimEnd() : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()))), "*/"]);
45267 printComment: printComment$1
45270 /** @typedef {import("../document").Doc} Doc */
45272 /** @type {import("assert")} */
45273 // TODO(azz): anything that imports from main shouldn't be in a `language-*` dir.
45277 hasNewline: hasNewline$7,
45278 hasNewlineInRange: hasNewlineInRange$6,
45279 getLast: getLast$9,
45280 printString: printString$2,
45281 printNumber: printNumber$2,
45282 isNextLineEmpty: isNextLineEmpty$9
45289 hardline: hardline$k,
45290 softline: softline$h,
45291 literalline: literalline$3,
45295 conditionalGroup: conditionalGroup$4,
45303 insertPragma: insertPragma$1
45306 printHtmlBinding: printHtmlBinding$1,
45307 isVueEventBindingExpression: isVueEventBindingExpression$1
45310 getFunctionParameters: getFunctionParameters$6,
45311 getCallArguments: getCallArguments$3,
45312 getParentExportDeclaration: getParentExportDeclaration$2,
45313 getTypeScriptMappedTypeModifier: getTypeScriptMappedTypeModifier$1,
45314 hasDanglingComments: hasDanglingComments$7,
45315 hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$3,
45316 hasLeadingOwnLineComment: hasLeadingOwnLineComment$4,
45317 hasNewlineBetweenOrAfterDecorators: hasNewlineBetweenOrAfterDecorators$2,
45318 hasNgSideEffect: hasNgSideEffect$1,
45319 hasPrettierIgnore: hasPrettierIgnore$1,
45320 hasTrailingComment: hasTrailingComment$6,
45321 isExportDeclaration: isExportDeclaration$1,
45322 isFunctionNotation: isFunctionNotation$1,
45323 isGetterOrSetter: isGetterOrSetter$1,
45324 isLiteral: isLiteral$2,
45325 isNgForOf: isNgForOf$1,
45326 isObjectType: isObjectType$3,
45327 isObjectTypePropertyAFunction: isObjectTypePropertyAFunction$2,
45328 isTheOnlyJSXElementInMarkdown: isTheOnlyJSXElementInMarkdown$2,
45329 isTSXFile: isTSXFile$1,
45330 isBlockComment: isBlockComment$9,
45331 needsHardlineAfterDanglingComment: needsHardlineAfterDanglingComment$2,
45332 rawText: rawText$3,
45333 shouldPrintComma: shouldPrintComma$8
45336 locStart: locStart$8,
45340 printOptionalToken: printOptionalToken$6,
45341 printBindExpressionCallee: printBindExpressionCallee$2,
45342 printTypeScriptModifiers: printTypeScriptModifiers$2,
45343 printDecorators: printDecorators$2,
45344 printFlowDeclaration: printFlowDeclaration$1,
45345 adjustClause: adjustClause$1
45348 printImportDeclaration: printImportDeclaration$1,
45349 printExportDeclaration: printExportDeclaration$1,
45350 printExportAllDeclaration: printExportAllDeclaration$1,
45351 printModuleSpecifier: printModuleSpecifier$1
45354 printFunctionParameters: printFunctionParameters$2
45355 } = functionParameters;
45357 printTemplateLiteral: printTemplateLiteral$1
45358 } = templateLiteral;
45360 printArray: printArray$1,
45361 printArrayItems: printArrayItems$1
45364 printObject: printObject$1
45367 printTypeAnnotation: printTypeAnnotation$3,
45368 shouldHugType: shouldHugType$3
45369 } = typeAnnotation;
45371 printJsxElement: printJsxElement$1,
45372 printJsxAttribute: printJsxAttribute$1,
45373 printJsxOpeningElement: printJsxOpeningElement$1,
45374 printJsxClosingElement: printJsxClosingElement$1,
45375 printJsxOpeningClosingFragment: printJsxOpeningClosingFragment$1,
45376 printJsxExpressionContainer: printJsxExpressionContainer$1,
45377 printJsxEmptyExpression: printJsxEmptyExpression$1,
45378 printJsxSpreadAttribute: printJsxSpreadAttribute$1,
45379 printJsxSpreadChild
45382 printClass: printClass$1,
45383 printClassMethod: printClassMethod$1
45386 printTypeParameters: printTypeParameters$1
45387 } = typeParameters;
45389 printPropertyKey: printPropertyKey$2
45392 printFunctionDeclaration: printFunctionDeclaration$1,
45393 printArrowFunctionExpression: printArrowFunctionExpression$1,
45394 printMethod: printMethod$2,
45395 printReturnAndThrowArgument: printReturnAndThrowArgument$1
45398 printCallExpression: printCallExpression$1
45399 } = callExpression;
45401 printInterface: printInterface$1
45404 printVariableDeclarator: printVariableDeclarator$1,
45405 printAssignmentExpression: printAssignmentExpression$1,
45406 printAssignment: printAssignment$1,
45407 printAssignmentRight: printAssignmentRight$1
45410 printBinaryishExpression: printBinaryishExpression$1
45413 printStatementSequence: printStatementSequence$2
45416 printMemberExpression: printMemberExpression$1
45419 printBlock: printBlock$1
45422 printComment: printComment$2
45425 function genericPrint(path, options, printPath, args) {
45426 const node = path.getValue();
45427 let needsParens = false;
45428 const linesWithoutParens = printPathNoParens(path, options, printPath, args);
45430 if (!node || isEmpty$2(linesWithoutParens)) {
45431 return linesWithoutParens;
45434 const parentExportDecl = getParentExportDeclaration$2(path);
45435 const decorators = [];
45437 if (node.type === "ClassMethod" || node.type === "ClassPrivateMethod" || node.type === "ClassProperty" || node.type === "FieldDefinition" || 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
45438 // was written before the export, the export will be responsible
45439 // for printing the decorators.
45440 !(parentExportDecl && locStart$8(parentExportDecl, {
45441 ignoreDecorators: true
45442 }) > locStart$8(node.decorators[0]))) {
45443 const shouldBreak = node.type === "ClassExpression" || node.type === "ClassDeclaration" || hasNewlineBetweenOrAfterDecorators$2(node, options);
45444 const separator = shouldBreak ? hardline$k : line$j;
45445 path.each(decoratorPath => {
45446 let decorator = decoratorPath.getValue();
45448 if (decorator.expression) {
45449 decorator = decorator.expression;
45451 decorator = decorator.callee;
45454 decorators.push(printPath(decoratorPath), separator);
45457 if (parentExportDecl) {
45458 decorators.unshift(hardline$k);
45460 } 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,
45461 // otherwise they are printed by the node.declaration
45463 ignoreDecorators: true
45464 }) > locStart$8(node.declaration.decorators[0])) {
45465 // Export declarations are responsible for printing any decorators
45466 // that logically apply to node.declaration.
45467 path.each(decoratorPath => {
45468 const decorator = decoratorPath.getValue();
45469 const prefix = decorator.type === "Decorator" ? "" : "@";
45470 decorators.push(prefix, printPath(decoratorPath), hardline$k);
45471 }, "declaration", "decorators");
45473 // Nodes with decorators can't have parentheses, so we can avoid
45474 // computing pathNeedsParens() except in this case.
45475 needsParens = needsParens_1(path, options);
45481 parts.unshift("(");
45484 parts.push(linesWithoutParens);
45487 const node = path.getValue();
45489 if (hasFlowShorthandAnnotationComment$3(node)) {
45491 parts.push(node.trailingComments[0].value.trimStart());
45493 node.trailingComments[0].printed = true;
45499 if (decorators.length > 0) {
45500 return group$l(concat$x(decorators.concat(parts)));
45503 return concat$x(parts);
45506 function printPathNoParens(path, options, print, args) {
45507 const n = path.getValue();
45508 const semi = options.semi ? ";" : "";
45514 if (typeof n === "string") {
45518 const htmlBinding = printHtmlBinding$1(path, options, print);
45521 return htmlBinding;
45523 /** @type{Doc[]} */
45529 case "JsExpressionRoot":
45530 return path.call(print, "node");
45533 return concat$x([path.call(print, "node"), hardline$k]);
45536 // Print @babel/parser's InterpreterDirective here so that
45537 // leading comments on the `Program` node get printed after the hashbang.
45538 if (n.program && n.program.interpreter) {
45539 parts.push(path.call(programPath => programPath.call(print, "interpreter"), "program"));
45542 parts.push(path.call(print, "program"));
45543 return concat$x(parts);
45547 const hasContents = !n.body.every(({
45549 }) => type === "EmptyStatement") || n.comments; // Babel 6
45551 if (n.directives) {
45552 const directivesCount = n.directives.length;
45553 path.each((childPath, index) => {
45554 parts.push(print(childPath), semi, hardline$k);
45556 if ((index < directivesCount - 1 || hasContents) && isNextLineEmpty$9(options.originalText, childPath.getValue(), locEnd$e)) {
45557 parts.push(hardline$k);
45562 parts.push(path.call(bodyPath => {
45563 return printStatementSequence$2(bodyPath, options, print);
45565 parts.push(comments.printDanglingComments(path, options,
45567 true)); // Only force a trailing newline if there were any contents.
45570 parts.push(hardline$k);
45573 return concat$x(parts);
45575 // Babel extension.
45577 case "EmptyStatement":
45580 case "ExpressionStatement":
45581 // Detect Flow and TypeScript directives
45583 return concat$x([nodeStr(n.expression, options, true), semi]);
45586 if (options.parser === "__vue_event_binding") {
45587 const parent = path.getParentNode();
45589 if (parent.type === "Program" && parent.body.length === 1 && parent.body[0] === n) {
45590 return concat$x([path.call(print, "expression"), isVueEventBindingExpression$1(n.expression) ? ";" : ""]);
45592 } // Do not append semicolon after the only JSX element in a program
45595 return concat$x([path.call(print, "expression"), isTheOnlyJSXElementInMarkdown$2(options, path) ? "" : semi]);
45596 // Babel non-standard node. Used for Closure-style type casts. See postprocess.js.
45598 case "ParenthesizedExpression":
45600 const shouldHug = !n.expression.comments;
45603 return concat$x(["(", path.call(print, "expression"), ")"]);
45606 return group$l(concat$x(["(", indent$p(concat$x([softline$h, path.call(print, "expression")])), softline$h, ")"]));
45609 case "AssignmentExpression":
45610 return printAssignmentExpression$1(path, options, print);
45612 case "VariableDeclarator":
45613 return printVariableDeclarator$1(path, options, print);
45615 case "BinaryExpression":
45616 case "LogicalExpression":
45617 case "NGPipeExpression":
45618 return printBinaryishExpression$1(path, options, print);
45620 case "AssignmentPattern":
45621 return concat$x([path.call(print, "left"), " = ", path.call(print, "right")]);
45623 case "TSTypeAssertion":
45625 const shouldBreakAfterCast = !(n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression");
45626 const castGroup = group$l(concat$x(["<", indent$p(concat$x([softline$h, path.call(print, "typeAnnotation")])), softline$h, ">"]));
45627 const exprContents = concat$x([ifBreak$d("("), indent$p(concat$x([softline$h, path.call(print, "expression")])), softline$h, ifBreak$d(")")]);
45629 if (shouldBreakAfterCast) {
45630 return conditionalGroup$4([concat$x([castGroup, path.call(print, "expression")]), concat$x([castGroup, group$l(exprContents, {
45632 })]), concat$x([castGroup, path.call(print, "expression")])]);
45635 return group$l(concat$x([castGroup, path.call(print, "expression")]));
45638 case "OptionalMemberExpression":
45639 case "MemberExpression":
45641 return printMemberExpression$1(path, options, print);
45644 case "MetaProperty":
45645 return concat$x([path.call(print, "meta"), ".", path.call(print, "property")]);
45647 case "BindExpression":
45649 parts.push(path.call(print, "object"));
45652 parts.push(group$l(indent$p(concat$x([softline$h, printBindExpressionCallee$2(path, options, print)]))));
45653 return concat$x(parts);
45657 return concat$x([n.name, printOptionalToken$6(path), printTypeAnnotation$3(path, options, print)]);
45660 case "V8IntrinsicIdentifier":
45661 return concat$x(["%", n.name]);
45663 case "SpreadElement":
45664 case "SpreadElementPattern":
45665 case "SpreadProperty":
45666 case "SpreadPropertyPattern":
45667 case "RestElement":
45668 case "ObjectTypeSpreadProperty":
45669 return concat$x(["...", path.call(print, "argument"), printTypeAnnotation$3(path, options, print)]);
45671 case "FunctionDeclaration":
45672 case "FunctionExpression":
45673 parts.push(printFunctionDeclaration$1(path, print, options, args && args.expandLastArg && getCallArguments$3(path.getParentNode()).length > 1));
45679 return concat$x(parts);
45681 case "ArrowFunctionExpression":
45682 return printArrowFunctionExpression$1(path, options, print, args);
45684 case "YieldExpression":
45685 parts.push("yield");
45692 parts.push(" ", path.call(print, "argument"));
45695 return concat$x(parts);
45697 case "AwaitExpression":
45699 parts.push("await");
45702 parts.push(" ", path.call(print, "argument"));
45705 const parent = path.getParentNode();
45707 if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && parent.object === n) {
45708 return group$l(concat$x([indent$p(concat$x([softline$h, concat$x(parts)])), softline$h]));
45711 return concat$x(parts);
45714 case "TSExportAssignment":
45715 return concat$x(["export = ", path.call(print, "expression"), semi]);
45717 case "ExportDefaultDeclaration":
45718 case "ExportNamedDeclaration":
45719 case "DeclareExportDeclaration":
45720 return printExportDeclaration$1(path, options, print);
45722 case "ExportAllDeclaration":
45723 case "DeclareExportAllDeclaration":
45724 return printExportAllDeclaration$1(path, options, print);
45726 case "ImportDeclaration":
45727 return printImportDeclaration$1(path, options, print);
45729 case "ImportSpecifier":
45730 case "ExportSpecifier":
45731 case "ImportNamespaceSpecifier":
45732 case "ExportNamespaceSpecifier":
45733 case "ImportDefaultSpecifier":
45734 case "ExportDefaultSpecifier":
45735 return printModuleSpecifier$1(path, options, print);
45737 case "ImportAttribute":
45738 return concat$x([path.call(print, "key"), ": ", path.call(print, "value")]);
45743 case "TSModuleBlock":
45744 case "BlockStatement":
45745 case "StaticBlock":
45746 return printBlock$1(path, options, print);
45748 case "ThrowStatement":
45749 case "ReturnStatement":
45750 return concat$x([n.type === "ReturnStatement" ? "return" : "throw", printReturnAndThrowArgument$1(path, options, print)]);
45752 case "NewExpression":
45753 case "ImportExpression":
45754 case "OptionalCallExpression":
45755 case "CallExpression":
45756 return printCallExpression$1(path, options, print);
45758 case "ObjectTypeInternalSlot":
45759 return concat$x([n.static ? "static " : "", "[[", path.call(print, "id"), "]]", printOptionalToken$6(path), n.method ? "" : ": ", path.call(print, "value")]);
45761 case "ObjectExpression":
45762 case "ObjectPattern":
45763 case "ObjectTypeAnnotation":
45764 case "TSInterfaceBody":
45765 case "TSTypeLiteral":
45766 case "RecordExpression":
45767 return printObject$1(path, options, print);
45770 case "ObjectProperty": // Non-standard AST node type.
45773 if (n.method || n.kind === "get" || n.kind === "set") {
45774 return printMethod$2(path, options, print);
45778 parts.push(path.call(print, "value"));
45780 parts.push(printAssignment$1(n.key, printPropertyKey$2(path, options, print), ":", n.value, path.call(print, "value"), options));
45783 return concat$x(parts);
45786 case "ClassMethod":
45787 case "ClassPrivateMethod":
45788 case "MethodDefinition":
45789 case "TSAbstractMethodDefinition":
45790 case "TSDeclareMethod":
45791 return printClassMethod$1(path, options, print);
45793 case "ObjectMethod":
45794 return printMethod$2(path, options, print);
45797 return concat$x(["@", path.call(print, "expression"), path.call(print, "callee")]);
45799 case "ArrayExpression":
45800 case "ArrayPattern":
45801 case "TupleExpression":
45802 return printArray$1(path, options, print);
45804 case "SequenceExpression":
45806 const parent = path.getParentNode(0);
45808 if (parent.type === "ExpressionStatement" || parent.type === "ForStatement") {
45809 // For ExpressionStatements and for-loop heads, which are among
45810 // the few places a SequenceExpression appears unparenthesized, we want
45811 // to indent expressions after the first.
45814 if (p.getName() === 0) {
45815 parts.push(print(p));
45817 parts.push(",", indent$p(concat$x([line$j, print(p)])));
45820 return group$l(concat$x(parts));
45823 return group$l(concat$x([join$f(concat$x([",", line$j]), path.map(print, "expressions"))]));
45826 case "ThisExpression":
45832 case "NullLiteral":
45833 // Babel 6 Literal split
45836 case "RegExpLiteral":
45837 // Babel 6 Literal split
45838 return printRegex(n);
45840 case "NumericLiteral":
45841 // Babel 6 Literal split
45842 return printNumber$2(n.extra.raw);
45844 case "DecimalLiteral":
45845 return printNumber$2(n.value) + "m";
45847 case "BigIntLiteral":
45848 // babel: n.extra.raw, flow: n.bigint
45849 return (n.bigint || n.extra.raw).toLowerCase();
45851 case "BooleanLiteral": // Babel 6 Literal split
45853 case "StringLiteral": // Babel 6 Literal split
45857 return printRegex(n.regex);
45862 return n.raw.toLowerCase();
45865 if (typeof n.value === "number") {
45866 return printNumber$2(n.raw);
45869 if (typeof n.value !== "string") {
45870 return "" + n.value;
45873 return nodeStr(n, options);
45876 return path.call(print, "value");
45879 case "DirectiveLiteral":
45880 return nodeStr(n, options);
45882 case "UnaryExpression":
45883 parts.push(n.operator);
45885 if (/[a-z]$/.test(n.operator)) {
45889 if (n.argument.comments && n.argument.comments.length > 0) {
45890 parts.push(group$l(concat$x(["(", indent$p(concat$x([softline$h, path.call(print, "argument")])), softline$h, ")"])));
45892 parts.push(path.call(print, "argument"));
45895 return concat$x(parts);
45897 case "UpdateExpression":
45898 parts.push(path.call(print, "argument"), n.operator);
45904 return concat$x(parts);
45906 case "ConditionalExpression":
45907 return ternary(path, options, print, {
45908 beforeParts: () => [path.call(print, "test")],
45909 afterParts: breakClosingParen => [breakClosingParen ? softline$h : ""],
45910 shouldCheckJsx: true,
45911 conditionalNodeType: "ConditionalExpression",
45912 consequentNodePropertyName: "consequent",
45913 alternateNodePropertyName: "alternate",
45914 testNodePropertyNames: ["test"]
45917 case "VariableDeclaration":
45919 const printed = path.map(childPath => {
45920 return print(childPath);
45921 }, "declarations"); // We generally want to terminate all variable declarations with a
45922 // semicolon, except when they in the () part of for loops.
45924 const parentNode = path.getParentNode();
45925 const isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement";
45926 const hasValue = n.declarations.some(decl => decl.init);
45929 if (printed.length === 1 && !n.declarations[0].comments) {
45930 firstVariable = printed[0];
45931 } else if (printed.length > 0) {
45932 // Indent first var to comply with eslint one-var rule
45933 firstVariable = indent$p(printed[0]);
45936 parts = [n.declare ? "declare " : "", n.kind, firstVariable ? concat$x([" ", firstVariable]) : "", indent$p(concat$x(printed.slice(1).map(p => concat$x([",", hasValue && !isParentForLoop ? hardline$k : line$j, p]))))];
45938 if (!(isParentForLoop && parentNode.body !== n)) {
45942 return group$l(concat$x(parts));
45945 case "TSTypeAliasDeclaration":
45948 parts.push("declare ");
45951 const printed = printAssignmentRight$1(n.id, n.typeAnnotation, n.typeAnnotation && path.call(print, "typeAnnotation"), options);
45952 parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi);
45953 return group$l(concat$x(parts));
45956 case "WithStatement":
45957 return group$l(concat$x(["with (", path.call(print, "object"), ")", adjustClause$1(n.body, path.call(print, "body"))]));
45959 case "IfStatement":
45961 const con = adjustClause$1(n.consequent, path.call(print, "consequent"));
45962 const opening = group$l(concat$x(["if (", group$l(concat$x([indent$p(concat$x([softline$h, path.call(print, "test")])), softline$h])), ")", con]));
45963 parts.push(opening);
45966 const commentOnOwnLine = hasTrailingComment$6(n.consequent) && n.consequent.comments.some(comment => comment.trailing && !isBlockComment$9(comment)) || needsHardlineAfterDanglingComment$2(n);
45967 const elseOnSameLine = n.consequent.type === "BlockStatement" && !commentOnOwnLine;
45968 parts.push(elseOnSameLine ? " " : hardline$k);
45970 if (hasDanglingComments$7(n)) {
45971 parts.push(comments.printDanglingComments(path, options, true), commentOnOwnLine ? hardline$k : " ");
45974 parts.push("else", group$l(adjustClause$1(n.alternate, path.call(print, "alternate"), n.alternate.type === "IfStatement")));
45977 return concat$x(parts);
45980 case "ForStatement":
45982 const body = adjustClause$1(n.body, path.call(print, "body")); // We want to keep dangling comments above the loop to stay consistent.
45983 // Any comment positioned between the for statement and the parentheses
45984 // is going to be printed before the statement.
45986 const dangling = comments.printDanglingComments(path, options,
45989 const printedComments = dangling ? concat$x([dangling, softline$h]) : "";
45991 if (!n.init && !n.test && !n.update) {
45992 return concat$x([printedComments, group$l(concat$x(["for (;;)", body]))]);
45995 return concat$x([printedComments, group$l(concat$x(["for (", group$l(concat$x([indent$p(concat$x([softline$h, path.call(print, "init"), ";", line$j, path.call(print, "test"), ";", line$j, path.call(print, "update")])), softline$h])), ")", body]))]);
45998 case "WhileStatement":
45999 return group$l(concat$x(["while (", group$l(concat$x([indent$p(concat$x([softline$h, path.call(print, "test")])), softline$h])), ")", adjustClause$1(n.body, path.call(print, "body"))]));
46001 case "ForInStatement":
46002 return group$l(concat$x(["for (", path.call(print, "left"), " in ", path.call(print, "right"), ")", adjustClause$1(n.body, path.call(print, "body"))]));
46004 case "ForOfStatement":
46005 return group$l(concat$x(["for", n.await ? " await" : "", " (", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause$1(n.body, path.call(print, "body"))]));
46007 case "DoWhileStatement":
46009 const clause = adjustClause$1(n.body, path.call(print, "body"));
46010 const doBody = group$l(concat$x(["do", clause]));
46013 if (n.body.type === "BlockStatement") {
46016 parts.push(hardline$k);
46019 parts.push("while (");
46020 parts.push(group$l(concat$x([indent$p(concat$x([softline$h, path.call(print, "test")])), softline$h])), ")", semi);
46021 return concat$x(parts);
46024 case "DoExpression":
46025 return concat$x(["do ", path.call(print, "body")]);
46027 case "BreakStatement":
46028 parts.push("break");
46031 parts.push(" ", path.call(print, "label"));
46035 return concat$x(parts);
46037 case "ContinueStatement":
46038 parts.push("continue");
46041 parts.push(" ", path.call(print, "label"));
46045 return concat$x(parts);
46047 case "LabeledStatement":
46048 if (n.body.type === "EmptyStatement") {
46049 return concat$x([path.call(print, "label"), ":;"]);
46052 return concat$x([path.call(print, "label"), ": ", path.call(print, "body")]);
46054 case "TryStatement":
46055 return concat$x(["try ", path.call(print, "block"), n.handler ? concat$x([" ", path.call(print, "handler")]) : "", n.finalizer ? concat$x([" finally ", path.call(print, "finalizer")]) : ""]);
46057 case "CatchClause":
46059 const hasComments = n.param.comments && n.param.comments.some(comment => !isBlockComment$9(comment) || comment.leading && hasNewline$7(options.originalText, locEnd$e(comment)) || comment.trailing && hasNewline$7(options.originalText, locStart$8(comment), {
46062 const param = path.call(print, "param");
46063 return concat$x(["catch ", hasComments ? concat$x(["(", indent$p(concat$x([softline$h, param])), softline$h, ") "]) : concat$x(["(", param, ") "]), path.call(print, "body")]);
46066 return concat$x(["catch ", path.call(print, "body")]);
46067 // Note: ignoring n.lexical because it has no printing consequences.
46069 case "SwitchStatement":
46070 return concat$x([group$l(concat$x(["switch (", indent$p(concat$x([softline$h, path.call(print, "discriminant")])), softline$h, ")"])), " {", n.cases.length > 0 ? indent$p(concat$x([hardline$k, join$f(hardline$k, path.map(casePath => {
46071 const caseNode = casePath.getValue();
46072 return concat$x([casePath.call(print), n.cases.indexOf(caseNode) !== n.cases.length - 1 && isNextLineEmpty$9(options.originalText, caseNode, locEnd$e) ? hardline$k : ""]);
46073 }, "cases"))])) : "", hardline$k, "}"]);
46078 parts.push("case ", path.call(print, "test"), ":");
46080 parts.push("default:");
46083 const consequent = n.consequent.filter(node => node.type !== "EmptyStatement");
46085 if (consequent.length > 0) {
46086 const cons = path.call(consequentPath => {
46087 return printStatementSequence$2(consequentPath, options, print);
46089 parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? concat$x([" ", cons]) : indent$p(concat$x([hardline$k, cons])));
46092 return concat$x(parts);
46094 // JSX extensions below.
46096 case "DebuggerStatement":
46097 return concat$x(["debugger", semi]);
46099 case "JSXAttribute":
46100 return printJsxAttribute$1(path, options, print);
46102 case "JSXIdentifier":
46103 return "" + n.name;
46105 case "JSXNamespacedName":
46106 return join$f(":", [path.call(print, "namespace"), path.call(print, "name")]);
46108 case "JSXMemberExpression":
46109 return join$f(".", [path.call(print, "object"), path.call(print, "property")]);
46111 case "TSQualifiedName":
46112 return join$f(".", [path.call(print, "left"), path.call(print, "right")]);
46114 case "JSXSpreadAttribute":
46115 return printJsxSpreadAttribute$1(path, options, print);
46117 case "JSXSpreadChild":
46118 return printJsxSpreadChild(path, options, print);
46120 case "JSXExpressionContainer":
46121 return printJsxExpressionContainer$1(path, options, print);
46123 case "JSXFragment":
46125 return printJsxElement$1(path, options, print);
46127 case "JSXOpeningElement":
46128 return printJsxOpeningElement$1(path, options, print);
46130 case "JSXClosingElement":
46131 return printJsxClosingElement$1(path, options, print);
46133 case "JSXOpeningFragment":
46134 case "JSXClosingFragment":
46135 return printJsxOpeningClosingFragment$1(path, options
46140 /* istanbul ignore next */
46141 throw new Error("JSXTest should be handled by JSXElement");
46143 case "JSXEmptyExpression":
46144 return printJsxEmptyExpression$1(path, options
46149 if (!n.comments && n.body.length === 0) {
46153 return concat$x(["{", n.body.length > 0 ? indent$p(concat$x([hardline$k, path.call(bodyPath => {
46154 return printStatementSequence$2(bodyPath, options, print);
46155 }, "body")])) : comments.printDanglingComments(path, options), hardline$k, "}"]);
46157 case "ClassProperty":
46158 case "FieldDefinition":
46159 case "TSAbstractClassProperty":
46160 case "ClassPrivateProperty":
46162 if (n.decorators && n.decorators.length !== 0) {
46163 parts.push(printDecorators$2(path, options, print));
46166 if (n.accessibility) {
46167 parts.push(n.accessibility + " ");
46171 parts.push("declare ");
46175 parts.push("static ");
46178 if (n.type === "TSAbstractClassProperty" || n.abstract) {
46179 parts.push("abstract ");
46183 parts.push("readonly ");
46187 parts.push(path.call(print, "variance"));
46190 parts.push(printPropertyKey$2(path, options, print), printOptionalToken$6(path), printTypeAnnotation$3(path, options, print));
46193 parts.push(" =", printAssignmentRight$1(n.key, n.value, path.call(print, "value"), options));
46197 return group$l(concat$x(parts));
46200 case "ClassDeclaration":
46201 case "ClassExpression":
46203 parts.push("declare ");
46206 parts.push(printClass$1(path, options, print));
46207 return concat$x(parts);
46209 case "TSInterfaceHeritage":
46210 case "TSExpressionWithTypeArguments":
46212 parts.push(path.call(print, "expression"));
46214 if (n.typeParameters) {
46215 parts.push(path.call(print, "typeParameters"));
46218 return concat$x(parts);
46220 case "TemplateElement":
46221 return join$f(literalline$3, n.value.raw.split(/\r?\n/g));
46223 case "TSTemplateLiteralType":
46224 case "TemplateLiteral":
46226 return printTemplateLiteral$1(path, print, options);
46229 case "TaggedTemplateExpression":
46230 return concat$x([path.call(print, "tag"), path.call(print, "typeParameters"), path.call(print, "quasi")]);
46231 // These types are unprintable because they serve as abstract
46232 // supertypes for other (printable) types.
46236 case "SourceLocation":
46242 case "Declaration":
46244 case "NamedSpecifier":
46246 case "MemberTypeAnnotation": // Flow
46249 /* istanbul ignore next */
46250 throw new Error("unprintable type: " + JSON.stringify(n.type));
46251 // Type Annotations for Facebook Flow, typically stripped out or
46252 // transformed away before printing.
46254 case "TypeAnnotation":
46255 case "TSTypeAnnotation":
46256 if (n.typeAnnotation) {
46257 return path.call(print, "typeAnnotation");
46259 /* istanbul ignore next */
46264 case "TSNamedTupleMember":
46265 return concat$x([path.call(print, "label"), n.optional ? "?" : "", ": ", path.call(print, "elementType")]);
46267 case "TSTupleType":
46268 case "TupleTypeAnnotation":
46270 const typesField = n.type === "TSTupleType" ? "elementTypes" : "types";
46271 const hasRest = n[typesField].length > 0 && getLast$9(n[typesField]).type === "TSRestType";
46272 return group$l(concat$x(["[", indent$p(concat$x([softline$h, printArrayItems$1(path, options, typesField, print)])), ifBreak$d(shouldPrintComma$8(options, "all") && !hasRest ? "," : ""), comments.printDanglingComments(path, options,
46274 true), softline$h, "]"]));
46277 case "ExistsTypeAnnotation":
46280 case "EmptyTypeAnnotation":
46283 case "MixedTypeAnnotation":
46286 case "ArrayTypeAnnotation":
46287 return concat$x([path.call(print, "elementType"), "[]"]);
46289 case "BooleanLiteralTypeAnnotation":
46290 return "" + n.value;
46292 case "DeclareClass":
46293 return printFlowDeclaration$1(path, printClass$1(path, options, print));
46295 case "TSDeclareFunction":
46296 // For TypeScript the TSDeclareFunction node shares the AST
46297 // structure with FunctionDeclaration
46298 return concat$x([n.declare ? "declare " : "", printFunctionDeclaration$1(path, print, options), semi]);
46300 case "DeclareFunction":
46301 return printFlowDeclaration$1(path, concat$x(["function ", path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), semi]));
46303 case "DeclareModule":
46304 return printFlowDeclaration$1(path, concat$x(["module ", path.call(print, "id"), " ", path.call(print, "body")]));
46306 case "DeclareModuleExports":
46307 return printFlowDeclaration$1(path, concat$x(["module.exports", ": ", path.call(print, "typeAnnotation"), semi]));
46309 case "DeclareVariable":
46310 return printFlowDeclaration$1(path, concat$x(["var ", path.call(print, "id"), semi]));
46312 case "DeclareOpaqueType":
46315 parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters"));
46318 parts.push(": ", path.call(print, "supertype"));
46322 parts.push(" = ", path.call(print, "impltype"));
46327 if (n.type === "DeclareOpaqueType") {
46328 return printFlowDeclaration$1(path, concat$x(parts));
46331 return concat$x(parts);
46334 case "EnumDeclaration":
46335 return concat$x(["enum ", path.call(print, "id"), " ", path.call(print, "body")]);
46337 case "EnumBooleanBody":
46338 case "EnumNumberBody":
46339 case "EnumStringBody":
46340 case "EnumSymbolBody":
46342 if (n.type === "EnumSymbolBody" || n.explicitType) {
46346 case "EnumBooleanBody":
46350 case "EnumNumberBody":
46354 case "EnumStringBody":
46358 case "EnumSymbolBody":
46363 parts.push("of ", type, " ");
46366 if (n.members.length === 0 && !n.hasUnknownMembers) {
46367 parts.push(group$l(concat$x(["{", comments.printDanglingComments(path, options), softline$h, "}"])));
46369 const members = n.members.length ? [hardline$k, printArrayItems$1(path, options, "members", print), n.hasUnknownMembers || shouldPrintComma$8(options) ? "," : ""] : [];
46370 parts.push(group$l(concat$x(["{", indent$p(concat$x([...members, ...(n.hasUnknownMembers ? [hardline$k, "..."] : [])])), comments.printDanglingComments(path, options,
46372 true), hardline$k, "}"])));
46375 return concat$x(parts);
46378 case "EnumBooleanMember":
46379 case "EnumNumberMember":
46380 case "EnumStringMember":
46381 return concat$x([path.call(print, "id"), " = ", typeof n.init === "object" ? path.call(print, "init") : String(n.init)]);
46383 case "EnumDefaultedMember":
46384 return path.call(print, "id");
46386 case "FunctionTypeAnnotation":
46387 case "TSFunctionType":
46389 // FunctionTypeAnnotation is ambiguous:
46390 // declare function foo(a: B): void; OR
46391 // var A: (a: B) => void;
46392 const parent = path.getParentNode(0);
46393 const parentParent = path.getParentNode(1);
46394 const parentParentParent = path.getParentNode(2);
46395 let isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !((parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeInternalSlot") && !parent.variance && !parent.optional && locStart$8(parent) === locStart$8(n) || parent.type === "ObjectTypeCallProperty" || parentParentParent && parentParentParent.type === "DeclareFunction");
46396 let needsColon = isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation"); // Sadly we can't put it inside of FastPath::needsColon because we are
46397 // printing ":" as part of the expression and it would put parenthesis
46400 const needsParens = needsColon && isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation") && parentParent.type === "ArrowFunctionExpression";
46402 if (isObjectTypePropertyAFunction$2(parent)) {
46403 isArrowFunctionTypeAnnotation = true;
46411 parts.push(printFunctionParameters$2(path, print, options,
46414 /* printTypeParams */
46415 true)); // The returnType is not wrapped in a TypeAnnotation, so the colon
46416 // needs to be added separately.
46418 if (n.returnType || n.predicate || n.typeAnnotation) {
46419 parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType"), path.call(print, "predicate"), path.call(print, "typeAnnotation"));
46426 return group$l(concat$x(parts));
46430 return concat$x(["...", path.call(print, "typeAnnotation")]);
46432 case "TSOptionalType":
46433 return concat$x([path.call(print, "typeAnnotation"), "?"]);
46435 case "FunctionTypeParam":
46437 const name = n.name ? path.call(print, "name") : path.getParentNode().this === n ? "this" : "";
46438 return concat$x([name, printOptionalToken$6(path), name ? ": " : "", path.call(print, "typeAnnotation")]);
46441 case "DeclareInterface":
46442 case "InterfaceDeclaration":
46443 case "InterfaceTypeAnnotation":
46444 case "TSInterfaceDeclaration":
46445 return printInterface$1(path, options, print);
46447 case "ClassImplements":
46448 case "InterfaceExtends":
46449 return concat$x([path.call(print, "id"), path.call(print, "typeParameters")]);
46451 case "TSClassImplements":
46452 return concat$x([path.call(print, "expression"), path.call(print, "typeParameters")]);
46454 case "TSIntersectionType":
46455 case "IntersectionTypeAnnotation":
46457 const types = path.map(print, "types");
46459 let wasIndented = false;
46461 for (let i = 0; i < types.length; ++i) {
46463 result.push(types[i]);
46464 } else if (isObjectType$3(n.types[i - 1]) && isObjectType$3(n.types[i])) {
46465 // If both are objects, don't indent
46466 result.push(concat$x([" & ", wasIndented ? indent$p(types[i]) : types[i]]));
46467 } else if (!isObjectType$3(n.types[i - 1]) && !isObjectType$3(n.types[i])) {
46468 // If no object is involved, go to the next line if it breaks
46469 result.push(indent$p(concat$x([" &", line$j, types[i]])));
46471 // If you go from object to non-object or vis-versa, then inline it
46473 wasIndented = true;
46476 result.push(" & ", i > 1 ? indent$p(types[i]) : types[i]);
46480 return group$l(concat$x(result));
46483 case "TSUnionType":
46484 case "UnionTypeAnnotation":
46486 // single-line variation
46488 // multi-line variation
46492 const parent = path.getParentNode(); // If there's a leading comment, the parent is doing the indentation
46494 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 && path.getParentNode(1).this !== parent) && !((parent.type === "TypeAlias" || parent.type === "VariableDeclarator" || parent.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment$4(options.originalText, n)); // {
46497 // should be inlined and not be printed in the multi-line variant
46499 const shouldHug = shouldHugType$3(n); // We want to align the children but without its comment, so it looks like
46504 const printed = path.map(typePath => {
46505 let printedType = typePath.call(print);
46508 printedType = align$4(2, printedType);
46511 return comments.printComments(typePath, () => printedType, options);
46515 return join$f(" | ", printed);
46518 const shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment$4(options.originalText, n);
46519 const code = concat$x([ifBreak$d(concat$x([shouldAddStartLine ? line$j : "", "| "])), join$f(concat$x([line$j, "| "]), printed)]);
46521 if (needsParens_1(path, options)) {
46522 return group$l(concat$x([indent$p(code), softline$h]));
46525 if (parent.type === "TupleTypeAnnotation" && parent.types.length > 1 || parent.type === "TSTupleType" && parent.elementTypes.length > 1) {
46526 return group$l(concat$x([indent$p(concat$x([ifBreak$d(concat$x(["(", softline$h])), code])), softline$h, ifBreak$d(")")]));
46529 return group$l(shouldIndent ? indent$p(code) : code);
46532 case "NullableTypeAnnotation":
46533 return concat$x(["?", path.call(print, "typeAnnotation")]);
46540 assert__default['default'].ok(kind === "plus" || kind === "minus");
46541 return kind === "plus" ? "+" : "-";
46544 case "ObjectTypeCallProperty":
46546 parts.push("static ");
46549 parts.push(path.call(print, "value"));
46550 return concat$x(parts);
46552 case "ObjectTypeIndexer":
46554 return concat$x([n.variance ? path.call(print, "variance") : "", "[", path.call(print, "id"), n.id ? ": " : "", path.call(print, "key"), "]: ", path.call(print, "value")]);
46557 case "ObjectTypeProperty":
46562 modifier = "proto ";
46563 } else if (n.static) {
46564 modifier = "static ";
46567 return concat$x([modifier, isGetterOrSetter$1(n) ? n.kind + " " : "", n.variance ? path.call(print, "variance") : "", printPropertyKey$2(path, options, print), printOptionalToken$6(path), isFunctionNotation$1(n) ? "" : ": ", path.call(print, "value")]);
46570 case "QualifiedTypeIdentifier":
46571 return concat$x([path.call(print, "qualification"), ".", path.call(print, "id")]);
46573 case "StringLiteralTypeAnnotation":
46574 return nodeStr(n, options);
46576 case "NumberLiteralTypeAnnotation":
46577 assert__default['default'].strictEqual(typeof n.value, "number");
46580 case "BigIntLiteralTypeAnnotation":
46581 if (n.extra != null) {
46582 return printNumber$2(n.extra.raw);
46585 return printNumber$2(n.raw);
46587 case "DeclareTypeAlias":
46590 if (n.type === "DeclareTypeAlias" || n.declare) {
46591 parts.push("declare ");
46594 const printed = printAssignmentRight$1(n.id, n.right, path.call(print, "right"), options);
46595 parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi);
46596 return group$l(concat$x(parts));
46599 case "TypeCastExpression":
46601 return concat$x(["(", path.call(print, "expression"), printTypeAnnotation$3(path, options, print), ")"]);
46604 case "TypeParameterDeclaration":
46605 case "TypeParameterInstantiation":
46607 const printed = printTypeParameters$1(path, options, print, "params");
46609 if (options.parser === "flow") {
46610 const start = locStart$8(n);
46611 const end = locEnd$e(n);
46612 const commentStartIndex = options.originalText.lastIndexOf("/*", start);
46613 const commentEndIndex = options.originalText.indexOf("*/", end);
46615 if (commentStartIndex !== -1 && commentEndIndex !== -1) {
46616 const comment = options.originalText.slice(commentStartIndex + 2, commentEndIndex).trim();
46618 if (comment.startsWith("::") && !comment.includes("/*") && !comment.includes("*/")) {
46619 return concat$x(["/*:: ", printed, " */"]);
46627 case "TSTypeParameterDeclaration":
46628 case "TSTypeParameterInstantiation":
46629 return printTypeParameters$1(path, options, print, "params");
46631 case "TSTypeParameter":
46632 case "TypeParameter":
46634 const parent = path.getParentNode();
46636 if (parent.type === "TSMappedType") {
46637 parts.push("[", path.call(print, "name"));
46639 if (n.constraint) {
46640 parts.push(" in ", path.call(print, "constraint"));
46643 if (parent.nameType) {
46644 parts.push(" as ", path.callParent(path => {
46645 return path.call(print, "nameType");
46650 return concat$x(parts);
46654 parts.push(path.call(print, "variance"));
46657 parts.push(path.call(print, "name"));
46661 parts.push(path.call(print, "bound"));
46664 if (n.constraint) {
46665 parts.push(" extends ", path.call(print, "constraint"));
46669 parts.push(" = ", path.call(print, "default"));
46670 } // Keep comma if the file extension is .tsx and
46671 // has one type parameter that isn't extend with any types.
46672 // Because, otherwise formatted result will be invalid as tsx.
46675 const grandParent = path.getNode(2);
46677 if (getFunctionParameters$6(parent).length === 1 && isTSXFile$1(options) && !n.constraint && grandParent.type === "ArrowFunctionExpression") {
46681 return concat$x(parts);
46684 case "TypeofTypeAnnotation":
46685 return concat$x(["typeof ", path.call(print, "argument")]);
46687 case "InferredPredicate":
46689 // Unhandled types below. If encountered, nodes of these types should
46690 // be either left alone or desugared into AST types that are fully
46691 // supported by the pretty-printer.
46693 case "DeclaredPredicate":
46694 return concat$x(["%checks(", path.call(print, "value"), ")"]);
46696 case "TSAbstractKeyword":
46699 case "AnyTypeAnnotation":
46700 case "TSAnyKeyword":
46703 case "TSAsyncKeyword":
46706 case "BooleanTypeAnnotation":
46707 case "TSBooleanKeyword":
46710 case "BigIntTypeAnnotation":
46711 case "TSBigIntKeyword":
46714 case "TSConstKeyword":
46717 case "TSDeclareKeyword":
46720 case "TSExportKeyword":
46723 case "NullLiteralTypeAnnotation":
46724 case "TSNullKeyword":
46727 case "TSNeverKeyword":
46730 case "NumberTypeAnnotation":
46731 case "TSNumberKeyword":
46734 case "TSObjectKeyword":
46737 case "TSProtectedKeyword":
46738 return "protected";
46740 case "TSPrivateKeyword":
46743 case "TSPublicKeyword":
46746 case "TSReadonlyKeyword":
46749 case "SymbolTypeAnnotation":
46750 case "TSSymbolKeyword":
46753 case "TSStaticKeyword":
46756 case "StringTypeAnnotation":
46757 case "TSStringKeyword":
46760 case "TSUndefinedKeyword":
46761 return "undefined";
46763 case "TSUnknownKeyword":
46766 case "VoidTypeAnnotation":
46767 case "TSVoidKeyword":
46770 case "TSAsExpression":
46771 return concat$x([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]);
46773 case "TSArrayType":
46774 return concat$x([path.call(print, "elementType"), "[]"]);
46776 case "TSPropertySignature":
46779 parts.push("export ");
46782 if (n.accessibility) {
46783 parts.push(n.accessibility + " ");
46787 parts.push("static ");
46791 parts.push("readonly ");
46794 parts.push(printPropertyKey$2(path, options, print), printOptionalToken$6(path));
46796 if (n.typeAnnotation) {
46798 parts.push(path.call(print, "typeAnnotation"));
46799 } // This isn't valid semantically, but it's in the AST so we can print it.
46802 if (n.initializer) {
46803 parts.push(" = ", path.call(print, "initializer"));
46806 return concat$x(parts);
46809 case "TSParameterProperty":
46810 if (n.accessibility) {
46811 parts.push(n.accessibility + " ");
46815 parts.push("export ");
46819 parts.push("static ");
46823 parts.push("readonly ");
46826 parts.push(path.call(print, "parameter"));
46827 return concat$x(parts);
46829 case "GenericTypeAnnotation":
46830 case "TSTypeReference":
46831 return concat$x([path.call(print, n.type === "TSTypeReference" ? "typeName" : "id"), printTypeParameters$1(path, options, print, "typeParameters")]);
46833 case "TSTypeQuery":
46834 return concat$x(["typeof ", path.call(print, "exprName")]);
46836 case "TSIndexSignature":
46838 const parent = path.getParentNode(); // The typescript parser accepts multiple parameters here. If you're
46839 // using them, it makes sense to have a trailing comma. But if you
46840 // aren't, this is more like a computed property name than an array.
46841 // So we leave off the trailing comma when there's just one parameter.
46843 const trailingComma = n.parameters.length > 1 ? ifBreak$d(shouldPrintComma$8(options) ? "," : "") : "";
46844 const parametersGroup = group$l(concat$x([indent$p(concat$x([softline$h, join$f(concat$x([", ", softline$h]), path.map(print, "parameters"))])), trailingComma, softline$h]));
46845 return concat$x([n.export ? "export " : "", n.accessibility ? concat$x([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.declare ? "declare " : "", "[", n.parameters ? parametersGroup : "", n.typeAnnotation ? "]: " : "]", n.typeAnnotation ? path.call(print, "typeAnnotation") : "", parent.type === "ClassBody" ? semi : ""]);
46848 case "TSTypePredicate":
46849 return concat$x([n.asserts ? "asserts " : "", path.call(print, "parameterName"), n.typeAnnotation ? concat$x([" is ", path.call(print, "typeAnnotation")]) : ""]);
46851 case "TSNonNullExpression":
46852 return concat$x([path.call(print, "expression"), "!"]);
46854 case "ThisTypeAnnotation":
46858 case "TSImportType":
46859 return concat$x([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, n.parameter ? "parameter" : "argument"), ")", !n.qualifier ? "" : concat$x([".", path.call(print, "qualifier")]), printTypeParameters$1(path, options, print, "typeParameters")]);
46861 case "TSLiteralType":
46862 return path.call(print, "literal");
46864 case "TSIndexedAccessType":
46865 return concat$x([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]);
46867 case "TSConstructSignatureDeclaration":
46868 case "TSCallSignatureDeclaration":
46869 case "TSConstructorType":
46871 if (n.type !== "TSCallSignatureDeclaration") {
46872 parts.push("new ");
46875 parts.push(group$l(printFunctionParameters$2(path, print, options,
46878 /* printTypeParams */
46881 if (n.returnType || n.typeAnnotation) {
46882 const isType = n.type === "TSConstructorType";
46883 parts.push(isType ? " => " : ": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
46886 return concat$x(parts);
46889 case "TSTypeOperator":
46890 return concat$x([n.operator, " ", path.call(print, "typeAnnotation")]);
46892 case "TSMappedType":
46894 const shouldBreak = hasNewlineInRange$6(options.originalText, locStart$8(n), locEnd$e(n));
46895 return group$l(concat$x(["{", indent$p(concat$x([options.bracketSpacing ? line$j : softline$h, n.readonly ? concat$x([getTypeScriptMappedTypeModifier$1(n.readonly, "readonly"), " "]) : "", printTypeScriptModifiers$2(path, options, print), path.call(print, "typeParameter"), n.optional ? getTypeScriptMappedTypeModifier$1(n.optional, "?") : "", n.typeAnnotation ? ": " : "", path.call(print, "typeAnnotation"), ifBreak$d(semi, "")])), comments.printDanglingComments(path, options,
46897 true), options.bracketSpacing ? line$j : softline$h, "}"]), {
46902 case "TSMethodSignature":
46903 parts.push(n.accessibility ? concat$x([n.accessibility, " "]) : "", n.export ? "export " : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.computed ? "[" : "", path.call(print, "key"), n.computed ? "]" : "", printOptionalToken$6(path), printFunctionParameters$2(path, print, options,
46906 /* printTypeParams */
46909 if (n.returnType || n.typeAnnotation) {
46910 parts.push(": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
46913 return group$l(concat$x(parts));
46915 case "TSNamespaceExportDeclaration":
46916 parts.push("export as namespace ", path.call(print, "id"));
46918 if (options.semi) {
46922 return group$l(concat$x(parts));
46924 case "TSEnumDeclaration":
46926 parts.push("declare ");
46930 parts.push(printTypeScriptModifiers$2(path, options, print));
46934 parts.push("const ");
46937 parts.push("enum ", path.call(print, "id"), " ");
46939 if (n.members.length === 0) {
46940 parts.push(group$l(concat$x(["{", comments.printDanglingComments(path, options), softline$h, "}"])));
46942 parts.push(group$l(concat$x(["{", indent$p(concat$x([hardline$k, printArrayItems$1(path, options, "members", print), shouldPrintComma$8(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options,
46944 true), hardline$k, "}"])));
46947 return concat$x(parts);
46949 case "TSEnumMember":
46950 parts.push(path.call(print, "id"));
46952 if (n.initializer) {
46953 parts.push(" = ", path.call(print, "initializer"));
46956 return concat$x(parts);
46958 case "TSImportEqualsDeclaration":
46960 parts.push("export ");
46963 parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference"));
46965 if (options.semi) {
46969 return group$l(concat$x(parts));
46971 case "TSExternalModuleReference":
46972 return concat$x(["require(", path.call(print, "expression"), ")"]);
46974 case "TSModuleDeclaration":
46976 const parent = path.getParentNode();
46977 const isExternalModule = isLiteral$2(n.id);
46978 const parentIsDeclaration = parent.type === "TSModuleDeclaration";
46979 const bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration";
46981 if (parentIsDeclaration) {
46985 parts.push("declare ");
46988 parts.push(printTypeScriptModifiers$2(path, options, print));
46989 const textBetweenNodeAndItsId = options.originalText.slice(locStart$8(n), locStart$8(n.id)); // Global declaration looks like this:
46990 // (declare)? global { ... }
46992 const isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId);
46994 if (!isGlobalDeclaration) {
46995 parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace ");
46999 parts.push(path.call(print, "id"));
47001 if (bodyIsDeclaration) {
47002 parts.push(path.call(print, "body"));
47003 } else if (n.body) {
47004 parts.push(" ", group$l(path.call(print, "body")));
47009 return concat$x(parts);
47012 case "PrivateName":
47013 // babel use `id`, meriyah use `name`
47014 return concat$x(["#", path.call(print, n.id ? "id" : "name")]);
47015 // TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields.
47017 case "TSPrivateIdentifier":
47018 return n.escapedText;
47020 case "TSConditionalType":
47021 return ternary(path, options, print, {
47022 beforeParts: () => [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")],
47023 afterParts: () => [],
47024 shouldCheckJsx: false,
47025 conditionalNodeType: "TSConditionalType",
47026 consequentNodePropertyName: "trueType",
47027 alternateNodePropertyName: "falseType",
47028 testNodePropertyNames: ["checkType", "extendsType"]
47031 case "TSInferType":
47032 return concat$x(["infer", " ", path.call(print, "typeParameter")]);
47034 case "InterpreterDirective":
47035 parts.push("#!", n.value, hardline$k);
47037 if (isNextLineEmpty$9(options.originalText, n, locEnd$e)) {
47038 parts.push(hardline$k);
47041 return concat$x(parts);
47044 return concat$x([].concat(path.call(print, "node"), !n.node.comments || n.node.comments.length === 0 ? [] : concat$x([" //", n.node.comments[0].value.trimEnd()])));
47046 case "NGChainedExpression":
47047 return group$l(join$f(concat$x([";", line$j]), path.map(childPath => hasNgSideEffect$1(childPath) ? print(childPath) : concat$x(["(", print(childPath), ")"]), "expressions")));
47049 case "NGEmptyExpression":
47052 case "NGQuotedExpression":
47053 return concat$x([n.prefix, ": ", n.value.trim()]);
47055 case "NGMicrosyntax":
47056 return concat$x(path.map((childPath, index) => concat$x([index === 0 ? "" : isNgForOf$1(childPath.getValue(), index, n) ? " " : concat$x([";", line$j]), print(childPath)]), "body"));
47058 case "NGMicrosyntaxKey":
47059 return /^[$_a-z][\w$]*(-[$_a-z][\w$])*$/i.test(n.name) ? n.name : JSON.stringify(n.name);
47061 case "NGMicrosyntaxExpression":
47062 return concat$x([path.call(print, "expression"), n.alias === null ? "" : concat$x([" as ", path.call(print, "alias")])]);
47064 case "NGMicrosyntaxKeyedExpression":
47066 const index = path.getName();
47067 const parentNode = path.getParentNode();
47068 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";
47069 return concat$x([path.call(print, "key"), shouldNotPrintColon ? " " : ": ", path.call(print, "expression")]);
47072 case "NGMicrosyntaxLet":
47073 return concat$x(["let ", path.call(print, "key"), n.value === null ? "" : concat$x([" = ", path.call(print, "value")])]);
47075 case "NGMicrosyntaxAs":
47076 return concat$x([path.call(print, "key"), " as ", path.call(print, "alias")]);
47078 case "PipelineBareFunction":
47079 return path.call(print, "callee");
47081 case "PipelineTopicExpression":
47082 return path.call(print, "expression");
47084 case "PipelinePrimaryTopicReference":
47087 return concat$x(parts);
47090 case "ArgumentPlaceholder":
47092 // These are not valid TypeScript. Printing them just for the sake of error recovery.
47094 case "TSJSDocAllType":
47097 case "TSJSDocUnknownType":
47100 case "TSJSDocNullableType":
47101 return concat$x(["?", path.call(print, "typeAnnotation")]);
47103 case "TSJSDocNonNullableType":
47104 return concat$x(["!", path.call(print, "typeAnnotation")]);
47106 case "TSJSDocFunctionType":
47107 return concat$x(["function(", // The parameters could be here, but typescript-estree doesn't convert them anyway (throws an error).
47108 "): ", path.call(print, "typeAnnotation")]);
47111 /* istanbul ignore next */
47112 throw new Error("unknown type: " + JSON.stringify(n.type));
47116 function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) {
47117 const raw = rawText$3(node);
47118 const isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral";
47119 return printString$2(raw, options, isDirectiveLiteral);
47122 function printRegex(node) {
47123 const flags = node.flags.split("").sort().join("");
47124 return `/${node.pattern}/${flags}`;
47127 function canAttachComment(node) {
47128 return node.type && node.type !== "CommentBlock" && node.type !== "CommentLine" && node.type !== "Line" && node.type !== "Block" && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import";
47131 var printerEstree = {
47132 preprocess: printPreprocess,
47133 print: genericPrint,
47135 insertPragma: insertPragma$1,
47136 massageAstNode: clean_1,
47137 hasPrettierIgnore: hasPrettierIgnore$1,
47138 willPrintOwnComments: comments$1.willPrintOwnComments,
47140 printComment: printComment$2,
47141 isBlockComment: isBlockComment$9,
47143 ownLine: comments$1.handleOwnLineComment,
47144 endOfLine: comments$1.handleEndOfLineComment,
47145 remaining: comments$1.handleRemainingComment
47147 getGapRegex: comments$1.getGapRegex,
47148 getCommentChildNodes: comments$1.getCommentChildNodes
47154 hardline: hardline$l,
47160 function genericPrint$1(path, options, print) {
47161 const node = path.getValue();
47163 switch (node.type) {
47165 return concat$y([path.call(print, "node"), hardline$l]);
47167 case "ArrayExpression":
47168 return node.elements.length === 0 ? "[]" : concat$y(["[", indent$q(concat$y([hardline$l, join$g(concat$y([",", hardline$l]), path.map(print, "elements"))])), hardline$l, "]"]);
47170 case "ObjectExpression":
47171 return node.properties.length === 0 ? "{}" : concat$y(["{", indent$q(concat$y([hardline$l, join$g(concat$y([",", hardline$l]), path.map(print, "properties"))])), hardline$l, "}"]);
47173 case "ObjectProperty":
47174 return concat$y([path.call(print, "key"), ": ", path.call(print, "value")]);
47176 case "UnaryExpression":
47177 return concat$y([node.operator === "+" ? "" : node.operator, path.call(print, "argument")]);
47179 case "NullLiteral":
47182 case "BooleanLiteral":
47183 return node.value ? "true" : "false";
47185 case "StringLiteral":
47186 case "NumericLiteral":
47187 return JSON.stringify(node.value);
47190 return JSON.stringify(node.name);
47193 /* istanbul ignore next */
47194 throw new Error("unknown type: " + JSON.stringify(node.type));
47198 const ignoredProperties$1 = new Set(["start", "end", "extra", "loc", "comments", "errors", "range"]);
47200 function clean$1(node, newNode
47207 if (type === "Identifier") {
47209 type: "StringLiteral",
47214 if (type === "UnaryExpression" && node.operator === "+") {
47215 return newNode.argument;
47219 clean$1.ignoredProperties = ignoredProperties$1;
47220 var printerEstreeJson = {
47221 preprocess: printPreprocess,
47222 print: genericPrint$1,
47223 massageAstNode: clean$1
47226 const CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
47228 var commonOptions = {
47231 category: CATEGORY_COMMON,
47234 description: "Print spaces between brackets.",
47235 oppositeDescription: "Do not print spaces between brackets."
47239 category: CATEGORY_COMMON,
47242 description: "Use single quotes instead of double quotes."
47246 category: CATEGORY_COMMON,
47255 description: "How to wrap prose.",
47259 description: "Wrap prose if it exceeds the print width."
47263 description: "Do not wrap prose."
47267 description: "Wrap prose as-is."
47272 const CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
47277 category: CATEGORY_JAVASCRIPT,
47286 description: "Include parentheses around a sole arrow function parameter.",
47289 description: "Always include parens. Example: `(x) => x`"
47292 description: "Omit parens when possible. Example: `x => x`"
47295 bracketSpacing: commonOptions.bracketSpacing,
47296 jsxBracketSameLine: {
47298 category: CATEGORY_JAVASCRIPT,
47301 description: "Put > on the last line instead of at a new line."
47305 category: CATEGORY_JAVASCRIPT,
47308 description: "Print semicolons.",
47309 oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them."
47311 singleQuote: commonOptions.singleQuote,
47314 category: CATEGORY_JAVASCRIPT,
47317 description: "Use single quotes in JSX."
47321 category: CATEGORY_JAVASCRIPT,
47323 default: "as-needed",
47324 description: "Change when properties in objects are quoted.",
47326 value: "as-needed",
47327 description: "Only add quotes around object properties where required."
47329 value: "consistent",
47330 description: "If at least one property in an object requires quotes, quote all properties."
47333 description: "Respect the input use of quotes in object properties."
47338 category: CATEGORY_JAVASCRIPT,
47350 description: "Print trailing commas wherever possible when multi-line.",
47353 description: "Trailing commas where valid in ES5 (objects, arrays, etc.)"
47356 description: "No trailing commas."
47359 description: "Trailing commas wherever possible (including function arguments)."
47364 var name$2 = "JavaScript";
47365 var type = "programming";
47366 var tmScope = "source.js";
47367 var aceMode = "javascript";
47368 var codemirrorMode = "javascript";
47369 var codemirrorMimeType = "text/javascript";
47370 var color = "#f1e05a";
47401 var interpreters = [
47413 var languageId = 183;
47414 var require$$0$2 = {
47419 codemirrorMode: codemirrorMode,
47420 codemirrorMimeType: codemirrorMimeType,
47423 extensions: extensions,
47424 filenames: filenames,
47425 interpreters: interpreters,
47426 languageId: languageId
47429 var name$3 = "JSX";
47430 var type$1 = "programming";
47431 var group$m = "JavaScript";
47432 var extensions$1 = [
47435 var tmScope$1 = "source.js.jsx";
47436 var aceMode$1 = "javascript";
47437 var codemirrorMode$1 = "jsx";
47438 var codemirrorMimeType$1 = "text/jsx";
47439 var languageId$1 = 178;
47444 extensions: extensions$1,
47445 tmScope: tmScope$1,
47446 aceMode: aceMode$1,
47447 codemirrorMode: codemirrorMode$1,
47448 codemirrorMimeType: codemirrorMimeType$1,
47449 languageId: languageId$1
47452 var name$4 = "TypeScript";
47453 var type$2 = "programming";
47454 var color$1 = "#2b7489";
47458 var interpreters$1 = [
47462 var extensions$2 = [
47465 var tmScope$2 = "source.ts";
47466 var aceMode$2 = "typescript";
47467 var codemirrorMode$2 = "javascript";
47468 var codemirrorMimeType$2 = "application/typescript";
47469 var languageId$2 = 378;
47474 aliases: aliases$1,
47475 interpreters: interpreters$1,
47476 extensions: extensions$2,
47477 tmScope: tmScope$2,
47478 aceMode: aceMode$2,
47479 codemirrorMode: codemirrorMode$2,
47480 codemirrorMimeType: codemirrorMimeType$2,
47481 languageId: languageId$2
47484 var name$5 = "TSX";
47485 var type$3 = "programming";
47486 var group$n = "TypeScript";
47487 var extensions$3 = [
47490 var tmScope$3 = "source.tsx";
47491 var aceMode$3 = "javascript";
47492 var codemirrorMode$3 = "jsx";
47493 var codemirrorMimeType$3 = "text/jsx";
47494 var languageId$3 = 94901924;
47499 extensions: extensions$3,
47500 tmScope: tmScope$3,
47501 aceMode: aceMode$3,
47502 codemirrorMode: codemirrorMode$3,
47503 codemirrorMimeType: codemirrorMimeType$3,
47504 languageId: languageId$3
47507 var name$6 = "JSON";
47508 var type$4 = "data";
47509 var tmScope$4 = "source.json";
47510 var aceMode$4 = "json";
47511 var codemirrorMode$4 = "javascript";
47512 var codemirrorMimeType$4 = "application/json";
47513 var searchable = false;
47514 var extensions$4 = [
47521 ".JSON-tmLanguage",
47532 var filenames$1 = [
47541 var languageId$4 = 174;
47542 var require$$4$1 = {
47545 tmScope: tmScope$4,
47546 aceMode: aceMode$4,
47547 codemirrorMode: codemirrorMode$4,
47548 codemirrorMimeType: codemirrorMimeType$4,
47549 searchable: searchable,
47550 extensions: extensions$4,
47551 filenames: filenames$1,
47552 languageId: languageId$4
47555 var name$7 = "JSON with Comments";
47556 var type$5 = "data";
47557 var group$o = "JSON";
47558 var tmScope$5 = "source.js";
47559 var aceMode$5 = "javascript";
47560 var codemirrorMode$5 = "javascript";
47561 var codemirrorMimeType$5 = "text/javascript";
47565 var extensions$5 = [
47568 ".sublime-commands",
47569 ".sublime-completions",
47573 ".sublime-mousemap",
47574 ".sublime-project",
47575 ".sublime-settings",
47577 ".sublime-workspace",
47578 ".sublime_metrics",
47581 var filenames$2 = [
47587 "devcontainer.json",
47589 "language-configuration.json",
47593 var languageId$5 = 423;
47598 tmScope: tmScope$5,
47599 aceMode: aceMode$5,
47600 codemirrorMode: codemirrorMode$5,
47601 codemirrorMimeType: codemirrorMimeType$5,
47602 aliases: aliases$2,
47603 extensions: extensions$5,
47604 filenames: filenames$2,
47605 languageId: languageId$5
47608 var name$8 = "JSON5";
47609 var type$6 = "data";
47610 var extensions$6 = [
47613 var tmScope$6 = "source.js";
47614 var aceMode$6 = "javascript";
47615 var codemirrorMode$6 = "javascript";
47616 var codemirrorMimeType$6 = "application/json";
47617 var languageId$6 = 175;
47621 extensions: extensions$6,
47622 tmScope: tmScope$6,
47623 aceMode: aceMode$6,
47624 codemirrorMode: codemirrorMode$6,
47625 codemirrorMimeType: codemirrorMimeType$6,
47626 languageId: languageId$6
47629 const languages = [createLanguage(require$$0$2, data => ({
47631 parsers: ["babel", "espree", "meriyah", "babel-flow", "babel-ts", "flow", "typescript"],
47632 vscodeLanguageIds: ["javascript", "mongo"],
47633 extensions: [...data.extensions, // WeiXin Script (Weixin Mini Programs)
47634 // https://developers.weixin.qq.com/miniprogram/en/dev/framework/view/wxs/
47636 })), createLanguage(require$$0$2, () => ({
47639 parsers: ["flow", "babel-flow"],
47640 vscodeLanguageIds: ["javascript"],
47643 extensions: [".js.flow"]
47644 })), createLanguage(require$$1, () => ({
47646 parsers: ["babel", "babel-flow", "babel-ts", "flow", "typescript", "espree", "meriyah"],
47647 vscodeLanguageIds: ["javascriptreact"]
47648 })), createLanguage(require$$2, () => ({
47650 parsers: ["typescript", "babel-ts"],
47651 vscodeLanguageIds: ["typescript"]
47652 })), createLanguage(require$$3, () => ({
47654 parsers: ["typescript", "babel-ts"],
47655 vscodeLanguageIds: ["typescriptreact"]
47656 })), createLanguage(require$$4$1, () => ({
47657 name: "JSON.stringify",
47659 parsers: ["json-stringify"],
47660 vscodeLanguageIds: ["json"],
47662 // .json file defaults to json instead of json-stringify
47663 filenames: ["package.json", "package-lock.json", "composer.json"]
47664 })), createLanguage(require$$4$1, data => ({
47667 vscodeLanguageIds: ["json"],
47668 filenames: [...data.filenames, ".prettierrc"],
47669 extensions: data.extensions.filter(extension => extension !== ".jsonl")
47670 })), createLanguage(require$$5, data => ({
47673 vscodeLanguageIds: ["jsonc"],
47674 filenames: [...data.filenames, ".eslintrc"]
47675 })), createLanguage(require$$6, () => ({
47677 parsers: ["json5"],
47678 vscodeLanguageIds: ["json5"]
47681 estree: printerEstree,
47682 "estree-json": printerEstreeJson
47687 return require("./parser-babel").parsers.babel;
47690 get "babel-flow"() {
47691 return require("./parser-babel").parsers["babel-flow"];
47695 return require("./parser-babel").parsers["babel-ts"];
47699 return require("./parser-babel").parsers.json;
47703 return require("./parser-babel").parsers.json5;
47706 get "json-stringify"() {
47707 return require("./parser-babel").parsers["json-stringify"];
47710 get __js_expression() {
47711 return require("./parser-babel").parsers.__js_expression;
47714 get __vue_expression() {
47715 return require("./parser-babel").parsers.__vue_expression;
47718 get __vue_event_binding() {
47719 return require("./parser-babel").parsers.__vue_event_binding;
47724 return require("./parser-flow").parsers.flow;
47729 return require("./parser-typescript").parsers.typescript;
47732 // JS - Angular Action
47733 get __ng_action() {
47734 return require("./parser-angular").parsers.__ng_action;
47737 // JS - Angular Binding
47738 get __ng_binding() {
47739 return require("./parser-angular").parsers.__ng_binding;
47742 // JS - Angular Interpolation
47743 get __ng_interpolation() {
47744 return require("./parser-angular").parsers.__ng_interpolation;
47747 // JS - Angular Directive
47748 get __ng_directive() {
47749 return require("./parser-angular").parsers.__ng_directive;
47754 return require("./parser-espree").parsers.espree;
47759 return require("./parser-meriyah").parsers.meriyah;
47765 options: options$2,
47771 isFrontMatterNode: isFrontMatterNode$1
47773 const ignoredProperties$2 = new Set(["raw", // front-matter
47774 "raws", "sourceIndex", "source", "before", "after", "trailingComma"]);
47776 function clean$2(ast, newObj, parent) {
47777 if (isFrontMatterNode$1(ast) && ast.lang === "yaml") {
47778 delete newObj.value;
47781 if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0) {
47783 // first non-front-matter comment
47784 if (parent.nodes[0] === ast || isFrontMatterNode$1(parent.nodes[0]) && parent.nodes[1] === ast) {
47790 delete newObj.text; // standalone pragma
47792 if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) {
47795 } // Last comment is not parsed, when omitting semicolon, #8675
47798 if (parent.type === "css-root" && getLast(parent.nodes) === ast) {
47803 if (ast.type === "value-root") {
47804 delete newObj.text;
47807 if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") {
47808 delete newObj.value;
47811 if (ast.type === "css-rule") {
47812 delete newObj.params;
47815 if (ast.type === "selector-combinator") {
47816 newObj.value = newObj.value.replace(/\s+/g, " ");
47819 if (ast.type === "media-feature") {
47820 newObj.value = newObj.value.replace(/ /g, "");
47823 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") {
47824 newObj.value = newObj.value.toLowerCase();
47827 if (ast.type === "css-decl") {
47828 newObj.prop = newObj.prop.toLowerCase();
47831 if (ast.type === "css-atrule" || ast.type === "css-import") {
47832 newObj.name = newObj.name.toLowerCase();
47835 if (ast.type === "value-number") {
47836 newObj.unit = newObj.unit.toLowerCase();
47839 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) {
47840 newObj.value = cleanCSSStrings(newObj.value);
47843 if (ast.type === "selector-attribute") {
47844 newObj.attribute = newObj.attribute.trim();
47846 if (newObj.namespace) {
47847 if (typeof newObj.namespace === "string") {
47848 newObj.namespace = newObj.namespace.trim();
47850 if (newObj.namespace.length === 0) {
47851 newObj.namespace = true;
47856 if (newObj.value) {
47857 newObj.value = newObj.value.trim().replace(/^["']|["']$/g, "");
47858 delete newObj.quoted;
47862 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) {
47863 newObj.value = newObj.value.replace(/([\d+.Ee-]+)([A-Za-z]*)/g, (match, numStr, unit) => {
47864 const num = Number(numStr);
47865 return isNaN(num) ? match : num + unit.toLowerCase();
47869 if (ast.type === "selector-tag") {
47870 const lowercasedValue = ast.value.toLowerCase();
47872 if (["from", "to"].includes(lowercasedValue)) {
47873 newObj.value = lowercasedValue;
47875 } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func`
47878 if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") {
47879 delete newObj.value;
47880 } // Workaround for SCSS nested properties
47883 if (ast.type === "selector-unknown") {
47884 delete newObj.value;
47888 clean$2.ignoredProperties = ignoredProperties$2;
47890 function cleanCSSStrings(value) {
47891 return value.replace(/'/g, '"').replace(/\\([^\dA-Fa-f])/g, "$1");
47894 var clean_1$1 = clean$2;
47898 hardline: hardline$m,
47900 markAsRoot: markAsRoot$1
47903 const DELIMITER_MAP = {
47908 function parse$7(text) {
47909 const delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp).join("|");
47910 const match = text.match( // trailing spaces after delimiters are allowed
47911 new RegExp(`^(${delimiterRegex})([^\\n]*)\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)`));
47913 if (match === null) {
47920 const [raw, delimiter, language, value] = match;
47921 let lang = DELIMITER_MAP[delimiter];
47923 if (lang !== "toml" && language && language.trim()) {
47924 lang = language.trim();
47929 type: "front-matter",
47932 raw: raw.replace(/\n$/, "")
47934 content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length)
47938 function print$1(node, textToDoc) {
47939 if (node.lang === "yaml") {
47940 const value = node.value.trim();
47941 const doc = value ? textToDoc(value, {
47944 stripTrailingHardline: true
47946 return markAsRoot$1(concat$z(["---", hardline$m, doc, doc ? hardline$m : "", "---"]));
47950 var frontMatter = {
47957 hardline: hardline$n,
47962 print: printFrontMatter
47965 function embed$1(path, print, textToDoc
47968 const node = path.getValue();
47970 if (node.type === "front-matter") {
47971 const doc = printFrontMatter(node, textToDoc);
47972 return doc ? concat$A([doc, hardline$n]) : "";
47976 var embed_1$1 = embed$1;
47979 parse: parseFrontMatter
47982 function hasPragma$1(text) {
47983 return pragma.hasPragma(parseFrontMatter(text).content);
47986 function insertPragma$2(text) {
47990 } = parseFrontMatter(text);
47991 return (frontMatter ? frontMatter.raw + "\n\n" : "") + pragma.insertPragma(content);
47995 hasPragma: hasPragma$1,
47996 insertPragma: insertPragma$2
47999 const colorAdjusterFunctions = new Set(["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"]);
48001 function getAncestorCounter(path, typeOrTypes) {
48002 const types = [].concat(typeOrTypes);
48006 while (ancestorNode = path.getParentNode(++counter)) {
48007 if (types.includes(ancestorNode.type)) {
48015 function getAncestorNode(path, typeOrTypes) {
48016 const counter = getAncestorCounter(path, typeOrTypes);
48017 return counter === -1 ? null : path.getParentNode(counter);
48020 function getPropOfDeclNode(path) {
48021 const declAncestorNode = getAncestorNode(path, "css-decl");
48022 return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase();
48025 function hasSCSSInterpolation(groupList) {
48026 if (groupList && groupList.length) {
48027 for (let i = groupList.length - 1; i > 0; i--) {
48028 // If we find `#{`, return true.
48029 if (groupList[i].type === "word" && groupList[i].value === "{" && groupList[i - 1].type === "word" && groupList[i - 1].value.endsWith("#")) {
48038 function hasStringOrFunction(groupList) {
48039 if (groupList && groupList.length) {
48040 for (let i = 0; i < groupList.length; i++) {
48041 if (groupList[i].type === "string" || groupList[i].type === "func") {
48050 function isSCSS(parser, text) {
48051 const hasExplicitParserChoice = parser === "less" || parser === "scss";
48052 const IS_POSSIBLY_SCSS = /(\w\s*:\s*[^:}]+|#){|@import[^\n]+(?:url|,)/;
48053 return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text);
48056 function isSCSSVariable(node) {
48057 return !!(node && node.type === "word" && node.value.startsWith("$"));
48060 function isWideKeywords(value) {
48061 return ["initial", "inherit", "unset", "revert"].includes(value.toLowerCase());
48064 function isKeyframeAtRuleKeywords(path, value) {
48065 const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
48066 return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].includes(value.toLowerCase());
48069 function maybeToLowerCase(value) {
48070 return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase();
48073 function insideValueFunctionNode(path, functionName) {
48074 const funcAncestorNode = getAncestorNode(path, "value-func");
48075 return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName;
48078 function insideICSSRuleNode(path) {
48079 const ruleAncestorNode = getAncestorNode(path, "css-rule");
48080 return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export"));
48083 function insideAtRuleNode(path, atRuleNameOrAtRuleNames) {
48084 const atRuleNames = [].concat(atRuleNameOrAtRuleNames);
48085 const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
48086 return atRuleAncestorNode && atRuleNames.includes(atRuleAncestorNode.name.toLowerCase());
48089 function insideURLFunctionInImportAtRuleNode(path) {
48090 const node = path.getValue();
48091 const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
48092 return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2;
48095 function isURLFunctionNode(node) {
48096 return node.type === "value-func" && node.value.toLowerCase() === "url";
48099 function isLastNode(path, node) {
48100 const parentNode = path.getParentNode();
48101 /* istanbul ignore next */
48110 return nodes && nodes.indexOf(node) === nodes.length - 1;
48113 function isDetachedRulesetDeclarationNode(node) {
48114 // If a Less file ends up being parsed with the SCSS parser, Less
48115 // variable declarations will be parsed as atrules with names ending
48116 // with a colon, so keep the original case then.
48118 /* istanbul ignore next */
48119 if (!node.selector) {
48123 return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value);
48126 function isForKeywordNode(node) {
48127 return node.type === "value-word" && ["from", "through", "end"].includes(node.value);
48130 function isIfElseKeywordNode(node) {
48131 return node.type === "value-word" && ["and", "or", "not"].includes(node.value);
48134 function isEachKeywordNode(node) {
48135 return node.type === "value-word" && node.value === "in";
48138 function isMultiplicationNode(node) {
48139 return node.type === "value-operator" && node.value === "*";
48142 function isDivisionNode(node) {
48143 return node.type === "value-operator" && node.value === "/";
48146 function isAdditionNode(node) {
48147 return node.type === "value-operator" && node.value === "+";
48150 function isSubtractionNode(node) {
48151 return node.type === "value-operator" && node.value === "-";
48154 function isModuloNode(node) {
48155 return node.type === "value-operator" && node.value === "%";
48158 function isMathOperatorNode(node) {
48159 return isMultiplicationNode(node) || isDivisionNode(node) || isAdditionNode(node) || isSubtractionNode(node) || isModuloNode(node);
48162 function isEqualityOperatorNode(node) {
48163 return node.type === "value-word" && ["==", "!="].includes(node.value);
48166 function isRelationalOperatorNode(node) {
48167 return node.type === "value-word" && ["<", ">", "<=", ">="].includes(node.value);
48170 function isSCSSControlDirectiveNode(node) {
48171 return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].includes(node.name);
48174 function isSCSSNestedPropertyNode(node) {
48175 /* istanbul ignore next */
48176 if (!node.selector) {
48180 return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":");
48183 function isDetachedRulesetCallNode(node) {
48184 return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params);
48187 function isTemplatePlaceholderNode(node) {
48188 return node.name.startsWith("prettier-placeholder");
48191 function isTemplatePropNode(node) {
48192 return node.prop.startsWith("@prettier-placeholder");
48195 function isPostcssSimpleVarNode(currentNode, nextNode) {
48196 return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before;
48199 function hasComposesNode(node) {
48200 return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes";
48203 function hasParensAroundNode(node) {
48204 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;
48207 function hasEmptyRawBefore(node) {
48208 return node.raws && node.raws.before === "";
48211 function isKeyValuePairNode(node) {
48212 return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon";
48215 function isKeyValuePairInParenGroupNode(node) {
48216 return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode(node.groups[0]);
48219 function isSCSSMapItemNode(path) {
48220 const node = path.getValue(); // Ignore empty item (i.e. `$key: ()`)
48222 if (node.groups.length === 0) {
48226 const parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`)
48228 if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) {
48232 const declNode = getAncestorNode(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`)
48234 if (declNode && declNode.prop && declNode.prop.startsWith("$")) {
48236 } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`)
48239 if (isKeyValuePairInParenGroupNode(parentParentNode)) {
48241 } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`)
48244 if (parentParentNode.type === "value-func") {
48251 function isInlineValueCommentNode(node) {
48252 return node.type === "value-comment" && node.inline;
48255 function isHashNode(node) {
48256 return node.type === "value-word" && node.value === "#";
48259 function isLeftCurlyBraceNode(node) {
48260 return node.type === "value-word" && node.value === "{";
48263 function isRightCurlyBraceNode(node) {
48264 return node.type === "value-word" && node.value === "}";
48267 function isWordNode(node) {
48268 return ["value-word", "value-atword"].includes(node.type);
48271 function isColonNode(node) {
48272 return node.type === "value-colon";
48275 function isMediaAndSupportsKeywords(node) {
48276 return node.value && ["not", "and", "or"].includes(node.value.toLowerCase());
48279 function isColorAdjusterFuncNode(node) {
48280 if (node.type !== "value-func") {
48284 return colorAdjusterFunctions.has(node.value.toLowerCase());
48285 } // TODO: only check `less` when we don't use `less` to parse `css`
48288 function isLessParser(options) {
48289 return options.parser === "css" || options.parser === "less";
48292 function lastLineHasInlineComment(text) {
48293 return /\/\//.test(text.split(/[\n\r]/).pop());
48296 function stringifyNode(node) {
48298 const open = node.open && node.open.value ? node.open.value : "";
48299 const groups = node.groups.reduce((previousValue, currentValue, index) => {
48300 return previousValue + stringifyNode(currentValue) + (node.groups[0].type === "comma_group" && index !== node.groups.length - 1 ? "," : "");
48302 const close = node.close && node.close.value ? node.close.value : "";
48303 return open + groups + close;
48306 const before = node.raws && node.raws.before ? node.raws.before : "";
48307 const quote = node.raws && node.raws.quote ? node.raws.quote : "";
48308 const atword = node.type === "atword" ? "@" : "";
48309 const value = node.value ? node.value : "";
48310 const unit = node.unit ? node.unit : "";
48311 const group = node.group ? stringifyNode(node.group) : "";
48312 const after = node.raws && node.raws.after ? node.raws.after : "";
48313 return before + quote + atword + value + quote + unit + group + after;
48316 function isAtWordPlaceholderNode(node) {
48317 return node && node.type === "value-atword" && node.value.startsWith("prettier-placeholder-");
48321 getAncestorCounter,
48324 hasSCSSInterpolation,
48325 hasStringOrFunction,
48327 insideValueFunctionNode,
48328 insideICSSRuleNode,
48330 insideURLFunctionInImportAtRuleNode,
48331 isKeyframeAtRuleKeywords,
48337 isSCSSControlDirectiveNode,
48338 isDetachedRulesetDeclarationNode,
48339 isRelationalOperatorNode,
48340 isEqualityOperatorNode,
48341 isMultiplicationNode,
48346 isMathOperatorNode,
48350 isIfElseKeywordNode,
48352 hasParensAroundNode,
48354 isSCSSNestedPropertyNode,
48355 isDetachedRulesetCallNode,
48356 isTemplatePlaceholderNode,
48357 isTemplatePropNode,
48358 isPostcssSimpleVarNode,
48359 isKeyValuePairNode,
48360 isKeyValuePairInParenGroupNode,
48362 isInlineValueCommentNode,
48364 isLeftCurlyBraceNode,
48365 isRightCurlyBraceNode,
48368 isMediaAndSupportsKeywords,
48369 isColorAdjusterFuncNode,
48370 lastLineHasInlineComment,
48372 isAtWordPlaceholderNode
48375 var lineColumnToIndex = function (lineColumn, text) {
48378 for (let i = 0; i < lineColumn.line - 1; ++i) {
48379 index = text.indexOf("\n", index) + 1;
48382 return index + lineColumn.column;
48386 getLast: getLast$a,
48387 skipEverythingButNewLine: skipEverythingButNewLine$2
48390 function calculateLocStart(node, text) {
48391 // value-* nodes have this
48392 if (typeof node.sourceIndex === "number") {
48393 return node.sourceIndex;
48396 return node.source ? lineColumnToIndex(node.source.start, text) - 1 : null;
48399 function calculateLocEnd(node, text) {
48400 if (node.type === "css-comment" && node.inline) {
48401 return skipEverythingButNewLine$2(text, node.source.startOffset);
48404 const endNode = node.nodes && getLast$a(node.nodes);
48406 if (endNode && node.source && !node.source.end) {
48410 if (node.source && node.source.end) {
48411 return lineColumnToIndex(node.source.end, text);
48417 function calculateLoc(node, text) {
48419 node.source.startOffset = calculateLocStart(node, text);
48420 node.source.endOffset = calculateLocEnd(node, text);
48423 for (const key in node) {
48424 const child = node[key];
48426 if (key === "source" || !child || typeof child !== "object") {
48430 if (child.type === "value-root" || child.type === "value-unknown") {
48431 calculateValueNodeLoc(child, getValueRootOffset(node), child.text || child.value);
48433 calculateLoc(child, text);
48438 function calculateValueNodeLoc(node, rootOffset, text) {
48440 node.source.startOffset = calculateLocStart(node, text) + rootOffset;
48441 node.source.endOffset = calculateLocEnd(node, text) + rootOffset;
48444 for (const key in node) {
48445 const child = node[key];
48447 if (key === "source" || !child || typeof child !== "object") {
48451 calculateValueNodeLoc(child, rootOffset, text);
48455 function getValueRootOffset(node) {
48456 let result = node.source.startOffset;
48458 if (typeof node.prop === "string") {
48459 result += node.prop.length;
48462 if (node.type === "css-atrule" && typeof node.name === "string") {
48463 result += 1 + node.name.length + node.raws.afterName.match(/^\s*:?\s*/)[0].length;
48466 if (node.type !== "css-atrule" && node.raws && typeof node.raws.between === "string") {
48467 result += node.raws.between.length;
48473 * Workaround for a bug: quotes and asterisks in inline comments corrupt loc data of subsequent nodes.
48474 * This function replaces the quotes and asterisks with spaces. Later, when the comments are printed,
48475 * their content is extracted from the original text.
48476 * - https://github.com/prettier/prettier/issues/7780
48477 * - https://github.com/shellscape/postcss-less/issues/145
48478 * - https://github.com/prettier/prettier/issues/8130
48479 * @param text {string}
48483 function replaceQuotesInInlineComments(text) {
48484 /** @typedef { 'initial' | 'single-quotes' | 'double-quotes' | 'url' | 'comment-block' | 'comment-inline' } State */
48486 /** @type {State} */
48487 let state = "initial";
48488 /** @type {State} */
48490 let stateToReturnFromQuotes = "initial";
48491 let inlineCommentStartIndex;
48492 let inlineCommentContainsQuotes = false;
48493 const inlineCommentsToReplace = [];
48495 for (let i = 0; i < text.length; i++) {
48501 state = "single-quotes";
48506 state = "double-quotes";
48510 if ((c === "u" || c === "U") && text.slice(i, i + 4).toLowerCase() === "url(") {
48516 if (c === "*" && text[i - 1] === "/") {
48517 state = "comment-block";
48521 if (c === "/" && text[i - 1] === "/") {
48522 state = "comment-inline";
48523 inlineCommentStartIndex = i - 1;
48529 case "single-quotes":
48530 if (c === "'" && text[i - 1] !== "\\") {
48531 state = stateToReturnFromQuotes;
48532 stateToReturnFromQuotes = "initial";
48535 if (c === "\n" || c === "\r") {
48536 return text; // invalid input
48541 case "double-quotes":
48542 if (c === '"' && text[i - 1] !== "\\") {
48543 state = stateToReturnFromQuotes;
48544 stateToReturnFromQuotes = "initial";
48547 if (c === "\n" || c === "\r") {
48548 return text; // invalid input
48558 if (c === "\n" || c === "\r") {
48559 return text; // invalid input
48563 state = "single-quotes";
48564 stateToReturnFromQuotes = "url";
48569 state = "double-quotes";
48570 stateToReturnFromQuotes = "url";
48576 case "comment-block":
48577 if (c === "/" && text[i - 1] === "*") {
48583 case "comment-inline":
48584 if (c === '"' || c === "'" || c === "*") {
48585 inlineCommentContainsQuotes = true;
48588 if (c === "\n" || c === "\r") {
48589 if (inlineCommentContainsQuotes) {
48590 inlineCommentsToReplace.push([inlineCommentStartIndex, i]);
48594 inlineCommentContainsQuotes = false;
48601 for (const [start, end] of inlineCommentsToReplace) {
48602 text = text.slice(0, start) + text.slice(start, end).replace(/["'*]/g, " ") + text.slice(end);
48608 function locStart$9(node) {
48609 return node.source.startOffset;
48612 function locEnd$f(node) {
48613 return node.source.endOffset;
48617 locStart: locStart$9,
48620 replaceQuotesInInlineComments
48624 printNumber: printNumber$3,
48625 printString: printString$3,
48626 hasNewline: hasNewline$8,
48627 isFrontMatterNode: isFrontMatterNode$2,
48628 isNextLineEmpty: isNextLineEmpty$a
48635 hardline: hardline$o,
48636 softline: softline$i,
48641 ifBreak: ifBreak$e,
48642 breakParent: breakParent$5
48645 removeLines: removeLines$2
48649 insertPragma: insertPragma$3
48652 getAncestorNode: getAncestorNode$1,
48653 getPropOfDeclNode: getPropOfDeclNode$1,
48654 maybeToLowerCase: maybeToLowerCase$1,
48655 insideValueFunctionNode: insideValueFunctionNode$1,
48656 insideICSSRuleNode: insideICSSRuleNode$1,
48657 insideAtRuleNode: insideAtRuleNode$1,
48658 insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1,
48659 isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1,
48660 isWideKeywords: isWideKeywords$1,
48662 isLastNode: isLastNode$1,
48663 isLessParser: isLessParser$1,
48664 isSCSSControlDirectiveNode: isSCSSControlDirectiveNode$1,
48665 isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode$1,
48666 isRelationalOperatorNode: isRelationalOperatorNode$1,
48667 isEqualityOperatorNode: isEqualityOperatorNode$1,
48668 isMultiplicationNode: isMultiplicationNode$1,
48669 isDivisionNode: isDivisionNode$1,
48670 isAdditionNode: isAdditionNode$1,
48671 isSubtractionNode: isSubtractionNode$1,
48672 isMathOperatorNode: isMathOperatorNode$1,
48673 isEachKeywordNode: isEachKeywordNode$1,
48674 isForKeywordNode: isForKeywordNode$1,
48675 isURLFunctionNode: isURLFunctionNode$1,
48676 isIfElseKeywordNode: isIfElseKeywordNode$1,
48677 hasComposesNode: hasComposesNode$1,
48678 hasParensAroundNode: hasParensAroundNode$1,
48679 hasEmptyRawBefore: hasEmptyRawBefore$1,
48680 isKeyValuePairNode: isKeyValuePairNode$1,
48681 isDetachedRulesetCallNode: isDetachedRulesetCallNode$1,
48682 isTemplatePlaceholderNode: isTemplatePlaceholderNode$1,
48683 isTemplatePropNode: isTemplatePropNode$1,
48684 isPostcssSimpleVarNode: isPostcssSimpleVarNode$1,
48685 isSCSSMapItemNode: isSCSSMapItemNode$1,
48686 isInlineValueCommentNode: isInlineValueCommentNode$1,
48687 isHashNode: isHashNode$1,
48688 isLeftCurlyBraceNode: isLeftCurlyBraceNode$1,
48689 isRightCurlyBraceNode: isRightCurlyBraceNode$1,
48690 isWordNode: isWordNode$1,
48691 isColonNode: isColonNode$1,
48692 isMediaAndSupportsKeywords: isMediaAndSupportsKeywords$1,
48693 isColorAdjusterFuncNode: isColorAdjusterFuncNode$1,
48694 lastLineHasInlineComment: lastLineHasInlineComment$1,
48695 isAtWordPlaceholderNode: isAtWordPlaceholderNode$1
48698 locStart: locStart$a,
48702 function shouldPrintComma$9(options) {
48703 return options.trailingComma === "es5" || options.trailingComma === "all";
48706 function genericPrint$2(path, options, print) {
48707 const node = path.getValue();
48708 /* istanbul ignore if */
48714 if (typeof node === "string") {
48718 switch (node.type) {
48719 case "front-matter":
48720 return concat$B([node.raw, hardline$o]);
48724 const nodes = printNodeSequence(path, options, print);
48725 const after = node.raws.after.trim();
48726 return concat$B([nodes, after ? ` ${after}` : "", nodes.parts.length ? hardline$o : ""]);
48729 case "css-comment":
48731 const isInlineComment = node.inline || node.raws.inline;
48732 const text = options.originalText.slice(locStart$a(node), locEnd$g(node));
48733 return isInlineComment ? text.trimEnd() : text;
48738 return concat$B([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$B([node.selector && node.selector.type === "selector-unknown" && lastLineHasInlineComment$1(node.selector.value) ? line$k : " ", "{", node.nodes.length > 0 ? indent$r(concat$B([hardline$o, printNodeSequence(path, options, print)])) : "", hardline$o, "}", isDetachedRulesetDeclarationNode$1(node) ? ";" : ""]) : ";"]);
48743 const parentNode = path.getParentNode();
48745 between: rawBetween
48747 const trimmedBetween = rawBetween.trim();
48748 const isColon = trimmedBetween === ":";
48749 let value = hasComposesNode$1(node) ? removeLines$2(path.call(print, "value")) : path.call(print, "value");
48751 if (!isColon && lastLineHasInlineComment$1(trimmedBetween)) {
48752 value = indent$r(concat$B([hardline$o, dedent$2(value)]));
48755 return concat$B([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode$1(path) ? node.prop : maybeToLowerCase$1(node.prop), trimmedBetween.startsWith("//") ? " " : "", trimmedBetween, node.extend ? "" : " ", isLessParser$1(options) && node.extend && node.selector ? concat$B(["extend(", path.call(print, "selector"), ")"]) : "", 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$B([" {", indent$r(concat$B([softline$i, printNodeSequence(path, options, print)])), softline$i, "}"]) : isTemplatePropNode$1(node) && !parentNode.raws.semicolon && options.originalText[locEnd$g(node) - 1] !== ";" ? "" : options.__isHTMLStyleAttribute && isLastNode$1(path, node) ? ifBreak$e(";", "") : ";"]);
48760 const parentNode = path.getParentNode();
48761 const isTemplatePlaceholderNodeWithoutSemiColon = isTemplatePlaceholderNode$1(node) && !parentNode.raws.semicolon && options.originalText[locEnd$g(node) - 1] !== ";";
48763 if (isLessParser$1(options)) {
48765 return concat$B([path.call(print, "selector"), node.important ? " !important" : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
48768 if (node.function) {
48769 return concat$B([node.name, concat$B([path.call(print, "params")]), isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
48772 if (node.variable) {
48773 return concat$B(["@", node.name, ": ", node.value ? concat$B([path.call(print, "value")]) : "", node.raws.between.trim() ? node.raws.between.trim() + " " : "", node.nodes ? concat$B(["{", indent$r(concat$B([node.nodes.length > 0 ? softline$i : "", printNodeSequence(path, options, print)])), softline$i, "}"]) : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
48777 return concat$B(["@", // If a Less file ends up being parsed with the SCSS parser, Less
48778 // variable declarations will be parsed as at-rules with names ending
48779 // with a colon, so keep the original case then.
48780 isDetachedRulesetCallNode$1(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase$1(node.name), node.params ? concat$B([isDetachedRulesetCallNode$1(node) ? "" : isTemplatePlaceholderNode$1(node) ? node.raws.afterName === "" ? "" : node.name.endsWith(":") ? " " : /^\s*\n\s*\n/.test(node.raws.afterName) ? concat$B([hardline$o, hardline$o]) : /^\s*\n/.test(node.raws.afterName) ? hardline$o : " " : " ", path.call(print, "params")]) : "", node.selector ? indent$r(concat$B([" ", path.call(print, "selector")])) : "", node.value ? group$p(concat$B([" ", path.call(print, "value"), isSCSSControlDirectiveNode$1(node) ? hasParensAroundNode$1(node) ? " " : line$k : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$B([isSCSSControlDirectiveNode$1(node) ? "" : node.selector && !node.selector.nodes && typeof node.selector.value === "string" && lastLineHasInlineComment$1(node.selector.value) || !node.selector && typeof node.params === "string" && lastLineHasInlineComment$1(node.params) ? line$k : " ", "{", indent$r(concat$B([node.nodes.length > 0 ? softline$i : "", printNodeSequence(path, options, print)])), softline$i, "}"]) : isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
48782 // postcss-media-query-parser
48784 case "media-query-list":
48787 path.each(childPath => {
48788 const node = childPath.getValue();
48790 if (node.type === "media-query" && node.value === "") {
48794 parts.push(childPath.call(print));
48796 return group$p(indent$r(join$h(line$k, parts)));
48799 case "media-query":
48801 return concat$B([join$h(" ", path.map(print, "nodes")), isLastNode$1(path, node) ? "" : ","]);
48806 return adjustNumbers(adjustStrings(node.value, options));
48809 case "media-feature-expression":
48815 return concat$B(["(", concat$B(path.map(print, "nodes")), ")"]);
48818 case "media-feature":
48820 return maybeToLowerCase$1(adjustStrings(node.value.replace(/ +/g, " "), options));
48823 case "media-colon":
48825 return concat$B([node.value, " "]);
48828 case "media-value":
48830 return adjustNumbers(adjustStrings(node.value, options));
48833 case "media-keyword":
48835 return adjustStrings(node.value, options);
48840 return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options);
48843 case "media-unknown":
48847 // postcss-selector-parser
48849 case "selector-root":
48851 return group$p(concat$B([insideAtRuleNode$1(path, "custom-selector") ? concat$B([getAncestorNode$1(path, "css-atrule").customSelector, line$k]) : "", join$h(concat$B([",", insideAtRuleNode$1(path, ["extend", "custom-selector", "nest"]) ? line$k : hardline$o]), path.map(print, "nodes"))]));
48854 case "selector-selector":
48856 return group$p(indent$r(concat$B(path.map(print, "nodes"))));
48859 case "selector-comment":
48864 case "selector-string":
48866 return adjustStrings(node.value, options);
48869 case "selector-tag":
48871 const parentNode = path.getParentNode();
48872 const index = parentNode && parentNode.nodes.indexOf(node);
48873 const prevNode = index && parentNode.nodes[index - 1];
48874 return concat$B([node.namespace ? concat$B([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isKeyframeAtRuleKeywords$1(path, node.value) ? node.value.toLowerCase() : node.value)]);
48877 case "selector-id":
48879 return concat$B(["#", node.value]);
48882 case "selector-class":
48884 return concat$B([".", adjustNumbers(adjustStrings(node.value, options))]);
48887 case "selector-attribute":
48889 return concat$B(["[", node.namespace ? concat$B([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" : "", "]"]);
48892 case "selector-combinator":
48894 if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") {
48895 const parentNode = path.getParentNode();
48896 const leading = parentNode.type === "selector-selector" && parentNode.nodes[0] === node ? "" : line$k;
48897 return concat$B([leading, node.value, isLastNode$1(path, node) ? "" : " "]);
48900 const leading = node.value.trim().startsWith("(") ? line$k : "";
48901 const value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$k;
48902 return concat$B([leading, value]);
48905 case "selector-universal":
48907 return concat$B([node.namespace ? concat$B([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]);
48910 case "selector-pseudo":
48912 return concat$B([maybeToLowerCase$1(node.value), node.nodes && node.nodes.length > 0 ? concat$B(["(", join$h(", ", path.map(print, "nodes")), ")"]) : ""]);
48915 case "selector-nesting":
48920 case "selector-unknown":
48922 const ruleAncestorNode = getAncestorNode$1(path, "css-rule"); // Nested SCSS property
48924 if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) {
48925 return adjustNumbers(adjustStrings(maybeToLowerCase$1(node.value), options));
48926 } // originalText has to be used for Less, see replaceQuotesInInlineComments in loc.js
48929 const parentNode = path.getParentNode();
48931 if (parentNode.raws && parentNode.raws.selector) {
48932 const start = locStart$a(parentNode);
48933 const end = start + parentNode.raws.selector.length;
48934 return options.originalText.slice(start, end).trim();
48935 } // Same reason above
48938 const grandParent = path.getParentNode(1);
48940 if (parentNode.type === "value-paren_group" && grandParent && grandParent.type === "value-func" && grandParent.value === "selector") {
48941 const start = locStart$a(parentNode.open) + 1;
48942 const end = locEnd$g(parentNode.close) - 1;
48943 const selector = options.originalText.slice(start, end).trim();
48944 return lastLineHasInlineComment$1(selector) ? concat$B([breakParent$5, selector]) : selector;
48949 // postcss-values-parser
48951 case "value-value":
48954 return path.call(print, "group");
48957 case "value-comment":
48959 return options.originalText.slice(locStart$a(node), locEnd$g(node));
48962 case "value-comma_group":
48964 const parentNode = path.getParentNode();
48965 const parentParentNode = path.getParentNode(1);
48966 const declAncestorProp = getPropOfDeclNode$1(path);
48967 const isGridValue = declAncestorProp && parentNode.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template"));
48968 const atRuleAncestorNode = getAncestorNode$1(path, "css-atrule");
48969 const isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode$1(atRuleAncestorNode);
48970 const printed = path.map(print, "groups");
48972 const insideURLFunction = insideValueFunctionNode$1(path, "url");
48973 let insideSCSSInterpolationInString = false;
48974 let didBreak = false;
48976 for (let i = 0; i < node.groups.length; ++i) {
48977 parts.push(printed[i]);
48978 const iPrevNode = node.groups[i - 1];
48979 const iNode = node.groups[i];
48980 const iNextNode = node.groups[i + 1];
48981 const iNextNextNode = node.groups[i + 2];
48983 if (insideURLFunction) {
48984 if (iNextNode && isAdditionNode$1(iNextNode) || isAdditionNode$1(iNode)) {
48989 } // Ignore after latest node (i.e. before semicolon)
48994 } // styled.div` background: var(--${one}); `
48997 if (iNode.type === "value-word" && iNode.value.endsWith("-") && isAtWordPlaceholderNode$1(iNextNode)) {
48999 } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`)
49002 const isStartSCSSInterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{");
49003 const isEndingSCSSInterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}");
49005 if (isStartSCSSInterpolationInString || isEndingSCSSInterpolationInString) {
49006 insideSCSSInterpolationInString = !insideSCSSInterpolationInString;
49010 if (insideSCSSInterpolationInString) {
49012 } // Ignore colon (i.e. `:`)
49015 if (isColonNode$1(iNode) || isColonNode$1(iNextNode)) {
49017 } // Ignore `@` in Less (i.e. `@@var;`)
49020 if (iNode.type === "value-atword" && iNode.value === "") {
49022 } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`)
49025 if (iNode.value === "~") {
49027 } // Ignore escape `\`
49030 if (iNode.value && iNode.value.includes("\\") && iNextNode && iNextNode.type !== "value-comment") {
49032 } // Ignore escaped `/`
49035 if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") {
49037 } // Ignore `\` (i.e. `$variable: \@small;`)
49040 if (iNode.value === "\\") {
49042 } // Ignore `$$` (i.e. `background-color: $$(style)Color;`)
49045 if (isPostcssSimpleVarNode$1(iNode, iNextNode)) {
49047 } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`)
49050 if (isHashNode$1(iNode) || isLeftCurlyBraceNode$1(iNode) || isRightCurlyBraceNode$1(iNextNode) || isLeftCurlyBraceNode$1(iNextNode) && hasEmptyRawBefore$1(iNextNode) || isRightCurlyBraceNode$1(iNode) && hasEmptyRawBefore$1(iNextNode)) {
49052 } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`)
49055 if (iNode.value === "--" && isHashNode$1(iNextNode)) {
49057 } // Formatting math operations
49060 const isMathOperator = isMathOperatorNode$1(iNode);
49061 const isNextMathOperator = isMathOperatorNode$1(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is
49062 // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`)
49063 // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`)
49065 if ((isMathOperator && isHashNode$1(iNextNode) || isNextMathOperator && isRightCurlyBraceNode$1(iNode)) && hasEmptyRawBefore$1(iNextNode)) {
49067 } // Print spaces before and after addition and subtraction math operators as is in `calc` function
49068 // due to the fact that it is not valid syntax
49069 // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`)
49072 if (insideValueFunctionNode$1(path, "calc") && (isAdditionNode$1(iNode) || isAdditionNode$1(iNextNode) || isSubtractionNode$1(iNode) || isSubtractionNode$1(iNextNode)) && hasEmptyRawBefore$1(iNextNode)) {
49074 } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`)
49075 // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is.
49078 const isColorAdjusterNode = (isAdditionNode$1(iNode) || isSubtractionNode$1(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode$1(parentParentNode) && !hasEmptyRawBefore$1(iNextNode);
49079 const requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode$1(iNextNextNode) || iNode.type === "value-func" || isWordNode$1(iNode);
49080 const requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode$1(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode$1(iPrevNode); // Formatting `/`, `+`, `-` sign
49082 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)))) {
49084 } // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`)
49087 if (isInlineValueCommentNode$1(iNode)) {
49088 if (parentNode.type === "value-paren_group") {
49089 parts.push(dedent$2(hardline$o));
49093 parts.push(hardline$o);
49095 } // Handle keywords in SCSS control directive
49098 if (isControlDirective && (isEqualityOperatorNode$1(iNextNode) || isRelationalOperatorNode$1(iNextNode) || isIfElseKeywordNode$1(iNextNode) || isEachKeywordNode$1(iNode) || isForKeywordNode$1(iNode))) {
49101 } // At-rule `namespace` should be in one line
49104 if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") {
49107 } // Formatting `grid` property
49111 if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) {
49112 parts.push(hardline$o);
49119 } // Add `space` before next math operation
49120 // Note: `grip` property have `/` delimiter and it is not math operation, so
49121 // `grid` property handles above
49124 if (isNextMathOperator) {
49127 } // allow function(returns-list($list)...)
49130 if (iNextNode && iNextNode.value === "...") {
49134 if (isAtWordPlaceholderNode$1(iNode) && isAtWordPlaceholderNode$1(iNextNode) && locEnd$g(iNode) === locStart$a(iNextNode)) {
49136 } // Be default all values go through `line`
49139 parts.push(line$k);
49143 parts.unshift(hardline$o);
49146 if (isControlDirective) {
49147 return group$p(indent$r(concat$B(parts)));
49148 } // Indent is not needed for import url when url is very long
49149 // and node has two groups
49150 // when type is value-comma_group
49151 // example @import url("verylongurl") projection,tv
49154 if (insideURLFunctionInImportAtRuleNode$1(path)) {
49155 return group$p(fill$4(parts));
49158 return group$p(indent$r(fill$4(parts)));
49161 case "value-paren_group":
49163 const parentNode = path.getParentNode();
49165 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:"))) {
49166 return concat$B([node.open ? path.call(print, "open") : "", join$h(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]);
49170 const printed = path.map(print, "groups");
49173 for (let i = 0; i < printed.length; i++) {
49175 res.push(concat$B([",", line$k]));
49178 res.push(printed[i]);
49181 return group$p(indent$r(fill$4(res)));
49184 const isSCSSMapItem = isSCSSMapItemNode$1(path);
49185 const lastItem = node.groups[node.groups.length - 1];
49186 const isLastItemComment = lastItem && lastItem.type === "value-comment";
49187 return group$p(concat$B([node.open ? path.call(print, "open") : "", indent$r(concat$B([softline$i, join$h(concat$B([",", line$k]), path.map(childPath => {
49188 const node = childPath.getValue();
49189 const printed = print(childPath); // Key/Value pair in open paren already indented
49191 if (isKeyValuePairNode$1(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") {
49192 printed.contents.contents.parts[1] = group$p(printed.contents.contents.parts[1]);
49193 return group$p(dedent$2(printed));
49197 }, "groups"))])), ifBreak$e(!isLastItemComment && isSCSS$1(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma$9(options) ? "," : ""), softline$i, node.close ? path.call(print, "close") : ""]), {
49198 shouldBreak: isSCSSMapItem
49204 return concat$B([node.value, insideAtRuleNode$1(path, "supports") && isMediaAndSupportsKeywords$1(node) ? " " : "", path.call(print, "group")]);
49207 case "value-paren":
49212 case "value-number":
49214 return concat$B([printCssNumber(node.value), maybeToLowerCase$1(node.unit)]);
49217 case "value-operator":
49224 if (node.isColor && node.isHex || isWideKeywords$1(node.value)) {
49225 return node.value.toLowerCase();
49231 case "value-colon":
49233 const parentNode = path.getParentNode();
49234 const index = parentNode && parentNode.groups.indexOf(node);
49235 const prevNode = index && parentNode.groups[index - 1];
49236 return concat$B([node.value, // Don't add spaces on escaped colon `:`, e.g: grid-template-rows: [row-1-00\:00] auto;
49237 prevNode && prevNode.value[prevNode.value.length - 1] === "\\" || // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`)
49238 insideValueFunctionNode$1(path, "url") ? "" : line$k]);
49240 // TODO: confirm this code is dead
49242 /* istanbul ignore next */
49244 case "value-comma":
49246 return concat$B([node.value, " "]);
49249 case "value-string":
49251 return printString$3(node.raws.quote + node.value + node.raws.quote, options);
49254 case "value-atword":
49256 return concat$B(["@", node.value]);
49259 case "value-unicode-range":
49264 case "value-unknown":
49270 /* istanbul ignore next */
49271 throw new Error(`Unknown postcss type ${JSON.stringify(node.type)}`);
49275 function printNodeSequence(path, options, print) {
49276 const node = path.getValue();
49278 path.each((pathChild, i) => {
49279 const prevNode = node.nodes[i - 1];
49281 if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") {
49282 const childNode = pathChild.getValue();
49283 parts.push(options.originalText.slice(locStart$a(childNode), locEnd$g(childNode)));
49285 parts.push(pathChild.call(print));
49288 if (i !== node.nodes.length - 1) {
49289 if (node.nodes[i + 1].type === "css-comment" && !hasNewline$8(options.originalText, locStart$a(node.nodes[i + 1]), {
49291 }) && !isFrontMatterNode$2(node.nodes[i]) || node.nodes[i + 1].type === "css-atrule" && node.nodes[i + 1].name === "else" && node.nodes[i].type !== "css-comment") {
49294 parts.push(options.__isHTMLStyleAttribute ? line$k : hardline$o);
49296 if (isNextLineEmpty$a(options.originalText, pathChild.getValue(), locEnd$g) && !isFrontMatterNode$2(node.nodes[i])) {
49297 parts.push(hardline$o);
49302 return concat$B(parts);
49305 const STRING_REGEX$3 = /(["'])(?:(?!\1)[^\\]|\\[\S\s])*\1/g;
49306 const NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[Ee][+-]?\d+)?/g;
49307 const STANDARD_UNIT_REGEX = /[A-Za-z]+/g;
49308 const WORD_PART_REGEX = /[$@]?[A-Z_a-z\u0080-\uFFFF][\w\u0080-\uFFFF-]*/g;
49309 const ADJUST_NUMBERS_REGEX = new RegExp(STRING_REGEX$3.source + "|" + `(${WORD_PART_REGEX.source})?` + `(${NUMBER_REGEX.source})` + `(${STANDARD_UNIT_REGEX.source})?`, "g");
49311 function adjustStrings(value, options) {
49312 return value.replace(STRING_REGEX$3, match => printString$3(match, options));
49315 function quoteAttributeValue(value, options) {
49316 const quote = options.singleQuote ? "'" : '"';
49317 return value.includes('"') || value.includes("'") ? value : quote + value + quote;
49320 function adjustNumbers(value) {
49321 return value.replace(ADJUST_NUMBERS_REGEX, (match, quote, wordPart, number, unit) => !wordPart && number ? printCssNumber(number) + maybeToLowerCase$1(unit || "") : match);
49324 function printCssNumber(rawNumber) {
49325 return printNumber$3(rawNumber) // Remove trailing `.0`.
49326 .replace(/\.0(?=$|e)/, "");
49329 var printerPostcss = {
49330 print: genericPrint$2,
49332 insertPragma: insertPragma$3,
49333 massageAstNode: clean_1$1
49337 singleQuote: commonOptions.singleQuote
49340 var name$9 = "CSS";
49341 var type$7 = "markup";
49342 var tmScope$7 = "source.css";
49343 var aceMode$7 = "css";
49344 var codemirrorMode$7 = "css";
49345 var codemirrorMimeType$7 = "text/css";
49346 var color$2 = "#563d7c";
49347 var extensions$7 = [
49350 var languageId$7 = 50;
49351 var require$$0$3 = {
49354 tmScope: tmScope$7,
49355 aceMode: aceMode$7,
49356 codemirrorMode: codemirrorMode$7,
49357 codemirrorMimeType: codemirrorMimeType$7,
49359 extensions: extensions$7,
49360 languageId: languageId$7
49363 var name$a = "PostCSS";
49364 var type$8 = "markup";
49365 var tmScope$8 = "source.postcss";
49366 var group$q = "CSS";
49367 var extensions$8 = [
49371 var aceMode$8 = "text";
49372 var languageId$8 = 262764437;
49373 var require$$1$1 = {
49376 tmScope: tmScope$8,
49378 extensions: extensions$8,
49379 aceMode: aceMode$8,
49380 languageId: languageId$8
49383 var name$b = "Less";
49384 var type$9 = "markup";
49385 var color$3 = "#1d365d";
49386 var extensions$9 = [
49389 var tmScope$9 = "source.css.less";
49390 var aceMode$9 = "less";
49391 var codemirrorMode$8 = "css";
49392 var codemirrorMimeType$8 = "text/css";
49393 var languageId$9 = 198;
49394 var require$$2$1 = {
49398 extensions: extensions$9,
49399 tmScope: tmScope$9,
49400 aceMode: aceMode$9,
49401 codemirrorMode: codemirrorMode$8,
49402 codemirrorMimeType: codemirrorMimeType$8,
49403 languageId: languageId$9
49406 var name$c = "SCSS";
49407 var type$a = "markup";
49408 var color$4 = "#c6538c";
49409 var tmScope$a = "source.css.scss";
49410 var aceMode$a = "scss";
49411 var codemirrorMode$9 = "css";
49412 var codemirrorMimeType$9 = "text/x-scss";
49413 var extensions$a = [
49416 var languageId$a = 329;
49417 var require$$3$1 = {
49421 tmScope: tmScope$a,
49422 aceMode: aceMode$a,
49423 codemirrorMode: codemirrorMode$9,
49424 codemirrorMimeType: codemirrorMimeType$9,
49425 extensions: extensions$a,
49426 languageId: languageId$a
49429 const languages$1 = [createLanguage(require$$0$3, data => ({
49432 vscodeLanguageIds: ["css"],
49433 extensions: [...data.extensions, // `WeiXin Style Sheets`(Weixin Mini Programs)
49434 // https://developers.weixin.qq.com/miniprogram/en/dev/framework/view/wxs/
49436 })), createLanguage(require$$1$1, () => ({
49439 vscodeLanguageIds: ["postcss"]
49440 })), createLanguage(require$$2$1, () => ({
49443 vscodeLanguageIds: ["less"]
49444 })), createLanguage(require$$3$1, () => ({
49447 vscodeLanguageIds: ["scss"]
49449 const printers$1 = {
49450 postcss: printerPostcss
49452 const parsers$1 = {
49453 // TODO: switch these to just `postcss` and use `language` instead.
49455 return require("./parser-postcss").parsers.css;
49459 return require("./parser-postcss").parsers.less;
49463 return require("./parser-postcss").parsers.scss;
49467 var languageCss = {
49468 languages: languages$1,
49469 options: options$3,
49470 printers: printers$1,
49474 function locStart$b(node) {
49475 return node.loc.start.offset;
49478 function locEnd$h(node) {
49479 return node.loc.end.offset;
49483 locStart: locStart$b,
49487 function clean$3(ast, newNode
49490 // (Glimmer/HTML) ignore TextNode whitespace
49491 if (ast.type === "TextNode") {
49492 const trimmed = ast.chars.trim();
49498 newNode.chars = trimmed;
49502 clean$3.ignoredProperties = new Set(["loc", "selfClosing"]);
49503 var clean_1$2 = clean$3;
49505 var htmlVoidElements = [
49531 function isUppercase(string) {
49532 return string.toUpperCase() === string;
49535 function isGlimmerComponent(node) {
49536 return isNodeOfSomeType(node, ["ElementNode"]) && typeof node.tag === "string" && (isUppercase(node.tag[0]) || node.tag.includes("."));
49539 const voidTags = new Set(htmlVoidElements);
49541 function isVoid(node) {
49542 return isGlimmerComponent(node) && node.children.every(n => isWhitespaceNode(n)) || voidTags.has(node.tag);
49545 function isWhitespaceNode(node) {
49546 return isNodeOfSomeType(node, ["TextNode"]) && !/\S/.test(node.chars);
49549 function isNodeOfSomeType(node, types) {
49550 return node && types.some(type => node.type === type);
49553 function isParentOfSomeType(path, types) {
49554 const parentNode = path.getParentNode(0);
49555 return isNodeOfSomeType(parentNode, types);
49558 function isPreviousNodeOfSomeType(path, types) {
49559 const previousNode = getPreviousNode(path);
49560 return isNodeOfSomeType(previousNode, types);
49563 function isNextNodeOfSomeType(path, types) {
49564 const nextNode = getNextNode(path);
49565 return isNodeOfSomeType(nextNode, types);
49568 function getSiblingNode(path, offset) {
49569 const node = path.getValue();
49570 const parentNode = path.getParentNode(0) || {};
49571 const children = parentNode.children || parentNode.body || parentNode.parts || [];
49572 const index = children.indexOf(node);
49573 return index !== -1 && children[index + offset];
49576 function getPreviousNode(path, lookBack = 1) {
49577 return getSiblingNode(path, -lookBack);
49580 function getNextNode(path) {
49581 return getSiblingNode(path, 1);
49584 function isPrettierIgnoreNode(node) {
49585 return isNodeOfSomeType(node, ["MustacheCommentStatement"]) && typeof node.value === "string" && node.value.trim() === "prettier-ignore";
49588 function hasPrettierIgnore$2(path) {
49589 const node = path.getValue();
49590 const previousPreviousNode = getPreviousNode(path, 2);
49591 return isPrettierIgnoreNode(node) || isPrettierIgnoreNode(previousPreviousNode);
49597 hasPrettierIgnore: hasPrettierIgnore$2,
49598 isNextNodeOfSomeType,
49600 isParentOfSomeType,
49601 isPreviousNodeOfSomeType,
49610 hardline: hardline$p,
49611 ifBreak: ifBreak$f,
49615 softline: softline$j
49619 locStart: locStart$c,
49623 getNextNode: getNextNode$1,
49624 getPreviousNode: getPreviousNode$1,
49625 hasPrettierIgnore: hasPrettierIgnore$3,
49626 isNextNodeOfSomeType: isNextNodeOfSomeType$1,
49627 isNodeOfSomeType: isNodeOfSomeType$1,
49628 isParentOfSomeType: isParentOfSomeType$1,
49629 isPreviousNodeOfSomeType: isPreviousNodeOfSomeType$1,
49631 isWhitespaceNode: isWhitespaceNode$1
49632 } = utils$8; // Formatter based on @glimmerjs/syntax's built-in test formatter:
49633 // https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts
49635 function print$2(path, options, print) {
49636 const n = path.getValue();
49637 /* istanbul ignore if*/
49643 if (hasPrettierIgnore$3(path)) {
49644 return options.originalText.slice(locStart$c(n), locEnd$i(n));
49652 return group$r(concat$C(path.map(print, "body")));
49655 case "ElementNode":
49657 // TODO: make it whitespace sensitive
49658 const bim = isNextNodeOfSomeType$1(path, ["ElementNode"]) ? hardline$p : "";
49661 return concat$C([group$r(printStartingTag(path, print)), bim]);
49664 const isWhitespaceOnly = n.children.every(n => isWhitespaceNode$1(n));
49665 return concat$C([group$r(printStartingTag(path, print)), group$r(concat$C([isWhitespaceOnly ? "" : indent$s(printChildren(path, options, print)), n.children.length ? hardline$p : "", concat$C(["</", n.tag, ">"])])), bim]);
49668 case "BlockStatement":
49670 const pp = path.getParentNode(1);
49671 const isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if";
49674 return concat$C([printElseIfBlock(path, print), printProgram(path, print), printInverse(path, print)]);
49677 return concat$C([printOpenBlock(path, print), group$r(concat$C([printProgram(path, print), printInverse(path, print), printCloseBlock(path, print)]))]);
49680 case "ElementModifierStatement":
49682 return group$r(concat$C(["{{", printPathAndParams(path, print), softline$j, "}}"]));
49685 case "MustacheStatement":
49687 const isParentOfSpecifiedTypes = isParentOfSomeType$1(path, ["AttrNode", "ConcatStatement"]);
49688 const isChildOfElementNodeAndDoesNotHaveParams = isParentOfSomeType$1(path, ["ElementNode"]) && doesNotHaveHashParams(n) && doesNotHavePositionalParams(n);
49689 const shouldBreakOpeningMustache = isParentOfSpecifiedTypes || isChildOfElementNodeAndDoesNotHaveParams;
49690 return group$r(concat$C([printOpeningMustache(n), shouldBreakOpeningMustache ? indent$s(softline$j) : "", printPathAndParams(path, print), softline$j, printClosingMustache(n)]));
49693 case "SubExpression":
49695 return group$r(concat$C(["(", printSubExpressionPathAndParams(path, print), softline$j, ")"]));
49700 const isText = n.value.type === "TextNode";
49701 const isEmptyText = isText && n.value.chars === ""; // If the text is empty and the value's loc start and end offsets are the
49702 // same, there is no value for this AttrNode and it should be printed
49703 // without the `=""`. Example: `<img data-test>` -> `<img data-test>`
49705 if (isEmptyText && locStart$c(n.value) === locEnd$i(n.value)) {
49706 return concat$C([n.name]);
49709 const value = path.call(print, "value");
49710 const quotedValue = isText ? printStringLiteral(value.parts.join(), options) : value;
49711 return concat$C([n.name, "=", quotedValue]);
49714 case "ConcatStatement":
49716 const quote = options.singleQuote ? "'" : '"';
49717 return concat$C([quote, ...path.map(partPath => print(partPath), "parts"), quote]);
49722 return concat$C([join$i(line$l, path.map(print, "pairs"))]);
49727 return concat$C([n.key, "=", path.call(print, "value")]);
49732 const maxLineBreaksToPreserve = 2;
49733 const isFirstElement = !getPreviousNode$1(path);
49734 const isLastElement = !getNextNode$1(path);
49735 const isWhitespaceOnly = !/\S/.test(n.chars);
49736 const lineBreaksCount = countNewLines(n.chars);
49737 let leadingLineBreaksCount = countLeadingNewLines(n.chars);
49738 let trailingLineBreaksCount = countTrailingNewLines(n.chars);
49740 if ((isFirstElement || isLastElement) && isWhitespaceOnly && isParentOfSomeType$1(path, ["Block", "ElementNode", "Template"])) {
49744 if (isWhitespaceOnly && lineBreaksCount) {
49745 leadingLineBreaksCount = Math.min(lineBreaksCount, maxLineBreaksToPreserve);
49746 trailingLineBreaksCount = 0;
49748 if (isNextNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) {
49749 trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1);
49752 if (isPreviousNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) {
49753 leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1);
49757 const inAttrNode = path.stack.includes("attributes");
49760 // TODO: format style and srcset attributes
49761 // and cleanup concat that is not necessary
49762 if (!isInAttributeOfName(path, "class")) {
49763 return concat$C([n.chars]);
49766 let leadingSpace = "";
49767 let trailingSpace = "";
49769 if (isParentOfSomeType$1(path, ["ConcatStatement"])) {
49770 if (isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) {
49771 leadingSpace = " ";
49774 if (isNextNodeOfSomeType$1(path, ["MustacheStatement"])) {
49775 trailingSpace = " ";
49779 return concat$C([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), n.chars.replace(/^\s+/g, leadingSpace).replace(/\s+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)]);
49782 let leadingSpace = "";
49783 let trailingSpace = "";
49785 if (trailingLineBreaksCount === 0 && isNextNodeOfSomeType$1(path, ["MustacheStatement"])) {
49786 trailingSpace = " ";
49789 if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) {
49790 leadingSpace = " ";
49793 if (isFirstElement) {
49794 leadingLineBreaksCount = 0;
49798 if (isLastElement) {
49799 trailingLineBreaksCount = 0;
49800 trailingSpace = "";
49803 let text = n.chars;
49804 /* if `{{my-component}}` (or any text starting with a mustache)
49805 * makes it to the TextNode,
49806 * it means it was escaped,
49807 * so let's print it escaped, ie.; `\{{my-component}}` */
49809 if (text.startsWith("{{") && text.includes("}}")) {
49810 text = "\\" + text;
49813 return concat$C([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), text.replace(/^\s+/g, leadingSpace).replace(/\s+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)]);
49816 case "MustacheCommentStatement":
49818 const dashes = n.value.includes("}}") ? "--" : "";
49819 return concat$C(["{{!", dashes, n.value, dashes, "}}"]);
49822 case "PathExpression":
49827 case "BooleanLiteral":
49829 return String(n.value);
49832 case "CommentStatement":
49834 return concat$C(["<!--", n.value, "-->"]);
49837 case "StringLiteral":
49839 return printStringLiteral(n.value, options);
49842 case "NumberLiteral":
49844 return String(n.value);
49847 case "UndefinedLiteral":
49849 return "undefined";
49852 case "NullLiteral":
49857 /* istanbul ignore next */
49860 throw new Error("unknown glimmer type: " + JSON.stringify(n.type));
49863 /* ElementNode print helpers */
49866 function printStartingTag(path, print) {
49867 const node = path.getValue();
49868 return concat$C(["<", node.tag, printAttributesLike(path, print), printBlockParams(node), printStartingTagEndMarker(node)]);
49871 function printAttributesLike(path, print) {
49872 const node = path.getValue();
49873 return indent$s(concat$C([node.attributes.length ? line$l : "", join$i(line$l, path.map(print, "attributes")), node.modifiers.length ? line$l : "", join$i(line$l, path.map(print, "modifiers")), node.comments.length ? line$l : "", join$i(line$l, path.map(print, "comments"))]));
49876 function printChildren(path, options, print) {
49877 return concat$C(path.map((childPath, childIndex) => {
49878 if (childIndex === 0) {
49879 return concat$C([softline$j, print(childPath, options, print)]);
49882 return print(childPath, options, print);
49886 function printStartingTagEndMarker(node) {
49887 if (isVoid$1(node)) {
49888 return ifBreak$f(concat$C([softline$j, "/>"]), concat$C([" />", softline$j]));
49891 return ifBreak$f(concat$C([softline$j, ">"]), ">");
49893 /* MustacheStatement print helpers */
49896 function printOpeningMustache(node) {
49897 const mustache = node.escaped === false ? "{{{" : "{{";
49898 const strip = node.strip && node.strip.open ? "~" : "";
49899 return concat$C([mustache, strip]);
49902 function printClosingMustache(node) {
49903 const mustache = node.escaped === false ? "}}}" : "}}";
49904 const strip = node.strip && node.strip.close ? "~" : "";
49905 return concat$C([strip, mustache]);
49907 /* BlockStatement print helpers */
49910 function printOpeningBlockOpeningMustache(node) {
49911 const opening = printOpeningMustache(node);
49912 const strip = node.openStrip.open ? "~" : "";
49913 return concat$C([opening, strip, "#"]);
49916 function printOpeningBlockClosingMustache(node) {
49917 const closing = printClosingMustache(node);
49918 const strip = node.openStrip.close ? "~" : "";
49919 return concat$C([strip, closing]);
49922 function printClosingBlockOpeningMustache(node) {
49923 const opening = printOpeningMustache(node);
49924 const strip = node.closeStrip.open ? "~" : "";
49925 return concat$C([opening, strip, "/"]);
49928 function printClosingBlockClosingMustache(node) {
49929 const closing = printClosingMustache(node);
49930 const strip = node.closeStrip.close ? "~" : "";
49931 return concat$C([strip, closing]);
49934 function printInverseBlockOpeningMustache(node) {
49935 const opening = printOpeningMustache(node);
49936 const strip = node.inverseStrip.open ? "~" : "";
49937 return concat$C([opening, strip]);
49940 function printInverseBlockClosingMustache(node) {
49941 const closing = printClosingMustache(node);
49942 const strip = node.inverseStrip.close ? "~" : "";
49943 return concat$C([strip, closing]);
49946 function printOpenBlock(path, print) {
49947 const node = path.getValue();
49948 return group$r(concat$C([printOpeningBlockOpeningMustache(node), printPathAndParams(path, print), printBlockParams(node.program), softline$j, printOpeningBlockClosingMustache(node)]));
49951 function printElseBlock(node) {
49952 return concat$C([hardline$p, printInverseBlockOpeningMustache(node), "else", printInverseBlockClosingMustache(node)]);
49955 function printElseIfBlock(path, print) {
49956 const parentNode = path.getParentNode(1);
49957 return concat$C([printInverseBlockOpeningMustache(parentNode), "else ", printPathAndParams(path, print), printInverseBlockClosingMustache(parentNode)]);
49960 function printCloseBlock(path, print) {
49961 const node = path.getValue();
49962 return concat$C([blockStatementHasOnlyWhitespaceInProgram(node) ? softline$j : hardline$p, printClosingBlockOpeningMustache(node), path.call(print, "path"), printClosingBlockClosingMustache(node)]);
49965 function blockStatementHasOnlyWhitespaceInProgram(node) {
49966 return isNodeOfSomeType$1(node, ["BlockStatement"]) && node.program.body.every(n => isWhitespaceNode$1(n));
49969 function blockStatementHasElseIf(node) {
49970 return blockStatementHasElse(node) && node.inverse.body.length === 1 && isNodeOfSomeType$1(node.inverse.body[0], ["BlockStatement"]) && node.inverse.body[0].path.parts[0] === "if";
49973 function blockStatementHasElse(node) {
49974 return isNodeOfSomeType$1(node, ["BlockStatement"]) && node.inverse;
49977 function printProgram(path, print) {
49978 const node = path.getValue();
49980 if (blockStatementHasOnlyWhitespaceInProgram(node)) {
49984 const program = path.call(print, "program");
49985 return indent$s(concat$C([hardline$p, program]));
49988 function printInverse(path, print) {
49989 const node = path.getValue();
49990 const inverse = path.call(print, "inverse");
49991 const parts = concat$C([hardline$p, inverse]);
49993 if (blockStatementHasElseIf(node)) {
49997 if (blockStatementHasElse(node)) {
49998 return concat$C([printElseBlock(node), indent$s(parts)]);
50003 /* TextNode print helpers */
50006 function isInAttributeOfName(path, type) {
50007 return isParentOfSomeType$1(path, ["AttrNode"]) && path.getParentNode().name.toLowerCase() === type || isParentOfSomeType$1(path, ["ConcatStatement"]) && path.getParentNode(1).name.toLowerCase() === type;
50010 function countNewLines(string) {
50011 /* istanbul ignore next */
50012 string = typeof string === "string" ? string : "";
50013 return string.split("\n").length - 1;
50016 function countLeadingNewLines(string) {
50017 /* istanbul ignore next */
50018 string = typeof string === "string" ? string : "";
50019 const newLines = (string.match(/^([^\S\n\r]*[\n\r])+/g) || [])[0] || "";
50020 return countNewLines(newLines);
50023 function countTrailingNewLines(string) {
50024 /* istanbul ignore next */
50025 string = typeof string === "string" ? string : "";
50026 const newLines = (string.match(/([\n\r][^\S\n\r]*)+$/g) || [])[0] || "";
50027 return countNewLines(newLines);
50030 function generateHardlines(number = 0, max = 0) {
50031 return new Array(Math.min(number, max)).fill(hardline$p);
50033 /* StringLiteral print helpers */
50036 * Prints a string literal with the correct surrounding quotes based on
50037 * `options.singleQuote` and the number of escaped quotes contained in
50038 * the string literal. This function is the glimmer equivalent of `printString`
50039 * in `common/util`, but has differences because of the way escaped characters
50040 * are treated in hbs string literals.
50041 * @param {string} stringLiteral - the string literal value
50042 * @param {object} options - the prettier options object
50046 function printStringLiteral(stringLiteral, options) {
50055 const preferred = options.singleQuote ? single : double;
50056 const alternate = preferred === single ? double : single;
50057 let shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for
50058 // enclosing the string, we might want to enclose with the alternate quote
50059 // instead, to minimize the number of escaped quotes.
50061 if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) {
50062 const numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length;
50063 const numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length;
50064 shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes;
50067 const enclosingQuote = shouldUseAlternateQuote ? alternate : preferred;
50068 const escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, `\\${enclosingQuote.quote}`);
50069 return concat$C([enclosingQuote.quote, escapedStringLiteral, enclosingQuote.quote]);
50071 /* SubExpression print helpers */
50074 function printSubExpressionPathAndParams(path, print) {
50075 const p = printPath(path, print);
50076 const params = printParams(path, print);
50082 return indent$s(concat$C([p, line$l, group$r(params)]));
50084 /* misc. print helpers */
50087 function printPathAndParams(path, print) {
50088 const p = printPath(path, print);
50089 const params = printParams(path, print);
50095 return indent$s(group$r(concat$C([p, line$l, params])));
50098 function printPath(path, print) {
50099 return path.call(print, "path");
50102 function printParams(path, print) {
50103 const node = path.getValue();
50106 if (node.params.length) {
50107 const params = path.map(print, "params");
50108 parts.push(...params);
50111 if (node.hash && node.hash.pairs.length > 0) {
50112 const hash = path.call(print, "hash");
50116 if (!parts.length) {
50120 return join$i(line$l, parts);
50123 function printBlockParams(node) {
50124 if (!node || !node.blockParams.length) {
50128 return concat$C([" as |", node.blockParams.join(" "), "|"]);
50131 function doesNotHaveHashParams(node) {
50132 return node.hash.pairs.length === 0;
50135 function doesNotHavePositionalParams(node) {
50136 return node.params.length === 0;
50139 var printerGlimmer = {
50141 massageAstNode: clean_1$2
50144 var name$d = "Handlebars";
50145 var type$b = "markup";
50146 var color$5 = "#f7931e";
50151 var extensions$b = [
50155 var tmScope$b = "text.html.handlebars";
50156 var aceMode$b = "handlebars";
50157 var languageId$b = 155;
50158 var require$$0$4 = {
50162 aliases: aliases$3,
50163 extensions: extensions$b,
50164 tmScope: tmScope$b,
50165 aceMode: aceMode$b,
50166 languageId: languageId$b
50169 const languages$2 = [createLanguage(require$$0$4, () => ({
50172 parsers: ["glimmer"],
50173 vscodeLanguageIds: ["handlebars"]
50175 const printers$2 = {
50176 glimmer: printerGlimmer
50178 const parsers$2 = {
50180 return require("./parser-glimmer").parsers.glimmer;
50184 var languageHandlebars = {
50185 languages: languages$2,
50186 printers: printers$2,
50190 function hasPragma$2(text) {
50191 return /^\s*#[^\S\n]*@(format|prettier)\s*(\n|$)/.test(text);
50194 function insertPragma$4(text) {
50195 return "# @format\n\n" + text;
50199 hasPragma: hasPragma$2,
50200 insertPragma: insertPragma$4
50203 function locStart$d(node) {
50204 if (typeof node.start === "number") {
50208 return node.loc && node.loc.start;
50211 function locEnd$j(node) {
50212 if (typeof node.end === "number") {
50216 return node.loc && node.loc.end;
50220 locStart: locStart$d,
50228 hardline: hardline$q,
50230 softline: softline$k,
50237 isNextLineEmpty: isNextLineEmpty$b
50240 insertPragma: insertPragma$5
50243 locStart: locStart$e,
50247 function genericPrint$3(path, options, print) {
50248 const n = path.getValue();
50254 if (typeof n === "string") {
50262 path.each((pathChild, index) => {
50263 parts.push(concat$D([pathChild.call(print)]));
50265 if (index !== n.definitions.length - 1) {
50266 parts.push(hardline$q);
50268 if (isNextLineEmpty$b(options.originalText, pathChild.getValue(), locEnd$k)) {
50269 parts.push(hardline$q);
50273 return concat$D([concat$D(parts), hardline$q]);
50276 case "OperationDefinition":
50278 const hasOperation = options.originalText[locStart$e(n)] !== "{";
50279 const hasName = !!n.name;
50280 return concat$D([hasOperation ? n.operation : "", hasOperation && hasName ? concat$D([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$s(concat$D(["(", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.map(print, "variableDefinitions"))])), softline$k, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]);
50283 case "FragmentDefinition":
50285 return concat$D(["fragment ", path.call(print, "name"), n.variableDefinitions && n.variableDefinitions.length ? group$s(concat$D(["(", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.map(print, "variableDefinitions"))])), softline$k, ")"])) : "", " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
50288 case "SelectionSet":
50290 return concat$D(["{", indent$t(concat$D([hardline$q, join$j(hardline$q, path.call(selectionsPath => printSequence(selectionsPath, options, print), "selections"))])), hardline$q, "}"]);
50295 return group$s(concat$D([n.alias ? concat$D([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$s(concat$D(["(", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$k, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")]));
50303 case "StringValue":
50306 return concat$D(['"""', hardline$q, join$j(hardline$q, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$q, '"""']);
50309 return concat$D(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']);
50319 case "BooleanValue":
50321 return n.value ? "true" : "false";
50331 return concat$D(["$", path.call(print, "name")]);
50336 return group$s(concat$D(["[", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.map(print, "values"))])), softline$k, "]"]));
50339 case "ObjectValue":
50341 return group$s(concat$D(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.map(print, "fields"))])), softline$k, ifBreak$g("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"]));
50344 case "ObjectField":
50347 return concat$D([path.call(print, "name"), ": ", path.call(print, "value")]);
50352 return concat$D(["@", path.call(print, "name"), n.arguments.length > 0 ? group$s(concat$D(["(", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$k, ")"])) : ""]);
50357 return path.call(print, "name");
50360 case "VariableDefinition":
50362 return concat$D([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$D([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
50365 case "ObjectTypeExtension":
50366 case "ObjectTypeDefinition":
50368 return concat$D([path.call(print, "description"), n.description ? hardline$q : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$D([" implements ", concat$D(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$D([" {", indent$t(concat$D([hardline$q, join$j(hardline$q, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$q, "}"]) : ""]);
50371 case "FieldDefinition":
50373 return concat$D([path.call(print, "description"), n.description ? hardline$q : "", path.call(print, "name"), n.arguments.length > 0 ? group$s(concat$D(["(", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$k, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]);
50376 case "DirectiveDefinition":
50378 return concat$D([path.call(print, "description"), n.description ? hardline$q : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$s(concat$D(["(", indent$t(concat$D([softline$k, join$j(concat$D([ifBreak$g("", ", "), softline$k]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$k, ")"])) : "", n.repeatable ? " repeatable" : "", concat$D([" on ", join$j(" | ", path.map(print, "locations"))])]);
50381 case "EnumTypeExtension":
50382 case "EnumTypeDefinition":
50384 return concat$D([path.call(print, "description"), n.description ? hardline$q : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$D([" {", indent$t(concat$D([hardline$q, join$j(hardline$q, path.call(valuesPath => printSequence(valuesPath, options, print), "values"))])), hardline$q, "}"]) : ""]);
50387 case "EnumValueDefinition":
50389 return concat$D([path.call(print, "description"), n.description ? hardline$q : "", path.call(print, "name"), printDirectives(path, print, n)]);
50392 case "InputValueDefinition":
50394 return concat$D([path.call(print, "description"), n.description ? n.description.block ? hardline$q : line$m : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$D([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
50397 case "InputObjectTypeExtension":
50398 case "InputObjectTypeDefinition":
50400 return concat$D([path.call(print, "description"), n.description ? hardline$q : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$D([" {", indent$t(concat$D([hardline$q, join$j(hardline$q, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$q, "}"]) : ""]);
50403 case "SchemaDefinition":
50405 return concat$D(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$t(concat$D([hardline$q, join$j(hardline$q, path.call(opsPath => printSequence(opsPath, options, print), "operationTypes"))])) : "", hardline$q, "}"]);
50408 case "OperationTypeDefinition":
50410 return concat$D([path.call(print, "operation"), ": ", path.call(print, "type")]);
50413 case "InterfaceTypeExtension":
50414 case "InterfaceTypeDefinition":
50416 return concat$D([path.call(print, "description"), n.description ? hardline$q : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), n.interfaces.length > 0 ? concat$D([" implements ", concat$D(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$D([" {", indent$t(concat$D([hardline$q, join$j(hardline$q, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$q, "}"]) : ""]);
50419 case "FragmentSpread":
50421 return concat$D(["...", path.call(print, "name"), printDirectives(path, print, n)]);
50424 case "InlineFragment":
50426 return concat$D(["...", n.typeCondition ? concat$D([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
50429 case "UnionTypeExtension":
50430 case "UnionTypeDefinition":
50432 return group$s(concat$D([path.call(print, "description"), n.description ? hardline$q : "", group$s(concat$D([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$D([" =", ifBreak$g("", " "), indent$t(concat$D([ifBreak$g(concat$D([line$m, " "])), join$j(concat$D([line$m, "| "]), path.map(print, "types"))]))]) : ""]))]));
50435 case "ScalarTypeExtension":
50436 case "ScalarTypeDefinition":
50438 return concat$D([path.call(print, "description"), n.description ? hardline$q : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]);
50441 case "NonNullType":
50443 return concat$D([path.call(print, "type"), "!"]);
50448 return concat$D(["[", path.call(print, "type"), "]"]);
50452 /* istanbul ignore next */
50453 throw new Error("unknown graphql type: " + JSON.stringify(n.kind));
50457 function printDirectives(path, print, n) {
50458 if (n.directives.length === 0) {
50462 const printed = join$j(line$m, path.map(print, "directives"));
50464 if (n.kind === "FragmentDefinition" || n.kind === "OperationDefinition") {
50465 return group$s(concat$D([line$m, printed]));
50468 return concat$D([" ", group$s(indent$t(concat$D([softline$k, printed])))]);
50471 function printSequence(sequencePath, options, print) {
50472 const count = sequencePath.getValue().length;
50473 return sequencePath.map((path, i) => {
50474 const printed = print(path);
50476 if (isNextLineEmpty$b(options.originalText, path.getValue(), locEnd$k) && i < count - 1) {
50477 return concat$D([printed, hardline$q]);
50484 function canAttachComment$1(node) {
50485 return node.kind && node.kind !== "Comment";
50488 function printComment$3(commentPath) {
50489 const comment = commentPath.getValue();
50491 if (comment.kind === "Comment") {
50492 return "#" + comment.value.trimEnd();
50494 /* istanbul ignore next */
50497 throw new Error("Not a comment: " + JSON.stringify(comment));
50500 function printInterfaces(path, options, print) {
50501 const node = path.getNode();
50506 const printed = path.map(node => print(node), "interfaces");
50508 for (let index = 0; index < interfaces.length; index++) {
50509 const interfaceNode = interfaces[index];
50510 parts.push(printed[index]);
50511 const nextInterfaceNode = interfaces[index + 1];
50513 if (nextInterfaceNode) {
50514 const textBetween = options.originalText.slice(interfaceNode.loc.end, nextInterfaceNode.loc.start);
50515 const hasComment = textBetween.includes("#");
50516 const separator = textBetween.replace(/#.*/g, "").trim();
50517 parts.push(separator === "," ? "," : " &");
50518 parts.push(hasComment ? line$m : " ");
50526 /*node, newNode , parent*/
50529 clean$4.ignoredProperties = new Set(["loc", "comments"]);
50531 function hasPrettierIgnore$4(path) {
50532 const node = path.getValue();
50533 return node && Array.isArray(node.comments) && node.comments.some(comment => comment.value.trim() === "prettier-ignore");
50536 var printerGraphql = {
50537 print: genericPrint$3,
50538 massageAstNode: clean$4,
50539 hasPrettierIgnore: hasPrettierIgnore$4,
50540 insertPragma: insertPragma$5,
50541 printComment: printComment$3,
50542 canAttachComment: canAttachComment$1
50546 bracketSpacing: commonOptions.bracketSpacing
50549 var name$e = "GraphQL";
50550 var type$c = "data";
50551 var color$6 = "#e10098";
50552 var extensions$c = [
50557 var tmScope$c = "source.graphql";
50558 var aceMode$c = "text";
50559 var languageId$c = 139;
50560 var require$$0$5 = {
50564 extensions: extensions$c,
50565 tmScope: tmScope$c,
50566 aceMode: aceMode$c,
50567 languageId: languageId$c
50570 const languages$3 = [createLanguage(require$$0$5, () => ({
50572 parsers: ["graphql"],
50573 vscodeLanguageIds: ["graphql"]
50575 const printers$3 = {
50576 graphql: printerGraphql
50578 const parsers$3 = {
50580 return require("./parser-graphql").parsers.graphql;
50584 var languageGraphql = {
50585 languages: languages$3,
50586 options: options$4,
50587 printers: printers$3,
50591 function locStart$f(node) {
50592 return node.position.start.offset;
50595 function locEnd$l(node) {
50596 return node.position.end.offset;
50600 locStart: locStart$f,
50605 "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])(?:[\\ufe00-\\ufe0f]|\\udb40[\\udd00-\\uddef])?",
50606 "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]",
50607 "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]"
50614 locStart: locStart$g,
50622 const INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "wikiLink", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"];
50623 const INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]);
50624 const kRegex = new RegExp(kPattern);
50625 const punctuationRegex = new RegExp(punctuationPattern);
50627 * split text into whitespaces and words
50628 * @param {string} text
50629 * @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>}
50632 function splitText(text, options) {
50633 const KIND_NON_CJK = "non-cjk";
50634 const KIND_CJ_LETTER = "cj-letter";
50635 const KIND_K_LETTER = "k-letter";
50636 const KIND_CJK_PUNCTUATION = "cjk-punctuation";
50638 (options.proseWrap === "preserve" ? text : text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")).split(/([\t\n ]+)/).forEach((token, index, tokens) => {
50640 if (index % 2 === 1) {
50642 type: "whitespace",
50643 value: /\n/.test(token) ? "\n" : " "
50646 } // word separated by whitespace
50649 if ((index === 0 || index === tokens.length - 1) && token === "") {
50653 token.split(new RegExp(`(${cjkPattern})`)).forEach((innerToken, innerIndex, innerTokens) => {
50654 if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") {
50659 if (innerIndex % 2 === 0) {
50660 if (innerToken !== "") {
50664 kind: KIND_NON_CJK,
50665 hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
50666 hasTrailingPunctuation: punctuationRegex.test(getLast$b(innerToken))
50674 appendNode(punctuationRegex.test(innerToken) ? {
50677 kind: KIND_CJK_PUNCTUATION,
50678 hasLeadingPunctuation: true,
50679 hasTrailingPunctuation: true
50683 kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER,
50684 hasLeadingPunctuation: false,
50685 hasTrailingPunctuation: false
50691 function appendNode(node) {
50692 const lastNode = getLast$b(nodes);
50694 if (lastNode && lastNode.type === "word") {
50695 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) {
50697 type: "whitespace",
50700 } else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace
50701 ![lastNode.value, node.value].some(value => /\u3000/.test(value))) {
50703 type: "whitespace",
50711 function isBetween(kind1, kind2) {
50712 return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1;
50717 function getOrderedListItemInfo(orderListItem, originalText) {
50718 const [, numberText, marker, leadingSpaces] = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/);
50726 function hasGitDiffFriendlyOrderedList(node, options) {
50727 if (!node.ordered) {
50731 if (node.children.length < 2) {
50735 const firstNumber = Number(getOrderedListItemInfo(node.children[0], options.originalText).numberText);
50736 const secondNumber = Number(getOrderedListItemInfo(node.children[1], options.originalText).numberText);
50738 if (firstNumber === 0 && node.children.length > 2) {
50739 const thirdNumber = Number(getOrderedListItemInfo(node.children[2], options.originalText).numberText);
50740 return secondNumber === 1 && thirdNumber === 1;
50743 return secondNumber === 1;
50744 } // The final new line should not include in value
50745 // https://github.com/remarkjs/remark/issues/512
50748 function getFencedCodeBlockValue(node, originalText) {
50753 if (node.position.end.offset === originalText.length && value.endsWith("\n") && // Code block has no end mark
50754 originalText.endsWith("\n")) {
50755 return value.slice(0, -1);
50761 function mapAst(ast, handler) {
50762 return function preorder(node, index, parentStack) {
50763 parentStack = parentStack || [];
50764 const newNode = Object.assign({}, handler(node, index, parentStack));
50766 if (newNode.children) {
50767 newNode.children = newNode.children.map((child, index) => {
50768 return preorder(child, index, [newNode].concat(parentStack));
50773 }(ast, null, null);
50776 function isAutolink(node) {
50777 if (!node || node.type !== "link" || node.children.length !== 1) {
50781 const child = node.children[0];
50782 return child && locStart$g(node) === locStart$g(child) && locEnd$m(node) === locEnd$m(child);
50788 punctuationPattern,
50789 getFencedCodeBlockValue,
50790 getOrderedListItemInfo,
50791 hasGitDiffFriendlyOrderedList,
50793 INLINE_NODE_WRAPPER_TYPES,
50798 inferParserByLanguage: inferParserByLanguage$1,
50799 getMaxContinuousCount: getMaxContinuousCount$2
50803 hardline: hardline$r,
50805 markAsRoot: markAsRoot$2
50808 replaceNewlinesWithLiterallines: replaceNewlinesWithLiterallines$2
50812 print: printFrontMatter$1
50815 getFencedCodeBlockValue: getFencedCodeBlockValue$1
50818 function embed$2(path, print, textToDoc, options) {
50819 const node = path.getValue();
50821 if (node.type === "code" && node.lang !== null) {
50822 const parser = inferParserByLanguage$1(node.lang, options);
50825 const styleUnit = options.__inJsTemplate ? "~" : "`";
50826 const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount$2(node.value, styleUnit) + 1));
50827 const doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), {
50830 stripTrailingHardline: true
50832 return markAsRoot$2(concat$E([style, node.lang, node.meta ? " " + node.meta : "", hardline$r, replaceNewlinesWithLiterallines$2(doc), hardline$r, style]));
50836 switch (node.type) {
50837 case "front-matter":
50838 return printFrontMatter$1(node, textToDoc);
50841 case "importExport":
50842 return concat$E([textToDoc(node.value, {
50845 stripTrailingHardline: true
50849 return textToDoc(`<$>${node.value}</$>`, {
50850 parser: "__js_expression",
50853 stripTrailingHardline: true
50860 var embed_1$2 = embed$2;
50863 parse: parseFrontMatter$1
50865 const pragmas = ["format", "prettier"];
50867 function startWithPragma(text) {
50868 const pragma = `@(${pragmas.join("|")})`;
50869 const regex = new RegExp([`<!--\\s*${pragma}\\s*-->`, `<!--.*\r?\n[\\s\\S]*(^|\n)[^\\S\n]*${pragma}[^\\S\n]*($|\n)[\\s\\S]*\n.*-->`].join("|"), "m");
50870 const matched = text.match(regex);
50871 return matched && matched.index === 0;
50876 hasPragma: text => startWithPragma(parseFrontMatter$1(text).content.trimStart()),
50877 insertPragma: text => {
50878 const extracted = parseFrontMatter$1(text);
50879 const pragma = `<!-- @${pragmas[0]} -->`;
50880 return extracted.frontMatter ? `${extracted.frontMatter.raw}\n\n${pragma}\n\n${extracted.content}` : `${pragma}\n\n${extracted.content}`;
50885 getOrderedListItemInfo: getOrderedListItemInfo$1,
50887 splitText: splitText$1
50888 } = utils$9; // 0x0 ~ 0x10ffff
50889 // eslint-disable-next-line no-control-regex
50891 const isSingleCharRegex = /^([\u0000-\uffff]|[\ud800-\udbff][\udc00-\udfff])$/;
50893 function preprocess$1(ast, options) {
50894 ast = restoreUnescapedCharacter(ast, options);
50895 ast = mergeContinuousTexts(ast);
50896 ast = transformInlineCode(ast);
50897 ast = transformIndentedCodeblockAndMarkItsParentList(ast, options);
50898 ast = markAlignedList(ast, options);
50899 ast = splitTextIntoSentences(ast, options);
50900 ast = transformImportExport(ast);
50901 ast = mergeContinuousImportExport(ast);
50905 function transformImportExport(ast) {
50906 return mapAst$1(ast, node => {
50907 if (node.type !== "import" && node.type !== "export") {
50911 return Object.assign({}, node, {
50912 type: "importExport"
50917 function transformInlineCode(ast) {
50918 return mapAst$1(ast, node => {
50919 if (node.type !== "inlineCode") {
50923 return Object.assign({}, node, {
50924 value: node.value.replace(/\s+/g, " ")
50929 function restoreUnescapedCharacter(ast, options) {
50930 return mapAst$1(ast, node => node.type !== "text" || node.value === "*" || node.value === "_" || // handle these cases in printer
50931 !isSingleCharRegex.test(node.value) || node.position.end.offset - node.position.start.offset === node.value.length ? node : Object.assign({}, node, {
50932 value: options.originalText.slice(node.position.start.offset, node.position.end.offset)
50936 function mergeContinuousImportExport(ast) {
50937 return mergeChildren(ast, (prevNode, node) => prevNode.type === "importExport" && node.type === "importExport", (prevNode, node) => ({
50938 type: "importExport",
50939 value: prevNode.value + "\n\n" + node.value,
50941 start: prevNode.position.start,
50942 end: node.position.end
50947 function mergeChildren(ast, shouldMerge, mergeNode) {
50948 return mapAst$1(ast, node => {
50949 if (!node.children) {
50953 const children = node.children.reduce((current, child) => {
50954 const lastChild = current[current.length - 1];
50956 if (lastChild && shouldMerge(lastChild, child)) {
50957 current.splice(-1, 1, mergeNode(lastChild, child));
50959 current.push(child);
50964 return Object.assign({}, node, {
50970 function mergeContinuousTexts(ast) {
50971 return mergeChildren(ast, (prevNode, node) => prevNode.type === "text" && node.type === "text", (prevNode, node) => ({
50973 value: prevNode.value + node.value,
50975 start: prevNode.position.start,
50976 end: node.position.end
50981 function splitTextIntoSentences(ast, options) {
50982 return mapAst$1(ast, (node, index, [parentNode]) => {
50983 if (node.type !== "text") {
50991 if (parentNode.type === "paragraph") {
50993 value = value.trimStart();
50996 if (index === parentNode.children.length - 1) {
50997 value = value.trimEnd();
51003 position: node.position,
51004 children: splitText$1(value, options)
51009 function transformIndentedCodeblockAndMarkItsParentList(ast, options) {
51010 return mapAst$1(ast, (node, index, parentStack) => {
51011 if (node.type === "code") {
51012 // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it
51013 const isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset));
51014 node.isIndented = isIndented;
51017 for (let i = 0; i < parentStack.length; i++) {
51018 const parent = parentStack[i]; // no need to check checked items
51020 if (parent.hasIndentedCodeblock) {
51024 if (parent.type === "list") {
51025 parent.hasIndentedCodeblock = true;
51035 function markAlignedList(ast, options) {
51036 return mapAst$1(ast, (node, index, parentStack) => {
51037 if (node.type === "list" && node.children.length !== 0) {
51038 // if one of its parents is not aligned, it's not possible to be aligned in sub-lists
51039 for (let i = 0; i < parentStack.length; i++) {
51040 const parent = parentStack[i];
51042 if (parent.type === "list" && !parent.isAligned) {
51043 node.isAligned = false;
51048 node.isAligned = isAligned(node);
51054 function getListItemStart(listItem) {
51055 return listItem.children.length === 0 ? -1 : listItem.children[0].position.start.column - 1;
51058 function isAligned(list) {
51059 if (!list.ordered) {
51067 const [firstItem, secondItem] = list.children;
51068 const firstInfo = getOrderedListItemInfo$1(firstItem, options.originalText);
51070 if (firstInfo.leadingSpaces.length > 1) {
51080 const firstStart = getListItemStart(firstItem);
51082 if (firstStart === -1) {
51092 if (list.children.length === 1) {
51102 return firstStart % options.tabWidth === 0;
51105 const secondStart = getListItemStart(secondItem);
51107 if (firstStart !== secondStart) {
51118 if (firstStart % options.tabWidth === 0) {
51138 const secondInfo = getOrderedListItemInfo$1(secondItem, options.originalText);
51139 return secondInfo.leadingSpaces.length > 1;
51143 var printPreprocess$1 = preprocess$1;
51146 isFrontMatterNode: isFrontMatterNode$3
51149 startWithPragma: startWithPragma$1
51151 const ignoredProperties$3 = new Set(["position", "raw" // front-matter
51154 function clean$5(ast, newObj, parent) {
51156 if (ast.type === "front-matter" || ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") {
51157 delete newObj.value;
51160 if (ast.type === "list") {
51161 delete newObj.isAligned;
51164 if (ast.type === "list" || ast.type === "listItem") {
51165 delete newObj.spread;
51166 delete newObj.loose;
51167 } // texts can be splitted or merged
51170 if (ast.type === "text") {
51174 if (ast.type === "inlineCode") {
51175 newObj.value = ast.value.replace(/[\t\n ]+/g, " ");
51178 if (ast.type === "wikiLink") {
51179 newObj.value = ast.value.trim().replace(/[\t\n]+/g, " ");
51182 if (ast.type === "definition" || ast.type === "linkReference") {
51183 newObj.label = ast.label.trim().replace(/[\t\n ]+/g, " ").toLowerCase();
51186 if ((ast.type === "definition" || ast.type === "link" || ast.type === "image") && ast.title) {
51187 newObj.title = ast.title.replace(/\\(["')])/g, "$1");
51188 } // for insert pragma
51191 if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || isFrontMatterNode$3(parent.children[0]) && parent.children[1] === ast) && ast.type === "html" && startWithPragma$1(ast.value)) {
51196 clean$5.ignoredProperties = ignoredProperties$3;
51197 var clean_1$3 = clean$5;
51200 getLast: getLast$c,
51201 getMinNotPresentContinuousCount: getMinNotPresentContinuousCount$1,
51202 getMaxContinuousCount: getMaxContinuousCount$3,
51203 getStringWidth: getStringWidth$4
51207 breakParent: breakParent$6,
51211 literalline: literalline$4,
51212 markAsRoot: markAsRoot$3,
51213 hardline: hardline$s,
51214 softline: softline$l,
51215 ifBreak: ifBreak$h,
51222 normalizeDoc: normalizeDoc$1
51225 printDocToString: printDocToString$3
51229 replaceEndOfLineWith: replaceEndOfLineWith$1
51232 insertPragma: insertPragma$6
51235 locStart: locStart$h,
51239 getFencedCodeBlockValue: getFencedCodeBlockValue$2,
51240 hasGitDiffFriendlyOrderedList: hasGitDiffFriendlyOrderedList$1,
51241 splitText: splitText$2,
51242 punctuationPattern: punctuationPattern$1,
51243 INLINE_NODE_TYPES: INLINE_NODE_TYPES$1,
51244 INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES$1,
51245 isAutolink: isAutolink$1
51248 * @typedef {import("../document").Doc} Doc
51251 const TRAILING_HARDLINE_NODES = new Set(["importExport"]);
51252 const SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link", "wikiLink"];
51253 const SIBLING_NODE_TYPES = new Set(["listItem", "definition", "footnoteDefinition"]);
51255 function genericPrint$4(path, options, print) {
51256 const node = path.getValue();
51258 if (shouldRemainTheSameContent(path)) {
51259 return concat$F(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)));
51262 switch (node.type) {
51263 case "front-matter":
51264 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
51267 if (node.children.length === 0) {
51271 return concat$F([normalizeDoc$1(printRoot(path, options, print)), !TRAILING_HARDLINE_NODES.has(getLastDescendantNode(node).type) ? hardline$s : ""]);
51274 return printChildren$1(path, options, print, {
51275 postprocessor: fill$5
51279 return printChildren$1(path, options, print);
51283 let escapedValue = node.value.replace(/\*/g, "\\$&") // escape all `*`
51284 .replace(new RegExp([`(^|${punctuationPattern$1})(_+)`, `(_+)(${punctuationPattern$1}|$)`].join("|"), "g"), (_, text1, underscore1, underscore2, text2) => (underscore1 ? `${text1}${underscore1}` : `${underscore2}${text2}`).replace(/_/g, "\\_")); // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
51286 const isFirstSentence = (node, name, index) => node.type === "sentence" && index === 0;
51288 const isLastChildAutolink = (node, name, index) => isAutolink$1(node.children[index - 1]);
51290 if (escapedValue !== node.value && (path.match(undefined, isFirstSentence, isLastChildAutolink) || path.match(undefined, isFirstSentence, (node, name, index) => node.type === "emphasis" && index === 0, isLastChildAutolink))) {
51291 // backslash is parsed as part of autolinks, so we need to remove it
51292 escapedValue = escapedValue.replace(/^(\\?[*_])+/, prefix => prefix.replace(/\\/g, ""));
51295 return escapedValue;
51300 const parentNode = path.getParentNode();
51301 const index = parentNode.children.indexOf(node);
51302 const nextNode = parentNode.children[index + 1];
51303 const proseWrap = // leading char that may cause different syntax
51304 nextNode && /^>|^([*+-]|#{1,6}|\d+[).])$/.test(nextNode.value) ? "never" : options.proseWrap;
51305 return printLine(path, node.value, {
51314 if (isAutolink$1(node.children[0])) {
51315 style = options.originalText[node.position.start.offset];
51317 const parentNode = path.getParentNode();
51318 const index = parentNode.children.indexOf(node);
51319 const prevNode = parentNode.children[index - 1];
51320 const nextNode = parentNode.children[index + 1];
51321 const hasPrevOrNextWord = // `1*2*3` is considered emphasis but `1_2_3` is not
51322 prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && getLast$c(prevNode.children).type === "word" && !getLast$c(prevNode.children).hasTrailingPunctuation || nextNode && nextNode.type === "sentence" && nextNode.children.length > 0 && nextNode.children[0].type === "word" && !nextNode.children[0].hasLeadingPunctuation;
51323 style = hasPrevOrNextWord || getAncestorNode$2(path, "emphasis") ? "*" : "_";
51326 return concat$F([style, printChildren$1(path, options, print), style]);
51330 return concat$F(["**", printChildren$1(path, options, print), "**"]);
51333 return concat$F(["~~", printChildren$1(path, options, print), "~~"]);
51337 const backtickCount = getMinNotPresentContinuousCount$1(node.value, "`");
51338 const style = "`".repeat(backtickCount || 1);
51339 const gap = backtickCount && !/^\s/.test(node.value) ? " " : "";
51340 return concat$F([style, gap, node.value, gap, style]);
51347 if (options.proseWrap === "preserve") {
51348 contents = node.value;
51350 contents = node.value.replace(/[\t\n]+/g, " ");
51353 return concat$F(["[[", contents, "]]"]);
51357 switch (options.originalText[node.position.start.offset]) {
51360 const mailto = "mailto:";
51361 const url = // <hello@example.com> is parsed as { url: "mailto:hello@example.com" }
51362 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;
51363 return concat$F(["<", url, ">"]);
51367 return concat$F(["[", printChildren$1(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
51370 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
51374 return concat$F(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
51377 return concat$F(["> ", align$5("> ", printChildren$1(path, options, print))]);
51380 return concat$F(["#".repeat(node.depth) + " ", printChildren$1(path, options, print)]);
51384 if (node.isIndented) {
51385 // indented code block
51386 const alignment = " ".repeat(4);
51387 return align$5(alignment, concat$F([alignment, concat$F(replaceEndOfLineWith$1(node.value, hardline$s))]));
51388 } // fenced code block
51391 const styleUnit = options.__inJsTemplate ? "~" : "`";
51392 const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount$3(node.value, styleUnit) + 1));
51393 return concat$F([style, node.lang || "", node.meta ? " " + node.meta : "", hardline$s, concat$F(replaceEndOfLineWith$1(getFencedCodeBlockValue$2(node, options.originalText), hardline$s)), hardline$s, style]);
51398 const parentNode = path.getParentNode();
51399 const value = parentNode.type === "root" && getLast$c(parentNode.children) === node ? node.value.trimEnd() : node.value;
51400 const isHtmlComment = /^<!--[\S\s]*-->$/.test(value);
51401 return concat$F(replaceEndOfLineWith$1(value, isHtmlComment ? hardline$s : markAsRoot$3(literalline$4)));
51406 const nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode());
51407 const isGitDiffFriendlyOrderedList = hasGitDiffFriendlyOrderedList$1(node, options);
51408 return printChildren$1(path, options, print, {
51409 processor: (childPath, index) => {
51410 const prefix = getPrefix();
51411 const childNode = childPath.getValue();
51413 if (childNode.children.length === 2 && childNode.children[1].type === "html" && childNode.children[0].position.start.column !== childNode.children[1].position.start.column) {
51414 return concat$F([prefix, printListItem(childPath, options, print, prefix)]);
51417 return concat$F([prefix, align$5(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]);
51419 function getPrefix() {
51420 const rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* ";
51421 return node.isAligned ||
51422 /* workaround for https://github.com/remarkjs/remark/issues/315 */
51423 node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix;
51429 case "thematicBreak":
51431 const counter = getAncestorCounter$1(path, "list");
51433 if (counter === -1) {
51437 const nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1));
51438 return nthSiblingIndex % 2 === 0 ? "***" : "---";
51441 case "linkReference":
51442 return concat$F(["[", printChildren$1(path, options, print), "]", node.referenceType === "full" ? concat$F(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]);
51444 case "imageReference":
51445 switch (node.referenceType) {
51447 return concat$F(["![", node.alt || "", "][", node.identifier, "]"]);
51450 return concat$F(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]);
51455 const lineOrSpace = options.proseWrap === "always" ? line$n : " ";
51456 return group$t(concat$F([concat$F(["[", node.identifier, "]:"]), indent$u(concat$F([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$F([lineOrSpace, printTitle(node.title, options, false)])]))]));
51458 // `footnote` requires `.use(footnotes, {inlineNotes: true})`, we are not using this option
51459 // https://github.com/remarkjs/remark-footnotes#optionsinlinenotes
51461 /* istanbul ignore next */
51464 return concat$F(["[^", printChildren$1(path, options, print), "]"]);
51466 case "footnoteReference":
51467 return concat$F(["[^", node.identifier, "]"]);
51469 case "footnoteDefinition":
51471 const nextNode = path.getParentNode().children[path.getName() + 1];
51472 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);
51473 return concat$F(["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$1(path, options, print) : group$t(concat$F([align$5(" ".repeat(4), printChildren$1(path, options, print, {
51474 processor: (childPath, index) => {
51475 return index === 0 ? group$t(concat$F([softline$l, childPath.call(print)])) : childPath.call(print);
51477 })), nextNode && nextNode.type === "footnoteDefinition" ? softline$l : ""]))]);
51481 return printTable(path, options, print);
51484 return printChildren$1(path, options, print);
51487 return /\s/.test(options.originalText[node.position.start.offset]) ? concat$F([" ", markAsRoot$3(literalline$4)]) : concat$F(["\\", hardline$s]);
51490 return concat$F(replaceEndOfLineWith$1(node.value, hardline$s));
51492 // fallback to the original text if multiparser failed
51493 // or `embeddedLanguageFormatting: "off"`
51495 case "importExport":
51496 return concat$F([node.value, hardline$s]);
51502 return concat$F(["$$", hardline$s, node.value ? concat$F([concat$F(replaceEndOfLineWith$1(node.value, hardline$s)), hardline$s]) : "", "$$"]);
51506 // remark-math trims content but we don't want to remove whitespaces
51507 // since it's very possible that it's recognized as math accidentally
51508 return options.originalText.slice(locStart$h(node), locEnd$n(node));
51511 case "tableRow": // handled in "table"
51513 case "listItem": // handled in "list"
51516 /* istanbul ignore next */
51517 throw new Error(`Unknown markdown type ${JSON.stringify(node.type)}`);
51521 function printListItem(path, options, print, listPrefix) {
51522 const node = path.getValue();
51523 const prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
51524 return concat$F([prefix, printChildren$1(path, options, print, {
51525 processor: (childPath, index) => {
51526 if (index === 0 && childPath.getValue().type !== "list") {
51527 return align$5(" ".repeat(prefix.length), childPath.call(print));
51530 const alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
51532 return concat$F([alignment, align$5(alignment, childPath.call(print))]);
51537 function alignListPrefix(prefix, options) {
51538 const additionalSpaces = getAdditionalSpaces();
51539 return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block
51542 function getAdditionalSpaces() {
51543 const restSpaces = prefix.length % options.tabWidth;
51544 return restSpaces === 0 ? 0 : options.tabWidth - restSpaces;
51548 function getNthListSiblingIndex(node, parentNode) {
51549 return getNthSiblingIndex(node, parentNode, siblingNode => siblingNode.ordered === node.ordered);
51552 function getNthSiblingIndex(node, parentNode, condition) {
51553 condition = condition || (() => true);
51557 for (const childNode of parentNode.children) {
51558 if (childNode.type === node.type && condition(childNode)) {
51564 if (childNode === node) {
51570 function getAncestorCounter$1(path, typeOrTypes) {
51571 const types = [].concat(typeOrTypes);
51575 while (ancestorNode = path.getParentNode(++counter)) {
51576 if (types.includes(ancestorNode.type)) {
51584 function getAncestorNode$2(path, typeOrTypes) {
51585 const counter = getAncestorCounter$1(path, typeOrTypes);
51586 return counter === -1 ? null : path.getParentNode(counter);
51589 function printLine(path, value, options) {
51590 if (options.proseWrap === "preserve" && value === "\n") {
51594 const isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES);
51595 return value !== "" ? isBreakable ? line$n : " " : isBreakable ? softline$l : "";
51598 function printTable(path, options, print) {
51599 const hardlineWithoutBreakParent = hardline$s.parts[0];
51600 const node = path.getValue();
51601 const columnMaxWidths = []; // { [rowIndex: number]: { [columnIndex: number]: {text: string, width: number} } }
51603 const contents = path.map(rowPath => rowPath.map((cellPath, columnIndex) => {
51604 const text = printDocToString$3(cellPath.call(print), options).formatted;
51605 const width = getStringWidth$4(text);
51606 columnMaxWidths[columnIndex] = Math.max(columnMaxWidths[columnIndex] || 3, // minimum width = 3 (---, :--, :-:, --:)
51612 }, "children"), "children");
51613 const alignedTable = printTableContents(
51617 if (options.proseWrap !== "never") {
51618 return concat$F([breakParent$6, alignedTable]);
51619 } // Only if the --prose-wrap never is set and it exceeds the print width.
51622 const compactTable = printTableContents(
51625 return concat$F([breakParent$6, group$t(ifBreak$h(compactTable, alignedTable))]);
51627 function printTableContents(isCompact) {
51628 /** @type{Doc[]} */
51629 const parts = [printRow(contents[0], isCompact), printAlign(isCompact)];
51631 if (contents.length > 1) {
51632 parts.push(join$k(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents, isCompact))));
51635 return join$k(hardlineWithoutBreakParent, parts);
51638 function printAlign(isCompact) {
51639 const align = columnMaxWidths.map((width, index) => {
51640 const align = node.align[index];
51641 const first = align === "center" || align === "left" ? ":" : "-";
51642 const last = align === "center" || align === "right" ? ":" : "-";
51643 const middle = isCompact ? "-" : "-".repeat(width - 2);
51644 return `${first}${middle}${last}`;
51646 return `| ${align.join(" | ")} |`;
51649 function printRow(rowContents, isCompact) {
51650 const columns = rowContents.map(({
51653 }, columnIndex) => {
51658 const spaces = columnMaxWidths[columnIndex] - width;
51659 const align = node.align[columnIndex];
51662 if (align === "right") {
51664 } else if (align === "center") {
51665 before = Math.floor(spaces / 2);
51668 const after = spaces - before;
51669 return `${" ".repeat(before)}${text}${" ".repeat(after)}`;
51671 return `| ${columns.join(" | ")} |`;
51675 function printRoot(path, options, print) {
51676 /** @typedef {{ index: number, offset: number }} IgnorePosition */
51678 /** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */
51679 const ignoreRanges = [];
51680 /** @type {IgnorePosition | null} */
51682 let ignoreStart = null;
51685 } = path.getValue();
51686 children.forEach((childNode, index) => {
51687 switch (isPrettierIgnore(childNode)) {
51689 if (ignoreStart === null) {
51692 offset: childNode.position.end.offset
51699 if (ignoreStart !== null) {
51700 ignoreRanges.push({
51701 start: ignoreStart,
51704 offset: childNode.position.start.offset
51707 ignoreStart = null;
51713 return printChildren$1(path, options, print, {
51714 processor: (childPath, index) => {
51715 if (ignoreRanges.length !== 0) {
51716 const ignoreRange = ignoreRanges[0];
51718 if (index === ignoreRange.start.index) {
51719 return concat$F([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]);
51722 if (ignoreRange.start.index < index && index < ignoreRange.end.index) {
51726 if (index === ignoreRange.end.index) {
51727 ignoreRanges.shift();
51732 return childPath.call(print);
51737 function printChildren$1(path, options, print, events) {
51738 events = events || {};
51739 const postprocessor = events.postprocessor || concat$F;
51741 const processor = events.processor || (childPath => childPath.call(print));
51743 const node = path.getValue();
51746 path.each((childPath, index) => {
51747 const childNode = childPath.getValue();
51748 const result = processor(childPath, index);
51750 if (result !== false) {
51753 prevNode: lastChildNode,
51758 if (!shouldNotPrePrintHardline(childNode, data)) {
51759 parts.push(hardline$s); // Can't find a case to pass `shouldPrePrintTripleHardline`
51761 /* istanbul ignore next */
51763 if (lastChildNode && TRAILING_HARDLINE_NODES.has(lastChildNode.type)) {
51764 if (shouldPrePrintTripleHardline(childNode, data)) {
51765 parts.push(hardline$s);
51768 if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
51769 parts.push(hardline$s);
51772 if (shouldPrePrintTripleHardline(childNode, data)) {
51773 parts.push(hardline$s);
51778 parts.push(result);
51779 lastChildNode = childNode;
51782 return postprocessor(parts);
51785 function getLastDescendantNode(node) {
51786 let current = node;
51788 while (current.children && current.children.length !== 0) {
51789 current = current.children[current.children.length - 1];
51794 /** @return {false | 'next' | 'start' | 'end'} */
51797 function isPrettierIgnore(node) {
51798 if (node.type !== "html") {
51802 const match = node.value.match(/^<!--\s*prettier-ignore(?:-(start|end))?\s*-->$/);
51803 return match === null ? false : match[1] ? match[1] : "next";
51806 function shouldNotPrePrintHardline(node, data) {
51807 const isFirstNode = data.parts.length === 0;
51808 const isInlineNode = INLINE_NODE_TYPES$1.includes(node.type);
51809 const isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES$1.includes(data.parentNode.type);
51810 return isFirstNode || isInlineNode || isInlineHTML;
51813 function shouldPrePrintDoubleHardline(node, data) {
51814 const isSequence = (data.prevNode && data.prevNode.type) === node.type;
51815 const isSiblingNode = isSequence && SIBLING_NODE_TYPES.has(node.type);
51816 const isInTightListItem = data.parentNode.type === "listItem" && !data.parentNode.loose;
51817 const isPrevNodeLooseListItem = data.prevNode && data.prevNode.type === "listItem" && data.prevNode.loose;
51818 const isPrevNodePrettierIgnore = isPrettierIgnore(data.prevNode) === "next";
51819 const isBlockHtmlWithoutBlankLineBetweenPrevHtml = node.type === "html" && data.prevNode && data.prevNode.type === "html" && data.prevNode.position.end.line + 1 === node.position.start.line;
51820 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;
51821 return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml || isHtmlDirectAfterListItem);
51824 function shouldPrePrintTripleHardline(node, data) {
51825 const isPrevNodeList = data.prevNode && data.prevNode.type === "list";
51826 const isIndentedCode = node.type === "code" && node.isIndented;
51827 return isPrevNodeList && isIndentedCode;
51830 function shouldRemainTheSameContent(path) {
51831 const ancestorNode = getAncestorNode$2(path, ["linkReference", "imageReference"]);
51832 return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full");
51835 function printUrl(url, dangerousCharOrChars) {
51836 const dangerousChars = [" "].concat(dangerousCharOrChars || []);
51837 return new RegExp(dangerousChars.map(x => `\\${x}`).join("|")).test(url) ? `<${url}>` : url;
51840 function printTitle(title, options, printSpace) {
51841 if (printSpace == null) {
51850 return " " + printTitle(title, options, false);
51851 } // title is escaped after `remark-parse` v7
51854 title = title.replace(/\\(["')])/g, "$1");
51856 if (title.includes('"') && title.includes("'") && !title.includes(")")) {
51857 return `(${title})`; // avoid escaped quotes
51858 } // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split
51861 const singleCount = title.split("'").length - 1;
51862 const doubleCount = title.split('"').length - 1;
51863 const quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"';
51864 title = title.replace(/\\/, "\\\\");
51865 title = title.replace(new RegExp(`(${quote})`, "g"), "\\$1");
51866 return `${quote}${title}${quote}`;
51869 function clamp(value, min, max) {
51870 return value < min ? min : value > max ? max : value;
51873 function hasPrettierIgnore$5(path) {
51874 const index = +path.getName();
51880 const prevNode = path.getParentNode().children[index - 1];
51881 return isPrettierIgnore(prevNode) === "next";
51884 var printerMarkdown = {
51885 preprocess: printPreprocess$1,
51886 print: genericPrint$4,
51888 massageAstNode: clean_1$3,
51889 hasPrettierIgnore: hasPrettierIgnore$5,
51890 insertPragma: insertPragma$6
51894 proseWrap: commonOptions.proseWrap,
51895 singleQuote: commonOptions.singleQuote
51898 var name$f = "Markdown";
51899 var type$d = "prose";
51900 var color$7 = "#083fa1";
51904 var aceMode$d = "markdown";
51905 var codemirrorMode$a = "gfm";
51906 var codemirrorMimeType$a = "text/x-gfm";
51908 var extensions$d = [
51920 var filenames$3 = [
51923 var tmScope$d = "source.gfm";
51924 var languageId$d = 222;
51925 var require$$0$6 = {
51929 aliases: aliases$4,
51930 aceMode: aceMode$d,
51931 codemirrorMode: codemirrorMode$a,
51932 codemirrorMimeType: codemirrorMimeType$a,
51934 extensions: extensions$d,
51935 filenames: filenames$3,
51936 tmScope: tmScope$d,
51937 languageId: languageId$d
51940 const languages$4 = [createLanguage(require$$0$6, data => ({
51942 parsers: ["markdown"],
51943 vscodeLanguageIds: ["markdown"],
51944 filenames: data.filenames.concat(["README"]),
51945 extensions: data.extensions.filter(extension => extension !== ".mdx")
51946 })), createLanguage(require$$0$6, () => ({
51950 vscodeLanguageIds: ["mdx"],
51952 extensions: [".mdx"]
51954 const printers$4 = {
51955 mdast: printerMarkdown
51957 const parsers$4 = {
51958 /* istanbul ignore next */
51960 return require("./parser-markdown").parsers.remark;
51964 return require("./parser-markdown").parsers.remark;
51968 return require("./parser-markdown").parsers.mdx;
51972 var languageMarkdown = {
51973 languages: languages$4,
51974 options: options$5,
51975 printers: printers$4,
51980 isFrontMatterNode: isFrontMatterNode$4
51982 const ignoredProperties$4 = new Set(["sourceSpan", "startSourceSpan", "endSourceSpan", "nameSpan", "valueSpan"]);
51984 function clean$6(ast, newNode) {
51985 if (ast.type === "text" || ast.type === "comment") {
51987 } // may be formatted by multiparser
51990 if (isFrontMatterNode$4(ast) || ast.type === "yaml" || ast.type === "toml") {
51994 if (ast.type === "attribute") {
51995 delete newNode.value;
51998 if (ast.type === "docType") {
51999 delete newNode.value;
52003 clean$6.ignoredProperties = ignoredProperties$4;
52004 var clean_1$4 = clean$6;
52006 var htmlTagNames = [
52380 "allowpaymentrequest",
52731 var htmlElementAttributes = {
52765 basefont: basefont,
52767 blockquote: blockquote,
52774 colgroup: colgroup,
52784 fieldset: fieldset,
52788 frameset: frameset,
52813 optgroup: optgroup,
52819 progress: progress,
52829 textarea: textarea,
52841 "CSS_DISPLAY_TAGS": {
52844 "basefont": "none",
52845 "datalist": "none",
52850 "noframes": "none",
52856 "template": "inline",
52861 "address": "block",
52862 "blockquote": "block",
52866 "figcaption": "block",
52872 "listing": "block",
52875 "plaintext": "block",
52878 "slot": "contents",
52881 "article": "block",
52891 "section": "block",
52900 "caption": "table-caption",
52901 "colgroup": "table-column-group",
52902 "col": "table-column",
52903 "thead": "table-header-group",
52904 "tbody": "table-row-group",
52905 "tfoot": "table-footer-group",
52907 "td": "table-cell",
52908 "th": "table-cell",
52909 "fieldset": "block",
52910 "button": "inline-block",
52911 "details": "block",
52912 "summary": "block",
52914 "meter": "inline-block",
52915 "progress": "inline-block",
52916 "object": "inline-block",
52917 "video": "inline-block",
52918 "audio": "inline-block",
52919 "select": "inline-block",
52921 "optgroup": "block"
52923 "CSS_DISPLAY_DEFAULT": "inline",
52924 "CSS_WHITE_SPACE_TAGS": {
52926 "plaintext": "pre",
52930 "table": "initial",
52931 "textarea": "pre-wrap"
52933 "CSS_WHITE_SPACE_DEFAULT": "normal"
52937 inferParserByLanguage: inferParserByLanguage$2,
52938 isFrontMatterNode: isFrontMatterNode$5
52942 CSS_DISPLAY_DEFAULT,
52943 CSS_WHITE_SPACE_TAGS,
52944 CSS_WHITE_SPACE_DEFAULT
52946 const HTML_TAGS = arrayToMap(htmlTagNames);
52947 const HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes, arrayToMap); // https://infra.spec.whatwg.org/#ascii-whitespace
52949 const HTML_WHITESPACE = new Set(["\t", "\n", "\f", "\r", " "]);
52951 const htmlTrimStart = string => string.replace(/^[\t\n\f\r ]+/, "");
52953 const htmlTrimEnd = string => string.replace(/[\t\n\f\r ]+$/, "");
52955 const htmlTrim = string => htmlTrimStart(htmlTrimEnd(string));
52957 const htmlTrimLeadingBlankLines = string => string.replace(/^[\t\f\r ]*?\n/g, "");
52959 const htmlTrimPreserveIndentation = string => htmlTrimLeadingBlankLines(htmlTrimEnd(string));
52961 const splitByHtmlWhitespace = string => string.split(/[\t\n\f\r ]+/);
52963 const getLeadingHtmlWhitespace = string => string.match(/^[\t\n\f\r ]*/)[0];
52965 const getLeadingAndTrailingHtmlWhitespace = string => {
52966 const [, leadingWhitespace, text, trailingWhitespace] = string.match(/^([\t\n\f\r ]*)([\S\s]*?)([\t\n\f\r ]*)$/);
52969 trailingWhitespace,
52974 const hasHtmlWhitespace = string => /[\t\n\f\r ]/.test(string);
52976 function arrayToMap(array) {
52977 const map = Object.create(null);
52979 for (const value of array) {
52986 function mapObject(object, fn) {
52987 const newObject = Object.create(null);
52989 for (const key of Object.keys(object)) {
52990 newObject[key] = fn(object[key], key);
52996 function shouldPreserveContent(node, options) {
52997 // unterminated node in ie conditional comment
52998 // e.g. <!--[if lt IE 9]><html><![endif]-->
52999 if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) {
53001 } // incomplete html in ie conditional comment
53002 // e.g. <!--[if lt IE 9]></div><![endif]-->
53005 if (node.type === "ieConditionalComment" && !node.complete) {
53007 } // TODO: handle non-text children in <pre>
53010 if (isPreLikeNode(node) && node.children.some(child => child.type !== "text" && child.type !== "interpolation")) {
53014 if (isVueNonHtmlBlock(node, options) && !isScriptLikeTag(node) && node.type !== "interpolation") {
53021 function hasPrettierIgnore$6(node) {
53022 /* istanbul ignore next */
53023 if (node.type === "attribute") {
53026 /* istanbul ignore next */
53029 if (!node.parent) {
53033 if (typeof node.index !== "number" || node.index === 0) {
53037 const prevNode = node.parent.children[node.index - 1];
53038 return isPrettierIgnore$1(prevNode);
53041 function isPrettierIgnore$1(node) {
53042 return node.type === "comment" && node.value.trim() === "prettier-ignore";
53045 function getPrettierIgnoreAttributeCommentData(value) {
53046 const match = value.trim().match(/^prettier-ignore-attribute(?:\s+([^]+))?$/);
53056 return match[1].split(/\s+/);
53058 /** there's no opening/closing tag or it's considered not breakable */
53061 function isTextLikeNode(node) {
53062 return node.type === "text" || node.type === "comment";
53065 function isScriptLikeTag(node) {
53066 return node.type === "element" && (node.fullName === "script" || node.fullName === "style" || node.fullName === "svg:style" || isUnknownNamespace(node) && (node.name === "script" || node.name === "style"));
53069 function canHaveInterpolation(node) {
53070 return node.children && !isScriptLikeTag(node);
53073 function isWhitespaceSensitiveNode(node) {
53074 return isScriptLikeTag(node) || node.type === "interpolation" || isIndentationSensitiveNode(node);
53077 function isIndentationSensitiveNode(node) {
53078 return getNodeCssStyleWhiteSpace(node).startsWith("pre");
53081 function isLeadingSpaceSensitiveNode(node, options) {
53082 const isLeadingSpaceSensitive = _isLeadingSpaceSensitiveNode();
53084 if (isLeadingSpaceSensitive && !node.prev && node.parent && node.parent.tagDefinition && node.parent.tagDefinition.ignoreFirstLf) {
53085 return node.type === "interpolation";
53088 return isLeadingSpaceSensitive;
53090 function _isLeadingSpaceSensitiveNode() {
53091 if (isFrontMatterNode$5(node)) {
53095 if ((node.type === "text" || node.type === "interpolation") && node.prev && (node.prev.type === "text" || node.prev.type === "interpolation")) {
53099 if (!node.parent || node.parent.cssDisplay === "none") {
53103 if (isPreLikeNode(node.parent)) {
53107 if (!node.prev && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || isVueCustomBlock(node.parent, options) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
53111 if (node.prev && !isNextLeadingSpaceSensitiveCssDisplay(node.prev.cssDisplay)) {
53119 function isTrailingSpaceSensitiveNode(node, options) {
53120 if (isFrontMatterNode$5(node)) {
53124 if ((node.type === "text" || node.type === "interpolation") && node.next && (node.next.type === "text" || node.next.type === "interpolation")) {
53128 if (!node.parent || node.parent.cssDisplay === "none") {
53132 if (isPreLikeNode(node.parent)) {
53136 if (!node.next && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || isVueCustomBlock(node.parent, options) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
53140 if (node.next && !isPrevTrailingSpaceSensitiveCssDisplay(node.next.cssDisplay)) {
53147 function isDanglingSpaceSensitiveNode(node) {
53148 return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag(node);
53151 function forceNextEmptyLine(node) {
53152 return isFrontMatterNode$5(node) || node.next && node.sourceSpan.end && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line;
53154 /** firstChild leadingSpaces and lastChild trailingSpaces */
53157 function forceBreakContent(node) {
53158 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 && node.firstChild.type !== "text" && hasLeadingLineBreak(node.firstChild) && (!node.lastChild.isTrailingSpaceSensitive || hasTrailingLineBreak(node.lastChild));
53160 /** spaces between children */
53163 function forceBreakChildren(node) {
53164 return node.type === "element" && node.children.length !== 0 && (["html", "head", "ul", "ol", "select"].includes(node.name) || node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell");
53167 function preferHardlineAsLeadingSpaces(node) {
53168 return preferHardlineAsSurroundingSpaces(node) || node.prev && preferHardlineAsTrailingSpaces(node.prev) || hasSurroundingLineBreak(node);
53171 function preferHardlineAsTrailingSpaces(node) {
53172 return preferHardlineAsSurroundingSpaces(node) || node.type === "element" && node.fullName === "br" || hasSurroundingLineBreak(node);
53175 function hasSurroundingLineBreak(node) {
53176 return hasLeadingLineBreak(node) && hasTrailingLineBreak(node);
53179 function hasLeadingLineBreak(node) {
53180 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);
53183 function hasTrailingLineBreak(node) {
53184 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);
53187 function preferHardlineAsSurroundingSpaces(node) {
53188 switch (node.type) {
53189 case "ieConditionalComment":
53195 return ["script", "select"].includes(node.name);
53201 function getLastDescendant(node) {
53202 return node.lastChild ? getLastDescendant(node.lastChild) : node;
53205 function hasNonTextChild(node) {
53206 return node.children && node.children.some(child => child.type !== "text");
53209 function _inferScriptParser(node) {
53215 if (type === "module" || type === "text/javascript" || type === "text/babel" || type === "application/javascript" || lang === "jsx") {
53219 if (type === "application/x-typescript" || lang === "ts" || lang === "tsx") {
53220 return "typescript";
53223 if (type === "text/markdown") {
53227 if (type === "text/html") {
53231 if (type && (type.endsWith("json") || type.endsWith("importmap"))) {
53235 if (type === "text/x-handlebars-template") {
53240 function inferStyleParser(node) {
53245 if (!lang || lang === "postcss" || lang === "css") {
53249 if (lang === "scss") {
53253 if (lang === "less") {
53258 function inferScriptParser(node, options) {
53259 if (node.name === "script" && !node.attrMap.src) {
53260 if (!node.attrMap.lang && !node.attrMap.type) {
53264 return _inferScriptParser(node);
53267 if (node.name === "style") {
53268 return inferStyleParser(node);
53271 if (options && isVueNonHtmlBlock(node, options)) {
53272 return _inferScriptParser(node) || !("src" in node.attrMap) && inferParserByLanguage$2(node.attrMap.lang, options);
53276 function isBlockLikeCssDisplay(cssDisplay) {
53277 return cssDisplay === "block" || cssDisplay === "list-item" || cssDisplay.startsWith("table");
53280 function isFirstChildLeadingSpaceSensitiveCssDisplay(cssDisplay) {
53281 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
53284 function isLastChildTrailingSpaceSensitiveCssDisplay(cssDisplay) {
53285 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
53288 function isPrevTrailingSpaceSensitiveCssDisplay(cssDisplay) {
53289 return !isBlockLikeCssDisplay(cssDisplay);
53292 function isNextLeadingSpaceSensitiveCssDisplay(cssDisplay) {
53293 return !isBlockLikeCssDisplay(cssDisplay);
53296 function isDanglingSpaceSensitiveCssDisplay(cssDisplay) {
53297 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
53300 function isPreLikeNode(node) {
53301 return getNodeCssStyleWhiteSpace(node).startsWith("pre");
53304 function countParents(path, predicate) {
53307 for (let i = path.stack.length - 1; i >= 0; i--) {
53308 const value = path.stack[i];
53310 if (value && typeof value === "object" && !Array.isArray(value) && predicate(value)) {
53318 function hasParent(node, fn) {
53319 let current = node;
53326 current = current.parent;
53332 function getNodeCssStyleDisplay(node, options) {
53333 if (node.prev && node.prev.type === "comment") {
53334 // <!-- display: block -->
53335 const match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/);
53342 let isInSvgForeignObject = false;
53344 if (node.type === "element" && node.namespace === "svg") {
53345 if (hasParent(node, parent => parent.fullName === "svg:foreignObject")) {
53346 isInSvgForeignObject = true;
53348 return node.name === "svg" ? "inline-block" : "block";
53352 switch (options.htmlWhitespaceSensitivity) {
53361 // See https://github.com/prettier/prettier/issues/8151
53362 if (options.parser === "vue" && node.parent && node.parent.type === "root") {
53366 return node.type === "element" && (!node.namespace || isInSvgForeignObject || isUnknownNamespace(node)) && CSS_DISPLAY_TAGS[node.name] || CSS_DISPLAY_DEFAULT;
53371 function isUnknownNamespace(node) {
53372 return node.type === "element" && !node.hasExplicitNamespace && !["html", "svg"].includes(node.namespace);
53375 function getNodeCssStyleWhiteSpace(node) {
53376 return node.type === "element" && (!node.namespace || isUnknownNamespace(node)) && CSS_WHITE_SPACE_TAGS[node.name] || CSS_WHITE_SPACE_DEFAULT;
53379 function getMinIndentation(text) {
53380 let minIndentation = Infinity;
53382 for (const lineText of text.split("\n")) {
53383 if (lineText.length === 0) {
53387 if (!HTML_WHITESPACE.has(lineText[0])) {
53391 const indentation = getLeadingHtmlWhitespace(lineText).length;
53393 if (lineText.length === indentation) {
53397 if (indentation < minIndentation) {
53398 minIndentation = indentation;
53402 return minIndentation === Infinity ? 0 : minIndentation;
53405 function dedentString(text, minIndent = getMinIndentation(text)) {
53406 return minIndent === 0 ? text : text.split("\n").map(lineText => lineText.slice(minIndent)).join("\n");
53409 function shouldNotPrintClosingTag(node, options) {
53410 return !node.isSelfClosing && !node.endSourceSpan && (hasPrettierIgnore$6(node) || shouldPreserveContent(node.parent, options));
53413 function countChars(text, char) {
53416 for (let i = 0; i < text.length; i++) {
53417 if (text[i] === char) {
53425 function unescapeQuoteEntities(text) {
53426 return text.replace(/'/g, "'").replace(/"/g, '"');
53427 } // top-level elements (excluding <template>, <style> and <script>) in Vue SFC are considered custom block
53428 // See https://vue-loader.vuejs.org/spec.html for detail
53431 const vueRootElementsSet = new Set(["template", "style", "script"]);
53433 function isVueCustomBlock(node, options) {
53434 return isVueSfcBlock(node, options) && !vueRootElementsSet.has(node.fullName);
53437 function isVueSfcBlock(node, options) {
53438 return options.parser === "vue" && node.type === "element" && node.parent.type === "root" && node.fullName.toLowerCase() !== "html";
53441 function isVueNonHtmlBlock(node, options) {
53442 return isVueSfcBlock(node, options) && (isVueCustomBlock(node, options) || node.attrMap.lang && node.attrMap.lang !== "html");
53445 function isVueSlotAttribute(attribute) {
53446 const attributeName = attribute.fullName;
53447 return attributeName.charAt(0) === "#" || attributeName === "slot-scope" || attributeName === "v-slot" || attributeName.startsWith("v-slot:");
53450 function isVueSfcBindingsAttribute(attribute, options) {
53451 const element = attribute.parent;
53453 if (!isVueSfcBlock(element, options)) {
53457 const tagName = element.fullName;
53458 const attributeName = attribute.fullName;
53459 return (// https://github.com/vuejs/rfcs/blob/sfc-improvements/active-rfcs/0000-sfc-script-setup.md
53460 tagName === "script" && attributeName === "setup" || // https://github.com/vuejs/rfcs/blob/sfc-improvements/active-rfcs/0000-sfc-style-variables.md
53461 tagName === "style" && attributeName === "vars"
53466 HTML_ELEMENT_ATTRIBUTES,
53469 htmlTrimPreserveIndentation,
53470 splitByHtmlWhitespace,
53472 getLeadingAndTrailingHtmlWhitespace,
53473 canHaveInterpolation,
53477 forceBreakChildren,
53479 forceNextEmptyLine,
53481 getNodeCssStyleDisplay,
53482 getNodeCssStyleWhiteSpace,
53483 getPrettierIgnoreAttributeCommentData,
53484 hasPrettierIgnore: hasPrettierIgnore$6,
53488 isVueSlotAttribute,
53489 isVueSfcBindingsAttribute,
53490 isDanglingSpaceSensitiveNode,
53491 isIndentationSensitiveNode,
53492 isLeadingSpaceSensitiveNode,
53496 isTrailingSpaceSensitiveNode,
53497 isWhitespaceSensitiveNode,
53498 isUnknownNamespace,
53499 preferHardlineAsLeadingSpaces,
53500 preferHardlineAsTrailingSpaces,
53501 shouldNotPrintClosingTag,
53502 shouldPreserveContent,
53503 unescapeQuoteEntities
53506 var chars$1 = createCommonjsModule(function (module, exports) {
53509 * Copyright Google Inc. All Rights Reserved.
53511 * Use of this source code is governed by an MIT-style license that can be
53512 * found in the LICENSE file at https://angular.io/license
53515 Object.defineProperty(exports, "__esModule", {
53519 exports.$BSPACE = 8;
53522 exports.$VTAB = 11;
53525 exports.$SPACE = 32;
53526 exports.$BANG = 33;
53528 exports.$HASH = 35;
53530 exports.$PERCENT = 37;
53531 exports.$AMPERSAND = 38;
53533 exports.$LPAREN = 40;
53534 exports.$RPAREN = 41;
53535 exports.$STAR = 42;
53536 exports.$PLUS = 43;
53537 exports.$COMMA = 44;
53538 exports.$MINUS = 45;
53539 exports.$PERIOD = 46;
53540 exports.$SLASH = 47;
53541 exports.$COLON = 58;
53542 exports.$SEMICOLON = 59;
53546 exports.$QUESTION = 63;
53555 exports.$LBRACKET = 91;
53556 exports.$BACKSLASH = 92;
53557 exports.$RBRACKET = 93;
53558 exports.$CARET = 94;
53571 exports.$LBRACE = 123;
53572 exports.$BAR = 124;
53573 exports.$RBRACE = 125;
53574 exports.$NBSP = 160;
53575 exports.$PIPE = 124;
53576 exports.$TILDA = 126;
53580 function isWhitespace(code) {
53581 return code >= exports.$TAB && code <= exports.$SPACE || code == exports.$NBSP;
53584 exports.isWhitespace = isWhitespace;
53586 function isDigit(code) {
53587 return exports.$0 <= code && code <= exports.$9;
53590 exports.isDigit = isDigit;
53592 function isAsciiLetter(code) {
53593 return code >= exports.$a && code <= exports.$z || code >= exports.$A && code <= exports.$Z;
53596 exports.isAsciiLetter = isAsciiLetter;
53598 function isAsciiHexDigit(code) {
53599 return code >= exports.$a && code <= exports.$f || code >= exports.$A && code <= exports.$F || isDigit(code);
53602 exports.isAsciiHexDigit = isAsciiHexDigit;
53604 function isNewLine(code) {
53605 return code === exports.$LF || code === exports.$CR;
53608 exports.isNewLine = isNewLine;
53610 function isOctalDigit(code) {
53611 return exports.$0 <= code && code <= exports.$7;
53614 exports.isOctalDigit = isOctalDigit;
53617 var static_symbol = createCommonjsModule(function (module, exports) {
53620 * Copyright Google Inc. All Rights Reserved.
53622 * Use of this source code is governed by an MIT-style license that can be
53623 * found in the LICENSE file at https://angular.io/license
53626 Object.defineProperty(exports, "__esModule", {
53630 * A token representing the a reference to a static type.
53632 * This token is unique for a filePath and name and can be used as a hash table key.
53635 class StaticSymbol {
53636 constructor(filePath, name, members) {
53637 this.filePath = filePath;
53639 this.members = members;
53642 assertNoMembers() {
53643 if (this.members.length) {
53644 throw new Error(`Illegal state: symbol without members expected, but got ${JSON.stringify(this)}.`);
53650 exports.StaticSymbol = StaticSymbol;
53652 * A cache of static symbol used by the StaticReflector to return the same symbol for the
53653 * same symbol values.
53656 class StaticSymbolCache {
53658 this.cache = new Map();
53661 get(declarationFile, name, members) {
53662 members = members || [];
53663 const memberSuffix = members.length ? `.${members.join('.')}` : '';
53664 const key = `"${declarationFile}".${name}${memberSuffix}`;
53665 let result = this.cache.get(key);
53668 result = new StaticSymbol(declarationFile, name, members);
53669 this.cache.set(key, result);
53677 exports.StaticSymbolCache = StaticSymbolCache;
53680 var util$5 = createCommonjsModule(function (module, exports) {
53683 * Copyright Google Inc. All Rights Reserved.
53685 * Use of this source code is governed by an MIT-style license that can be
53686 * found in the LICENSE file at https://angular.io/license
53689 Object.defineProperty(exports, "__esModule", {
53692 const DASH_CASE_REGEXP = /-+([a-z0-9])/g;
53694 function dashCaseToCamelCase(input) {
53695 return input.replace(DASH_CASE_REGEXP, (...m) => m[1].toUpperCase());
53698 exports.dashCaseToCamelCase = dashCaseToCamelCase;
53700 function splitAtColon(input, defaultValues) {
53701 return _splitAt(input, ':', defaultValues);
53704 exports.splitAtColon = splitAtColon;
53706 function splitAtPeriod(input, defaultValues) {
53707 return _splitAt(input, '.', defaultValues);
53710 exports.splitAtPeriod = splitAtPeriod;
53712 function _splitAt(input, character, defaultValues) {
53713 const characterIndex = input.indexOf(character);
53714 if (characterIndex == -1) return defaultValues;
53715 return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()];
53718 function visitValue(value, visitor, context) {
53719 if (Array.isArray(value)) {
53720 return visitor.visitArray(value, context);
53723 if (isStrictStringMap(value)) {
53724 return visitor.visitStringMap(value, context);
53727 if (value == null || typeof value == 'string' || typeof value == 'number' || typeof value == 'boolean') {
53728 return visitor.visitPrimitive(value, context);
53731 return visitor.visitOther(value, context);
53734 exports.visitValue = visitValue;
53736 function isDefined(val) {
53737 return val !== null && val !== undefined;
53740 exports.isDefined = isDefined;
53742 function noUndefined(val) {
53743 return val === undefined ? null : val;
53746 exports.noUndefined = noUndefined;
53748 class ValueTransformer {
53749 visitArray(arr, context) {
53750 return arr.map(value => visitValue(value, this, context));
53753 visitStringMap(map, context) {
53755 Object.keys(map).forEach(key => {
53756 result[key] = visitValue(map[key], this, context);
53761 visitPrimitive(value, context) {
53765 visitOther(value, context) {
53771 exports.ValueTransformer = ValueTransformer;
53772 exports.SyncAsync = {
53773 assertSync: value => {
53774 if (isPromise(value)) {
53775 throw new Error(`Illegal state: value cannot be a promise`);
53780 then: (value, cb) => {
53781 return isPromise(value) ? value.then(cb) : cb(value);
53783 all: syncAsyncValues => {
53784 return syncAsyncValues.some(isPromise) ? Promise.all(syncAsyncValues) : syncAsyncValues;
53788 function error(msg) {
53789 throw new Error(`Internal Error: ${msg}`);
53792 exports.error = error;
53794 function syntaxError(msg, parseErrors) {
53795 const error = Error(msg);
53796 error[ERROR_SYNTAX_ERROR] = true;
53797 if (parseErrors) error[ERROR_PARSE_ERRORS] = parseErrors;
53801 exports.syntaxError = syntaxError;
53802 const ERROR_SYNTAX_ERROR = 'ngSyntaxError';
53803 const ERROR_PARSE_ERRORS = 'ngParseErrors';
53805 function isSyntaxError(error) {
53806 return error[ERROR_SYNTAX_ERROR];
53809 exports.isSyntaxError = isSyntaxError;
53811 function getParseErrors(error) {
53812 return error[ERROR_PARSE_ERRORS] || [];
53815 exports.getParseErrors = getParseErrors; // Escape characters that have a special meaning in Regular Expressions
53817 function escapeRegExp(s) {
53818 return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
53821 exports.escapeRegExp = escapeRegExp;
53822 const STRING_MAP_PROTO = Object.getPrototypeOf({});
53824 function isStrictStringMap(obj) {
53825 return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === STRING_MAP_PROTO;
53828 function utf8Encode(str) {
53831 for (let index = 0; index < str.length; index++) {
53832 let codePoint = str.charCodeAt(index); // decode surrogate
53833 // see https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
53835 if (codePoint >= 0xd800 && codePoint <= 0xdbff && str.length > index + 1) {
53836 const low = str.charCodeAt(index + 1);
53838 if (low >= 0xdc00 && low <= 0xdfff) {
53840 codePoint = (codePoint - 0xd800 << 10) + low - 0xdc00 + 0x10000;
53844 if (codePoint <= 0x7f) {
53845 encoded += String.fromCharCode(codePoint);
53846 } else if (codePoint <= 0x7ff) {
53847 encoded += String.fromCharCode(codePoint >> 6 & 0x1F | 0xc0, codePoint & 0x3f | 0x80);
53848 } else if (codePoint <= 0xffff) {
53849 encoded += String.fromCharCode(codePoint >> 12 | 0xe0, codePoint >> 6 & 0x3f | 0x80, codePoint & 0x3f | 0x80);
53850 } else if (codePoint <= 0x1fffff) {
53851 encoded += String.fromCharCode(codePoint >> 18 & 0x07 | 0xf0, codePoint >> 12 & 0x3f | 0x80, codePoint >> 6 & 0x3f | 0x80, codePoint & 0x3f | 0x80);
53858 exports.utf8Encode = utf8Encode;
53860 function stringify(token) {
53861 if (typeof token === 'string') {
53865 if (token instanceof Array) {
53866 return '[' + token.map(stringify).join(', ') + ']';
53869 if (token == null) {
53873 if (token.overriddenName) {
53874 return `${token.overriddenName}`;
53878 return `${token.name}`;
53881 if (!token.toString) {
53883 } // WARNING: do not try to `JSON.stringify(token)` here
53884 // see https://github.com/angular/angular/issues/23440
53887 const res = token.toString();
53893 const newLineIndex = res.indexOf('\n');
53894 return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
53897 exports.stringify = stringify;
53899 * Lazily retrieves the reference value from a forwardRef.
53902 function resolveForwardRef(type) {
53903 if (typeof type === 'function' && type.hasOwnProperty('__forward_ref__')) {
53910 exports.resolveForwardRef = resolveForwardRef;
53912 * Determine if the argument is shaped like a Promise
53915 function isPromise(obj) {
53916 // allow any Promise/A+ compliant thenable.
53917 // It's up to the caller to ensure that obj.then conforms to the spec
53918 return !!obj && typeof obj.then === 'function';
53921 exports.isPromise = isPromise;
53924 constructor(full) {
53926 const splits = full.split('.');
53927 this.major = splits[0];
53928 this.minor = splits[1];
53929 this.patch = splits.slice(2).join('.');
53934 exports.Version = Version;
53936 const __window = typeof window !== 'undefined' && window;
53938 const __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope && self;
53940 const __global = typeof global !== 'undefined' && global; // Check __global first, because in Node tests both __global and __window may be defined and _global
53941 // should be __global in that case.
53944 const _global = __global || __window || __self;
53946 exports.global = _global;
53949 var compile_metadata = createCommonjsModule(function (module, exports) {
53952 * Copyright Google Inc. All Rights Reserved.
53954 * Use of this source code is governed by an MIT-style license that can be
53955 * found in the LICENSE file at https://angular.io/license
53958 Object.defineProperty(exports, "__esModule", {
53960 }); // group 0: "[prop] or (event) or @trigger"
53961 // group 1: "prop" from "[prop]"
53962 // group 2: "event" from "(event)"
53963 // group 3: "@trigger" from "@trigger"
53965 const HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))|(\@[-\w]+)$/;
53967 function sanitizeIdentifier(name) {
53968 return name.replace(/\W/g, '_');
53971 exports.sanitizeIdentifier = sanitizeIdentifier;
53972 let _anonymousTypeIndex = 0;
53974 function identifierName(compileIdentifier) {
53975 if (!compileIdentifier || !compileIdentifier.reference) {
53979 const ref = compileIdentifier.reference;
53981 if (ref instanceof static_symbol.StaticSymbol) {
53985 if (ref['__anonymousType']) {
53986 return ref['__anonymousType'];
53989 let identifier = util$5.stringify(ref);
53991 if (identifier.indexOf('(') >= 0) {
53992 // case: anonymous functions!
53993 identifier = `anonymous_${_anonymousTypeIndex++}`;
53994 ref['__anonymousType'] = identifier;
53996 identifier = sanitizeIdentifier(identifier);
54002 exports.identifierName = identifierName;
54004 function identifierModuleUrl(compileIdentifier) {
54005 const ref = compileIdentifier.reference;
54007 if (ref instanceof static_symbol.StaticSymbol) {
54008 return ref.filePath;
54012 return `./${util$5.stringify(ref)}`;
54015 exports.identifierModuleUrl = identifierModuleUrl;
54017 function viewClassName(compType, embeddedTemplateIndex) {
54018 return `View_${identifierName({
54019 reference: compType
54020 })}_${embeddedTemplateIndex}`;
54023 exports.viewClassName = viewClassName;
54025 function rendererTypeName(compType) {
54026 return `RenderType_${identifierName({
54027 reference: compType
54031 exports.rendererTypeName = rendererTypeName;
54033 function hostViewClassName(compType) {
54034 return `HostView_${identifierName({
54035 reference: compType
54039 exports.hostViewClassName = hostViewClassName;
54041 function componentFactoryName(compType) {
54042 return `${identifierName({
54043 reference: compType
54047 exports.componentFactoryName = componentFactoryName;
54048 var CompileSummaryKind;
54050 (function (CompileSummaryKind) {
54051 CompileSummaryKind[CompileSummaryKind["Pipe"] = 0] = "Pipe";
54052 CompileSummaryKind[CompileSummaryKind["Directive"] = 1] = "Directive";
54053 CompileSummaryKind[CompileSummaryKind["NgModule"] = 2] = "NgModule";
54054 CompileSummaryKind[CompileSummaryKind["Injectable"] = 3] = "Injectable";
54055 })(CompileSummaryKind = exports.CompileSummaryKind || (exports.CompileSummaryKind = {}));
54057 function tokenName(token) {
54058 return token.value != null ? sanitizeIdentifier(token.value) : identifierName(token.identifier);
54061 exports.tokenName = tokenName;
54063 function tokenReference(token) {
54064 if (token.identifier != null) {
54065 return token.identifier.reference;
54067 return token.value;
54071 exports.tokenReference = tokenReference;
54073 * Metadata about a stylesheet
54076 class CompileStylesheetMetadata {
54082 this.moduleUrl = moduleUrl || null;
54083 this.styles = _normalizeArray(styles);
54084 this.styleUrls = _normalizeArray(styleUrls);
54089 exports.CompileStylesheetMetadata = CompileStylesheetMetadata;
54091 * Metadata regarding compilation of a template.
54094 class CompileTemplateMetadata {
54102 externalStylesheets,
54104 ngContentSelectors,
54107 preserveWhitespaces
54109 this.encapsulation = encapsulation;
54110 this.template = template;
54111 this.templateUrl = templateUrl;
54112 this.htmlAst = htmlAst;
54113 this.styles = _normalizeArray(styles);
54114 this.styleUrls = _normalizeArray(styleUrls);
54115 this.externalStylesheets = _normalizeArray(externalStylesheets);
54116 this.animations = animations ? flatten(animations) : [];
54117 this.ngContentSelectors = ngContentSelectors || [];
54119 if (interpolation && interpolation.length != 2) {
54120 throw new Error(`'interpolation' should have a start and an end symbol.`);
54123 this.interpolation = interpolation;
54124 this.isInline = isInline;
54125 this.preserveWhitespaces = preserveWhitespaces;
54130 ngContentSelectors: this.ngContentSelectors,
54131 encapsulation: this.encapsulation,
54132 styles: this.styles,
54133 animations: this.animations
54139 exports.CompileTemplateMetadata = CompileTemplateMetadata;
54141 * Metadata regarding compilation of a directive.
54144 class CompileDirectiveMetadata {
54166 const hostListeners = {};
54167 const hostProperties = {};
54168 const hostAttributes = {};
54170 if (host != null) {
54171 Object.keys(host).forEach(key => {
54172 const value = host[key];
54173 const matches = key.match(HOST_REG_EXP);
54175 if (matches === null) {
54176 hostAttributes[key] = value;
54177 } else if (matches[1] != null) {
54178 hostProperties[matches[1]] = value;
54179 } else if (matches[2] != null) {
54180 hostListeners[matches[2]] = value;
54185 const inputsMap = {};
54187 if (inputs != null) {
54188 inputs.forEach(bindConfig => {
54189 // canonical syntax: `dirProp: elProp`
54190 // if there is no `:`, use dirProp = elProp
54191 const parts = util$5.splitAtColon(bindConfig, [bindConfig, bindConfig]);
54192 inputsMap[parts[0]] = parts[1];
54196 const outputsMap = {};
54198 if (outputs != null) {
54199 outputs.forEach(bindConfig => {
54200 // canonical syntax: `dirProp: elProp`
54201 // if there is no `:`, use dirProp = elProp
54202 const parts = util$5.splitAtColon(bindConfig, [bindConfig, bindConfig]);
54203 outputsMap[parts[0]] = parts[1];
54207 return new CompileDirectiveMetadata({
54210 isComponent: !!isComponent,
54215 outputs: outputsMap,
54255 this.isHost = !!isHost;
54257 this.isComponent = isComponent;
54258 this.selector = selector;
54259 this.exportAs = exportAs;
54260 this.changeDetection = changeDetection;
54261 this.inputs = inputs;
54262 this.outputs = outputs;
54263 this.hostListeners = hostListeners;
54264 this.hostProperties = hostProperties;
54265 this.hostAttributes = hostAttributes;
54266 this.providers = _normalizeArray(providers);
54267 this.viewProviders = _normalizeArray(viewProviders);
54268 this.queries = _normalizeArray(queries);
54269 this.guards = guards;
54270 this.viewQueries = _normalizeArray(viewQueries);
54271 this.entryComponents = _normalizeArray(entryComponents);
54272 this.template = template;
54273 this.componentViewType = componentViewType;
54274 this.rendererType = rendererType;
54275 this.componentFactory = componentFactory;
54280 summaryKind: CompileSummaryKind.Directive,
54282 isComponent: this.isComponent,
54283 selector: this.selector,
54284 exportAs: this.exportAs,
54285 inputs: this.inputs,
54286 outputs: this.outputs,
54287 hostListeners: this.hostListeners,
54288 hostProperties: this.hostProperties,
54289 hostAttributes: this.hostAttributes,
54290 providers: this.providers,
54291 viewProviders: this.viewProviders,
54292 queries: this.queries,
54293 guards: this.guards,
54294 viewQueries: this.viewQueries,
54295 entryComponents: this.entryComponents,
54296 changeDetection: this.changeDetection,
54297 template: this.template && this.template.toSummary(),
54298 componentViewType: this.componentViewType,
54299 rendererType: this.rendererType,
54300 componentFactory: this.componentFactory
54306 exports.CompileDirectiveMetadata = CompileDirectiveMetadata;
54308 class CompilePipeMetadata {
54316 this.pure = !!pure;
54321 summaryKind: CompileSummaryKind.Pipe,
54330 exports.CompilePipeMetadata = CompilePipeMetadata;
54332 class CompileShallowModuleMetadata {}
54334 exports.CompileShallowModuleMetadata = CompileShallowModuleMetadata;
54336 * Metadata regarding compilation of a module.
54339 class CompileNgModuleMetadata {
54343 declaredDirectives,
54344 exportedDirectives,
54348 bootstrapComponents,
54355 this.type = type || null;
54356 this.declaredDirectives = _normalizeArray(declaredDirectives);
54357 this.exportedDirectives = _normalizeArray(exportedDirectives);
54358 this.declaredPipes = _normalizeArray(declaredPipes);
54359 this.exportedPipes = _normalizeArray(exportedPipes);
54360 this.providers = _normalizeArray(providers);
54361 this.entryComponents = _normalizeArray(entryComponents);
54362 this.bootstrapComponents = _normalizeArray(bootstrapComponents);
54363 this.importedModules = _normalizeArray(importedModules);
54364 this.exportedModules = _normalizeArray(exportedModules);
54365 this.schemas = _normalizeArray(schemas);
54366 this.id = id || null;
54367 this.transitiveModule = transitiveModule || null;
54371 const module = this.transitiveModule;
54373 summaryKind: CompileSummaryKind.NgModule,
54375 entryComponents: module.entryComponents,
54376 providers: module.providers,
54377 modules: module.modules,
54378 exportedDirectives: module.exportedDirectives,
54379 exportedPipes: module.exportedPipes
54385 exports.CompileNgModuleMetadata = CompileNgModuleMetadata;
54387 class TransitiveCompileNgModuleMetadata {
54389 this.directivesSet = new Set();
54390 this.directives = [];
54391 this.exportedDirectivesSet = new Set();
54392 this.exportedDirectives = [];
54393 this.pipesSet = new Set();
54395 this.exportedPipesSet = new Set();
54396 this.exportedPipes = [];
54397 this.modulesSet = new Set();
54399 this.entryComponentsSet = new Set();
54400 this.entryComponents = [];
54401 this.providers = [];
54404 addProvider(provider, module) {
54405 this.providers.push({
54406 provider: provider,
54412 if (!this.directivesSet.has(id.reference)) {
54413 this.directivesSet.add(id.reference);
54414 this.directives.push(id);
54418 addExportedDirective(id) {
54419 if (!this.exportedDirectivesSet.has(id.reference)) {
54420 this.exportedDirectivesSet.add(id.reference);
54421 this.exportedDirectives.push(id);
54426 if (!this.pipesSet.has(id.reference)) {
54427 this.pipesSet.add(id.reference);
54428 this.pipes.push(id);
54432 addExportedPipe(id) {
54433 if (!this.exportedPipesSet.has(id.reference)) {
54434 this.exportedPipesSet.add(id.reference);
54435 this.exportedPipes.push(id);
54440 if (!this.modulesSet.has(id.reference)) {
54441 this.modulesSet.add(id.reference);
54442 this.modules.push(id);
54446 addEntryComponent(ec) {
54447 if (!this.entryComponentsSet.has(ec.componentType)) {
54448 this.entryComponentsSet.add(ec.componentType);
54449 this.entryComponents.push(ec);
54455 exports.TransitiveCompileNgModuleMetadata = TransitiveCompileNgModuleMetadata;
54457 function _normalizeArray(obj) {
54461 class ProviderMeta {
54462 constructor(token, {
54470 this.token = token;
54471 this.useClass = useClass || null;
54472 this.useValue = useValue;
54473 this.useExisting = useExisting;
54474 this.useFactory = useFactory || null;
54475 this.dependencies = deps || null;
54476 this.multi = !!multi;
54481 exports.ProviderMeta = ProviderMeta;
54483 function flatten(list) {
54484 return list.reduce((flat, item) => {
54485 const flatItem = Array.isArray(item) ? flatten(item) : item;
54486 return flat.concat(flatItem);
54490 exports.flatten = flatten;
54492 function jitSourceUrl(url) {
54493 // Note: We need 3 "/" so that ng shows up as a separate domain
54494 // in the chrome dev tools.
54495 return url.replace(/(\w+:\/\/[\w:-]+)?(\/+)?/, 'ng:///');
54498 function templateSourceUrl(ngModuleType, compMeta, templateMeta) {
54501 if (templateMeta.isInline) {
54502 if (compMeta.type.reference instanceof static_symbol.StaticSymbol) {
54503 // Note: a .ts file might contain multiple components with inline templates,
54504 // so we need to give them unique urls, as these will be used for sourcemaps.
54505 url = `${compMeta.type.reference.filePath}.${compMeta.type.reference.name}.html`;
54507 url = `${identifierName(ngModuleType)}/${identifierName(compMeta.type)}.html`;
54510 url = templateMeta.templateUrl;
54513 return compMeta.type.reference instanceof static_symbol.StaticSymbol ? url : jitSourceUrl(url);
54516 exports.templateSourceUrl = templateSourceUrl;
54518 function sharedStylesheetJitUrl(meta, id) {
54519 const pathParts = meta.moduleUrl.split(/\/\\/g);
54520 const baseName = pathParts[pathParts.length - 1];
54521 return jitSourceUrl(`css/${id}${baseName}.ngstyle.js`);
54524 exports.sharedStylesheetJitUrl = sharedStylesheetJitUrl;
54526 function ngModuleJitUrl(moduleMeta) {
54527 return jitSourceUrl(`${identifierName(moduleMeta.type)}/module.ngfactory.js`);
54530 exports.ngModuleJitUrl = ngModuleJitUrl;
54532 function templateJitUrl(ngModuleType, compMeta) {
54533 return jitSourceUrl(`${identifierName(ngModuleType)}/${identifierName(compMeta.type)}.ngfactory.js`);
54536 exports.templateJitUrl = templateJitUrl;
54539 var parse_util = createCommonjsModule(function (module, exports) {
54541 Object.defineProperty(exports, "__esModule", {
54546 * Copyright Google Inc. All Rights Reserved.
54548 * Use of this source code is governed by an MIT-style license that can be
54549 * found in the LICENSE file at https://angular.io/license
54552 class ParseLocation {
54553 constructor(file, offset, line, col) {
54555 this.offset = offset;
54561 return this.offset != null ? `${this.file.url}@${this.line}:${this.col}` : this.file.url;
54565 const source = this.file.content;
54566 const len = source.length;
54567 let offset = this.offset;
54568 let line = this.line;
54569 let col = this.col;
54571 while (offset > 0 && delta < 0) {
54574 const ch = source.charCodeAt(offset);
54576 if (ch == chars$1.$LF) {
54578 const priorLine = source.substr(0, offset - 1).lastIndexOf(String.fromCharCode(chars$1.$LF));
54579 col = priorLine > 0 ? offset - priorLine : offset;
54585 while (offset < len && delta > 0) {
54586 const ch = source.charCodeAt(offset);
54590 if (ch == chars$1.$LF) {
54598 return new ParseLocation(this.file, offset, line, col);
54599 } // Return the source around the location
54600 // Up to `maxChars` or `maxLines` on each side of the location
54603 getContext(maxChars, maxLines) {
54604 const content = this.file.content;
54605 let startOffset = this.offset;
54607 if (startOffset != null) {
54608 if (startOffset > content.length - 1) {
54609 startOffset = content.length - 1;
54612 let endOffset = startOffset;
54616 while (ctxChars < maxChars && startOffset > 0) {
54620 if (content[startOffset] == '\n') {
54621 if (++ctxLines == maxLines) {
54630 while (ctxChars < maxChars && endOffset < content.length - 1) {
54634 if (content[endOffset] == '\n') {
54635 if (++ctxLines == maxLines) {
54642 before: content.substring(startOffset, this.offset),
54643 after: content.substring(this.offset, endOffset + 1)
54652 exports.ParseLocation = ParseLocation;
54654 class ParseSourceFile {
54655 constructor(content, url) {
54656 this.content = content;
54662 exports.ParseSourceFile = ParseSourceFile;
54664 class ParseSourceSpan {
54665 constructor(start, end, details = null) {
54666 this.start = start;
54668 this.details = details;
54672 return this.start.file.content.substring(this.start.offset, this.end.offset);
54677 exports.ParseSourceSpan = ParseSourceSpan;
54678 exports.EMPTY_PARSE_LOCATION = new ParseLocation(new ParseSourceFile('', ''), 0, 0, 0);
54679 exports.EMPTY_SOURCE_SPAN = new ParseSourceSpan(exports.EMPTY_PARSE_LOCATION, exports.EMPTY_PARSE_LOCATION);
54680 var ParseErrorLevel;
54682 (function (ParseErrorLevel) {
54683 ParseErrorLevel[ParseErrorLevel["WARNING"] = 0] = "WARNING";
54684 ParseErrorLevel[ParseErrorLevel["ERROR"] = 1] = "ERROR";
54685 })(ParseErrorLevel = exports.ParseErrorLevel || (exports.ParseErrorLevel = {}));
54688 constructor(span, msg, level = ParseErrorLevel.ERROR) {
54691 this.level = level;
54694 contextualMessage() {
54695 const ctx = this.span.start.getContext(100, 3);
54696 return ctx ? `${this.msg} ("${ctx.before}[${ParseErrorLevel[this.level]} ->]${ctx.after}")` : this.msg;
54700 const details = this.span.details ? `, ${this.span.details}` : '';
54701 return `${this.contextualMessage()}: ${this.span.start}${details}`;
54706 exports.ParseError = ParseError;
54708 function typeSourceSpan(kind, type) {
54709 const moduleUrl = compile_metadata.identifierModuleUrl(type);
54710 const sourceFileName = moduleUrl != null ? `in ${kind} ${compile_metadata.identifierName(type)} in ${moduleUrl}` : `in ${kind} ${compile_metadata.identifierName(type)}`;
54711 const sourceFile = new ParseSourceFile('', sourceFileName);
54712 return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
54715 exports.typeSourceSpan = typeSourceSpan;
54717 * Generates Source Span object for a given R3 Type for JIT mode.
54719 * @param kind Component or Directive.
54720 * @param typeName name of the Component or Directive.
54721 * @param sourceUrl reference to Component or Directive source.
54722 * @returns instance of ParseSourceSpan that represent a given Component or Directive.
54725 function r3JitTypeSourceSpan(kind, typeName, sourceUrl) {
54726 const sourceFileName = `in ${kind} ${typeName} in ${sourceUrl}`;
54727 const sourceFile = new ParseSourceFile('', sourceFileName);
54728 return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
54731 exports.r3JitTypeSourceSpan = r3JitTypeSourceSpan;
54738 htmlTrim: htmlTrim$1,
54739 getLeadingAndTrailingHtmlWhitespace: getLeadingAndTrailingHtmlWhitespace$1,
54740 hasHtmlWhitespace: hasHtmlWhitespace$1,
54741 canHaveInterpolation: canHaveInterpolation$1,
54742 getNodeCssStyleDisplay: getNodeCssStyleDisplay$1,
54743 isDanglingSpaceSensitiveNode: isDanglingSpaceSensitiveNode$1,
54744 isIndentationSensitiveNode: isIndentationSensitiveNode$1,
54745 isLeadingSpaceSensitiveNode: isLeadingSpaceSensitiveNode$1,
54746 isTrailingSpaceSensitiveNode: isTrailingSpaceSensitiveNode$1,
54747 isWhitespaceSensitiveNode: isWhitespaceSensitiveNode$1
54749 const PREPROCESS_PIPELINE = [removeIgnorableFirstLf, mergeIeConditonalStartEndCommentIntoElementOpeningTag, mergeCdataIntoText, extractInterpolation, extractWhitespaces, addCssDisplay, addIsSelfClosing, addHasHtmComponentClosingTag, addIsSpaceSensitive, mergeSimpleElementIntoText];
54751 function preprocess$2(ast, options) {
54752 for (const fn of PREPROCESS_PIPELINE) {
54753 ast = fn(ast, options);
54759 function removeIgnorableFirstLf(ast
54762 return ast.map(node => {
54763 if (node.type === "element" && node.tagDefinition.ignoreFirstLf && node.children.length !== 0 && node.children[0].type === "text" && node.children[0].value[0] === "\n") {
54764 const [text, ...rest] = node.children;
54765 return node.clone({
54766 children: text.value.length === 1 ? rest : [text.clone({
54767 value: text.value.slice(1)
54776 function mergeIeConditonalStartEndCommentIntoElementOpeningTag(ast
54780 * <!--[if ...]><!--><target><!--<![endif]-->
54782 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;
54784 return ast.map(node => {
54785 if (node.children) {
54786 const isTargetResults = node.children.map(isTarget);
54788 if (isTargetResults.some(Boolean)) {
54789 const newChildren = [];
54791 for (let i = 0; i < node.children.length; i++) {
54792 const child = node.children[i];
54794 if (isTargetResults[i + 1]) {
54795 // ieConditionalStartComment
54799 if (isTargetResults[i]) {
54800 const ieConditionalStartComment = child.prev;
54801 const ieConditionalEndComment = child.firstChild;
54802 const startSourceSpan = new ParseSourceSpan(ieConditionalStartComment.sourceSpan.start, ieConditionalEndComment.sourceSpan.end);
54803 const sourceSpan = new ParseSourceSpan(startSourceSpan.start, child.sourceSpan.end);
54804 newChildren.push(child.clone({
54805 condition: ieConditionalStartComment.condition,
54808 children: child.children.slice(1)
54813 newChildren.push(child);
54816 return node.clone({
54817 children: newChildren
54826 function mergeNodeIntoText(ast, shouldMerge, getValue) {
54827 return ast.map(node => {
54828 if (node.children) {
54829 const shouldMergeResults = node.children.map(shouldMerge);
54831 if (shouldMergeResults.some(Boolean)) {
54832 const newChildren = [];
54834 for (let i = 0; i < node.children.length; i++) {
54835 const child = node.children[i];
54837 if (child.type !== "text" && !shouldMergeResults[i]) {
54838 newChildren.push(child);
54842 const newChild = child.type === "text" ? child : child.clone({
54844 value: getValue(child)
54847 if (newChildren.length === 0 || newChildren[newChildren.length - 1].type !== "text") {
54848 newChildren.push(newChild);
54852 const lastChild = newChildren.pop();
54853 newChildren.push(lastChild.clone({
54854 value: lastChild.value + newChild.value,
54855 sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, newChild.sourceSpan.end)
54859 return node.clone({
54860 children: newChildren
54869 function mergeCdataIntoText(ast
54872 return mergeNodeIntoText(ast, node => node.type === "cdata", node => `<![CDATA[${node.value}]]>`);
54875 function mergeSimpleElementIntoText(ast
54878 const isSimpleElement = node => node.type === "element" && node.attrs.length === 0 && node.children.length === 1 && node.firstChild.type === "text" && !hasHtmlWhitespace$1(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";
54880 return ast.map(node => {
54881 if (node.children) {
54882 const isSimpleElementResults = node.children.map(isSimpleElement);
54884 if (isSimpleElementResults.some(Boolean)) {
54885 const newChildren = [];
54887 for (let i = 0; i < node.children.length; i++) {
54888 const child = node.children[i];
54890 if (isSimpleElementResults[i]) {
54891 const lastChild = newChildren.pop();
54892 const nextChild = node.children[++i];
54894 isTrailingSpaceSensitive,
54897 newChildren.push(lastChild.clone({
54898 value: lastChild.value + `<${child.rawName}>` + child.firstChild.value + `</${child.rawName}>` + nextChild.value,
54899 sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, nextChild.sourceSpan.end),
54900 isTrailingSpaceSensitive,
54904 newChildren.push(child);
54908 return node.clone({
54909 children: newChildren
54918 function extractInterpolation(ast, options) {
54919 if (options.parser === "html") {
54923 const interpolationRegex = /{{([\S\s]+?)}}/g;
54924 return ast.map(node => {
54925 if (!canHaveInterpolation$1(node)) {
54929 const newChildren = [];
54931 for (const child of node.children) {
54932 if (child.type !== "text") {
54933 newChildren.push(child);
54937 let startSourceSpan = child.sourceSpan.start;
54938 let endSourceSpan = null;
54939 const components = child.value.split(interpolationRegex);
54941 for (let i = 0; i < components.length; i++, startSourceSpan = endSourceSpan) {
54942 const value = components[i];
54945 endSourceSpan = startSourceSpan.moveBy(value.length);
54947 if (value.length !== 0) {
54951 sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan)
54958 endSourceSpan = startSourceSpan.moveBy(value.length + 4); // `{{` + `}}`
54961 type: "interpolation",
54962 sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan),
54963 children: value.length === 0 ? [] : [{
54966 sourceSpan: new ParseSourceSpan(startSourceSpan.moveBy(2), endSourceSpan.moveBy(-2))
54972 return node.clone({
54973 children: newChildren
54978 * - add `hasLeadingSpaces` field
54979 * - add `hasTrailingSpaces` field
54980 * - add `hasDanglingSpaces` field for parent nodes
54981 * - add `isWhitespaceSensitive`, `isIndentationSensitive` field for text nodes
54982 * - remove insensitive whitespaces
54986 function extractWhitespaces(ast
54989 const TYPE_WHITESPACE = "whitespace";
54990 return ast.map(node => {
54991 if (!node.children) {
54995 if (node.children.length === 0 || node.children.length === 1 && node.children[0].type === "text" && htmlTrim$1(node.children[0].value).length === 0) {
54996 return node.clone({
54998 hasDanglingSpaces: node.children.length !== 0
55002 const isWhitespaceSensitive = isWhitespaceSensitiveNode$1(node);
55003 const isIndentationSensitive = isIndentationSensitiveNode$1(node);
55004 return node.clone({
55005 isWhitespaceSensitive,
55006 isIndentationSensitive,
55007 children: node.children // extract whitespace nodes
55008 .reduce((newChildren, child) => {
55009 if (child.type !== "text" || isWhitespaceSensitive) {
55010 return newChildren.concat(child);
55013 const localChildren = [];
55018 } = getLeadingAndTrailingHtmlWhitespace$1(child.value);
55020 if (leadingWhitespace) {
55021 localChildren.push({
55022 type: TYPE_WHITESPACE
55027 localChildren.push({
55030 sourceSpan: new ParseSourceSpan(child.sourceSpan.start.moveBy(leadingWhitespace.length), child.sourceSpan.end.moveBy(-trailingWhitespace.length))
55034 if (trailingWhitespace) {
55035 localChildren.push({
55036 type: TYPE_WHITESPACE
55040 return newChildren.concat(localChildren);
55041 }, []) // set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
55042 .reduce((newChildren, child, i, children) => {
55043 if (child.type === TYPE_WHITESPACE) {
55044 return newChildren;
55047 const hasLeadingSpaces = i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
55048 const hasTrailingSpaces = i !== children.length - 1 && children[i + 1].type === TYPE_WHITESPACE;
55049 return newChildren.concat(Object.assign({}, child, {
55058 function addIsSelfClosing(ast
55061 return ast.map(node => Object.assign(node, {
55062 isSelfClosing: !node.children || node.type === "element" && (node.tagDefinition.isVoid || // self-closing
55063 node.startSourceSpan === node.endSourceSpan)
55067 function addHasHtmComponentClosingTag(ast, options) {
55068 return ast.map(node => node.type !== "element" ? node : Object.assign(node, {
55069 hasHtmComponentClosingTag: node.endSourceSpan && /^<\s*\/\s*\/\s*>$/.test(options.originalText.slice(node.endSourceSpan.start.offset, node.endSourceSpan.end.offset))
55073 function addCssDisplay(ast, options) {
55074 return ast.map(node => Object.assign(node, {
55075 cssDisplay: getNodeCssStyleDisplay$1(node, options)
55079 * - add `isLeadingSpaceSensitive` field
55080 * - add `isTrailingSpaceSensitive` field
55081 * - add `isDanglingSpaceSensitive` field for parent nodes
55085 function addIsSpaceSensitive(ast, options) {
55086 return ast.map(node => {
55087 if (!node.children) {
55091 if (node.children.length === 0) {
55092 return node.clone({
55093 isDanglingSpaceSensitive: isDanglingSpaceSensitiveNode$1(node)
55097 return node.clone({
55098 children: node.children.map(child => {
55099 return Object.assign({}, child, {
55100 isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode$1(child, options),
55101 isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode$1(child, options)
55103 }).map((child, index, children) => Object.assign({}, child, {
55104 isLeadingSpaceSensitive: index === 0 ? child.isLeadingSpaceSensitive : children[index - 1].isTrailingSpaceSensitive && child.isLeadingSpaceSensitive,
55105 isTrailingSpaceSensitive: index === children.length - 1 ? child.isTrailingSpaceSensitive : children[index + 1].isLeadingSpaceSensitive && child.isTrailingSpaceSensitive
55111 var printPreprocess$2 = preprocess$2;
55113 function hasPragma$3(text) {
55114 return /^\s*<!--\s*@(format|prettier)\s*-->/.test(text);
55117 function insertPragma$7(text) {
55118 return "<!-- @format -->\n\n" + text.replace(/^\s*\n/, "");
55122 hasPragma: hasPragma$3,
55123 insertPragma: insertPragma$7
55126 function locStart$i(node) {
55127 return node.sourceSpan.start.offset;
55130 function locEnd$o(node) {
55131 return node.sourceSpan.end.offset;
55135 locStart: locStart$i,
55146 * v-for="... in ..."
55147 * v-for="... of ..."
55148 * v-for="(..., ...) in ..."
55149 * v-for="(..., ...) of ..."
55152 function printVueFor(value, textToDoc) {
55157 } = parseVueFor(value);
55158 return concat$G([group$u(textToDoc(`function _(${left}) {}`, {
55160 __isVueForBindingLeft: true
55161 })), " ", operator, " ", textToDoc(right, {
55162 parser: "__js_expression"
55164 stripTrailingHardline: true
55166 } // modified from https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/parser/index.js#L370-L387
55169 function parseVueFor(value) {
55170 const forAliasRE = /([^]*?)\s+(in|of)\s+([^]*)/;
55171 const forIteratorRE = /,([^,\]}]*)(?:,([^,\]}]*))?$/;
55172 const stripParensRE = /^\(|\)$/g;
55173 const inMatch = value.match(forAliasRE);
55180 res.for = inMatch[3].trim();
55181 const alias = inMatch[1].trim().replace(stripParensRE, "");
55182 const iteratorMatch = alias.match(forIteratorRE);
55184 if (iteratorMatch) {
55185 res.alias = alias.replace(forIteratorRE, "");
55186 res.iterator1 = iteratorMatch[1].trim();
55188 if (iteratorMatch[2]) {
55189 res.iterator2 = iteratorMatch[2].trim();
55196 left: `${[res.alias, res.iterator1, res.iterator2].filter(Boolean).join(",")}`,
55197 operator: inMatch[2],
55202 function printVueBindings(value, textToDoc) {
55203 return textToDoc(`function _(${value}) {}`, {
55205 __isVueBindings: true
55207 stripTrailingHardline: true
55211 function isVueEventBindingExpression$2(eventBindingValue) {
55212 // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/codegen/events.js#L3-L4
55213 // arrow function or anonymous function
55214 const fnExpRE = /^([\w$]+|\([^)]*?\))\s*=>|^function\s*\(/; // simple member expression chain (a, a.b, a['b'], a["b"], a[0], a[b])
55216 const simplePathRE = /^[$A-Z_a-z][\w$]*(?:\.[$A-Z_a-z][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[$A-Z_a-z][\w$]*])*$/; // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/helpers.js#L104
55218 const value = eventBindingValue.trim();
55219 return fnExpRE.test(value) || simplePathRE.test(value);
55223 isVueEventBindingExpression: isVueEventBindingExpression$2,
55228 var parseSrcset = createCommonjsModule(function (module) {
55232 * By Alex Bell | MIT License
55234 * JS Parser for the string value that appears in markup <img srcset="here">
55236 * @returns Array [{url: _, d: _, w: _, h:_}, ...]
55238 * Based super duper closely on the reference algorithm at:
55239 * https://html.spec.whatwg.org/multipage/embedded-content.html#parse-a-srcset-attribute
55241 * Most comments are copied in directly from the spec
55242 * (except for comments in parens).
55244 (function (root, factory) {
55245 if ( module.exports) {
55246 // Node. Does not work with strict CommonJS, but
55247 // only CommonJS-like environments that support module.exports,
55249 module.exports = factory();
55251 // Browser globals (root is window)
55252 root.parseSrcset = factory();
55254 })(this, function () {
55255 // 1. Let input be the value passed to this algorithm.
55256 return function (input, options) {
55257 var logger = options && options.logger || console; // UTILITY FUNCTIONS
55258 // Manual is faster than RegEx
55259 // http://bjorn.tipling.com/state-and-regular-expressions-in-javascript
55260 // http://jsperf.com/whitespace-character/5
55262 function isSpace(c) {
55263 return c === "\u0020" || // space
55264 c === "\u0009" || // horizontal tab
55265 c === "\u000A" || // new line
55266 c === "\u000C" || // form feed
55267 c === "\u000D"; // carriage return
55270 function collectCharacters(regEx) {
55272 match = regEx.exec(input.substring(pos));
55276 pos += chars.length;
55281 var inputLength = input.length,
55282 // (Don't use \s, to avoid matching non-breaking space)
55283 regexLeadingSpaces = /^[ \t\n\r\u000c]+/,
55284 regexLeadingCommasOrSpaces = /^[, \t\n\r\u000c]+/,
55285 regexLeadingNotSpaces = /^[^ \t\n\r\u000c]+/,
55286 regexTrailingCommas = /[,]+$/,
55287 regexNonNegativeInteger = /^\d+$/,
55288 // ( Positive or negative or unsigned integers or decimals, without or without exponents.
55289 // Must include at least one digit.
55290 // According to spec tests any decimal point must be followed by a digit.
55291 // No leading plus sign is allowed.)
55292 // https://html.spec.whatwg.org/multipage/infrastructure.html#valid-floating-point-number
55293 regexFloatingPoint = /^-?(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/,
55299 // 2. Let position be a pointer into input, initially pointing at the start
55302 // 3. Let candidates be an initially empty source set.
55303 candidates = []; // 4. Splitting loop: Collect a sequence of characters that are space
55304 // characters or U+002C COMMA characters. If any U+002C COMMA characters
55305 // were collected, that is a parse error.
55308 collectCharacters(regexLeadingCommasOrSpaces); // 5. If position is past the end of input, return candidates and abort these steps.
55310 if (pos >= inputLength) {
55311 return candidates; // (we're done, this is the sole return path)
55312 } // 6. Collect a sequence of characters that are not space characters,
55313 // and let that be url.
55316 url = collectCharacters(regexLeadingNotSpaces); // 7. Let descriptors be a new empty list.
55318 descriptors = []; // 8. If url ends with a U+002C COMMA character (,), follow these substeps:
55319 // (1). Remove all trailing U+002C COMMA characters from url. If this removed
55320 // more than one character, that is a parse error.
55322 if (url.slice(-1) === ",") {
55323 url = url.replace(regexTrailingCommas, ""); // (Jump ahead to step 9 to skip tokenization and just push the candidate).
55325 parseDescriptors(); // Otherwise, follow these substeps:
55328 } // (close else of step 8)
55329 // 16. Return to the step labeled splitting loop.
55331 } // (Close of big while loop.)
55334 * Tokenizes descriptor properties prior to parsing
55335 * Returns undefined.
55339 function tokenize() {
55340 // 8.1. Descriptor tokeniser: Skip whitespace
55341 collectCharacters(regexLeadingSpaces); // 8.2. Let current descriptor be the empty string.
55343 currentDescriptor = ""; // 8.3. Let state be in descriptor.
55345 state = "in descriptor";
55348 // 8.4. Let c be the character at position.
55349 c = input.charAt(pos); // Do the following depending on the value of state.
55350 // For the purpose of this step, "EOF" is a special character representing
55351 // that position is past the end of input.
55354 if (state === "in descriptor") {
55355 // Do the following, depending on the value of c:
55357 // If current descriptor is not empty, append current descriptor to
55358 // descriptors and let current descriptor be the empty string.
55359 // Set state to after descriptor.
55361 if (currentDescriptor) {
55362 descriptors.push(currentDescriptor);
55363 currentDescriptor = "";
55364 state = "after descriptor";
55365 } // U+002C COMMA (,)
55366 // Advance position to the next character in input. If current descriptor
55367 // is not empty, append current descriptor to descriptors. Jump to the step
55368 // labeled descriptor parser.
55370 } else if (c === ",") {
55373 if (currentDescriptor) {
55374 descriptors.push(currentDescriptor);
55377 parseDescriptors();
55378 return; // U+0028 LEFT PARENTHESIS (()
55379 // Append c to current descriptor. Set state to in parens.
55380 } else if (c === "\u0028") {
55381 currentDescriptor = currentDescriptor + c;
55382 state = "in parens"; // EOF
55383 // If current descriptor is not empty, append current descriptor to
55384 // descriptors. Jump to the step labeled descriptor parser.
55385 } else if (c === "") {
55386 if (currentDescriptor) {
55387 descriptors.push(currentDescriptor);
55390 parseDescriptors();
55391 return; // Anything else
55392 // Append c to current descriptor.
55394 currentDescriptor = currentDescriptor + c;
55395 } // (end "in descriptor"
55398 } else if (state === "in parens") {
55399 // U+0029 RIGHT PARENTHESIS ())
55400 // Append c to current descriptor. Set state to in descriptor.
55402 currentDescriptor = currentDescriptor + c;
55403 state = "in descriptor"; // EOF
55404 // Append current descriptor to descriptors. Jump to the step labeled
55405 // descriptor parser.
55406 } else if (c === "") {
55407 descriptors.push(currentDescriptor);
55408 parseDescriptors();
55409 return; // Anything else
55410 // Append c to current descriptor.
55412 currentDescriptor = currentDescriptor + c;
55413 } // After descriptor
55415 } else if (state === "after descriptor") {
55416 // Do the following, depending on the value of c:
55417 // Space character: Stay in this state.
55418 if (isSpace(c)) ; else if (c === "") {
55419 parseDescriptors();
55420 return; // Anything else
55421 // Set state to in descriptor. Set position to the previous character in input.
55423 state = "in descriptor";
55426 } // Advance position to the next character in input.
55429 pos += 1; // Repeat this step.
55430 } // (close while true loop)
55434 * Adds descriptor properties to a candidate, pushes to the candidates array
55435 * @return undefined
55437 // Declared outside of the while loop so that it's only created once.
55440 function parseDescriptors() {
55441 // 9. Descriptor parser: Let error be no.
55442 var pError = false,
55443 // 10. Let width be absent.
55444 // 11. Let density be absent.
55445 // 12. Let future-compat-h be absent. (We're implementing it now as h)
55455 floatVal; // 13. For each descriptor in descriptors, run the appropriate set of steps
55456 // from the following list:
55458 for (i = 0; i < descriptors.length; i++) {
55459 desc = descriptors[i];
55460 lastChar = desc[desc.length - 1];
55461 value = desc.substring(0, desc.length - 1);
55462 intVal = parseInt(value, 10);
55463 floatVal = parseFloat(value); // If the descriptor consists of a valid non-negative integer followed by
55464 // a U+0077 LATIN SMALL LETTER W character
55466 if (regexNonNegativeInteger.test(value) && lastChar === "w") {
55467 // If width and density are not both absent, then let error be yes.
55470 } // Apply the rules for parsing non-negative integers to the descriptor.
55471 // If the result is zero, let error be yes.
55472 // Otherwise, let width be the result.
55475 if (intVal === 0) {
55479 } // If the descriptor consists of a valid floating-point number followed by
55480 // a U+0078 LATIN SMALL LETTER X character
55482 } else if (regexFloatingPoint.test(value) && lastChar === "x") {
55483 // If width, density and future-compat-h are not all absent, then let error
55487 } // Apply the rules for parsing floating-point number values to the descriptor.
55488 // If the result is less than zero, let error be yes. Otherwise, let density
55492 if (floatVal < 0) {
55496 } // If the descriptor consists of a valid non-negative integer followed by
55497 // a U+0068 LATIN SMALL LETTER H character
55499 } else if (regexNonNegativeInteger.test(value) && lastChar === "h") {
55500 // If height and density are not both absent, then let error be yes.
55503 } // Apply the rules for parsing non-negative integers to the descriptor.
55504 // If the result is zero, let error be yes. Otherwise, let future-compat-h
55508 if (intVal === 0) {
55512 } // Anything else, Let error be yes.
55517 } // (close step 13 for loop)
55518 // 15. If error is still no, then append a new image source to candidates whose
55519 // URL is url, associated with a width width if not absent and a pixel
55520 // density density if not absent. Otherwise, there is a parse error.
55524 candidate.url = url;
55538 candidates.push(candidate);
55539 } else if (logger && logger.error) {
55540 logger.error("Invalid srcset descriptor found in '" + input + "' at '" + desc + "'.");
55542 } // (close parseDescriptors fn)
55551 ifBreak: ifBreak$i,
55557 function printImgSrcset(value) {
55558 const srcset = parseSrcset(value, {
55561 throw new Error(message);
55566 const hasW = srcset.some(({
55569 const hasH = srcset.some(({
55572 const hasX = srcset.some(({
55576 if (hasW + hasH + hasX > 1) {
55577 throw new Error("Mixed descriptor in srcset is not supported");
55580 const key = hasW ? "w" : hasH ? "h" : "d";
55581 const unit = hasW ? "w" : hasH ? "h" : "x";
55583 const getMax = values => Math.max(...values);
55585 const urls = srcset.map(src => src.url);
55586 const maxUrlLength = getMax(urls.map(url => url.length));
55587 const descriptors = srcset.map(src => src[key]).map(descriptor => descriptor ? descriptor.toString() : "");
55588 const descriptorLeftLengths = descriptors.map(descriptor => {
55589 const index = descriptor.indexOf(".");
55590 return index === -1 ? descriptor.length : index;
55592 const maxDescriptorLeftLength = getMax(descriptorLeftLengths);
55593 return join$l(concat$H([",", line$o]), urls.map((url, index) => {
55594 const parts = [url];
55595 const descriptor = descriptors[index];
55598 const urlPadding = maxUrlLength - url.length + 1;
55599 const descriptorPadding = maxDescriptorLeftLength - descriptorLeftLengths[index];
55600 const alignment = " ".repeat(urlPadding + descriptorPadding);
55601 parts.push(ifBreak$i(alignment, " "), descriptor + unit);
55604 return concat$H(parts);
55608 function printClassNames(value) {
55609 return value.trim().split(/\s+/).join(" ");
55612 var syntaxAttribute = {
55621 normalizeParts: normalizeParts$2
55625 replaceEndOfLineWith: replaceEndOfLineWith$2
55628 print: printFrontMatter$2
55631 breakParent: breakParent$7,
55632 dedentToRoot: dedentToRoot$2,
55635 hardline: hardline$t,
55636 ifBreak: ifBreak$j,
55640 literalline: literalline$5,
55641 softline: softline$m
55644 htmlTrimPreserveIndentation: htmlTrimPreserveIndentation$1,
55645 splitByHtmlWhitespace: splitByHtmlWhitespace$1,
55646 countChars: countChars$1,
55647 countParents: countParents$1,
55648 dedentString: dedentString$1,
55649 forceBreakChildren: forceBreakChildren$1,
55650 forceBreakContent: forceBreakContent$1,
55651 forceNextEmptyLine: forceNextEmptyLine$1,
55652 getLastDescendant: getLastDescendant$1,
55653 getPrettierIgnoreAttributeCommentData: getPrettierIgnoreAttributeCommentData$1,
55654 hasPrettierIgnore: hasPrettierIgnore$7,
55655 inferScriptParser: inferScriptParser$1,
55656 isVueCustomBlock: isVueCustomBlock$1,
55657 isVueNonHtmlBlock: isVueNonHtmlBlock$1,
55658 isVueSlotAttribute: isVueSlotAttribute$1,
55659 isVueSfcBindingsAttribute: isVueSfcBindingsAttribute$1,
55660 isScriptLikeTag: isScriptLikeTag$1,
55661 isTextLikeNode: isTextLikeNode$1,
55662 preferHardlineAsLeadingSpaces: preferHardlineAsLeadingSpaces$1,
55663 shouldNotPrintClosingTag: shouldNotPrintClosingTag$1,
55664 shouldPreserveContent: shouldPreserveContent$1,
55665 unescapeQuoteEntities: unescapeQuoteEntities$1,
55666 isPreLikeNode: isPreLikeNode$1
55669 insertPragma: insertPragma$8
55672 locStart: locStart$j,
55676 printVueFor: printVueFor$1,
55677 printVueBindings: printVueBindings$1,
55678 isVueEventBindingExpression: isVueEventBindingExpression$3
55681 printImgSrcset: printImgSrcset$1,
55682 printClassNames: printClassNames$1
55683 } = syntaxAttribute;
55685 function concat$I(parts) {
55686 const newParts = normalizeParts$2(parts);
55687 return newParts.length === 0 ? "" : newParts.length === 1 ? newParts[0] : builders.concat(newParts);
55690 function embed$4(path, print, textToDoc, options) {
55691 const node = path.getValue();
55693 switch (node.type) {
55696 if (isScriptLikeTag$1(node) || node.type === "interpolation") {
55697 // Fall through to "text"
55701 if (!node.isSelfClosing && isVueNonHtmlBlock$1(node, options)) {
55702 const parser = inferScriptParser$1(node, options);
55708 const content = getNodeContent(node, options);
55709 let isEmpty = /^\s*$/.test(content);
55713 doc = textToDoc(htmlTrimPreserveIndentation$1(content), {
55716 stripTrailingHardline: true
55718 isEmpty = doc === "";
55721 return concat$I([printOpeningTagPrefix(node, options), group$v(printOpeningTag(path, options, print)), isEmpty ? "" : hardline$t, doc, isEmpty ? "" : hardline$t, printClosingTag(node, options), printClosingTagSuffix(node, options)]);
55729 if (isScriptLikeTag$1(node.parent)) {
55730 const parser = inferScriptParser$1(node.parent);
55733 const value = parser === "markdown" ? dedentString$1(node.value.replace(/^[^\S\n]*?\n/, "")) : node.value;
55734 const textToDocOptions = {
55738 if (options.parser === "html" && parser === "babel") {
55739 let sourceType = "script";
55744 if (attrMap && (attrMap.type === "module" || attrMap.type === "text/babel" && attrMap["data-type"] === "module")) {
55745 sourceType = "module";
55748 textToDocOptions.__babelSourceType = sourceType;
55751 return builders.concat([concat$I([breakParent$7, printOpeningTagPrefix(node, options), textToDoc(value, textToDocOptions, {
55752 stripTrailingHardline: true
55753 }), printClosingTagSuffix(node, options)])]);
55755 } else if (node.parent.type === "interpolation") {
55756 return concat$I([indent$v(concat$I([line$p, textToDoc(node.value, Object.assign({
55757 __isInHtmlInterpolation: true
55758 }, options.parser === "angular" ? {
55759 parser: "__ng_interpolation",
55760 trailingComma: "none"
55761 } : options.parser === "vue" ? {
55762 parser: "__vue_expression"
55764 parser: "__js_expression"
55766 stripTrailingHardline: true
55767 })])), node.parent.next && needsToBorrowPrevClosingTagEndMarker(node.parent.next) ? " " : line$p]);
55777 } // lit-html: html`<my-element obj=${obj}></my-element>`
55780 if (/^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
55781 return concat$I([node.rawName, "=", node.value]);
55782 } // lwc: html`<my-element data-for={value}></my-element>`
55785 if (options.parser === "lwc") {
55786 const interpolationRegex = /^{[\S\s]*}$/;
55788 if (interpolationRegex.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
55789 return concat$I([node.rawName, "=", node.value]);
55793 const embeddedAttributeValueDoc = printEmbeddedAttributeValue(node, (code, opts) => // strictly prefer single quote to avoid unnecessary html entity escape
55794 textToDoc(code, Object.assign({
55795 __isInHtmlAttribute: true
55797 stripTrailingHardline: true
55800 if (embeddedAttributeValueDoc) {
55801 return concat$I([node.rawName, '="', group$v(mapDoc$4(embeddedAttributeValueDoc, doc => typeof doc === "string" ? doc.replace(/"/g, """) : doc)), '"']);
55807 case "front-matter":
55808 return printFrontMatter$2(node, textToDoc);
55812 function genericPrint$5(path, options, print) {
55813 const node = path.getValue();
55815 switch (node.type) {
55816 case "front-matter":
55817 return concat$I(replaceEndOfLineWith$2(node.raw, literalline$5));
55820 if (options.__onHtmlRoot) {
55821 options.__onHtmlRoot(node);
55822 } // use original concat to not break stripTrailingHardline
55825 return builders.concat([group$v(printChildren$2(path, options, print)), hardline$t]);
55828 case "ieConditionalComment":
55830 if (shouldPreserveContent$1(node, options)) {
55831 return concat$I([].concat(printOpeningTagPrefix(node, options), group$v(printOpeningTag(path, options, print)), replaceEndOfLineWith$2(getNodeContent(node, options), literalline$5), printClosingTag(node, options), printClosingTagSuffix(node, options)));
55842 * exception: break if the opening tag breaks
55855 const shouldHugContent = node.children.length === 1 && node.firstChild.type === "interpolation" && node.firstChild.isLeadingSpaceSensitive && !node.firstChild.hasLeadingSpaces && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces;
55856 const attrGroupId = Symbol("element-attr-group-id");
55857 return concat$I([group$v(concat$I([group$v(printOpeningTag(path, options, print), {
55859 }), node.children.length === 0 ? node.hasDanglingSpaces && node.isDanglingSpaceSensitive ? line$p : "" : concat$I([forceBreakContent$1(node) ? breakParent$7 : "", (childrenDoc => shouldHugContent ? ifBreak$j(indent$v(childrenDoc), childrenDoc, {
55860 groupId: attrGroupId
55861 }) : (isScriptLikeTag$1(node) || isVueCustomBlock$1(node, options)) && node.parent.type === "root" && options.parser === "vue" && !options.vueIndentScriptAndStyle ? childrenDoc : indent$v(childrenDoc))(concat$I([shouldHugContent ? ifBreak$j(softline$m, "", {
55862 groupId: attrGroupId
55863 }) : node.firstChild.hasLeadingSpaces && node.firstChild.isLeadingSpaceSensitive ? line$p : node.firstChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive ? dedentToRoot$2(softline$m) : softline$m, printChildren$2(path, options, print)])), (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? " " : "" : shouldHugContent ? ifBreak$j(softline$m, "", {
55864 groupId: attrGroupId
55865 }) : node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? line$p : (node.lastChild.type === "comment" || node.lastChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive) && new RegExp(`\\n[\\t ]{${options.tabWidth * countParents$1(path, n => n.parent && n.parent.type !== "root")}}$`).test(node.lastChild.value) ?
55874 "" : softline$m])])), printClosingTag(node, options)]);
55877 case "ieConditionalStartComment":
55878 case "ieConditionalEndComment":
55879 return concat$I([printOpeningTagStart(node), printClosingTagEnd(node)]);
55881 case "interpolation":
55882 return concat$I([printOpeningTagStart(node, options), concat$I(path.map(print, "children")), printClosingTagEnd(node, options)]);
55886 if (node.parent.type === "interpolation") {
55887 // replace the trailing literalline with hardline for better readability
55888 const trailingNewlineRegex = /\n[^\S\n]*?$/;
55889 const hasTrailingNewline = trailingNewlineRegex.test(node.value);
55890 const value = hasTrailingNewline ? node.value.replace(trailingNewlineRegex, "") : node.value;
55891 return concat$I([concat$I(replaceEndOfLineWith$2(value, literalline$5)), hasTrailingNewline ? hardline$t : ""]);
55894 return fill$6(normalizeParts$2([].concat(printOpeningTagPrefix(node, options), getTextValueParts(node), printClosingTagSuffix(node, options))));
55898 return concat$I([group$v(concat$I([printOpeningTagStart(node, options), " ", node.value.replace(/^html\b/i, "html").replace(/\s+/g, " ")])), printClosingTagEnd(node, options)]);
55902 return concat$I([printOpeningTagPrefix(node, options), concat$I(replaceEndOfLineWith$2(options.originalText.slice(locStart$j(node), locEnd$p(node)), literalline$5)), printClosingTagSuffix(node, options)]);
55907 if (node.value === null) {
55908 return node.rawName;
55911 const value = unescapeQuoteEntities$1(node.value);
55912 const singleQuoteCount = countChars$1(value, "'");
55913 const doubleQuoteCount = countChars$1(value, '"');
55914 const quote = singleQuoteCount < doubleQuoteCount ? "'" : '"';
55915 return concat$I([node.rawName, concat$I(["=", quote, concat$I(replaceEndOfLineWith$2(quote === '"' ? value.replace(/"/g, """) : value.replace(/'/g, "'"), literalline$5)), quote])]);
55919 /* istanbul ignore next */
55920 throw new Error(`Unexpected node type ${node.type}`);
55924 function printChildren$2(path, options, print) {
55925 const node = path.getValue();
55927 if (forceBreakChildren$1(node)) {
55928 return concat$I([breakParent$7, concat$I(path.map(childPath => {
55929 const childNode = childPath.getValue();
55930 const prevBetweenLine = !childNode.prev ? "" : printBetweenLine(childNode.prev, childNode);
55931 return concat$I([!prevBetweenLine ? "" : concat$I([prevBetweenLine, forceNextEmptyLine$1(childNode.prev) ? hardline$t : ""]), printChild(childPath)]);
55935 const groupIds = node.children.map(() => Symbol(""));
55936 return concat$I(path.map((childPath, childIndex) => {
55937 const childNode = childPath.getValue();
55939 if (isTextLikeNode$1(childNode)) {
55940 if (childNode.prev && isTextLikeNode$1(childNode.prev)) {
55941 const prevBetweenLine = printBetweenLine(childNode.prev, childNode);
55943 if (prevBetweenLine) {
55944 if (forceNextEmptyLine$1(childNode.prev)) {
55945 return concat$I([hardline$t, hardline$t, printChild(childPath)]);
55948 return concat$I([prevBetweenLine, printChild(childPath)]);
55952 return printChild(childPath);
55955 const prevParts = [];
55956 const leadingParts = [];
55957 const trailingParts = [];
55958 const nextParts = [];
55959 const prevBetweenLine = childNode.prev ? printBetweenLine(childNode.prev, childNode) : "";
55960 const nextBetweenLine = childNode.next ? printBetweenLine(childNode, childNode.next) : "";
55962 if (prevBetweenLine) {
55963 if (forceNextEmptyLine$1(childNode.prev)) {
55964 prevParts.push(hardline$t, hardline$t);
55965 } else if (prevBetweenLine === hardline$t) {
55966 prevParts.push(hardline$t);
55968 if (isTextLikeNode$1(childNode.prev)) {
55969 leadingParts.push(prevBetweenLine);
55971 leadingParts.push(ifBreak$j("", softline$m, {
55972 groupId: groupIds[childIndex - 1]
55978 if (nextBetweenLine) {
55979 if (forceNextEmptyLine$1(childNode)) {
55980 if (isTextLikeNode$1(childNode.next)) {
55981 nextParts.push(hardline$t, hardline$t);
55983 } else if (nextBetweenLine === hardline$t) {
55984 if (isTextLikeNode$1(childNode.next)) {
55985 nextParts.push(hardline$t);
55988 trailingParts.push(nextBetweenLine);
55992 return concat$I([].concat(prevParts, group$v(concat$I([concat$I(leadingParts), group$v(concat$I([printChild(childPath), concat$I(trailingParts)]), {
55993 id: groupIds[childIndex]
55994 })])), nextParts));
55997 function printChild(childPath) {
55998 const child = childPath.getValue();
56000 if (hasPrettierIgnore$7(child)) {
56001 return concat$I([].concat(printOpeningTagPrefix(child, options), replaceEndOfLineWith$2(options.originalText.slice(locStart$j(child) + (child.prev && needsToBorrowNextOpeningTagStartMarker(child.prev) ? printOpeningTagStartMarker(child).length : 0), locEnd$p(child) - (child.next && needsToBorrowPrevClosingTagEndMarker(child.next) ? printClosingTagEndMarker(child, options).length : 0)), literalline$5), printClosingTagSuffix(child, options)));
56004 return print(childPath);
56007 function printBetweenLine(prevNode, nextNode) {
56008 return isTextLikeNode$1(prevNode) && isTextLikeNode$1(nextNode) ? prevNode.isTrailingSpaceSensitive ? prevNode.hasTrailingSpaces ? preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$t : line$p : "" : preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$t : softline$m : needsToBorrowNextOpeningTagStartMarker(prevNode) && (hasPrettierIgnore$7(nextNode) ||
56014 nextNode.firstChild ||
56020 nextNode.isSelfClosing ||
56026 nextNode.type === "element" && nextNode.attrs.length !== 0) ||
56033 prevNode.type === "element" && prevNode.isSelfClosing && needsToBorrowPrevClosingTagEndMarker(nextNode) ? "" : !nextNode.isLeadingSpaceSensitive || preferHardlineAsLeadingSpaces$1(nextNode) ||
56035 * Want to write us a letter? Use our<a
56036 * ><b><a>mailing address</a></b></a
56040 needsToBorrowPrevClosingTagEndMarker(nextNode) && prevNode.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild) && prevNode.lastChild.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild.lastChild) ? hardline$t : nextNode.hasLeadingSpaces ? line$p : softline$m;
56044 function getNodeContent(node, options) {
56045 let start = node.startSourceSpan.end.offset;
56047 if (node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild)) {
56048 start -= printOpeningTagEndMarker(node).length;
56051 let end = node.endSourceSpan.start.offset;
56053 if (node.lastChild && needsToBorrowParentClosingTagStartMarker(node.lastChild)) {
56054 end += printClosingTagStartMarker(node, options).length;
56055 } else if (needsToBorrowLastChildClosingTagEndMarker(node)) {
56056 end -= printClosingTagEndMarker(node.lastChild, options).length;
56059 return options.originalText.slice(start, end);
56062 function printAttributes(path, options, print) {
56063 const node = path.getValue();
56065 if (!node.attrs || node.attrs.length === 0) {
56066 return node.isSelfClosing ?
56074 const ignoreAttributeData = node.prev && node.prev.type === "comment" && getPrettierIgnoreAttributeCommentData$1(node.prev.value);
56075 const hasPrettierIgnoreAttribute = typeof ignoreAttributeData === "boolean" ? () => ignoreAttributeData : Array.isArray(ignoreAttributeData) ? attribute => ignoreAttributeData.includes(attribute.rawName) : () => false;
56076 const printedAttributes = path.map(attributePath => {
56077 const attribute = attributePath.getValue();
56078 return hasPrettierIgnoreAttribute(attribute) ? concat$I(replaceEndOfLineWith$2(options.originalText.slice(locStart$j(attribute), locEnd$p(attribute)), literalline$5)) : print(attributePath);
56080 const forceNotToBreakAttrContent = node.type === "element" && node.fullName === "script" && node.attrs.length === 1 && node.attrs[0].fullName === "src" && node.children.length === 0;
56081 const parts = [indent$v(concat$I([forceNotToBreakAttrContent ? " " : line$p, join$m(line$p, printedAttributes)]))];
56090 node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ||
56097 node.isSelfClosing && needsToBorrowLastChildClosingTagEndMarker(node.parent) || forceNotToBreakAttrContent) {
56098 parts.push(node.isSelfClosing ? " " : "");
56100 parts.push(node.isSelfClosing ? line$p : softline$m);
56103 return concat$I(parts);
56106 function printOpeningTag(path, options, print) {
56107 const node = path.getValue();
56108 return concat$I([printOpeningTagStart(node, options), printAttributes(path, options, print), node.isSelfClosing ? "" : printOpeningTagEnd(node)]);
56111 function printOpeningTagStart(node, options) {
56112 return node.prev && needsToBorrowNextOpeningTagStartMarker(node.prev) ? "" : concat$I([printOpeningTagPrefix(node, options), printOpeningTagStartMarker(node)]);
56115 function printOpeningTagEnd(node) {
56116 return node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ? "" : printOpeningTagEndMarker(node);
56119 function printClosingTag(node, options) {
56120 return concat$I([node.isSelfClosing ? "" : printClosingTagStart(node, options), printClosingTagEnd(node, options)]);
56123 function printClosingTagStart(node, options) {
56124 return node.lastChild && needsToBorrowParentClosingTagStartMarker(node.lastChild) ? "" : concat$I([printClosingTagPrefix(node, options), printClosingTagStartMarker(node, options)]);
56127 function printClosingTagEnd(node, options) {
56128 return (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? "" : concat$I([printClosingTagEndMarker(node, options), printClosingTagSuffix(node, options)]);
56131 function needsToBorrowNextOpeningTagStartMarker(node) {
56137 return node.next && !isTextLikeNode$1(node.next) && isTextLikeNode$1(node) && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces;
56140 function needsToBorrowParentOpeningTagEndMarker(node) {
56150 return !node.prev && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
56153 function needsToBorrowPrevClosingTagEndMarker(node) {
56163 return node.prev && node.prev.type !== "docType" && !isTextLikeNode$1(node.prev) && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
56166 function needsToBorrowLastChildClosingTagEndMarker(node) {
56174 return node.lastChild && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces && !isTextLikeNode$1(getLastDescendant$1(node.lastChild)) && !isPreLikeNode$1(node);
56177 function needsToBorrowParentClosingTagStartMarker(node) {
56189 return !node.next && !node.hasTrailingSpaces && node.isTrailingSpaceSensitive && isTextLikeNode$1(getLastDescendant$1(node));
56192 function printOpeningTagPrefix(node, options) {
56193 return needsToBorrowParentOpeningTagEndMarker(node) ? printOpeningTagEndMarker(node.parent) : needsToBorrowPrevClosingTagEndMarker(node) ? printClosingTagEndMarker(node.prev, options) : "";
56196 function printClosingTagPrefix(node, options) {
56197 return needsToBorrowLastChildClosingTagEndMarker(node) ? printClosingTagEndMarker(node.lastChild, options) : "";
56200 function printClosingTagSuffix(node, options) {
56201 return needsToBorrowParentClosingTagStartMarker(node) ? printClosingTagStartMarker(node.parent, options) : needsToBorrowNextOpeningTagStartMarker(node) ? printOpeningTagStartMarker(node.next) : "";
56204 function printOpeningTagStartMarker(node) {
56205 switch (node.type) {
56206 case "ieConditionalComment":
56207 case "ieConditionalStartComment":
56208 return `<!--[if ${node.condition}`;
56210 case "ieConditionalEndComment":
56213 case "interpolation":
56217 return "<!DOCTYPE";
56220 if (node.condition) {
56221 return `<!--[if ${node.condition}]><!--><${node.rawName}`;
56227 return `<${node.rawName}`;
56231 function printOpeningTagEndMarker(node) {
56232 assert__default['default'](!node.isSelfClosing);
56234 switch (node.type) {
56235 case "ieConditionalComment":
56239 if (node.condition) {
56240 return "><!--<![endif]-->";
56250 function printClosingTagStartMarker(node, options) {
56251 assert__default['default'](!node.isSelfClosing);
56252 /* istanbul ignore next */
56254 if (shouldNotPrintClosingTag$1(node, options)) {
56258 switch (node.type) {
56259 case "ieConditionalComment":
56263 if (node.hasHtmComponentClosingTag) {
56270 return `</${node.rawName}`;
56274 function printClosingTagEndMarker(node, options) {
56275 if (shouldNotPrintClosingTag$1(node, options)) {
56279 switch (node.type) {
56280 case "ieConditionalComment":
56281 case "ieConditionalEndComment":
56282 return "[endif]-->";
56284 case "ieConditionalStartComment":
56287 case "interpolation":
56291 if (node.isSelfClosing) {
56302 function getTextValueParts(node, value = node.value) {
56303 return node.parent.isWhitespaceSensitive ? node.parent.isIndentationSensitive ? replaceEndOfLineWith$2(value, literalline$5) : replaceEndOfLineWith$2(dedentString$1(htmlTrimPreserveIndentation$1(value)), hardline$t) : join$m(line$p, splitByHtmlWhitespace$1(value)).parts;
56306 function printEmbeddedAttributeValue(node, originalTextToDoc, options) {
56307 const isKeyMatched = patterns => new RegExp(patterns.join("|")).test(node.fullName);
56309 const getValue = () => unescapeQuoteEntities$1(node.value);
56311 let shouldHug = false;
56313 const __onHtmlBindingRoot = (root, options) => {
56314 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;
56316 if (rootNode && (rootNode.type === "ObjectExpression" || rootNode.type === "ArrayExpression" || options.parser === "__vue_expression" && (rootNode.type === "TemplateLiteral" || rootNode.type === "StringLiteral"))) {
56321 const printHug = doc => group$v(doc);
56323 const printExpand = (doc, canHaveTrailingWhitespace = true) => group$v(concat$I([indent$v(concat$I([softline$m, doc])), canHaveTrailingWhitespace ? softline$m : ""]));
56325 const printMaybeHug = doc => shouldHug ? printHug(doc) : printExpand(doc);
56327 const textToDoc = (code, opts) => originalTextToDoc(code, Object.assign({
56328 __onHtmlBindingRoot
56330 stripTrailingHardline: true
56333 if (node.fullName === "srcset" && (node.parent.fullName === "img" || node.parent.fullName === "source")) {
56334 return printExpand(printImgSrcset$1(getValue()));
56337 if (node.fullName === "class" && !options.parentParser) {
56338 const value = getValue();
56340 if (!value.includes("{{")) {
56341 return printClassNames$1(value);
56345 if (node.fullName === "style" && !options.parentParser) {
56346 const value = getValue();
56348 if (!value.includes("{{")) {
56349 return printExpand(textToDoc(value, {
56351 __isHTMLStyleAttribute: true
56356 if (options.parser === "vue") {
56357 if (node.fullName === "v-for") {
56358 return printVueFor$1(getValue(), textToDoc);
56361 if (isVueSlotAttribute$1(node) || isVueSfcBindingsAttribute$1(node, options)) {
56362 return printVueBindings$1(getValue(), textToDoc);
56365 * @click="jsStatement"
56366 * @click="jsExpression"
56367 * v-on:click="jsStatement"
56368 * v-on:click="jsExpression"
56372 const vueEventBindingPatterns = ["^@", "^v-on:"];
56374 * :class="vueExpression"
56375 * v-bind:id="vueExpression"
56378 const vueExpressionBindingPatterns = ["^:", "^v-bind:"];
56380 * v-if="jsExpression"
56383 const jsExpressionBindingPatterns = ["^v-"];
56385 if (isKeyMatched(vueEventBindingPatterns)) {
56386 const value = getValue();
56387 return printMaybeHug(textToDoc(value, {
56388 parser: isVueEventBindingExpression$3(value) ? "__js_expression" : "__vue_event_binding"
56392 if (isKeyMatched(vueExpressionBindingPatterns)) {
56393 return printMaybeHug(textToDoc(getValue(), {
56394 parser: "__vue_expression"
56398 if (isKeyMatched(jsExpressionBindingPatterns)) {
56399 return printMaybeHug(textToDoc(getValue(), {
56400 parser: "__js_expression"
56405 if (options.parser === "angular") {
56406 const ngTextToDoc = (code, opts) => // angular does not allow trailing comma
56407 textToDoc(code, Object.assign({}, opts, {
56408 trailingComma: "none"
56411 * *directive="angularDirective"
56415 const ngDirectiveBindingPatterns = ["^\\*"];
56417 * (click)="angularStatement"
56418 * on-click="angularStatement"
56421 const ngStatementBindingPatterns = ["^\\(.+\\)$", "^on-"];
56423 * [target]="angularExpression"
56424 * bind-target="angularExpression"
56425 * [(target)]="angularExpression"
56426 * bindon-target="angularExpression"
56429 const ngExpressionBindingPatterns = ["^\\[.+\\]$", "^bind(on)?-", // Unofficial rudimentary support for some of the most used directives of AngularJS 1.x
56430 "^ng-(if|show|hide|class|style)$"];
56432 * i18n="longDescription"
56433 * i18n-attr="longDescription"
56436 const ngI18nPatterns = ["^i18n(-.+)?$"];
56438 if (isKeyMatched(ngStatementBindingPatterns)) {
56439 return printMaybeHug(ngTextToDoc(getValue(), {
56440 parser: "__ng_action"
56444 if (isKeyMatched(ngExpressionBindingPatterns)) {
56445 return printMaybeHug(ngTextToDoc(getValue(), {
56446 parser: "__ng_binding"
56450 if (isKeyMatched(ngI18nPatterns)) {
56451 const value = getValue().trim();
56452 return printExpand(fill$6(getTextValueParts(node, value)), !value.includes("@@"));
56455 if (isKeyMatched(ngDirectiveBindingPatterns)) {
56456 return printMaybeHug(ngTextToDoc(getValue(), {
56457 parser: "__ng_directive"
56461 const interpolationRegex = /{{([\S\s]+?)}}/g;
56462 const value = getValue();
56464 if (interpolationRegex.test(value)) {
56466 value.split(interpolationRegex).forEach((part, index) => {
56467 if (index % 2 === 0) {
56468 parts.push(concat$I(replaceEndOfLineWith$2(part, literalline$5)));
56471 parts.push(group$v(concat$I(["{{", indent$v(concat$I([line$p, ngTextToDoc(part, {
56472 parser: "__ng_interpolation",
56473 __isInHtmlInterpolation: true // to avoid unexpected `}}`
56475 })])), line$p, "}}"])));
56477 parts.push("{{", concat$I(replaceEndOfLineWith$2(part, literalline$5)), "}}");
56481 return group$v(concat$I(parts));
56488 var printerHtml = {
56489 preprocess: printPreprocess$2,
56490 print: genericPrint$5,
56491 insertPragma: insertPragma$8,
56492 massageAstNode: clean_1$4,
56496 const CATEGORY_HTML = "HTML"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
56499 htmlWhitespaceSensitivity: {
56501 category: CATEGORY_HTML,
56504 description: "How to handle whitespaces in HTML.",
56507 description: "Respect the default value of CSS display property."
56510 description: "Whitespaces are considered sensitive."
56513 description: "Whitespaces are considered insensitive."
56516 vueIndentScriptAndStyle: {
56518 category: CATEGORY_HTML,
56521 description: "Indent script and style tags in Vue files."
56525 var name$g = "HTML";
56526 var type$e = "markup";
56527 var tmScope$e = "text.html.basic";
56528 var aceMode$e = "html";
56529 var codemirrorMode$b = "htmlmixed";
56530 var codemirrorMimeType$b = "text/html";
56531 var color$8 = "#e34c26";
56535 var extensions$e = [
56544 var languageId$e = 146;
56545 var require$$0$7 = {
56548 tmScope: tmScope$e,
56549 aceMode: aceMode$e,
56550 codemirrorMode: codemirrorMode$b,
56551 codemirrorMimeType: codemirrorMimeType$b,
56553 aliases: aliases$5,
56554 extensions: extensions$e,
56555 languageId: languageId$e
56558 var name$h = "Vue";
56559 var type$f = "markup";
56560 var color$9 = "#2c3e50";
56561 var extensions$f = [
56564 var tmScope$f = "text.html.vue";
56565 var aceMode$f = "html";
56566 var languageId$f = 391;
56567 var require$$1$2 = {
56571 extensions: extensions$f,
56572 tmScope: tmScope$f,
56573 aceMode: aceMode$f,
56574 languageId: languageId$f
56577 const languages$5 = [createLanguage(require$$0$7, () => ({
56580 parsers: ["angular"],
56581 vscodeLanguageIds: ["html"],
56582 extensions: [".component.html"],
56584 })), createLanguage(require$$0$7, data => ({
56587 vscodeLanguageIds: ["html"],
56588 extensions: data.extensions.concat([".mjml" // MJML is considered XML in Linguist but it should be formatted as HTML
56590 })), createLanguage(require$$0$7, () => ({
56591 name: "Lightning Web Components",
56594 vscodeLanguageIds: ["html"],
56597 })), createLanguage(require$$1$2, () => ({
56600 vscodeLanguageIds: ["vue"]
56602 const printers$5 = {
56605 const parsers$5 = {
56608 return require("./parser-html").parsers.html;
56613 return require("./parser-html").parsers.vue;
56618 return require("./parser-html").parsers.angular;
56621 // Lightning Web Components
56623 return require("./parser-html").parsers.lwc;
56627 var languageHtml = {
56628 languages: languages$5,
56629 printers: printers$5,
56630 options: options$6,
56634 function isPragma(text) {
56635 return /^\s*@(prettier|format)\s*$/.test(text);
56638 function hasPragma$4(text) {
56639 return /^\s*#[^\S\n]*@(prettier|format)\s*?(\n|$)/.test(text);
56642 function insertPragma$9(text) {
56643 return `# @format\n\n${text}`;
56648 hasPragma: hasPragma$4,
56649 insertPragma: insertPragma$9
56652 function locStart$k(node) {
56653 return node.position.start.offset;
56656 function locEnd$q(node) {
56657 return node.position.end.offset;
56661 locStart: locStart$k,
56669 function getAncestorCount(path, filter) {
56671 const pathStackLength = path.stack.length - 1;
56673 for (let i = 0; i < pathStackLength; i++) {
56674 const value = path.stack[i];
56676 if (isNode(value) && filter(value)) {
56684 * @param {any} value
56685 * @param {string[]=} types
56689 function isNode(value, types) {
56690 return value && typeof value.type === "string" && (!types || types.includes(value.type));
56693 function mapNode(node, callback, parent) {
56694 return callback("children" in node ? Object.assign({}, node, {
56695 children: node.children.map(childNode => mapNode(childNode, callback, node))
56696 }) : node, parent);
56699 function defineShortcut(x, key, getter) {
56700 Object.defineProperty(x, key, {
56706 function isNextLineEmpty$c(node, text) {
56707 let newlineCount = 0;
56708 const textLength = text.length;
56710 for (let i = node.position.end.offset - 1; i < textLength; i++) {
56711 const char = text[i];
56713 if (char === "\n") {
56717 if (newlineCount === 1 && /\S/.test(char)) {
56721 if (newlineCount === 2) {
56729 function isLastDescendantNode(path) {
56730 const node = path.getValue();
56732 switch (node.type) {
56739 const pathStackLength = path.stack.length;
56741 for (let i = 1; i < pathStackLength; i++) {
56742 const item = path.stack[i];
56743 const parentItem = path.stack[i - 1];
56745 if (Array.isArray(parentItem) && typeof item === "number" && item !== parentItem.length - 1) {
56753 function getLastDescendantNode$1(node) {
56754 return "children" in node && node.children.length !== 0 ? getLastDescendantNode$1(getLast$d(node.children)) : node;
56757 function isPrettierIgnore$2(comment) {
56758 return comment.value.trim() === "prettier-ignore";
56761 function hasPrettierIgnore$8(path) {
56762 const node = path.getValue();
56764 if (node.type === "documentBody") {
56765 const document = path.getParentNode();
56766 return hasEndComments(document.head) && isPrettierIgnore$2(getLast$d(document.head.endComments));
56769 return hasLeadingComments(node) && isPrettierIgnore$2(getLast$d(node.leadingComments));
56772 function isEmptyNode(node) {
56773 return (!node.children || node.children.length === 0) && !hasComments(node);
56776 function hasComments(node) {
56777 return hasLeadingComments(node) || hasMiddleComments(node) || hasIndicatorComment(node) || hasTrailingComment$7(node) || hasEndComments(node);
56780 function hasLeadingComments(node) {
56781 return node && node.leadingComments && node.leadingComments.length !== 0;
56784 function hasMiddleComments(node) {
56785 return node && node.middleComments && node.middleComments.length !== 0;
56788 function hasIndicatorComment(node) {
56789 return node && node.indicatorComment;
56792 function hasTrailingComment$7(node) {
56793 return node && node.trailingComment;
56796 function hasEndComments(node) {
56797 return node && node.endComments && node.endComments.length !== 0;
56800 * " a b c d e f " -> [" a b", "c d", "e f "]
56804 function splitWithSingleSpace(text) {
56808 for (const part of text.split(/( +)/g)) {
56809 /* istanbul ignore else */
56810 if (part !== " ") {
56811 if (lastPart === " ") {
56814 parts.push((parts.pop() || "") + part);
56816 } else if (lastPart === undefined) {
56822 /* istanbul ignore next */
56825 if (lastPart === " ") {
56826 parts.push((parts.pop() || "") + " ");
56829 if (parts[0] === "") {
56831 parts.unshift(" " + (parts.shift() || ""));
56837 function getFlowScalarLineContents(nodeType, content, options) {
56838 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());
56840 if (options.proseWrap === "preserve") {
56841 return rawLineContents.map(lineContent => lineContent.length === 0 ? [] : [lineContent]);
56844 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
56845 nodeType === "quoteDouble" && getLast$d(getLast$d(reduced)).endsWith("\\")) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]), []).map(lineContentWords => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords);
56848 function getBlockValueLineContents(node, {
56853 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 `|`
56854 .match(/^[^\n]*?\n([\S\s]*)$/)[1];
56855 const leadingSpaceCount = node.indent === null ? (match => match ? match[1].length : Infinity)(content.match(/^( *)\S/m)) : node.indent - 1 + parentIndent;
56856 const rawLineContents = content.split("\n").map(lineContent => lineContent.slice(leadingSpaceCount));
56858 if (options.proseWrap === "preserve" || node.type === "blockLiteral") {
56859 return removeUnnecessaryTrailingNewlines(rawLineContents.map(lineContent => lineContent.length === 0 ? [] : [lineContent]));
56862 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$d(reduced)) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]), []).map(lineContentWords => lineContentWords.reduce((reduced, word) => // disallow trailing spaces
56863 reduced.length !== 0 && /\s$/.test(getLast$d(reduced)) ? reduced.concat(reduced.pop() + " " + word) : reduced.concat(word), [])).map(lineContentWords => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords));
56865 function removeUnnecessaryTrailingNewlines(lineContents) {
56866 if (node.chomping === "keep") {
56867 return getLast$d(lineContents).length === 0 ? lineContents.slice(0, -1) : lineContents;
56870 let trailingNewlineCount = 0;
56872 for (let i = lineContents.length - 1; i >= 0; i--) {
56873 if (lineContents[i].length === 0) {
56874 trailingNewlineCount++;
56880 return trailingNewlineCount === 0 ? lineContents : trailingNewlineCount >= 2 && !isLastDescendant ? // next empty line
56881 lineContents.slice(0, -(trailingNewlineCount - 1)) : lineContents.slice(0, -trailingNewlineCount);
56886 getLast: getLast$d,
56892 isNextLineEmpty: isNextLineEmpty$c,
56893 isLastDescendantNode,
56894 getBlockValueLineContents,
56895 getFlowScalarLineContents,
56896 getLastDescendantNode: getLastDescendantNode$1,
56897 hasPrettierIgnore: hasPrettierIgnore$8,
56898 hasLeadingComments,
56900 hasIndicatorComment,
56901 hasTrailingComment: hasTrailingComment$7,
56905 const docBuilders$2 = document.builders;
56907 conditionalGroup: conditionalGroup$5,
56908 breakParent: breakParent$8,
56911 dedentToRoot: dedentToRoot$3,
56914 hardline: hardline$u,
56915 ifBreak: ifBreak$k,
56918 lineSuffix: lineSuffix$2,
56919 literalline: literalline$6,
56920 markAsRoot: markAsRoot$4,
56921 softline: softline$n
56924 replaceEndOfLineWith: replaceEndOfLineWith$3,
56925 isPreviousLineEmpty: isPreviousLineEmpty$3
56928 insertPragma: insertPragma$a,
56929 isPragma: isPragma$1
56932 locStart: locStart$l
56935 getAncestorCount: getAncestorCount$1,
56936 getBlockValueLineContents: getBlockValueLineContents$1,
56937 getFlowScalarLineContents: getFlowScalarLineContents$1,
56938 getLast: getLast$e,
56939 getLastDescendantNode: getLastDescendantNode$2,
56940 hasLeadingComments: hasLeadingComments$1,
56941 hasMiddleComments: hasMiddleComments$1,
56942 hasIndicatorComment: hasIndicatorComment$1,
56943 hasTrailingComment: hasTrailingComment$8,
56944 hasEndComments: hasEndComments$1,
56945 hasPrettierIgnore: hasPrettierIgnore$9,
56946 isLastDescendantNode: isLastDescendantNode$1,
56947 isNextLineEmpty: isNextLineEmpty$d,
56949 isEmptyNode: isEmptyNode$1,
56950 defineShortcut: defineShortcut$1,
56954 function preprocess$3(ast) {
56955 return mapNode$1(ast, defineShortcuts);
56958 function defineShortcuts(node) {
56959 switch (node.type) {
56961 defineShortcut$1(node, "head", () => node.children[0]);
56962 defineShortcut$1(node, "body", () => node.children[1]);
56965 case "documentBody":
56966 case "sequenceItem":
56967 case "flowSequenceItem":
56969 case "mappingValue":
56970 defineShortcut$1(node, "content", () => node.children[0]);
56973 case "mappingItem":
56974 case "flowMappingItem":
56975 defineShortcut$1(node, "key", () => node.children[0]);
56976 defineShortcut$1(node, "value", () => node.children[1]);
56983 function genericPrint$6(path, options, print) {
56984 const node = path.getValue();
56985 const parentNode = path.getParentNode();
56986 const tag = !node.tag ? "" : path.call(print, "tag");
56987 const anchor = !node.anchor ? "" : path.call(print, "anchor");
56988 const nextEmptyLine = isNode$1(node, ["mapping", "sequence", "comment", "directive", "mappingItem", "sequenceItem"]) && !isLastDescendantNode$1(path) ? printNextEmptyLine(path, options.originalText) : "";
56989 return concat$J([node.type !== "mappingValue" && hasLeadingComments$1(node) ? concat$J([join$n(hardline$u, path.map(print, "leadingComments")), hardline$u]) : "", tag, tag && anchor ? " " : "", anchor, tag || anchor ? isNode$1(node, ["sequence", "mapping"]) && !hasMiddleComments$1(node) ? hardline$u : " " : "", hasMiddleComments$1(node) ? concat$J([node.middleComments.length === 1 ? "" : hardline$u, join$n(hardline$u, path.map(print, "middleComments")), hardline$u]) : "", hasPrettierIgnore$9(path) ? concat$J(replaceEndOfLineWith$3(options.originalText.slice(node.position.start.offset, node.position.end.offset).trimEnd(), literalline$6)) : group$w(_print(node, parentNode, path, options, print)), hasTrailingComment$8(node) && !isNode$1(node, ["document", "documentHead"]) ? lineSuffix$2(concat$J([node.type === "mappingValue" && !node.content ? "" : " ", parentNode.type === "mappingKey" && path.getParentNode(2).type === "mapping" && isInlineNode(node) ? "" : breakParent$8, path.call(print, "trailingComment")])) : "", shouldPrintEndComments(node) ? align$6(node.type === "sequenceItem" ? 2 : 0, concat$J([hardline$u, join$n(hardline$u, path.map(path => concat$J([isPreviousLineEmpty$3(options.originalText, path.getValue(), locStart$l) ? hardline$u : "", print(path)]), "endComments"))])) : "", nextEmptyLine]);
56992 function _print(node, parentNode, path, options, print) {
56993 switch (node.type) {
56995 return concat$J([join$n(hardline$u, path.map((childPath, index) => {
56996 const document = node.children[index];
56997 const nextDocument = node.children[index + 1];
56998 return concat$J([print(childPath), shouldPrintDocumentEndMarker(document, nextDocument) ? concat$J([hardline$u, "...", hasTrailingComment$8(document) ? concat$J([" ", path.call(print, "trailingComment")]) : ""]) : !nextDocument || hasTrailingComment$8(nextDocument.head) ? "" : concat$J([hardline$u, "---"])]);
56999 }, "children")), node.children.length === 0 || (lastDescendantNode => isNode$1(lastDescendantNode, ["blockLiteral", "blockFolded"]) && lastDescendantNode.chomping === "keep")(getLastDescendantNode$2(node)) ? "" : hardline$u]);
57003 const nextDocument = parentNode.children[path.getName() + 1];
57004 return join$n(hardline$u, [shouldPrintDocumentHeadEndMarker(node, nextDocument, parentNode, options) === "head" ? join$n(hardline$u, [node.head.children.length === 0 && node.head.endComments.length === 0 ? "" : path.call(print, "head"), concat$J(["---", hasTrailingComment$8(node.head) ? concat$J([" ", path.call(print, "head", "trailingComment")]) : ""])].filter(Boolean)) : "", shouldPrintDocumentBody(node) ? path.call(print, "body") : ""].filter(Boolean));
57007 case "documentHead":
57008 return join$n(hardline$u, [].concat(path.map(print, "children"), path.map(print, "endComments")));
57010 case "documentBody":
57012 const children = join$n(hardline$u, path.map(print, "children")).parts;
57013 const endComments = join$n(hardline$u, path.map(print, "endComments")).parts;
57014 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)
57015 "" : // an extra newline for better readability
57016 concat$J([hardline$u, hardline$u]) : hardline$u)(getLastDescendantNode$2(node));
57017 return concat$J([].concat(children, separator, endComments));
57021 return concat$J(["%", join$n(" ", [node.name].concat(node.parameters))]);
57024 return concat$J(["#", node.value]);
57027 return concat$J(["*", node.value]);
57030 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
57033 return concat$J(["&", node.value]);
57036 return printFlowScalarContent(node.type, options.originalText.slice(node.position.start.offset, node.position.end.offset), options);
57038 case "quoteDouble":
57039 case "quoteSingle":
57041 const singleQuote = "'";
57042 const doubleQuote = '"';
57043 const raw = options.originalText.slice(node.position.start.offset + 1, node.position.end.offset - 1);
57045 if (node.type === "quoteSingle" && raw.includes("\\") || node.type === "quoteDouble" && /\\[^"]/.test(raw)) {
57046 // only quoteDouble can use escape chars
57047 // and quoteSingle do not need to escape backslashes
57048 const originalQuote = node.type === "quoteDouble" ? doubleQuote : singleQuote;
57049 return concat$J([originalQuote, printFlowScalarContent(node.type, raw, options), originalQuote]);
57050 } else if (raw.includes(doubleQuote)) {
57051 return concat$J([singleQuote, printFlowScalarContent(node.type, node.type === "quoteDouble" ? raw // double quote needs to be escaped by backslash in quoteDouble
57052 .replace(/\\"/g, doubleQuote).replace(/'/g, singleQuote.repeat(2)) : raw, options), singleQuote]);
57055 if (raw.includes(singleQuote)) {
57056 return concat$J([doubleQuote, printFlowScalarContent(node.type, node.type === "quoteSingle" ? // single quote needs to be escaped by 2 single quotes in quoteSingle
57057 raw.replace(/''/g, singleQuote) : raw, options), doubleQuote]);
57060 const quote = options.singleQuote ? singleQuote : doubleQuote;
57061 return concat$J([quote, printFlowScalarContent(node.type, raw, options), quote]);
57064 case "blockFolded":
57065 case "blockLiteral":
57067 const parentIndent = getAncestorCount$1(path, ancestorNode => isNode$1(ancestorNode, ["sequence", "mapping"]));
57068 const isLastDescendant = isLastDescendantNode$1(path);
57069 return concat$J([node.type === "blockFolded" ? ">" : "|", node.indent === null ? "" : node.indent.toString(), node.chomping === "clip" ? "" : node.chomping === "keep" ? "+" : "-", hasIndicatorComment$1(node) ? concat$J([" ", path.call(print, "indicatorComment")]) : "", (node.indent === null ? dedent$3 : dedentToRoot$3)(align$6(node.indent === null ? options.tabWidth : node.indent - 1 + parentIndent, concat$J(getBlockValueLineContents$1(node, {
57073 }).reduce((reduced, lineWords, index, lineContents) => reduced.concat(index === 0 ? hardline$u : "", fill$7(join$n(line$q, lineWords).parts), index !== lineContents.length - 1 ? lineWords.length === 0 ? hardline$u : markAsRoot$4(literalline$6) : node.chomping === "keep" && isLastDescendant ? lineWords.length === 0 ? dedentToRoot$3(hardline$u) : dedentToRoot$3(literalline$6) : ""), []))))]);
57077 return join$n(hardline$u, path.map(print, "children"));
57079 case "sequenceItem":
57080 return concat$J(["- ", align$6(2, !node.content ? "" : path.call(print, "content"))]);
57083 return !node.content ? "" : path.call(print, "content");
57085 case "mappingValue":
57086 return !node.content ? "" : path.call(print, "content");
57089 return join$n(hardline$u, path.map(print, "children"));
57091 case "mappingItem":
57092 case "flowMappingItem":
57094 const isEmptyMappingKey = isEmptyNode$1(node.key);
57095 const isEmptyMappingValue = isEmptyNode$1(node.value);
57097 if (isEmptyMappingKey && isEmptyMappingValue) {
57098 return concat$J([": "]);
57101 const key = path.call(print, "key");
57102 const value = path.call(print, "value");
57104 if (isEmptyMappingValue) {
57105 return node.type === "flowMappingItem" && parentNode.type === "flowMapping" ? key : node.type === "mappingItem" && isAbsolutelyPrintedAsSingleLineNode(node.key.content, options) && !hasTrailingComment$8(node.key.content) && (!parentNode.tag || parentNode.tag.value !== "tag:yaml.org,2002:set") ? concat$J([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ":"]) : concat$J(["? ", align$6(2, key)]);
57108 if (isEmptyMappingKey) {
57109 return concat$J([": ", align$6(2, value)]);
57112 const groupId = Symbol("mappingKey");
57113 const forceExplicitKey = hasLeadingComments$1(node.value) || !isInlineNode(node.key.content);
57114 return forceExplicitKey ? concat$J(["? ", align$6(2, key), hardline$u, join$n("", path.map(print, "value", "leadingComments").map(comment => concat$J([comment, hardline$u]))), ": ", align$6(2, value)]) : // force singleline
57115 isSingleLineNode(node.key.content) && !hasLeadingComments$1(node.key.content) && !hasMiddleComments$1(node.key.content) && !hasTrailingComment$8(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$J([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ": ", value]) : conditionalGroup$5([concat$J([group$w(concat$J([ifBreak$k("? "), group$w(align$6(2, key), {
57117 })])), ifBreak$k(concat$J([hardline$u, ": ", align$6(2, value)]), indent(concat$J([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$8(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$u : !node.value.content ? "" : line$q, value])), {
57122 case "flowMapping":
57123 case "flowSequence":
57125 const openMarker = node.type === "flowMapping" ? "{" : "[";
57126 const closeMarker = node.type === "flowMapping" ? "}" : "]";
57127 const bracketSpacing = node.type === "flowMapping" && node.children.length !== 0 && options.bracketSpacing ? line$q : softline$n;
57129 const isLastItemEmptyMappingItem = node.children.length !== 0 && (lastItem => lastItem.type === "flowMappingItem" && isEmptyNode$1(lastItem.key) && isEmptyNode$1(lastItem.value))(getLast$e(node.children));
57131 const trailingComma = options.trailingComma === "none" ? "" : ifBreak$k(",", "");
57132 return concat$J([openMarker, indent(concat$J([bracketSpacing, concat$J(path.map((childPath, index) => concat$J([print(childPath), index === node.children.length - 1 ? "" : concat$J([",", line$q, node.children[index].position.start.line !== node.children[index + 1].position.start.line ? printNextEmptyLine(childPath, options.originalText) : ""])]), "children")), trailingComma, hasEndComments$1(node) ? concat$J([hardline$u, join$n(hardline$u, path.map(print, "endComments"))]) : ""])), isLastItemEmptyMappingItem ? "" : bracketSpacing, closeMarker]);
57135 case "flowSequenceItem":
57136 return path.call(print, "content");
57137 // istanbul ignore next
57140 throw new Error(`Unexpected node type ${node.type}`);
57143 function indent(doc) {
57144 return docBuilders$2.align(" ".repeat(options.tabWidth), doc);
57148 function align$6(n, doc) {
57149 return typeof n === "number" && n > 0 ? docBuilders$2.align(" ".repeat(n), doc) : docBuilders$2.align(n, doc);
57152 function isInlineNode(node) {
57153 /* istanbul ignore next */
57158 switch (node.type) {
57160 case "quoteDouble":
57161 case "quoteSingle":
57163 case "flowMapping":
57164 case "flowSequence":
57172 function isSingleLineNode(node) {
57173 /* istanbul ignore next */
57178 switch (node.type) {
57180 case "quoteDouble":
57181 case "quoteSingle":
57182 return node.position.start.line === node.position.end.line;
57192 function shouldPrintDocumentBody(document) {
57193 return document.body.children.length !== 0 || hasEndComments$1(document.body);
57196 function shouldPrintDocumentEndMarker(document, nextDocument) {
57199 *... # trailingComment
57201 hasTrailingComment$8(document) || nextDocument && (
57207 nextDocument.head.children.length !== 0 ||
57213 hasEndComments$1(nextDocument.head))
57217 function shouldPrintDocumentHeadEndMarker(document, nextDocument, root, options) {
57221 * preserve the first document head end marker
57223 root.children[0] === document && /---(\s|$)/.test(options.originalText.slice(locStart$l(document), locStart$l(document) + 4)) ||
57228 document.head.children.length !== 0 ||
57233 hasEndComments$1(document.head) ||
57235 * --- # trailing comment
57237 hasTrailingComment$8(document.head)) {
57241 if (shouldPrintDocumentEndMarker(document, nextDocument)) {
57245 return nextDocument ? "root" : false;
57248 function isAbsolutelyPrintedAsSingleLineNode(node, options) {
57253 switch (node.type) {
57255 case "quoteSingle":
57256 case "quoteDouble":
57266 if (options.proseWrap === "preserve") {
57267 return node.position.start.line === node.position.end.line;
57270 if ( // backslash-newline
57271 /\\$/m.test(options.originalText.slice(node.position.start.offset, node.position.end.offset))) {
57275 switch (options.proseWrap) {
57277 return !node.value.includes("\n");
57280 return !/[\n ]/.test(node.value);
57281 // istanbul ignore next
57288 function needsSpaceInFrontOfMappingValue(node) {
57289 return node.key.content && node.key.content.type === "alias";
57292 function shouldPrintEndComments(node) {
57293 return hasEndComments$1(node) && !isNode$1(node, ["documentHead", "documentBody", "flowMapping", "flowSequence"]);
57296 const printedEmptyLineCache = new WeakMap();
57298 function printNextEmptyLine(path, originalText) {
57299 const node = path.getValue();
57300 const root = path.stack[0];
57301 let isNextEmptyLinePrintedSet;
57303 if (printedEmptyLineCache.has(root)) {
57304 isNextEmptyLinePrintedSet = printedEmptyLineCache.get(root);
57306 isNextEmptyLinePrintedSet = new Set();
57307 printedEmptyLineCache.set(root, isNextEmptyLinePrintedSet);
57310 if (!isNextEmptyLinePrintedSet.has(node.position.end.line)) {
57311 isNextEmptyLinePrintedSet.add(node.position.end.line);
57313 if (isNextLineEmpty$d(node, originalText) && !shouldPrintEndComments(path.getParentNode())) {
57321 function printFlowScalarContent(nodeType, content, options) {
57322 const lineContents = getFlowScalarLineContents$1(nodeType, content, options);
57323 return join$n(hardline$u, lineContents.map(lineContentWords => fill$7(join$n(line$q, lineContentWords).parts)));
57326 function clean$7(node, newNode
57329 if (isNode$1(newNode)) {
57330 delete newNode.position;
57332 switch (newNode.type) {
57335 if (isPragma$1(newNode.value)) {
57341 case "quoteDouble":
57342 case "quoteSingle":
57343 newNode.type = "quote";
57349 var printerYaml = {
57350 preprocess: preprocess$3,
57351 print: genericPrint$6,
57352 massageAstNode: clean$7,
57353 insertPragma: insertPragma$a
57357 bracketSpacing: commonOptions.bracketSpacing,
57358 singleQuote: commonOptions.singleQuote,
57359 proseWrap: commonOptions.proseWrap
57362 var name$i = "YAML";
57363 var type$g = "data";
57364 var color$a = "#cb171e";
57365 var tmScope$g = "source.yaml";
57369 var extensions$g = [
57377 ".yaml-tmlanguage",
57381 var filenames$4 = [
57388 var aceMode$g = "yaml";
57389 var codemirrorMode$c = "yaml";
57390 var codemirrorMimeType$c = "text/x-yaml";
57391 var languageId$g = 407;
57392 var require$$0$8 = {
57396 tmScope: tmScope$g,
57397 aliases: aliases$6,
57398 extensions: extensions$g,
57399 filenames: filenames$4,
57400 aceMode: aceMode$g,
57401 codemirrorMode: codemirrorMode$c,
57402 codemirrorMimeType: codemirrorMimeType$c,
57403 languageId: languageId$g
57406 const languages$6 = [createLanguage(require$$0$8, data => ({
57409 vscodeLanguageIds: ["yaml", "ansible", "home-assistant"],
57410 // yarn.lock is not YAML: https://github.com/yarnpkg/yarn/issues/5629
57411 filenames: data.filenames.filter(filename => filename !== "yarn.lock")
57413 const parsers$6 = {
57415 return require("./parser-yaml").parsers.yaml;
57419 var languageYaml = {
57420 languages: languages$6,
57424 options: options$7,
57428 var languages$7 = [// JS
57430 languageCss, // Handlebars
57431 languageHandlebars, // GraphQL
57432 languageGraphql, // Markdown
57433 languageMarkdown, // HTML
57434 languageHtml, // YAML
57437 const memoizedLoad = dist$1(load, {
57438 cacheKey: JSON.stringify
57440 const memoizedSearch = dist$1(findPluginsInNodeModules);
57442 const clearCache$2 = () => {
57443 dist$1.clear(memoizedLoad);
57444 dist$1.clear(memoizedSearch);
57447 function load(plugins, pluginSearchDirs) {
57452 if (!pluginSearchDirs) {
57453 pluginSearchDirs = [];
57454 } // unless pluginSearchDirs are provided, auto-load plugins from node_modules that are parent to Prettier
57457 if (!pluginSearchDirs.length) {
57458 const autoLoadDir = thirdParty.findParentDir(__dirname, "node_modules");
57461 pluginSearchDirs = [autoLoadDir];
57465 const [externalPluginNames, externalPluginInstances] = partition_1(plugins, plugin => typeof plugin === "string");
57466 const externalManualLoadPluginInfos = externalPluginNames.map(pluginName => {
57471 requirePath = resolve_1(path__default['default'].resolve(process.cwd(), pluginName));
57473 // try node modules
57474 requirePath = resolve_1(pluginName, {
57475 paths: [process.cwd()]
57484 const externalAutoLoadPluginInfos = pluginSearchDirs.map(pluginSearchDir => {
57485 const resolvedPluginSearchDir = path__default['default'].resolve(process.cwd(), pluginSearchDir);
57486 const nodeModulesDir = path__default['default'].resolve(resolvedPluginSearchDir, "node_modules"); // In some fringe cases (ex: files "mounted" as virtual directories), the
57487 // isDirectory(resolvedPluginSearchDir) check might be false even though
57488 // the node_modules actually exists.
57490 if (!isDirectory$1(nodeModulesDir) && !isDirectory$1(resolvedPluginSearchDir)) {
57491 throw new Error(`${pluginSearchDir} does not exist or is not a directory`);
57494 return memoizedSearch(nodeModulesDir).map(pluginName => ({
57496 requirePath: resolve_1(pluginName, {
57497 paths: [resolvedPluginSearchDir]
57500 }).reduce((a, b) => a.concat(b), []);
57501 const externalPlugins = uniqBy_1(externalManualLoadPluginInfos.concat(externalAutoLoadPluginInfos), "requirePath").map(externalPluginInfo => Object.assign({
57502 name: externalPluginInfo.name
57503 }, require(externalPluginInfo.requirePath))).concat(externalPluginInstances);
57504 return languages$7.concat(externalPlugins);
57507 function findPluginsInNodeModules(nodeModulesDir) {
57508 const pluginPackageJsonPaths = globby$1.sync(["prettier-plugin-*/package.json", "@*/prettier-plugin-*/package.json", "@prettier/plugin-*/package.json"], {
57509 cwd: nodeModulesDir,
57510 expandDirectories: false
57512 return pluginPackageJsonPaths.map(path__default['default'].dirname);
57515 function isDirectory$1(dir) {
57517 return fs__default['default'].statSync(dir).isDirectory();
57523 var loadPlugins = {
57524 loadPlugins: memoizedLoad,
57525 clearCache: clearCache$2
57532 getSupportInfo: getSupportInfo$3
57535 function _withPlugins(fn, optsArgIdx = 1 // Usually `opts` is the 2nd argument
57537 return (...args) => {
57538 const opts = args[optsArgIdx] || {};
57539 args[optsArgIdx] = Object.assign({}, opts, {
57540 plugins: loadPlugins.loadPlugins(opts.plugins, opts.pluginSearchDirs)
57542 return fn(...args);
57546 function withPlugins(fn, optsArgIdx) {
57547 const resultingFn = _withPlugins(fn, optsArgIdx);
57551 resultingFn.sync = _withPlugins(fn.sync, optsArgIdx);
57554 return resultingFn;
57557 const formatWithCursor = withPlugins(core.formatWithCursor);
57561 format(text, opts) {
57562 return formatWithCursor(text, opts).formatted;
57565 check(text, opts) {
57568 } = formatWithCursor(text, opts);
57569 return formatted === text;
57573 resolveConfig: resolveConfig_1.resolveConfig,
57574 resolveConfigFile: resolveConfig_1.resolveConfigFile,
57576 clearConfigCache() {
57577 resolveConfig_1.clearCache();
57578 loadPlugins.clearCache();
57582 /** @type {typeof getFileInfo} */
57583 withPlugins(getFileInfo_1),
57585 /** @type {typeof getSupportInfo} */
57586 withPlugins(getSupportInfo$3, 0),
57587 version: version$2,
57592 coreOptions: coreOptions,
57593 createIgnorer: createIgnorer_1,
57594 optionsModule: options$1,
57595 optionsNormalizer: optionsNormalizer,
57601 /* istanbul ignore next */
57603 parse: withPlugins(core.parse),
57604 formatAST: withPlugins(core.formatAST),
57605 formatDoc: withPlugins(core.formatDoc),
57606 printToDoc: withPlugins(core.printToDoc),
57607 printDocToString: withPlugins(core.printDocToString)
57611 var prettier = src$2;
57613 module.exports = prettier;