4 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6 var fs$1 = _interopDefault(require('fs'));
7 var os$1 = _interopDefault(require('os'));
8 var path$2 = _interopDefault(require('path'));
9 var assert$1 = _interopDefault(require('assert'));
10 var util$3 = _interopDefault(require('util'));
11 var events$1 = _interopDefault(require('events'));
12 var readline$1 = _interopDefault(require('readline'));
14 var name = "prettier";
15 var version = "1.19.1";
16 var description = "Prettier is an opinionated code formatter";
18 prettier: "./bin/prettier.js"
20 var repository = "prettier/prettier";
21 var homepage = "https://prettier.io";
22 var author = "James Long";
24 var main = "./index.js";
29 "@angular/compiler": "8.2.13",
30 "@babel/code-frame": "7.5.5",
31 "@babel/parser": "7.7.3",
32 "@glimmer/syntax": "0.41.0",
33 "@iarna/toml": "2.2.3",
34 "@typescript-eslint/typescript-estree": "2.6.1",
35 "angular-estree-parser": "1.1.5",
36 "angular-html-parser": "1.3.0",
44 editorconfig: "0.15.3",
45 "editorconfig-to-prettier": "0.1.1",
46 "escape-string-regexp": "1.0.5",
48 "find-parent-dir": "0.3.0",
49 "find-project-root": "1.1.1",
50 "flow-parser": "0.111.3",
51 "get-stream": "4.1.0",
54 "html-element-attributes": "2.2.0",
55 "html-styles": "1.0.0",
56 "html-tag-names": "1.1.4",
59 "jest-docblock": "24.9.0",
60 "json-stable-stringify": "1.0.1",
62 "lines-and-columns": "1.1.6",
63 "linguist-languages": "7.6.0",
64 "lodash.uniqby": "4.7.0",
68 "n-readlines": "1.0.0",
69 "normalize-path": "3.0.0",
70 "parse-srcset": "ikatyang/parse-srcset#54eb9c1cb21db5c62b4d0e275d7249516df6f0ee",
71 "postcss-less": "2.0.0",
72 "postcss-media-query-parser": "0.2.3",
73 "postcss-scss": "2.0.0",
74 "postcss-selector-parser": "2.2.3",
75 "postcss-values-parser": "1.5.0",
76 "regexp-util": "1.2.2",
77 "remark-math": "1.0.6",
78 "remark-parse": "5.0.0",
81 "string-width": "4.1.0",
83 "unicode-regex": "3.0.0",
86 "yaml-unist-parser": "1.1.1"
88 var devDependencies = {
89 "@babel/core": "7.7.2",
90 "@babel/preset-env": "7.7.1",
91 "@rollup/plugin-alias": "2.2.0",
92 "@rollup/plugin-replace": "2.2.1",
93 "babel-loader": "8.0.6",
95 "builtin-modules": "3.1.0",
99 "eslint-config-prettier": "6.5.0",
100 "eslint-formatter-friendly": "7.0.0",
101 "eslint-plugin-import": "2.18.2",
102 "eslint-plugin-prettier": "3.1.1",
103 "eslint-plugin-react": "7.16.0",
106 "jest-junit": "9.0.0",
107 "jest-snapshot-serializer-ansi": "1.0.0",
108 "jest-snapshot-serializer-raw": "1.1.0",
109 "jest-watch-typeahead": "0.4.0",
115 "rollup-plugin-babel": "4.3.3",
116 "rollup-plugin-commonjs": "10.1.0",
117 "rollup-plugin-json": "4.0.0",
118 "rollup-plugin-node-globals": "1.4.0",
119 "rollup-plugin-node-resolve": "5.2.0",
120 "rollup-plugin-terser": "5.1.2",
122 "snapshot-diff": "0.4.0",
123 "strip-ansi": "5.2.0",
124 "synchronous-promise": "2.0.10",
126 "terser-webpack-plugin": "2.2.1",
130 prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1",
131 "prepare-release": "yarn && yarn build && yarn test:dist",
133 "test:dist": "node ./scripts/test-dist.js",
134 "test-integration": "jest tests_integration",
135 "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",
136 "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",
137 "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",
138 "check-types": "tsc",
139 lint: "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly",
140 "lint-docs": "prettylint {.,docs,website,website/blog}/*.md",
141 "lint-dist": "eslint --no-eslintrc --no-ignore --env=browser \"dist/!(bin-prettier|index|third-party).js\"",
142 build: "node --max-old-space-size=3072 ./scripts/build/build.js",
143 "build-docs": "node ./scripts/build-docs.js",
144 "check-deps": "node ./scripts/check-deps.js",
145 spellcheck: "npx -p cspell@4.0.31 cspell {bin,scripts,src}/**/*.js {docs,website/blog,changelog_unreleased}/**/*.md"
150 description: description,
152 repository: repository,
158 dependencies: dependencies,
159 devDependencies: devDependencies,
163 var _package$1 = /*#__PURE__*/Object.freeze({
167 description: description,
169 repository: repository,
175 dependencies: dependencies,
176 devDependencies: devDependencies,
184 diff: function diff(oldString, newString) {
185 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
186 var callback = options.callback;
188 if (typeof options === 'function') {
193 this.options = options;
196 function done(value) {
198 setTimeout(function () {
199 callback(undefined, value);
205 } // Allow subclasses to massage the input prior to running
208 oldString = this.castInput(oldString);
209 newString = this.castInput(newString);
210 oldString = this.removeEmpty(this.tokenize(oldString));
211 newString = this.removeEmpty(this.tokenize(newString));
212 var newLen = newString.length,
213 oldLen = oldString.length;
215 var maxEditLength = newLen + oldLen;
219 }]; // Seed editLength = 0, i.e. the content starts with the same values
221 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
223 if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
224 // Identity per the equality and tokenizer
226 value: this.join(newString),
227 count: newString.length
229 } // Main worker method. checks all permutations of a given edit length for acceptance.
232 function execEditLength() {
233 for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
234 var basePath = void 0;
236 var addPath = bestPath[diagonalPath - 1],
237 removePath = bestPath[diagonalPath + 1],
238 _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
241 // No one else is going to attempt to use this value, clear it
242 bestPath[diagonalPath - 1] = undefined;
245 var canAdd = addPath && addPath.newPos + 1 < newLen,
246 canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
248 if (!canAdd && !canRemove) {
249 // If this path is a terminal then prune
250 bestPath[diagonalPath] = undefined;
252 } // Select the diagonal that we want to branch from. We select the prior
253 // path whose position in the new string is the farthest from the origin
254 // and does not pass the bounds of the diff graph
257 if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
258 basePath = clonePath(removePath);
259 self.pushComponent(basePath.components, undefined, true);
261 basePath = addPath; // No need to clone, we've pulled it from the list
264 self.pushComponent(basePath.components, true, undefined);
267 _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
269 if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
270 return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
272 // Otherwise track this path as a potential candidate and continue.
273 bestPath[diagonalPath] = basePath;
278 } // Performs the length of edit iteration. Is a bit fugly as this has to support the
279 // sync and async mode which is never fun. Loops over execEditLength until a value
285 setTimeout(function () {
286 // This should not happen, but we want to be safe.
288 /* istanbul ignore next */
289 if (editLength > maxEditLength) {
293 if (!execEditLength()) {
299 while (editLength <= maxEditLength) {
300 var ret = execEditLength();
308 pushComponent: function pushComponent(components, added, removed) {
309 var last = components[components.length - 1];
311 if (last && last.added === added && last.removed === removed) {
312 // We need to clone here as the component clone operation is just
313 // as shallow array clone
314 components[components.length - 1] = {
315 count: last.count + 1,
327 extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
328 var newLen = newString.length,
329 oldLen = oldString.length,
330 newPos = basePath.newPos,
331 oldPos = newPos - diagonalPath,
334 while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
341 basePath.components.push({
346 basePath.newPos = newPos;
349 equals: function equals(left, right) {
350 if (this.options.comparator) {
351 return this.options.comparator(left, right);
353 return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
356 removeEmpty: function removeEmpty(array) {
359 for (var i = 0; i < array.length; i++) {
367 castInput: function castInput(value) {
370 tokenize: function tokenize(value) {
371 return value.split('');
373 join: function join(chars) {
374 return chars.join('');
378 function buildValues(diff, components, newString, oldString, useLongestToken) {
379 var componentPos = 0,
380 componentLen = components.length,
384 for (; componentPos < componentLen; componentPos++) {
385 var component = components[componentPos];
387 if (!component.removed) {
388 if (!component.added && useLongestToken) {
389 var value = newString.slice(newPos, newPos + component.count);
390 value = value.map(function (value, i) {
391 var oldValue = oldString[oldPos + i];
392 return oldValue.length > value.length ? oldValue : value;
394 component.value = diff.join(value);
396 component.value = diff.join(newString.slice(newPos, newPos + component.count));
399 newPos += component.count; // Common case
401 if (!component.added) {
402 oldPos += component.count;
405 component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
406 oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
407 // The diffing algorithm is tied to add then remove output and this is the simplest
408 // route to get the desired output with minimal overhead.
410 if (componentPos && components[componentPos - 1].added) {
411 var tmp = components[componentPos - 1];
412 components[componentPos - 1] = components[componentPos];
413 components[componentPos] = tmp;
416 } // Special case handle for when one terminal is ignored (i.e. whitespace).
417 // For this case we merge the terminal into the prior string and drop the change.
418 // This is only available for string mode.
421 var lastComponent = components[componentLen - 1];
423 if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
424 components[componentLen - 2].value += lastComponent.value;
431 function clonePath(path) {
434 components: path.components.slice(0)
438 var characterDiff = new Diff();
440 function diffChars(oldStr, newStr, options) {
441 return characterDiff.diff(oldStr, newStr, options);
444 function generateOptions(options, defaults) {
445 if (typeof options === 'function') {
446 defaults.callback = options;
447 } else if (options) {
448 for (var name in options) {
449 /* istanbul ignore else */
450 if (options.hasOwnProperty(name)) {
451 defaults[name] = options[name];
458 // Ranges and exceptions:
459 // Latin-1 Supplement, 0080–00FF
460 // - U+00D7 × Multiplication sign
461 // - U+00F7 ÷ Division sign
462 // Latin Extended-A, 0100–017F
463 // Latin Extended-B, 0180–024F
464 // IPA Extensions, 0250–02AF
465 // Spacing Modifier Letters, 02B0–02FF
466 // - U+02C7 ˇ ˇ Caron
467 // - U+02D8 ˘ ˘ Breve
468 // - U+02D9 ˙ ˙ Dot Above
469 // - U+02DA ˚ ˚ Ring Above
470 // - U+02DB ˛ ˛ Ogonek
471 // - U+02DC ˜ ˜ Small Tilde
472 // - U+02DD ˝ ˝ Double Acute Accent
473 // Latin Extended Additional, 1E00–1EFF
476 var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
477 var reWhitespace = /\S/;
478 var wordDiff = new Diff();
480 wordDiff.equals = function (left, right) {
481 if (this.options.ignoreCase) {
482 left = left.toLowerCase();
483 right = right.toLowerCase();
486 return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
489 wordDiff.tokenize = function (value) {
490 var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
492 for (var i = 0; i < tokens.length - 1; i++) {
493 // If we have an empty string in the next field and we have only word chars before and after, merge
494 if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
495 tokens[i] += tokens[i + 2];
496 tokens.splice(i + 1, 2);
504 function diffWords(oldStr, newStr, options) {
505 options = generateOptions(options, {
506 ignoreWhitespace: true
508 return wordDiff.diff(oldStr, newStr, options);
511 function diffWordsWithSpace(oldStr, newStr, options) {
512 return wordDiff.diff(oldStr, newStr, options);
515 var lineDiff = new Diff();
517 lineDiff.tokenize = function (value) {
519 linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
521 if (!linesAndNewlines[linesAndNewlines.length - 1]) {
522 linesAndNewlines.pop();
523 } // Merge the content and line separators into single tokens
526 for (var i = 0; i < linesAndNewlines.length; i++) {
527 var line = linesAndNewlines[i];
529 if (i % 2 && !this.options.newlineIsToken) {
530 retLines[retLines.length - 1] += line;
532 if (this.options.ignoreWhitespace) {
543 function diffLines(oldStr, newStr, callback) {
544 return lineDiff.diff(oldStr, newStr, callback);
547 function diffTrimmedLines(oldStr, newStr, callback) {
548 var options = generateOptions(callback, {
549 ignoreWhitespace: true
551 return lineDiff.diff(oldStr, newStr, options);
554 var sentenceDiff = new Diff();
556 sentenceDiff.tokenize = function (value) {
557 return value.split(/(\S.+?[.!?])(?=\s+|$)/);
560 function diffSentences(oldStr, newStr, callback) {
561 return sentenceDiff.diff(oldStr, newStr, callback);
564 var cssDiff = new Diff();
566 cssDiff.tokenize = function (value) {
567 return value.split(/([{}:;,]|\s+)/);
570 function diffCss(oldStr, newStr, callback) {
571 return cssDiff.diff(oldStr, newStr, callback);
574 function _typeof(obj) {
575 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
576 _typeof = function _typeof(obj) {
580 _typeof = function _typeof(obj) {
581 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
588 function _toConsumableArray(arr) {
589 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
592 function _arrayWithoutHoles(arr) {
593 if (Array.isArray(arr)) {
594 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
602 function _iterableToArray(iter) {
603 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
606 function _nonIterableSpread() {
607 throw new TypeError("Invalid attempt to spread non-iterable instance");
610 var objectPrototypeToString = Object.prototype.toString;
611 var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
612 // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
614 jsonDiff.useLongestToken = true;
615 jsonDiff.tokenize = lineDiff.tokenize;
617 jsonDiff.castInput = function (value) {
618 var _this$options = this.options,
619 undefinedReplacement = _this$options.undefinedReplacement,
620 _this$options$stringi = _this$options.stringifyReplacer,
621 stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
622 return typeof v === 'undefined' ? undefinedReplacement : v;
623 } : _this$options$stringi;
624 return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
627 jsonDiff.equals = function (left, right) {
628 return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
631 function diffJson(oldObj, newObj, options) {
632 return jsonDiff.diff(oldObj, newObj, options);
633 } // This function handles the presence of circular references by bailing out when encountering an
634 // object that is already on the "stack" of items being processed. Accepts an optional replacer
637 function canonicalize(obj, stack, replacementStack, replacer, key) {
639 replacementStack = replacementStack || [];
642 obj = replacer(key, obj);
647 for (i = 0; i < stack.length; i += 1) {
648 if (stack[i] === obj) {
649 return replacementStack[i];
653 var canonicalizedObj;
655 if ('[object Array]' === objectPrototypeToString.call(obj)) {
657 canonicalizedObj = new Array(obj.length);
658 replacementStack.push(canonicalizedObj);
660 for (i = 0; i < obj.length; i += 1) {
661 canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
665 replacementStack.pop();
666 return canonicalizedObj;
669 if (obj && obj.toJSON) {
673 if (_typeof(obj) === 'object' && obj !== null) {
675 canonicalizedObj = {};
676 replacementStack.push(canonicalizedObj);
682 /* istanbul ignore else */
683 if (obj.hasOwnProperty(_key)) {
684 sortedKeys.push(_key);
690 for (i = 0; i < sortedKeys.length; i += 1) {
691 _key = sortedKeys[i];
692 canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
696 replacementStack.pop();
698 canonicalizedObj = obj;
701 return canonicalizedObj;
704 var arrayDiff = new Diff();
706 arrayDiff.tokenize = function (value) {
707 return value.slice();
710 arrayDiff.join = arrayDiff.removeEmpty = function (value) {
714 function diffArrays(oldArr, newArr, callback) {
715 return arrayDiff.diff(oldArr, newArr, callback);
718 function parsePatch(uniDiff) {
719 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
720 var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
721 delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
725 function parseIndex() {
727 list.push(index); // Parse diff metadata
729 while (i < diffstr.length) {
730 var line = diffstr[i]; // File header found, end parsing diff metadata
732 if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
737 var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
740 index.index = header[1];
744 } // Parse file headers if they are defined. Unified diff requires them, but
745 // there's no technical issues to have an isolated hunk without file header
748 parseFileHeader(index);
749 parseFileHeader(index); // Parse hunks
753 while (i < diffstr.length) {
754 var _line = diffstr[i];
756 if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
758 } else if (/^@@/.test(_line)) {
759 index.hunks.push(parseHunk());
760 } else if (_line && options.strict) {
761 // Ignore unexpected content unless in strict mode
762 throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
767 } // Parses the --- and +++ headers, if none are found, no lines
771 function parseFileHeader(index) {
772 var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
775 var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
776 var data = fileHeader[2].split('\t', 2);
777 var fileName = data[0].replace(/\\\\/g, '\\');
779 if (/^".*"$/.test(fileName)) {
780 fileName = fileName.substr(1, fileName.length - 2);
783 index[keyPrefix + 'FileName'] = fileName;
784 index[keyPrefix + 'Header'] = (data[1] || '').trim();
788 // This assumes that we are at the start of a hunk.
791 function parseHunk() {
792 var chunkHeaderIndex = i,
793 chunkHeaderLine = diffstr[i++],
794 chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
796 oldStart: +chunkHeader[1],
797 oldLines: +chunkHeader[2] || 1,
798 newStart: +chunkHeader[3],
799 newLines: +chunkHeader[4] || 1,
806 for (; i < diffstr.length; i++) {
807 // Lines starting with '---' could be mistaken for the "remove line" operation
808 // But they could be the header for the next file. Therefore prune such cases out.
809 if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
813 var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
815 if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
816 hunk.lines.push(diffstr[i]);
817 hunk.linedelimiters.push(delimiters[i] || '\n');
819 if (operation === '+') {
821 } else if (operation === '-') {
823 } else if (operation === ' ') {
830 } // Handle the empty block count case
833 if (!addCount && hunk.newLines === 1) {
837 if (!removeCount && hunk.oldLines === 1) {
839 } // Perform optional sanity checking
842 if (options.strict) {
843 if (addCount !== hunk.newLines) {
844 throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
847 if (removeCount !== hunk.oldLines) {
848 throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
855 while (i < diffstr.length) {
860 } // Iterator that traverses in the range of [min, max], stepping
861 // by distance from a given start position. I.e. for [0, 4], with
862 // start of 2, this will iterate 2, 3, 1, 4, 0.
865 function distanceIterator(start, minLine, maxLine) {
866 var wantForward = true,
867 backwardExhausted = false,
868 forwardExhausted = false,
870 return function iterator() {
871 if (wantForward && !forwardExhausted) {
872 if (backwardExhausted) {
876 } // Check if trying to fit beyond text length, and if not, check it fits
877 // after offset location (or desired location on first iteration)
880 if (start + localOffset <= maxLine) {
884 forwardExhausted = true;
887 if (!backwardExhausted) {
888 if (!forwardExhausted) {
890 } // Check if trying to fit before text beginning, and if not, check it fits
891 // before offset location
894 if (minLine <= start - localOffset) {
895 return -localOffset++;
898 backwardExhausted = true;
900 } // We tried to fit hunk before text beginning and beyond text length, then
901 // hunk can't fit on the text. Return undefined
906 function applyPatch(source, uniDiff) {
907 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
909 if (typeof uniDiff === 'string') {
910 uniDiff = parsePatch(uniDiff);
913 if (Array.isArray(uniDiff)) {
914 if (uniDiff.length > 1) {
915 throw new Error('applyPatch only works with a single input.');
918 uniDiff = uniDiff[0];
919 } // Apply the diff to the input
922 var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
923 delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
924 hunks = uniDiff.hunks,
925 compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
926 return line === patchContent;
929 fuzzFactor = options.fuzzFactor || 0,
935 * Checks if the hunk exactly fits on the provided location
939 function hunkFits(hunk, toPos) {
940 for (var j = 0; j < hunk.lines.length; j++) {
941 var line = hunk.lines[j],
942 operation = line.length > 0 ? line[0] : ' ',
943 content = line.length > 0 ? line.substr(1) : line;
945 if (operation === ' ' || operation === '-') {
946 // Context sanity check
947 if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
950 if (errorCount > fuzzFactor) {
960 } // Search best fit offsets for each hunk based on the previous ones
963 for (var i = 0; i < hunks.length; i++) {
965 maxLine = lines.length - hunk.oldLines,
967 toPos = offset + hunk.oldStart - 1;
968 var iterator = distanceIterator(toPos, minLine, maxLine);
970 for (; localOffset !== undefined; localOffset = iterator()) {
971 if (hunkFits(hunk, toPos + localOffset)) {
972 hunk.offset = offset += localOffset;
977 if (localOffset === undefined) {
979 } // Set lower text limit to end of the current hunk, so next ones don't try
980 // to fit over already patched text
983 minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
984 } // Apply patch hunks
989 for (var _i = 0; _i < hunks.length; _i++) {
990 var _hunk = hunks[_i],
991 _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
993 diffOffset += _hunk.newLines - _hunk.oldLines;
996 // Creating a new file
1000 for (var j = 0; j < _hunk.lines.length; j++) {
1001 var line = _hunk.lines[j],
1002 operation = line.length > 0 ? line[0] : ' ',
1003 content = line.length > 0 ? line.substr(1) : line,
1004 delimiter = _hunk.linedelimiters[j];
1006 if (operation === ' ') {
1008 } else if (operation === '-') {
1009 lines.splice(_toPos, 1);
1010 delimiters.splice(_toPos, 1);
1011 /* istanbul ignore else */
1012 } else if (operation === '+') {
1013 lines.splice(_toPos, 0, content);
1014 delimiters.splice(_toPos, 0, delimiter);
1016 } else if (operation === '\\') {
1017 var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
1019 if (previousOperation === '+') {
1021 } else if (previousOperation === '-') {
1026 } // Handle EOFNL insertion/removal
1030 while (!lines[lines.length - 1]) {
1034 } else if (addEOFNL) {
1036 delimiters.push('\n');
1039 for (var _k = 0; _k < lines.length - 1; _k++) {
1040 lines[_k] = lines[_k] + delimiters[_k];
1043 return lines.join('');
1044 } // Wrapper that supports multiple file patches via callbacks.
1047 function applyPatches(uniDiff, options) {
1048 if (typeof uniDiff === 'string') {
1049 uniDiff = parsePatch(uniDiff);
1052 var currentIndex = 0;
1054 function processIndex() {
1055 var index = uniDiff[currentIndex++];
1058 return options.complete();
1061 options.loadFile(index, function (err, data) {
1063 return options.complete(err);
1066 var updatedContent = applyPatch(data, index, options);
1067 options.patched(index, updatedContent, function (err) {
1069 return options.complete(err);
1080 function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1085 if (typeof options.context === 'undefined') {
1086 options.context = 4;
1089 var diff = diffLines(oldStr, newStr, options);
1093 }); // Append an empty value to make cleanup easier
1095 function contextLines(lines) {
1096 return lines.map(function (entry) {
1102 var oldRangeStart = 0,
1108 var _loop = function _loop(i) {
1109 var current = diff[i],
1110 lines = current.lines || current.value.replace(/\n$/, '').split('\n');
1111 current.lines = lines;
1113 if (current.added || current.removed) {
1114 var _curRange; // If we have previous context, start with that
1117 if (!oldRangeStart) {
1118 var prev = diff[i - 1];
1119 oldRangeStart = oldLine;
1120 newRangeStart = newLine;
1123 curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
1124 oldRangeStart -= curRange.length;
1125 newRangeStart -= curRange.length;
1127 } // Output our changes
1130 (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
1131 return (current.added ? '+' : '-') + entry;
1132 }))); // Track the updated file position
1135 if (current.added) {
1136 newLine += lines.length;
1138 oldLine += lines.length;
1141 // Identical context lines. Track line changes
1142 if (oldRangeStart) {
1143 // Close out any changes that have been output (or join overlapping)
1144 if (lines.length <= options.context * 2 && i < diff.length - 2) {
1145 var _curRange2; // Overlapping
1148 (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
1150 var _curRange3; // end the range and output
1153 var contextSize = Math.min(lines.length, options.context);
1155 (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
1158 oldStart: oldRangeStart,
1159 oldLines: oldLine - oldRangeStart + contextSize,
1160 newStart: newRangeStart,
1161 newLines: newLine - newRangeStart + contextSize,
1165 if (i >= diff.length - 2 && lines.length <= options.context) {
1166 // EOF is inside this hunk
1167 var oldEOFNewline = /\n$/.test(oldStr);
1168 var newEOFNewline = /\n$/.test(newStr);
1169 var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
1171 if (!oldEOFNewline && noNlBeforeAdds) {
1172 // special case: old has no eol and no trailing context; no-nl can end up before adds
1173 curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
1176 if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
1177 curRange.push('\\ No newline at end of file');
1188 oldLine += lines.length;
1189 newLine += lines.length;
1193 for (var i = 0; i < diff.length; i++) {
1198 oldFileName: oldFileName,
1199 newFileName: newFileName,
1200 oldHeader: oldHeader,
1201 newHeader: newHeader,
1206 function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1207 var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
1210 if (oldFileName == newFileName) {
1211 ret.push('Index: ' + oldFileName);
1214 ret.push('===================================================================');
1215 ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
1216 ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
1218 for (var i = 0; i < diff.hunks.length; i++) {
1219 var hunk = diff.hunks[i];
1220 ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
1221 ret.push.apply(ret, hunk.lines);
1224 return ret.join('\n') + '\n';
1227 function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
1228 return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
1231 function arrayEqual(a, b) {
1232 if (a.length !== b.length) {
1236 return arrayStartsWith(a, b);
1239 function arrayStartsWith(array, start) {
1240 if (start.length > array.length) {
1244 for (var i = 0; i < start.length; i++) {
1245 if (start[i] !== array[i]) {
1253 function calcLineCount(hunk) {
1254 var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
1255 oldLines = _calcOldNewLineCount.oldLines,
1256 newLines = _calcOldNewLineCount.newLines;
1258 if (oldLines !== undefined) {
1259 hunk.oldLines = oldLines;
1261 delete hunk.oldLines;
1264 if (newLines !== undefined) {
1265 hunk.newLines = newLines;
1267 delete hunk.newLines;
1271 function merge(mine, theirs, base) {
1272 mine = loadPatch(mine, base);
1273 theirs = loadPatch(theirs, base);
1274 var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
1275 // Leaving sanity checks on this to the API consumer that may know more about the
1276 // meaning in their own context.
1278 if (mine.index || theirs.index) {
1279 ret.index = mine.index || theirs.index;
1282 if (mine.newFileName || theirs.newFileName) {
1283 if (!fileNameChanged(mine)) {
1284 // No header or no change in ours, use theirs (and ours if theirs does not exist)
1285 ret.oldFileName = theirs.oldFileName || mine.oldFileName;
1286 ret.newFileName = theirs.newFileName || mine.newFileName;
1287 ret.oldHeader = theirs.oldHeader || mine.oldHeader;
1288 ret.newHeader = theirs.newHeader || mine.newHeader;
1289 } else if (!fileNameChanged(theirs)) {
1290 // No header or no change in theirs, use ours
1291 ret.oldFileName = mine.oldFileName;
1292 ret.newFileName = mine.newFileName;
1293 ret.oldHeader = mine.oldHeader;
1294 ret.newHeader = mine.newHeader;
1296 // Both changed... figure it out
1297 ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
1298 ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
1299 ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
1300 ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
1310 while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
1311 var mineCurrent = mine.hunks[mineIndex] || {
1314 theirsCurrent = theirs.hunks[theirsIndex] || {
1318 if (hunkBefore(mineCurrent, theirsCurrent)) {
1319 // This patch does not overlap with any of the others, yay.
1320 ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
1322 theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
1323 } else if (hunkBefore(theirsCurrent, mineCurrent)) {
1324 // This patch does not overlap with any of the others, yay.
1325 ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
1327 mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
1329 // Overlap, merge as best we can
1331 oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
1333 newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
1337 mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
1340 ret.hunks.push(mergedHunk);
1347 function loadPatch(param, base) {
1348 if (typeof param === 'string') {
1349 if (/^@@/m.test(param) || /^Index:/m.test(param)) {
1350 return parsePatch(param)[0];
1354 throw new Error('Must provide a base reference or pass in a patch');
1357 return structuredPatch(undefined, undefined, base, param);
1363 function fileNameChanged(patch) {
1364 return patch.newFileName && patch.newFileName !== patch.oldFileName;
1367 function selectField(index, mine, theirs) {
1368 if (mine === theirs) {
1371 index.conflict = true;
1379 function hunkBefore(test, check) {
1380 return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
1383 function cloneHunk(hunk, offset) {
1385 oldStart: hunk.oldStart,
1386 oldLines: hunk.oldLines,
1387 newStart: hunk.newStart + offset,
1388 newLines: hunk.newLines,
1393 function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
1394 // This will generally result in a conflicted hunk, but there are cases where the context
1395 // is the only overlap where we can successfully merge the content here.
1402 offset: theirOffset,
1405 }; // Handle any leading content
1407 insertLeading(hunk, mine, their);
1408 insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
1410 while (mine.index < mine.lines.length && their.index < their.lines.length) {
1411 var mineCurrent = mine.lines[mine.index],
1412 theirCurrent = their.lines[their.index];
1414 if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
1415 // Both modified ...
1416 mutualChange(hunk, mine, their);
1417 } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
1418 var _hunk$lines; // Mine inserted
1421 (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
1422 } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
1423 var _hunk$lines2; // Theirs inserted
1426 (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
1427 } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
1428 // Mine removed or edited
1429 removal(hunk, mine, their);
1430 } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
1431 // Their removed or edited
1432 removal(hunk, their, mine, true);
1433 } else if (mineCurrent === theirCurrent) {
1435 hunk.lines.push(mineCurrent);
1440 conflict(hunk, collectChange(mine), collectChange(their));
1442 } // Now push anything that may be remaining
1445 insertTrailing(hunk, mine);
1446 insertTrailing(hunk, their);
1447 calcLineCount(hunk);
1450 function mutualChange(hunk, mine, their) {
1451 var myChanges = collectChange(mine),
1452 theirChanges = collectChange(their);
1454 if (allRemoves(myChanges) && allRemoves(theirChanges)) {
1455 // Special case for remove changes that are supersets of one another
1456 if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
1459 (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
1462 } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
1465 (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
1469 } else if (arrayEqual(myChanges, theirChanges)) {
1472 (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
1477 conflict(hunk, myChanges, theirChanges);
1480 function removal(hunk, mine, their, swap) {
1481 var myChanges = collectChange(mine),
1482 theirChanges = collectContext(their, myChanges);
1484 if (theirChanges.merged) {
1487 (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
1489 conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
1493 function conflict(hunk, mine, their) {
1494 hunk.conflict = true;
1502 function insertLeading(hunk, insert, their) {
1503 while (insert.offset < their.offset && insert.index < insert.lines.length) {
1504 var line = insert.lines[insert.index++];
1505 hunk.lines.push(line);
1510 function insertTrailing(hunk, insert) {
1511 while (insert.index < insert.lines.length) {
1512 var line = insert.lines[insert.index++];
1513 hunk.lines.push(line);
1517 function collectChange(state) {
1519 operation = state.lines[state.index][0];
1521 while (state.index < state.lines.length) {
1522 var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
1524 if (operation === '-' && line[0] === '+') {
1528 if (operation === line[0]) {
1539 function collectContext(state, matchChanges) {
1543 contextChanges = false,
1546 while (matchIndex < matchChanges.length && state.index < state.lines.length) {
1547 var change = state.lines[state.index],
1548 match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
1550 if (match[0] === '+') {
1554 contextChanges = contextChanges || change[0] !== ' ';
1556 matchIndex++; // Consume any additions in the other block as a conflict to attempt
1557 // to pull in the remaining context after this
1559 if (change[0] === '+') {
1562 while (change[0] === '+') {
1563 changes.push(change);
1564 change = state.lines[++state.index];
1568 if (match.substr(1) === change.substr(1)) {
1569 changes.push(change);
1576 if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
1584 while (matchIndex < matchChanges.length) {
1585 merged.push(matchChanges[matchIndex++]);
1594 function allRemoves(changes) {
1595 return changes.reduce(function (prev, change) {
1596 return prev && change[0] === '-';
1600 function skipRemoveSuperset(state, removeChanges, delta) {
1601 for (var i = 0; i < delta; i++) {
1602 var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
1604 if (state.lines[state.index + i] !== ' ' + changeContent) {
1609 state.index += delta;
1613 function calcOldNewLineCount(lines) {
1616 lines.forEach(function (line) {
1617 if (typeof line !== 'string') {
1618 var myCount = calcOldNewLineCount(line.mine);
1619 var theirCount = calcOldNewLineCount(line.theirs);
1621 if (oldLines !== undefined) {
1622 if (myCount.oldLines === theirCount.oldLines) {
1623 oldLines += myCount.oldLines;
1625 oldLines = undefined;
1629 if (newLines !== undefined) {
1630 if (myCount.newLines === theirCount.newLines) {
1631 newLines += myCount.newLines;
1633 newLines = undefined;
1637 if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
1641 if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
1650 } // See: http://code.google.com/p/google-diff-match-patch/wiki/API
1653 function convertChangesToDMP(changes) {
1658 for (var i = 0; i < changes.length; i++) {
1659 change = changes[i];
1663 } else if (change.removed) {
1669 ret.push([operation, change.value]);
1675 function convertChangesToXML(changes) {
1678 for (var i = 0; i < changes.length; i++) {
1679 var change = changes[i];
1683 } else if (change.removed) {
1687 ret.push(escapeHTML(change.value));
1691 } else if (change.removed) {
1696 return ret.join('');
1699 function escapeHTML(s) {
1701 n = n.replace(/&/g, '&');
1702 n = n.replace(/</g, '<');
1703 n = n.replace(/>/g, '>');
1704 n = n.replace(/"/g, '"');
1708 var index_es6 = /*#__PURE__*/Object.freeze({
1711 diffChars: diffChars,
1712 diffWords: diffWords,
1713 diffWordsWithSpace: diffWordsWithSpace,
1714 diffLines: diffLines,
1715 diffTrimmedLines: diffTrimmedLines,
1716 diffSentences: diffSentences,
1719 diffArrays: diffArrays,
1720 structuredPatch: structuredPatch,
1721 createTwoFilesPatch: createTwoFilesPatch,
1722 createPatch: createPatch,
1723 applyPatch: applyPatch,
1724 applyPatches: applyPatches,
1725 parsePatch: parsePatch,
1727 convertChangesToDMP: convertChangesToDMP,
1728 convertChangesToXML: convertChangesToXML,
1729 canonicalize: canonicalize
1733 * normalize-path <https://github.com/jonschlinkert/normalize-path>
1735 * Copyright (c) 2014-2018, Jon Schlinkert.
1736 * Released under the MIT License.
1738 var normalizePath = function normalizePath(path, stripTrailing) {
1739 if (typeof path !== 'string') {
1740 throw new TypeError('expected path to be a string');
1743 if (path === '\\' || path === '/') return '/';
1744 var len = path.length;
1745 if (len <= 1) return path; // ensure that win32 namespaces has two leading slashes, so that the path is
1746 // handled properly by the win32 version of path.parse() after being normalized
1747 // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
1751 if (len > 4 && path[3] === '\\') {
1754 if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
1755 path = path.slice(2);
1760 var segs = path.split(/[/\\]+/);
1762 if (stripTrailing !== false && segs[segs.length - 1] === '') {
1766 return prefix + segs.join('/');
1769 function _classCallCheck(instance, Constructor) {
1770 if (!(instance instanceof Constructor)) {
1771 throw new TypeError("Cannot call a class as a function");
1775 function _defineProperties(target, props) {
1776 for (var i = 0; i < props.length; i++) {
1777 var descriptor = props[i];
1778 descriptor.enumerable = descriptor.enumerable || false;
1779 descriptor.configurable = true;
1780 if ("value" in descriptor) descriptor.writable = true;
1781 Object.defineProperty(target, descriptor.key, descriptor);
1785 function _createClass(Constructor, protoProps, staticProps) {
1786 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
1787 if (staticProps) _defineProperties(Constructor, staticProps);
1791 function _inherits(subClass, superClass) {
1792 if (typeof superClass !== "function" && superClass !== null) {
1793 throw new TypeError("Super expression must either be null or a function");
1796 subClass.prototype = Object.create(superClass && superClass.prototype, {
1803 if (superClass) _setPrototypeOf(subClass, superClass);
1806 function _getPrototypeOf(o) {
1807 _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
1808 return o.__proto__ || Object.getPrototypeOf(o);
1810 return _getPrototypeOf(o);
1813 function _setPrototypeOf(o, p) {
1814 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
1819 return _setPrototypeOf(o, p);
1822 function isNativeReflectConstruct() {
1823 if (typeof Reflect === "undefined" || !Reflect.construct) return false;
1824 if (Reflect.construct.sham) return false;
1825 if (typeof Proxy === "function") return true;
1828 Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
1835 function _construct(Parent, args, Class) {
1836 if (isNativeReflectConstruct()) {
1837 _construct = Reflect.construct;
1839 _construct = function _construct(Parent, args, Class) {
1841 a.push.apply(a, args);
1842 var Constructor = Function.bind.apply(Parent, a);
1843 var instance = new Constructor();
1844 if (Class) _setPrototypeOf(instance, Class.prototype);
1849 return _construct.apply(null, arguments);
1852 function _isNativeFunction(fn) {
1853 return Function.toString.call(fn).indexOf("[native code]") !== -1;
1856 function _wrapNativeSuper(Class) {
1857 var _cache = typeof Map === "function" ? new Map() : undefined;
1859 _wrapNativeSuper = function _wrapNativeSuper(Class) {
1860 if (Class === null || !_isNativeFunction(Class)) return Class;
1862 if (typeof Class !== "function") {
1863 throw new TypeError("Super expression must either be null or a function");
1866 if (typeof _cache !== "undefined") {
1867 if (_cache.has(Class)) return _cache.get(Class);
1869 _cache.set(Class, Wrapper);
1872 function Wrapper() {
1873 return _construct(Class, arguments, _getPrototypeOf(this).constructor);
1876 Wrapper.prototype = Object.create(Class.prototype, {
1884 return _setPrototypeOf(Wrapper, Class);
1887 return _wrapNativeSuper(Class);
1890 function _assertThisInitialized(self) {
1891 if (self === void 0) {
1892 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
1898 function _possibleConstructorReturn(self, call) {
1899 if (call && (typeof call === "object" || typeof call === "function")) {
1903 return _assertThisInitialized(self);
1906 function _superPropBase(object, property) {
1907 while (!Object.prototype.hasOwnProperty.call(object, property)) {
1908 object = _getPrototypeOf(object);
1909 if (object === null) break;
1915 function _get(target, property, receiver) {
1916 if (typeof Reflect !== "undefined" && Reflect.get) {
1919 _get = function _get(target, property, receiver) {
1920 var base = _superPropBase(target, property);
1923 var desc = Object.getOwnPropertyDescriptor(base, property);
1926 return desc.get.call(receiver);
1933 return _get(target, property, receiver || target);
1936 function _slicedToArray(arr, i) {
1937 return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
1940 function _toConsumableArray$1(arr) {
1941 return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _nonIterableSpread$1();
1944 function _arrayWithoutHoles$1(arr) {
1945 if (Array.isArray(arr)) {
1946 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
1952 function _arrayWithHoles(arr) {
1953 if (Array.isArray(arr)) return arr;
1956 function _iterableToArray$1(iter) {
1957 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
1960 function _iterableToArrayLimit(arr, i) {
1961 if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
1971 for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
1972 _arr.push(_s.value);
1974 if (i && _arr.length === i) break;
1981 if (!_n && _i["return"] != null) _i["return"]();
1990 function _nonIterableSpread$1() {
1991 throw new TypeError("Invalid attempt to spread non-iterable instance");
1994 function _nonIterableRest() {
1995 throw new TypeError("Invalid attempt to destructure non-iterable instance");
2006 function LineByLine(file, options) {
2007 _classCallCheck(this, LineByLine);
2009 options = options || {};
2010 if (!options.readChunk) options.readChunk = 1024;
2012 if (!options.newLineCharacter) {
2013 options.newLineCharacter = 0x0a; //linux line ending
2015 options.newLineCharacter = options.newLineCharacter.charCodeAt(0);
2018 if (typeof file === 'number') {
2021 this.fd = fs$1.openSync(file, 'r');
2024 this.options = options;
2025 this.newLineCharacter = options.newLineCharacter;
2029 _createClass(LineByLine, [{
2030 key: "_searchInBuffer",
2031 value: function _searchInBuffer(buffer, hexNeedle) {
2034 for (var i = 0; i <= buffer.length; i++) {
2035 var b_byte = buffer[i];
2037 if (b_byte === hexNeedle) {
2047 value: function reset() {
2048 this.eofReached = false;
2049 this.linesCache = [];
2050 this.fdPosition = 0;
2054 value: function close() {
2055 fs$1.closeSync(this.fd);
2059 key: "_extractLines",
2060 value: function _extractLines(buffer) {
2063 var bufferPosition = 0;
2064 var lastNewLineBufferPosition = 0;
2067 var bufferPositionValue = buffer[bufferPosition++];
2069 if (bufferPositionValue === this.newLineCharacter) {
2070 line = buffer.slice(lastNewLineBufferPosition, bufferPosition);
2072 lastNewLineBufferPosition = bufferPosition;
2073 } else if (!bufferPositionValue) {
2078 var leftovers = buffer.slice(lastNewLineBufferPosition, bufferPosition);
2080 if (leftovers.length) {
2081 lines.push(leftovers);
2088 value: function _readChunk(lineLeftovers) {
2089 var totalBytesRead = 0;
2094 var readBuffer = new Buffer(this.options.readChunk);
2095 bytesRead = fs$1.readSync(this.fd, readBuffer, 0, this.options.readChunk, this.fdPosition);
2096 totalBytesRead = totalBytesRead + bytesRead;
2097 this.fdPosition = this.fdPosition + bytesRead;
2098 buffers.push(readBuffer);
2099 } while (bytesRead && this._searchInBuffer(buffers[buffers.length - 1], this.options.newLineCharacter) === -1);
2101 var bufferData = Buffer.concat(buffers);
2103 if (bytesRead < this.options.readChunk) {
2104 this.eofReached = true;
2105 bufferData = bufferData.slice(0, totalBytesRead);
2108 if (totalBytesRead) {
2109 this.linesCache = this._extractLines(bufferData);
2111 if (lineLeftovers) {
2112 this.linesCache[0] = Buffer.concat([lineLeftovers, this.linesCache[0]]);
2116 return totalBytesRead;
2120 value: function next() {
2121 if (!this.fd) return false;
2124 if (this.eofReached && this.linesCache.length === 0) {
2130 if (!this.linesCache.length) {
2131 bytesRead = this._readChunk();
2134 if (this.linesCache.length) {
2135 line = this.linesCache.shift();
2136 var lastLineCharacter = line[line.length - 1];
2138 if (lastLineCharacter !== 0x0a) {
2139 bytesRead = this._readChunk(line);
2142 line = this.linesCache.shift();
2147 if (this.eofReached && this.linesCache.length === 0) {
2151 if (line && line[line.length - 1] === this.newLineCharacter) {
2152 line = line.slice(0, line.length - 1);
2162 var readlines = LineByLine;
2167 _inherits(ConfigError, _Error);
2169 function ConfigError() {
2170 _classCallCheck(this, ConfigError);
2172 return _possibleConstructorReturn(this, _getPrototypeOf(ConfigError).apply(this, arguments));
2176 }(_wrapNativeSuper(Error));
2180 function (_Error2) {
2181 _inherits(DebugError, _Error2);
2183 function DebugError() {
2184 _classCallCheck(this, DebugError);
2186 return _possibleConstructorReturn(this, _getPrototypeOf(DebugError).apply(this, arguments));
2190 }(_wrapNativeSuper(Error));
2192 var UndefinedParserError =
2194 function (_Error3) {
2195 _inherits(UndefinedParserError, _Error3);
2197 function UndefinedParserError() {
2198 _classCallCheck(this, UndefinedParserError);
2200 return _possibleConstructorReturn(this, _getPrototypeOf(UndefinedParserError).apply(this, arguments));
2203 return UndefinedParserError;
2204 }(_wrapNativeSuper(Error));
2209 UndefinedParserError
2212 function unwrapExports (x) {
2213 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
2216 function createCommonjsModule(fn, module) {
2217 return module = { exports: {} }, fn(module, module.exports), module.exports;
2220 function getCjsExportFromNamespace (n) {
2221 return n && n['default'] || n;
2224 var semver = createCommonjsModule(function (module, exports) {
2225 exports = module.exports = SemVer;
2227 /* istanbul ignore next */
2229 if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
2230 debug = function debug() {
2231 var args = Array.prototype.slice.call(arguments, 0);
2232 args.unshift('SEMVER');
2233 console.log.apply(console, args);
2236 debug = function debug() {};
2237 } // Note: this is the semver.org version of the spec that it implements
2238 // Not necessarily the package version of this code.
2241 exports.SEMVER_SPEC_VERSION = '2.0.0';
2242 var MAX_LENGTH = 256;
2243 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
2244 /* istanbul ignore next */
2245 9007199254740991; // Max safe segment length for coercion.
2247 var MAX_SAFE_COMPONENT_LENGTH = 16; // The actual regexps go on exports.re
2249 var re = exports.re = [];
2250 var src = exports.src = [];
2251 var t = exports.tokens = {};
2256 } // The following Regular Expressions can be used for tokenizing,
2257 // validating, and parsing SemVer version strings.
2258 // ## Numeric Identifier
2259 // A single `0`, or a non-zero digit followed by zero or more digits.
2262 tok('NUMERICIDENTIFIER');
2263 src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*';
2264 tok('NUMERICIDENTIFIERLOOSE');
2265 src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier
2266 // Zero or more digits, followed by a letter or hyphen, and then zero or
2267 // more letters, digits, or hyphens.
2269 tok('NONNUMERICIDENTIFIER');
2270 src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version
2271 // Three dot-separated numeric identifiers.
2274 src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')';
2275 tok('MAINVERSIONLOOSE');
2276 src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier
2277 // A numeric identifier, or a non-numeric identifier.
2279 tok('PRERELEASEIDENTIFIER');
2280 src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + '|' + src[t.NONNUMERICIDENTIFIER] + ')';
2281 tok('PRERELEASEIDENTIFIERLOOSE');
2282 src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + '|' + src[t.NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version
2283 // Hyphen, followed by one or more dot-separated pre-release version
2287 src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))';
2288 tok('PRERELEASELOOSE');
2289 src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier
2290 // Any combination of digits, letters, or hyphens.
2292 tok('BUILDIDENTIFIER');
2293 src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata
2294 // Plus sign, followed by one or more period-separated build metadata
2298 src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))'; // ## Full Version String
2299 // A main version, followed optionally by a pre-release version and
2301 // Note that the only major, minor, patch, and pre-release sections of
2302 // the version string are capturing groups. The build metadata is not a
2303 // capturing group, because it should not ever be used in version
2308 src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + src[t.PRERELEASE] + '?' + src[t.BUILD] + '?';
2309 src[t.FULL] = '^' + src[t.FULLPLAIN] + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
2310 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
2311 // common in the npm registry.
2314 src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + src[t.PRERELEASELOOSE] + '?' + src[t.BUILD] + '?';
2316 src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$';
2318 src[t.GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x".
2319 // Note that "x.x" is a valid xRange identifer, meaning "any version"
2320 // Only the first item is strictly required.
2322 tok('XRANGEIDENTIFIERLOOSE');
2323 src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
2324 tok('XRANGEIDENTIFIER');
2325 src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*';
2327 src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:' + src[t.PRERELEASE] + ')?' + src[t.BUILD] + '?' + ')?)?';
2328 tok('XRANGEPLAINLOOSE');
2329 src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[t.PRERELEASELOOSE] + ')?' + src[t.BUILD] + '?' + ')?)?';
2331 src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$';
2333 src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$'; // Coercion.
2334 // Extract anything that could conceivably be a part of a valid semver
2337 src[t.COERCE] = '(^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])';
2339 re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g'); // Tilde ranges.
2340 // Meaning is "reasonably at or greater than"
2343 src[t.LONETILDE] = '(?:~>?)';
2345 src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+';
2346 re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g');
2347 var tildeTrimReplace = '$1~';
2349 src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$';
2351 src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$'; // Caret ranges.
2352 // Meaning is "at least and backwards compatible with"
2355 src[t.LONECARET] = '(?:\\^)';
2357 src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+';
2358 re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g');
2359 var caretTrimReplace = '$1^';
2361 src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$';
2363 src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version"
2365 tok('COMPARATORLOOSE');
2366 src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$';
2368 src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing
2369 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
2371 tok('COMPARATORTRIM');
2372 src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')'; // this one has to use the /g flag
2374 re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g');
2375 var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
2376 // Note that these all use the loose form, because they'll be
2377 // checked against either the strict or loose comparator form
2381 src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAIN] + ')' + '\\s*$';
2382 tok('HYPHENRANGELOOSE');
2383 src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all.
2386 src[t.STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects.
2387 // All are flag-free, unless they were created above with a flag.
2389 for (var i = 0; i < R; i++) {
2393 re[i] = new RegExp(src[i]);
2397 exports.parse = parse;
2399 function parse(version, options) {
2400 if (!options || typeof options !== 'object') {
2403 includePrerelease: false
2407 if (version instanceof SemVer) {
2411 if (typeof version !== 'string') {
2415 if (version.length > MAX_LENGTH) {
2419 var r = options.loose ? re[t.LOOSE] : re[t.FULL];
2421 if (!r.test(version)) {
2426 return new SemVer(version, options);
2432 exports.valid = valid;
2434 function valid(version, options) {
2435 var v = parse(version, options);
2436 return v ? v.version : null;
2439 exports.clean = clean;
2441 function clean(version, options) {
2442 var s = parse(version.trim().replace(/^[=v]+/, ''), options);
2443 return s ? s.version : null;
2446 exports.SemVer = SemVer;
2448 function SemVer(version, options) {
2449 if (!options || typeof options !== 'object') {
2452 includePrerelease: false
2456 if (version instanceof SemVer) {
2457 if (version.loose === options.loose) {
2460 version = version.version;
2462 } else if (typeof version !== 'string') {
2463 throw new TypeError('Invalid Version: ' + version);
2466 if (version.length > MAX_LENGTH) {
2467 throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters');
2470 if (!(this instanceof SemVer)) {
2471 return new SemVer(version, options);
2474 debug('SemVer', version, options);
2475 this.options = options;
2476 this.loose = !!options.loose;
2477 var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
2480 throw new TypeError('Invalid Version: ' + version);
2483 this.raw = version; // these are actually numbers
2489 if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
2490 throw new TypeError('Invalid major version');
2493 if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
2494 throw new TypeError('Invalid minor version');
2497 if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
2498 throw new TypeError('Invalid patch version');
2499 } // numberify any prerelease numeric ids
2503 this.prerelease = [];
2505 this.prerelease = m[4].split('.').map(function (id) {
2506 if (/^[0-9]+$/.test(id)) {
2509 if (num >= 0 && num < MAX_SAFE_INTEGER) {
2518 this.build = m[5] ? m[5].split('.') : [];
2522 SemVer.prototype.format = function () {
2523 this.version = this.major + '.' + this.minor + '.' + this.patch;
2525 if (this.prerelease.length) {
2526 this.version += '-' + this.prerelease.join('.');
2529 return this.version;
2532 SemVer.prototype.toString = function () {
2533 return this.version;
2536 SemVer.prototype.compare = function (other) {
2537 debug('SemVer.compare', this.version, this.options, other);
2539 if (!(other instanceof SemVer)) {
2540 other = new SemVer(other, this.options);
2543 return this.compareMain(other) || this.comparePre(other);
2546 SemVer.prototype.compareMain = function (other) {
2547 if (!(other instanceof SemVer)) {
2548 other = new SemVer(other, this.options);
2551 return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
2554 SemVer.prototype.comparePre = function (other) {
2555 if (!(other instanceof SemVer)) {
2556 other = new SemVer(other, this.options);
2557 } // NOT having a prerelease is > having one
2560 if (this.prerelease.length && !other.prerelease.length) {
2562 } else if (!this.prerelease.length && other.prerelease.length) {
2564 } else if (!this.prerelease.length && !other.prerelease.length) {
2571 var a = this.prerelease[i];
2572 var b = other.prerelease[i];
2573 debug('prerelease compare', i, a, b);
2575 if (a === undefined && b === undefined) {
2577 } else if (b === undefined) {
2579 } else if (a === undefined) {
2581 } else if (a === b) {
2584 return compareIdentifiers(a, b);
2589 SemVer.prototype.compareBuild = function (other) {
2590 if (!(other instanceof SemVer)) {
2591 other = new SemVer(other, this.options);
2597 var a = this.build[i];
2598 var b = other.build[i];
2599 debug('prerelease compare', i, a, b);
2601 if (a === undefined && b === undefined) {
2603 } else if (b === undefined) {
2605 } else if (a === undefined) {
2607 } else if (a === b) {
2610 return compareIdentifiers(a, b);
2613 }; // preminor will bump the version up to the next minor release, and immediately
2614 // down to pre-release. premajor and prepatch work the same way.
2617 SemVer.prototype.inc = function (release, identifier) {
2620 this.prerelease.length = 0;
2624 this.inc('pre', identifier);
2628 this.prerelease.length = 0;
2631 this.inc('pre', identifier);
2635 // If this is already a prerelease, it will bump to the next version
2636 // drop any prereleases that might already exist, since they are not
2637 // relevant at this point.
2638 this.prerelease.length = 0;
2639 this.inc('patch', identifier);
2640 this.inc('pre', identifier);
2642 // If the input is a non-prerelease version, this acts the same as
2646 if (this.prerelease.length === 0) {
2647 this.inc('patch', identifier);
2650 this.inc('pre', identifier);
2654 // If this is a pre-major version, bump up to the same major version.
2655 // Otherwise increment major.
2656 // 1.0.0-5 bumps to 1.0.0
2657 // 1.1.0 bumps to 2.0.0
2658 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
2664 this.prerelease = [];
2668 // If this is a pre-minor version, bump up to the same minor version.
2669 // Otherwise increment minor.
2670 // 1.2.0-5 bumps to 1.2.0
2671 // 1.2.1 bumps to 1.3.0
2672 if (this.patch !== 0 || this.prerelease.length === 0) {
2677 this.prerelease = [];
2681 // If this is not a pre-release version, it will increment the patch.
2682 // If it is a pre-release it will bump up to the same patch version.
2683 // 1.2.0-5 patches to 1.2.0
2684 // 1.2.0 patches to 1.2.1
2685 if (this.prerelease.length === 0) {
2689 this.prerelease = [];
2691 // This probably shouldn't be used publicly.
2692 // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
2695 if (this.prerelease.length === 0) {
2696 this.prerelease = [0];
2698 var i = this.prerelease.length;
2701 if (typeof this.prerelease[i] === 'number') {
2702 this.prerelease[i]++;
2708 // didn't increment anything
2709 this.prerelease.push(0);
2714 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
2715 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
2716 if (this.prerelease[0] === identifier) {
2717 if (isNaN(this.prerelease[1])) {
2718 this.prerelease = [identifier, 0];
2721 this.prerelease = [identifier, 0];
2728 throw new Error('invalid increment argument: ' + release);
2732 this.raw = this.version;
2738 function inc(version, release, loose, identifier) {
2739 if (typeof loose === 'string') {
2745 return new SemVer(version, loose).inc(release, identifier).version;
2751 exports.diff = diff;
2753 function diff(version1, version2) {
2754 if (eq(version1, version2)) {
2757 var v1 = parse(version1);
2758 var v2 = parse(version2);
2761 if (v1.prerelease.length || v2.prerelease.length) {
2763 var defaultResult = 'prerelease';
2766 for (var key in v1) {
2767 if (key === 'major' || key === 'minor' || key === 'patch') {
2768 if (v1[key] !== v2[key]) {
2769 return prefix + key;
2774 return defaultResult; // may be undefined
2778 exports.compareIdentifiers = compareIdentifiers;
2779 var numeric = /^[0-9]+$/;
2781 function compareIdentifiers(a, b) {
2782 var anum = numeric.test(a);
2783 var bnum = numeric.test(b);
2790 return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
2793 exports.rcompareIdentifiers = rcompareIdentifiers;
2795 function rcompareIdentifiers(a, b) {
2796 return compareIdentifiers(b, a);
2799 exports.major = major;
2801 function major(a, loose) {
2802 return new SemVer(a, loose).major;
2805 exports.minor = minor;
2807 function minor(a, loose) {
2808 return new SemVer(a, loose).minor;
2811 exports.patch = patch;
2813 function patch(a, loose) {
2814 return new SemVer(a, loose).patch;
2817 exports.compare = compare;
2819 function compare(a, b, loose) {
2820 return new SemVer(a, loose).compare(new SemVer(b, loose));
2823 exports.compareLoose = compareLoose;
2825 function compareLoose(a, b) {
2826 return compare(a, b, true);
2829 exports.compareBuild = compareBuild;
2831 function compareBuild(a, b, loose) {
2832 var versionA = new SemVer(a, loose);
2833 var versionB = new SemVer(b, loose);
2834 return versionA.compare(versionB) || versionA.compareBuild(versionB);
2837 exports.rcompare = rcompare;
2839 function rcompare(a, b, loose) {
2840 return compare(b, a, loose);
2843 exports.sort = sort;
2845 function sort(list, loose) {
2846 return list.sort(function (a, b) {
2847 return exports.compareBuild(a, b, loose);
2851 exports.rsort = rsort;
2853 function rsort(list, loose) {
2854 return list.sort(function (a, b) {
2855 return exports.compareBuild(b, a, loose);
2861 function gt(a, b, loose) {
2862 return compare(a, b, loose) > 0;
2867 function lt(a, b, loose) {
2868 return compare(a, b, loose) < 0;
2873 function eq(a, b, loose) {
2874 return compare(a, b, loose) === 0;
2879 function neq(a, b, loose) {
2880 return compare(a, b, loose) !== 0;
2885 function gte(a, b, loose) {
2886 return compare(a, b, loose) >= 0;
2891 function lte(a, b, loose) {
2892 return compare(a, b, loose) <= 0;
2897 function cmp(a, op, b, loose) {
2900 if (typeof a === 'object') a = a.version;
2901 if (typeof b === 'object') b = b.version;
2905 if (typeof a === 'object') a = a.version;
2906 if (typeof b === 'object') b = b.version;
2912 return eq(a, b, loose);
2915 return neq(a, b, loose);
2918 return gt(a, b, loose);
2921 return gte(a, b, loose);
2924 return lt(a, b, loose);
2927 return lte(a, b, loose);
2930 throw new TypeError('Invalid operator: ' + op);
2934 exports.Comparator = Comparator;
2936 function Comparator(comp, options) {
2937 if (!options || typeof options !== 'object') {
2940 includePrerelease: false
2944 if (comp instanceof Comparator) {
2945 if (comp.loose === !!options.loose) {
2952 if (!(this instanceof Comparator)) {
2953 return new Comparator(comp, options);
2956 debug('comparator', comp, options);
2957 this.options = options;
2958 this.loose = !!options.loose;
2961 if (this.semver === ANY) {
2964 this.value = this.operator + this.semver.version;
2967 debug('comp', this);
2972 Comparator.prototype.parse = function (comp) {
2973 var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
2974 var m = comp.match(r);
2977 throw new TypeError('Invalid comparator: ' + comp);
2980 this.operator = m[1] !== undefined ? m[1] : '';
2982 if (this.operator === '=') {
2984 } // if it literally is just '>' or '' then allow anything.
2990 this.semver = new SemVer(m[2], this.options.loose);
2994 Comparator.prototype.toString = function () {
2998 Comparator.prototype.test = function (version) {
2999 debug('Comparator.test', version, this.options.loose);
3001 if (this.semver === ANY || version === ANY) {
3005 if (typeof version === 'string') {
3007 version = new SemVer(version, this.options);
3013 return cmp(version, this.operator, this.semver, this.options);
3016 Comparator.prototype.intersects = function (comp, options) {
3017 if (!(comp instanceof Comparator)) {
3018 throw new TypeError('a Comparator is required');
3021 if (!options || typeof options !== 'object') {
3024 includePrerelease: false
3030 if (this.operator === '') {
3031 if (this.value === '') {
3035 rangeTmp = new Range(comp.value, options);
3036 return satisfies(this.value, rangeTmp, options);
3037 } else if (comp.operator === '') {
3038 if (comp.value === '') {
3042 rangeTmp = new Range(this.value, options);
3043 return satisfies(comp.semver, rangeTmp, options);
3046 var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>');
3047 var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<');
3048 var sameSemVer = this.semver.version === comp.semver.version;
3049 var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=');
3050 var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<');
3051 var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>');
3052 return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
3055 exports.Range = Range;
3057 function Range(range, options) {
3058 if (!options || typeof options !== 'object') {
3061 includePrerelease: false
3065 if (range instanceof Range) {
3066 if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
3069 return new Range(range.raw, options);
3073 if (range instanceof Comparator) {
3074 return new Range(range.value, options);
3077 if (!(this instanceof Range)) {
3078 return new Range(range, options);
3081 this.options = options;
3082 this.loose = !!options.loose;
3083 this.includePrerelease = !!options.includePrerelease; // First, split based on boolean or ||
3086 this.set = range.split(/\s*\|\|\s*/).map(function (range) {
3087 return this.parseRange(range.trim());
3088 }, this).filter(function (c) {
3089 // throw out any that are not relevant for whatever reason
3093 if (!this.set.length) {
3094 throw new TypeError('Invalid SemVer Range: ' + range);
3100 Range.prototype.format = function () {
3101 this.range = this.set.map(function (comps) {
3102 return comps.join(' ').trim();
3103 }).join('||').trim();
3107 Range.prototype.toString = function () {
3111 Range.prototype.parseRange = function (range) {
3112 var loose = this.options.loose;
3113 range = range.trim(); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
3115 var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
3116 range = range.replace(hr, hyphenReplace);
3117 debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
3119 range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
3120 debug('comparator trim', range, re[t.COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3`
3122 range = range.replace(re[t.TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3`
3124 range = range.replace(re[t.CARETTRIM], caretTrimReplace); // normalize spaces
3126 range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and
3127 // ready to be split into comparators.
3129 var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
3130 var set = range.split(' ').map(function (comp) {
3131 return parseComparator(comp, this.options);
3132 }, this).join(' ').split(/\s+/);
3134 if (this.options.loose) {
3135 // in loose mode, throw out any that are not valid comparators
3136 set = set.filter(function (comp) {
3137 return !!comp.match(compRe);
3141 set = set.map(function (comp) {
3142 return new Comparator(comp, this.options);
3147 Range.prototype.intersects = function (range, options) {
3148 if (!(range instanceof Range)) {
3149 throw new TypeError('a Range is required');
3152 return this.set.some(function (thisComparators) {
3153 return isSatisfiable(thisComparators, options) && range.set.some(function (rangeComparators) {
3154 return isSatisfiable(rangeComparators, options) && thisComparators.every(function (thisComparator) {
3155 return rangeComparators.every(function (rangeComparator) {
3156 return thisComparator.intersects(rangeComparator, options);
3161 }; // take a set of comparators and determine whether there
3162 // exists a version which can satisfy it
3165 function isSatisfiable(comparators, options) {
3167 var remainingComparators = comparators.slice();
3168 var testComparator = remainingComparators.pop();
3170 while (result && remainingComparators.length) {
3171 result = remainingComparators.every(function (otherComparator) {
3172 return testComparator.intersects(otherComparator, options);
3174 testComparator = remainingComparators.pop();
3178 } // Mostly just for testing and legacy API reasons
3181 exports.toComparators = toComparators;
3183 function toComparators(range, options) {
3184 return new Range(range, options).set.map(function (comp) {
3185 return comp.map(function (c) {
3187 }).join(' ').trim().split(' ');
3189 } // comprised of xranges, tildes, stars, and gtlt's at this point.
3190 // already replaced the hyphen ranges
3191 // turn into a set of JUST comparators.
3194 function parseComparator(comp, options) {
3195 debug('comp', comp, options);
3196 comp = replaceCarets(comp, options);
3197 debug('caret', comp);
3198 comp = replaceTildes(comp, options);
3199 debug('tildes', comp);
3200 comp = replaceXRanges(comp, options);
3201 debug('xrange', comp);
3202 comp = replaceStars(comp, options);
3203 debug('stars', comp);
3208 return !id || id.toLowerCase() === 'x' || id === '*';
3209 } // ~, ~> --> * (any, kinda silly)
3210 // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
3211 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
3212 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
3213 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
3214 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
3217 function replaceTildes(comp, options) {
3218 return comp.trim().split(/\s+/).map(function (comp) {
3219 return replaceTilde(comp, options);
3223 function replaceTilde(comp, options) {
3224 var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
3225 return comp.replace(r, function (_, M, m, p, pr) {
3226 debug('tilde', comp, _, M, m, p, pr);
3231 } else if (isX(m)) {
3232 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
3233 } else if (isX(p)) {
3234 // ~1.2 == >=1.2.0 <1.3.0
3235 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
3237 debug('replaceTilde pr', pr);
3238 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0';
3240 // ~1.2.3 == >=1.2.3 <1.3.0
3241 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
3244 debug('tilde return', ret);
3247 } // ^ --> * (any, kinda silly)
3248 // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
3249 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
3250 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
3251 // ^1.2.3 --> >=1.2.3 <2.0.0
3252 // ^1.2.0 --> >=1.2.0 <2.0.0
3255 function replaceCarets(comp, options) {
3256 return comp.trim().split(/\s+/).map(function (comp) {
3257 return replaceCaret(comp, options);
3261 function replaceCaret(comp, options) {
3262 debug('caret', comp, options);
3263 var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
3264 return comp.replace(r, function (_, M, m, p, pr) {
3265 debug('caret', comp, _, M, m, p, pr);
3270 } else if (isX(m)) {
3271 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
3272 } else if (isX(p)) {
3274 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
3276 ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
3279 debug('replaceCaret pr', pr);
3283 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1);
3285 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0';
3288 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0';
3295 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1);
3297 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
3300 ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0';
3304 debug('caret return', ret);
3309 function replaceXRanges(comp, options) {
3310 debug('replaceXRanges', comp, options);
3311 return comp.split(/\s+/).map(function (comp) {
3312 return replaceXRange(comp, options);
3316 function replaceXRange(comp, options) {
3318 var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
3319 return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
3320 debug('xRange', comp, ret, gtlt, M, m, p, pr);
3322 var xm = xM || isX(m);
3323 var xp = xm || isX(p);
3326 if (gtlt === '=' && anyX) {
3328 } // if we're including prereleases in the match, then we need
3329 // to fix this to -0, the lowest possible prerelease value
3332 pr = options.includePrerelease ? '-0' : '';
3335 if (gtlt === '>' || gtlt === '<') {
3336 // nothing is allowed
3339 // nothing is forbidden
3342 } else if (gtlt && anyX) {
3343 // we know patch is an x, because we have any x at all.
3354 // >1.2.3 => >= 1.2.4
3365 } else if (gtlt === '<=') {
3366 // <=0.7.x is actually <0.8.0, since any 0.7.x should
3367 // pass. Similarly, <=7.x is actually <8.0.0, etc.
3377 ret = gtlt + M + '.' + m + '.' + p + pr;
3379 ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr;
3381 ret = '>=' + M + '.' + m + '.0' + pr + ' <' + M + '.' + (+m + 1) + '.0' + pr;
3384 debug('xRange return', ret);
3387 } // Because * is AND-ed with everything else in the comparator,
3388 // and '' means "any version", just remove the *s entirely.
3391 function replaceStars(comp, options) {
3392 debug('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets!
3394 return comp.trim().replace(re[t.STAR], '');
3395 } // This function is passed to string.replace(re[t.HYPHENRANGE])
3396 // M, m, patch, prerelease, build
3397 // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
3398 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
3399 // 1.2 - 3.4 => >=1.2.0 <3.5.0
3402 function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
3405 } else if (isX(fm)) {
3406 from = '>=' + fM + '.0.0';
3407 } else if (isX(fp)) {
3408 from = '>=' + fM + '.' + fm + '.0';
3415 } else if (isX(tm)) {
3416 to = '<' + (+tM + 1) + '.0.0';
3417 } else if (isX(tp)) {
3418 to = '<' + tM + '.' + (+tm + 1) + '.0';
3420 to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;
3425 return (from + ' ' + to).trim();
3426 } // if ANY of the sets match ALL of its comparators, then pass
3429 Range.prototype.test = function (version) {
3434 if (typeof version === 'string') {
3436 version = new SemVer(version, this.options);
3442 for (var i = 0; i < this.set.length; i++) {
3443 if (testSet(this.set[i], version, this.options)) {
3451 function testSet(set, version, options) {
3452 for (var i = 0; i < set.length; i++) {
3453 if (!set[i].test(version)) {
3458 if (version.prerelease.length && !options.includePrerelease) {
3459 // Find the set of versions that are allowed to have prereleases
3460 // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
3461 // That should allow `1.2.3-pr.2` to pass.
3462 // However, `1.2.4-alpha.notready` should NOT be allowed,
3463 // even though it's within the range set by the comparators.
3464 for (i = 0; i < set.length; i++) {
3465 debug(set[i].semver);
3467 if (set[i].semver === ANY) {
3471 if (set[i].semver.prerelease.length > 0) {
3472 var allowed = set[i].semver;
3474 if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
3478 } // Version has a -pre, but it's not one of the ones we like.
3487 exports.satisfies = satisfies;
3489 function satisfies(version, range, options) {
3491 range = new Range(range, options);
3496 return range.test(version);
3499 exports.maxSatisfying = maxSatisfying;
3501 function maxSatisfying(versions, range, options) {
3506 var rangeObj = new Range(range, options);
3511 versions.forEach(function (v) {
3512 if (rangeObj.test(v)) {
3513 // satisfies(v, range, options)
3514 if (!max || maxSV.compare(v) === -1) {
3515 // compare(max, v, true)
3517 maxSV = new SemVer(max, options);
3524 exports.minSatisfying = minSatisfying;
3526 function minSatisfying(versions, range, options) {
3531 var rangeObj = new Range(range, options);
3536 versions.forEach(function (v) {
3537 if (rangeObj.test(v)) {
3538 // satisfies(v, range, options)
3539 if (!min || minSV.compare(v) === 1) {
3540 // compare(min, v, true)
3542 minSV = new SemVer(min, options);
3549 exports.minVersion = minVersion;
3551 function minVersion(range, loose) {
3552 range = new Range(range, loose);
3553 var minver = new SemVer('0.0.0');
3555 if (range.test(minver)) {
3559 minver = new SemVer('0.0.0-0');
3561 if (range.test(minver)) {
3567 for (var i = 0; i < range.set.length; ++i) {
3568 var comparators = range.set[i];
3569 comparators.forEach(function (comparator) {
3570 // Clone to avoid manipulating the comparator's semver object.
3571 var compver = new SemVer(comparator.semver.version);
3573 switch (comparator.operator) {
3575 if (compver.prerelease.length === 0) {
3578 compver.prerelease.push(0);
3581 compver.raw = compver.format();
3587 if (!minver || gt(minver, compver)) {
3595 /* Ignore maximum versions */
3598 /* istanbul ignore next */
3601 throw new Error('Unexpected operation: ' + comparator.operator);
3606 if (minver && range.test(minver)) {
3613 exports.validRange = validRange;
3615 function validRange(range, options) {
3617 // Return '*' instead of '' so that truthiness works.
3618 // This will throw if it's invalid anyway
3619 return new Range(range, options).range || '*';
3623 } // Determine if version is less than all the versions possible in the range
3628 function ltr(version, range, options) {
3629 return outside(version, range, '<', options);
3630 } // Determine if version is greater than all the versions possible in the range.
3635 function gtr(version, range, options) {
3636 return outside(version, range, '>', options);
3639 exports.outside = outside;
3641 function outside(version, range, hilo, options) {
3642 version = new SemVer(version, options);
3643 range = new Range(range, options);
3644 var gtfn, ltefn, ltfn, comp, ecomp;
3664 throw new TypeError('Must provide a hilo val of "<" or ">"');
3665 } // If it satisifes the range it is not outside
3668 if (satisfies(version, range, options)) {
3670 } // From now on, variable terms are as if we're in "gtr" mode.
3671 // but note that everything is flipped for the "ltr" function.
3674 for (var i = 0; i < range.set.length; ++i) {
3675 var comparators = range.set[i];
3678 comparators.forEach(function (comparator) {
3679 if (comparator.semver === ANY) {
3680 comparator = new Comparator('>=0.0.0');
3683 high = high || comparator;
3684 low = low || comparator;
3686 if (gtfn(comparator.semver, high.semver, options)) {
3688 } else if (ltfn(comparator.semver, low.semver, options)) {
3691 }); // If the edge version comparator has a operator then our version
3694 if (high.operator === comp || high.operator === ecomp) {
3696 } // If the lowest version comparator has an operator and our version
3697 // is less than it then it isn't higher than the range
3700 if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
3702 } else if (low.operator === ecomp && ltfn(version, low.semver)) {
3710 exports.prerelease = prerelease;
3712 function prerelease(version, options) {
3713 var parsed = parse(version, options);
3714 return parsed && parsed.prerelease.length ? parsed.prerelease : null;
3717 exports.intersects = intersects;
3719 function intersects(r1, r2, options) {
3720 r1 = new Range(r1, options);
3721 r2 = new Range(r2, options);
3722 return r1.intersects(r2);
3725 exports.coerce = coerce;
3727 function coerce(version, options) {
3728 if (version instanceof SemVer) {
3732 if (typeof version === 'number') {
3733 version = String(version);
3736 if (typeof version !== 'string') {
3740 options = options || {};
3744 match = version.match(re[t.COERCE]);
3746 // Find the right-most coercible string that does not share
3747 // a terminus with a more left-ward coercible string.
3748 // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
3750 // Walk through the string checking with a /g regexp
3751 // Manually set the index so as to pick up overlapping matches.
3752 // Stop when we get a match that ends at the string end, since no
3753 // coercible string can be more right-ward without the same terminus.
3756 while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) {
3757 if (!match || next.index + next[0].length !== match.index + match[0].length) {
3761 re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
3762 } // leave it in a clean state
3765 re[t.COERCERTL].lastIndex = -1;
3768 if (match === null) {
3772 return parse(match[2] + '.' + (match[3] || '0') + '.' + (match[4] || '0'), options);
3775 var semver_1 = semver.SEMVER_SPEC_VERSION;
3776 var semver_2 = semver.re;
3777 var semver_3 = semver.src;
3778 var semver_4 = semver.tokens;
3779 var semver_5 = semver.parse;
3780 var semver_6 = semver.valid;
3781 var semver_7 = semver.clean;
3782 var semver_8 = semver.SemVer;
3783 var semver_9 = semver.inc;
3784 var semver_10 = semver.diff;
3785 var semver_11 = semver.compareIdentifiers;
3786 var semver_12 = semver.rcompareIdentifiers;
3787 var semver_13 = semver.major;
3788 var semver_14 = semver.minor;
3789 var semver_15 = semver.patch;
3790 var semver_16 = semver.compare;
3791 var semver_17 = semver.compareLoose;
3792 var semver_18 = semver.compareBuild;
3793 var semver_19 = semver.rcompare;
3794 var semver_20 = semver.sort;
3795 var semver_21 = semver.rsort;
3796 var semver_22 = semver.gt;
3797 var semver_23 = semver.lt;
3798 var semver_24 = semver.eq;
3799 var semver_25 = semver.neq;
3800 var semver_26 = semver.gte;
3801 var semver_27 = semver.lte;
3802 var semver_28 = semver.cmp;
3803 var semver_29 = semver.Comparator;
3804 var semver_30 = semver.Range;
3805 var semver_31 = semver.toComparators;
3806 var semver_32 = semver.satisfies;
3807 var semver_33 = semver.maxSatisfying;
3808 var semver_34 = semver.minSatisfying;
3809 var semver_35 = semver.minVersion;
3810 var semver_36 = semver.validRange;
3811 var semver_37 = semver.ltr;
3812 var semver_38 = semver.gtr;
3813 var semver_39 = semver.outside;
3814 var semver_40 = semver.prerelease;
3815 var semver_41 = semver.intersects;
3816 var semver_42 = semver.coerce;
3818 var arrayify = function arrayify(object, keyName) {
3819 return Object.keys(object).reduce(function (array, key) {
3820 return array.concat(Object.assign({
3826 var dedent_1 = createCommonjsModule(function (module) {
3828 function dedent(strings) {
3831 if (typeof strings === "string") {
3832 // dedent can be used as a plain function
3836 } // first, perform interpolation
3841 for (var i = 0; i < raw.length; i++) {
3842 result += raw[i]. // join lines when there is a suppressed newline
3843 replace(/\\\n[ \t]*/g, ""). // handle escaped backticks
3844 replace(/\\`/g, "`");
3846 if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) {
3847 result += arguments.length <= i + 1 ? undefined : arguments[i + 1];
3849 } // now strip indentation
3852 var lines = result.split("\n");
3854 lines.forEach(function (l) {
3855 var m = l.match(/^(\s+)\S+/);
3858 var indent = m[1].length;
3861 // this is the first indented line
3864 mindent = Math.min(mindent, indent);
3869 if (mindent !== null) {
3870 result = lines.map(function (l) {
3871 return l[0] === " " ? l.slice(mindent) : l;
3873 } // dedent eats leading and trailing whitespace too
3876 result = result.trim(); // handle escaped newlines at the end to ensure they don't get stripped too
3878 return result.replace(/\\n/g, "\n");
3882 module.exports = dedent;
3886 var CATEGORY_CONFIG = "Config";
3887 var CATEGORY_EDITOR = "Editor";
3888 var CATEGORY_FORMAT = "Format";
3889 var CATEGORY_OTHER = "Other";
3890 var CATEGORY_OUTPUT = "Output";
3891 var CATEGORY_GLOBAL = "Global";
3892 var CATEGORY_SPECIAL = "Special";
3894 * @typedef {Object} OptionInfo
3895 * @property {string} [since] - available since version
3896 * @property {string} category
3897 * @property {'int' | 'boolean' | 'choice' | 'path'} type
3898 * @property {boolean} [array] - indicate it's an array of the specified type
3899 * @property {OptionValueInfo} [default]
3900 * @property {OptionRangeInfo} [range] - for type int
3901 * @property {string} description
3902 * @property {string} [deprecated] - deprecated since version
3903 * @property {OptionRedirectInfo} [redirect] - redirect deprecated option
3904 * @property {(value: any) => boolean} [exception]
3905 * @property {OptionChoiceInfo[]} [choices] - for type choice
3906 * @property {string} [cliName]
3907 * @property {string} [cliCategory]
3908 * @property {string} [cliDescription]
3910 * @typedef {number | boolean | string} OptionValue
3911 * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo
3913 * @typedef {Object} OptionRedirectInfo
3914 * @property {string} option
3915 * @property {OptionValue} value
3917 * @typedef {Object} OptionRangeInfo
3918 * @property {number} start - recommended range start
3919 * @property {number} end - recommended range end
3920 * @property {number} step - recommended range step
3922 * @typedef {Object} OptionChoiceInfo
3923 * @property {boolean | string} value - boolean for the option that is originally boolean type
3924 * @property {string} description
3925 * @property {string} [since] - undefined if available since the first version of the option
3926 * @property {string} [deprecated] - deprecated since version
3927 * @property {OptionValueInfo} [redirect] - redirect deprecated value
3930 /** @type {{ [name: string]: OptionInfo }} */
3935 category: CATEGORY_SPECIAL,
3943 description: dedent_1`
3944 Print (to stderr) where a cursor at the given position would move to after formatting.
3945 This option cannot be used with --range-start and --range-end.
3947 cliCategory: CATEGORY_EDITOR
3951 category: CATEGORY_GLOBAL,
3954 description: "Which end of line characters to apply.",
3957 description: dedent_1`
3959 (mixed values within one file are normalised by looking at what's used after the first line)
3963 description: "Line Feed only (\\n), common on Linux and macOS as well as inside git repos"
3966 description: "Carriage Return + Line Feed characters (\\r\\n), common on Windows"
3969 description: "Carriage Return character only (\\r), used very rarely"
3974 category: CATEGORY_SPECIAL,
3976 description: "Specify the input filepath. This will be used to do parser inference.",
3977 cliName: "stdin-filepath",
3978 cliCategory: CATEGORY_OTHER,
3979 cliDescription: "Path to the file to pretend that stdin comes from."
3983 category: CATEGORY_SPECIAL,
3986 description: "Insert @format pragma into file's first docblock comment.",
3987 cliCategory: CATEGORY_OTHER
3991 category: CATEGORY_GLOBAL,
4000 description: "Which parser to use.",
4001 exception: function exception(value) {
4002 return typeof value === "string" || typeof value === "function";
4009 description: "JavaScript",
4010 deprecated: "1.16.0",
4015 description: "JavaScript"
4017 value: "babel-flow",
4021 value: "typescript",
4023 description: "TypeScript"
4031 description: "CSS/Less/SCSS",
4032 deprecated: "1.7.1",
4049 description: "JSON5"
4051 value: "json-stringify",
4053 description: "JSON.stringify"
4057 description: "GraphQL"
4061 description: "Markdown"
4077 description: "Handlebars"
4085 description: "Angular"
4089 description: "Lightning Web Components"
4099 category: CATEGORY_GLOBAL,
4100 description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.",
4101 exception: function exception(value) {
4102 return typeof value === "string" || typeof value === "object";
4105 cliCategory: CATEGORY_CONFIG
4114 category: CATEGORY_GLOBAL,
4115 description: dedent_1`
4116 Custom directory that contains prettier plugins in node_modules subdirectory.
4117 Overrides default behavior when plugins are searched relatively to the location of Prettier.
4118 Multiple values are accepted.
4120 exception: function exception(value) {
4121 return typeof value === "string" || typeof value === "object";
4123 cliName: "plugin-search-dir",
4124 cliCategory: CATEGORY_CONFIG
4128 category: CATEGORY_GLOBAL,
4131 description: "The line length where Prettier will try wrap.",
4140 category: CATEGORY_SPECIAL,
4148 description: dedent_1`
4149 Format code ending at a given character offset (exclusive).
4150 The range will extend forwards to the end of the selected statement.
4151 This option cannot be used with --cursor-offset.
4153 cliCategory: CATEGORY_EDITOR
4157 category: CATEGORY_SPECIAL,
4165 description: dedent_1`
4166 Format code starting at a given character offset.
4167 The range will extend backwards to the start of the first line containing the selected statement.
4168 This option cannot be used with --cursor-offset.
4170 cliCategory: CATEGORY_EDITOR
4174 category: CATEGORY_SPECIAL,
4177 description: dedent_1`
4178 Require either '@prettier' or '@format' to be present in the file's first docblock comment
4179 in order for it to be formatted.
4181 cliCategory: CATEGORY_OTHER
4185 category: CATEGORY_GLOBAL,
4187 description: "Number of spaces per indentation level.",
4196 category: CATEGORY_GLOBAL,
4205 deprecated: "0.0.10",
4206 description: "Use flow parser.",
4211 cliName: "flow-parser"
4215 category: CATEGORY_GLOBAL,
4218 description: "Indent with tabs instead of spaces."
4232 var require$$0 = getCjsExportFromNamespace(_package$1);
4234 var currentVersion = require$$0.version;
4235 var coreOptions$1 = coreOptions.options;
4237 function getSupportInfo(version, opts) {
4238 opts = Object.assign({
4240 showUnreleased: false,
4241 showDeprecated: false,
4246 // pre-release version is smaller than the normal version in semver,
4247 // we need to treat it as the normal one so as to test new features.
4248 version = currentVersion.split("-", 1)[0];
4251 var plugins = opts.plugins;
4252 var options = arrayify(Object.assign(plugins.reduce(function (currentOptions, plugin) {
4253 return Object.assign(currentOptions, plugin.options);
4254 }, {}), coreOptions$1), "name").sort(function (a, b) {
4255 return a.name === b.name ? 0 : a.name < b.name ? -1 : 1;
4256 }).filter(filterSince).filter(filterDeprecated).map(mapDeprecated).map(mapInternal).map(function (option) {
4257 var newOption = Object.assign({}, option);
4259 if (Array.isArray(newOption.default)) {
4260 newOption.default = newOption.default.length === 1 ? newOption.default[0].value : newOption.default.filter(filterSince).sort(function (info1, info2) {
4261 return semver.compare(info2.since, info1.since);
4265 if (Array.isArray(newOption.choices)) {
4266 newOption.choices = newOption.choices.filter(filterSince).filter(filterDeprecated).map(mapDeprecated);
4270 }).map(function (option) {
4271 var filteredPlugins = plugins.filter(function (plugin) {
4272 return plugin.defaultOptions && plugin.defaultOptions[option.name] !== undefined;
4274 var pluginDefaults = filteredPlugins.reduce(function (reduced, plugin) {
4275 reduced[plugin.name] = plugin.defaultOptions[option.name];
4278 return Object.assign(option, {
4282 var usePostCssParser = semver.lt(version, "1.7.1");
4283 var useBabylonParser = semver.lt(version, "1.16.0");
4284 var languages = plugins.reduce(function (all, plugin) {
4285 return all.concat(plugin.languages || []);
4286 }, []).filter(filterSince).map(function (language) {
4287 // Prevent breaking changes
4288 if (language.name === "Markdown") {
4289 return Object.assign({}, language, {
4290 parsers: ["markdown"]
4294 if (language.name === "TypeScript") {
4295 return Object.assign({}, language, {
4296 parsers: ["typescript"]
4298 } // "babylon" was renamed to "babel" in 1.16.0
4301 if (useBabylonParser && language.parsers.indexOf("babel") !== -1) {
4302 return Object.assign({}, language, {
4303 parsers: language.parsers.map(function (parser) {
4304 return parser === "babel" ? "babylon" : parser;
4309 if (usePostCssParser && (language.name === "CSS" || language.group === "CSS")) {
4310 return Object.assign({}, language, {
4311 parsers: ["postcss"]
4322 function filterSince(object) {
4323 return opts.showUnreleased || !("since" in object) || object.since && semver.gte(version, object.since);
4326 function filterDeprecated(object) {
4327 return opts.showDeprecated || !("deprecated" in object) || object.deprecated && semver.lt(version, object.deprecated);
4330 function mapDeprecated(object) {
4331 if (!object.deprecated || opts.showDeprecated) {
4335 var newObject = Object.assign({}, object);
4336 delete newObject.deprecated;
4337 delete newObject.redirect;
4341 function mapInternal(object) {
4342 if (opts.showInternal) {
4346 var newObject = Object.assign({}, object);
4347 delete newObject.cliName;
4348 delete newObject.cliCategory;
4349 delete newObject.cliDescription;
4358 /*! *****************************************************************************
\r
4359 Copyright (c) Microsoft Corporation. All rights reserved.
\r
4360 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
\r
4361 this file except in compliance with the License. You may obtain a copy of the
\r
4362 License at http://www.apache.org/licenses/LICENSE-2.0
\r
4364 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
\r
4365 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
\r
4366 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
\r
4367 MERCHANTABLITY OR NON-INFRINGEMENT.
\r
4369 See the Apache Version 2.0 License for specific language governing permissions
\r
4370 and limitations under the License.
\r
4371 ***************************************************************************** */
4373 /* global Reflect, Promise */
4374 var _extendStatics = function extendStatics(d, b) {
4375 _extendStatics = Object.setPrototypeOf || {
4377 } instanceof Array && function (d, b) {
4379 } || function (d, b) {
4381 if (b.hasOwnProperty(p)) d[p] = b[p];
4385 return _extendStatics(d, b);
4388 function __extends(d, b) {
4389 _extendStatics(d, b);
4392 this.constructor = d;
4395 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
4398 var _assign = function __assign() {
4399 _assign = Object.assign || function __assign(t) {
4400 for (var s, i = 1, n = arguments.length; i < n; i++) {
4404 if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
4411 return _assign.apply(this, arguments);
4413 function __rest(s, e) {
4417 if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
4420 if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
4421 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
4425 function __decorate(decorators, target, key, desc) {
4426 var c = arguments.length,
4427 r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
4429 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--) {
4430 if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
4432 return c > 3 && r && Object.defineProperty(target, key, r), r;
4434 function __param(paramIndex, decorator) {
4435 return function (target, key) {
4436 decorator(target, key, paramIndex);
4439 function __metadata(metadataKey, metadataValue) {
4440 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
4442 function __awaiter(thisArg, _arguments, P, generator) {
4443 return new (P || (P = Promise))(function (resolve, reject) {
4444 function fulfilled(value) {
4446 step(generator.next(value));
4452 function rejected(value) {
4454 step(generator["throw"](value));
4460 function step(result) {
4461 result.done ? resolve(result.value) : new P(function (resolve) {
4462 resolve(result.value);
4463 }).then(fulfilled, rejected);
4466 step((generator = generator.apply(thisArg, _arguments || [])).next());
4469 function __generator(thisArg, body) {
4472 sent: function sent() {
4473 if (t[0] & 1) throw t[1];
4487 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
4492 return function (v) {
4493 return step([n, v]);
4498 if (f) throw new TypeError("Generator is already executing.");
4502 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;
4503 if (y = 0, t) op = [op[0] & 2, t.value];
4532 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
4537 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
4542 if (op[0] === 6 && _.label < t[1]) {
4548 if (t && _.label < t[2]) {
4556 if (t[2]) _.ops.pop();
4563 op = body.call(thisArg, _);
4572 if (op[0] & 5) throw op[1];
4574 value: op[0] ? op[1] : void 0,
4579 function __exportStar(m, exports) {
4581 if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4584 function __values(o) {
4585 var m = typeof Symbol === "function" && o[Symbol.iterator],
4587 if (m) return m.call(o);
4589 next: function next() {
4590 if (o && i >= o.length) o = void 0;
4598 function __read(o, n) {
4599 var m = typeof Symbol === "function" && o[Symbol.iterator];
4607 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) {
4616 if (r && !r.done && (m = i["return"])) m.call(i);
4618 if (e) throw e.error;
4624 function __spread() {
4625 for (var ar = [], i = 0; i < arguments.length; i++) {
4626 ar = ar.concat(__read(arguments[i]));
4631 function __spreadArrays() {
4632 for (var s = 0, i = 0, il = arguments.length; i < il; i++) {
4633 s += arguments[i].length;
4636 for (var r = Array(s), k = 0, i = 0; i < il; i++) {
4637 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) {
4644 function __await(v) {
4645 return this instanceof __await ? (this.v = v, this) : new __await(v);
4647 function __asyncGenerator(thisArg, _arguments, generator) {
4648 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4649 var g = generator.apply(thisArg, _arguments || []),
4652 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
4657 if (g[n]) i[n] = function (v) {
4658 return new Promise(function (a, b) {
4659 q.push([n, v, a, b]) > 1 || resume(n, v);
4664 function resume(n, v) {
4673 r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
4676 function fulfill(value) {
4677 resume("next", value);
4680 function reject(value) {
4681 resume("throw", value);
4684 function settle(f, v) {
4685 if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
4688 function __asyncDelegator(o) {
4690 return i = {}, verb("next"), verb("throw", function (e) {
4692 }), verb("return"), i[Symbol.iterator] = function () {
4696 function verb(n, f) {
4697 i[n] = o[n] ? function (v) {
4699 value: __await(o[n](v)),
4700 done: n === "return"
4705 function __asyncValues(o) {
4706 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4707 var m = o[Symbol.asyncIterator],
4709 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 () {
4714 i[n] = o[n] && function (v) {
4715 return new Promise(function (resolve, reject) {
4716 v = o[n](v), settle(resolve, reject, v.done, v.value);
4721 function settle(resolve, reject, d, v) {
4722 Promise.resolve(v).then(function (v) {
4730 function __makeTemplateObject(cooked, raw) {
4731 if (Object.defineProperty) {
4732 Object.defineProperty(cooked, "raw", {
4741 function __importStar(mod) {
4742 if (mod && mod.__esModule) return mod;
4744 if (mod != null) for (var k in mod) {
4745 if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
4747 result.default = mod;
4750 function __importDefault(mod) {
4751 return mod && mod.__esModule ? mod : {
4756 var tslib_es6 = /*#__PURE__*/Object.freeze({
4758 __extends: __extends,
4759 get __assign () { return _assign; },
4761 __decorate: __decorate,
4763 __metadata: __metadata,
4764 __awaiter: __awaiter,
4765 __generator: __generator,
4766 __exportStar: __exportStar,
4770 __spreadArrays: __spreadArrays,
4772 __asyncGenerator: __asyncGenerator,
4773 __asyncDelegator: __asyncDelegator,
4774 __asyncValues: __asyncValues,
4775 __makeTemplateObject: __makeTemplateObject,
4776 __importStar: __importStar,
4777 __importDefault: __importDefault
4780 var api = createCommonjsModule(function (module, exports) {
4782 Object.defineProperty(exports, "__esModule", {
4785 exports.apiDescriptor = {
4786 key: function key(_key) {
4787 return /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(_key) ? _key : JSON.stringify(_key);
4791 if (value === null || typeof value !== 'object') {
4792 return JSON.stringify(value);
4795 if (Array.isArray(value)) {
4796 return `[${value.map(function (subValue) {
4797 return exports.apiDescriptor.value(subValue);
4801 var keys = Object.keys(value);
4802 return keys.length === 0 ? '{}' : `{ ${keys.map(function (key) {
4803 return `${exports.apiDescriptor.key(key)}: ${exports.apiDescriptor.value(value[key])}`;
4807 pair: function pair(_ref) {
4810 return exports.apiDescriptor.value({
4817 var api_1 = api.apiDescriptor;
4819 var tslib_1 = getCjsExportFromNamespace(tslib_es6);
4821 var descriptors = createCommonjsModule(function (module, exports) {
4823 Object.defineProperty(exports, "__esModule", {
4827 tslib_1.__exportStar(api, exports);
4829 unwrapExports(descriptors);
4831 var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
4833 var escapeStringRegexp = function escapeStringRegexp(str) {
4834 if (typeof str !== 'string') {
4835 throw new TypeError('Expected a string');
4838 return str.replace(matchOperatorsRe, '\\$&');
4842 "aliceblue": [240, 248, 255],
4843 "antiquewhite": [250, 235, 215],
4844 "aqua": [0, 255, 255],
4845 "aquamarine": [127, 255, 212],
4846 "azure": [240, 255, 255],
4847 "beige": [245, 245, 220],
4848 "bisque": [255, 228, 196],
4850 "blanchedalmond": [255, 235, 205],
4851 "blue": [0, 0, 255],
4852 "blueviolet": [138, 43, 226],
4853 "brown": [165, 42, 42],
4854 "burlywood": [222, 184, 135],
4855 "cadetblue": [95, 158, 160],
4856 "chartreuse": [127, 255, 0],
4857 "chocolate": [210, 105, 30],
4858 "coral": [255, 127, 80],
4859 "cornflowerblue": [100, 149, 237],
4860 "cornsilk": [255, 248, 220],
4861 "crimson": [220, 20, 60],
4862 "cyan": [0, 255, 255],
4863 "darkblue": [0, 0, 139],
4864 "darkcyan": [0, 139, 139],
4865 "darkgoldenrod": [184, 134, 11],
4866 "darkgray": [169, 169, 169],
4867 "darkgreen": [0, 100, 0],
4868 "darkgrey": [169, 169, 169],
4869 "darkkhaki": [189, 183, 107],
4870 "darkmagenta": [139, 0, 139],
4871 "darkolivegreen": [85, 107, 47],
4872 "darkorange": [255, 140, 0],
4873 "darkorchid": [153, 50, 204],
4874 "darkred": [139, 0, 0],
4875 "darksalmon": [233, 150, 122],
4876 "darkseagreen": [143, 188, 143],
4877 "darkslateblue": [72, 61, 139],
4878 "darkslategray": [47, 79, 79],
4879 "darkslategrey": [47, 79, 79],
4880 "darkturquoise": [0, 206, 209],
4881 "darkviolet": [148, 0, 211],
4882 "deeppink": [255, 20, 147],
4883 "deepskyblue": [0, 191, 255],
4884 "dimgray": [105, 105, 105],
4885 "dimgrey": [105, 105, 105],
4886 "dodgerblue": [30, 144, 255],
4887 "firebrick": [178, 34, 34],
4888 "floralwhite": [255, 250, 240],
4889 "forestgreen": [34, 139, 34],
4890 "fuchsia": [255, 0, 255],
4891 "gainsboro": [220, 220, 220],
4892 "ghostwhite": [248, 248, 255],
4893 "gold": [255, 215, 0],
4894 "goldenrod": [218, 165, 32],
4895 "gray": [128, 128, 128],
4896 "green": [0, 128, 0],
4897 "greenyellow": [173, 255, 47],
4898 "grey": [128, 128, 128],
4899 "honeydew": [240, 255, 240],
4900 "hotpink": [255, 105, 180],
4901 "indianred": [205, 92, 92],
4902 "indigo": [75, 0, 130],
4903 "ivory": [255, 255, 240],
4904 "khaki": [240, 230, 140],
4905 "lavender": [230, 230, 250],
4906 "lavenderblush": [255, 240, 245],
4907 "lawngreen": [124, 252, 0],
4908 "lemonchiffon": [255, 250, 205],
4909 "lightblue": [173, 216, 230],
4910 "lightcoral": [240, 128, 128],
4911 "lightcyan": [224, 255, 255],
4912 "lightgoldenrodyellow": [250, 250, 210],
4913 "lightgray": [211, 211, 211],
4914 "lightgreen": [144, 238, 144],
4915 "lightgrey": [211, 211, 211],
4916 "lightpink": [255, 182, 193],
4917 "lightsalmon": [255, 160, 122],
4918 "lightseagreen": [32, 178, 170],
4919 "lightskyblue": [135, 206, 250],
4920 "lightslategray": [119, 136, 153],
4921 "lightslategrey": [119, 136, 153],
4922 "lightsteelblue": [176, 196, 222],
4923 "lightyellow": [255, 255, 224],
4924 "lime": [0, 255, 0],
4925 "limegreen": [50, 205, 50],
4926 "linen": [250, 240, 230],
4927 "magenta": [255, 0, 255],
4928 "maroon": [128, 0, 0],
4929 "mediumaquamarine": [102, 205, 170],
4930 "mediumblue": [0, 0, 205],
4931 "mediumorchid": [186, 85, 211],
4932 "mediumpurple": [147, 112, 219],
4933 "mediumseagreen": [60, 179, 113],
4934 "mediumslateblue": [123, 104, 238],
4935 "mediumspringgreen": [0, 250, 154],
4936 "mediumturquoise": [72, 209, 204],
4937 "mediumvioletred": [199, 21, 133],
4938 "midnightblue": [25, 25, 112],
4939 "mintcream": [245, 255, 250],
4940 "mistyrose": [255, 228, 225],
4941 "moccasin": [255, 228, 181],
4942 "navajowhite": [255, 222, 173],
4943 "navy": [0, 0, 128],
4944 "oldlace": [253, 245, 230],
4945 "olive": [128, 128, 0],
4946 "olivedrab": [107, 142, 35],
4947 "orange": [255, 165, 0],
4948 "orangered": [255, 69, 0],
4949 "orchid": [218, 112, 214],
4950 "palegoldenrod": [238, 232, 170],
4951 "palegreen": [152, 251, 152],
4952 "paleturquoise": [175, 238, 238],
4953 "palevioletred": [219, 112, 147],
4954 "papayawhip": [255, 239, 213],
4955 "peachpuff": [255, 218, 185],
4956 "peru": [205, 133, 63],
4957 "pink": [255, 192, 203],
4958 "plum": [221, 160, 221],
4959 "powderblue": [176, 224, 230],
4960 "purple": [128, 0, 128],
4961 "rebeccapurple": [102, 51, 153],
4963 "rosybrown": [188, 143, 143],
4964 "royalblue": [65, 105, 225],
4965 "saddlebrown": [139, 69, 19],
4966 "salmon": [250, 128, 114],
4967 "sandybrown": [244, 164, 96],
4968 "seagreen": [46, 139, 87],
4969 "seashell": [255, 245, 238],
4970 "sienna": [160, 82, 45],
4971 "silver": [192, 192, 192],
4972 "skyblue": [135, 206, 235],
4973 "slateblue": [106, 90, 205],
4974 "slategray": [112, 128, 144],
4975 "slategrey": [112, 128, 144],
4976 "snow": [255, 250, 250],
4977 "springgreen": [0, 255, 127],
4978 "steelblue": [70, 130, 180],
4979 "tan": [210, 180, 140],
4980 "teal": [0, 128, 128],
4981 "thistle": [216, 191, 216],
4982 "tomato": [255, 99, 71],
4983 "turquoise": [64, 224, 208],
4984 "violet": [238, 130, 238],
4985 "wheat": [245, 222, 179],
4986 "white": [255, 255, 255],
4987 "whitesmoke": [245, 245, 245],
4988 "yellow": [255, 255, 0],
4989 "yellowgreen": [154, 205, 50]
4992 var conversions = createCommonjsModule(function (module) {
4994 // NOTE: conversions should only return primitive values (i.e. arrays, or
4995 // values that give correct `typeof` results).
4996 // do not use box values types (i.e. Number(), String(), etc.)
4997 var reverseKeywords = {};
4999 for (var key in colorName) {
5000 if (colorName.hasOwnProperty(key)) {
5001 reverseKeywords[colorName[key]] = key;
5005 var convert = module.exports = {
5056 labels: ['h', 'c', 'g']
5060 labels: ['r16', 'g16', 'b16']
5066 }; // hide .channels and .labels properties
5068 for (var model in convert) {
5069 if (convert.hasOwnProperty(model)) {
5070 if (!('channels' in convert[model])) {
5071 throw new Error('missing channels property: ' + model);
5074 if (!('labels' in convert[model])) {
5075 throw new Error('missing channel labels property: ' + model);
5078 if (convert[model].labels.length !== convert[model].channels) {
5079 throw new Error('channel and label counts mismatch: ' + model);
5082 var channels = convert[model].channels;
5083 var labels = convert[model].labels;
5084 delete convert[model].channels;
5085 delete convert[model].labels;
5086 Object.defineProperty(convert[model], 'channels', {
5089 Object.defineProperty(convert[model], 'labels', {
5095 convert.rgb.hsl = function (rgb) {
5096 var r = rgb[0] / 255;
5097 var g = rgb[1] / 255;
5098 var b = rgb[2] / 255;
5099 var min = Math.min(r, g, b);
5100 var max = Math.max(r, g, b);
5101 var delta = max - min;
5108 } else if (r === max) {
5109 h = (g - b) / delta;
5110 } else if (g === max) {
5111 h = 2 + (b - r) / delta;
5112 } else if (b === max) {
5113 h = 4 + (r - g) / delta;
5116 h = Math.min(h * 60, 360);
5122 l = (min + max) / 2;
5126 } else if (l <= 0.5) {
5127 s = delta / (max + min);
5129 s = delta / (2 - max - min);
5132 return [h, s * 100, l * 100];
5135 convert.rgb.hsv = function (rgb) {
5139 var min = Math.min(r, g, b);
5140 var max = Math.max(r, g, b);
5141 var delta = max - min;
5149 s = delta / max * 1000 / 10;
5154 } else if (r === max) {
5155 h = (g - b) / delta;
5156 } else if (g === max) {
5157 h = 2 + (b - r) / delta;
5158 } else if (b === max) {
5159 h = 4 + (r - g) / delta;
5162 h = Math.min(h * 60, 360);
5168 v = max / 255 * 1000 / 10;
5172 convert.rgb.hwb = function (rgb) {
5176 var h = convert.rgb.hsl(rgb)[0];
5177 var w = 1 / 255 * Math.min(r, Math.min(g, b));
5178 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
5179 return [h, w * 100, b * 100];
5182 convert.rgb.cmyk = function (rgb) {
5183 var r = rgb[0] / 255;
5184 var g = rgb[1] / 255;
5185 var b = rgb[2] / 255;
5190 k = Math.min(1 - r, 1 - g, 1 - b);
5191 c = (1 - r - k) / (1 - k) || 0;
5192 m = (1 - g - k) / (1 - k) || 0;
5193 y = (1 - b - k) / (1 - k) || 0;
5194 return [c * 100, m * 100, y * 100, k * 100];
5197 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
5201 function comparativeDistance(x, y) {
5202 return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
5205 convert.rgb.keyword = function (rgb) {
5206 var reversed = reverseKeywords[rgb];
5212 var currentClosestDistance = Infinity;
5213 var currentClosestKeyword;
5215 for (var keyword in colorName) {
5216 if (colorName.hasOwnProperty(keyword)) {
5217 var value = colorName[keyword]; // Compute comparative distance
5219 var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
5221 if (distance < currentClosestDistance) {
5222 currentClosestDistance = distance;
5223 currentClosestKeyword = keyword;
5228 return currentClosestKeyword;
5231 convert.keyword.rgb = function (keyword) {
5232 return colorName[keyword];
5235 convert.rgb.xyz = function (rgb) {
5236 var r = rgb[0] / 255;
5237 var g = rgb[1] / 255;
5238 var b = rgb[2] / 255; // assume sRGB
5240 r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
5241 g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
5242 b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
5243 var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
5244 var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
5245 var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
5246 return [x * 100, y * 100, z * 100];
5249 convert.rgb.lab = function (rgb) {
5250 var xyz = convert.rgb.xyz(rgb);
5260 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
5261 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
5262 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
5269 convert.hsl.rgb = function (hsl) {
5270 var h = hsl[0] / 360;
5271 var s = hsl[1] / 100;
5272 var l = hsl[2] / 100;
5281 return [val, val, val];
5293 for (var i = 0; i < 3; i++) {
5294 t3 = h + 1 / 3 * -(i - 1);
5305 val = t1 + (t2 - t1) * 6 * t3;
5306 } else if (2 * t3 < 1) {
5308 } else if (3 * t3 < 2) {
5309 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
5320 convert.hsl.hsv = function (hsl) {
5322 var s = hsl[1] / 100;
5323 var l = hsl[2] / 100;
5325 var lmin = Math.max(l, 0.01);
5329 s *= l <= 1 ? l : 2 - l;
5330 smin *= lmin <= 1 ? lmin : 2 - lmin;
5332 sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
5333 return [h, sv * 100, v * 100];
5336 convert.hsv.rgb = function (hsv) {
5337 var h = hsv[0] / 60;
5338 var s = hsv[1] / 100;
5339 var v = hsv[2] / 100;
5340 var hi = Math.floor(h) % 6;
5341 var f = h - Math.floor(h);
5342 var p = 255 * v * (1 - s);
5343 var q = 255 * v * (1 - s * f);
5344 var t = 255 * v * (1 - s * (1 - f));
5368 convert.hsv.hsl = function (hsv) {
5370 var s = hsv[1] / 100;
5371 var v = hsv[2] / 100;
5372 var vmin = Math.max(v, 0.01);
5377 lmin = (2 - s) * vmin;
5379 sl /= lmin <= 1 ? lmin : 2 - lmin;
5382 return [h, sl * 100, l * 100];
5383 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
5386 convert.hwb.rgb = function (hwb) {
5387 var h = hwb[0] / 360;
5388 var wh = hwb[1] / 100;
5389 var bl = hwb[2] / 100;
5390 var ratio = wh + bl;
5394 var n; // wh + bl cant be > 1
5401 i = Math.floor(6 * h);
5405 if ((i & 0x01) !== 0) {
5409 n = wh + f * (v - wh); // linear interpolation
5455 return [r * 255, g * 255, b * 255];
5458 convert.cmyk.rgb = function (cmyk) {
5459 var c = cmyk[0] / 100;
5460 var m = cmyk[1] / 100;
5461 var y = cmyk[2] / 100;
5462 var k = cmyk[3] / 100;
5466 r = 1 - Math.min(1, c * (1 - k) + k);
5467 g = 1 - Math.min(1, m * (1 - k) + k);
5468 b = 1 - Math.min(1, y * (1 - k) + k);
5469 return [r * 255, g * 255, b * 255];
5472 convert.xyz.rgb = function (xyz) {
5473 var x = xyz[0] / 100;
5474 var y = xyz[1] / 100;
5475 var z = xyz[2] / 100;
5479 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
5480 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
5481 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
5483 r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
5484 g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
5485 b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
5486 r = Math.min(Math.max(0, r), 1);
5487 g = Math.min(Math.max(0, g), 1);
5488 b = Math.min(Math.max(0, b), 1);
5489 return [r * 255, g * 255, b * 255];
5492 convert.xyz.lab = function (xyz) {
5502 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
5503 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
5504 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
5511 convert.lab.xyz = function (lab) {
5521 var y2 = Math.pow(y, 3);
5522 var x2 = Math.pow(x, 3);
5523 var z2 = Math.pow(z, 3);
5524 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
5525 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
5526 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
5533 convert.lab.lch = function (lab) {
5540 hr = Math.atan2(b, a);
5541 h = hr * 360 / 2 / Math.PI;
5547 c = Math.sqrt(a * a + b * b);
5551 convert.lch.lab = function (lch) {
5558 hr = h / 360 * 2 * Math.PI;
5559 a = c * Math.cos(hr);
5560 b = c * Math.sin(hr);
5564 convert.rgb.ansi16 = function (args) {
5568 var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
5570 value = Math.round(value / 50);
5576 var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
5585 convert.hsv.ansi16 = function (args) {
5586 // optimization here; we already know the value and don't need to get
5587 // it converted for us.
5588 return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
5591 convert.rgb.ansi256 = function (args) {
5594 var b = args[2]; // we use the extended greyscale palette here, with the exception of
5595 // black and white. normal palette only has 4 greyscale shades.
5597 if (r === g && g === b) {
5606 return Math.round((r - 8) / 247 * 24) + 232;
5609 var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
5613 convert.ansi16.rgb = function (args) {
5614 var color = args % 10; // handle greyscale
5616 if (color === 0 || color === 7) {
5621 color = color / 10.5 * 255;
5622 return [color, color, color];
5625 var mult = (~~(args > 50) + 1) * 0.5;
5626 var r = (color & 1) * mult * 255;
5627 var g = (color >> 1 & 1) * mult * 255;
5628 var b = (color >> 2 & 1) * mult * 255;
5632 convert.ansi256.rgb = function (args) {
5635 var c = (args - 232) * 10 + 8;
5641 var r = Math.floor(args / 36) / 5 * 255;
5642 var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
5643 var b = rem % 6 / 5 * 255;
5647 convert.rgb.hex = function (args) {
5648 var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
5649 var string = integer.toString(16).toUpperCase();
5650 return '000000'.substring(string.length) + string;
5653 convert.hex.rgb = function (args) {
5654 var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
5660 var colorString = match[0];
5662 if (match[0].length === 3) {
5663 colorString = colorString.split('').map(function (char) {
5668 var integer = parseInt(colorString, 16);
5669 var r = integer >> 16 & 0xFF;
5670 var g = integer >> 8 & 0xFF;
5671 var b = integer & 0xFF;
5675 convert.rgb.hcg = function (rgb) {
5676 var r = rgb[0] / 255;
5677 var g = rgb[1] / 255;
5678 var b = rgb[2] / 255;
5679 var max = Math.max(Math.max(r, g), b);
5680 var min = Math.min(Math.min(r, g), b);
5681 var chroma = max - min;
5686 grayscale = min / (1 - chroma);
5693 } else if (max === r) {
5694 hue = (g - b) / chroma % 6;
5695 } else if (max === g) {
5696 hue = 2 + (b - r) / chroma;
5698 hue = 4 + (r - g) / chroma + 4;
5703 return [hue * 360, chroma * 100, grayscale * 100];
5706 convert.hsl.hcg = function (hsl) {
5707 var s = hsl[1] / 100;
5708 var l = hsl[2] / 100;
5715 c = 2.0 * s * (1.0 - l);
5719 f = (l - 0.5 * c) / (1.0 - c);
5722 return [hsl[0], c * 100, f * 100];
5725 convert.hsv.hcg = function (hsv) {
5726 var s = hsv[1] / 100;
5727 var v = hsv[2] / 100;
5732 f = (v - c) / (1 - c);
5735 return [hsv[0], c * 100, f * 100];
5738 convert.hcg.rgb = function (hcg) {
5739 var h = hcg[0] / 360;
5740 var c = hcg[1] / 100;
5741 var g = hcg[2] / 100;
5744 return [g * 255, g * 255, g * 255];
5747 var pure = [0, 0, 0];
5753 switch (Math.floor(hi)) {
5791 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
5794 convert.hcg.hsv = function (hcg) {
5795 var c = hcg[1] / 100;
5796 var g = hcg[2] / 100;
5797 var v = c + g * (1.0 - c);
5804 return [hcg[0], f * 100, v * 100];
5807 convert.hcg.hsl = function (hcg) {
5808 var c = hcg[1] / 100;
5809 var g = hcg[2] / 100;
5810 var l = g * (1.0 - c) + 0.5 * c;
5813 if (l > 0.0 && l < 0.5) {
5815 } else if (l >= 0.5 && l < 1.0) {
5816 s = c / (2 * (1 - l));
5819 return [hcg[0], s * 100, l * 100];
5822 convert.hcg.hwb = function (hcg) {
5823 var c = hcg[1] / 100;
5824 var g = hcg[2] / 100;
5825 var v = c + g * (1.0 - c);
5826 return [hcg[0], (v - c) * 100, (1 - v) * 100];
5829 convert.hwb.hcg = function (hwb) {
5830 var w = hwb[1] / 100;
5831 var b = hwb[2] / 100;
5837 g = (v - c) / (1 - c);
5840 return [hwb[0], c * 100, g * 100];
5843 convert.apple.rgb = function (apple) {
5844 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
5847 convert.rgb.apple = function (rgb) {
5848 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
5851 convert.gray.rgb = function (args) {
5852 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
5855 convert.gray.hsl = convert.gray.hsv = function (args) {
5856 return [0, 0, args[0]];
5859 convert.gray.hwb = function (gray) {
5860 return [0, 100, gray[0]];
5863 convert.gray.cmyk = function (gray) {
5864 return [0, 0, 0, gray[0]];
5867 convert.gray.lab = function (gray) {
5868 return [gray[0], 0, 0];
5871 convert.gray.hex = function (gray) {
5872 var val = Math.round(gray[0] / 100 * 255) & 0xFF;
5873 var integer = (val << 16) + (val << 8) + val;
5874 var string = integer.toString(16).toUpperCase();
5875 return '000000'.substring(string.length) + string;
5878 convert.rgb.gray = function (rgb) {
5879 var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
5880 return [val / 255 * 100];
5883 var conversions_1 = conversions.rgb;
5884 var conversions_2 = conversions.hsl;
5885 var conversions_3 = conversions.hsv;
5886 var conversions_4 = conversions.hwb;
5887 var conversions_5 = conversions.cmyk;
5888 var conversions_6 = conversions.xyz;
5889 var conversions_7 = conversions.lab;
5890 var conversions_8 = conversions.lch;
5891 var conversions_9 = conversions.hex;
5892 var conversions_10 = conversions.keyword;
5893 var conversions_11 = conversions.ansi16;
5894 var conversions_12 = conversions.ansi256;
5895 var conversions_13 = conversions.hcg;
5896 var conversions_14 = conversions.apple;
5897 var conversions_15 = conversions.gray;
5900 this function routes a model to all other models.
5902 all functions that are routed have a property `.conversion` attached
5903 to the returned synthetic function. This property is an array
5904 of strings, each with the steps in between the 'from' and 'to'
5905 color models (inclusive).
5907 conversions that are not possible simply are not included.
5909 // https://jsperf.com/object-keys-vs-for-in-with-closure/3
5911 var models = Object.keys(conversions);
5913 function buildGraph() {
5916 for (var len = models.length, i = 0; i < len; i++) {
5917 graph[models[i]] = {
5918 // http://jsperf.com/1-vs-infinity
5919 // micro-opt, but this is simple.
5926 } // https://en.wikipedia.org/wiki/Breadth-first_search
5929 function deriveBFS(fromModel) {
5930 var graph = buildGraph();
5931 var queue = [fromModel]; // unshift -> queue -> pop
5933 graph[fromModel].distance = 0;
5935 while (queue.length) {
5936 var current = queue.pop();
5937 var adjacents = Object.keys(conversions[current]);
5939 for (var len = adjacents.length, i = 0; i < len; i++) {
5940 var adjacent = adjacents[i];
5941 var node = graph[adjacent];
5943 if (node.distance === -1) {
5944 node.distance = graph[current].distance + 1;
5945 node.parent = current;
5946 queue.unshift(adjacent);
5954 function link(from, to) {
5955 return function (args) {
5956 return to(from(args));
5960 function wrapConversion(toModel, graph) {
5961 var path = [graph[toModel].parent, toModel];
5962 var fn = conversions[graph[toModel].parent][toModel];
5963 var cur = graph[toModel].parent;
5965 while (graph[cur].parent) {
5966 path.unshift(graph[cur].parent);
5967 fn = link(conversions[graph[cur].parent][cur], fn);
5968 cur = graph[cur].parent;
5971 fn.conversion = path;
5975 var route = function route(fromModel) {
5976 var graph = deriveBFS(fromModel);
5977 var conversion = {};
5978 var models = Object.keys(graph);
5980 for (var len = models.length, i = 0; i < len; i++) {
5981 var toModel = models[i];
5982 var node = graph[toModel];
5984 if (node.parent === null) {
5985 // no possible conversion, or this node is the source model.
5989 conversion[toModel] = wrapConversion(toModel, graph);
5996 var models$1 = Object.keys(conversions);
5998 function wrapRaw(fn) {
5999 var wrappedFn = function wrappedFn(args) {
6000 if (args === undefined || args === null) {
6004 if (arguments.length > 1) {
6005 args = Array.prototype.slice.call(arguments);
6009 }; // preserve .conversion property if there is one
6012 if ('conversion' in fn) {
6013 wrappedFn.conversion = fn.conversion;
6019 function wrapRounded(fn) {
6020 var wrappedFn = function wrappedFn(args) {
6021 if (args === undefined || args === null) {
6025 if (arguments.length > 1) {
6026 args = Array.prototype.slice.call(arguments);
6029 var result = fn(args); // we're assuming the result is an array here.
6030 // see notice in conversions.js; don't use box types
6031 // in conversion functions.
6033 if (typeof result === 'object') {
6034 for (var len = result.length, i = 0; i < len; i++) {
6035 result[i] = Math.round(result[i]);
6040 }; // preserve .conversion property if there is one
6043 if ('conversion' in fn) {
6044 wrappedFn.conversion = fn.conversion;
6050 models$1.forEach(function (fromModel) {
6051 convert[fromModel] = {};
6052 Object.defineProperty(convert[fromModel], 'channels', {
6053 value: conversions[fromModel].channels
6055 Object.defineProperty(convert[fromModel], 'labels', {
6056 value: conversions[fromModel].labels
6058 var routes = route(fromModel);
6059 var routeModels = Object.keys(routes);
6060 routeModels.forEach(function (toModel) {
6061 var fn = routes[toModel];
6062 convert[fromModel][toModel] = wrapRounded(fn);
6063 convert[fromModel][toModel].raw = wrapRaw(fn);
6066 var colorConvert = convert;
6068 var ansiStyles = createCommonjsModule(function (module) {
6070 var wrapAnsi16 = function wrapAnsi16(fn, offset) {
6071 return function () {
6072 var code = fn.apply(colorConvert, arguments);
6073 return `\u001B[${code + offset}m`;
6077 var wrapAnsi256 = function wrapAnsi256(fn, offset) {
6078 return function () {
6079 var code = fn.apply(colorConvert, arguments);
6080 return `\u001B[${38 + offset};5;${code}m`;
6084 var wrapAnsi16m = function wrapAnsi16m(fn, offset) {
6085 return function () {
6086 var rgb = fn.apply(colorConvert, arguments);
6087 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
6091 function assembleStyles() {
6092 var codes = new Map();
6096 // 21 isn't widely supported and 22 does the same thing
6103 strikethrough: [9, 29]
6116 redBright: [91, 39],
6117 greenBright: [92, 39],
6118 yellowBright: [93, 39],
6119 blueBright: [94, 39],
6120 magentaBright: [95, 39],
6121 cyanBright: [96, 39],
6122 whiteBright: [97, 39]
6130 bgMagenta: [45, 49],
6134 bgBlackBright: [100, 49],
6135 bgRedBright: [101, 49],
6136 bgGreenBright: [102, 49],
6137 bgYellowBright: [103, 49],
6138 bgBlueBright: [104, 49],
6139 bgMagentaBright: [105, 49],
6140 bgCyanBright: [106, 49],
6141 bgWhiteBright: [107, 49]
6145 styles.color.grey = styles.color.gray;
6147 for (var _i = 0, _Object$keys = Object.keys(styles); _i < _Object$keys.length; _i++) {
6148 var groupName = _Object$keys[_i];
6149 var group = styles[groupName];
6151 for (var _i3 = 0, _Object$keys3 = Object.keys(group); _i3 < _Object$keys3.length; _i3++) {
6152 var styleName = _Object$keys3[_i3];
6153 var style = group[styleName];
6154 styles[styleName] = {
6155 open: `\u001B[${style[0]}m`,
6156 close: `\u001B[${style[1]}m`
6158 group[styleName] = styles[styleName];
6159 codes.set(style[0], style[1]);
6162 Object.defineProperty(styles, groupName, {
6166 Object.defineProperty(styles, 'codes', {
6172 var ansi2ansi = function ansi2ansi(n) {
6176 var rgb2rgb = function rgb2rgb(r, g, b) {
6180 styles.color.close = '\u001B[39m';
6181 styles.bgColor.close = '\u001B[49m';
6182 styles.color.ansi = {
6183 ansi: wrapAnsi16(ansi2ansi, 0)
6185 styles.color.ansi256 = {
6186 ansi256: wrapAnsi256(ansi2ansi, 0)
6188 styles.color.ansi16m = {
6189 rgb: wrapAnsi16m(rgb2rgb, 0)
6191 styles.bgColor.ansi = {
6192 ansi: wrapAnsi16(ansi2ansi, 10)
6194 styles.bgColor.ansi256 = {
6195 ansi256: wrapAnsi256(ansi2ansi, 10)
6197 styles.bgColor.ansi16m = {
6198 rgb: wrapAnsi16m(rgb2rgb, 10)
6201 for (var _i2 = 0, _Object$keys2 = Object.keys(colorConvert); _i2 < _Object$keys2.length; _i2++) {
6202 var key = _Object$keys2[_i2];
6204 if (typeof colorConvert[key] !== 'object') {
6208 var suite = colorConvert[key];
6210 if (key === 'ansi16') {
6214 if ('ansi16' in suite) {
6215 styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
6216 styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
6219 if ('ansi256' in suite) {
6220 styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
6221 styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
6224 if ('rgb' in suite) {
6225 styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
6226 styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
6231 } // Make the export immutable
6234 Object.defineProperty(module, 'exports', {
6240 var hasFlag = function hasFlag(flag, argv) {
6241 argv = argv || process.argv;
6242 var prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
6243 var pos = argv.indexOf(prefix + flag);
6244 var terminatorPos = argv.indexOf('--');
6245 return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
6248 var env = process.env;
6251 if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
6253 } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
6257 if ('FORCE_COLOR' in env) {
6258 forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
6261 function translateLevel(level) {
6274 function supportsColor(stream) {
6275 if (forceColor === false) {
6279 if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
6283 if (hasFlag('color=256')) {
6287 if (stream && !stream.isTTY && forceColor !== true) {
6291 var min = forceColor ? 1 : 0;
6293 if (process.platform === 'win32') {
6294 // Node.js 7.5.0 is the first version of Node.js to include a patch to
6295 // libuv that enables 256 color output on Windows. Anything earlier and it
6296 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
6297 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
6298 // release that supports 256 colors. Windows 10 build 14931 is the first release
6299 // that supports 16m/TrueColor.
6300 var osRelease = os$1.release().split('.');
6302 if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
6303 return Number(osRelease[2]) >= 14931 ? 3 : 2;
6310 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function (sign) {
6312 }) || env.CI_NAME === 'codeship') {
6319 if ('TEAMCITY_VERSION' in env) {
6320 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
6323 if (env.COLORTERM === 'truecolor') {
6327 if ('TERM_PROGRAM' in env) {
6328 var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
6330 switch (env.TERM_PROGRAM) {
6332 return version >= 3 ? 3 : 2;
6334 case 'Apple_Terminal':
6340 if (/-256(color)?$/i.test(env.TERM)) {
6344 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
6348 if ('COLORTERM' in env) {
6352 if (env.TERM === 'dumb') {
6359 function getSupportLevel(stream) {
6360 var level = supportsColor(stream);
6361 return translateLevel(level);
6364 var supportsColor_1 = {
6365 supportsColor: getSupportLevel,
6366 stdout: getSupportLevel(process.stdout),
6367 stderr: getSupportLevel(process.stderr)
6370 var TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
6371 var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
6372 var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
6373 var ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
6374 var ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
6376 function unescape(c) {
6377 if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
6378 return String.fromCharCode(parseInt(c.slice(1), 16));
6381 return ESCAPES.get(c) || c;
6384 function parseArguments(name, args) {
6386 var chunks = args.trim().split(/\s*,\s*/g);
6388 var _iteratorNormalCompletion = true;
6389 var _didIteratorError = false;
6390 var _iteratorError = undefined;
6393 for (var _iterator = chunks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
6394 var chunk = _step.value;
6396 if (!isNaN(chunk)) {
6397 results.push(Number(chunk));
6398 } else if (matches = chunk.match(STRING_REGEX)) {
6399 results.push(matches[2].replace(ESCAPE_REGEX, function (m, escape, chr) {
6400 return escape ? unescape(escape) : chr;
6403 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
6407 _didIteratorError = true;
6408 _iteratorError = err;
6411 if (!_iteratorNormalCompletion && _iterator.return != null) {
6415 if (_didIteratorError) {
6416 throw _iteratorError;
6424 function parseStyle(style) {
6425 STYLE_REGEX.lastIndex = 0;
6429 while ((matches = STYLE_REGEX.exec(style)) !== null) {
6430 var name = matches[1];
6433 var args = parseArguments(name, matches[2]);
6434 results.push([name].concat(args));
6436 results.push([name]);
6443 function buildStyle(chalk, styles) {
6445 var _iteratorNormalCompletion2 = true;
6446 var _didIteratorError2 = false;
6447 var _iteratorError2 = undefined;
6450 for (var _iterator2 = styles[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
6451 var layer = _step2.value;
6452 var _iteratorNormalCompletion3 = true;
6453 var _didIteratorError3 = false;
6454 var _iteratorError3 = undefined;
6457 for (var _iterator3 = layer.styles[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
6458 var style = _step3.value;
6459 enabled[style[0]] = layer.inverse ? null : style.slice(1);
6462 _didIteratorError3 = true;
6463 _iteratorError3 = err;
6466 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
6467 _iterator3.return();
6470 if (_didIteratorError3) {
6471 throw _iteratorError3;
6477 _didIteratorError2 = true;
6478 _iteratorError2 = err;
6481 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
6482 _iterator2.return();
6485 if (_didIteratorError2) {
6486 throw _iteratorError2;
6491 var current = chalk;
6493 for (var _i = 0, _Object$keys = Object.keys(enabled); _i < _Object$keys.length; _i++) {
6494 var styleName = _Object$keys[_i];
6496 if (Array.isArray(enabled[styleName])) {
6497 if (!(styleName in current)) {
6498 throw new Error(`Unknown Chalk style: ${styleName}`);
6501 if (enabled[styleName].length > 0) {
6502 current = current[styleName].apply(current, enabled[styleName]);
6504 current = current[styleName];
6512 var templates = function templates(chalk, tmp) {
6515 var chunk = []; // eslint-disable-next-line max-params
6517 tmp.replace(TEMPLATE_REGEX, function (m, escapeChar, inverse, style, close, chr) {
6519 chunk.push(unescape(escapeChar));
6521 var str = chunk.join('');
6523 chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
6526 styles: parseStyle(style)
6529 if (styles.length === 0) {
6530 throw new Error('Found extraneous } in Chalk template literal');
6533 chunks.push(buildStyle(chalk, styles)(chunk.join('')));
6540 chunks.push(chunk.join(''));
6542 if (styles.length > 0) {
6543 var errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
6544 throw new Error(errMsg);
6547 return chunks.join('');
6550 var chalk = createCommonjsModule(function (module) {
6552 var stdoutColor = supportsColor_1.stdout;
6553 var isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
6555 var levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
6557 var skipModels = new Set(['gray']);
6558 var styles = Object.create(null);
6560 function applyOptions(obj, options) {
6561 options = options || {}; // Detect level if not set manually
6563 var scLevel = stdoutColor ? stdoutColor.level : 0;
6564 obj.level = options.level === undefined ? scLevel : options.level;
6565 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
6568 function Chalk(options) {
6569 // We check for this.template here since calling `chalk.constructor()`
6570 // by itself will have a `this` of a previously constructed chalk object
6571 if (!this || !(this instanceof Chalk) || this.template) {
6573 applyOptions(_chalk, options);
6575 _chalk.template = function () {
6576 var args = [].slice.call(arguments);
6577 return chalkTag.apply(null, [_chalk.template].concat(args));
6580 Object.setPrototypeOf(_chalk, Chalk.prototype);
6581 Object.setPrototypeOf(_chalk.template, _chalk);
6582 _chalk.template.constructor = Chalk;
6583 return _chalk.template;
6586 applyOptions(this, options);
6587 } // Use bright blue on Windows as the normal blue color is illegible
6590 if (isSimpleWindowsTerm) {
6591 ansiStyles.blue.open = '\u001B[94m';
6594 var _loop = function _loop() {
6595 var key = _Object$keys[_i];
6596 ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
6599 var codes = ansiStyles[key];
6600 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
6606 for (var _i = 0, _Object$keys = Object.keys(ansiStyles); _i < _Object$keys.length; _i++) {
6612 return build.call(this, this._styles || [], true, 'visible');
6616 ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
6618 var _loop2 = function _loop2() {
6619 var model = _Object$keys2[_i2];
6621 if (skipModels.has(model)) {
6627 var level = this.level;
6628 return function () {
6629 var open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
6632 close: ansiStyles.color.close,
6633 closeRe: ansiStyles.color.closeRe
6635 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
6642 for (var _i2 = 0, _Object$keys2 = Object.keys(ansiStyles.color.ansi); _i2 < _Object$keys2.length; _i2++) {
6643 var _ret = _loop2();
6645 if (_ret === "continue") continue;
6648 ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
6650 var _loop3 = function _loop3() {
6651 var model = _Object$keys3[_i3];
6653 if (skipModels.has(model)) {
6657 var bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
6660 var level = this.level;
6661 return function () {
6662 var open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
6665 close: ansiStyles.bgColor.close,
6666 closeRe: ansiStyles.bgColor.closeRe
6668 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
6675 for (var _i3 = 0, _Object$keys3 = Object.keys(ansiStyles.bgColor.ansi); _i3 < _Object$keys3.length; _i3++) {
6676 var _ret2 = _loop3();
6678 if (_ret2 === "continue") continue;
6681 var proto = Object.defineProperties(function () {}, styles);
6683 function build(_styles, _empty, key) {
6684 var builder = function builder() {
6685 return applyStyle.apply(builder, arguments);
6688 builder._styles = _styles;
6689 builder._empty = _empty;
6691 Object.defineProperty(builder, 'level', {
6703 Object.defineProperty(builder, 'enabled', {
6707 return self.enabled;
6711 self.enabled = enabled;
6714 }); // See below for fix regarding invisible grey/dim combination on Windows
6716 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
6717 // no way to create a function with a different prototype
6719 builder.__proto__ = proto; // eslint-disable-line no-proto
6724 function applyStyle() {
6725 // Support varags, but simply cast to string in case there's only one arg
6726 var args = arguments;
6727 var argsLen = args.length;
6728 var str = String(arguments[0]);
6730 if (argsLen === 0) {
6735 // Don't slice `arguments`, it prevents V8 optimizations
6736 for (var a = 1; a < argsLen; a++) {
6737 str += ' ' + args[a];
6741 if (!this.enabled || this.level <= 0 || !str) {
6742 return this._empty ? '' : str;
6743 } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
6744 // see https://github.com/chalk/chalk/issues/58
6745 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
6748 var originalDim = ansiStyles.dim.open;
6750 if (isSimpleWindowsTerm && this.hasGrey) {
6751 ansiStyles.dim.open = '';
6754 var _iteratorNormalCompletion = true;
6755 var _didIteratorError = false;
6756 var _iteratorError = undefined;
6759 for (var _iterator = this._styles.slice().reverse()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
6760 var code = _step.value;
6761 // Replace any instances already present with a re-opening code
6762 // otherwise only the part of the string until said closing code
6763 // will be colored, and the rest will simply be 'plain'.
6764 str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
6765 // after next line to fix a bleed issue on macOS
6766 // https://github.com/chalk/chalk/pull/92
6768 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
6769 } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
6772 _didIteratorError = true;
6773 _iteratorError = err;
6776 if (!_iteratorNormalCompletion && _iterator.return != null) {
6780 if (_didIteratorError) {
6781 throw _iteratorError;
6786 ansiStyles.dim.open = originalDim;
6790 function chalkTag(chalk, strings) {
6791 if (!Array.isArray(strings)) {
6792 // If chalk() was called by itself or with a string,
6793 // return the string itself as a string.
6794 return [].slice.call(arguments, 1).join(' ');
6797 var args = [].slice.call(arguments, 2);
6798 var parts = [strings.raw[0]];
6800 for (var i = 1; i < strings.length; i++) {
6801 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
6802 parts.push(String(strings.raw[i]));
6805 return templates(chalk, parts.join(''));
6808 Object.defineProperties(Chalk.prototype, styles);
6809 module.exports = Chalk(); // eslint-disable-line new-cap
6811 module.exports.supportsColor = stdoutColor;
6812 module.exports.default = module.exports; // For TypeScript
6814 var chalk_1 = chalk.supportsColor;
6816 var common = createCommonjsModule(function (module, exports) {
6818 Object.defineProperty(exports, "__esModule", {
6822 exports.commonDeprecatedHandler = function (keyOrPair, redirectTo, _ref) {
6823 var descriptor = _ref.descriptor;
6824 var messages = [`${chalk.default.yellow(typeof keyOrPair === 'string' ? descriptor.key(keyOrPair) : descriptor.pair(keyOrPair))} is deprecated`];
6827 messages.push(`we now treat it as ${chalk.default.blue(typeof redirectTo === 'string' ? descriptor.key(redirectTo) : descriptor.pair(redirectTo))}`);
6830 return messages.join('; ') + '.';
6833 unwrapExports(common);
6834 var common_1 = common.commonDeprecatedHandler;
6836 var deprecated = createCommonjsModule(function (module, exports) {
6838 Object.defineProperty(exports, "__esModule", {
6842 tslib_1.__exportStar(common, exports);
6844 unwrapExports(deprecated);
6846 var common$1 = createCommonjsModule(function (module, exports) {
6848 Object.defineProperty(exports, "__esModule", {
6852 exports.commonInvalidHandler = function (key, value, utils) {
6853 return [`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(' ');
6856 unwrapExports(common$1);
6857 var common_1$1 = common$1.commonInvalidHandler;
6859 var invalid = createCommonjsModule(function (module, exports) {
6861 Object.defineProperty(exports, "__esModule", {
6865 tslib_1.__exportStar(common$1, exports);
6867 unwrapExports(invalid);
6869 /* eslint-disable no-nested-ternary */
6872 var charCodeCache = [];
6874 var leven = function leven(a, b) {
6879 var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the
6880 // shortest & which one is the longest
6882 if (a.length > b.length) {
6887 var aLen = a.length;
6888 var bLen = b.length;
6896 } // Performing suffix trimming:
6897 // We can linearly drop suffix common to both strings since they
6898 // don't increase distance at all
6899 // Note: `~-` is the bitwise way to perform a `- 1` operation
6902 while (aLen > 0 && a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen)) {
6909 } // Performing prefix trimming
6910 // We can linearly drop prefix common to both strings since they
6911 // don't increase distance at all
6916 while (start < aLen && a.charCodeAt(start) === b.charCodeAt(start)) {
6935 charCodeCache[start + i] = a.charCodeAt(start + i);
6940 bCharCode = b.charCodeAt(start + j);
6944 for (i = 0; i < aLen; i++) {
6945 tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1;
6947 ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2;
6954 var leven_1 = createCommonjsModule(function (module, exports) {
6956 Object.defineProperty(exports, "__esModule", {
6960 exports.levenUnknownHandler = function (key, value, _ref) {
6961 var descriptor = _ref.descriptor,
6962 logger = _ref.logger,
6963 schemas = _ref.schemas;
6964 var messages = [`Ignored unknown option ${chalk.default.yellow(descriptor.pair({
6968 var suggestion = Object.keys(schemas).sort().find(function (knownKey) {
6969 return leven(key, knownKey) < 3;
6973 messages.push(`Did you mean ${chalk.default.blue(descriptor.key(suggestion))}?`);
6976 logger.warn(messages.join(' '));
6979 unwrapExports(leven_1);
6980 var leven_2 = leven_1.levenUnknownHandler;
6982 var unknown = createCommonjsModule(function (module, exports) {
6984 Object.defineProperty(exports, "__esModule", {
6988 tslib_1.__exportStar(leven_1, exports);
6990 unwrapExports(unknown);
6992 var handlers = createCommonjsModule(function (module, exports) {
6994 Object.defineProperty(exports, "__esModule", {
6998 tslib_1.__exportStar(deprecated, exports);
7000 tslib_1.__exportStar(invalid, exports);
7002 tslib_1.__exportStar(unknown, exports);
7004 unwrapExports(handlers);
7006 var schema = createCommonjsModule(function (module, exports) {
7008 Object.defineProperty(exports, "__esModule", {
7011 var HANDLER_KEYS = ['default', 'expected', 'validate', 'deprecated', 'forward', 'redirect', 'overlap', 'preprocess', 'postprocess'];
7013 function createSchema(SchemaConstructor, parameters) {
7014 var schema = new SchemaConstructor(parameters);
7015 var subSchema = Object.create(schema);
7016 var _iteratorNormalCompletion = true;
7017 var _didIteratorError = false;
7018 var _iteratorError = undefined;
7021 for (var _iterator = HANDLER_KEYS[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
7022 var handlerKey = _step.value;
7024 if (handlerKey in parameters) {
7025 subSchema[handlerKey] = normalizeHandler(parameters[handlerKey], schema, Schema.prototype[handlerKey].length);
7029 _didIteratorError = true;
7030 _iteratorError = err;
7033 if (!_iteratorNormalCompletion && _iterator.return != null) {
7037 if (_didIteratorError) {
7038 throw _iteratorError;
7046 exports.createSchema = createSchema;
7051 function Schema(parameters) {
7052 _classCallCheck(this, Schema);
7054 this.name = parameters.name;
7057 _createClass(Schema, [{
7059 value: function _default(_utils) {
7061 } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
7065 value: function expected(_utils) {
7067 } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
7071 value: function validate(_value, _utils) {
7076 value: function deprecated(_value, _utils) {
7081 value: function forward(_value, _utils) {
7086 value: function redirect(_value, _utils) {
7091 value: function overlap(currentValue, _newValue, _utils) {
7092 return currentValue;
7096 value: function preprocess(value, _utils) {
7101 value: function postprocess(value, _utils) {
7106 value: function create(parameters) {
7107 // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/5863
7108 return createSchema(this, parameters);
7115 exports.Schema = Schema;
7117 function normalizeHandler(handler, superSchema, handlerArgumentsLength) {
7118 return typeof handler === 'function' ? function () {
7119 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
7120 args[_key] = arguments[_key];
7123 return handler.apply(void 0, _toConsumableArray$1(args.slice(0, handlerArgumentsLength - 1)).concat([superSchema], _toConsumableArray$1(args.slice(handlerArgumentsLength - 1))));
7129 unwrapExports(schema);
7130 var schema_1 = schema.createSchema;
7131 var schema_2 = schema.Schema;
7133 var alias = createCommonjsModule(function (module, exports) {
7135 Object.defineProperty(exports, "__esModule", {
7141 function (_schema_1$Schema) {
7142 _inherits(AliasSchema, _schema_1$Schema);
7144 function AliasSchema(parameters) {
7147 _classCallCheck(this, AliasSchema);
7149 _this = _possibleConstructorReturn(this, _getPrototypeOf(AliasSchema).call(this, parameters));
7150 _this._sourceName = parameters.sourceName;
7154 _createClass(AliasSchema, [{
7156 value: function expected(utils) {
7157 return utils.schemas[this._sourceName].expected(utils);
7161 value: function validate(value, utils) {
7162 return utils.schemas[this._sourceName].validate(value, utils);
7166 value: function redirect(_value, _utils) {
7167 return this._sourceName;
7174 exports.AliasSchema = AliasSchema;
7176 unwrapExports(alias);
7177 var alias_1 = alias.AliasSchema;
7179 var any = createCommonjsModule(function (module, exports) {
7181 Object.defineProperty(exports, "__esModule", {
7187 function (_schema_1$Schema) {
7188 _inherits(AnySchema, _schema_1$Schema);
7190 function AnySchema() {
7191 _classCallCheck(this, AnySchema);
7193 return _possibleConstructorReturn(this, _getPrototypeOf(AnySchema).apply(this, arguments));
7196 _createClass(AnySchema, [{
7198 value: function expected() {
7203 value: function validate() {
7211 exports.AnySchema = AnySchema;
7214 var any_1 = any.AnySchema;
7216 var array = createCommonjsModule(function (module, exports) {
7218 Object.defineProperty(exports, "__esModule", {
7224 function (_schema_1$Schema) {
7225 _inherits(ArraySchema, _schema_1$Schema);
7227 function ArraySchema(_a) {
7230 _classCallCheck(this, ArraySchema);
7232 var valueSchema = _a.valueSchema,
7234 name = _a$name === void 0 ? valueSchema.name : _a$name,
7235 handlers = tslib_1.__rest(_a, ["valueSchema", "name"]);
7237 _this = _possibleConstructorReturn(this, _getPrototypeOf(ArraySchema).call(this, Object.assign({}, handlers, {
7240 _this._valueSchema = valueSchema;
7244 _createClass(ArraySchema, [{
7246 value: function expected(utils) {
7247 return `an array of ${this._valueSchema.expected(utils)}`;
7251 value: function validate(value, utils) {
7252 if (!Array.isArray(value)) {
7256 var invalidValues = [];
7257 var _iteratorNormalCompletion = true;
7258 var _didIteratorError = false;
7259 var _iteratorError = undefined;
7262 for (var _iterator = value[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
7263 var subValue = _step.value;
7264 var subValidateResult = utils.normalizeValidateResult(this._valueSchema.validate(subValue, utils), subValue);
7266 if (subValidateResult !== true) {
7267 invalidValues.push(subValidateResult.value);
7271 _didIteratorError = true;
7272 _iteratorError = err;
7275 if (!_iteratorNormalCompletion && _iterator.return != null) {
7279 if (_didIteratorError) {
7280 throw _iteratorError;
7285 return invalidValues.length === 0 ? true : {
7286 value: invalidValues
7291 value: function deprecated(value, utils) {
7292 var deprecatedResult = [];
7293 var _iteratorNormalCompletion2 = true;
7294 var _didIteratorError2 = false;
7295 var _iteratorError2 = undefined;
7298 for (var _iterator2 = value[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
7299 var subValue = _step2.value;
7300 var subDeprecatedResult = utils.normalizeDeprecatedResult(this._valueSchema.deprecated(subValue, utils), subValue);
7302 if (subDeprecatedResult !== false) {
7303 deprecatedResult.push.apply(deprecatedResult, _toConsumableArray$1(subDeprecatedResult.map(function (_ref) {
7304 var deprecatedValue = _ref.value;
7306 value: [deprecatedValue]
7312 _didIteratorError2 = true;
7313 _iteratorError2 = err;
7316 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
7317 _iterator2.return();
7320 if (_didIteratorError2) {
7321 throw _iteratorError2;
7326 return deprecatedResult;
7330 value: function forward(value, utils) {
7331 var forwardResult = [];
7332 var _iteratorNormalCompletion3 = true;
7333 var _didIteratorError3 = false;
7334 var _iteratorError3 = undefined;
7337 for (var _iterator3 = value[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
7338 var subValue = _step3.value;
7339 var subForwardResult = utils.normalizeForwardResult(this._valueSchema.forward(subValue, utils), subValue);
7340 forwardResult.push.apply(forwardResult, _toConsumableArray$1(subForwardResult.map(wrapTransferResult)));
7343 _didIteratorError3 = true;
7344 _iteratorError3 = err;
7347 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
7348 _iterator3.return();
7351 if (_didIteratorError3) {
7352 throw _iteratorError3;
7357 return forwardResult;
7361 value: function redirect(value, utils) {
7364 var _iteratorNormalCompletion4 = true;
7365 var _didIteratorError4 = false;
7366 var _iteratorError4 = undefined;
7369 for (var _iterator4 = value[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
7370 var subValue = _step4.value;
7371 var subRedirectResult = utils.normalizeRedirectResult(this._valueSchema.redirect(subValue, utils), subValue);
7373 if ('remain' in subRedirectResult) {
7374 remain.push(subRedirectResult.remain);
7377 redirect.push.apply(redirect, _toConsumableArray$1(subRedirectResult.redirect.map(wrapTransferResult)));
7380 _didIteratorError4 = true;
7381 _iteratorError4 = err;
7384 if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
7385 _iterator4.return();
7388 if (_didIteratorError4) {
7389 throw _iteratorError4;
7394 return remain.length === 0 ? {
7403 value: function overlap(currentValue, newValue) {
7404 return currentValue.concat(newValue);
7411 exports.ArraySchema = ArraySchema;
7413 function wrapTransferResult(_ref2) {
7414 var from = _ref2.from,
7422 unwrapExports(array);
7423 var array_1 = array.ArraySchema;
7425 var boolean_1 = createCommonjsModule(function (module, exports) {
7427 Object.defineProperty(exports, "__esModule", {
7433 function (_schema_1$Schema) {
7434 _inherits(BooleanSchema, _schema_1$Schema);
7436 function BooleanSchema() {
7437 _classCallCheck(this, BooleanSchema);
7439 return _possibleConstructorReturn(this, _getPrototypeOf(BooleanSchema).apply(this, arguments));
7442 _createClass(BooleanSchema, [{
7444 value: function expected() {
7445 return 'true or false';
7449 value: function validate(value) {
7450 return typeof value === 'boolean';
7454 return BooleanSchema;
7457 exports.BooleanSchema = BooleanSchema;
7459 unwrapExports(boolean_1);
7460 var boolean_2 = boolean_1.BooleanSchema;
7462 var utils = createCommonjsModule(function (module, exports) {
7464 Object.defineProperty(exports, "__esModule", {
7468 function recordFromArray(array, mainKey) {
7469 var record = Object.create(null);
7470 var _iteratorNormalCompletion = true;
7471 var _didIteratorError = false;
7472 var _iteratorError = undefined;
7475 for (var _iterator = array[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
7476 var value = _step.value;
7477 var key = value[mainKey]; // istanbul ignore next
7480 throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`);
7484 record[key] = value;
7487 _didIteratorError = true;
7488 _iteratorError = err;
7491 if (!_iteratorNormalCompletion && _iterator.return != null) {
7495 if (_didIteratorError) {
7496 throw _iteratorError;
7504 exports.recordFromArray = recordFromArray;
7506 function mapFromArray(array, mainKey) {
7507 var map = new Map();
7508 var _iteratorNormalCompletion2 = true;
7509 var _didIteratorError2 = false;
7510 var _iteratorError2 = undefined;
7513 for (var _iterator2 = array[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
7514 var value = _step2.value;
7515 var key = value[mainKey]; // istanbul ignore next
7518 throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`);
7521 map.set(key, value);
7524 _didIteratorError2 = true;
7525 _iteratorError2 = err;
7528 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
7529 _iterator2.return();
7532 if (_didIteratorError2) {
7533 throw _iteratorError2;
7541 exports.mapFromArray = mapFromArray;
7543 function createAutoChecklist() {
7544 var map = Object.create(null);
7545 return function (id) {
7546 var idString = JSON.stringify(id);
7548 if (map[idString]) {
7552 map[idString] = true;
7557 exports.createAutoChecklist = createAutoChecklist;
7559 function partition(array, predicate) {
7561 var falseArray = [];
7562 var _iteratorNormalCompletion3 = true;
7563 var _didIteratorError3 = false;
7564 var _iteratorError3 = undefined;
7567 for (var _iterator3 = array[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
7568 var value = _step3.value;
7570 if (predicate(value)) {
7571 trueArray.push(value);
7573 falseArray.push(value);
7577 _didIteratorError3 = true;
7578 _iteratorError3 = err;
7581 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
7582 _iterator3.return();
7585 if (_didIteratorError3) {
7586 throw _iteratorError3;
7591 return [trueArray, falseArray];
7594 exports.partition = partition;
7596 function isInt(value) {
7597 return value === Math.floor(value);
7600 exports.isInt = isInt;
7602 function comparePrimitive(a, b) {
7607 var typeofA = typeof a;
7608 var typeofB = typeof b;
7609 var orders = ['undefined', 'object', 'boolean', 'number', 'string'];
7611 if (typeofA !== typeofB) {
7612 return orders.indexOf(typeofA) - orders.indexOf(typeofB);
7615 if (typeofA !== 'string') {
7616 return Number(a) - Number(b);
7619 return a.localeCompare(b);
7622 exports.comparePrimitive = comparePrimitive;
7624 function normalizeDefaultResult(result) {
7625 return result === undefined ? {} : result;
7628 exports.normalizeDefaultResult = normalizeDefaultResult;
7630 function normalizeValidateResult(result, value) {
7631 return result === true ? true : result === false ? {
7636 exports.normalizeValidateResult = normalizeValidateResult;
7638 function normalizeDeprecatedResult(result, value) {
7639 var doNotNormalizeTrue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
7640 return result === false ? false : result === true ? doNotNormalizeTrue ? true : [{
7642 }] : 'value' in result ? [result] : result.length === 0 ? false : result;
7645 exports.normalizeDeprecatedResult = normalizeDeprecatedResult;
7647 function normalizeTransferResult(result, value) {
7648 return typeof result === 'string' || 'key' in result ? {
7651 } : 'from' in result ? {
7660 exports.normalizeTransferResult = normalizeTransferResult;
7662 function normalizeForwardResult(result, value) {
7663 return result === undefined ? [] : Array.isArray(result) ? result.map(function (transferResult) {
7664 return normalizeTransferResult(transferResult, value);
7665 }) : [normalizeTransferResult(result, value)];
7668 exports.normalizeForwardResult = normalizeForwardResult;
7670 function normalizeRedirectResult(result, value) {
7671 var redirect = normalizeForwardResult(typeof result === 'object' && 'redirect' in result ? result.redirect : result, value);
7672 return redirect.length === 0 ? {
7675 } : typeof result === 'object' && 'remain' in result ? {
7676 remain: result.remain,
7683 exports.normalizeRedirectResult = normalizeRedirectResult;
7685 unwrapExports(utils);
7686 var utils_1 = utils.recordFromArray;
7687 var utils_2 = utils.mapFromArray;
7688 var utils_3 = utils.createAutoChecklist;
7689 var utils_4 = utils.partition;
7690 var utils_5 = utils.isInt;
7691 var utils_6 = utils.comparePrimitive;
7692 var utils_7 = utils.normalizeDefaultResult;
7693 var utils_8 = utils.normalizeValidateResult;
7694 var utils_9 = utils.normalizeDeprecatedResult;
7695 var utils_10 = utils.normalizeTransferResult;
7696 var utils_11 = utils.normalizeForwardResult;
7697 var utils_12 = utils.normalizeRedirectResult;
7699 var choice = createCommonjsModule(function (module, exports) {
7701 Object.defineProperty(exports, "__esModule", {
7707 function (_schema_1$Schema) {
7708 _inherits(ChoiceSchema, _schema_1$Schema);
7710 function ChoiceSchema(parameters) {
7713 _classCallCheck(this, ChoiceSchema);
7715 _this = _possibleConstructorReturn(this, _getPrototypeOf(ChoiceSchema).call(this, parameters));
7716 _this._choices = utils.mapFromArray(parameters.choices.map(function (choice) {
7717 return choice && typeof choice === 'object' ? choice : {
7724 _createClass(ChoiceSchema, [{
7726 value: function expected(_ref) {
7729 var descriptor = _ref.descriptor;
7730 var choiceValues = Array.from(this._choices.keys()).map(function (value) {
7731 return _this2._choices.get(value);
7732 }).filter(function (choiceInfo) {
7733 return !choiceInfo.deprecated;
7734 }).map(function (choiceInfo) {
7735 return choiceInfo.value;
7736 }).sort(utils.comparePrimitive).map(descriptor.value);
7737 var head = choiceValues.slice(0, -2);
7738 var tail = choiceValues.slice(-2);
7739 return head.concat(tail.join(' or ')).join(', ');
7743 value: function validate(value) {
7744 return this._choices.has(value);
7748 value: function deprecated(value) {
7749 var choiceInfo = this._choices.get(value);
7751 return choiceInfo && choiceInfo.deprecated ? {
7757 value: function forward(value) {
7758 var choiceInfo = this._choices.get(value);
7760 return choiceInfo ? choiceInfo.forward : undefined;
7764 value: function redirect(value) {
7765 var choiceInfo = this._choices.get(value);
7767 return choiceInfo ? choiceInfo.redirect : undefined;
7771 return ChoiceSchema;
7774 exports.ChoiceSchema = ChoiceSchema;
7776 unwrapExports(choice);
7777 var choice_1 = choice.ChoiceSchema;
7779 var number = createCommonjsModule(function (module, exports) {
7781 Object.defineProperty(exports, "__esModule", {
7787 function (_schema_1$Schema) {
7788 _inherits(NumberSchema, _schema_1$Schema);
7790 function NumberSchema() {
7791 _classCallCheck(this, NumberSchema);
7793 return _possibleConstructorReturn(this, _getPrototypeOf(NumberSchema).apply(this, arguments));
7796 _createClass(NumberSchema, [{
7798 value: function expected() {
7803 value: function validate(value, _utils) {
7804 return typeof value === 'number';
7808 return NumberSchema;
7811 exports.NumberSchema = NumberSchema;
7813 unwrapExports(number);
7814 var number_1 = number.NumberSchema;
7816 var integer = createCommonjsModule(function (module, exports) {
7818 Object.defineProperty(exports, "__esModule", {
7824 function (_number_1$NumberSchem) {
7825 _inherits(IntegerSchema, _number_1$NumberSchem);
7827 function IntegerSchema() {
7828 _classCallCheck(this, IntegerSchema);
7830 return _possibleConstructorReturn(this, _getPrototypeOf(IntegerSchema).apply(this, arguments));
7833 _createClass(IntegerSchema, [{
7835 value: function expected() {
7836 return 'an integer';
7840 value: function validate(value, utils$1) {
7841 return utils$1.normalizeValidateResult(_get(_getPrototypeOf(IntegerSchema.prototype), "validate", this).call(this, value, utils$1), value) === true && utils.isInt(value);
7845 return IntegerSchema;
7846 }(number.NumberSchema);
7848 exports.IntegerSchema = IntegerSchema;
7850 unwrapExports(integer);
7851 var integer_1 = integer.IntegerSchema;
7853 var string = createCommonjsModule(function (module, exports) {
7855 Object.defineProperty(exports, "__esModule", {
7861 function (_schema_1$Schema) {
7862 _inherits(StringSchema, _schema_1$Schema);
7864 function StringSchema() {
7865 _classCallCheck(this, StringSchema);
7867 return _possibleConstructorReturn(this, _getPrototypeOf(StringSchema).apply(this, arguments));
7870 _createClass(StringSchema, [{
7872 value: function expected() {
7877 value: function validate(value) {
7878 return typeof value === 'string';
7882 return StringSchema;
7885 exports.StringSchema = StringSchema;
7887 unwrapExports(string);
7888 var string_1 = string.StringSchema;
7890 var schemas = createCommonjsModule(function (module, exports) {
7892 Object.defineProperty(exports, "__esModule", {
7896 tslib_1.__exportStar(alias, exports);
7898 tslib_1.__exportStar(any, exports);
7900 tslib_1.__exportStar(array, exports);
7902 tslib_1.__exportStar(boolean_1, exports);
7904 tslib_1.__exportStar(choice, exports);
7906 tslib_1.__exportStar(integer, exports);
7908 tslib_1.__exportStar(number, exports);
7910 tslib_1.__exportStar(string, exports);
7912 unwrapExports(schemas);
7914 var defaults = createCommonjsModule(function (module, exports) {
7916 Object.defineProperty(exports, "__esModule", {
7919 exports.defaultDescriptor = api.apiDescriptor;
7920 exports.defaultUnknownHandler = leven_1.levenUnknownHandler;
7921 exports.defaultInvalidHandler = invalid.commonInvalidHandler;
7922 exports.defaultDeprecatedHandler = common.commonDeprecatedHandler;
7924 unwrapExports(defaults);
7925 var defaults_1 = defaults.defaultDescriptor;
7926 var defaults_2 = defaults.defaultUnknownHandler;
7927 var defaults_3 = defaults.defaultInvalidHandler;
7928 var defaults_4 = defaults.defaultDeprecatedHandler;
7930 var normalize = createCommonjsModule(function (module, exports) {
7932 Object.defineProperty(exports, "__esModule", {
7936 exports.normalize = function (options, schemas, opts) {
7937 return new Normalizer(schemas, opts).normalize(options);
7943 function Normalizer(schemas, opts) {
7944 _classCallCheck(this, Normalizer);
7946 // istanbul ignore next
7947 var _ref = opts || {},
7948 _ref$logger = _ref.logger,
7949 logger = _ref$logger === void 0 ? console : _ref$logger,
7950 _ref$descriptor = _ref.descriptor,
7951 descriptor = _ref$descriptor === void 0 ? defaults.defaultDescriptor : _ref$descriptor,
7952 _ref$unknown = _ref.unknown,
7953 unknown = _ref$unknown === void 0 ? defaults.defaultUnknownHandler : _ref$unknown,
7954 _ref$invalid = _ref.invalid,
7955 invalid = _ref$invalid === void 0 ? defaults.defaultInvalidHandler : _ref$invalid,
7956 _ref$deprecated = _ref.deprecated,
7957 deprecated = _ref$deprecated === void 0 ? defaults.defaultDeprecatedHandler : _ref$deprecated;
7962 /* istanbul ignore next */
7964 warn: function warn() {}
7966 schemas: utils.recordFromArray(schemas, 'name'),
7967 normalizeDefaultResult: utils.normalizeDefaultResult,
7968 normalizeDeprecatedResult: utils.normalizeDeprecatedResult,
7969 normalizeForwardResult: utils.normalizeForwardResult,
7970 normalizeRedirectResult: utils.normalizeRedirectResult,
7971 normalizeValidateResult: utils.normalizeValidateResult
7973 this._unknownHandler = unknown;
7974 this._invalidHandler = invalid;
7975 this._deprecatedHandler = deprecated;
7976 this.cleanHistory();
7979 _createClass(Normalizer, [{
7980 key: "cleanHistory",
7981 value: function cleanHistory() {
7982 this._hasDeprecationWarned = utils.createAutoChecklist();
7986 value: function normalize(options) {
7989 var normalized = {};
7990 var restOptionsArray = [options];
7992 var applyNormalization = function applyNormalization() {
7993 while (restOptionsArray.length !== 0) {
7994 var currentOptions = restOptionsArray.shift();
7996 var transferredOptionsArray = _this._applyNormalization(currentOptions, normalized);
7998 restOptionsArray.push.apply(restOptionsArray, _toConsumableArray$1(transferredOptionsArray));
8002 applyNormalization();
8004 for (var _i = 0, _Object$keys = Object.keys(this._utils.schemas); _i < _Object$keys.length; _i++) {
8005 var key = _Object$keys[_i];
8006 var schema = this._utils.schemas[key];
8008 if (!(key in normalized)) {
8009 var defaultResult = utils.normalizeDefaultResult(schema.default(this._utils));
8011 if ('value' in defaultResult) {
8012 restOptionsArray.push({
8013 [key]: defaultResult.value
8019 applyNormalization();
8021 for (var _i2 = 0, _Object$keys2 = Object.keys(this._utils.schemas); _i2 < _Object$keys2.length; _i2++) {
8022 var _key = _Object$keys2[_i2];
8023 var _schema = this._utils.schemas[_key];
8025 if (_key in normalized) {
8026 normalized[_key] = _schema.postprocess(normalized[_key], this._utils);
8033 key: "_applyNormalization",
8034 value: function _applyNormalization(options, normalized) {
8037 var transferredOptionsArray = [];
8039 var _utils_1$partition = utils.partition(Object.keys(options), function (key) {
8040 return key in _this2._utils.schemas;
8042 _utils_1$partition2 = _slicedToArray(_utils_1$partition, 2),
8043 knownOptionNames = _utils_1$partition2[0],
8044 unknownOptionNames = _utils_1$partition2[1];
8046 var _iteratorNormalCompletion = true;
8047 var _didIteratorError = false;
8048 var _iteratorError = undefined;
8051 var _loop = function _loop() {
8052 var key = _step.value;
8053 var schema = _this2._utils.schemas[key];
8054 var value = schema.preprocess(options[key], _this2._utils);
8055 var validateResult = utils.normalizeValidateResult(schema.validate(value, _this2._utils), value);
8057 if (validateResult !== true) {
8058 var invalidValue = validateResult.value;
8060 var errorMessageOrError = _this2._invalidHandler(key, invalidValue, _this2._utils);
8062 throw typeof errorMessageOrError === 'string' ? new Error(errorMessageOrError) :
8063 /* istanbul ignore next*/
8064 errorMessageOrError;
8067 var appendTransferredOptions = function appendTransferredOptions(_ref2) {
8068 var from = _ref2.from,
8070 transferredOptionsArray.push(typeof to === 'string' ? {
8077 var warnDeprecated = function warnDeprecated(_ref3) {
8078 var currentValue = _ref3.value,
8079 redirectTo = _ref3.redirectTo;
8080 var deprecatedResult = utils.normalizeDeprecatedResult(schema.deprecated(currentValue, _this2._utils), value,
8081 /* doNotNormalizeTrue */
8084 if (deprecatedResult === false) {
8088 if (deprecatedResult === true) {
8089 if (!_this2._hasDeprecationWarned(key)) {
8090 _this2._utils.logger.warn(_this2._deprecatedHandler(key, redirectTo, _this2._utils));
8093 var _iteratorNormalCompletion3 = true;
8094 var _didIteratorError3 = false;
8095 var _iteratorError3 = undefined;
8098 for (var _iterator3 = deprecatedResult[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
8099 var deprecatedValue = _step3.value.value;
8102 value: deprecatedValue
8105 if (!_this2._hasDeprecationWarned(pair)) {
8106 var redirectToPair = typeof redirectTo === 'string' ? {
8108 value: deprecatedValue
8111 _this2._utils.logger.warn(_this2._deprecatedHandler(pair, redirectToPair, _this2._utils));
8115 _didIteratorError3 = true;
8116 _iteratorError3 = err;
8119 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
8120 _iterator3.return();
8123 if (_didIteratorError3) {
8124 throw _iteratorError3;
8131 var forwardResult = utils.normalizeForwardResult(schema.forward(value, _this2._utils), value);
8132 forwardResult.forEach(appendTransferredOptions);
8133 var redirectResult = utils.normalizeRedirectResult(schema.redirect(value, _this2._utils), value);
8134 redirectResult.redirect.forEach(appendTransferredOptions);
8136 if ('remain' in redirectResult) {
8137 var remainingValue = redirectResult.remain;
8138 normalized[key] = key in normalized ? schema.overlap(normalized[key], remainingValue, _this2._utils) : remainingValue;
8140 value: remainingValue
8144 var _iteratorNormalCompletion4 = true;
8145 var _didIteratorError4 = false;
8146 var _iteratorError4 = undefined;
8149 for (var _iterator4 = redirectResult.redirect[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
8150 var _step4$value = _step4.value,
8151 from = _step4$value.from,
8152 to = _step4$value.to;
8159 _didIteratorError4 = true;
8160 _iteratorError4 = err;
8163 if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
8164 _iterator4.return();
8167 if (_didIteratorError4) {
8168 throw _iteratorError4;
8174 for (var _iterator = knownOptionNames[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
8178 _didIteratorError = true;
8179 _iteratorError = err;
8182 if (!_iteratorNormalCompletion && _iterator.return != null) {
8186 if (_didIteratorError) {
8187 throw _iteratorError;
8192 var _iteratorNormalCompletion2 = true;
8193 var _didIteratorError2 = false;
8194 var _iteratorError2 = undefined;
8197 for (var _iterator2 = unknownOptionNames[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
8198 var key = _step2.value;
8199 var value = options[key];
8201 var unknownResult = this._unknownHandler(key, value, this._utils);
8203 if (unknownResult) {
8204 for (var _i3 = 0, _Object$keys3 = Object.keys(unknownResult); _i3 < _Object$keys3.length; _i3++) {
8205 var unknownKey = _Object$keys3[_i3];
8206 var unknownOption = {
8207 [unknownKey]: unknownResult[unknownKey]
8210 if (unknownKey in this._utils.schemas) {
8211 transferredOptionsArray.push(unknownOption);
8213 Object.assign(normalized, unknownOption);
8219 _didIteratorError2 = true;
8220 _iteratorError2 = err;
8223 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
8224 _iterator2.return();
8227 if (_didIteratorError2) {
8228 throw _iteratorError2;
8233 return transferredOptionsArray;
8240 exports.Normalizer = Normalizer;
8242 unwrapExports(normalize);
8243 var normalize_1 = normalize.normalize;
8244 var normalize_2 = normalize.Normalizer;
8246 var lib = createCommonjsModule(function (module, exports) {
8248 Object.defineProperty(exports, "__esModule", {
8252 tslib_1.__exportStar(descriptors, exports);
8254 tslib_1.__exportStar(handlers, exports);
8256 tslib_1.__exportStar(schemas, exports);
8258 tslib_1.__exportStar(normalize, exports);
8260 tslib_1.__exportStar(schema, exports);
8265 var charCodeCache$1 = [];
8267 var leven$1 = function leven(left, right) {
8268 if (left === right) {
8272 var swap = left; // Swapping the strings if `a` is longer than `b` so we know which one is the
8273 // shortest & which one is the longest
8275 if (left.length > right.length) {
8280 var leftLength = left.length;
8281 var rightLength = right.length; // Performing suffix trimming:
8282 // We can linearly drop suffix common to both strings since they
8283 // don't increase distance at all
8284 // Note: `~-` is the bitwise way to perform a `- 1` operation
8286 while (leftLength > 0 && left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength)) {
8289 } // Performing prefix trimming
8290 // We can linearly drop prefix common to both strings since they
8291 // don't increase distance at all
8296 while (start < leftLength && left.charCodeAt(start) === right.charCodeAt(start)) {
8300 leftLength -= start;
8301 rightLength -= start;
8303 if (leftLength === 0) {
8314 while (i < leftLength) {
8315 charCodeCache$1[i] = left.charCodeAt(start + i);
8319 while (j < rightLength) {
8320 bCharCode = right.charCodeAt(start + j);
8324 for (i = 0; i < leftLength; i++) {
8325 temp2 = bCharCode === charCodeCache$1[i] ? temp : temp + 1;
8326 temp = array$1[i]; // eslint-disable-next-line no-multi-assign
8328 result = array$1[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2;
8335 var leven_1$1 = leven$1; // TODO: Remove this for the next major release
8337 var default_1 = leven$1;
8338 leven_1$1.default = default_1;
8340 var cliDescriptor = {
8341 key: function key(_key) {
8342 return _key.length === 1 ? `-${_key}` : `--${_key}`;
8344 value: function value(_value) {
8345 return lib.apiDescriptor.value(_value);
8347 pair: function pair(_ref) {
8350 return value === false ? `--no-${key}` : value === true ? cliDescriptor.key(key) : value === "" ? `${cliDescriptor.key(key)} without an argument` : `${cliDescriptor.key(key)}=${value}`;
8356 function (_vnopts$ChoiceSchema) {
8357 _inherits(FlagSchema, _vnopts$ChoiceSchema);
8359 function FlagSchema(_ref2) {
8362 var name = _ref2.name,
8363 flags = _ref2.flags;
8365 _classCallCheck(this, FlagSchema);
8367 _this = _possibleConstructorReturn(this, _getPrototypeOf(FlagSchema).call(this, {
8371 _this._flags = flags.slice().sort();
8375 _createClass(FlagSchema, [{
8377 value: function preprocess(value, utils) {
8378 if (typeof value === "string" && value.length !== 0 && this._flags.indexOf(value) === -1) {
8379 var suggestion = this._flags.find(function (flag) {
8380 return leven_1$1(flag, value) < 3;
8384 utils.logger.warn([`Unknown flag ${chalk.yellow(utils.descriptor.value(value))},`, `did you mean ${chalk.blue(utils.descriptor.value(suggestion))}?`].join(" "));
8393 value: function expected() {
8399 }(lib.ChoiceSchema);
8401 var hasDeprecationWarned;
8403 function normalizeOptions(options, optionInfos) {
8404 var _ref3 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
8405 logger = _ref3.logger,
8406 _ref3$isCLI = _ref3.isCLI,
8407 isCLI = _ref3$isCLI === void 0 ? false : _ref3$isCLI,
8408 _ref3$passThrough = _ref3.passThrough,
8409 passThrough = _ref3$passThrough === void 0 ? false : _ref3$passThrough;
8411 var unknown = !passThrough ? lib.levenUnknownHandler : Array.isArray(passThrough) ? function (key, value) {
8412 return passThrough.indexOf(key) === -1 ? undefined : {
8415 } : function (key, value) {
8420 var descriptor = isCLI ? cliDescriptor : lib.apiDescriptor;
8421 var schemas = optionInfosToSchemas(optionInfos, {
8424 var normalizer = new lib.Normalizer(schemas, {
8429 var shouldSuppressDuplicateDeprecationWarnings = logger !== false;
8431 if (shouldSuppressDuplicateDeprecationWarnings && hasDeprecationWarned) {
8432 normalizer._hasDeprecationWarned = hasDeprecationWarned;
8435 var normalized = normalizer.normalize(options);
8437 if (shouldSuppressDuplicateDeprecationWarnings) {
8438 hasDeprecationWarned = normalizer._hasDeprecationWarned;
8444 function optionInfosToSchemas(optionInfos, _ref4) {
8445 var isCLI = _ref4.isCLI;
8449 schemas.push(lib.AnySchema.create({
8454 var _iteratorNormalCompletion = true;
8455 var _didIteratorError = false;
8456 var _iteratorError = undefined;
8459 for (var _iterator = optionInfos[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
8460 var optionInfo = _step.value;
8461 schemas.push(optionInfoToSchema(optionInfo, {
8466 if (optionInfo.alias && isCLI) {
8467 schemas.push(lib.AliasSchema.create({
8468 name: optionInfo.alias,
8469 sourceName: optionInfo.name
8474 _didIteratorError = true;
8475 _iteratorError = err;
8478 if (!_iteratorNormalCompletion && _iterator.return != null) {
8482 if (_didIteratorError) {
8483 throw _iteratorError;
8491 function optionInfoToSchema(optionInfo, _ref5) {
8492 var isCLI = _ref5.isCLI,
8493 optionInfos = _ref5.optionInfos;
8494 var SchemaConstructor;
8496 name: optionInfo.name
8500 switch (optionInfo.type) {
8502 SchemaConstructor = lib.IntegerSchema;
8505 parameters.preprocess = function (value) {
8506 return Number(value);
8513 SchemaConstructor = lib.StringSchema;
8517 SchemaConstructor = lib.ChoiceSchema;
8518 parameters.choices = optionInfo.choices.map(function (choiceInfo) {
8519 return typeof choiceInfo === "object" && choiceInfo.redirect ? Object.assign({}, choiceInfo, {
8522 key: optionInfo.name,
8523 value: choiceInfo.redirect
8531 SchemaConstructor = lib.BooleanSchema;
8535 SchemaConstructor = FlagSchema;
8536 parameters.flags = optionInfos.map(function (optionInfo) {
8537 return [].concat(optionInfo.alias || [], optionInfo.description ? optionInfo.name : [], optionInfo.oppositeDescription ? `no-${optionInfo.name}` : []);
8538 }).reduce(function (a, b) {
8544 SchemaConstructor = lib.StringSchema;
8548 throw new Error(`Unexpected type ${optionInfo.type}`);
8551 if (optionInfo.exception) {
8552 parameters.validate = function (value, schema, utils) {
8553 return optionInfo.exception(value) || schema.validate(value, utils);
8556 parameters.validate = function (value, schema, utils) {
8557 return value === undefined || schema.validate(value, utils);
8561 if (optionInfo.redirect) {
8562 handlers.redirect = function (value) {
8563 return !value ? undefined : {
8565 key: optionInfo.redirect.option,
8566 value: optionInfo.redirect.value
8572 if (optionInfo.deprecated) {
8573 handlers.deprecated = true;
8574 } // allow CLI overriding, e.g., prettier package.json --tab-width 1 --tab-width 2
8577 if (isCLI && !optionInfo.array) {
8578 var originalPreprocess = parameters.preprocess || function (x) {
8582 parameters.preprocess = function (value, schema, utils) {
8583 return schema.preprocess(originalPreprocess(Array.isArray(value) ? value[value.length - 1] : value), utils);
8587 return optionInfo.array ? lib.ArraySchema.create(Object.assign(isCLI ? {
8588 preprocess: function preprocess(v) {
8589 return [].concat(v);
8592 valueSchema: SchemaConstructor.create(parameters)
8593 })) : SchemaConstructor.create(Object.assign({}, parameters, handlers));
8596 function normalizeApiOptions(options, optionInfos, opts) {
8597 return normalizeOptions(options, optionInfos, opts);
8600 function normalizeCliOptions(options, optionInfos, opts) {
8601 return normalizeOptions(options, optionInfos, Object.assign({
8606 var optionsNormalizer = {
8607 normalizeApiOptions,
8611 var getLast = function getLast(arr) {
8612 return arr.length > 0 ? arr[arr.length - 1] : null;
8615 function locStart(node, opts) {
8616 opts = opts || {}; // Handle nodes with decorators. They should start at the first decorator
8618 if (!opts.ignoreDecorators && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0) {
8619 return locStart(node.declaration.decorators[0]);
8622 if (!opts.ignoreDecorators && node.decorators && node.decorators.length > 0) {
8623 return locStart(node.decorators[0]);
8626 if (node.__location) {
8627 return node.__location.startOffset;
8631 return node.range[0];
8634 if (typeof node.start === "number") {
8639 return node.loc.start;
8645 function locEnd(node) {
8646 var endNode = node.nodes && getLast(node.nodes);
8648 if (endNode && node.source && !node.source.end) {
8652 if (node.__location) {
8653 return node.__location.endOffset;
8656 var loc = node.range ? node.range[1] : typeof node.end === "number" ? node.end : null;
8658 if (node.typeAnnotation) {
8659 return Math.max(loc, locEnd(node.typeAnnotation));
8662 if (node.loc && !loc) {
8663 return node.loc.end;
8674 var jsTokens = createCommonjsModule(function (module, exports) {
8675 // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell
8676 // License: MIT. (See LICENSE.)
8677 Object.defineProperty(exports, "__esModule", {
8679 }); // This regex comes from regex.coffee, and is inserted here by generate-index.js
8680 // (run `npm run build`).
8682 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;
8684 exports.matchToToken = function (match) {
8690 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";
8694 unwrapExports(jsTokens);
8695 var jsTokens_1 = jsTokens.matchToToken;
8697 var ast = createCommonjsModule(function (module) {
8699 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
8701 Redistribution and use in source and binary forms, with or without
8702 modification, are permitted provided that the following conditions are met:
8704 * Redistributions of source code must retain the above copyright
8705 notice, this list of conditions and the following disclaimer.
8706 * Redistributions in binary form must reproduce the above copyright
8707 notice, this list of conditions and the following disclaimer in the
8708 documentation and/or other materials provided with the distribution.
8710 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
8711 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
8712 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
8713 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
8714 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
8715 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
8716 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
8717 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8718 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8719 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8723 function isExpression(node) {
8728 switch (node.type) {
8729 case 'ArrayExpression':
8730 case 'AssignmentExpression':
8731 case 'BinaryExpression':
8732 case 'CallExpression':
8733 case 'ConditionalExpression':
8734 case 'FunctionExpression':
8737 case 'LogicalExpression':
8738 case 'MemberExpression':
8739 case 'NewExpression':
8740 case 'ObjectExpression':
8741 case 'SequenceExpression':
8742 case 'ThisExpression':
8743 case 'UnaryExpression':
8744 case 'UpdateExpression':
8751 function isIterationStatement(node) {
8756 switch (node.type) {
8757 case 'DoWhileStatement':
8758 case 'ForInStatement':
8759 case 'ForStatement':
8760 case 'WhileStatement':
8767 function isStatement(node) {
8772 switch (node.type) {
8773 case 'BlockStatement':
8774 case 'BreakStatement':
8775 case 'ContinueStatement':
8776 case 'DebuggerStatement':
8777 case 'DoWhileStatement':
8778 case 'EmptyStatement':
8779 case 'ExpressionStatement':
8780 case 'ForInStatement':
8781 case 'ForStatement':
8783 case 'LabeledStatement':
8784 case 'ReturnStatement':
8785 case 'SwitchStatement':
8786 case 'ThrowStatement':
8787 case 'TryStatement':
8788 case 'VariableDeclaration':
8789 case 'WhileStatement':
8790 case 'WithStatement':
8797 function isSourceElement(node) {
8798 return isStatement(node) || node != null && node.type === 'FunctionDeclaration';
8801 function trailingStatement(node) {
8802 switch (node.type) {
8804 if (node.alternate != null) {
8805 return node.alternate;
8808 return node.consequent;
8810 case 'LabeledStatement':
8811 case 'ForStatement':
8812 case 'ForInStatement':
8813 case 'WhileStatement':
8814 case 'WithStatement':
8821 function isProblematicIfStatement(node) {
8824 if (node.type !== 'IfStatement') {
8828 if (node.alternate == null) {
8832 current = node.consequent;
8835 if (current.type === 'IfStatement') {
8836 if (current.alternate == null) {
8841 current = trailingStatement(current);
8848 isExpression: isExpression,
8849 isStatement: isStatement,
8850 isIterationStatement: isIterationStatement,
8851 isSourceElement: isSourceElement,
8852 isProblematicIfStatement: isProblematicIfStatement,
8853 trailingStatement: trailingStatement
8856 /* vim: set sw=4 ts=4 et tw=80 : */
8859 var ast_1 = ast.isExpression;
8860 var ast_2 = ast.isStatement;
8861 var ast_3 = ast.isIterationStatement;
8862 var ast_4 = ast.isSourceElement;
8863 var ast_5 = ast.isProblematicIfStatement;
8864 var ast_6 = ast.trailingStatement;
8866 var code = createCommonjsModule(function (module) {
8868 Copyright (C) 2013-2014 Yusuke Suzuki <utatane.tea@gmail.com>
8869 Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
8871 Redistribution and use in source and binary forms, with or without
8872 modification, are permitted provided that the following conditions are met:
8874 * Redistributions of source code must retain the above copyright
8875 notice, this list of conditions and the following disclaimer.
8876 * Redistributions in binary form must reproduce the above copyright
8877 notice, this list of conditions and the following disclaimer in the
8878 documentation and/or other materials provided with the distribution.
8880 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
8881 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
8882 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
8883 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
8884 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
8885 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
8886 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
8887 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8888 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8889 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8893 var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`.
8896 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart:
8897 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]/,
8898 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart:
8899 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]/
8902 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart:
8903 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]/,
8904 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart:
8905 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]/
8908 function isDecimalDigit(ch) {
8909 return 0x30 <= ch && ch <= 0x39; // 0..9
8912 function isHexDigit(ch) {
8913 return 0x30 <= ch && ch <= 0x39 || // 0..9
8914 0x61 <= ch && ch <= 0x66 || // a..f
8915 0x41 <= ch && ch <= 0x46; // A..F
8918 function isOctalDigit(ch) {
8919 return ch >= 0x30 && ch <= 0x37; // 0..7
8920 } // 7.2 White Space
8923 NON_ASCII_WHITESPACES = [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF];
8925 function isWhiteSpace(ch) {
8926 return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
8927 } // 7.3 Line Terminators
8930 function isLineTerminator(ch) {
8931 return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;
8932 } // 7.6 Identifier Names and Identifiers
8935 function fromCodePoint(cp) {
8937 return String.fromCharCode(cp);
8940 var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800);
8941 var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00);
8945 IDENTIFIER_START = new Array(0x80);
8947 for (ch = 0; ch < 0x80; ++ch) {
8948 IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
8949 ch >= 0x41 && ch <= 0x5A || // A..Z
8950 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
8953 IDENTIFIER_PART = new Array(0x80);
8955 for (ch = 0; ch < 0x80; ++ch) {
8956 IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
8957 ch >= 0x41 && ch <= 0x5A || // A..Z
8958 ch >= 0x30 && ch <= 0x39 || // 0..9
8959 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
8962 function isIdentifierStartES5(ch) {
8963 return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
8966 function isIdentifierPartES5(ch) {
8967 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
8970 function isIdentifierStartES6(ch) {
8971 return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
8974 function isIdentifierPartES6(ch) {
8975 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
8979 isDecimalDigit: isDecimalDigit,
8980 isHexDigit: isHexDigit,
8981 isOctalDigit: isOctalDigit,
8982 isWhiteSpace: isWhiteSpace,
8983 isLineTerminator: isLineTerminator,
8984 isIdentifierStartES5: isIdentifierStartES5,
8985 isIdentifierPartES5: isIdentifierPartES5,
8986 isIdentifierStartES6: isIdentifierStartES6,
8987 isIdentifierPartES6: isIdentifierPartES6
8990 /* vim: set sw=4 ts=4 et tw=80 : */
8993 var code_1 = code.isDecimalDigit;
8994 var code_2 = code.isHexDigit;
8995 var code_3 = code.isOctalDigit;
8996 var code_4 = code.isWhiteSpace;
8997 var code_5 = code.isLineTerminator;
8998 var code_6 = code.isIdentifierStartES5;
8999 var code_7 = code.isIdentifierPartES5;
9000 var code_8 = code.isIdentifierStartES6;
9001 var code_9 = code.isIdentifierPartES6;
9003 var keyword = createCommonjsModule(function (module) {
9005 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
9007 Redistribution and use in source and binary forms, with or without
9008 modification, are permitted provided that the following conditions are met:
9010 * Redistributions of source code must retain the above copyright
9011 notice, this list of conditions and the following disclaimer.
9012 * Redistributions in binary form must reproduce the above copyright
9013 notice, this list of conditions and the following disclaimer in the
9014 documentation and/or other materials provided with the distribution.
9016 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
9017 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
9018 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
9019 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
9020 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
9021 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
9022 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
9023 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9024 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
9025 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9031 function isStrictModeReservedWordES6(id) {
9048 function isKeywordES5(id, strict) {
9049 // yield should not be treated as keyword under non-strict mode.
9050 if (!strict && id === 'yield') {
9054 return isKeywordES6(id, strict);
9057 function isKeywordES6(id, strict) {
9058 if (strict && isStrictModeReservedWordES6(id)) {
9062 switch (id.length) {
9064 return id === 'if' || id === 'in' || id === 'do';
9067 return id === 'var' || id === 'for' || id === 'new' || id === 'try';
9070 return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum';
9073 return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super';
9076 return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import';
9079 return id === 'default' || id === 'finally' || id === 'extends';
9082 return id === 'function' || id === 'continue' || id === 'debugger';
9085 return id === 'instanceof';
9092 function isReservedWordES5(id, strict) {
9093 return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict);
9096 function isReservedWordES6(id, strict) {
9097 return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict);
9100 function isRestrictedWord(id) {
9101 return id === 'eval' || id === 'arguments';
9104 function isIdentifierNameES5(id) {
9107 if (id.length === 0) {
9111 ch = id.charCodeAt(0);
9113 if (!code$1.isIdentifierStartES5(ch)) {
9117 for (i = 1, iz = id.length; i < iz; ++i) {
9118 ch = id.charCodeAt(i);
9120 if (!code$1.isIdentifierPartES5(ch)) {
9128 function decodeUtf16(lead, trail) {
9129 return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
9132 function isIdentifierNameES6(id) {
9133 var i, iz, ch, lowCh, check;
9135 if (id.length === 0) {
9139 check = code$1.isIdentifierStartES6;
9141 for (i = 0, iz = id.length; i < iz; ++i) {
9142 ch = id.charCodeAt(i);
9144 if (0xD800 <= ch && ch <= 0xDBFF) {
9151 lowCh = id.charCodeAt(i);
9153 if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) {
9157 ch = decodeUtf16(ch, lowCh);
9164 check = code$1.isIdentifierPartES6;
9170 function isIdentifierES5(id, strict) {
9171 return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
9174 function isIdentifierES6(id, strict) {
9175 return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
9179 isKeywordES5: isKeywordES5,
9180 isKeywordES6: isKeywordES6,
9181 isReservedWordES5: isReservedWordES5,
9182 isReservedWordES6: isReservedWordES6,
9183 isRestrictedWord: isRestrictedWord,
9184 isIdentifierNameES5: isIdentifierNameES5,
9185 isIdentifierNameES6: isIdentifierNameES6,
9186 isIdentifierES5: isIdentifierES5,
9187 isIdentifierES6: isIdentifierES6
9190 /* vim: set sw=4 ts=4 et tw=80 : */
9193 var keyword_1 = keyword.isKeywordES5;
9194 var keyword_2 = keyword.isKeywordES6;
9195 var keyword_3 = keyword.isReservedWordES5;
9196 var keyword_4 = keyword.isReservedWordES6;
9197 var keyword_5 = keyword.isRestrictedWord;
9198 var keyword_6 = keyword.isIdentifierNameES5;
9199 var keyword_7 = keyword.isIdentifierNameES6;
9200 var keyword_8 = keyword.isIdentifierES5;
9201 var keyword_9 = keyword.isIdentifierES6;
9203 var utils$1 = createCommonjsModule(function (module, exports) {
9205 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
9207 Redistribution and use in source and binary forms, with or without
9208 modification, are permitted provided that the following conditions are met:
9210 * Redistributions of source code must retain the above copyright
9211 notice, this list of conditions and the following disclaimer.
9212 * Redistributions in binary form must reproduce the above copyright
9213 notice, this list of conditions and the following disclaimer in the
9214 documentation and/or other materials provided with the distribution.
9216 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
9217 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
9218 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
9219 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
9220 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
9221 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
9222 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
9223 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9224 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
9225 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9230 exports.code = code;
9231 exports.keyword = keyword;
9233 /* vim: set sw=4 ts=4 et tw=80 : */
9236 var utils_1$1 = utils$1.ast;
9237 var utils_2$1 = utils$1.code;
9238 var utils_3$1 = utils$1.keyword;
9240 var lib$1 = createCommonjsModule(function (module, exports) {
9242 Object.defineProperty(exports, "__esModule", {
9245 exports.shouldHighlight = shouldHighlight;
9246 exports.getChalk = getChalk;
9247 exports.default = highlight;
9249 function _jsTokens() {
9250 var data = _interopRequireWildcard(jsTokens);
9252 _jsTokens = function _jsTokens() {
9259 function _esutils() {
9260 var data = _interopRequireDefault(utils$1);
9262 _esutils = function _esutils() {
9270 var data = _interopRequireDefault(chalk);
9272 _chalk = function _chalk() {
9279 function _interopRequireDefault(obj) {
9280 return obj && obj.__esModule ? obj : {
9285 function _interopRequireWildcard(obj) {
9286 if (obj && obj.__esModule) {
9292 for (var key in obj) {
9293 if (Object.prototype.hasOwnProperty.call(obj, key)) {
9294 var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
9296 if (desc.get || desc.set) {
9297 Object.defineProperty(newObj, key, desc);
9299 newObj[key] = obj[key];
9305 newObj.default = obj;
9310 function getDefs(chalk) {
9312 keyword: chalk.cyan,
9313 capitalized: chalk.yellow,
9314 jsx_tag: chalk.yellow,
9315 punctuator: chalk.yellow,
9316 number: chalk.magenta,
9317 string: chalk.green,
9318 regex: chalk.magenta,
9319 comment: chalk.grey,
9320 invalid: chalk.white.bgRed.bold
9324 var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
9325 var JSX_TAG = /^[a-z][\w-]*$/i;
9326 var BRACKET = /^[()[\]{}]$/;
9328 function getTokenType(match) {
9329 var _match$slice = match.slice(-2),
9330 _match$slice2 = _slicedToArray(_match$slice, 2),
9331 offset = _match$slice2[0],
9332 text = _match$slice2[1];
9334 var token = (0, _jsTokens().matchToToken)(match);
9336 if (token.type === "name") {
9337 if (_esutils().default.keyword.isReservedWordES6(token.value)) {
9341 if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
9345 if (token.value[0] !== token.value[0].toLowerCase()) {
9346 return "capitalized";
9350 if (token.type === "punctuator" && BRACKET.test(token.value)) {
9354 if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
9355 return "punctuator";
9361 function highlightTokens(defs, text) {
9362 return text.replace(_jsTokens().default, function () {
9363 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
9364 args[_key] = arguments[_key];
9367 var type = getTokenType(args);
9368 var colorize = defs[type];
9371 return args[0].split(NEWLINE).map(function (str) {
9372 return colorize(str);
9380 function shouldHighlight(options) {
9381 return _chalk().default.supportsColor || options.forceColor;
9384 function getChalk(options) {
9385 var chalk = _chalk().default;
9387 if (options.forceColor) {
9388 chalk = new (_chalk().default.constructor)({
9397 function highlight(code) {
9398 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
9400 if (shouldHighlight(options)) {
9401 var chalk = getChalk(options);
9402 var defs = getDefs(chalk);
9403 return highlightTokens(defs, code);
9409 unwrapExports(lib$1);
9410 var lib_1 = lib$1.shouldHighlight;
9411 var lib_2 = lib$1.getChalk;
9413 var lib$2 = createCommonjsModule(function (module, exports) {
9415 Object.defineProperty(exports, "__esModule", {
9418 exports.codeFrameColumns = codeFrameColumns;
9419 exports.default = _default;
9421 function _highlight() {
9422 var data = _interopRequireWildcard(lib$1);
9424 _highlight = function _highlight() {
9431 function _interopRequireWildcard(obj) {
9432 if (obj && obj.__esModule) {
9438 for (var key in obj) {
9439 if (Object.prototype.hasOwnProperty.call(obj, key)) {
9440 var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
9442 if (desc.get || desc.set) {
9443 Object.defineProperty(newObj, key, desc);
9445 newObj[key] = obj[key];
9451 newObj.default = obj;
9456 var deprecationWarningShown = false;
9458 function getDefs(chalk) {
9461 marker: chalk.red.bold,
9462 message: chalk.red.bold
9466 var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
9468 function getMarkerLines(loc, source, opts) {
9469 var startLoc = Object.assign({
9473 var endLoc = Object.assign({}, startLoc, loc.end);
9475 var _ref = opts || {},
9476 _ref$linesAbove = _ref.linesAbove,
9477 linesAbove = _ref$linesAbove === void 0 ? 2 : _ref$linesAbove,
9478 _ref$linesBelow = _ref.linesBelow,
9479 linesBelow = _ref$linesBelow === void 0 ? 3 : _ref$linesBelow;
9481 var startLine = startLoc.line;
9482 var startColumn = startLoc.column;
9483 var endLine = endLoc.line;
9484 var endColumn = endLoc.column;
9485 var start = Math.max(startLine - (linesAbove + 1), 0);
9486 var end = Math.min(source.length, endLine + linesBelow);
9488 if (startLine === -1) {
9492 if (endLine === -1) {
9493 end = source.length;
9496 var lineDiff = endLine - startLine;
9497 var markerLines = {};
9500 for (var i = 0; i <= lineDiff; i++) {
9501 var lineNumber = i + startLine;
9504 markerLines[lineNumber] = true;
9505 } else if (i === 0) {
9506 var sourceLength = source[lineNumber - 1].length;
9507 markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
9508 } else if (i === lineDiff) {
9509 markerLines[lineNumber] = [0, endColumn];
9511 var _sourceLength = source[lineNumber - i].length;
9512 markerLines[lineNumber] = [0, _sourceLength];
9516 if (startColumn === endColumn) {
9518 markerLines[startLine] = [startColumn, 0];
9520 markerLines[startLine] = true;
9523 markerLines[startLine] = [startColumn, endColumn - startColumn];
9534 function codeFrameColumns(rawLines, loc) {
9535 var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
9536 var highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight().shouldHighlight)(opts);
9537 var chalk = (0, _highlight().getChalk)(opts);
9538 var defs = getDefs(chalk);
9540 var maybeHighlight = function maybeHighlight(chalkFn, string) {
9541 return highlighted ? chalkFn(string) : string;
9544 var lines = rawLines.split(NEWLINE);
9546 var _getMarkerLines = getMarkerLines(loc, lines, opts),
9547 start = _getMarkerLines.start,
9548 end = _getMarkerLines.end,
9549 markerLines = _getMarkerLines.markerLines;
9551 var hasColumns = loc.start && typeof loc.start.column === "number";
9552 var numberMaxWidth = String(end).length;
9553 var highlightedLines = highlighted ? (0, _highlight().default)(rawLines, opts) : rawLines;
9554 var frame = highlightedLines.split(NEWLINE).slice(start, end).map(function (line, index) {
9555 var number = start + 1 + index;
9556 var paddedNumber = ` ${number}`.slice(-numberMaxWidth);
9557 var gutter = ` ${paddedNumber} | `;
9558 var hasMarker = markerLines[number];
9559 var lastMarkerLine = !markerLines[number + 1];
9562 var markerLine = "";
9564 if (Array.isArray(hasMarker)) {
9565 var markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
9566 var numberOfMarkers = hasMarker[1] || 1;
9567 markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
9569 if (lastMarkerLine && opts.message) {
9570 markerLine += " " + maybeHighlight(defs.message, opts.message);
9574 return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
9576 return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;
9580 if (opts.message && !hasColumns) {
9581 frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
9585 return chalk.reset(frame);
9591 function _default(rawLines, lineNumber, colNumber) {
9592 var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
9594 if (!deprecationWarningShown) {
9595 deprecationWarningShown = true;
9596 var message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
9598 if (process.emitWarning) {
9599 process.emitWarning(message, "DeprecationWarning");
9601 var deprecationError = new Error(message);
9602 deprecationError.name = "DeprecationWarning";
9603 console.warn(new Error(message));
9607 colNumber = Math.max(colNumber, 0);
9614 return codeFrameColumns(rawLines, location, opts);
9617 unwrapExports(lib$2);
9618 var lib_1$1 = lib$2.codeFrameColumns;
9620 var ConfigError$1 = errors.ConfigError;
9621 var locStart$1 = loc.locStart,
9622 locEnd$1 = loc.locEnd; // Use defineProperties()/getOwnPropertyDescriptor() to prevent
9623 // triggering the parsers getters.
9625 var ownNames = Object.getOwnPropertyNames;
9626 var ownDescriptor = Object.getOwnPropertyDescriptor;
9628 function getParsers(options) {
9630 var _iteratorNormalCompletion = true;
9631 var _didIteratorError = false;
9632 var _iteratorError = undefined;
9635 for (var _iterator = options.plugins[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
9636 var plugin = _step.value;
9638 if (!plugin.parsers) {
9642 var _iteratorNormalCompletion2 = true;
9643 var _didIteratorError2 = false;
9644 var _iteratorError2 = undefined;
9647 for (var _iterator2 = ownNames(plugin.parsers)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
9648 var name = _step2.value;
9649 Object.defineProperty(parsers, name, ownDescriptor(plugin.parsers, name));
9652 _didIteratorError2 = true;
9653 _iteratorError2 = err;
9656 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
9657 _iterator2.return();
9660 if (_didIteratorError2) {
9661 throw _iteratorError2;
9667 _didIteratorError = true;
9668 _iteratorError = err;
9671 if (!_iteratorNormalCompletion && _iterator.return != null) {
9675 if (_didIteratorError) {
9676 throw _iteratorError;
9684 function resolveParser(opts, parsers) {
9685 parsers = parsers || getParsers(opts);
9687 if (typeof opts.parser === "function") {
9688 // Custom parser API always works with JavaScript.
9691 astFormat: "estree",
9692 locStart: locStart$1,
9697 if (typeof opts.parser === "string") {
9698 if (Object.prototype.hasOwnProperty.call(parsers, opts.parser)) {
9699 return parsers[opts.parser];
9701 /* istanbul ignore next */
9707 parse: require(path$2.resolve(process.cwd(), opts.parser)),
9708 astFormat: "estree",
9709 locStart: locStart$1,
9713 /* istanbul ignore next */
9714 throw new ConfigError$1(`Couldn't resolve parser "${opts.parser}"`);
9720 function parse(text, opts) {
9721 var parsers = getParsers(opts); // Create a new object {parserName: parseFn}. Uses defineProperty() to only call
9722 // the parsers getters when actually calling the parser `parse` function.
9724 var parsersForCustomParserApi = Object.keys(parsers).reduce(function (object, parserName) {
9725 return Object.defineProperty(object, parserName, {
9729 return parsers[parserName].parse;
9734 var parser = resolveParser(opts, parsers);
9737 if (parser.preprocess) {
9738 text = parser.preprocess(text, opts);
9743 ast: parser.parse(text, parsersForCustomParserApi, opts)
9746 var loc = error.loc;
9749 var codeFrame = lib$2;
9750 error.codeFrame = codeFrame.codeFrameColumns(text, loc, {
9753 error.message += "\n" + error.codeFrame;
9756 /* istanbul ignore next */
9768 var UndefinedParserError$1 = errors.UndefinedParserError;
9769 var getSupportInfo$1 = support.getSupportInfo;
9770 var resolveParser$1 = parser.resolveParser;
9771 var hiddenDefaults = {
9772 astFormat: "estree",
9774 originalText: undefined,
9777 }; // Copy options and fill in default values.
9779 function normalize$1(options, opts) {
9781 var rawOptions = Object.assign({}, options);
9782 var supportOptions = getSupportInfo$1(null, {
9783 plugins: options.plugins,
9784 showUnreleased: true,
9785 showDeprecated: true
9787 var defaults = supportOptions.reduce(function (reduced, optionInfo) {
9788 return optionInfo.default !== undefined ? Object.assign(reduced, {
9789 [optionInfo.name]: optionInfo.default
9791 }, Object.assign({}, hiddenDefaults));
9793 if (!rawOptions.parser) {
9794 if (!rawOptions.filepath) {
9795 var logger = opts.logger || console;
9796 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.");
9797 rawOptions.parser = "babel";
9799 rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins);
9801 if (!rawOptions.parser) {
9802 throw new UndefinedParserError$1(`No parser could be inferred for file: ${rawOptions.filepath}`);
9807 var parser = resolveParser$1(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(function (x) {
9808 return x.name === "parser";
9813 rawOptions.astFormat = parser.astFormat;
9814 rawOptions.locEnd = parser.locEnd;
9815 rawOptions.locStart = parser.locStart;
9816 var plugin = getPlugin(rawOptions);
9817 rawOptions.printer = plugin.printers[rawOptions.astFormat];
9818 var pluginDefaults = supportOptions.filter(function (optionInfo) {
9819 return optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name] !== undefined;
9820 }).reduce(function (reduced, optionInfo) {
9821 return Object.assign(reduced, {
9822 [optionInfo.name]: optionInfo.pluginDefaults[plugin.name]
9825 var mixedDefaults = Object.assign({}, defaults, pluginDefaults);
9826 Object.keys(mixedDefaults).forEach(function (k) {
9827 if (rawOptions[k] == null) {
9828 rawOptions[k] = mixedDefaults[k];
9832 if (rawOptions.parser === "json") {
9833 rawOptions.trailingComma = "none";
9836 return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({
9837 passThrough: Object.keys(hiddenDefaults)
9841 function getPlugin(options) {
9842 var astFormat = options.astFormat;
9845 throw new Error("getPlugin() requires astFormat to be set");
9848 var printerPlugin = options.plugins.find(function (plugin) {
9849 return plugin.printers && plugin.printers[astFormat];
9852 if (!printerPlugin) {
9853 throw new Error(`Couldn't find plugin for AST format "${astFormat}"`);
9856 return printerPlugin;
9859 function getInterpreter(filepath) {
9860 if (typeof filepath !== "string") {
9867 fd = fs$1.openSync(filepath, "r");
9873 var liner = new readlines(fd);
9874 var firstLine = liner.next().toString("utf8"); // #!/bin/env node, #!/usr/bin/env node
9876 var m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/);
9880 } // #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node
9883 var m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/);
9891 // There are some weird cases where paths are missing, causing Jest
9892 // failures. It's unclear what these correspond to in the real world.
9896 // There are some weird cases where paths are missing, causing Jest
9897 // failures. It's unclear what these correspond to in the real world.
9899 } catch (err) {// nop
9904 function inferParser(filepath, plugins) {
9905 var filepathParts = normalizePath(filepath).split("/");
9906 var filename = filepathParts[filepathParts.length - 1].toLowerCase(); // If the file has no extension, we can try to infer the language from the
9907 // interpreter in the shebang line, if any; but since this requires FS access,
9910 var language = getSupportInfo$1(null, {
9912 }).languages.find(function (language) {
9913 return language.since !== null && (language.extensions && language.extensions.some(function (extension) {
9914 return filename.endsWith(extension);
9915 }) || language.filenames && language.filenames.find(function (name) {
9916 return name.toLowerCase() === filename;
9917 }) || filename.indexOf(".") === -1 && language.interpreters && language.interpreters.indexOf(getInterpreter(filepath)) !== -1);
9919 return language && language.parsers[0];
9923 normalize: normalize$1,
9928 function massageAST(ast, options, parent) {
9929 if (Array.isArray(ast)) {
9930 return ast.map(function (e) {
9931 return massageAST(e, options, parent);
9932 }).filter(function (e) {
9937 if (!ast || typeof ast !== "object") {
9943 for (var _i = 0, _Object$keys = Object.keys(ast); _i < _Object$keys.length; _i++) {
9944 var key = _Object$keys[_i];
9946 if (typeof ast[key] !== "function") {
9947 newObj[key] = massageAST(ast[key], options, ast);
9951 if (options.printer.massageAstNode) {
9952 var result = options.printer.massageAstNode(ast, newObj, parent);
9954 if (result === null) {
9966 var massageAst = massageAST;
9969 * @param {Doc[]} parts
9974 function concat(parts) {
9975 // access the internals of a document directly.
9976 // if(parts.length === 1) {
9977 // // If it's a single document, no need to concat it.
9988 * @param {Doc} contents
9993 function indent(contents) {
10001 * @param {number} n
10002 * @param {Doc} contents
10007 function align(n, contents) {
10016 * @param {Doc} contents
10017 * @param {object} [opts] - TBD ???
10022 function group(contents, opts) {
10028 contents: contents,
10029 break: !!opts.shouldBreak,
10030 expandedStates: opts.expandedStates
10034 * @param {Doc} contents
10039 function dedentToRoot(contents) {
10040 return align(-Infinity, contents);
10043 * @param {Doc} contents
10048 function markAsRoot(contents) {
10049 // @ts-ignore - TBD ???:
10055 * @param {Doc} contents
10060 function dedent(contents) {
10061 return align(-1, contents);
10064 * @param {Doc[]} states
10065 * @param {object} [opts] - TBD ???
10070 function conditionalGroup(states, opts) {
10071 return group(states[0], Object.assign(opts || {}, {
10072 expandedStates: states
10076 * @param {Doc[]} parts
10081 function fill(parts) {
10089 * @param {Doc} [breakContents]
10090 * @param {Doc} [flatContents]
10091 * @param {object} [opts] - TBD ???
10096 function ifBreak(breakContents, flatContents, opts) {
10103 groupId: opts.groupId
10107 * @param {Doc} contents
10112 function lineSuffix(contents) {
10115 type: "line-suffix",
10120 var lineSuffixBoundary = {
10121 type: "line-suffix-boundary"
10123 var breakParent = {
10124 type: "break-parent"
10136 var hardline = concat([{
10140 var literalline = concat([{
10147 placeholder: Symbol("cursor")
10151 * @param {Doc[]} arr
10155 function join(sep, arr) {
10158 for (var i = 0; i < arr.length; i++) {
10166 return concat(res);
10170 * @param {number} size
10171 * @param {number} tabWidth
10175 function addAlignmentToDoc(doc, size, tabWidth) {
10179 // Use indent to add tabs for all the levels of tabs we need
10180 for (var i = 0; i < Math.floor(size / tabWidth); ++i) {
10181 aligned = indent(aligned);
10182 } // Use align for all the spaces that are needed
10185 aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current
10186 // indentation, so we use -Infinity to reset the indentation to 0
10188 aligned = align(-Infinity, aligned);
10194 var docBuilders = {
10205 lineSuffixBoundary,
10218 var ansiRegex = function ansiRegex(options) {
10219 options = Object.assign({
10222 var pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|');
10223 return new RegExp(pattern, options.onlyFirst ? undefined : 'g');
10226 var stripAnsi = function stripAnsi(string) {
10227 return typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
10230 var stripAnsi_1 = stripAnsi;
10231 var default_1$1 = stripAnsi;
10232 stripAnsi_1.default = default_1$1;
10234 /* eslint-disable yoda */
10236 var isFullwidthCodePoint = function isFullwidthCodePoint(codePoint) {
10237 if (Number.isNaN(codePoint)) {
10239 } // Code points are derived from:
10240 // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
10243 if (codePoint >= 0x1100 && (codePoint <= 0x115F || // Hangul Jamo
10244 codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET
10245 codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET
10246 // CJK Radicals Supplement .. Enclosed CJK Letters and Months
10247 0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
10248 0x3250 <= codePoint && codePoint <= 0x4DBF || // CJK Unified Ideographs .. Yi Radicals
10249 0x4E00 <= codePoint && codePoint <= 0xA4C6 || // Hangul Jamo Extended-A
10250 0xA960 <= codePoint && codePoint <= 0xA97C || // Hangul Syllables
10251 0xAC00 <= codePoint && codePoint <= 0xD7A3 || // CJK Compatibility Ideographs
10252 0xF900 <= codePoint && codePoint <= 0xFAFF || // Vertical Forms
10253 0xFE10 <= codePoint && codePoint <= 0xFE19 || // CJK Compatibility Forms .. Small Form Variants
10254 0xFE30 <= codePoint && codePoint <= 0xFE6B || // Halfwidth and Fullwidth Forms
10255 0xFF01 <= codePoint && codePoint <= 0xFF60 || 0xFFE0 <= codePoint && codePoint <= 0xFFE6 || // Kana Supplement
10256 0x1B000 <= codePoint && codePoint <= 0x1B001 || // Enclosed Ideographic Supplement
10257 0x1F200 <= codePoint && codePoint <= 0x1F251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
10258 0x20000 <= codePoint && codePoint <= 0x3FFFD)) {
10265 var isFullwidthCodePoint_1 = isFullwidthCodePoint;
10266 var default_1$2 = isFullwidthCodePoint;
10267 isFullwidthCodePoint_1.default = default_1$2;
10269 var emojiRegex = function emojiRegex() {
10270 // https://mths.be/emoji
10271 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;
10274 var stringWidth = function stringWidth(string) {
10275 string = string.replace(emojiRegex(), ' ');
10277 if (typeof string !== 'string' || string.length === 0) {
10281 string = stripAnsi_1(string);
10284 for (var i = 0; i < string.length; i++) {
10285 var code = string.codePointAt(i); // Ignore control characters
10287 if (code <= 0x1F || code >= 0x7F && code <= 0x9F) {
10289 } // Ignore combining characters
10292 if (code >= 0x300 && code <= 0x36F) {
10297 if (code > 0xFFFF) {
10301 width += isFullwidthCodePoint_1(code) ? 2 : 1;
10307 var stringWidth_1 = stringWidth; // TODO: remove this in the next major version
10309 var default_1$3 = stringWidth;
10310 stringWidth_1.default = default_1$3;
10312 var notAsciiRegex = /[^\x20-\x7F]/;
10314 function isExportDeclaration(node) {
10316 switch (node.type) {
10317 case "ExportDefaultDeclaration":
10318 case "ExportDefaultSpecifier":
10319 case "DeclareExportDeclaration":
10320 case "ExportNamedDeclaration":
10321 case "ExportAllDeclaration":
10329 function getParentExportDeclaration(path) {
10330 var parentNode = path.getParentNode();
10332 if (path.getName() === "declaration" && isExportDeclaration(parentNode)) {
10339 function getPenultimate(arr) {
10340 if (arr.length > 1) {
10341 return arr[arr.length - 2];
10347 * @typedef {{backwards?: boolean}} SkipOptions
10351 * @param {string | RegExp} chars
10352 * @returns {(text: string, index: number | false, opts?: SkipOptions) => number | false}
10356 function skip(chars) {
10357 return function (text, index, opts) {
10358 var backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having
10359 // to check for failures (did someone say monads?).
10361 if (index === false) {
10365 var length = text.length;
10366 var cursor = index;
10368 while (cursor >= 0 && cursor < length) {
10369 var c = text.charAt(cursor);
10371 if (chars instanceof RegExp) {
10372 if (!chars.test(c)) {
10375 } else if (chars.indexOf(c) === -1) {
10379 backwards ? cursor-- : cursor++;
10382 if (cursor === -1 || cursor === length) {
10383 // If we reached the beginning or end of the file, return the
10384 // out-of-bounds cursor. It's up to the caller to handle this
10385 // correctly. We don't want to indicate `false` though if it
10386 // actually skipped valid characters.
10394 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
10398 var skipWhitespace = skip(/\s/);
10400 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
10403 var skipSpaces = skip(" \t");
10405 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
10408 var skipToLineEnd = skip(",; \t");
10410 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
10413 var skipEverythingButNewLine = skip(/[^\r\n]/);
10415 * @param {string} text
10416 * @param {number | false} index
10417 * @returns {number | false}
10420 function skipInlineComment(text, index) {
10421 if (index === false) {
10425 if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") {
10426 for (var i = index + 2; i < text.length; ++i) {
10427 if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") {
10436 * @param {string} text
10437 * @param {number | false} index
10438 * @returns {number | false}
10442 function skipTrailingComment(text, index) {
10443 if (index === false) {
10447 if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") {
10448 return skipEverythingButNewLine(text, index);
10452 } // This one doesn't use the above helper function because it wants to
10453 // test \r\n in order and `skip` doesn't support ordering and we only
10454 // want to skip one newline. It's simple to implement.
10457 * @param {string} text
10458 * @param {number | false} index
10459 * @param {SkipOptions=} opts
10460 * @returns {number | false}
10464 function skipNewline(text, index, opts) {
10465 var backwards = opts && opts.backwards;
10467 if (index === false) {
10471 var atIndex = text.charAt(index);
10474 if (text.charAt(index - 1) === "\r" && atIndex === "\n") {
10478 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
10482 if (atIndex === "\r" && text.charAt(index + 1) === "\n") {
10486 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
10494 * @param {string} text
10495 * @param {number} index
10496 * @param {SkipOptions=} opts
10497 * @returns {boolean}
10501 function hasNewline(text, index, opts) {
10503 var idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
10504 var idx2 = skipNewline(text, idx, opts);
10505 return idx !== idx2;
10508 * @param {string} text
10509 * @param {number} start
10510 * @param {number} end
10511 * @returns {boolean}
10515 function hasNewlineInRange(text, start, end) {
10516 for (var i = start; i < end; ++i) {
10517 if (text.charAt(i) === "\n") {
10523 } // Note: this function doesn't ignore leading comments unlike isNextLineEmpty
10527 * @param {string} text
10529 * @param {(node: N) => number} locStart
10533 function isPreviousLineEmpty(text, node, locStart) {
10534 /** @type {number | false} */
10535 var idx = locStart(node) - 1;
10536 idx = skipSpaces(text, idx, {
10539 idx = skipNewline(text, idx, {
10542 idx = skipSpaces(text, idx, {
10545 var idx2 = skipNewline(text, idx, {
10548 return idx !== idx2;
10551 * @param {string} text
10552 * @param {number} index
10553 * @returns {boolean}
10557 function isNextLineEmptyAfterIndex(text, index) {
10558 /** @type {number | false} */
10560 /** @type {number | false} */
10564 while (idx !== oldIdx) {
10565 // We need to skip all the potential trailing inline comments
10567 idx = skipToLineEnd(text, idx);
10568 idx = skipInlineComment(text, idx);
10569 idx = skipSpaces(text, idx);
10572 idx = skipTrailingComment(text, idx);
10573 idx = skipNewline(text, idx);
10574 return idx !== false && hasNewline(text, idx);
10578 * @param {string} text
10580 * @param {(node: N) => number} locEnd
10581 * @returns {boolean}
10585 function isNextLineEmpty(text, node, locEnd) {
10586 return isNextLineEmptyAfterIndex(text, locEnd(node));
10589 * @param {string} text
10590 * @param {number} idx
10591 * @returns {number | false}
10595 function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) {
10596 /** @type {number | false} */
10598 /** @type {number | false} */
10602 while (nextIdx !== oldIdx) {
10604 nextIdx = skipSpaces(text, nextIdx);
10605 nextIdx = skipInlineComment(text, nextIdx);
10606 nextIdx = skipTrailingComment(text, nextIdx);
10607 nextIdx = skipNewline(text, nextIdx);
10614 * @param {string} text
10616 * @param {(node: N) => number} locEnd
10617 * @returns {number | false}
10621 function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) {
10622 return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node));
10626 * @param {string} text
10628 * @param {(node: N) => number} locEnd
10629 * @returns {string}
10633 function getNextNonSpaceNonCommentCharacter(text, node, locEnd) {
10634 return text.charAt( // @ts-ignore => TBD: can return false, should we define a fallback?
10635 getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd));
10638 * @param {string} text
10639 * @param {number} index
10640 * @param {SkipOptions=} opts
10641 * @returns {boolean}
10645 function hasSpaces(text, index, opts) {
10647 var idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
10648 return idx !== index;
10651 * @param {{range?: [number, number], start?: number}} node
10652 * @param {number} index
10656 function setLocStart(node, index) {
10658 node.range[0] = index;
10660 node.start = index;
10664 * @param {{range?: [number, number], end?: number}} node
10665 * @param {number} index
10669 function setLocEnd(node, index) {
10671 node.range[1] = index;
10677 var PRECEDENCE = {};
10678 [["|>"], ["??"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach(function (tier, i) {
10679 tier.forEach(function (op) {
10680 PRECEDENCE[op] = i;
10684 function getPrecedence(op) {
10685 return PRECEDENCE[op];
10688 var equalityOperators = {
10694 var multiplicativeOperators = {
10699 var bitshiftOperators = {
10705 function shouldFlatten(parentOp, nodeOp) {
10706 if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) {
10708 } // ** is right-associative
10709 // x ** y ** z --> x ** (y ** z)
10712 if (parentOp === "**") {
10714 } // x == y == z --> (x == y) == z
10717 if (equalityOperators[parentOp] && equalityOperators[nodeOp]) {
10719 } // x * y % z --> (x * y) % z
10722 if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) {
10724 } // x * y / z --> (x * y) / z
10725 // x / y * z --> (x / y) * z
10728 if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) {
10730 } // x << y << z --> (x << y) << z
10733 if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) {
10740 function isBitwiseOperator(operator) {
10741 return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&";
10742 } // Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr
10743 // holds) `function`, `class`, or `do {}`. Will be overzealous if there's
10744 // already necessary grouping parentheses.
10747 function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) {
10748 node = getLeftMost(node);
10750 switch (node.type) {
10751 case "FunctionExpression":
10752 case "ClassExpression":
10753 case "DoExpression":
10754 return forbidFunctionClassAndDoExpr;
10756 case "ObjectExpression":
10759 case "MemberExpression":
10760 case "OptionalMemberExpression":
10761 return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
10763 case "TaggedTemplateExpression":
10764 if (node.tag.type === "FunctionExpression") {
10765 // IIFEs are always already parenthesized
10769 return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr);
10771 case "CallExpression":
10772 case "OptionalCallExpression":
10773 if (node.callee.type === "FunctionExpression") {
10774 // IIFEs are always already parenthesized
10778 return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr);
10780 case "ConditionalExpression":
10781 return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr);
10783 case "UpdateExpression":
10784 return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr);
10786 case "BindExpression":
10787 return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
10789 case "SequenceExpression":
10790 return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr);
10792 case "TSAsExpression":
10793 return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr);
10800 function getLeftMost(node) {
10802 return getLeftMost(node.left);
10808 * @param {string} value
10809 * @param {number} tabWidth
10810 * @param {number=} startIndex
10811 * @returns {number}
10815 function getAlignmentSize(value, tabWidth, startIndex) {
10816 startIndex = startIndex || 0;
10819 for (var i = startIndex; i < value.length; ++i) {
10820 if (value[i] === "\t") {
10821 // Tabs behave in a way that they are aligned to the nearest
10822 // multiple of tabWidth:
10823 // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4
10824 // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ...
10825 size = size + tabWidth - size % tabWidth;
10834 * @param {string} value
10835 * @param {number} tabWidth
10836 * @returns {number}
10840 function getIndentSize(value, tabWidth) {
10841 var lastNewlineIndex = value.lastIndexOf("\n");
10843 if (lastNewlineIndex === -1) {
10847 return getAlignmentSize( // All the leading whitespaces
10848 value.slice(lastNewlineIndex + 1).match(/^[ \t]*/)[0], tabWidth);
10851 * @typedef {'"' | "'"} Quote
10856 * @param {string} raw
10857 * @param {Quote} preferredQuote
10862 function getPreferredQuote(raw, preferredQuote) {
10863 // `rawContent` is the string exactly like it appeared in the input source
10864 // code, without its enclosing quotes.
10865 var rawContent = raw.slice(1, -1);
10866 /** @type {{ quote: '"', regex: RegExp }} */
10872 /** @type {{ quote: "'", regex: RegExp }} */
10878 var preferred = preferredQuote === "'" ? single : double;
10879 var alternate = preferred === single ? double : single;
10880 var result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing
10881 // the string, we might want to enclose with the alternate quote instead, to
10882 // minimize the number of escaped quotes.
10884 if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) {
10885 var numPreferredQuotes = (rawContent.match(preferred.regex) || []).length;
10886 var numAlternateQuotes = (rawContent.match(alternate.regex) || []).length;
10887 result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote;
10893 function printString(raw, options, isDirectiveLiteral) {
10894 // `rawContent` is the string exactly like it appeared in the input source
10895 // code, without its enclosing quotes.
10896 var rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap
10897 // the quotes on a DirectiveLiteral.
10899 var canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'");
10900 /** @type {Quote} */
10902 var enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't
10903 // change the escape sequences they use.
10904 // See https://github.com/prettier/prettier/issues/1555
10905 // and https://tc39.github.io/ecma262/#directive-prologue
10907 if (isDirectiveLiteral) {
10908 if (canChangeDirectiveQuotes) {
10909 return enclosingQuote + rawContent + enclosingQuote;
10913 } // It might sound unnecessary to use `makeString` even if the string already
10914 // is enclosed with `enclosingQuote`, but it isn't. The string could contain
10915 // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes
10916 // sure that we consistently output the minimum amount of escaped quotes.
10919 return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.embeddedInHtml));
10922 * @param {string} rawContent
10923 * @param {Quote} enclosingQuote
10924 * @param {boolean=} unescapeUnnecessaryEscapes
10925 * @returns {string}
10929 function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) {
10930 var otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double).
10932 var regex = /\\([\s\S])|(['"])/g; // Escape and unescape single and double quotes as needed to be able to
10933 // enclose `rawContent` with `enclosingQuote`.
10935 var newContent = rawContent.replace(regex, function (match, escaped, quote) {
10936 // If we matched an escape, and the escaped character is a quote of the
10937 // other type than we intend to enclose the string with, there's no need for
10938 // it to be escaped, so return it _without_ the backslash.
10939 if (escaped === otherQuote) {
10941 } // If we matched an unescaped quote and it is of the _same_ type as we
10942 // intend to enclose the string with, it must be escaped, so return it with
10946 if (quote === enclosingQuote) {
10947 return "\\" + quote;
10952 } // Unescape any unnecessarily escaped character.
10953 // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27
10956 return unescapeUnnecessaryEscapes && /^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(escaped) ? escaped : "\\" + escaped;
10958 return enclosingQuote + newContent + enclosingQuote;
10961 function printNumber(rawNumber) {
10962 return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation.
10963 .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0).
10964 .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit.
10965 .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes.
10966 .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot.
10967 .replace(/\.(?=e|$)/, "");
10970 * @param {string} str
10971 * @param {string} target
10972 * @returns {number}
10976 function getMaxContinuousCount(str, target) {
10977 var results = str.match(new RegExp(`(${escapeStringRegexp(target)})+`, "g"));
10979 if (results === null) {
10983 return results.reduce(function (maxCount, result) {
10984 return Math.max(maxCount, result.length / target.length);
10988 function getMinNotPresentContinuousCount(str, target) {
10989 var matches = str.match(new RegExp(`(${escapeStringRegexp(target)})+`, "g"));
10991 if (matches === null) {
10995 var countPresent = new Map();
10997 var _iteratorNormalCompletion = true;
10998 var _didIteratorError = false;
10999 var _iteratorError = undefined;
11002 for (var _iterator = matches[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
11003 var match = _step.value;
11004 var count = match.length / target.length;
11005 countPresent.set(count, true);
11012 _didIteratorError = true;
11013 _iteratorError = err;
11016 if (!_iteratorNormalCompletion && _iterator.return != null) {
11017 _iterator.return();
11020 if (_didIteratorError) {
11021 throw _iteratorError;
11026 for (var i = 1; i < max; i++) {
11027 if (!countPresent.get(i)) {
11035 * @param {string} text
11036 * @returns {number}
11040 function getStringWidth(text) {
11043 } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width`
11046 if (!notAsciiRegex.test(text)) {
11047 return text.length;
11050 return stringWidth_1(text);
11053 function hasIgnoreComment(path) {
11054 var node = path.getValue();
11055 return hasNodeIgnoreComment(node);
11058 function hasNodeIgnoreComment(node) {
11059 return node && node.comments && node.comments.length > 0 && node.comments.some(function (comment) {
11060 return comment.value.trim() === "prettier-ignore";
11064 function matchAncestorTypes(path, types, index) {
11065 index = index || 0;
11066 types = types.slice();
11068 while (types.length) {
11069 var parent = path.getParentNode(index);
11070 var type = types.shift();
11072 if (!parent || parent.type !== type) {
11082 function addCommentHelper(node, comment) {
11083 var comments = node.comments || (node.comments = []);
11084 comments.push(comment);
11085 comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment
11086 // We already "print" it via the raw text, we don't need to re-print it as a
11089 if (node.type === "JSXText") {
11090 comment.printed = true;
11094 function addLeadingComment(node, comment) {
11095 comment.leading = true;
11096 comment.trailing = false;
11097 addCommentHelper(node, comment);
11100 function addDanglingComment(node, comment) {
11101 comment.leading = false;
11102 comment.trailing = false;
11103 addCommentHelper(node, comment);
11106 function addTrailingComment(node, comment) {
11107 comment.leading = false;
11108 comment.trailing = true;
11109 addCommentHelper(node, comment);
11112 function isWithinParentArrayProperty(path, propertyName) {
11113 var node = path.getValue();
11114 var parent = path.getParentNode();
11116 if (parent == null) {
11120 if (!Array.isArray(parent[propertyName])) {
11124 var key = path.getName();
11125 return parent[propertyName][key] === node;
11128 function replaceEndOfLineWith(text, replacement) {
11130 var _iteratorNormalCompletion2 = true;
11131 var _didIteratorError2 = false;
11132 var _iteratorError2 = undefined;
11135 for (var _iterator2 = text.split("\n")[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
11136 var part = _step2.value;
11138 if (parts.length !== 0) {
11139 parts.push(replacement);
11145 _didIteratorError2 = true;
11146 _iteratorError2 = err;
11149 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
11150 _iterator2.return();
11153 if (_didIteratorError2) {
11154 throw _iteratorError2;
11163 replaceEndOfLineWith,
11165 getMaxContinuousCount,
11166 getMinNotPresentContinuousCount,
11170 isExportDeclaration,
11171 getParentExportDeclaration,
11174 getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
11175 getNextNonSpaceNonCommentCharacterIndex,
11176 getNextNonSpaceNonCommentCharacter,
11181 skipEverythingButNewLine,
11183 skipTrailingComment,
11185 isNextLineEmptyAfterIndex,
11187 isPreviousLineEmpty,
11193 startsWithNoLookaheadToken,
11200 hasNodeIgnoreComment,
11202 matchAncestorTypes,
11204 addDanglingComment,
11205 addTrailingComment,
11206 isWithinParentArrayProperty
11209 function guessEndOfLine(text) {
11210 var index = text.indexOf("\r");
11213 return text.charAt(index + 1) === "\n" ? "crlf" : "cr";
11219 function convertEndOfLineToChars(value) {
11234 convertEndOfLineToChars
11237 var getStringWidth$1 = util.getStringWidth;
11238 var convertEndOfLineToChars$1 = endOfLine.convertEndOfLineToChars;
11239 var concat$1 = docBuilders.concat,
11240 fill$1 = docBuilders.fill,
11241 cursor$1 = docBuilders.cursor;
11242 /** @type {Record<symbol, typeof MODE_BREAK | typeof MODE_FLAT>} */
11245 var MODE_BREAK = 1;
11248 function rootIndent() {
11256 function makeIndent(ind, options) {
11257 return generateInd(ind, {
11262 function makeAlign(ind, n, options) {
11263 return n === -Infinity ? ind.root || rootIndent() : n < 0 ? generateInd(ind, {
11265 }, options) : !n ? ind : n.type === "root" ? Object.assign({}, ind, {
11267 }) : typeof n === "string" ? generateInd(ind, {
11268 type: "stringAlign",
11270 }, options) : generateInd(ind, {
11271 type: "numberAlign",
11276 function generateInd(ind, newPart, options) {
11277 var queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart);
11281 var lastSpaces = 0;
11282 var _iteratorNormalCompletion = true;
11283 var _didIteratorError = false;
11284 var _iteratorError = undefined;
11287 for (var _iterator = queue[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
11288 var part = _step.value;
11290 switch (part.type) {
11294 if (options.useTabs) {
11297 addSpaces(options.tabWidth);
11302 case "stringAlign":
11305 length += part.n.length;
11308 case "numberAlign":
11310 lastSpaces += part.n;
11313 /* istanbul ignore next */
11316 throw new Error(`Unexpected type '${part.type}'`);
11320 _didIteratorError = true;
11321 _iteratorError = err;
11324 if (!_iteratorNormalCompletion && _iterator.return != null) {
11325 _iterator.return();
11328 if (_didIteratorError) {
11329 throw _iteratorError;
11335 return Object.assign({}, ind, {
11341 function addTabs(count) {
11342 value += "\t".repeat(count);
11343 length += options.tabWidth * count;
11346 function addSpaces(count) {
11347 value += " ".repeat(count);
11352 if (options.useTabs) {
11359 function flushTabs() {
11360 if (lastTabs > 0) {
11367 function flushSpaces() {
11368 if (lastSpaces > 0) {
11369 addSpaces(lastSpaces);
11375 function resetLast() {
11381 function trim$1(out) {
11382 if (out.length === 0) {
11386 var trimCount = 0; // Trim whitespace at the end of line
11388 while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[ \t]*$/)) {
11389 trimCount += out.pop().length;
11392 if (out.length && typeof out[out.length - 1] === "string") {
11393 var trimmed = out[out.length - 1].replace(/[ \t]*$/, "");
11394 trimCount += out[out.length - 1].length - trimmed.length;
11395 out[out.length - 1] = trimmed;
11401 function fits(next, restCommands, width, options, mustBeFlat) {
11402 var restIdx = restCommands.length;
11403 var cmds = [next]; // `out` is only used for width counting because `trim` requires to look
11404 // backwards for space characters.
11408 while (width >= 0) {
11409 if (cmds.length === 0) {
11410 if (restIdx === 0) {
11414 cmds.push(restCommands[restIdx - 1]);
11419 var x = cmds.pop();
11424 if (typeof doc === "string") {
11426 width -= getStringWidth$1(doc);
11428 switch (doc.type) {
11430 for (var i = doc.parts.length - 1; i >= 0; i--) {
11431 cmds.push([ind, mode, doc.parts[i]]);
11437 cmds.push([makeIndent(ind, options), mode, doc.contents]);
11441 cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
11445 width += trim$1(out);
11449 if (mustBeFlat && doc.break) {
11453 cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]);
11456 groupModeMap[doc.id] = cmds[cmds.length - 1][1];
11462 for (var _i = doc.parts.length - 1; _i >= 0; _i--) {
11463 cmds.push([ind, mode, doc.parts[_i]]);
11470 var groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
11472 if (groupMode === MODE_BREAK) {
11473 if (doc.breakContents) {
11474 cmds.push([ind, mode, doc.breakContents]);
11478 if (groupMode === MODE_FLAT) {
11479 if (doc.flatContents) {
11480 cmds.push([ind, mode, doc.flatContents]);
11514 function printDocToString(doc, options) {
11516 var width = options.printWidth;
11517 var newLine = convertEndOfLineToChars$1(options.endOfLine);
11518 var pos = 0; // cmds is basically a stack. We've turned a recursive call into a
11519 // while loop which is much faster. The while loop below adds new
11520 // cmds to the array instead of recursively calling `print`.
11522 var cmds = [[rootIndent(), MODE_BREAK, doc]];
11524 var shouldRemeasure = false;
11525 var lineSuffix = [];
11527 while (cmds.length !== 0) {
11528 var x = cmds.pop();
11533 if (typeof _doc === "string") {
11535 pos += getStringWidth$1(_doc);
11537 switch (_doc.type) {
11539 out.push(cursor$1.placeholder);
11543 for (var i = _doc.parts.length - 1; i >= 0; i--) {
11544 cmds.push([ind, mode, _doc.parts[i]]);
11550 cmds.push([makeIndent(ind, options), mode, _doc.contents]);
11554 cmds.push([makeAlign(ind, _doc.n, options), mode, _doc.contents]);
11558 pos -= trim$1(out);
11564 if (!shouldRemeasure) {
11565 cmds.push([ind, _doc.break ? MODE_BREAK : MODE_FLAT, _doc.contents]);
11573 shouldRemeasure = false;
11574 var next = [ind, MODE_FLAT, _doc.contents];
11575 var rem = width - pos;
11577 if (!_doc.break && fits(next, cmds, rem, options)) {
11580 // Expanded states are a rare case where a document
11581 // can manually provide multiple representations of
11582 // itself. It provides an array of documents
11583 // going from the least expanded (most flattened)
11584 // representation first to the most expanded. If a
11585 // group has these, we need to manually go through
11586 // these states and find the first one that fits.
11587 if (_doc.expandedStates) {
11588 var mostExpanded = _doc.expandedStates[_doc.expandedStates.length - 1];
11591 cmds.push([ind, MODE_BREAK, mostExpanded]);
11594 for (var _i2 = 1; _i2 < _doc.expandedStates.length + 1; _i2++) {
11595 if (_i2 >= _doc.expandedStates.length) {
11596 cmds.push([ind, MODE_BREAK, mostExpanded]);
11599 var state = _doc.expandedStates[_i2];
11600 var cmd = [ind, MODE_FLAT, state];
11602 if (fits(cmd, cmds, rem, options)) {
11610 cmds.push([ind, MODE_BREAK, _doc.contents]);
11619 groupModeMap[_doc.id] = cmds[cmds.length - 1][1];
11623 // Fills each line with as much code as possible before moving to a new
11624 // line with the same indentation.
11626 // Expects doc.parts to be an array of alternating content and
11627 // whitespace. The whitespace contains the linebreaks.
11630 // ["I", line, "love", line, "monkeys"]
11632 // [{ type: group, ... }, softline, { type: group, ... }]
11634 // It uses this parts structure to handle three main layout cases:
11635 // * The first two content items fit on the same line without
11637 // -> output the first content item and the whitespace "flat".
11638 // * Only the first content item fits on the line without breaking
11639 // -> output the first content item "flat" and the whitespace with
11641 // * Neither content item fits on the line without breaking
11642 // -> output the first content item and the whitespace with "break".
11646 var _rem = width - pos;
11648 var parts = _doc.parts;
11650 if (parts.length === 0) {
11654 var content = parts[0];
11655 var contentFlatCmd = [ind, MODE_FLAT, content];
11656 var contentBreakCmd = [ind, MODE_BREAK, content];
11657 var contentFits = fits(contentFlatCmd, [], _rem, options, true);
11659 if (parts.length === 1) {
11661 cmds.push(contentFlatCmd);
11663 cmds.push(contentBreakCmd);
11669 var whitespace = parts[1];
11670 var whitespaceFlatCmd = [ind, MODE_FLAT, whitespace];
11671 var whitespaceBreakCmd = [ind, MODE_BREAK, whitespace];
11673 if (parts.length === 2) {
11675 cmds.push(whitespaceFlatCmd);
11676 cmds.push(contentFlatCmd);
11678 cmds.push(whitespaceBreakCmd);
11679 cmds.push(contentBreakCmd);
11683 } // At this point we've handled the first pair (context, separator)
11684 // and will create a new fill doc for the rest of the content.
11685 // Ideally we wouldn't mutate the array here but coping all the
11686 // elements to a new array would make this algorithm quadratic,
11687 // which is unusable for large arrays (e.g. large texts in JSX).
11690 parts.splice(0, 2);
11691 var remainingCmd = [ind, mode, fill$1(parts)];
11692 var secondContent = parts[0];
11693 var firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$1([content, whitespace, secondContent])];
11694 var firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], _rem, options, true);
11696 if (firstAndSecondContentFits) {
11697 cmds.push(remainingCmd);
11698 cmds.push(whitespaceFlatCmd);
11699 cmds.push(contentFlatCmd);
11700 } else if (contentFits) {
11701 cmds.push(remainingCmd);
11702 cmds.push(whitespaceBreakCmd);
11703 cmds.push(contentFlatCmd);
11705 cmds.push(remainingCmd);
11706 cmds.push(whitespaceBreakCmd);
11707 cmds.push(contentBreakCmd);
11715 var groupMode = _doc.groupId ? groupModeMap[_doc.groupId] : mode;
11717 if (groupMode === MODE_BREAK) {
11718 if (_doc.breakContents) {
11719 cmds.push([ind, mode, _doc.breakContents]);
11723 if (groupMode === MODE_FLAT) {
11724 if (_doc.flatContents) {
11725 cmds.push([ind, mode, _doc.flatContents]);
11732 case "line-suffix":
11733 lineSuffix.push([ind, mode, _doc.contents]);
11736 case "line-suffix-boundary":
11737 if (lineSuffix.length > 0) {
11738 cmds.push([ind, mode, {
11757 // This line was forced into the output even if we
11758 // were in flattened mode, so we need to tell the next
11759 // group that no matter what, it needs to remeasure
11760 // because the previous measurement didn't accurately
11761 // capture the entire expression (this is necessary
11762 // for nested groups)
11763 shouldRemeasure = true;
11769 if (lineSuffix.length) {
11770 cmds.push([ind, mode, _doc]);
11771 [].push.apply(cmds, lineSuffix.reverse());
11776 if (_doc.literal) {
11778 out.push(newLine, ind.root.value);
11779 pos = ind.root.length;
11785 pos -= trim$1(out);
11786 out.push(newLine + ind.value);
11798 var cursorPlaceholderIndex = out.indexOf(cursor$1.placeholder);
11800 if (cursorPlaceholderIndex !== -1) {
11801 var otherCursorPlaceholderIndex = out.indexOf(cursor$1.placeholder, cursorPlaceholderIndex + 1);
11802 var beforeCursor = out.slice(0, cursorPlaceholderIndex).join("");
11803 var aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join("");
11804 var afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join("");
11806 formatted: beforeCursor + aroundCursor + afterCursor,
11807 cursorNodeStart: beforeCursor.length,
11808 cursorNodeText: aroundCursor
11813 formatted: out.join("")
11821 var traverseDocOnExitStackMarker = {};
11823 function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) {
11824 var docsStack = [doc];
11826 while (docsStack.length !== 0) {
11827 var _doc = docsStack.pop();
11829 if (_doc === traverseDocOnExitStackMarker) {
11830 onExit(docsStack.pop());
11834 var shouldRecurse = true;
11837 if (onEnter(_doc) === false) {
11838 shouldRecurse = false;
11843 docsStack.push(_doc);
11844 docsStack.push(traverseDocOnExitStackMarker);
11847 if (shouldRecurse) {
11848 // When there are multiple parts to process,
11849 // the parts need to be pushed onto the stack in reverse order,
11850 // so that they are processed in the original order
11851 // when the stack is popped.
11852 if (_doc.type === "concat" || _doc.type === "fill") {
11853 for (var ic = _doc.parts.length, i = ic - 1; i >= 0; --i) {
11854 docsStack.push(_doc.parts[i]);
11856 } else if (_doc.type === "if-break") {
11857 if (_doc.flatContents) {
11858 docsStack.push(_doc.flatContents);
11861 if (_doc.breakContents) {
11862 docsStack.push(_doc.breakContents);
11864 } else if (_doc.type === "group" && _doc.expandedStates) {
11865 if (shouldTraverseConditionalGroups) {
11866 for (var _ic = _doc.expandedStates.length, _i = _ic - 1; _i >= 0; --_i) {
11867 docsStack.push(_doc.expandedStates[_i]);
11870 docsStack.push(_doc.contents);
11872 } else if (_doc.contents) {
11873 docsStack.push(_doc.contents);
11879 function mapDoc(doc, cb) {
11880 if (doc.type === "concat" || doc.type === "fill") {
11881 var parts = doc.parts.map(function (part) {
11882 return mapDoc(part, cb);
11884 return cb(Object.assign({}, doc, {
11887 } else if (doc.type === "if-break") {
11888 var breakContents = doc.breakContents && mapDoc(doc.breakContents, cb);
11889 var flatContents = doc.flatContents && mapDoc(doc.flatContents, cb);
11890 return cb(Object.assign({}, doc, {
11894 } else if (doc.contents) {
11895 var contents = mapDoc(doc.contents, cb);
11896 return cb(Object.assign({}, doc, {
11904 function findInDoc(doc, fn, defaultValue) {
11905 var result = defaultValue;
11906 var hasStopped = false;
11908 function findInDocOnEnterFn(doc) {
11909 var maybeResult = fn(doc);
11911 if (maybeResult !== undefined) {
11913 result = maybeResult;
11921 traverseDoc(doc, findInDocOnEnterFn);
11925 function isEmpty(n) {
11926 return typeof n === "string" && n.length === 0;
11929 function isLineNextFn(doc) {
11930 if (typeof doc === "string") {
11934 if (doc.type === "line") {
11939 function isLineNext(doc) {
11940 return findInDoc(doc, isLineNextFn, false);
11943 function willBreakFn(doc) {
11944 if (doc.type === "group" && doc.break) {
11948 if (doc.type === "line" && doc.hard) {
11952 if (doc.type === "break-parent") {
11957 function willBreak(doc) {
11958 return findInDoc(doc, willBreakFn, false);
11961 function breakParentGroup(groupStack) {
11962 if (groupStack.length > 0) {
11963 var parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because
11964 // the user is expected to manually handle what breaks.
11966 if (!parentGroup.expandedStates) {
11967 parentGroup.break = true;
11974 function propagateBreaks(doc) {
11975 var alreadyVisitedSet = new Set();
11976 var groupStack = [];
11978 function propagateBreaksOnEnterFn(doc) {
11979 if (doc.type === "break-parent") {
11980 breakParentGroup(groupStack);
11983 if (doc.type === "group") {
11984 groupStack.push(doc);
11986 if (alreadyVisitedSet.has(doc)) {
11990 alreadyVisitedSet.add(doc);
11994 function propagateBreaksOnExitFn(doc) {
11995 if (doc.type === "group") {
11996 var group = groupStack.pop();
11999 breakParentGroup(groupStack);
12004 traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn,
12005 /* shouldTraverseConditionalGroups */
12009 function removeLinesFn(doc) {
12010 // Force this doc into flat mode by statically converting all
12011 // lines into spaces (or soft lines into nothing). Hard lines
12012 // should still output because there's too great of a chance
12013 // of breaking existing assumptions otherwise.
12014 if (doc.type === "line" && !doc.hard) {
12015 return doc.soft ? "" : " ";
12016 } else if (doc.type === "if-break") {
12017 return doc.flatContents || "";
12023 function removeLines(doc) {
12024 return mapDoc(doc, removeLinesFn);
12027 function stripTrailingHardline(doc) {
12028 // HACK remove ending hardline, original PR: #1984
12029 if (doc.type === "concat" && doc.parts.length !== 0) {
12030 var lastPart = doc.parts[doc.parts.length - 1];
12032 if (lastPart.type === "concat") {
12033 if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") {
12036 parts: doc.parts.slice(0, -1)
12042 parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart))
12059 stripTrailingHardline
12062 function flattenDoc(doc) {
12063 if (doc.type === "concat") {
12066 for (var i = 0; i < doc.parts.length; ++i) {
12067 var doc2 = doc.parts[i];
12069 if (typeof doc2 !== "string" && doc2.type === "concat") {
12070 [].push.apply(res, flattenDoc(doc2).parts);
12072 var flattened = flattenDoc(doc2);
12074 if (flattened !== "") {
12075 res.push(flattened);
12080 return Object.assign({}, doc, {
12083 } else if (doc.type === "if-break") {
12084 return Object.assign({}, doc, {
12085 breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null,
12086 flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null
12088 } else if (doc.type === "group") {
12089 return Object.assign({}, doc, {
12090 contents: flattenDoc(doc.contents),
12091 expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates
12093 } else if (doc.contents) {
12094 return Object.assign({}, doc, {
12095 contents: flattenDoc(doc.contents)
12102 function printDoc(doc) {
12103 if (typeof doc === "string") {
12104 return JSON.stringify(doc);
12107 if (doc.type === "line") {
12109 return "literalline";
12123 if (doc.type === "break-parent") {
12124 return "breakParent";
12127 if (doc.type === "trim") {
12131 if (doc.type === "concat") {
12132 return "[" + doc.parts.map(printDoc).join(", ") + "]";
12135 if (doc.type === "indent") {
12136 return "indent(" + printDoc(doc.contents) + ")";
12139 if (doc.type === "align") {
12140 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) + ")";
12143 if (doc.type === "if-break") {
12144 return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")";
12147 if (doc.type === "group") {
12148 if (doc.expandedStates) {
12149 return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])";
12152 return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")";
12155 if (doc.type === "fill") {
12156 return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")";
12159 if (doc.type === "line-suffix") {
12160 return "lineSuffix(" + printDoc(doc.contents) + ")";
12163 if (doc.type === "line-suffix-boundary") {
12164 return "lineSuffixBoundary";
12167 throw new Error("Unknown doc type " + doc.type);
12171 printDocToDebug: function printDocToDebug(doc) {
12172 return printDoc(flattenDoc(doc));
12177 builders: docBuilders,
12178 printer: docPrinter,
12183 var mapDoc$1 = doc.utils.mapDoc;
12185 function isNextLineEmpty$1(text, node, options) {
12186 return util.isNextLineEmpty(text, node, options.locEnd);
12189 function isPreviousLineEmpty$1(text, node, options) {
12190 return util.isPreviousLineEmpty(text, node, options.locStart);
12193 function getNextNonSpaceNonCommentCharacterIndex$1(text, node, options) {
12194 return util.getNextNonSpaceNonCommentCharacterIndex(text, node, options.locEnd);
12198 getMaxContinuousCount: util.getMaxContinuousCount,
12199 getStringWidth: util.getStringWidth,
12200 getAlignmentSize: util.getAlignmentSize,
12201 getIndentSize: util.getIndentSize,
12203 skipWhitespace: util.skipWhitespace,
12204 skipSpaces: util.skipSpaces,
12205 skipNewline: util.skipNewline,
12206 skipToLineEnd: util.skipToLineEnd,
12207 skipEverythingButNewLine: util.skipEverythingButNewLine,
12208 skipInlineComment: util.skipInlineComment,
12209 skipTrailingComment: util.skipTrailingComment,
12210 hasNewline: util.hasNewline,
12211 hasNewlineInRange: util.hasNewlineInRange,
12212 hasSpaces: util.hasSpaces,
12213 isNextLineEmpty: isNextLineEmpty$1,
12214 isNextLineEmptyAfterIndex: util.isNextLineEmptyAfterIndex,
12215 isPreviousLineEmpty: isPreviousLineEmpty$1,
12216 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1,
12218 // TODO: remove in 2.0, we already exposed it in docUtils
12219 makeString: util.makeString,
12220 addLeadingComment: util.addLeadingComment,
12221 addDanglingComment: util.addDanglingComment,
12222 addTrailingComment: util.addTrailingComment
12225 var _require$$0$builders = doc.builders,
12226 concat$2 = _require$$0$builders.concat,
12227 hardline$1 = _require$$0$builders.hardline,
12228 breakParent$1 = _require$$0$builders.breakParent,
12229 indent$1 = _require$$0$builders.indent,
12230 lineSuffix$1 = _require$$0$builders.lineSuffix,
12231 join$1 = _require$$0$builders.join,
12232 cursor$2 = _require$$0$builders.cursor;
12233 var hasNewline$1 = util.hasNewline,
12234 skipNewline$1 = util.skipNewline,
12235 isPreviousLineEmpty$2 = util.isPreviousLineEmpty;
12236 var addLeadingComment$1 = utilShared.addLeadingComment,
12237 addDanglingComment$1 = utilShared.addDanglingComment,
12238 addTrailingComment$1 = utilShared.addTrailingComment;
12239 var childNodesCacheKey = Symbol("child-nodes");
12241 function getSortedChildNodes(node, options, resultArray) {
12246 var printer = options.printer,
12247 locStart = options.locStart,
12248 locEnd = options.locEnd;
12251 if (node && printer.canAttachComment && printer.canAttachComment(node)) {
12252 // This reverse insertion sort almost always takes constant
12253 // time because we almost always (maybe always?) append the
12254 // nodes in order anyway.
12257 for (i = resultArray.length - 1; i >= 0; --i) {
12258 if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) {
12263 resultArray.splice(i + 1, 0, node);
12266 } else if (node[childNodesCacheKey]) {
12267 return node[childNodesCacheKey];
12272 if (printer.getCommentChildNodes) {
12273 childNodes = printer.getCommentChildNodes(node);
12274 } else if (node && typeof node === "object") {
12275 childNodes = Object.keys(node).filter(function (n) {
12276 return n !== "enclosingNode" && n !== "precedingNode" && n !== "followingNode";
12277 }).map(function (n) {
12286 if (!resultArray) {
12287 Object.defineProperty(node, childNodesCacheKey, {
12288 value: resultArray = [],
12293 childNodes.forEach(function (childNode) {
12294 getSortedChildNodes(childNode, options, resultArray);
12296 return resultArray;
12297 } // As efficiently as possible, decorate the comment object with
12298 // .precedingNode, .enclosingNode, and/or .followingNode properties, at
12299 // least one of which is guaranteed to be defined.
12302 function decorateComment(node, comment, options) {
12303 var locStart = options.locStart,
12304 locEnd = options.locEnd;
12305 var childNodes = getSortedChildNodes(node, options);
12307 var followingNode; // Time to dust off the old binary search robes and wizard hat.
12310 var right = childNodes.length;
12312 while (left < right) {
12313 var middle = left + right >> 1;
12314 var child = childNodes[middle];
12316 if (locStart(child) - locStart(comment) <= 0 && locEnd(comment) - locEnd(child) <= 0) {
12317 // The comment is completely contained by this child node.
12318 comment.enclosingNode = child;
12319 decorateComment(child, comment, options);
12320 return; // Abandon the binary search at this level.
12323 if (locEnd(child) - locStart(comment) <= 0) {
12324 // This child node falls completely before the comment.
12325 // Because we will never consider this node or any nodes
12326 // before it again, this node must be the closest preceding
12327 // node we have encountered so far.
12328 precedingNode = child;
12333 if (locEnd(comment) - locStart(child) <= 0) {
12334 // This child node falls completely after the comment.
12335 // Because we will never consider this node or any nodes after
12336 // it again, this node must be the closest following node we
12337 // have encountered so far.
12338 followingNode = child;
12342 /* istanbul ignore next */
12345 throw new Error("Comment location overlaps with node location");
12346 } // We don't want comments inside of different expressions inside of the same
12347 // template literal to move to another expression.
12350 if (comment.enclosingNode && comment.enclosingNode.type === "TemplateLiteral") {
12351 var quasis = comment.enclosingNode.quasis;
12352 var commentIndex = findExpressionIndexForComment(quasis, comment, options);
12354 if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) {
12355 precedingNode = null;
12358 if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) {
12359 followingNode = null;
12363 if (precedingNode) {
12364 comment.precedingNode = precedingNode;
12367 if (followingNode) {
12368 comment.followingNode = followingNode;
12372 function attach(comments, ast, text, options) {
12373 if (!Array.isArray(comments)) {
12377 var tiesToBreak = [];
12378 var locStart = options.locStart,
12379 locEnd = options.locEnd;
12380 comments.forEach(function (comment, i) {
12381 if (options.parser === "json" || options.parser === "json5" || options.parser === "__js_expression" || options.parser === "__vue_expression") {
12382 if (locStart(comment) - locStart(ast) <= 0) {
12383 addLeadingComment$1(ast, comment);
12387 if (locEnd(comment) - locEnd(ast) >= 0) {
12388 addTrailingComment$1(ast, comment);
12393 decorateComment(ast, comment, options);
12394 var precedingNode = comment.precedingNode,
12395 enclosingNode = comment.enclosingNode,
12396 followingNode = comment.followingNode;
12397 var pluginHandleOwnLineComment = options.printer.handleComments && options.printer.handleComments.ownLine ? options.printer.handleComments.ownLine : function () {
12400 var pluginHandleEndOfLineComment = options.printer.handleComments && options.printer.handleComments.endOfLine ? options.printer.handleComments.endOfLine : function () {
12403 var pluginHandleRemainingComment = options.printer.handleComments && options.printer.handleComments.remaining ? options.printer.handleComments.remaining : function () {
12406 var isLastComment = comments.length - 1 === i;
12408 if (hasNewline$1(text, locStart(comment), {
12411 // If a comment exists on its own line, prefer a leading comment.
12412 // We also need to check if it's the first line of the file.
12413 if (pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)) ; else if (followingNode) {
12414 // Always a leading comment.
12415 addLeadingComment$1(followingNode, comment);
12416 } else if (precedingNode) {
12417 addTrailingComment$1(precedingNode, comment);
12418 } else if (enclosingNode) {
12419 addDanglingComment$1(enclosingNode, comment);
12421 // There are no nodes, let's attach it to the root of the ast
12423 /* istanbul ignore next */
12424 addDanglingComment$1(ast, comment);
12426 } else if (hasNewline$1(text, locEnd(comment))) {
12427 if (pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode) {
12428 // There is content before this comment on the same line, but
12429 // none after it, so prefer a trailing comment of the previous node.
12430 addTrailingComment$1(precedingNode, comment);
12431 } else if (followingNode) {
12432 addLeadingComment$1(followingNode, comment);
12433 } else if (enclosingNode) {
12434 addDanglingComment$1(enclosingNode, comment);
12436 // There are no nodes, let's attach it to the root of the ast
12438 /* istanbul ignore next */
12439 addDanglingComment$1(ast, comment);
12442 if (pluginHandleRemainingComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode && followingNode) {
12443 // Otherwise, text exists both before and after the comment on
12444 // the same line. If there is both a preceding and following
12445 // node, use a tie-breaking algorithm to determine if it should
12446 // be attached to the next or previous node. In the last case,
12447 // simply attach the right node;
12448 var tieCount = tiesToBreak.length;
12450 if (tieCount > 0) {
12451 var lastTie = tiesToBreak[tieCount - 1];
12453 if (lastTie.followingNode !== comment.followingNode) {
12454 breakTies(tiesToBreak, text, options);
12458 tiesToBreak.push(comment);
12459 } else if (precedingNode) {
12460 addTrailingComment$1(precedingNode, comment);
12461 } else if (followingNode) {
12462 addLeadingComment$1(followingNode, comment);
12463 } else if (enclosingNode) {
12464 addDanglingComment$1(enclosingNode, comment);
12466 // There are no nodes, let's attach it to the root of the ast
12468 /* istanbul ignore next */
12469 addDanglingComment$1(ast, comment);
12473 breakTies(tiesToBreak, text, options);
12474 comments.forEach(function (comment) {
12475 // These node references were useful for breaking ties, but we
12476 // don't need them anymore, and they create cycles in the AST that
12477 // may lead to infinite recursion if we don't delete them here.
12478 delete comment.precedingNode;
12479 delete comment.enclosingNode;
12480 delete comment.followingNode;
12484 function breakTies(tiesToBreak, text, options) {
12485 var tieCount = tiesToBreak.length;
12487 if (tieCount === 0) {
12491 var _tiesToBreak$ = tiesToBreak[0],
12492 precedingNode = _tiesToBreak$.precedingNode,
12493 followingNode = _tiesToBreak$.followingNode;
12494 var gapEndPos = options.locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps
12495 // between the tied comments. In order to qualify as leading, a
12496 // comment must be separated from followingNode by an unbroken series of
12497 // gaps (or other comments). Gaps should only contain whitespace or open
12500 var indexOfFirstLeadingComment;
12502 for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) {
12503 var comment = tiesToBreak[indexOfFirstLeadingComment - 1];
12504 assert$1.strictEqual(comment.precedingNode, precedingNode);
12505 assert$1.strictEqual(comment.followingNode, followingNode);
12506 var gap = text.slice(options.locEnd(comment), gapEndPos);
12508 if (/^[\s(]*$/.test(gap)) {
12509 gapEndPos = options.locStart(comment);
12511 // The gap string contained something other than whitespace or open
12517 tiesToBreak.forEach(function (comment, i) {
12518 if (i < indexOfFirstLeadingComment) {
12519 addTrailingComment$1(precedingNode, comment);
12521 addLeadingComment$1(followingNode, comment);
12524 tiesToBreak.length = 0;
12527 function printComment(commentPath, options) {
12528 var comment = commentPath.getValue();
12529 comment.printed = true;
12530 return options.printer.printComment(commentPath, options);
12533 function findExpressionIndexForComment(quasis, comment, options) {
12534 var startPos = options.locStart(comment) - 1;
12536 for (var i = 1; i < quasis.length; ++i) {
12537 if (startPos < getQuasiRange(quasis[i]).start) {
12540 } // We haven't found it, it probably means that some of the locations are off.
12541 // Let's just return the first one.
12543 /* istanbul ignore next */
12549 function getQuasiRange(expr) {
12550 if (expr.start !== undefined) {
12560 start: expr.range[0],
12565 function printLeadingComment(commentPath, print, options) {
12566 var comment = commentPath.getValue();
12567 var contents = printComment(commentPath, options);
12573 var isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // Leading block comments should see if they need to stay on the
12574 // same line or not.
12577 return concat$2([contents, hasNewline$1(options.originalText, options.locEnd(comment)) ? hardline$1 : " "]);
12580 return concat$2([contents, hardline$1]);
12583 function printTrailingComment(commentPath, print, options) {
12584 var comment = commentPath.getValue();
12585 var contents = printComment(commentPath, options);
12591 var isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // We don't want the line to break
12592 // when the parentParentNode is a ClassDeclaration/-Expression
12593 // And the parentNode is in the superClass property
12595 var parentNode = commentPath.getNode(1);
12596 var parentParentNode = commentPath.getNode(2);
12597 var isParentSuperClass = parentParentNode && (parentParentNode.type === "ClassDeclaration" || parentParentNode.type === "ClassExpression") && parentParentNode.superClass === parentNode;
12599 if (hasNewline$1(options.originalText, options.locStart(comment), {
12602 // This allows comments at the end of nested structures:
12608 // Those kinds of comments are almost always leading comments, but
12609 // here it doesn't go "outside" the block and turns it into a
12610 // trailing comment for `2`. We can simulate the above by checking
12611 // if this a comment on its own line; normal trailing comments are
12612 // always at the end of another expression.
12613 var isLineBeforeEmpty = isPreviousLineEmpty$2(options.originalText, comment, options.locStart);
12614 return lineSuffix$1(concat$2([hardline$1, isLineBeforeEmpty ? hardline$1 : "", contents]));
12615 } else if (isBlock || isParentSuperClass) {
12616 // Trailing block comments never need a newline
12617 return concat$2([" ", contents]);
12620 return concat$2([lineSuffix$1(concat$2([" ", contents])), !isBlock ? breakParent$1 : ""]);
12623 function printDanglingComments(path, options, sameIndent, filter) {
12625 var node = path.getValue();
12627 if (!node || !node.comments) {
12631 path.each(function (commentPath) {
12632 var comment = commentPath.getValue();
12634 if (comment && !comment.leading && !comment.trailing && (!filter || filter(comment))) {
12635 parts.push(printComment(commentPath, options));
12639 if (parts.length === 0) {
12644 return join$1(hardline$1, parts);
12647 return indent$1(concat$2([hardline$1, join$1(hardline$1, parts)]));
12650 function prependCursorPlaceholder(path, options, printed) {
12651 if (path.getNode() === options.cursorNode && path.getValue()) {
12652 return concat$2([cursor$2, printed, cursor$2]);
12658 function printComments(path, print, options, needsSemi) {
12659 var value = path.getValue();
12660 var printed = print(path);
12661 var comments = value && value.comments;
12663 if (!comments || comments.length === 0) {
12664 return prependCursorPlaceholder(path, options, printed);
12667 var leadingParts = [];
12668 var trailingParts = [needsSemi ? ";" : "", printed];
12669 path.each(function (commentPath) {
12670 var comment = commentPath.getValue();
12671 var leading = comment.leading,
12672 trailing = comment.trailing;
12675 var contents = printLeadingComment(commentPath, print, options);
12681 leadingParts.push(contents);
12682 var text = options.originalText;
12683 var index = skipNewline$1(text, options.locEnd(comment));
12685 if (index !== false && hasNewline$1(text, index)) {
12686 leadingParts.push(hardline$1);
12688 } else if (trailing) {
12689 trailingParts.push(printTrailingComment(commentPath, print, options));
12692 return prependCursorPlaceholder(path, options, concat$2(leadingParts.concat(trailingParts)));
12698 printDanglingComments,
12699 getSortedChildNodes
12702 function FastPath(value) {
12703 assert$1.ok(this instanceof FastPath);
12704 this.stack = [value];
12705 } // The name of the current property is always the penultimate element of
12706 // this.stack, and always a String.
12709 FastPath.prototype.getName = function getName() {
12710 var s = this.stack;
12711 var len = s.length;
12715 } // Since the name is always a string, null is a safe sentinel value to
12716 // return if we do not know the name of the (root) value.
12718 /* istanbul ignore next */
12722 }; // The value of the current property is always the final element of
12726 FastPath.prototype.getValue = function getValue() {
12727 var s = this.stack;
12728 return s[s.length - 1];
12731 function getNodeHelper(path, count) {
12732 var stackIndex = getNodeStackIndexHelper(path.stack, count);
12733 return stackIndex === -1 ? null : path.stack[stackIndex];
12736 function getNodeStackIndexHelper(stack, count) {
12737 for (var i = stack.length - 1; i >= 0; i -= 2) {
12738 var value = stack[i];
12740 if (value && !Array.isArray(value) && --count < 0) {
12748 FastPath.prototype.getNode = function getNode(count) {
12749 return getNodeHelper(this, ~~count);
12752 FastPath.prototype.getParentNode = function getParentNode(count) {
12753 return getNodeHelper(this, ~~count + 1);
12754 }; // Temporarily push properties named by string arguments given after the
12755 // callback function onto this.stack, then call the callback with a
12756 // reference to this (modified) FastPath object. Note that the stack will
12757 // be restored to its original state after the callback is finished, so it
12758 // is probably a mistake to retain a reference to the path.
12761 FastPath.prototype.call = function call(callback
12762 /*, name1, name2, ... */
12764 var s = this.stack;
12765 var origLen = s.length;
12766 var value = s[origLen - 1];
12767 var argc = arguments.length;
12769 for (var i = 1; i < argc; ++i) {
12770 var name = arguments[i];
12771 value = value[name];
12772 s.push(name, value);
12775 var result = callback(this);
12776 s.length = origLen;
12780 FastPath.prototype.callParent = function callParent(callback, count) {
12781 var stackIndex = getNodeStackIndexHelper(this.stack, ~~count + 1);
12782 var parentValues = this.stack.splice(stackIndex + 1);
12783 var result = callback(this);
12784 Array.prototype.push.apply(this.stack, parentValues);
12786 }; // Similar to FastPath.prototype.call, except that the value obtained by
12787 // accessing this.getValue()[name1][name2]... should be array-like. The
12788 // callback will be called with a reference to this path object for each
12789 // element of the array.
12792 FastPath.prototype.each = function each(callback
12793 /*, name1, name2, ... */
12795 var s = this.stack;
12796 var origLen = s.length;
12797 var value = s[origLen - 1];
12798 var argc = arguments.length;
12800 for (var i = 1; i < argc; ++i) {
12801 var name = arguments[i];
12802 value = value[name];
12803 s.push(name, value);
12806 for (var _i = 0; _i < value.length; ++_i) {
12808 s.push(_i, value[_i]); // If the callback needs to know the value of i, call
12809 // path.getName(), assuming path is the parameter name.
12816 s.length = origLen;
12817 }; // Similar to FastPath.prototype.each, except that the results of the
12818 // callback function invocations are stored in an array and returned at
12819 // the end of the iteration.
12822 FastPath.prototype.map = function map(callback
12823 /*, name1, name2, ... */
12825 var s = this.stack;
12826 var origLen = s.length;
12827 var value = s[origLen - 1];
12828 var argc = arguments.length;
12830 for (var i = 1; i < argc; ++i) {
12831 var name = arguments[i];
12832 value = value[name];
12833 s.push(name, value);
12836 var result = new Array(value.length);
12838 for (var _i2 = 0; _i2 < value.length; ++_i2) {
12839 if (_i2 in value) {
12840 s.push(_i2, value[_i2]);
12841 result[_i2] = callback(this, _i2);
12846 s.length = origLen;
12850 var fastPath = FastPath;
12852 var normalize$2 = options$1.normalize;
12854 function printSubtree(path, print, options, printAstToDoc) {
12855 if (options.printer.embed) {
12856 return options.printer.embed(path, print, function (text, partialNextOptions) {
12857 return textToDoc(text, partialNextOptions, options, printAstToDoc);
12862 function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc) {
12863 var nextOptions = normalize$2(Object.assign({}, parentOptions, partialNextOptions, {
12864 parentParser: parentOptions.parser,
12865 embeddedInHtml: !!(parentOptions.embeddedInHtml || parentOptions.parser === "html" || parentOptions.parser === "vue" || parentOptions.parser === "angular" || parentOptions.parser === "lwc"),
12870 var result = parser.parse(text, nextOptions);
12871 var ast = result.ast;
12872 text = result.text;
12873 var astComments = ast.comments;
12874 delete ast.comments;
12875 comments.attach(astComments, ast, text, nextOptions);
12876 return printAstToDoc(ast, nextOptions);
12879 var multiparser = {
12884 var docBuilders$1 = doc$1.builders;
12885 var concat$3 = docBuilders$1.concat;
12886 var hardline$2 = docBuilders$1.hardline;
12887 var addAlignmentToDoc$1 = docBuilders$1.addAlignmentToDoc;
12888 var docUtils$1 = doc$1.utils;
12890 * Takes an abstract syntax tree (AST) and recursively converts it to a
12891 * document (series of printing primitives).
12893 * This is done by descending down the AST recursively. The recursion
12894 * involves two functions that call each other:
12896 * 1. printGenerically(), which is defined as an inner function here.
12897 * It basically takes care of node caching.
12898 * 2. callPluginPrintFunction(), which checks for some options, and
12899 * ultimately calls the print() function provided by the plugin.
12901 * The plugin function will call printGenerically() again for child nodes
12902 * of the current node, which will do its housekeeping, then call the
12903 * plugin function again, and so on.
12905 * All the while, these functions pass a "path" variable around, which
12906 * is a stack-like data structure (FastPath) that maintains the current
12907 * state of the recursion. It is called "path", because it represents
12908 * the path to the current node through the Abstract Syntax Tree.
12911 function printAstToDoc(ast, options) {
12912 var alignmentSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
12913 var printer = options.printer;
12915 if (printer.preprocess) {
12916 ast = printer.preprocess(ast, options);
12919 var cache = new Map();
12921 function printGenerically(path, args) {
12922 var node = path.getValue();
12923 var shouldCache = node && typeof node === "object" && args === undefined;
12925 if (shouldCache && cache.has(node)) {
12926 return cache.get(node);
12927 } // We let JSXElement print its comments itself because it adds () around
12928 // UnionTypeAnnotation has to align the child without the comments
12933 if (printer.willPrintOwnComments && printer.willPrintOwnComments(path, options)) {
12934 res = callPluginPrintFunction(path, options, printGenerically, args);
12936 // printComments will call the plugin print function and check for
12937 // comments to print
12938 res = comments.printComments(path, function (p) {
12939 return callPluginPrintFunction(p, options, printGenerically, args);
12940 }, options, args && args.needsSemi);
12944 cache.set(node, res);
12950 var doc = printGenerically(new fastPath(ast));
12952 if (alignmentSize > 0) {
12953 // Add a hardline to make the indents take effect
12954 // It should be removed in index.js format()
12955 doc = addAlignmentToDoc$1(concat$3([hardline$2, doc]), alignmentSize, options.tabWidth);
12958 docUtils$1.propagateBreaks(doc);
12962 function callPluginPrintFunction(path, options, printPath, args) {
12963 assert$1.ok(path instanceof fastPath);
12964 var node = path.getValue();
12965 var printer = options.printer; // Escape hatch
12967 if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path)) {
12968 return options.originalText.slice(options.locStart(node), options.locEnd(node));
12973 // Potentially switch to a different parser
12974 var sub = multiparser.printSubtree(path, printPath, options, printAstToDoc);
12980 /* istanbul ignore if */
12981 if (process.env.PRETTIER_DEBUG) {
12983 } // Continue with current parser
12988 return printer.print(path, options, printPath, args);
12991 var astToDoc = printAstToDoc;
12993 function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) {
12994 var resultStartNode = startNodeAndParents.node;
12995 var resultEndNode = endNodeAndParents.node;
12997 if (resultStartNode === resultEndNode) {
12999 startNode: resultStartNode,
13000 endNode: resultEndNode
13004 var _iteratorNormalCompletion = true;
13005 var _didIteratorError = false;
13006 var _iteratorError = undefined;
13009 for (var _iterator = endNodeAndParents.parentNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
13010 var endParent = _step.value;
13012 if (endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node)) {
13013 resultEndNode = endParent;
13019 _didIteratorError = true;
13020 _iteratorError = err;
13023 if (!_iteratorNormalCompletion && _iterator.return != null) {
13024 _iterator.return();
13027 if (_didIteratorError) {
13028 throw _iteratorError;
13033 var _iteratorNormalCompletion2 = true;
13034 var _didIteratorError2 = false;
13035 var _iteratorError2 = undefined;
13038 for (var _iterator2 = startNodeAndParents.parentNodes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
13039 var startParent = _step2.value;
13041 if (startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node)) {
13042 resultStartNode = startParent;
13048 _didIteratorError2 = true;
13049 _iteratorError2 = err;
13052 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
13053 _iterator2.return();
13056 if (_didIteratorError2) {
13057 throw _iteratorError2;
13063 startNode: resultStartNode,
13064 endNode: resultEndNode
13068 function findNodeAtOffset(node, offset, options, predicate, parentNodes) {
13069 predicate = predicate || function () {
13073 parentNodes = parentNodes || [];
13074 var start = options.locStart(node, options.locStart);
13075 var end = options.locEnd(node, options.locEnd);
13077 if (start <= offset && offset <= end) {
13078 var _iteratorNormalCompletion3 = true;
13079 var _didIteratorError3 = false;
13080 var _iteratorError3 = undefined;
13083 for (var _iterator3 = comments.getSortedChildNodes(node, options)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
13084 var childNode = _step3.value;
13085 var childResult = findNodeAtOffset(childNode, offset, options, predicate, [node].concat(parentNodes));
13088 return childResult;
13092 _didIteratorError3 = true;
13093 _iteratorError3 = err;
13096 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
13097 _iterator3.return();
13100 if (_didIteratorError3) {
13101 throw _iteratorError3;
13106 if (predicate(node)) {
13109 parentNodes: parentNodes
13113 } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5
13116 function isSourceElement(opts, node) {
13117 if (node == null) {
13119 } // JS and JS like to avoid repetitions
13122 var jsSourceElements = ["FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015
13123 "ImportDeclaration", // Module
13124 "ExportDefaultDeclaration", // Module
13125 "ExportNamedDeclaration", // Module
13126 "ExportAllDeclaration", // Module
13127 "TypeAlias", // Flow
13128 "InterfaceDeclaration", // Flow, TypeScript
13129 "TypeAliasDeclaration", // TypeScript
13130 "ExportAssignment", // TypeScript
13131 "ExportDeclaration" // TypeScript
13133 var jsonSourceElements = ["ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"];
13134 var graphqlSourceElements = ["OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition"];
13136 switch (opts.parser) {
13140 return jsSourceElements.indexOf(node.type) > -1;
13143 return jsonSourceElements.indexOf(node.type) > -1;
13146 return graphqlSourceElements.indexOf(node.kind) > -1;
13149 return node.tag !== "root";
13155 function calculateRange(text, opts, ast) {
13156 // Contract the range so that it has non-whitespace characters at its endpoints.
13157 // This ensures we can format a range that doesn't end on a node.
13158 var rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd);
13159 var startNonWhitespace = Math.max(opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart);
13160 var endNonWhitespace;
13162 for (endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace) {
13163 if (text[endNonWhitespace - 1].match(/\S/)) {
13168 var startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace, opts, function (node) {
13169 return isSourceElement(opts, node);
13171 var endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace, opts, function (node) {
13172 return isSourceElement(opts, node);
13175 if (!startNodeAndParents || !endNodeAndParents) {
13182 var siblingAncestors = findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts);
13183 var startNode = siblingAncestors.startNode,
13184 endNode = siblingAncestors.endNode;
13185 var rangeStart = Math.min(opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart));
13186 var rangeEnd = Math.max(opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd));
13188 rangeStart: rangeStart,
13198 var require$$0$1 = getCjsExportFromNamespace(index_es6);
13200 var normalizeOptions$1 = options$1.normalize;
13201 var guessEndOfLine$1 = endOfLine.guessEndOfLine,
13202 convertEndOfLineToChars$2 = endOfLine.convertEndOfLineToChars;
13203 var mapDoc$2 = doc.utils.mapDoc,
13204 printDocToString$1 = doc.printer.printDocToString,
13205 printDocToDebug = doc.debug.printDocToDebug;
13206 var UTF8BOM = 0xfeff;
13207 var CURSOR = Symbol("cursor");
13208 var PLACEHOLDERS = {
13209 cursorOffset: "<<<PRETTIER_CURSOR>>>",
13210 rangeStart: "<<<PRETTIER_RANGE_START>>>",
13211 rangeEnd: "<<<PRETTIER_RANGE_END>>>"
13214 function ensureAllCommentsPrinted(astComments) {
13215 if (!astComments) {
13219 for (var i = 0; i < astComments.length; ++i) {
13220 if (astComments[i].value.trim() === "prettier-ignore") {
13221 // If there's a prettier-ignore, we're not printing that sub-tree so we
13222 // don't know if the comments was printed or not.
13227 astComments.forEach(function (comment) {
13228 if (!comment.printed) {
13229 throw new Error('Comment "' + comment.value.trim() + '" was not printed. Please report this error!');
13232 delete comment.printed;
13236 function attachComments(text, ast, opts) {
13237 var astComments = ast.comments;
13240 delete ast.comments;
13241 comments.attach(astComments, ast, text, opts);
13245 opts.originalText = opts.parser === "yaml" ? text : text.trimRight();
13246 return astComments;
13249 function coreFormat(text, opts, addAlignmentSize) {
13250 if (!text || !text.trim().length) {
13257 addAlignmentSize = addAlignmentSize || 0;
13258 var parsed = parser.parse(text, opts);
13259 var ast = parsed.ast;
13260 text = parsed.text;
13262 if (opts.cursorOffset >= 0) {
13263 var nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts);
13265 if (nodeResult && nodeResult.node) {
13266 opts.cursorNode = nodeResult.node;
13270 var astComments = attachComments(text, ast, opts);
13271 var doc = astToDoc(ast, opts, addAlignmentSize);
13272 var eol = convertEndOfLineToChars$2(opts.endOfLine);
13273 var result = printDocToString$1(opts.endOfLine === "lf" ? doc : mapDoc$2(doc, function (currentDoc) {
13274 return typeof currentDoc === "string" && currentDoc.indexOf("\n") !== -1 ? currentDoc.replace(/\n/g, eol) : currentDoc;
13276 ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline
13278 if (addAlignmentSize > 0) {
13279 var trimmed = result.formatted.trim();
13281 if (result.cursorNodeStart !== undefined) {
13282 result.cursorNodeStart -= result.formatted.indexOf(trimmed);
13285 result.formatted = trimmed + convertEndOfLineToChars$2(opts.endOfLine);
13288 if (opts.cursorOffset >= 0) {
13289 var oldCursorNodeStart;
13290 var oldCursorNodeText;
13291 var cursorOffsetRelativeToOldCursorNode;
13292 var newCursorNodeStart;
13293 var newCursorNodeText;
13295 if (opts.cursorNode && result.cursorNodeText) {
13296 oldCursorNodeStart = opts.locStart(opts.cursorNode);
13297 oldCursorNodeText = text.slice(oldCursorNodeStart, opts.locEnd(opts.cursorNode));
13298 cursorOffsetRelativeToOldCursorNode = opts.cursorOffset - oldCursorNodeStart;
13299 newCursorNodeStart = result.cursorNodeStart;
13300 newCursorNodeText = result.cursorNodeText;
13302 oldCursorNodeStart = 0;
13303 oldCursorNodeText = text;
13304 cursorOffsetRelativeToOldCursorNode = opts.cursorOffset;
13305 newCursorNodeStart = 0;
13306 newCursorNodeText = result.formatted;
13309 if (oldCursorNodeText === newCursorNodeText) {
13311 formatted: result.formatted,
13312 cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode
13314 } // diff old and new cursor node texts, with a special cursor
13315 // symbol inserted to find out where it moves to
13318 var oldCursorNodeCharArray = oldCursorNodeText.split("");
13319 oldCursorNodeCharArray.splice(cursorOffsetRelativeToOldCursorNode, 0, CURSOR);
13320 var newCursorNodeCharArray = newCursorNodeText.split("");
13321 var cursorNodeDiff = require$$0$1.diffArrays(oldCursorNodeCharArray, newCursorNodeCharArray);
13322 var cursorOffset = newCursorNodeStart;
13323 var _iteratorNormalCompletion = true;
13324 var _didIteratorError = false;
13325 var _iteratorError = undefined;
13328 for (var _iterator = cursorNodeDiff[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
13329 var entry = _step.value;
13331 if (entry.removed) {
13332 if (entry.value.indexOf(CURSOR) > -1) {
13336 cursorOffset += entry.count;
13340 _didIteratorError = true;
13341 _iteratorError = err;
13344 if (!_iteratorNormalCompletion && _iterator.return != null) {
13345 _iterator.return();
13348 if (_didIteratorError) {
13349 throw _iteratorError;
13355 formatted: result.formatted,
13361 formatted: result.formatted
13365 function formatRange(text, opts) {
13366 var parsed = parser.parse(text, opts);
13367 var ast = parsed.ast;
13368 text = parsed.text;
13369 var range = rangeUtil.calculateRange(text, opts, ast);
13370 var rangeStart = range.rangeStart;
13371 var rangeEnd = range.rangeEnd;
13372 var rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line.
13373 // This is so we can detect indentation correctly and restore it.
13374 // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0
13376 var rangeStart2 = Math.min(rangeStart, text.lastIndexOf("\n", rangeStart) + 1);
13377 var indentString = text.slice(rangeStart2, rangeStart);
13378 var alignmentSize = util.getAlignmentSize(indentString, opts.tabWidth);
13379 var rangeResult = coreFormat(rangeString, Object.assign({}, opts, {
13381 rangeEnd: Infinity,
13382 // track the cursor offset only if it's within our range
13383 cursorOffset: opts.cursorOffset >= rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart : -1
13384 }), alignmentSize); // Since the range contracts to avoid trailing whitespace,
13385 // we need to remove the newline that was inserted by the `format` call.
13387 var rangeTrimmed = rangeResult.formatted.trimRight();
13388 var rangeLeft = text.slice(0, rangeStart);
13389 var rangeRight = text.slice(rangeEnd);
13390 var cursorOffset = opts.cursorOffset;
13392 if (opts.cursorOffset >= rangeEnd) {
13393 // handle the case where the cursor was past the end of the range
13394 cursorOffset = opts.cursorOffset - rangeEnd + (rangeStart + rangeTrimmed.length);
13395 } else if (rangeResult.cursorOffset !== undefined) {
13396 // handle the case where the cursor was in the range
13397 cursorOffset = rangeResult.cursorOffset + rangeStart;
13398 } // keep the cursor as it was if it was before the start of the range
13403 if (opts.endOfLine === "lf") {
13404 formatted = rangeLeft + rangeTrimmed + rangeRight;
13406 var eol = convertEndOfLineToChars$2(opts.endOfLine);
13408 if (cursorOffset >= 0) {
13409 var parts = [rangeLeft, rangeTrimmed, rangeRight];
13411 var partOffset = cursorOffset;
13413 while (partIndex < parts.length) {
13414 var part = parts[partIndex];
13416 if (partOffset < part.length) {
13417 parts[partIndex] = parts[partIndex].slice(0, partOffset) + PLACEHOLDERS.cursorOffset + parts[partIndex].slice(partOffset);
13422 partOffset -= part.length;
13425 var newRangeLeft = parts[0],
13426 newRangeTrimmed = parts[1],
13427 newRangeRight = parts[2];
13428 formatted = (newRangeLeft.replace(/\n/g, eol) + newRangeTrimmed + newRangeRight.replace(/\n/g, eol)).replace(PLACEHOLDERS.cursorOffset, function (_, index) {
13429 cursorOffset = index;
13433 formatted = rangeLeft.replace(/\n/g, eol) + rangeTrimmed + rangeRight.replace(/\n/g, eol);
13443 function format(text, opts) {
13444 var selectedParser = parser.resolveParser(opts);
13445 var hasPragma = !selectedParser.hasPragma || selectedParser.hasPragma(text);
13447 if (opts.requirePragma && !hasPragma) {
13453 if (opts.endOfLine === "auto") {
13454 opts.endOfLine = guessEndOfLine$1(text);
13457 var hasCursor = opts.cursorOffset >= 0;
13458 var hasRangeStart = opts.rangeStart > 0;
13459 var hasRangeEnd = opts.rangeEnd < text.length; // get rid of CR/CRLF parsing
13461 if (text.indexOf("\r") !== -1) {
13462 var offsetKeys = [hasCursor && "cursorOffset", hasRangeStart && "rangeStart", hasRangeEnd && "rangeEnd"].filter(Boolean).sort(function (aKey, bKey) {
13463 return opts[aKey] - opts[bKey];
13466 for (var i = offsetKeys.length - 1; i >= 0; i--) {
13467 var key = offsetKeys[i];
13468 text = text.slice(0, opts[key]) + PLACEHOLDERS[key] + text.slice(opts[key]);
13471 text = text.replace(/\r\n?/g, "\n");
13473 var _loop = function _loop(_i) {
13474 var key = offsetKeys[_i];
13475 text = text.replace(PLACEHOLDERS[key], function (_, index) {
13481 for (var _i = 0; _i < offsetKeys.length; _i++) {
13486 var hasUnicodeBOM = text.charCodeAt(0) === UTF8BOM;
13488 if (hasUnicodeBOM) {
13489 text = text.substring(1);
13492 opts.cursorOffset++;
13495 if (hasRangeStart) {
13505 opts.cursorOffset = -1;
13508 if (opts.rangeStart < 0) {
13509 opts.rangeStart = 0;
13512 if (opts.rangeEnd > text.length) {
13513 opts.rangeEnd = text.length;
13516 var result = hasRangeStart || hasRangeEnd ? formatRange(text, opts) : coreFormat(opts.insertPragma && opts.printer.insertPragma && !hasPragma ? opts.printer.insertPragma(text) : text, opts);
13518 if (hasUnicodeBOM) {
13519 result.formatted = String.fromCharCode(UTF8BOM) + result.formatted;
13522 result.cursorOffset++;
13530 formatWithCursor(text, opts) {
13531 opts = normalizeOptions$1(opts);
13532 return format(text, opts);
13535 parse(text, opts, massage) {
13536 opts = normalizeOptions$1(opts);
13538 if (text.indexOf("\r") !== -1) {
13539 text = text.replace(/\r\n?/g, "\n");
13542 var parsed = parser.parse(text, opts);
13545 parsed.ast = massageAst(parsed.ast, opts);
13551 formatAST(ast, opts) {
13552 opts = normalizeOptions$1(opts);
13553 var doc = astToDoc(ast, opts);
13554 return printDocToString$1(doc, opts);
13557 // Doesn't handle shebang for now
13558 formatDoc(doc, opts) {
13559 var debug = printDocToDebug(doc);
13560 opts = normalizeOptions$1(Object.assign({}, opts, {
13563 return format(debug, opts).formatted;
13566 printToDoc(text, opts) {
13567 opts = normalizeOptions$1(opts);
13568 var parsed = parser.parse(text, opts);
13569 var ast = parsed.ast;
13570 text = parsed.text;
13571 attachComments(text, ast, opts);
13572 return astToDoc(ast, opts);
13575 printDocToString(doc, opts) {
13576 return printDocToString$1(doc, normalizeOptions$1(opts));
13581 // A simple implementation of make-array
13582 function make_array(subject) {
13583 return Array.isArray(subject) ? subject : [subject];
13586 var REGEX_BLANK_LINE = /^\s+$/;
13587 var REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
13588 var REGEX_LEADING_EXCAPED_HASH = /^\\#/;
13590 var KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
13591 /* istanbul ignore next */
13594 var define = function define(object, key, value) {
13595 return Object.defineProperty(object, key, {
13600 var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression
13601 // The cases are complicated, see test cases for details
13603 var sanitizeRange = function sanitizeRange(range) {
13604 return range.replace(REGEX_REGEXP_RANGE, function (match, from, to) {
13605 return from.charCodeAt(0) <= to.charCodeAt(0) ? match // Invalid range (out of order) which is ok for gitignore rules but
13606 // fatal for JavaScript regular expression, so eliminate it.
13609 }; // > If the pattern ends with a slash,
13610 // > it is removed for the purpose of the following description,
13611 // > but it would only find a match with a directory.
13612 // > In other words, foo/ will match a directory foo and paths underneath it,
13613 // > but will not match a regular file or a symbolic link foo
13614 // > (this is consistent with the way how pathspec works in general in Git).
13615 // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
13616 // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
13617 // you could use option `mark: true` with `glob`
13618 // '`foo/`' should not continue with the '`..`'
13621 var DEFAULT_REPLACER_PREFIX = [// > Trailing spaces are ignored unless they are quoted with backslash ("\")
13625 /\\?\s+$/, function (match) {
13626 return match.indexOf('\\') === 0 ? ' ' : '';
13627 }], // replace (\ ) with ' '
13628 [/\\\s/g, function () {
13630 }], // Escape metacharacters
13631 // which is written down by users but means special for regular expressions.
13632 // > There are 12 characters with special meanings:
13633 // > - the backslash \,
13634 // > - the caret ^,
13635 // > - the dollar sign $,
13636 // > - the period or dot .,
13637 // > - the vertical bar or pipe symbol |,
13638 // > - the question mark ?,
13639 // > - the asterisk or star *,
13640 // > - the plus sign +,
13641 // > - the opening parenthesis (,
13642 // > - the closing parenthesis ),
13643 // > - and the opening square bracket [,
13644 // > - the opening curly brace {,
13645 // > These special characters are often called "metacharacters".
13646 [/[\\^$.|*+(){]/g, function (match) {
13647 return `\\${match}`;
13648 }], [// > [abc] matches any character inside the brackets
13649 // > (in this case a, b, or c);
13650 /\[([^\]/]*)($|\])/g, function (match, p1, p2) {
13651 return p2 === ']' ? `[${sanitizeRange(p1)}]` : `\\${match}`;
13652 }], [// > a question mark (?) matches a single character
13653 /(?!\\)\?/g, function () {
13655 }], // leading slash
13656 [// > A leading slash matches the beginning of the pathname.
13657 // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
13658 // A leading slash matches the beginning of the pathname
13659 /^\//, function () {
13661 }], // replace special metacharacter slash after the leading slash
13662 [/\//g, function () {
13664 }], [// > A leading "**" followed by a slash means match in all directories.
13665 // > For example, "**/foo" matches file or directory "foo" anywhere,
13666 // > the same as pattern "foo".
13667 // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
13668 // > under directory "foo".
13669 // Notice that the '*'s have been replaced as '\\*'
13670 /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo'
13672 return '^(?:.*\\/)?';
13674 var DEFAULT_REPLACER_SUFFIX = [// starting
13675 [// there will be no leading '/'
13676 // (which has been replaced by section "leading slash")
13677 // If starts with '**', adding a '^' to the regular expression also works
13678 /^(?=[^^])/, function startingReplacer() {
13679 return !/\/(?!$)/.test(this) // > If the pattern does not contain a slash /,
13680 // > Git treats it as a shell glob pattern
13681 // Actually, if there is only a trailing slash,
13682 // git also treats it as a shell glob pattern
13683 ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for
13684 // > consumption by fnmatch(3)
13686 }], // two globstars
13687 [// Use lookahead assertions so that we could match more than one `'/**'`
13688 /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories
13689 // should not use '*', or it will be replaced by the next replacer
13690 // Check if it is not the last `'/**'`
13691 function (match, index, str) {
13692 return index + 6 < str.length // case: /**/
13693 // > A slash followed by two consecutive asterisks then a slash matches
13694 // > zero or more directories.
13695 // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
13697 ? '(?:\\/[^\\/]+)*' // case: /**
13698 // > A trailing `"/**"` matches everything inside.
13699 // #21: everything inside but it should not include the current folder
13701 }], // intermediate wildcards
13702 [// Never replace escaped '*'
13703 // ignore rule '\*' will match the path '*'
13705 // 'abc.*' -> skip this rule
13706 /(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js'
13707 // '*.js' doesn't match 'abc'
13708 function (match, p1) {
13709 return `${p1}[^\\/]*`;
13710 }], // trailing wildcard
13711 [/(\^|\\\/)?\\\*$/, function (match, p1) {
13712 var prefix = p1 // '\^':
13713 // '/*' does not match ''
13714 // '/*' does not match everything
13716 // 'abc/*' does not match 'abc/'
13717 ? `${p1}[^/]+` // 'a*' matches 'a'
13718 // 'a*' matches 'aa'
13720 return `${prefix}(?=$|\\/$)`;
13722 /\\\\\\/g, function () {
13725 var POSITIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [// 'f'
13737 [// 'js' will not match 'js.'
13738 // 'ab' will not match 'abc'
13739 /(?:[^*/])$/, // 'js*' will not match 'a.js'
13740 // 'js/' will not match 'a.js'
13741 // 'js' will match 'a.js' and 'a.js/'
13743 return `${match}(?=$|\\/)`;
13744 }]], DEFAULT_REPLACER_SUFFIX);
13745 var NEGATIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [// #24, #38
13746 // The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore)
13747 // A negative pattern without a trailing wildcard should not
13748 // re-include the things inside that directory.
13750 // ['node_modules/*', '!node_modules']
13751 // should ignore `node_modules/a.js`
13752 [/(?:[^*])$/, function (match) {
13753 return `${match}(?=$|\\/$)`;
13754 }]], DEFAULT_REPLACER_SUFFIX); // A simple cache, because an ignore rule only has only one certain meaning
13756 var cache = Object.create(null); // @param {pattern}
13758 var make_regex = function make_regex(pattern, negative, ignorecase) {
13759 var r = cache[pattern];
13765 var replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS;
13766 var source = replacers.reduce(function (prev, current) {
13767 return prev.replace(current[0], current[1].bind(pattern));
13769 return cache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source);
13770 }; // > A blank line matches no files, so it can serve as a separator for readability.
13773 var checkPattern = function checkPattern(pattern) {
13774 return pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment.
13775 && pattern.indexOf('#') !== 0;
13778 var createRule = function createRule(pattern, ignorecase) {
13779 var origin = pattern;
13780 var negative = false; // > An optional prefix "!" which negates the pattern;
13782 if (pattern.indexOf('!') === 0) {
13784 pattern = pattern.substr(1);
13787 pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that
13788 // > begin with a literal "!", for example, `"\!important!.txt"`.
13789 .replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that
13790 // > begin with a hash.
13791 .replace(REGEX_LEADING_EXCAPED_HASH, '#');
13792 var regex = make_regex(pattern, negative, ignorecase);
13804 function IgnoreBase() {
13805 var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
13806 _ref$ignorecase = _ref.ignorecase,
13807 ignorecase = _ref$ignorecase === void 0 ? true : _ref$ignorecase;
13809 _classCallCheck(this, IgnoreBase);
13812 this._ignorecase = ignorecase;
13813 define(this, KEY_IGNORE, true);
13818 _createClass(IgnoreBase, [{
13820 value: function _initCache() {
13821 this._cache = Object.create(null);
13822 } // @param {Array.<string>|string|Ignore} pattern
13826 value: function add(pattern) {
13827 this._added = false;
13829 if (typeof pattern === 'string') {
13830 pattern = pattern.split(/\r?\n/g);
13833 make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore,
13834 // making the behavior changed.
13845 value: function addPattern(pattern) {
13846 return this.add(pattern);
13849 key: "_addPattern",
13850 value: function _addPattern(pattern) {
13852 if (pattern && pattern[KEY_IGNORE]) {
13853 this._rules = this._rules.concat(pattern._rules);
13854 this._added = true;
13858 if (checkPattern(pattern)) {
13859 var rule = createRule(pattern, this._ignorecase);
13860 this._added = true;
13862 this._rules.push(rule);
13867 value: function filter(paths) {
13870 return make_array(paths).filter(function (path) {
13871 return _this._filter(path);
13875 key: "createFilter",
13876 value: function createFilter() {
13879 return function (path) {
13880 return _this2._filter(path);
13885 value: function ignores(path) {
13886 return !this._filter(path);
13887 } // @returns `Boolean` true if the `path` is NOT ignored
13891 value: function _filter(path, slices) {
13896 if (path in this._cache) {
13897 return this._cache[path];
13902 // ['path', 'to', 'a.js']
13903 slices = path.split(SLASH);
13907 return this._cache[path] = slices.length // > It is not possible to re-include a file if a parent directory of
13908 // > that file is excluded.
13909 // If the path contains a parent directory, check the parent first
13910 ? this._filter(slices.join(SLASH) + SLASH, slices) && this._test(path) // Or only test the path
13911 : this._test(path);
13912 } // @returns {Boolean} true if a file is NOT ignored
13916 value: function _test(path) {
13917 // Explicitly define variable type by setting matched to `0`
13920 this._rules.forEach(function (rule) {
13921 // if matched = true, then we only test negative rules
13922 // if matched = false, then we test non-negative rules
13923 if (!(matched ^ rule.negative)) {
13924 matched = rule.negative ^ rule.regex.test(path);
13934 // --------------------------------------------------------------
13936 /* istanbul ignore if */
13939 if ( // Detect `process` so that it can run in browsers.
13940 typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
13941 var filter = IgnoreBase.prototype._filter;
13942 /* eslint no-control-regex: "off" */
13944 var make_posix = function make_posix(str) {
13945 return /^\\\\\?\\/.test(str) || /[^\x00-\x80]+/.test(str) ? str : str.replace(/\\/g, '/');
13948 IgnoreBase.prototype._filter = function filterWin32(path, slices) {
13949 path = make_posix(path);
13950 return filter.call(this, path, slices);
13954 var ignore = function ignore(options) {
13955 return new IgnoreBase(options);
13959 * @param {string} filename
13960 * @returns {Promise<null | string>}
13964 function getFileContentOrNull(filename) {
13965 return new Promise(function (resolve, reject) {
13966 fs$1.readFile(filename, "utf8", function (error, data) {
13967 if (error && error.code !== "ENOENT") {
13968 reject(createError(filename, error));
13970 resolve(error ? null : data);
13976 * @param {string} filename
13977 * @returns {null | string}
13981 getFileContentOrNull.sync = function (filename) {
13983 return fs$1.readFileSync(filename, "utf8");
13985 if (error && error.code === "ENOENT") {
13989 throw createError(filename, error);
13993 function createError(filename, error) {
13994 return new Error(`Unable to read ${filename}: ${error.message}`);
13997 var getFileContentOrNull_1 = getFileContentOrNull;
14000 * @param {undefined | string} ignorePath
14001 * @param {undefined | boolean} withNodeModules
14005 function createIgnorer(ignorePath, withNodeModules) {
14006 return (!ignorePath ? Promise.resolve(null) : getFileContentOrNull_1(path$2.resolve(ignorePath))).then(function (ignoreContent) {
14007 return _createIgnorer(ignoreContent, withNodeModules);
14011 * @param {undefined | string} ignorePath
14012 * @param {undefined | boolean} withNodeModules
14016 createIgnorer.sync = function (ignorePath, withNodeModules) {
14017 var ignoreContent = !ignorePath ? null : getFileContentOrNull_1.sync(path$2.resolve(ignorePath));
14018 return _createIgnorer(ignoreContent, withNodeModules);
14021 * @param {null | string} ignoreContent
14022 * @param {undefined | boolean} withNodeModules
14026 function _createIgnorer(ignoreContent, withNodeModules) {
14027 var ignorer = ignore().add(ignoreContent || "");
14029 if (!withNodeModules) {
14030 ignorer.add("node_modules");
14036 var createIgnorer_1 = createIgnorer;
14038 var thirdParty = require("./third-party");
14040 var concatMap = function concatMap(xs, fn) {
14043 for (var i = 0; i < xs.length; i++) {
14044 var x = fn(xs[i], i);
14045 if (isArray(x)) res.push.apply(res, x);else res.push(x);
14051 var isArray = Array.isArray || function (xs) {
14052 return Object.prototype.toString.call(xs) === '[object Array]';
14055 var balancedMatch = balanced;
14057 function balanced(a, b, str) {
14058 if (a instanceof RegExp) a = maybeMatch(a, str);
14059 if (b instanceof RegExp) b = maybeMatch(b, str);
14060 var r = range(a, b, str);
14064 pre: str.slice(0, r[0]),
14065 body: str.slice(r[0] + a.length, r[1]),
14066 post: str.slice(r[1] + b.length)
14070 function maybeMatch(reg, str) {
14071 var m = str.match(reg);
14072 return m ? m[0] : null;
14075 balanced.range = range;
14077 function range(a, b, str) {
14078 var begs, beg, left, right, result;
14079 var ai = str.indexOf(a);
14080 var bi = str.indexOf(b, ai + 1);
14083 if (ai >= 0 && bi > 0) {
14087 while (i >= 0 && !result) {
14090 ai = str.indexOf(a, i + 1);
14091 } else if (begs.length == 1) {
14092 result = [begs.pop(), bi];
14101 bi = str.indexOf(b, i + 1);
14104 i = ai < bi && ai >= 0 ? ai : bi;
14108 result = [left, right];
14115 var braceExpansion = expandTop;
14116 var escSlash = '\0SLASH' + Math.random() + '\0';
14117 var escOpen = '\0OPEN' + Math.random() + '\0';
14118 var escClose = '\0CLOSE' + Math.random() + '\0';
14119 var escComma = '\0COMMA' + Math.random() + '\0';
14120 var escPeriod = '\0PERIOD' + Math.random() + '\0';
14122 function numeric(str) {
14123 return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
14126 function escapeBraces(str) {
14127 return str.split('\\\\').join(escSlash).split('\\{').join(escOpen).split('\\}').join(escClose).split('\\,').join(escComma).split('\\.').join(escPeriod);
14130 function unescapeBraces(str) {
14131 return str.split(escSlash).join('\\').split(escOpen).join('{').split(escClose).join('}').split(escComma).join(',').split(escPeriod).join('.');
14132 } // Basically just str.split(","), but handling cases
14133 // where we have nested braced sections, which should be
14134 // treated as individual members, like {a,{b,c},d}
14137 function parseCommaParts(str) {
14138 if (!str) return [''];
14140 var m = balancedMatch('{', '}', str);
14141 if (!m) return str.split(',');
14145 var p = pre.split(',');
14146 p[p.length - 1] += '{' + body + '}';
14147 var postParts = parseCommaParts(post);
14150 p[p.length - 1] += postParts.shift();
14151 p.push.apply(p, postParts);
14154 parts.push.apply(parts, p);
14158 function expandTop(str) {
14159 if (!str) return []; // I don't know why Bash 4.3 does this, but it does.
14160 // Anything starting with {} will have the first two bytes preserved
14161 // but *only* at the top level, so {},a}b will not expand to anything,
14162 // but a{},b}c will be expanded to [a}c,abc].
14163 // One could argue that this is a bug in Bash, but since the goal of
14164 // this module is to match Bash's rules, we escape a leading {}
14166 if (str.substr(0, 2) === '{}') {
14167 str = '\\{\\}' + str.substr(2);
14170 return expand(escapeBraces(str), true).map(unescapeBraces);
14173 function embrace(str) {
14174 return '{' + str + '}';
14177 function isPadded(el) {
14178 return /^-?0\d/.test(el);
14181 function lte(i, y) {
14185 function gte(i, y) {
14189 function expand(str, isTop) {
14190 var expansions = [];
14191 var m = balancedMatch('{', '}', str);
14192 if (!m || /\$$/.test(m.pre)) return [str];
14193 var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
14194 var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
14195 var isSequence = isNumericSequence || isAlphaSequence;
14196 var isOptions = m.body.indexOf(',') >= 0;
14198 if (!isSequence && !isOptions) {
14200 if (m.post.match(/,.*\}/)) {
14201 str = m.pre + '{' + m.body + escClose + m.post;
14202 return expand(str);
14211 n = m.body.split(/\.\./);
14213 n = parseCommaParts(m.body);
14215 if (n.length === 1) {
14216 // x{{a,b}}y ==> x{a}y x{b}y
14217 n = expand(n[0], false).map(embrace);
14219 if (n.length === 1) {
14220 var post = m.post.length ? expand(m.post, false) : [''];
14221 return post.map(function (p) {
14222 return m.pre + n[0] + p;
14226 } // at this point, n is the parts, and we know it's not a comma set
14227 // with a single entry.
14228 // no need to expand pre, since it is guaranteed to be free of brace-sets
14232 var post = m.post.length ? expand(m.post, false) : [''];
14236 var x = numeric(n[0]);
14237 var y = numeric(n[1]);
14238 var width = Math.max(n[0].length, n[1].length);
14239 var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
14241 var reverse = y < x;
14248 var pad = n.some(isPadded);
14251 for (var i = x; test(i, y); i += incr) {
14254 if (isAlphaSequence) {
14255 c = String.fromCharCode(i);
14256 if (c === '\\') c = '';
14261 var need = width - c.length;
14264 var z = new Array(need + 1).join('0');
14265 if (i < 0) c = '-' + z + c.slice(1);else c = z + c;
14273 N = concatMap(n, function (el) {
14274 return expand(el, false);
14278 for (var j = 0; j < N.length; j++) {
14279 for (var k = 0; k < post.length; k++) {
14280 var expansion = pre + N[j] + post[k];
14281 if (!isTop || isSequence || expansion) expansions.push(expansion);
14288 var minimatch_1 = minimatch;
14289 minimatch.Minimatch = Minimatch;
14298 var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
14320 }; // any single thing other than /
14321 // don't need to escape / when using new RegExp()
14323 var qmark = '[^/]'; // * => any number of characters
14325 var star = qmark + '*?'; // ** when dots are allowed. Anything goes, except .. and .
14326 // not (^ or / followed by one or two dots followed by $ or /),
14327 // followed by anything, any number of times.
14329 var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; // not a ^ or / followed by a dot,
14330 // followed by anything, any number of times.
14332 var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; // characters that need to be escaped in RegExp.
14334 var reSpecials = charSet('().*{}+?[]^$\\!'); // "abc" -> { a:true, b:true, c:true }
14336 function charSet(s) {
14337 return s.split('').reduce(function (set, c) {
14341 } // normalizes slashes.
14344 var slashSplit = /\/+/;
14345 minimatch.filter = filter$1;
14347 function filter$1(pattern, options) {
14348 options = options || {};
14349 return function (p, i, list) {
14350 return minimatch(p, pattern, options);
14354 function ext(a, b) {
14358 Object.keys(b).forEach(function (k) {
14361 Object.keys(a).forEach(function (k) {
14367 minimatch.defaults = function (def) {
14368 if (!def || !Object.keys(def).length) return minimatch;
14369 var orig = minimatch;
14371 var m = function minimatch(p, pattern, options) {
14372 return orig.minimatch(p, pattern, ext(def, options));
14375 m.Minimatch = function Minimatch(pattern, options) {
14376 return new orig.Minimatch(pattern, ext(def, options));
14382 Minimatch.defaults = function (def) {
14383 if (!def || !Object.keys(def).length) return Minimatch;
14384 return minimatch.defaults(def).Minimatch;
14387 function minimatch(p, pattern, options) {
14388 if (typeof pattern !== 'string') {
14389 throw new TypeError('glob pattern string required');
14392 if (!options) options = {}; // shortcut: comments match nothing.
14394 if (!options.nocomment && pattern.charAt(0) === '#') {
14396 } // "" only matches ""
14399 if (pattern.trim() === '') return p === '';
14400 return new Minimatch(pattern, options).match(p);
14403 function Minimatch(pattern, options) {
14404 if (!(this instanceof Minimatch)) {
14405 return new Minimatch(pattern, options);
14408 if (typeof pattern !== 'string') {
14409 throw new TypeError('glob pattern string required');
14412 if (!options) options = {};
14413 pattern = pattern.trim(); // windows support: need to use /, not \
14415 if (path.sep !== '/') {
14416 pattern = pattern.split(path.sep).join('/');
14419 this.options = options;
14421 this.pattern = pattern;
14422 this.regexp = null;
14423 this.negate = false;
14424 this.comment = false;
14425 this.empty = false; // make the set of regexps etc.
14430 Minimatch.prototype.debug = function () {};
14432 Minimatch.prototype.make = make;
14435 // don't do it more than once.
14436 if (this._made) return;
14437 var pattern = this.pattern;
14438 var options = this.options; // empty patterns and comments match nothing.
14440 if (!options.nocomment && pattern.charAt(0) === '#') {
14441 this.comment = true;
14448 } // step 1: figure out negation, etc.
14451 this.parseNegate(); // step 2: expand braces
14453 var set = this.globSet = this.braceExpand();
14454 if (options.debug) this.debug = console.error;
14455 this.debug(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion
14456 // matching patterns.
14457 // These will be regexps, except in the case of "**", which is
14458 // set to the GLOBSTAR object for globstar behavior,
14459 // and will not contain any / characters
14461 set = this.globParts = set.map(function (s) {
14462 return s.split(slashSplit);
14464 this.debug(this.pattern, set); // glob --> regexps
14466 set = set.map(function (s, si, set) {
14467 return s.map(this.parse, this);
14469 this.debug(this.pattern, set); // filter out everything that didn't compile properly.
14471 set = set.filter(function (s) {
14472 return s.indexOf(false) === -1;
14474 this.debug(this.pattern, set);
14478 Minimatch.prototype.parseNegate = parseNegate;
14480 function parseNegate() {
14481 var pattern = this.pattern;
14482 var negate = false;
14483 var options = this.options;
14484 var negateOffset = 0;
14485 if (options.nonegate) return;
14487 for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === '!'; i++) {
14492 if (negateOffset) this.pattern = pattern.substr(negateOffset);
14493 this.negate = negate;
14494 } // Brace expansion:
14495 // a{b,c}d -> abd acd
14496 // a{b,}c -> abc ac
14497 // a{0..3}d -> a0d a1d a2d a3d
14498 // a{b,c{d,e}f}g -> abg acdfg acefg
14499 // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
14501 // Invalid sets are not expanded.
14502 // a{2..}b -> a{2..}b
14506 minimatch.braceExpand = function (pattern, options) {
14507 return braceExpand(pattern, options);
14510 Minimatch.prototype.braceExpand = braceExpand;
14512 function braceExpand(pattern, options) {
14514 if (this instanceof Minimatch) {
14515 options = this.options;
14521 pattern = typeof pattern === 'undefined' ? this.pattern : pattern;
14523 if (typeof pattern === 'undefined') {
14524 throw new TypeError('undefined pattern');
14527 if (options.nobrace || !pattern.match(/\{.*\}/)) {
14528 // shortcut. no need to expand.
14532 return braceExpansion(pattern);
14533 } // parse a component of the expanded set.
14534 // At this point, no pattern may contain "/" in it
14535 // so we're going to return a 2d array, where each entry is the full
14536 // pattern, split on '/', and then turned into a regular expression.
14537 // A regexp is made at the end which joins each array with an
14538 // escaped /, and another full one which joins each regexp with |.
14540 // Following the lead of Bash 4.1, note that "**" only has special meaning
14541 // when it is the *only* thing in a path portion. Otherwise, any series
14542 // of * is equivalent to a single *. Globstar behavior is enabled by
14543 // default, and can be disabled by setting options.noglobstar.
14546 Minimatch.prototype.parse = parse$1;
14549 function parse$1(pattern, isSub) {
14550 if (pattern.length > 1024 * 64) {
14551 throw new TypeError('pattern is too long');
14554 var options = this.options; // shortcuts
14556 if (!options.noglobstar && pattern === '**') return GLOBSTAR;
14557 if (pattern === '') return '';
14559 var hasMagic = !!options.nocase;
14560 var escaping = false; // ? => one single character
14562 var patternListStack = [];
14563 var negativeLists = [];
14565 var inClass = false;
14566 var reClassStart = -1;
14567 var classStart = -1; // . and .. never match anything that doesn't start with .,
14568 // even when options.dot is set.
14570 var patternStart = pattern.charAt(0) === '.' ? '' // anything
14571 // not (start or / followed by . or .. followed by / or end)
14572 : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)';
14575 function clearStateChar() {
14577 // we had some state-tracking character
14578 // that wasn't consumed by this pass.
14579 switch (stateChar) {
14591 re += '\\' + stateChar;
14595 self.debug('clearStateChar %j %j', stateChar, re);
14600 for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
14601 this.debug('%s\t%s %s %j', pattern, i, re, c); // skip over any that are escaped.
14603 if (escaping && reSpecials[c]) {
14611 // completely not allowed, even escaped.
14612 // Should already be path-split by now.
14619 // the various stateChar values
14620 // for the "extglob" stuff.
14627 this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); // all of those are literals inside a class, except that
14628 // the glob [!a] means [^a] in regexp
14631 this.debug(' in class');
14632 if (c === '!' && i === classStart + 1) c = '^';
14635 } // if we already have a stateChar, then it means
14636 // that there was something like ** or +? in there.
14637 // Handle the stateChar, then proceed with this one.
14640 self.debug('call clearStateChar %j', stateChar);
14642 stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
14643 // just clear the statechar *now*, rather than even diving into
14644 // the patternList stuff.
14646 if (options.noext) clearStateChar();
14660 patternListStack.push({
14663 reStart: re.length,
14664 open: plTypes[stateChar].open,
14665 close: plTypes[stateChar].close
14666 }); // negation is (?:(?!js)[^/]*)
14668 re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
14669 this.debug('plType %j %j', stateChar, re);
14674 if (inClass || !patternListStack.length) {
14681 var pl = patternListStack.pop(); // negation is (?:(?!js)[^/]*)
14682 // The others are (?:<pattern>)<type>
14686 if (pl.type === '!') {
14687 negativeLists.push(pl);
14690 pl.reEnd = re.length;
14694 if (inClass || !patternListStack.length || escaping) {
14703 // these are mostly the same in regexp and glob
14706 // swallow any state-tracking char before the [
14716 reClassStart = re.length;
14721 // a right bracket shall lose its special
14722 // meaning and represent itself in
14723 // a bracket expression if it occurs
14724 // first in the list. -- POSIX.2 2.8.3.2
14725 if (i === classStart + 1 || !inClass) {
14729 } // handle the case where we left a class open.
14730 // "[z-a]" is valid, equivalent to "\[z-a\]"
14734 // split where the last [ was, make sure we don't have
14735 // an invalid re. if so, re-walk the contents of the
14736 // would-be class to re-translate any characters that
14737 // were passed through as-is
14738 // TODO: It would probably be faster to determine this
14739 // without a try/catch and a new RegExp, but it's tricky
14740 // to do safely. For now, this is safe and works.
14741 var cs = pattern.substring(classStart + 1, i);
14744 RegExp('[' + cs + ']');
14746 // not a valid class!
14747 var sp = this.parse(cs, SUBPARSE);
14748 re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
14749 hasMagic = hasMagic || sp[1];
14753 } // finish up the class.
14762 // swallow any state char that wasn't consumed
14768 } else if (reSpecials[c] && !(c === '^' && inClass)) {
14776 // handle the case where we left a class open.
14777 // "[abc" is valid, equivalent to "\[abc"
14781 // split where the last [ was, and escape it
14782 // this is a huge pita. We now have to re-walk
14783 // the contents of the would-be class to re-translate
14784 // any characters that were passed through as-is
14785 cs = pattern.substr(classStart + 1);
14786 sp = this.parse(cs, SUBPARSE);
14787 re = re.substr(0, reClassStart) + '\\[' + sp[0];
14788 hasMagic = hasMagic || sp[1];
14789 } // handle the case where we had a +( thing at the *end*
14791 // each pattern list stack adds 3 chars, and we need to go through
14792 // and escape any | chars that were passed through as-is for the regexp.
14793 // Go through and escape them, taking care not to double-escape any
14794 // | chars that were already escaped.
14797 for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
14798 var tail = re.slice(pl.reStart + pl.open.length);
14799 this.debug('setting tail', re, pl); // maybe some even number of \, then maybe 1 \, followed by a |
14801 tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
14803 // the | isn't already escaped, so escape it.
14805 } // need to escape all those slashes *again*, without escaping the
14806 // one that we need for escaping the | character. As it works out,
14807 // escaping an even number of slashes can be done by simply repeating
14808 // it exactly after itself. That's why this trick works.
14810 // I am sorry that you have to see this.
14813 return $1 + $1 + $2 + '|';
14815 this.debug('tail=%j\n %s', tail, tail, pl, re);
14816 var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type;
14818 re = re.slice(0, pl.reStart) + t + '\\(' + tail;
14819 } // handle trailing things that only matter at the very end.
14827 } // only need to apply the nodot start if the re starts with
14828 // something that could conceivably capture a dot
14831 var addPatternStart = false;
14833 switch (re.charAt(0)) {
14837 addPatternStart = true;
14838 } // Hack to work around lack of negative lookbehind in JS
14839 // A pattern like: *.!(x).!(y|z) needs to ensure that a name
14840 // like 'a.xyz.yz' doesn't match. So, the first negative
14841 // lookahead, has to look ALL the way ahead, to the end of
14845 for (var n = negativeLists.length - 1; n > -1; n--) {
14846 var nl = negativeLists[n];
14847 var nlBefore = re.slice(0, nl.reStart);
14848 var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
14849 var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
14850 var nlAfter = re.slice(nl.reEnd);
14851 nlLast += nlAfter; // Handle nested stuff like *(*.js|!(*.json)), where open parens
14852 // mean that we should *not* include the ) in the bit that is considered
14853 // "after" the negated section.
14855 var openParensBefore = nlBefore.split('(').length - 1;
14856 var cleanAfter = nlAfter;
14858 for (i = 0; i < openParensBefore; i++) {
14859 cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
14862 nlAfter = cleanAfter;
14865 if (nlAfter === '' && isSub !== SUBPARSE) {
14869 var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
14871 } // if the re is not "" at this point, then we need to make sure
14872 // it doesn't match against an empty path part.
14873 // Otherwise a/* will match a/, which it should not.
14876 if (re !== '' && hasMagic) {
14880 if (addPatternStart) {
14881 re = patternStart + re;
14882 } // parsing just a piece of a larger pattern.
14885 if (isSub === SUBPARSE) {
14886 return [re, hasMagic];
14887 } // skip the regexp for non-magical patterns
14888 // unescape anything in it, though, so that it'll be
14889 // an exact match against a file etc.
14893 return globUnescape(pattern);
14896 var flags = options.nocase ? 'i' : '';
14899 var regExp = new RegExp('^' + re + '$', flags);
14901 // If it was an invalid regular expression, then it can't match
14902 // anything. This trick looks for a character after the end of
14903 // the string, which is of course impossible, except in multi-line
14904 // mode, but it's not a /m regex.
14905 return new RegExp('$.');
14908 regExp._glob = pattern;
14913 minimatch.makeRe = function (pattern, options) {
14914 return new Minimatch(pattern, options || {}).makeRe();
14917 Minimatch.prototype.makeRe = makeRe;
14919 function makeRe() {
14920 if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
14921 // pattern strings, or "**".
14923 // It's better to use .match(). This function shouldn't
14924 // be used, really, but it's pretty convenient sometimes,
14925 // when you just want to work with a regex.
14927 var set = this.set;
14930 this.regexp = false;
14931 return this.regexp;
14934 var options = this.options;
14935 var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
14936 var flags = options.nocase ? 'i' : '';
14937 var re = set.map(function (pattern) {
14938 return pattern.map(function (p) {
14939 return p === GLOBSTAR ? twoStar : typeof p === 'string' ? regExpEscape(p) : p._src;
14941 }).join('|'); // must match entire pattern
14942 // ending in a * or ** will make it less strict.
14944 re = '^(?:' + re + ')$'; // can match anything, as long as it's not this.
14946 if (this.negate) re = '^(?!' + re + ').*$';
14949 this.regexp = new RegExp(re, flags);
14951 this.regexp = false;
14954 return this.regexp;
14957 minimatch.match = function (list, pattern, options) {
14958 options = options || {};
14959 var mm = new Minimatch(pattern, options);
14960 list = list.filter(function (f) {
14961 return mm.match(f);
14964 if (mm.options.nonull && !list.length) {
14965 list.push(pattern);
14971 Minimatch.prototype.match = match;
14973 function match(f, partial) {
14974 this.debug('match', f, this.pattern); // short-circuit in the case of busted things.
14977 if (this.comment) return false;
14978 if (this.empty) return f === '';
14979 if (f === '/' && partial) return true;
14980 var options = this.options; // windows: need to use /, not \
14982 if (path.sep !== '/') {
14983 f = f.split(path.sep).join('/');
14984 } // treat the test path as a set of pathparts.
14987 f = f.split(slashSplit);
14988 this.debug(this.pattern, 'split', f); // just ONE of the pattern sets in this.set needs to match
14989 // in order for it to be valid. If negating, then just one
14990 // match means that we have failed.
14991 // Either way, return on the first hit.
14993 var set = this.set;
14994 this.debug(this.pattern, 'set', set); // Find the basename of the path by looking for the last non-empty segment
14999 for (i = f.length - 1; i >= 0; i--) {
15001 if (filename) break;
15004 for (i = 0; i < set.length; i++) {
15005 var pattern = set[i];
15008 if (options.matchBase && pattern.length === 1) {
15012 var hit = this.matchOne(file, pattern, partial);
15015 if (options.flipNegate) return true;
15016 return !this.negate;
15018 } // didn't get any hits. this is success if it's a negative
15019 // pattern, failure otherwise.
15022 if (options.flipNegate) return false;
15023 return this.negate;
15024 } // set partial to true to test if, for example,
15025 // "/a/b" matches the start of "/*/b/*/d"
15026 // Partial means, if you run out of file before you run
15027 // out of pattern, then that's fine, as long as all
15028 // the parts match.
15031 Minimatch.prototype.matchOne = function (file, pattern, partial) {
15032 var options = this.options;
15033 this.debug('matchOne', {
15038 this.debug('matchOne', file.length, pattern.length);
15040 for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
15041 this.debug('matchOne loop');
15042 var p = pattern[pi];
15044 this.debug(pattern, p, f); // should be impossible.
15045 // some invalid regexp stuff in the set.
15047 if (p === false) return false;
15049 if (p === GLOBSTAR) {
15050 this.debug('GLOBSTAR', [pattern, p, f]); // "**"
15051 // a/**/b/**/c would match the following:
15056 // To do this, take the rest of the pattern after
15057 // the **, and see if it would match the file remainder.
15058 // If so, return success.
15059 // If not, the ** "swallows" a segment, and try again.
15060 // This is recursively awful.
15062 // a/**/b/**/c matching a/b/x/y/z/c
15065 // - matchOne(b/x/y/z/c, b/**/c)
15068 // - matchOne(x/y/z/c, c) -> no
15069 // - matchOne(y/z/c, c) -> no
15070 // - matchOne(z/c, c) -> no
15071 // - matchOne(c, c) yes, hit
15077 this.debug('** at the end'); // a ** at the end will just swallow the rest.
15078 // We have found a match.
15079 // however, it will not swallow /.x, unless
15080 // options.dot is set.
15081 // . and .. are *never* matched by **, for explosively
15082 // exponential reasons.
15084 for (; fi < fl; fi++) {
15085 if (file[fi] === '.' || file[fi] === '..' || !options.dot && file[fi].charAt(0) === '.') return false;
15089 } // ok, let's see if we can swallow whatever we can.
15093 var swallowee = file[fr];
15094 this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); // XXX remove this slice. Just pass the start index.
15096 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
15097 this.debug('globstar found match!', fr, fl, swallowee); // found a match.
15101 // can't swallow "." or ".." ever.
15102 // can only swallow ".foo" when explicitly asked.
15103 if (swallowee === '.' || swallowee === '..' || !options.dot && swallowee.charAt(0) === '.') {
15104 this.debug('dot detected!', file, fr, pattern, pr);
15106 } // ** swallows a segment, and continue.
15109 this.debug('globstar swallow a segment, and continue');
15112 } // no match was found.
15113 // However, in partial mode, we can't say this is necessarily over.
15114 // If there's more *pattern* left, then
15119 this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
15120 if (fr === fl) return true;
15124 } // something other than **
15125 // non-magic patterns just have to match exactly
15126 // patterns with magic have been turned into regexps.
15131 if (typeof p === 'string') {
15132 if (options.nocase) {
15133 hit = f.toLowerCase() === p.toLowerCase();
15138 this.debug('string match', p, f, hit);
15141 this.debug('pattern match', p, f, hit);
15144 if (!hit) return false;
15145 } // Note: ending in / means that we'll get a final ""
15146 // at the end of the pattern. This can only match a
15147 // corresponding "" at the end of the file.
15148 // If the file ends in /, then it can only match a
15149 // a pattern that ends in /, unless the pattern just
15150 // doesn't have any more for it. But, a/b/ should *not*
15151 // match "a/b/*", even though "" matches against the
15152 // [^/]*? pattern, except in partial mode, where it might
15153 // simply not be reached yet.
15154 // However, a/b/ should still satisfy a/*
15155 // now either we fell off the end of the pattern, or we're done.
15158 if (fi === fl && pi === pl) {
15159 // ran out of pattern and filename at the same time.
15162 } else if (fi === fl) {
15163 // ran out of file, but still had pattern left.
15164 // this is ok if we're doing the match as part of
15165 // a glob fs traversal.
15167 } else if (pi === pl) {
15168 // ran out of pattern, still have file left.
15169 // this is only acceptable if we're on the very last
15170 // empty segment of a file with a trailing slash.
15171 // a/* should match a/b/
15172 var emptyFileEnd = fi === fl - 1 && file[fi] === '';
15173 return emptyFileEnd;
15174 } // should be unreachable.
15177 throw new Error('wtf?');
15178 }; // replace stuff like \* with *
15181 function globUnescape(s) {
15182 return s.replace(/\\(.)/g, '$1');
15185 function regExpEscape(s) {
15186 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
15190 var async_hooks = ">= 8";
15191 var buffer_ieee754 = "< 0.9.7";
15193 var child_process = true;
15194 var cluster = true;
15195 var console$1 = true;
15196 var constants = true;
15198 var _debug_agent = ">= 1 && < 8";
15199 var _debugger = "< 8";
15204 var freelist = "< 6";
15206 var _http_agent = ">= 0.11.1";
15207 var _http_client = ">= 0.11.1";
15208 var _http_common = ">= 0.11.1";
15209 var _http_incoming = ">= 0.11.1";
15210 var _http_outgoing = ">= 0.11.1";
15211 var _http_server = ">= 0.11.1";
15213 var http2 = ">= 8.8";
15215 var inspector = ">= 8.0.0";
15216 var _linklist = "< 8";
15217 var module$1 = true;
15221 var perf_hooks = ">= 8.5";
15222 var process$1 = ">= 1";
15223 var punycode = true;
15224 var querystring = true;
15225 var readline = true;
15227 var smalloc = ">= 0.11.5 && < 3";
15228 var _stream_duplex = ">= 0.9.4";
15229 var _stream_transform = ">= 0.9.4";
15230 var _stream_wrap = ">= 1.4.1";
15231 var _stream_passthrough = ">= 0.9.4";
15232 var _stream_readable = ">= 0.9.4";
15233 var _stream_writable = ">= 0.9.4";
15235 var string_decoder = true;
15238 var _tls_common = ">= 0.11.13";
15239 var _tls_legacy = ">= 0.11.3 && < 10";
15240 var _tls_wrap = ">= 0.11.3";
15242 var trace_events = ">= 10";
15248 var worker_threads = ">= 11.7";
15252 async_hooks: async_hooks,
15253 buffer_ieee754: buffer_ieee754,
15255 child_process: child_process,
15257 console: console$1,
15258 constants: constants,
15260 _debug_agent: _debug_agent,
15261 _debugger: _debugger,
15266 freelist: freelist,
15268 "fs/promises": ">= 10 && < 10.1",
15269 _http_agent: _http_agent,
15270 _http_client: _http_client,
15271 _http_common: _http_common,
15272 _http_incoming: _http_incoming,
15273 _http_outgoing: _http_outgoing,
15274 _http_server: _http_server,
15278 inspector: inspector,
15279 _linklist: _linklist,
15282 "node-inspect/lib/_inspect": ">= 7.6.0 && < 12",
15283 "node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12",
15284 "node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12",
15287 perf_hooks: perf_hooks,
15288 process: process$1,
15289 punycode: punycode,
15290 querystring: querystring,
15291 readline: readline,
15294 _stream_duplex: _stream_duplex,
15295 _stream_transform: _stream_transform,
15296 _stream_wrap: _stream_wrap,
15297 _stream_passthrough: _stream_passthrough,
15298 _stream_readable: _stream_readable,
15299 _stream_writable: _stream_writable,
15301 string_decoder: string_decoder,
15304 _tls_common: _tls_common,
15305 _tls_legacy: _tls_legacy,
15306 _tls_wrap: _tls_wrap,
15308 trace_events: trace_events,
15312 "v8/tools/arguments": ">= 10 && < 12",
15313 "v8/tools/codemap": [
15317 "v8/tools/consarray": [
15321 "v8/tools/csvparser": [
15325 "v8/tools/logreader": [
15329 "v8/tools/profile_view": [
15333 "v8/tools/splaytree": [
15339 worker_threads: worker_threads,
15343 var core$2 = /*#__PURE__*/Object.freeze({
15346 async_hooks: async_hooks,
15347 buffer_ieee754: buffer_ieee754,
15349 child_process: child_process,
15351 console: console$1,
15352 constants: constants,
15354 _debug_agent: _debug_agent,
15355 _debugger: _debugger,
15360 freelist: freelist,
15362 _http_agent: _http_agent,
15363 _http_client: _http_client,
15364 _http_common: _http_common,
15365 _http_incoming: _http_incoming,
15366 _http_outgoing: _http_outgoing,
15367 _http_server: _http_server,
15371 inspector: inspector,
15372 _linklist: _linklist,
15377 perf_hooks: perf_hooks,
15378 process: process$1,
15379 punycode: punycode,
15380 querystring: querystring,
15381 readline: readline,
15384 _stream_duplex: _stream_duplex,
15385 _stream_transform: _stream_transform,
15386 _stream_wrap: _stream_wrap,
15387 _stream_passthrough: _stream_passthrough,
15388 _stream_readable: _stream_readable,
15389 _stream_writable: _stream_writable,
15391 string_decoder: string_decoder,
15394 _tls_common: _tls_common,
15395 _tls_legacy: _tls_legacy,
15396 _tls_wrap: _tls_wrap,
15398 trace_events: trace_events,
15404 worker_threads: worker_threads,
15409 var data = getCjsExportFromNamespace(core$2);
15411 var current = process.versions && process.versions.node && process.versions.node.split('.') || [];
15413 function specifierIncluded(specifier) {
15414 var parts = specifier.split(' ');
15415 var op = parts.length > 1 ? parts[0] : '=';
15416 var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.');
15418 for (var i = 0; i < 3; ++i) {
15419 var cur = Number(current[i] || 0);
15420 var ver = Number(versionParts[i] || 0);
15423 continue; // eslint-disable-line no-restricted-syntax, no-continue
15428 } else if (op === '>=') {
15435 return op === '>=';
15438 function matchesRange(range) {
15439 var specifiers = range.split(/ ?&& ?/);
15441 if (specifiers.length === 0) {
15445 for (var i = 0; i < specifiers.length; ++i) {
15446 if (!specifierIncluded(specifiers[i])) {
15454 function versionIncluded(specifierValue) {
15455 if (typeof specifierValue === 'boolean') {
15456 return specifierValue;
15459 if (specifierValue && typeof specifierValue === 'object') {
15460 for (var i = 0; i < specifierValue.length; ++i) {
15461 if (matchesRange(specifierValue[i])) {
15469 return matchesRange(specifierValue);
15474 for (var mod in data) {
15475 // eslint-disable-line no-restricted-syntax
15476 if (Object.prototype.hasOwnProperty.call(data, mod)) {
15477 core$3[mod] = versionIncluded(data[mod]);
15481 var core_1 = core$3;
15483 var caller = function caller() {
15484 // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
15485 var origPrepareStackTrace = Error.prepareStackTrace;
15487 Error.prepareStackTrace = function (_, stack) {
15491 var stack = new Error().stack;
15492 Error.prepareStackTrace = origPrepareStackTrace;
15493 return stack[2].getFileName();
15496 var pathParse = createCommonjsModule(function (module) {
15498 var isWindows = process.platform === 'win32'; // Regex to split a windows path into three parts: [*, device, slash,
15499 // tail] windows-only
15501 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; // Regex to split the tail part of the above into [*, dir, basename, ext]
15503 var splitTailRe = /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
15504 var win32 = {}; // Function to split a filename into [root, dir, basename, ext]
15506 function win32SplitPath(filename) {
15507 // Separate device+slash from tail
15508 var result = splitDeviceRe.exec(filename),
15509 device = (result[1] || '') + (result[2] || ''),
15510 tail = result[3] || ''; // Split the tail into dir, basename and extension
15512 var result2 = splitTailRe.exec(tail),
15514 basename = result2[2],
15516 return [device, dir, basename, ext];
15519 win32.parse = function (pathString) {
15520 if (typeof pathString !== 'string') {
15521 throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
15524 var allParts = win32SplitPath(pathString);
15526 if (!allParts || allParts.length !== 4) {
15527 throw new TypeError("Invalid path '" + pathString + "'");
15532 dir: allParts[0] + allParts[1].slice(0, -1),
15535 name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
15537 }; // Split a filename into [root, dir, basename, ext], unix version
15538 // 'root' is just a slash, or nothing.
15541 var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
15544 function posixSplitPath(filename) {
15545 return splitPathRe.exec(filename).slice(1);
15548 posix.parse = function (pathString) {
15549 if (typeof pathString !== 'string') {
15550 throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
15553 var allParts = posixSplitPath(pathString);
15555 if (!allParts || allParts.length !== 4) {
15556 throw new TypeError("Invalid path '" + pathString + "'");
15559 allParts[1] = allParts[1] || '';
15560 allParts[2] = allParts[2] || '';
15561 allParts[3] = allParts[3] || '';
15564 dir: allParts[0] + allParts[1].slice(0, -1),
15567 name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
15571 if (isWindows) module.exports = win32.parse;else
15573 module.exports = posix.parse;
15574 module.exports.posix = posix.parse;
15575 module.exports.win32 = win32.parse;
15577 var pathParse_1 = pathParse.posix;
15578 var pathParse_2 = pathParse.win32;
15580 var parse$2 = path$2.parse || pathParse;
15582 var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) {
15585 if (/^([A-Za-z]:)/.test(absoluteStart)) {
15587 } else if (/^\\\\/.test(absoluteStart)) {
15591 var paths = [absoluteStart];
15592 var parsed = parse$2(absoluteStart);
15594 while (parsed.dir !== paths[paths.length - 1]) {
15595 paths.push(parsed.dir);
15596 parsed = parse$2(parsed.dir);
15599 return paths.reduce(function (dirs, aPath) {
15600 return dirs.concat(modules.map(function (moduleDir) {
15601 return path$2.resolve(prefix, aPath, moduleDir);
15606 var nodeModulesPaths = function nodeModulesPaths(start, opts, request) {
15607 var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ['node_modules'];
15609 if (opts && typeof opts.paths === 'function') {
15610 return opts.paths(request, start, function () {
15611 return getNodeModulesDirs(start, modules);
15615 var dirs = getNodeModulesDirs(start, modules);
15616 return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
15619 var normalizeOptions$2 = function normalizeOptions(x, opts) {
15621 * This file is purposefully a passthrough. It's expected that third-party
15622 * environments will override it at runtime in order to inject special logic
15623 * into `resolve` (by manipulating the options). One such example is the PnP
15624 * code path in Yarn.
15629 var defaultIsFile = function isFile(file, cb) {
15630 fs$1.stat(file, function (err, stat) {
15632 return cb(null, stat.isFile() || stat.isFIFO());
15635 if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
15640 var defaultIsDir = function isDirectory(dir, cb) {
15641 fs$1.stat(dir, function (err, stat) {
15643 return cb(null, stat.isDirectory());
15646 if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
15651 var maybeUnwrapSymlink = function maybeUnwrapSymlink(x, opts, cb) {
15652 if (opts && opts.preserveSymlinks === false) {
15653 fs$1.realpath(x, function (realPathErr, realPath) {
15654 if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr);else cb(null, realPathErr ? x : realPath);
15661 var async = function resolve(x, options, callback) {
15663 var opts = options;
15665 if (typeof options === 'function') {
15670 if (typeof x !== 'string') {
15671 var err = new TypeError('Path must be a string.');
15672 return process.nextTick(function () {
15677 opts = normalizeOptions$2(x, opts);
15678 var isFile = opts.isFile || defaultIsFile;
15679 var isDirectory = opts.isDirectory || defaultIsDir;
15680 var readFile = opts.readFile || fs$1.readFile;
15681 var extensions = opts.extensions || ['.js'];
15682 var basedir = opts.basedir || path$2.dirname(caller());
15683 var parent = opts.filename || basedir;
15684 opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
15686 var absoluteStart = path$2.resolve(basedir);
15687 maybeUnwrapSymlink(absoluteStart, opts, function (err, realStart) {
15688 if (err) cb(err);else init(realStart);
15692 function init(basedir) {
15693 if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
15694 res = path$2.resolve(basedir, x);
15695 if (x === '..' || x.slice(-1) === '/') res += '/';
15697 if (/\/$/.test(x) && res === basedir) {
15698 loadAsDirectory(res, opts.package, onfile);
15699 } else loadAsFile(res, opts.package, onfile);
15700 } else loadNodeModules(x, basedir, function (err, n, pkg) {
15701 if (err) cb(err);else if (core_1[x]) return cb(null, x);else if (n) {
15702 return maybeUnwrapSymlink(n, opts, function (err, realN) {
15706 cb(null, realN, pkg);
15710 var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
15711 moduleError.code = 'MODULE_NOT_FOUND';
15717 function onfile(err, m, pkg) {
15718 if (err) cb(err);else if (m) cb(null, m, pkg);else loadAsDirectory(res, function (err, d, pkg) {
15719 if (err) cb(err);else if (d) {
15720 maybeUnwrapSymlink(d, opts, function (err, realD) {
15724 cb(null, realD, pkg);
15728 var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
15729 moduleError.code = 'MODULE_NOT_FOUND';
15735 function loadAsFile(x, thePackage, callback) {
15736 var loadAsFilePackage = thePackage;
15739 if (typeof loadAsFilePackage === 'function') {
15740 cb = loadAsFilePackage;
15741 loadAsFilePackage = undefined;
15744 var exts = [''].concat(extensions);
15745 load(exts, x, loadAsFilePackage);
15747 function load(exts, x, loadPackage) {
15748 if (exts.length === 0) return cb(null, undefined, loadPackage);
15749 var file = x + exts[0];
15750 var pkg = loadPackage;
15751 if (pkg) onpkg(null, pkg);else loadpkg(path$2.dirname(file), onpkg);
15753 function onpkg(err, pkg_, dir) {
15755 if (err) return cb(err);
15757 if (dir && pkg && opts.pathFilter) {
15758 var rfile = path$2.relative(dir, file);
15759 var rel = rfile.slice(0, rfile.length - exts[0].length);
15760 var r = opts.pathFilter(pkg, x, rel);
15761 if (r) return load([''].concat(extensions.slice()), path$2.resolve(dir, r), pkg);
15764 isFile(file, onex);
15767 function onex(err, ex) {
15768 if (err) return cb(err);
15769 if (ex) return cb(null, file, pkg);
15770 load(exts.slice(1), x, pkg);
15775 function loadpkg(dir, cb) {
15776 if (dir === '' || dir === '/') return cb(null);
15778 if (process.platform === 'win32' && /^\w:[/\\]*$/.test(dir)) {
15782 if (/[/\\]node_modules[/\\]*$/.test(dir)) return cb(null);
15783 var pkgfile = path$2.join(dir, 'package.json');
15784 isFile(pkgfile, function (err, ex) {
15785 // on err, ex is false
15786 if (!ex) return loadpkg(path$2.dirname(dir), cb);
15787 readFile(pkgfile, function (err, body) {
15791 var pkg = JSON.parse(body);
15792 } catch (jsonErr) {}
15794 if (pkg && opts.packageFilter) {
15795 pkg = opts.packageFilter(pkg, pkgfile);
15798 cb(null, pkg, dir);
15803 function loadAsDirectory(x, loadAsDirectoryPackage, callback) {
15805 var fpkg = loadAsDirectoryPackage;
15807 if (typeof fpkg === 'function') {
15809 fpkg = opts.package;
15812 var pkgfile = path$2.join(x, 'package.json');
15813 isFile(pkgfile, function (err, ex) {
15814 if (err) return cb(err);
15815 if (!ex) return loadAsFile(path$2.join(x, 'index'), fpkg, cb);
15816 readFile(pkgfile, function (err, body) {
15817 if (err) return cb(err);
15820 var pkg = JSON.parse(body);
15821 } catch (jsonErr) {}
15823 if (opts.packageFilter) {
15824 pkg = opts.packageFilter(pkg, pkgfile);
15828 if (typeof pkg.main !== 'string') {
15829 var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
15830 mainError.code = 'INVALID_PACKAGE_MAIN';
15831 return cb(mainError);
15834 if (pkg.main === '.' || pkg.main === './') {
15835 pkg.main = 'index';
15838 loadAsFile(path$2.resolve(x, pkg.main), pkg, function (err, m, pkg) {
15839 if (err) return cb(err);
15840 if (m) return cb(null, m, pkg);
15841 if (!pkg) return loadAsFile(path$2.join(x, 'index'), pkg, cb);
15842 var dir = path$2.resolve(x, pkg.main);
15843 loadAsDirectory(dir, pkg, function (err, n, pkg) {
15844 if (err) return cb(err);
15845 if (n) return cb(null, n, pkg);
15846 loadAsFile(path$2.join(x, 'index'), pkg, cb);
15852 loadAsFile(path$2.join(x, '/index'), pkg, cb);
15857 function processDirs(cb, dirs) {
15858 if (dirs.length === 0) return cb(null, undefined);
15860 isDirectory(dir, isdir);
15862 function isdir(err, isdir) {
15863 if (err) return cb(err);
15864 if (!isdir) return processDirs(cb, dirs.slice(1));
15865 var file = path$2.join(dir, x);
15866 loadAsFile(file, opts.package, onfile);
15869 function onfile(err, m, pkg) {
15870 if (err) return cb(err);
15871 if (m) return cb(null, m, pkg);
15872 loadAsDirectory(path$2.join(dir, x), opts.package, ondir);
15875 function ondir(err, n, pkg) {
15876 if (err) return cb(err);
15877 if (n) return cb(null, n, pkg);
15878 processDirs(cb, dirs.slice(1));
15882 function loadNodeModules(x, start, cb) {
15883 processDirs(cb, nodeModulesPaths(start, opts, x));
15887 var defaultIsFile$1 = function isFile(file) {
15889 var stat = fs$1.statSync(file);
15891 if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
15895 return stat.isFile() || stat.isFIFO();
15898 var defaultIsDir$1 = function isDirectory(dir) {
15900 var stat = fs$1.statSync(dir);
15902 if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
15906 return stat.isDirectory();
15909 var maybeUnwrapSymlink$1 = function maybeUnwrapSymlink(x, opts) {
15910 if (opts && opts.preserveSymlinks === false) {
15912 return fs$1.realpathSync(x);
15913 } catch (realPathErr) {
15914 if (realPathErr.code !== 'ENOENT') {
15923 var sync = function sync(x, options) {
15924 if (typeof x !== 'string') {
15925 throw new TypeError('Path must be a string.');
15928 var opts = normalizeOptions$2(x, options);
15929 var isFile = opts.isFile || defaultIsFile$1;
15930 var readFileSync = opts.readFileSync || fs$1.readFileSync;
15931 var isDirectory = opts.isDirectory || defaultIsDir$1;
15932 var extensions = opts.extensions || ['.js'];
15933 var basedir = opts.basedir || path$2.dirname(caller());
15934 var parent = opts.filename || basedir;
15935 opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
15937 var absoluteStart = maybeUnwrapSymlink$1(path$2.resolve(basedir), opts);
15939 if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
15940 var res = path$2.resolve(absoluteStart, x);
15941 if (x === '..' || x.slice(-1) === '/') res += '/';
15942 var m = loadAsFileSync(res) || loadAsDirectorySync(res);
15943 if (m) return maybeUnwrapSymlink$1(m, opts);
15944 } else if (core_1[x]) {
15947 var n = loadNodeModulesSync(x, absoluteStart);
15948 if (n) return maybeUnwrapSymlink$1(n, opts);
15951 if (core_1[x]) return x;
15952 var err = new Error("Cannot find module '" + x + "' from '" + parent + "'");
15953 err.code = 'MODULE_NOT_FOUND';
15956 function loadAsFileSync(x) {
15957 var pkg = loadpkg(path$2.dirname(x));
15959 if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) {
15960 var rfile = path$2.relative(pkg.dir, x);
15961 var r = opts.pathFilter(pkg.pkg, x, rfile);
15964 x = path$2.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign
15972 for (var i = 0; i < extensions.length; i++) {
15973 var file = x + extensions[i];
15975 if (isFile(file)) {
15981 function loadpkg(dir) {
15982 if (dir === '' || dir === '/') return;
15984 if (process.platform === 'win32' && /^\w:[/\\]*$/.test(dir)) {
15988 if (/[/\\]node_modules[/\\]*$/.test(dir)) return;
15989 var pkgfile = path$2.join(dir, 'package.json');
15991 if (!isFile(pkgfile)) {
15992 return loadpkg(path$2.dirname(dir));
15995 var body = readFileSync(pkgfile);
15998 var pkg = JSON.parse(body);
15999 } catch (jsonErr) {}
16001 if (pkg && opts.packageFilter) {
16002 pkg = opts.packageFilter(pkg, dir);
16011 function loadAsDirectorySync(x) {
16012 var pkgfile = path$2.join(x, '/package.json');
16014 if (isFile(pkgfile)) {
16016 var body = readFileSync(pkgfile, 'UTF8');
16017 var pkg = JSON.parse(body);
16020 if (opts.packageFilter) {
16021 pkg = opts.packageFilter(pkg, x);
16025 if (typeof pkg.main !== 'string') {
16026 var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
16027 mainError.code = 'INVALID_PACKAGE_MAIN';
16031 if (pkg.main === '.' || pkg.main === './') {
16032 pkg.main = 'index';
16036 var m = loadAsFileSync(path$2.resolve(x, pkg.main));
16038 var n = loadAsDirectorySync(path$2.resolve(x, pkg.main));
16044 return loadAsFileSync(path$2.join(x, '/index'));
16047 function loadNodeModulesSync(x, start) {
16048 var dirs = nodeModulesPaths(start, opts, x);
16050 for (var i = 0; i < dirs.length; i++) {
16053 if (isDirectory(dir)) {
16054 var m = loadAsFileSync(path$2.join(dir, '/', x));
16056 var n = loadAsDirectorySync(path$2.join(dir, '/', x));
16063 var resolve = createCommonjsModule(function (module, exports) {
16064 async.core = core_1;
16066 async.isCore = function isCore(x) {
16071 module.exports = async;
16074 var mimicFn = function mimicFn(to, from) {
16075 var _iteratorNormalCompletion = true;
16076 var _didIteratorError = false;
16077 var _iteratorError = undefined;
16080 for (var _iterator = Reflect.ownKeys(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
16081 var prop = _step.value;
16082 Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
16085 _didIteratorError = true;
16086 _iteratorError = err;
16089 if (!_iteratorNormalCompletion && _iterator.return != null) {
16090 _iterator.return();
16093 if (_didIteratorError) {
16094 throw _iteratorError;
16102 var mimicFn_1 = mimicFn; // TODO: Remove this for the next major release
16104 var default_1$4 = mimicFn;
16105 mimicFn_1.default = default_1$4;
16107 var isPromise = function isPromise(input) {
16108 return input instanceof Promise || input !== null && typeof input === 'object' && typeof input.then === 'function' && typeof input.catch === 'function';
16111 var pIsPromise = isPromise; // TODO: Remove this for the next major release
16113 var default_1$5 = isPromise;
16114 pIsPromise.default = default_1$5;
16116 var pDefer = function pDefer() {
16118 ret.promise = new Promise(function (resolve, reject) {
16119 ret.resolve = resolve;
16120 ret.reject = reject;
16125 var dist = createCommonjsModule(function (module, exports) {
16127 var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
16128 return new (P || (P = Promise))(function (resolve, reject) {
16129 function fulfilled(value) {
16131 step(generator.next(value));
16137 function rejected(value) {
16139 step(generator["throw"](value));
16145 function step(result) {
16146 result.done ? resolve(result.value) : new P(function (resolve) {
16147 resolve(result.value);
16148 }).then(fulfilled, rejected);
16151 step((generator = generator.apply(thisArg, _arguments || [])).next());
16155 var __importDefault = this && this.__importDefault || function (mod) {
16156 return mod && mod.__esModule ? mod : {
16161 Object.defineProperty(exports, "__esModule", {
16165 var p_defer_1 = __importDefault(pDefer);
16167 function mapAgeCleaner(map) {
16170 var property = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'maxAge';
16172 var processingTimer;
16173 var processingDeferred;
16175 var cleanup = function cleanup() {
16176 return __awaiter(_this, void 0, void 0,
16178 regeneratorRuntime.mark(function _callee2() {
16181 var setupTimer, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, entry;
16183 return regeneratorRuntime.wrap(function _callee2$(_context2) {
16185 switch (_context2.prev = _context2.next) {
16187 if (!(processingKey !== undefined)) {
16188 _context2.next = 2;
16192 return _context2.abrupt("return");
16195 setupTimer = function setupTimer(item) {
16196 return __awaiter(_this2, void 0, void 0,
16198 regeneratorRuntime.mark(function _callee() {
16200 return regeneratorRuntime.wrap(function _callee$(_context) {
16202 switch (_context.prev = _context.next) {
16204 processingDeferred = p_defer_1.default();
16205 delay = item[1][property] - Date.now();
16207 if (!(delay <= 0)) {
16212 // Remove the item immediately if the delay is equal to or below 0
16213 map.delete(item[0]);
16214 processingDeferred.resolve();
16215 return _context.abrupt("return");
16218 // Keep track of the current processed key
16219 processingKey = item[0];
16220 processingTimer = setTimeout(function () {
16221 // Remove the item when the timeout fires
16222 map.delete(item[0]);
16224 if (processingDeferred) {
16225 processingDeferred.resolve();
16227 }, delay); // tslint:disable-next-line:strict-type-predicates
16229 if (typeof processingTimer.unref === 'function') {
16230 // Don't hold up the process from exiting
16231 processingTimer.unref();
16234 return _context.abrupt("return", processingDeferred.promise);
16238 return _context.stop();
16245 _context2.prev = 3;
16246 _iteratorNormalCompletion = true;
16247 _didIteratorError = false;
16248 _iteratorError = undefined;
16249 _context2.prev = 7;
16250 _iterator = map[Symbol.iterator]();
16253 if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
16254 _context2.next = 16;
16258 entry = _step.value;
16259 _context2.next = 13;
16260 return setupTimer(entry);
16263 _iteratorNormalCompletion = true;
16264 _context2.next = 9;
16268 _context2.next = 22;
16272 _context2.prev = 18;
16273 _context2.t0 = _context2["catch"](7);
16274 _didIteratorError = true;
16275 _iteratorError = _context2.t0;
16278 _context2.prev = 22;
16279 _context2.prev = 23;
16281 if (!_iteratorNormalCompletion && _iterator.return != null) {
16282 _iterator.return();
16286 _context2.prev = 25;
16288 if (!_didIteratorError) {
16289 _context2.next = 28;
16293 throw _iteratorError;
16296 return _context2.finish(25);
16299 return _context2.finish(22);
16302 _context2.next = 34;
16306 _context2.prev = 32;
16307 _context2.t1 = _context2["catch"](3);
16310 processingKey = undefined;
16314 return _context2.stop();
16317 }, _callee2, null, [[3, 32], [7, 18, 22, 30], [23,, 25, 29]]);
16321 var reset = function reset() {
16322 processingKey = undefined;
16324 if (processingTimer !== undefined) {
16325 clearTimeout(processingTimer);
16326 processingTimer = undefined;
16329 if (processingDeferred !== undefined) {
16330 // tslint:disable-line:early-exit
16331 processingDeferred.reject(undefined);
16332 processingDeferred = undefined;
16336 var originalSet = map.set.bind(map);
16338 map.set = function (key, value) {
16339 if (map.has(key)) {
16340 // If the key already exist, remove it so we can add it back at the end of the map.
16342 } // Call the original `map.set`
16345 var result = originalSet(key, value); // If we are already processing a key and the key added is the current processed key, stop processing it
16347 if (processingKey && processingKey === key) {
16349 } // Always run the cleanup method in case it wasn't started yet
16352 cleanup(); // tslint:disable-line:no-floating-promises
16357 cleanup(); // tslint:disable-line:no-floating-promises
16362 exports.default = mapAgeCleaner; // Add support for CJS
16364 module.exports = mapAgeCleaner;
16365 module.exports.default = mapAgeCleaner;
16367 unwrapExports(dist);
16369 var cacheStore = new WeakMap();
16371 var defaultCacheKey = function defaultCacheKey() {
16372 for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) {
16373 arguments_[_key] = arguments[_key];
16376 if (arguments_.length === 0) {
16377 return '__defaultKey';
16380 if (arguments_.length === 1) {
16381 var firstArgument = arguments_[0];
16382 var isObject = typeof firstArgument === 'object' && firstArgument !== null;
16383 var isPrimitive = !isObject;
16386 return firstArgument;
16390 return JSON.stringify(arguments_);
16393 var mem = function mem(fn) {
16394 var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
16395 _ref$cacheKey = _ref.cacheKey,
16396 cacheKey = _ref$cacheKey === void 0 ? defaultCacheKey : _ref$cacheKey,
16397 _ref$cache = _ref.cache,
16398 cache = _ref$cache === void 0 ? new Map() : _ref$cache,
16399 _ref$cachePromiseReje = _ref.cachePromiseRejection,
16400 cachePromiseRejection = _ref$cachePromiseReje === void 0 ? true : _ref$cachePromiseReje,
16401 maxAge = _ref.maxAge;
16403 if (typeof maxAge === 'number') {
16407 var memoized = function memoized() {
16408 for (var _len2 = arguments.length, arguments_ = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
16409 arguments_[_key2] = arguments[_key2];
16412 var key = cacheKey.apply(void 0, arguments_);
16414 if (cache.has(key)) {
16415 return cache.get(key).data;
16418 var cacheItem = fn.apply(this, arguments_);
16421 maxAge: maxAge ? Date.now() + maxAge : Infinity
16424 if (pIsPromise(cacheItem) && cachePromiseRejection === false) {
16425 cacheItem.catch(function () {
16426 return cache.delete(key);
16434 // The below call will throw in some host environments
16435 // See https://github.com/sindresorhus/mimic-fn/issues/10
16436 mimicFn_1(memoized, fn);
16439 cacheStore.set(memoized, cache);
16445 var clear = function clear(fn) {
16446 var cache = cacheStore.get(fn);
16448 if (cache && typeof cache.clear === 'function') {
16452 mem_1.clear = clear;
16454 var semver$1 = createCommonjsModule(function (module, exports) {
16455 exports = module.exports = SemVer; // The debug function is excluded entirely from the minified version.
16462 if (typeof process === 'object' &&
16466 process.env.NODE_DEBUG &&
16468 /\bsemver\b/i.test(process.env.NODE_DEBUG))
16470 debug = function debug() {
16472 var args = Array.prototype.slice.call(arguments, 0);
16475 args.unshift('SEMVER');
16478 console.log.apply(console, args);
16484 debug = function debug() {}; // Note: this is the semver.org version of the spec that it implements
16485 // Not necessarily the package version of this code.
16487 exports.SEMVER_SPEC_VERSION = '2.0.0';
16488 var MAX_LENGTH = 256;
16489 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // Max safe segment length for coercion.
16491 var MAX_SAFE_COMPONENT_LENGTH = 16; // The actual regexps go on exports.re
16493 var re = exports.re = [];
16494 var src = exports.src = [];
16495 var R = 0; // The following Regular Expressions can be used for tokenizing,
16496 // validating, and parsing SemVer version strings.
16497 // ## Numeric Identifier
16498 // A single `0`, or a non-zero digit followed by zero or more digits.
16500 var NUMERICIDENTIFIER = R++;
16501 src[NUMERICIDENTIFIER] = '0|[1-9]\\d*';
16502 var NUMERICIDENTIFIERLOOSE = R++;
16503 src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier
16504 // Zero or more digits, followed by a letter or hyphen, and then zero or
16505 // more letters, digits, or hyphens.
16507 var NONNUMERICIDENTIFIER = R++;
16508 src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version
16509 // Three dot-separated numeric identifiers.
16511 var MAINVERSION = R++;
16512 src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')';
16513 var MAINVERSIONLOOSE = R++;
16514 src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier
16515 // A numeric identifier, or a non-numeric identifier.
16517 var PRERELEASEIDENTIFIER = R++;
16518 src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')';
16519 var PRERELEASEIDENTIFIERLOOSE = R++;
16520 src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version
16521 // Hyphen, followed by one or more dot-separated pre-release version
16524 var PRERELEASE = R++;
16525 src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))';
16526 var PRERELEASELOOSE = R++;
16527 src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier
16528 // Any combination of digits, letters, or hyphens.
16530 var BUILDIDENTIFIER = R++;
16531 src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata
16532 // Plus sign, followed by one or more period-separated build metadata
16536 src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; // ## Full Version String
16537 // A main version, followed optionally by a pre-release version and
16539 // Note that the only major, minor, patch, and pre-release sections of
16540 // the version string are capturing groups. The build metadata is not a
16541 // capturing group, because it should not ever be used in version
16545 var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?';
16546 src[FULL] = '^' + FULLPLAIN + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
16547 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
16548 // common in the npm registry.
16550 var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?';
16552 src[LOOSE] = '^' + LOOSEPLAIN + '$';
16554 src[GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x".
16555 // Note that "x.x" is a valid xRange identifer, meaning "any version"
16556 // Only the first item is strictly required.
16558 var XRANGEIDENTIFIERLOOSE = R++;
16559 src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
16560 var XRANGEIDENTIFIER = R++;
16561 src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*';
16562 var XRANGEPLAIN = R++;
16563 src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?';
16564 var XRANGEPLAINLOOSE = R++;
16565 src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?';
16567 src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$';
16568 var XRANGELOOSE = R++;
16569 src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; // Coercion.
16570 // Extract anything that could conceivably be a part of a valid semver
16573 src[COERCE] = '(?:^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])'; // Tilde ranges.
16574 // Meaning is "reasonably at or greater than"
16576 var LONETILDE = R++;
16577 src[LONETILDE] = '(?:~>?)';
16578 var TILDETRIM = R++;
16579 src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+';
16580 re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g');
16581 var tildeTrimReplace = '$1~';
16583 src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$';
16584 var TILDELOOSE = R++;
16585 src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; // Caret ranges.
16586 // Meaning is "at least and backwards compatible with"
16588 var LONECARET = R++;
16589 src[LONECARET] = '(?:\\^)';
16590 var CARETTRIM = R++;
16591 src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+';
16592 re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g');
16593 var caretTrimReplace = '$1^';
16595 src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$';
16596 var CARETLOOSE = R++;
16597 src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version"
16599 var COMPARATORLOOSE = R++;
16600 src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$';
16601 var COMPARATOR = R++;
16602 src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing
16603 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
16605 var COMPARATORTRIM = R++;
16606 src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; // this one has to use the /g flag
16608 re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g');
16609 var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
16610 // Note that these all use the loose form, because they'll be
16611 // checked against either the strict or loose comparator form
16614 var HYPHENRANGE = R++;
16615 src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$';
16616 var HYPHENRANGELOOSE = R++;
16617 src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all.
16620 src[STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects.
16621 // All are flag-free, unless they were created above with a flag.
16623 for (var i = 0; i < R; i++) {
16625 if (!re[i]) re[i] = new RegExp(src[i]);
16628 exports.parse = parse;
16630 function parse(version, options) {
16631 if (!options || typeof options !== 'object') options = {
16633 includePrerelease: false
16635 if (version instanceof SemVer) return version;
16636 if (typeof version !== 'string') return null;
16637 if (version.length > MAX_LENGTH) return null;
16638 var r = options.loose ? re[LOOSE] : re[FULL];
16639 if (!r.test(version)) return null;
16642 return new SemVer(version, options);
16648 exports.valid = valid;
16650 function valid(version, options) {
16651 var v = parse(version, options);
16652 return v ? v.version : null;
16655 exports.clean = clean;
16657 function clean(version, options) {
16658 var s = parse(version.trim().replace(/^[=v]+/, ''), options);
16659 return s ? s.version : null;
16662 exports.SemVer = SemVer;
16664 function SemVer(version, options) {
16665 if (!options || typeof options !== 'object') options = {
16667 includePrerelease: false
16670 if (version instanceof SemVer) {
16671 if (version.loose === options.loose) return version;else version = version.version;
16672 } else if (typeof version !== 'string') {
16673 throw new TypeError('Invalid Version: ' + version);
16676 if (version.length > MAX_LENGTH) throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters');
16677 if (!(this instanceof SemVer)) return new SemVer(version, options);
16678 debug('SemVer', version, options);
16679 this.options = options;
16680 this.loose = !!options.loose;
16681 var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]);
16682 if (!m) throw new TypeError('Invalid Version: ' + version);
16683 this.raw = version; // these are actually numbers
16685 this.major = +m[1];
16686 this.minor = +m[2];
16687 this.patch = +m[3];
16688 if (this.major > MAX_SAFE_INTEGER || this.major < 0) throw new TypeError('Invalid major version');
16689 if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) throw new TypeError('Invalid minor version');
16690 if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) throw new TypeError('Invalid patch version'); // numberify any prerelease numeric ids
16692 if (!m[4]) this.prerelease = [];else this.prerelease = m[4].split('.').map(function (id) {
16693 if (/^[0-9]+$/.test(id)) {
16695 if (num >= 0 && num < MAX_SAFE_INTEGER) return num;
16700 this.build = m[5] ? m[5].split('.') : [];
16704 SemVer.prototype.format = function () {
16705 this.version = this.major + '.' + this.minor + '.' + this.patch;
16706 if (this.prerelease.length) this.version += '-' + this.prerelease.join('.');
16707 return this.version;
16710 SemVer.prototype.toString = function () {
16711 return this.version;
16714 SemVer.prototype.compare = function (other) {
16715 debug('SemVer.compare', this.version, this.options, other);
16716 if (!(other instanceof SemVer)) other = new SemVer(other, this.options);
16717 return this.compareMain(other) || this.comparePre(other);
16720 SemVer.prototype.compareMain = function (other) {
16721 if (!(other instanceof SemVer)) other = new SemVer(other, this.options);
16722 return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
16725 SemVer.prototype.comparePre = function (other) {
16726 if (!(other instanceof SemVer)) other = new SemVer(other, this.options); // NOT having a prerelease is > having one
16728 if (this.prerelease.length && !other.prerelease.length) return -1;else if (!this.prerelease.length && other.prerelease.length) return 1;else if (!this.prerelease.length && !other.prerelease.length) return 0;
16732 var a = this.prerelease[i];
16733 var b = other.prerelease[i];
16734 debug('prerelease compare', i, a, b);
16735 if (a === undefined && b === undefined) return 0;else if (b === undefined) return 1;else if (a === undefined) return -1;else if (a === b) continue;else return compareIdentifiers(a, b);
16737 }; // preminor will bump the version up to the next minor release, and immediately
16738 // down to pre-release. premajor and prepatch work the same way.
16741 SemVer.prototype.inc = function (release, identifier) {
16744 this.prerelease.length = 0;
16748 this.inc('pre', identifier);
16752 this.prerelease.length = 0;
16755 this.inc('pre', identifier);
16759 // If this is already a prerelease, it will bump to the next version
16760 // drop any prereleases that might already exist, since they are not
16761 // relevant at this point.
16762 this.prerelease.length = 0;
16763 this.inc('patch', identifier);
16764 this.inc('pre', identifier);
16766 // If the input is a non-prerelease version, this acts the same as
16770 if (this.prerelease.length === 0) this.inc('patch', identifier);
16771 this.inc('pre', identifier);
16775 // If this is a pre-major version, bump up to the same major version.
16776 // Otherwise increment major.
16777 // 1.0.0-5 bumps to 1.0.0
16778 // 1.1.0 bumps to 2.0.0
16779 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) this.major++;
16782 this.prerelease = [];
16786 // If this is a pre-minor version, bump up to the same minor version.
16787 // Otherwise increment minor.
16788 // 1.2.0-5 bumps to 1.2.0
16789 // 1.2.1 bumps to 1.3.0
16790 if (this.patch !== 0 || this.prerelease.length === 0) this.minor++;
16792 this.prerelease = [];
16796 // If this is not a pre-release version, it will increment the patch.
16797 // If it is a pre-release it will bump up to the same patch version.
16798 // 1.2.0-5 patches to 1.2.0
16799 // 1.2.0 patches to 1.2.1
16800 if (this.prerelease.length === 0) this.patch++;
16801 this.prerelease = [];
16803 // This probably shouldn't be used publicly.
16804 // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
16807 if (this.prerelease.length === 0) this.prerelease = [0];else {
16808 var i = this.prerelease.length;
16811 if (typeof this.prerelease[i] === 'number') {
16812 this.prerelease[i]++;
16817 if (i === -1) // didn't increment anything
16818 this.prerelease.push(0);
16822 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
16823 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
16824 if (this.prerelease[0] === identifier) {
16825 if (isNaN(this.prerelease[1])) this.prerelease = [identifier, 0];
16826 } else this.prerelease = [identifier, 0];
16832 throw new Error('invalid increment argument: ' + release);
16836 this.raw = this.version;
16842 function inc(version, release, loose, identifier) {
16843 if (typeof loose === 'string') {
16844 identifier = loose;
16849 return new SemVer(version, loose).inc(release, identifier).version;
16855 exports.diff = diff;
16857 function diff(version1, version2) {
16858 if (eq(version1, version2)) {
16861 var v1 = parse(version1);
16862 var v2 = parse(version2);
16864 if (v1.prerelease.length || v2.prerelease.length) {
16865 for (var key in v1) {
16866 if (key === 'major' || key === 'minor' || key === 'patch') {
16867 if (v1[key] !== v2[key]) {
16868 return 'pre' + key;
16873 return 'prerelease';
16876 for (var key in v1) {
16877 if (key === 'major' || key === 'minor' || key === 'patch') {
16878 if (v1[key] !== v2[key]) {
16886 exports.compareIdentifiers = compareIdentifiers;
16887 var numeric = /^[0-9]+$/;
16889 function compareIdentifiers(a, b) {
16890 var anum = numeric.test(a);
16891 var bnum = numeric.test(b);
16893 if (anum && bnum) {
16898 return anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : a > b ? 1 : 0;
16901 exports.rcompareIdentifiers = rcompareIdentifiers;
16903 function rcompareIdentifiers(a, b) {
16904 return compareIdentifiers(b, a);
16907 exports.major = major;
16909 function major(a, loose) {
16910 return new SemVer(a, loose).major;
16913 exports.minor = minor;
16915 function minor(a, loose) {
16916 return new SemVer(a, loose).minor;
16919 exports.patch = patch;
16921 function patch(a, loose) {
16922 return new SemVer(a, loose).patch;
16925 exports.compare = compare;
16927 function compare(a, b, loose) {
16928 return new SemVer(a, loose).compare(new SemVer(b, loose));
16931 exports.compareLoose = compareLoose;
16933 function compareLoose(a, b) {
16934 return compare(a, b, true);
16937 exports.rcompare = rcompare;
16939 function rcompare(a, b, loose) {
16940 return compare(b, a, loose);
16943 exports.sort = sort;
16945 function sort(list, loose) {
16946 return list.sort(function (a, b) {
16947 return exports.compare(a, b, loose);
16951 exports.rsort = rsort;
16953 function rsort(list, loose) {
16954 return list.sort(function (a, b) {
16955 return exports.rcompare(a, b, loose);
16961 function gt(a, b, loose) {
16962 return compare(a, b, loose) > 0;
16967 function lt(a, b, loose) {
16968 return compare(a, b, loose) < 0;
16973 function eq(a, b, loose) {
16974 return compare(a, b, loose) === 0;
16979 function neq(a, b, loose) {
16980 return compare(a, b, loose) !== 0;
16985 function gte(a, b, loose) {
16986 return compare(a, b, loose) >= 0;
16991 function lte(a, b, loose) {
16992 return compare(a, b, loose) <= 0;
16997 function cmp(a, op, b, loose) {
17002 if (typeof a === 'object') a = a.version;
17003 if (typeof b === 'object') b = b.version;
17008 if (typeof a === 'object') a = a.version;
17009 if (typeof b === 'object') b = b.version;
17016 ret = eq(a, b, loose);
17020 ret = neq(a, b, loose);
17024 ret = gt(a, b, loose);
17028 ret = gte(a, b, loose);
17032 ret = lt(a, b, loose);
17036 ret = lte(a, b, loose);
17040 throw new TypeError('Invalid operator: ' + op);
17046 exports.Comparator = Comparator;
17048 function Comparator(comp, options) {
17049 if (!options || typeof options !== 'object') options = {
17051 includePrerelease: false
17054 if (comp instanceof Comparator) {
17055 if (comp.loose === !!options.loose) return comp;else comp = comp.value;
17058 if (!(this instanceof Comparator)) return new Comparator(comp, options);
17059 debug('comparator', comp, options);
17060 this.options = options;
17061 this.loose = !!options.loose;
17063 if (this.semver === ANY) this.value = '';else this.value = this.operator + this.semver.version;
17064 debug('comp', this);
17069 Comparator.prototype.parse = function (comp) {
17070 var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
17071 var m = comp.match(r);
17072 if (!m) throw new TypeError('Invalid comparator: ' + comp);
17073 this.operator = m[1];
17074 if (this.operator === '=') this.operator = ''; // if it literally is just '>' or '' then allow anything.
17076 if (!m[2]) this.semver = ANY;else this.semver = new SemVer(m[2], this.options.loose);
17079 Comparator.prototype.toString = function () {
17083 Comparator.prototype.test = function (version) {
17084 debug('Comparator.test', version, this.options.loose);
17085 if (this.semver === ANY) return true;
17086 if (typeof version === 'string') version = new SemVer(version, this.options);
17087 return cmp(version, this.operator, this.semver, this.options);
17090 Comparator.prototype.intersects = function (comp, options) {
17091 if (!(comp instanceof Comparator)) {
17092 throw new TypeError('a Comparator is required');
17095 if (!options || typeof options !== 'object') options = {
17097 includePrerelease: false
17101 if (this.operator === '') {
17102 rangeTmp = new Range(comp.value, options);
17103 return satisfies(this.value, rangeTmp, options);
17104 } else if (comp.operator === '') {
17105 rangeTmp = new Range(this.value, options);
17106 return satisfies(comp.semver, rangeTmp, options);
17109 var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>');
17110 var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<');
17111 var sameSemVer = this.semver.version === comp.semver.version;
17112 var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=');
17113 var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<');
17114 var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>');
17115 return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
17118 exports.Range = Range;
17120 function Range(range, options) {
17121 if (!options || typeof options !== 'object') options = {
17123 includePrerelease: false
17126 if (range instanceof Range) {
17127 if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
17130 return new Range(range.raw, options);
17134 if (range instanceof Comparator) {
17135 return new Range(range.value, options);
17138 if (!(this instanceof Range)) return new Range(range, options);
17139 this.options = options;
17140 this.loose = !!options.loose;
17141 this.includePrerelease = !!options.includePrerelease; // First, split based on boolean or ||
17144 this.set = range.split(/\s*\|\|\s*/).map(function (range) {
17145 return this.parseRange(range.trim());
17146 }, this).filter(function (c) {
17147 // throw out any that are not relevant for whatever reason
17151 if (!this.set.length) {
17152 throw new TypeError('Invalid SemVer Range: ' + range);
17158 Range.prototype.format = function () {
17159 this.range = this.set.map(function (comps) {
17160 return comps.join(' ').trim();
17161 }).join('||').trim();
17165 Range.prototype.toString = function () {
17169 Range.prototype.parseRange = function (range) {
17170 var loose = this.options.loose;
17171 range = range.trim(); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
17173 var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];
17174 range = range.replace(hr, hyphenReplace);
17175 debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
17177 range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);
17178 debug('comparator trim', range, re[COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3`
17180 range = range.replace(re[TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3`
17182 range = range.replace(re[CARETTRIM], caretTrimReplace); // normalize spaces
17184 range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and
17185 // ready to be split into comparators.
17187 var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
17188 var set = range.split(' ').map(function (comp) {
17189 return parseComparator(comp, this.options);
17190 }, this).join(' ').split(/\s+/);
17192 if (this.options.loose) {
17193 // in loose mode, throw out any that are not valid comparators
17194 set = set.filter(function (comp) {
17195 return !!comp.match(compRe);
17199 set = set.map(function (comp) {
17200 return new Comparator(comp, this.options);
17205 Range.prototype.intersects = function (range, options) {
17206 if (!(range instanceof Range)) {
17207 throw new TypeError('a Range is required');
17210 return this.set.some(function (thisComparators) {
17211 return thisComparators.every(function (thisComparator) {
17212 return range.set.some(function (rangeComparators) {
17213 return rangeComparators.every(function (rangeComparator) {
17214 return thisComparator.intersects(rangeComparator, options);
17219 }; // Mostly just for testing and legacy API reasons
17222 exports.toComparators = toComparators;
17224 function toComparators(range, options) {
17225 return new Range(range, options).set.map(function (comp) {
17226 return comp.map(function (c) {
17228 }).join(' ').trim().split(' ');
17230 } // comprised of xranges, tildes, stars, and gtlt's at this point.
17231 // already replaced the hyphen ranges
17232 // turn into a set of JUST comparators.
17235 function parseComparator(comp, options) {
17236 debug('comp', comp, options);
17237 comp = replaceCarets(comp, options);
17238 debug('caret', comp);
17239 comp = replaceTildes(comp, options);
17240 debug('tildes', comp);
17241 comp = replaceXRanges(comp, options);
17242 debug('xrange', comp);
17243 comp = replaceStars(comp, options);
17244 debug('stars', comp);
17249 return !id || id.toLowerCase() === 'x' || id === '*';
17250 } // ~, ~> --> * (any, kinda silly)
17251 // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
17252 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
17253 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
17254 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
17255 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
17258 function replaceTildes(comp, options) {
17259 return comp.trim().split(/\s+/).map(function (comp) {
17260 return replaceTilde(comp, options);
17264 function replaceTilde(comp, options) {
17265 if (!options || typeof options !== 'object') options = {
17267 includePrerelease: false
17269 var r = options.loose ? re[TILDELOOSE] : re[TILDE];
17270 return comp.replace(r, function (_, M, m, p, pr) {
17271 debug('tilde', comp, _, M, m, p, pr);
17273 if (isX(M)) ret = '';else if (isX(m)) ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';else if (isX(p)) // ~1.2 == >=1.2.0 <1.3.0
17274 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';else if (pr) {
17275 debug('replaceTilde pr', pr);
17276 if (pr.charAt(0) !== '-') pr = '-' + pr;
17277 ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0';
17278 } else // ~1.2.3 == >=1.2.3 <1.3.0
17279 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
17280 debug('tilde return', ret);
17283 } // ^ --> * (any, kinda silly)
17284 // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
17285 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
17286 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
17287 // ^1.2.3 --> >=1.2.3 <2.0.0
17288 // ^1.2.0 --> >=1.2.0 <2.0.0
17291 function replaceCarets(comp, options) {
17292 return comp.trim().split(/\s+/).map(function (comp) {
17293 return replaceCaret(comp, options);
17297 function replaceCaret(comp, options) {
17298 debug('caret', comp, options);
17299 if (!options || typeof options !== 'object') options = {
17301 includePrerelease: false
17303 var r = options.loose ? re[CARETLOOSE] : re[CARET];
17304 return comp.replace(r, function (_, M, m, p, pr) {
17305 debug('caret', comp, _, M, m, p, pr);
17307 if (isX(M)) ret = '';else if (isX(m)) ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';else if (isX(p)) {
17308 if (M === '0') ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';else ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
17310 debug('replaceCaret pr', pr);
17311 if (pr.charAt(0) !== '-') pr = '-' + pr;
17314 if (m === '0') ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + m + '.' + (+p + 1);else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0';
17315 } else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + (+M + 1) + '.0.0';
17320 if (m === '0') ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1);else ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
17321 } else ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0';
17323 debug('caret return', ret);
17328 function replaceXRanges(comp, options) {
17329 debug('replaceXRanges', comp, options);
17330 return comp.split(/\s+/).map(function (comp) {
17331 return replaceXRange(comp, options);
17335 function replaceXRange(comp, options) {
17336 comp = comp.trim();
17337 if (!options || typeof options !== 'object') options = {
17339 includePrerelease: false
17341 var r = options.loose ? re[XRANGELOOSE] : re[XRANGE];
17342 return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
17343 debug('xRange', comp, ret, gtlt, M, m, p, pr);
17345 var xm = xM || isX(m);
17346 var xp = xm || isX(p);
17348 if (gtlt === '=' && anyX) gtlt = '';
17351 if (gtlt === '>' || gtlt === '<') {
17352 // nothing is allowed
17355 // nothing is forbidden
17358 } else if (gtlt && anyX) {
17359 // replace X with 0
17363 if (gtlt === '>') {
17366 // >1.2.3 => >= 1.2.4
17377 } else if (gtlt === '<=') {
17378 // <=0.7.x is actually <0.8.0, since any 0.7.x should
17379 // pass. Similarly, <=7.x is actually <8.0.0, etc.
17381 if (xm) M = +M + 1;else m = +m + 1;
17384 ret = gtlt + M + '.' + m + '.' + p;
17386 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
17388 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
17391 debug('xRange return', ret);
17394 } // Because * is AND-ed with everything else in the comparator,
17395 // and '' means "any version", just remove the *s entirely.
17398 function replaceStars(comp, options) {
17399 debug('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets!
17401 return comp.trim().replace(re[STAR], '');
17402 } // This function is passed to string.replace(re[HYPHENRANGE])
17403 // M, m, patch, prerelease, build
17404 // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
17405 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
17406 // 1.2 - 3.4 => >=1.2.0 <3.5.0
17409 function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
17410 if (isX(fM)) from = '';else if (isX(fm)) from = '>=' + fM + '.0.0';else if (isX(fp)) from = '>=' + fM + '.' + fm + '.0';else from = '>=' + from;
17411 if (isX(tM)) to = '';else if (isX(tm)) to = '<' + (+tM + 1) + '.0.0';else if (isX(tp)) to = '<' + tM + '.' + (+tm + 1) + '.0';else if (tpr) to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;else to = '<=' + to;
17412 return (from + ' ' + to).trim();
17413 } // if ANY of the sets match ALL of its comparators, then pass
17416 Range.prototype.test = function (version) {
17417 if (!version) return false;
17418 if (typeof version === 'string') version = new SemVer(version, this.options);
17420 for (var i = 0; i < this.set.length; i++) {
17421 if (testSet(this.set[i], version, this.options)) return true;
17427 function testSet(set, version, options) {
17428 for (var i = 0; i < set.length; i++) {
17429 if (!set[i].test(version)) return false;
17432 if (!options) options = {};
17434 if (version.prerelease.length && !options.includePrerelease) {
17435 // Find the set of versions that are allowed to have prereleases
17436 // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
17437 // That should allow `1.2.3-pr.2` to pass.
17438 // However, `1.2.4-alpha.notready` should NOT be allowed,
17439 // even though it's within the range set by the comparators.
17440 for (var i = 0; i < set.length; i++) {
17441 debug(set[i].semver);
17442 if (set[i].semver === ANY) continue;
17444 if (set[i].semver.prerelease.length > 0) {
17445 var allowed = set[i].semver;
17446 if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) return true;
17448 } // Version has a -pre, but it's not one of the ones we like.
17457 exports.satisfies = satisfies;
17459 function satisfies(version, range, options) {
17461 range = new Range(range, options);
17466 return range.test(version);
17469 exports.maxSatisfying = maxSatisfying;
17471 function maxSatisfying(versions, range, options) {
17476 var rangeObj = new Range(range, options);
17481 versions.forEach(function (v) {
17482 if (rangeObj.test(v)) {
17483 // satisfies(v, range, options)
17484 if (!max || maxSV.compare(v) === -1) {
17485 // compare(max, v, true)
17487 maxSV = new SemVer(max, options);
17494 exports.minSatisfying = minSatisfying;
17496 function minSatisfying(versions, range, options) {
17501 var rangeObj = new Range(range, options);
17506 versions.forEach(function (v) {
17507 if (rangeObj.test(v)) {
17508 // satisfies(v, range, options)
17509 if (!min || minSV.compare(v) === 1) {
17510 // compare(min, v, true)
17512 minSV = new SemVer(min, options);
17519 exports.validRange = validRange;
17521 function validRange(range, options) {
17523 // Return '*' instead of '' so that truthiness works.
17524 // This will throw if it's invalid anyway
17525 return new Range(range, options).range || '*';
17529 } // Determine if version is less than all the versions possible in the range
17534 function ltr(version, range, options) {
17535 return outside(version, range, '<', options);
17536 } // Determine if version is greater than all the versions possible in the range.
17541 function gtr(version, range, options) {
17542 return outside(version, range, '>', options);
17545 exports.outside = outside;
17547 function outside(version, range, hilo, options) {
17548 version = new SemVer(version, options);
17549 range = new Range(range, options);
17550 var gtfn, ltefn, ltfn, comp, ecomp;
17570 throw new TypeError('Must provide a hilo val of "<" or ">"');
17571 } // If it satisifes the range it is not outside
17574 if (satisfies(version, range, options)) {
17576 } // From now on, variable terms are as if we're in "gtr" mode.
17577 // but note that everything is flipped for the "ltr" function.
17580 for (var i = 0; i < range.set.length; ++i) {
17581 var comparators = range.set[i];
17584 comparators.forEach(function (comparator) {
17585 if (comparator.semver === ANY) {
17586 comparator = new Comparator('>=0.0.0');
17589 high = high || comparator;
17590 low = low || comparator;
17592 if (gtfn(comparator.semver, high.semver, options)) {
17594 } else if (ltfn(comparator.semver, low.semver, options)) {
17597 }); // If the edge version comparator has a operator then our version
17598 // isn't outside it
17600 if (high.operator === comp || high.operator === ecomp) {
17602 } // If the lowest version comparator has an operator and our version
17603 // is less than it then it isn't higher than the range
17606 if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
17608 } else if (low.operator === ecomp && ltfn(version, low.semver)) {
17616 exports.prerelease = prerelease;
17618 function prerelease(version, options) {
17619 var parsed = parse(version, options);
17620 return parsed && parsed.prerelease.length ? parsed.prerelease : null;
17623 exports.intersects = intersects;
17625 function intersects(r1, r2, options) {
17626 r1 = new Range(r1, options);
17627 r2 = new Range(r2, options);
17628 return r1.intersects(r2);
17631 exports.coerce = coerce;
17633 function coerce(version) {
17634 if (version instanceof SemVer) return version;
17635 if (typeof version !== 'string') return null;
17636 var match = version.match(re[COERCE]);
17637 if (match == null) return null;
17638 return parse((match[1] || '0') + '.' + (match[2] || '0') + '.' + (match[3] || '0'));
17641 var semver_1$1 = semver$1.SEMVER_SPEC_VERSION;
17642 var semver_2$1 = semver$1.re;
17643 var semver_3$1 = semver$1.src;
17644 var semver_4$1 = semver$1.parse;
17645 var semver_5$1 = semver$1.valid;
17646 var semver_6$1 = semver$1.clean;
17647 var semver_7$1 = semver$1.SemVer;
17648 var semver_8$1 = semver$1.inc;
17649 var semver_9$1 = semver$1.diff;
17650 var semver_10$1 = semver$1.compareIdentifiers;
17651 var semver_11$1 = semver$1.rcompareIdentifiers;
17652 var semver_12$1 = semver$1.major;
17653 var semver_13$1 = semver$1.minor;
17654 var semver_14$1 = semver$1.patch;
17655 var semver_15$1 = semver$1.compare;
17656 var semver_16$1 = semver$1.compareLoose;
17657 var semver_17$1 = semver$1.rcompare;
17658 var semver_18$1 = semver$1.sort;
17659 var semver_19$1 = semver$1.rsort;
17660 var semver_20$1 = semver$1.gt;
17661 var semver_21$1 = semver$1.lt;
17662 var semver_22$1 = semver$1.eq;
17663 var semver_23$1 = semver$1.neq;
17664 var semver_24$1 = semver$1.gte;
17665 var semver_25$1 = semver$1.lte;
17666 var semver_26$1 = semver$1.cmp;
17667 var semver_27$1 = semver$1.Comparator;
17668 var semver_28$1 = semver$1.Range;
17669 var semver_29$1 = semver$1.toComparators;
17670 var semver_30$1 = semver$1.satisfies;
17671 var semver_31$1 = semver$1.maxSatisfying;
17672 var semver_32$1 = semver$1.minSatisfying;
17673 var semver_33$1 = semver$1.validRange;
17674 var semver_34$1 = semver$1.ltr;
17675 var semver_35$1 = semver$1.gtr;
17676 var semver_36$1 = semver$1.outside;
17677 var semver_37$1 = semver$1.prerelease;
17678 var semver_38$1 = semver$1.intersects;
17679 var semver_39$1 = semver$1.coerce;
17681 var hasOwnProperty = Object.prototype.hasOwnProperty;
17682 var pseudomap = PseudoMap;
17684 function PseudoMap(set) {
17685 if (!(this instanceof PseudoMap)) // whyyyyyyy
17686 throw new TypeError("Constructor PseudoMap requires 'new'");
17690 if (set instanceof PseudoMap || typeof Map === 'function' && set instanceof Map) set.forEach(function (value, key) {
17691 this.set(key, value);
17692 }, this);else if (Array.isArray(set)) set.forEach(function (kv) {
17693 this.set(kv[0], kv[1]);
17694 }, this);else throw new TypeError('invalid argument');
17698 PseudoMap.prototype.forEach = function (fn, thisp) {
17699 thisp = thisp || this;
17700 Object.keys(this._data).forEach(function (k) {
17701 if (k !== 'size') fn.call(thisp, this._data[k].value, this._data[k].key);
17705 PseudoMap.prototype.has = function (k) {
17706 return !!find(this._data, k);
17709 PseudoMap.prototype.get = function (k) {
17710 var res = find(this._data, k);
17711 return res && res.value;
17714 PseudoMap.prototype.set = function (k, v) {
17715 set(this._data, k, v);
17718 PseudoMap.prototype.delete = function (k) {
17719 var res = find(this._data, k);
17722 delete this._data[res._index];
17727 PseudoMap.prototype.clear = function () {
17728 var data = Object.create(null);
17730 Object.defineProperty(this, '_data', {
17733 configurable: true,
17738 Object.defineProperty(PseudoMap.prototype, 'size', {
17739 get: function get() {
17740 return this._data.size;
17742 set: function set(n) {},
17747 PseudoMap.prototype.values = PseudoMap.prototype.keys = PseudoMap.prototype.entries = function () {
17748 throw new Error('iterators are not implemented in this version');
17749 }; // Either identical, or both NaN
17752 function same(a, b) {
17753 return a === b || a !== a && b !== b;
17756 function Entry(k, v, i) {
17762 function find(data, k) {
17763 for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) {
17764 if (same(data[key].key, k)) return data[key];
17768 function set(data, k, v) {
17769 for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) {
17770 if (same(data[key].key, k)) {
17771 data[key].value = v;
17777 data[key] = new Entry(k, v, key);
17780 var map = createCommonjsModule(function (module) {
17781 if (process.env.npm_package_name === 'pseudomap' && process.env.npm_lifecycle_script === 'test') process.env.TEST_PSEUDOMAP = 'true';
17783 if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) {
17784 module.exports = Map;
17786 module.exports = pseudomap;
17790 var yallist = Yallist;
17791 Yallist.Node = Node;
17792 Yallist.create = Yallist;
17794 function Yallist(list) {
17797 if (!(self instanceof Yallist)) {
17798 self = new Yallist();
17805 if (list && typeof list.forEach === 'function') {
17806 list.forEach(function (item) {
17809 } else if (arguments.length > 0) {
17810 for (var i = 0, l = arguments.length; i < l; i++) {
17811 self.push(arguments[i]);
17818 Yallist.prototype.removeNode = function (node) {
17819 if (node.list !== this) {
17820 throw new Error('removing node which does not belong to this list');
17823 var next = node.next;
17824 var prev = node.prev;
17834 if (node === this.head) {
17838 if (node === this.tail) {
17842 node.list.length--;
17848 Yallist.prototype.unshiftNode = function (node) {
17849 if (node === this.head) {
17854 node.list.removeNode(node);
17857 var head = this.head;
17874 Yallist.prototype.pushNode = function (node) {
17875 if (node === this.tail) {
17880 node.list.removeNode(node);
17883 var tail = this.tail;
17900 Yallist.prototype.push = function () {
17901 for (var i = 0, l = arguments.length; i < l; i++) {
17902 push(this, arguments[i]);
17905 return this.length;
17908 Yallist.prototype.unshift = function () {
17909 for (var i = 0, l = arguments.length; i < l; i++) {
17910 unshift(this, arguments[i]);
17913 return this.length;
17916 Yallist.prototype.pop = function () {
17921 var res = this.tail.value;
17922 this.tail = this.tail.prev;
17925 this.tail.next = null;
17934 Yallist.prototype.shift = function () {
17939 var res = this.head.value;
17940 this.head = this.head.next;
17943 this.head.prev = null;
17952 Yallist.prototype.forEach = function (fn, thisp) {
17953 thisp = thisp || this;
17955 for (var walker = this.head, i = 0; walker !== null; i++) {
17956 fn.call(thisp, walker.value, i, this);
17957 walker = walker.next;
17961 Yallist.prototype.forEachReverse = function (fn, thisp) {
17962 thisp = thisp || this;
17964 for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
17965 fn.call(thisp, walker.value, i, this);
17966 walker = walker.prev;
17970 Yallist.prototype.get = function (n) {
17971 for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
17972 // abort out of the list early if we hit a cycle
17973 walker = walker.next;
17976 if (i === n && walker !== null) {
17977 return walker.value;
17981 Yallist.prototype.getReverse = function (n) {
17982 for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
17983 // abort out of the list early if we hit a cycle
17984 walker = walker.prev;
17987 if (i === n && walker !== null) {
17988 return walker.value;
17992 Yallist.prototype.map = function (fn, thisp) {
17993 thisp = thisp || this;
17994 var res = new Yallist();
17996 for (var walker = this.head; walker !== null;) {
17997 res.push(fn.call(thisp, walker.value, this));
17998 walker = walker.next;
18004 Yallist.prototype.mapReverse = function (fn, thisp) {
18005 thisp = thisp || this;
18006 var res = new Yallist();
18008 for (var walker = this.tail; walker !== null;) {
18009 res.push(fn.call(thisp, walker.value, this));
18010 walker = walker.prev;
18016 Yallist.prototype.reduce = function (fn, initial) {
18018 var walker = this.head;
18020 if (arguments.length > 1) {
18022 } else if (this.head) {
18023 walker = this.head.next;
18024 acc = this.head.value;
18026 throw new TypeError('Reduce of empty list with no initial value');
18029 for (var i = 0; walker !== null; i++) {
18030 acc = fn(acc, walker.value, i);
18031 walker = walker.next;
18037 Yallist.prototype.reduceReverse = function (fn, initial) {
18039 var walker = this.tail;
18041 if (arguments.length > 1) {
18043 } else if (this.tail) {
18044 walker = this.tail.prev;
18045 acc = this.tail.value;
18047 throw new TypeError('Reduce of empty list with no initial value');
18050 for (var i = this.length - 1; walker !== null; i--) {
18051 acc = fn(acc, walker.value, i);
18052 walker = walker.prev;
18058 Yallist.prototype.toArray = function () {
18059 var arr = new Array(this.length);
18061 for (var i = 0, walker = this.head; walker !== null; i++) {
18062 arr[i] = walker.value;
18063 walker = walker.next;
18069 Yallist.prototype.toArrayReverse = function () {
18070 var arr = new Array(this.length);
18072 for (var i = 0, walker = this.tail; walker !== null; i++) {
18073 arr[i] = walker.value;
18074 walker = walker.prev;
18080 Yallist.prototype.slice = function (from, to) {
18081 to = to || this.length;
18090 from += this.length;
18093 var ret = new Yallist();
18095 if (to < from || to < 0) {
18103 if (to > this.length) {
18107 for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
18108 walker = walker.next;
18111 for (; walker !== null && i < to; i++, walker = walker.next) {
18112 ret.push(walker.value);
18118 Yallist.prototype.sliceReverse = function (from, to) {
18119 to = to || this.length;
18128 from += this.length;
18131 var ret = new Yallist();
18133 if (to < from || to < 0) {
18141 if (to > this.length) {
18145 for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
18146 walker = walker.prev;
18149 for (; walker !== null && i > from; i--, walker = walker.prev) {
18150 ret.push(walker.value);
18156 Yallist.prototype.reverse = function () {
18157 var head = this.head;
18158 var tail = this.tail;
18160 for (var walker = head; walker !== null; walker = walker.prev) {
18161 var p = walker.prev;
18162 walker.prev = walker.next;
18171 function push(self, item) {
18172 self.tail = new Node(item, self.tail, null, self);
18175 self.head = self.tail;
18181 function unshift(self, item) {
18182 self.head = new Node(item, null, self.head, self);
18185 self.tail = self.head;
18191 function Node(value, prev, next, list) {
18192 if (!(this instanceof Node)) {
18193 return new Node(value, prev, next, list);
18197 this.value = value;
18214 var lruCache = LRUCache; // This will be a proper iterable 'Map' in engines that support it,
18215 // or a fakey-fake PseudoMap in older versions.
18216 // A linked list to keep track of recently-used-ness
18217 // use symbols if possible, otherwise just _props
18219 var hasSymbol = typeof Symbol === 'function' && process.env._nodeLRUCacheForceNoSymbol !== '1';
18223 makeSymbol = function makeSymbol(key) {
18224 return Symbol(key);
18227 makeSymbol = function makeSymbol(key) {
18232 var MAX = makeSymbol('max');
18233 var LENGTH = makeSymbol('length');
18234 var LENGTH_CALCULATOR = makeSymbol('lengthCalculator');
18235 var ALLOW_STALE = makeSymbol('allowStale');
18236 var MAX_AGE = makeSymbol('maxAge');
18237 var DISPOSE = makeSymbol('dispose');
18238 var NO_DISPOSE_ON_SET = makeSymbol('noDisposeOnSet');
18239 var LRU_LIST = makeSymbol('lruList');
18240 var CACHE = makeSymbol('cache');
18242 function naiveLength() {
18244 } // lruList is a yallist where the head is the youngest
18245 // item, and the tail is the oldest. the list contains the Hit
18246 // objects as the entries.
18247 // Each Hit object has a reference to its Yallist.Node. This
18250 // cache is a Map (or PseudoMap) that matches the keys to
18251 // the Yallist.Node object.
18254 function LRUCache(options) {
18255 if (!(this instanceof LRUCache)) {
18256 return new LRUCache(options);
18259 if (typeof options === 'number') {
18269 var max = this[MAX] = options.max; // Kind of weird to have a default max of Infinity, but oh well.
18271 if (!max || !(typeof max === 'number') || max <= 0) {
18272 this[MAX] = Infinity;
18275 var lc = options.length || naiveLength;
18277 if (typeof lc !== 'function') {
18281 this[LENGTH_CALCULATOR] = lc;
18282 this[ALLOW_STALE] = options.stale || false;
18283 this[MAX_AGE] = options.maxAge || 0;
18284 this[DISPOSE] = options.dispose;
18285 this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
18287 } // resize the cache when the max changes.
18290 Object.defineProperty(LRUCache.prototype, 'max', {
18291 set: function set(mL) {
18292 if (!mL || !(typeof mL === 'number') || mL <= 0) {
18299 get: function get() {
18304 Object.defineProperty(LRUCache.prototype, 'allowStale', {
18305 set: function set(allowStale) {
18306 this[ALLOW_STALE] = !!allowStale;
18308 get: function get() {
18309 return this[ALLOW_STALE];
18313 Object.defineProperty(LRUCache.prototype, 'maxAge', {
18314 set: function set(mA) {
18315 if (!mA || !(typeof mA === 'number') || mA < 0) {
18319 this[MAX_AGE] = mA;
18322 get: function get() {
18323 return this[MAX_AGE];
18326 }); // resize the cache when the lengthCalculator changes.
18328 Object.defineProperty(LRUCache.prototype, 'lengthCalculator', {
18329 set: function set(lC) {
18330 if (typeof lC !== 'function') {
18334 if (lC !== this[LENGTH_CALCULATOR]) {
18335 this[LENGTH_CALCULATOR] = lC;
18337 this[LRU_LIST].forEach(function (hit) {
18338 hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
18339 this[LENGTH] += hit.length;
18345 get: function get() {
18346 return this[LENGTH_CALCULATOR];
18350 Object.defineProperty(LRUCache.prototype, 'length', {
18351 get: function get() {
18352 return this[LENGTH];
18356 Object.defineProperty(LRUCache.prototype, 'itemCount', {
18357 get: function get() {
18358 return this[LRU_LIST].length;
18363 LRUCache.prototype.rforEach = function (fn, thisp) {
18364 thisp = thisp || this;
18366 for (var walker = this[LRU_LIST].tail; walker !== null;) {
18367 var prev = walker.prev;
18368 forEachStep(this, fn, walker, thisp);
18373 function forEachStep(self, fn, node, thisp) {
18374 var hit = node.value;
18376 if (isStale(self, hit)) {
18379 if (!self[ALLOW_STALE]) {
18385 fn.call(thisp, hit.value, hit.key, self);
18389 LRUCache.prototype.forEach = function (fn, thisp) {
18390 thisp = thisp || this;
18392 for (var walker = this[LRU_LIST].head; walker !== null;) {
18393 var next = walker.next;
18394 forEachStep(this, fn, walker, thisp);
18399 LRUCache.prototype.keys = function () {
18400 return this[LRU_LIST].toArray().map(function (k) {
18405 LRUCache.prototype.values = function () {
18406 return this[LRU_LIST].toArray().map(function (k) {
18411 LRUCache.prototype.reset = function () {
18412 if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) {
18413 this[LRU_LIST].forEach(function (hit) {
18414 this[DISPOSE](hit.key, hit.value);
18418 this[CACHE] = new map(); // hash of items by key
18420 this[LRU_LIST] = new yallist(); // list of items in order of use recency
18422 this[LENGTH] = 0; // length of items in the list
18425 LRUCache.prototype.dump = function () {
18426 return this[LRU_LIST].map(function (hit) {
18427 if (!isStale(this, hit)) {
18431 e: hit.now + (hit.maxAge || 0)
18434 }, this).toArray().filter(function (h) {
18439 LRUCache.prototype.dumpLru = function () {
18440 return this[LRU_LIST];
18442 /* istanbul ignore next */
18445 LRUCache.prototype.inspect = function (n, opts) {
18446 var str = 'LRUCache {';
18447 var extras = false;
18448 var as = this[ALLOW_STALE];
18451 str += '\n allowStale: true';
18455 var max = this[MAX];
18457 if (max && max !== Infinity) {
18462 str += '\n max: ' + util$3.inspect(max, opts);
18466 var maxAge = this[MAX_AGE];
18473 str += '\n maxAge: ' + util$3.inspect(maxAge, opts);
18477 var lc = this[LENGTH_CALCULATOR];
18479 if (lc && lc !== naiveLength) {
18484 str += '\n length: ' + util$3.inspect(this[LENGTH], opts);
18488 var didFirst = false;
18489 this[LRU_LIST].forEach(function (item) {
18501 var key = util$3.inspect(item.key).split('\n').join('\n ');
18506 if (item.maxAge !== maxAge) {
18507 val.maxAge = item.maxAge;
18510 if (lc !== naiveLength) {
18511 val.length = item.length;
18514 if (isStale(this, item)) {
18518 val = util$3.inspect(val, opts).split('\n').join('\n ');
18519 str += key + ' => ' + val;
18522 if (didFirst || extras) {
18530 LRUCache.prototype.set = function (key, value, maxAge) {
18531 maxAge = maxAge || this[MAX_AGE];
18532 var now = maxAge ? Date.now() : 0;
18533 var len = this[LENGTH_CALCULATOR](value, key);
18535 if (this[CACHE].has(key)) {
18536 if (len > this[MAX]) {
18537 del(this, this[CACHE].get(key));
18541 var node = this[CACHE].get(key);
18542 var item = node.value; // dispose of the old one before overwriting
18543 // split out into 2 ifs for better coverage tracking
18545 if (this[DISPOSE]) {
18546 if (!this[NO_DISPOSE_ON_SET]) {
18547 this[DISPOSE](key, item.value);
18552 item.maxAge = maxAge;
18553 item.value = value;
18554 this[LENGTH] += len - item.length;
18561 var hit = new Entry$1(key, value, len, now, maxAge); // oversized objects fall out of cache automatically.
18563 if (hit.length > this[MAX]) {
18564 if (this[DISPOSE]) {
18565 this[DISPOSE](key, value);
18571 this[LENGTH] += hit.length;
18572 this[LRU_LIST].unshift(hit);
18573 this[CACHE].set(key, this[LRU_LIST].head);
18578 LRUCache.prototype.has = function (key) {
18579 if (!this[CACHE].has(key)) return false;
18580 var hit = this[CACHE].get(key).value;
18582 if (isStale(this, hit)) {
18589 LRUCache.prototype.get = function (key) {
18590 return get(this, key, true);
18593 LRUCache.prototype.peek = function (key) {
18594 return get(this, key, false);
18597 LRUCache.prototype.pop = function () {
18598 var node = this[LRU_LIST].tail;
18599 if (!node) return null;
18604 LRUCache.prototype.del = function (key) {
18605 del(this, this[CACHE].get(key));
18608 LRUCache.prototype.load = function (arr) {
18611 var now = Date.now(); // A previous serialized cache has the most recent items first
18613 for (var l = arr.length - 1; l >= 0; l--) {
18615 var expiresAt = hit.e || 0;
18617 if (expiresAt === 0) {
18618 // the item was created without expiration in a non aged cache
18619 this.set(hit.k, hit.v);
18621 var maxAge = expiresAt - now; // dont add already expired items
18624 this.set(hit.k, hit.v, maxAge);
18630 LRUCache.prototype.prune = function () {
18632 this[CACHE].forEach(function (value, key) {
18633 get(self, key, false);
18637 function get(self, key, doUse) {
18638 var node = self[CACHE].get(key);
18641 var hit = node.value;
18643 if (isStale(self, hit)) {
18645 if (!self[ALLOW_STALE]) hit = undefined;
18648 self[LRU_LIST].unshiftNode(node);
18652 if (hit) hit = hit.value;
18658 function isStale(self, hit) {
18659 if (!hit || !hit.maxAge && !self[MAX_AGE]) {
18664 var diff = Date.now() - hit.now;
18667 stale = diff > hit.maxAge;
18669 stale = self[MAX_AGE] && diff > self[MAX_AGE];
18675 function trim$2(self) {
18676 if (self[LENGTH] > self[MAX]) {
18677 for (var walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) {
18678 // We know that we're about to delete this one, and also
18679 // what the next least recently used key will be, so just
18680 // go ahead and set it now.
18681 var prev = walker.prev;
18688 function del(self, node) {
18690 var hit = node.value;
18692 if (self[DISPOSE]) {
18693 self[DISPOSE](hit.key, hit.value);
18696 self[LENGTH] -= hit.length;
18697 self[CACHE].delete(hit.key);
18698 self[LRU_LIST].removeNode(node);
18700 } // classy, since V8 prefers predictable objects.
18703 function Entry$1(key, value, length, now, maxAge) {
18705 this.value = value;
18706 this.length = length;
18708 this.maxAge = maxAge || 0;
18711 var sigmund_1 = sigmund;
18713 function sigmund(subject, maxSessions) {
18714 maxSessions = maxSessions || 10;
18719 function psychoAnalyze(subject, session) {
18720 if (session > maxSessions) return;
18722 if (typeof subject === 'function' || typeof subject === 'undefined') {
18726 if (typeof subject !== 'object' || !subject || subject instanceof RE) {
18727 analysis += subject;
18731 if (notes.indexOf(subject) !== -1 || session === maxSessions) return;
18732 notes.push(subject);
18734 Object.keys(subject).forEach(function (issue, _, __) {
18735 // pseudo-private values. skip those.
18736 if (issue.charAt(0) === '_') return;
18737 var to = typeof subject[issue];
18738 if (to === 'function' || to === 'undefined') return;
18740 psychoAnalyze(subject[issue], session + 1);
18744 psychoAnalyze(subject, 0);
18746 } // vim: set softtabstop=4 shiftwidth=4:
18748 var fnmatch = createCommonjsModule(function (module, exports) {
18749 // Based on minimatch.js by isaacs <https://npmjs.org/package/minimatch>
18750 var platform = typeof process === "object" ? process.platform : "win32";
18751 if (module) module.exports = minimatch;else exports.minimatch = minimatch;
18752 minimatch.Minimatch = Minimatch;
18753 var cache = minimatch.cache = new lruCache({
18756 GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
18757 var qmark = "[^/]" // * => any number of characters
18759 star = qmark + "*?" // ** when dots are allowed. Anything goes, except .. and .
18760 // not (^ or / followed by one or two dots followed by $ or /),
18761 // followed by anything, any number of times.
18763 twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" // not a ^ or / followed by a dot,
18764 // followed by anything, any number of times.
18766 twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" // characters that need to be escaped in RegExp.
18768 reSpecials = charSet("().*{}+?[]^$\\!"); // "abc" -> { a:true, b:true, c:true }
18770 function charSet(s) {
18771 return s.split("").reduce(function (set, c) {
18775 } // normalizes slashes.
18778 var slashSplit = /\/+/;
18779 minimatch.monkeyPatch = monkeyPatch;
18781 function monkeyPatch() {
18782 var desc = Object.getOwnPropertyDescriptor(String.prototype, "match");
18783 var orig = desc.value;
18785 desc.value = function (p) {
18786 if (p instanceof Minimatch) return p.match(this);
18787 return orig.call(this, p);
18790 Object.defineProperty(String.prototype, desc);
18793 minimatch.filter = filter;
18795 function filter(pattern, options) {
18796 options = options || {};
18797 return function (p, i, list) {
18798 return minimatch(p, pattern, options);
18802 function ext(a, b) {
18806 Object.keys(b).forEach(function (k) {
18809 Object.keys(a).forEach(function (k) {
18815 minimatch.defaults = function (def) {
18816 if (!def || !Object.keys(def).length) return minimatch;
18817 var orig = minimatch;
18819 var m = function minimatch(p, pattern, options) {
18820 return orig.minimatch(p, pattern, ext(def, options));
18823 m.Minimatch = function Minimatch(pattern, options) {
18824 return new orig.Minimatch(pattern, ext(def, options));
18830 Minimatch.defaults = function (def) {
18831 if (!def || !Object.keys(def).length) return Minimatch;
18832 return minimatch.defaults(def).Minimatch;
18835 function minimatch(p, pattern, options) {
18836 if (typeof pattern !== "string") {
18837 throw new TypeError("glob pattern string required");
18840 if (!options) options = {}; // shortcut: comments match nothing.
18842 if (!options.nocomment && pattern.charAt(0) === "#") {
18844 } // "" only matches ""
18847 if (pattern.trim() === "") return p === "";
18848 return new Minimatch(pattern, options).match(p);
18851 function Minimatch(pattern, options) {
18852 if (!(this instanceof Minimatch)) {
18853 return new Minimatch(pattern, options, cache);
18856 if (typeof pattern !== "string") {
18857 throw new TypeError("glob pattern string required");
18860 if (!options) options = {}; // windows: need to use /, not \
18861 // On other platforms, \ is a valid (albeit bad) filename char.
18863 if (platform === "win32") {
18864 pattern = pattern.split("\\").join("/");
18866 // these things aren't particularly big, but walking down the string
18867 // and turning it into a regexp can get pretty costly.
18870 var cacheKey = pattern + "\n" + sigmund_1(options);
18871 var cached = minimatch.cache.get(cacheKey);
18872 if (cached) return cached;
18873 minimatch.cache.set(cacheKey, this);
18874 this.options = options;
18876 this.pattern = pattern;
18877 this.regexp = null;
18878 this.negate = false;
18879 this.comment = false;
18880 this.empty = false; // make the set of regexps etc.
18885 Minimatch.prototype.make = make;
18888 // don't do it more than once.
18889 if (this._made) return;
18890 var pattern = this.pattern;
18891 var options = this.options; // empty patterns and comments match nothing.
18893 if (!options.nocomment && pattern.charAt(0) === "#") {
18894 this.comment = true;
18901 } // step 1: figure out negation, etc.
18904 this.parseNegate(); // step 2: expand braces
18906 var set = this.globSet = this.braceExpand();
18907 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
18908 // matching patterns.
18909 // These will be regexps, except in the case of "**", which is
18910 // set to the GLOBSTAR object for globstar behavior,
18911 // and will not contain any / characters
18913 set = this.globParts = set.map(function (s) {
18914 return s.split(slashSplit);
18916 if (options.debug) console.error(this.pattern, set); // glob --> regexps
18918 set = set.map(function (s, si, set) {
18919 return s.map(this.parse, this);
18921 if (options.debug) console.error(this.pattern, set); // filter out everything that didn't compile properly.
18923 set = set.filter(function (s) {
18924 return -1 === s.indexOf(false);
18926 if (options.debug) console.error(this.pattern, set);
18930 Minimatch.prototype.parseNegate = parseNegate;
18932 function parseNegate() {
18933 var pattern = this.pattern,
18935 options = this.options,
18937 if (options.nonegate) return;
18939 for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) {
18944 if (negateOffset) this.pattern = pattern.substr(negateOffset);
18945 this.negate = negate;
18946 } // Brace expansion:
18947 // a{b,c}d -> abd acd
18948 // a{b,}c -> abc ac
18949 // a{0..3}d -> a0d a1d a2d a3d
18950 // a{b,c{d,e}f}g -> abg acdfg acefg
18951 // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
18953 // Invalid sets are not expanded.
18954 // a{2..}b -> a{2..}b
18958 minimatch.braceExpand = function (pattern, options) {
18959 return new Minimatch(pattern, options).braceExpand();
18962 Minimatch.prototype.braceExpand = braceExpand;
18964 function braceExpand(pattern, options) {
18965 options = options || this.options;
18966 pattern = typeof pattern === "undefined" ? this.pattern : pattern;
18968 if (typeof pattern === "undefined") {
18969 throw new Error("undefined pattern");
18972 if (options.nobrace || !pattern.match(/\{.*\}/)) {
18973 // shortcut. no need to expand.
18977 var escaping = false; // examples and comments refer to this crazy pattern:
18978 // a{b,c{d,e},{f,g}h}x{y,z}
18990 // everything before the first \{ is just a prefix.
18991 // So, we pluck that off, and work with the rest,
18992 // and then prepend it to everything we find.
18994 if (pattern.charAt(0) !== "{") {
18995 // console.error(pattern)
18998 for (var i = 0, l = pattern.length; i < l; i++) {
18999 var c = pattern.charAt(i); // console.error(i, c)
19002 escaping = !escaping;
19003 } else if (c === "{" && !escaping) {
19004 prefix = pattern.substr(0, i);
19007 } // actually no sets, all { were escaped.
19010 if (prefix === null) {
19011 // console.error("no sets")
19015 var tail = braceExpand(pattern.substr(i), options);
19016 return tail.map(function (t) {
19019 } // now we have something like:
19020 // {b,c{d,e},{f,g}h}x{y,z}
19021 // walk through the set, expanding each part, until
19022 // the set ends. then, we'll expand the suffix.
19023 // If the set only has a single member, then'll put the {} back
19024 // first, handle numeric sets, since they're easier
19027 var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/);
19030 // console.error("numset", numset[1], numset[2])
19031 var suf = braceExpand(pattern.substr(numset[0].length), options),
19032 start = +numset[1],
19034 inc = start > end ? -1 : 1,
19037 for (var i = start; i != end + inc; i += inc) {
19038 // append all the suffixes
19039 for (var ii = 0, ll = suf.length; ii < ll; ii++) {
19040 set.push(i + suf[ii]);
19045 } // ok, walk through the set
19046 // We hope, somewhat optimistically, that there
19047 // will be a } at the end.
19048 // If the closing brace isn't found, then the pattern is
19049 // interpreted as braceExpand("\\" + pattern) so that
19050 // the leading \{ will be interpreted literally.
19053 var i = 1 // skip the \{
19060 function addMember() {
19063 } // console.error("Entering for")
19066 FOR: for (i = 1, l = pattern.length; i < l; i++) {
19067 var c = pattern.charAt(i); // console.error("", i, c)
19071 member += "\\" + c;
19084 depth--; // if this closes the actual set, then we're done
19087 addMember(); // pluck off the close-brace
19113 // now we've either finished the set, and the suffix is
19114 // pattern.substr(i), or we have *not* closed the set,
19115 // and need to escape the leading brace
19119 // console.error("didn't close", pattern)
19120 return braceExpand("\\" + pattern, options);
19121 } // x{y,z} -> ["xy", "xz"]
19122 // console.error("set", set)
19123 // console.error("suffix", pattern.substr(i))
19126 var suf = braceExpand(pattern.substr(i), options); // ["b", "c{d,e}","{f,g}h"] ->
19127 // [["b"], ["cd", "ce"], ["fh", "gh"]]
19129 var addBraces = set.length === 1; // console.error("set pre-expanded", set)
19131 set = set.map(function (p) {
19132 return braceExpand(p, options);
19133 }); // console.error("set expanded", set)
19134 // [["b"], ["cd", "ce"], ["fh", "gh"]] ->
19135 // ["b", "cd", "ce", "fh", "gh"]
19137 set = set.reduce(function (l, r) {
19138 return l.concat(r);
19142 set = set.map(function (s) {
19143 return "{" + s + "}";
19145 } // now attach the suffixes.
19150 for (var i = 0, l = set.length; i < l; i++) {
19151 for (var ii = 0, ll = suf.length; ii < ll; ii++) {
19152 ret.push(set[i] + suf[ii]);
19157 } // parse a component of the expanded set.
19158 // At this point, no pattern may contain "/" in it
19159 // so we're going to return a 2d array, where each entry is the full
19160 // pattern, split on '/', and then turned into a regular expression.
19161 // A regexp is made at the end which joins each array with an
19162 // escaped /, and another full one which joins each regexp with |.
19164 // Following the lead of Bash 4.1, note that "**" only has special meaning
19165 // when it is the *only* thing in a path portion. Otherwise, any series
19166 // of * is equivalent to a single *. Globstar behavior is enabled by
19167 // default, and can be disabled by setting options.noglobstar.
19170 Minimatch.prototype.parse = parse;
19173 function parse(pattern, isSub) {
19174 var options = this.options; // shortcuts
19176 if (!options.noglobstar && pattern === "**") return GLOBSTAR;
19177 if (pattern === "") return "";
19179 hasMagic = !!options.nocase,
19180 escaping = false // ? => one single character
19182 patternListStack = [],
19187 classStart = -1 // . and .. never match anything that doesn't start with .,
19188 // even when options.dot is set.
19190 patternStart = pattern.charAt(0) === "." ? "" // anything
19191 // not (start or / followed by . or .. followed by / or end)
19192 : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" : "(?!\\.)";
19194 function clearStateChar() {
19196 // we had some state-tracking character
19197 // that wasn't consumed by this pass.
19198 switch (stateChar) {
19210 re += "\\" + stateChar;
19218 for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
19219 if (options.debug) {
19220 console.error("%s\t%s %s %j", pattern, i, re, c);
19221 } // skip over any that are escaped.
19224 if (escaping && reSpecials[c]) {
19232 // completely not allowed, even escaped.
19233 // Should already be path-split by now.
19240 // the various stateChar values
19241 // for the "extglob" stuff.
19248 if (options.debug) {
19249 console.error("%s\t%s %s %j <-- stateChar", pattern, i, re, c);
19250 } // all of those are literals inside a class, except that
19251 // the glob [!a] means [^a] in regexp
19255 if (c === "!" && i === classStart + 1) c = "^";
19258 } // if we already have a stateChar, then it means
19259 // that there was something like ** or +? in there.
19260 // Handle the stateChar, then proceed with this one.
19264 stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
19265 // just clear the statechar *now*, rather than even diving into
19266 // the patternList stuff.
19268 if (options.noext) clearStateChar();
19282 plType = stateChar;
19283 patternListStack.push({
19287 }); // negation is (?:(?!js)[^/]*)
19289 re += stateChar === "!" ? "(?:(?!" : "(?:";
19294 if (inClass || !patternListStack.length) {
19301 plType = patternListStack.pop().type; // negation is (?:(?!js)[^/]*)
19302 // The others are (?:<pattern>)<type>
19313 // the default anyway
19319 if (inClass || !patternListStack.length || escaping) {
19327 // these are mostly the same in regexp and glob
19330 // swallow any state-tracking char before the [
19340 reClassStart = re.length;
19345 // a right bracket shall lose its special
19346 // meaning and represent itself in
19347 // a bracket expression if it occurs
19348 // first in the list. -- POSIX.2 2.8.3.2
19349 if (i === classStart + 1 || !inClass) {
19353 } // finish up the class.
19362 // swallow any state char that wasn't consumed
19368 } else if (reSpecials[c] && !(c === "^" && inClass)) {
19376 // handle the case where we left a class open.
19377 // "[abc" is valid, equivalent to "\[abc"
19381 // split where the last [ was, and escape it
19382 // this is a huge pita. We now have to re-walk
19383 // the contents of the would-be class to re-translate
19384 // any characters that were passed through as-is
19385 var cs = pattern.substr(classStart + 1),
19386 sp = this.parse(cs, SUBPARSE);
19387 re = re.substr(0, reClassStart) + "\\[" + sp[0];
19388 hasMagic = hasMagic || sp[1];
19389 } // handle the case where we had a +( thing at the *end*
19391 // each pattern list stack adds 3 chars, and we need to go through
19392 // and escape any | chars that were passed through as-is for the regexp.
19393 // Go through and escape them, taking care not to double-escape any
19394 // | chars that were already escaped.
19399 while (pl = patternListStack.pop()) {
19400 var tail = re.slice(pl.reStart + 3); // maybe some even number of \, then maybe 1 \, followed by a |
19402 tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {
19404 // the | isn't already escaped, so escape it.
19406 } // need to escape all those slashes *again*, without escaping the
19407 // one that we need for escaping the | character. As it works out,
19408 // escaping an even number of slashes can be done by simply repeating
19409 // it exactly after itself. That's why this trick works.
19411 // I am sorry that you have to see this.
19414 return $1 + $1 + $2 + "|";
19415 }); // console.error("tail=%j\n %s", tail, tail)
19417 var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
19419 re = re.slice(0, pl.reStart) + t + "\\(" + tail;
19420 } // handle trailing things that only matter at the very end.
19428 } // only need to apply the nodot start if the re starts with
19429 // something that could conceivably capture a dot
19432 var addPatternStart = false;
19434 switch (re.charAt(0)) {
19438 addPatternStart = true;
19439 } // if the re is not "" at this point, then we need to make sure
19440 // it doesn't match against an empty path part.
19441 // Otherwise a/* will match a/, which it should not.
19444 if (re !== "" && hasMagic) re = "(?=.)" + re;
19445 if (addPatternStart) re = patternStart + re; // parsing just a piece of a larger pattern.
19447 if (isSub === SUBPARSE) {
19448 return [re, hasMagic];
19449 } // skip the regexp for non-magical patterns
19450 // unescape anything in it, though, so that it'll be
19451 // an exact match against a file etc.
19455 return globUnescape(pattern);
19458 var flags = options.nocase ? "i" : "",
19459 regExp = new RegExp("^" + re + "$", flags);
19460 regExp._glob = pattern;
19465 minimatch.makeRe = function (pattern, options) {
19466 return new Minimatch(pattern, options || {}).makeRe();
19469 Minimatch.prototype.makeRe = makeRe;
19471 function makeRe() {
19472 if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
19473 // pattern strings, or "**".
19475 // It's better to use .match(). This function shouldn't
19476 // be used, really, but it's pretty convenient sometimes,
19477 // when you just want to work with a regex.
19479 var set = this.set;
19480 if (!set.length) return this.regexp = false;
19481 var options = this.options;
19482 var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot,
19483 flags = options.nocase ? "i" : "";
19484 var re = set.map(function (pattern) {
19485 return pattern.map(function (p) {
19486 return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src;
19488 }).join("|"); // must match entire pattern
19489 // ending in a * or ** will make it less strict.
19491 re = "^(?:" + re + ")$"; // can match anything, as long as it's not this.
19493 if (this.negate) re = "^(?!" + re + ").*$";
19496 return this.regexp = new RegExp(re, flags);
19498 return this.regexp = false;
19502 minimatch.match = function (list, pattern, options) {
19503 var mm = new Minimatch(pattern, options);
19504 list = list.filter(function (f) {
19505 return mm.match(f);
19508 if (options.nonull && !list.length) {
19509 list.push(pattern);
19515 Minimatch.prototype.match = match;
19517 function match(f, partial) {
19518 // console.error("match", f, this.pattern)
19519 // short-circuit in the case of busted things.
19521 if (this.comment) return false;
19522 if (this.empty) return f === "";
19523 if (f === "/" && partial) return true;
19524 var options = this.options; // windows: need to use /, not \
19525 // On other platforms, \ is a valid (albeit bad) filename char.
19527 if (platform === "win32") {
19528 f = f.split("\\").join("/");
19529 } // treat the test path as a set of pathparts.
19532 f = f.split(slashSplit);
19534 if (options.debug) {
19535 console.error(this.pattern, "split", f);
19536 } // just ONE of the pattern sets in this.set needs to match
19537 // in order for it to be valid. If negating, then just one
19538 // match means that we have failed.
19539 // Either way, return on the first hit.
19542 var set = this.set; // console.error(this.pattern, "set", set)
19544 for (var i = 0, l = set.length; i < l; i++) {
19545 var pattern = set[i];
19546 var hit = this.matchOne(f, pattern, partial);
19549 if (options.flipNegate) return true;
19550 return !this.negate;
19552 } // didn't get any hits. this is success if it's a negative
19553 // pattern, failure otherwise.
19556 if (options.flipNegate) return false;
19557 return this.negate;
19558 } // set partial to true to test if, for example,
19559 // "/a/b" matches the start of "/*/b/*/d"
19560 // Partial means, if you run out of file before you run
19561 // out of pattern, then that's fine, as long as all
19562 // the parts match.
19565 Minimatch.prototype.matchOne = function (file, pattern, partial) {
19566 var options = this.options;
19568 if (options.debug) {
19569 console.error("matchOne", {
19576 if (options.matchBase && pattern.length === 1) {
19577 file = path$2.basename(file.join("/")).split("/");
19580 if (options.debug) {
19581 console.error("matchOne", file.length, pattern.length);
19584 for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
19585 if (options.debug) {
19586 console.error("matchOne loop");
19589 var p = pattern[pi],
19592 if (options.debug) {
19593 console.error(pattern, p, f);
19594 } // should be impossible.
19595 // some invalid regexp stuff in the set.
19598 if (p === false) return false;
19600 if (p === GLOBSTAR) {
19601 if (options.debug) console.error('GLOBSTAR', [pattern, p, f]); // "**"
19602 // a/**/b/**/c would match the following:
19607 // To do this, take the rest of the pattern after
19608 // the **, and see if it would match the file remainder.
19609 // If so, return success.
19610 // If not, the ** "swallows" a segment, and try again.
19611 // This is recursively awful.
19613 // a/**/b/**/c matching a/b/x/y/z/c
19616 // - matchOne(b/x/y/z/c, b/**/c)
19619 // - matchOne(x/y/z/c, c) -> no
19620 // - matchOne(y/z/c, c) -> no
19621 // - matchOne(z/c, c) -> no
19622 // - matchOne(c, c) yes, hit
19628 if (options.debug) console.error('** at the end'); // a ** at the end will just swallow the rest.
19629 // We have found a match.
19630 // however, it will not swallow /.x, unless
19631 // options.dot is set.
19632 // . and .. are *never* matched by **, for explosively
19633 // exponential reasons.
19635 for (; fi < fl; fi++) {
19636 if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
19640 } // ok, let's see if we can swallow whatever we can.
19643 WHILE: while (fr < fl) {
19644 var swallowee = file[fr];
19646 if (options.debug) {
19647 console.error('\nglobstar while', file, fr, pattern, pr, swallowee);
19648 } // XXX remove this slice. Just pass the start index.
19651 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
19652 if (options.debug) console.error('globstar found match!', fr, fl, swallowee); // found a match.
19656 // can't swallow "." or ".." ever.
19657 // can only swallow ".foo" when explicitly asked.
19658 if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
19659 if (options.debug) console.error("dot detected!", file, fr, pattern, pr);
19661 } // ** swallows a segment, and continue.
19664 if (options.debug) console.error('globstar swallow a segment, and continue');
19667 } // no match was found.
19668 // However, in partial mode, we can't say this is necessarily over.
19669 // If there's more *pattern* left, then
19674 // console.error("\n>>> no match, partial?", file, fr, pattern, pr)
19675 if (fr === fl) return true;
19679 } // something other than **
19680 // non-magic patterns just have to match exactly
19681 // patterns with magic have been turned into regexps.
19686 if (typeof p === "string") {
19687 if (options.nocase) {
19688 hit = f.toLowerCase() === p.toLowerCase();
19693 if (options.debug) {
19694 console.error("string match", p, f, hit);
19699 if (options.debug) {
19700 console.error("pattern match", p, f, hit);
19704 if (!hit) return false;
19705 } // Note: ending in / means that we'll get a final ""
19706 // at the end of the pattern. This can only match a
19707 // corresponding "" at the end of the file.
19708 // If the file ends in /, then it can only match a
19709 // a pattern that ends in /, unless the pattern just
19710 // doesn't have any more for it. But, a/b/ should *not*
19711 // match "a/b/*", even though "" matches against the
19712 // [^/]*? pattern, except in partial mode, where it might
19713 // simply not be reached yet.
19714 // However, a/b/ should still satisfy a/*
19715 // now either we fell off the end of the pattern, or we're done.
19718 if (fi === fl && pi === pl) {
19719 // ran out of pattern and filename at the same time.
19722 } else if (fi === fl) {
19723 // ran out of file, but still had pattern left.
19724 // this is ok if we're doing the match as part of
19725 // a glob fs traversal.
19727 } else if (pi === pl) {
19728 // ran out of pattern, still have file left.
19729 // this is only acceptable if we're on the very last
19730 // empty segment of a file with a trailing slash.
19731 // a/* should match a/b/
19732 var emptyFileEnd = fi === fl - 1 && file[fi] === "";
19733 return emptyFileEnd;
19734 } // should be unreachable.
19737 throw new Error("wtf?");
19738 }; // replace stuff like \* with *
19741 function globUnescape(s) {
19742 return s.replace(/\\(.)/g, "$1");
19745 function regExpEscape(s) {
19746 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
19749 var fnmatch_1 = fnmatch.minimatch;
19751 var ini = createCommonjsModule(function (module, exports) {
19753 var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
19754 return new (P || (P = Promise))(function (resolve, reject) {
19755 function fulfilled(value) {
19757 step(generator.next(value));
19763 function rejected(value) {
19765 step(generator["throw"](value));
19771 function step(result) {
19772 result.done ? resolve(result.value) : new P(function (resolve) {
19773 resolve(result.value);
19774 }).then(fulfilled, rejected);
19777 step((generator = generator.apply(thisArg, _arguments || [])).next());
19781 var __generator = this && this.__generator || function (thisArg, body) {
19784 sent: function sent() {
19785 if (t[0] & 1) throw t[1];
19799 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
19804 return function (v) {
19805 return step([n, v]);
19809 function step(op) {
19810 if (f) throw new TypeError("Generator is already executing.");
19814 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;
19815 if (y = 0, t) op = [op[0] & 2, t.value];
19844 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
19849 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
19854 if (op[0] === 6 && _.label < t[1]) {
19860 if (t && _.label < t[2]) {
19868 if (t[2]) _.ops.pop();
19875 op = body.call(thisArg, _);
19884 if (op[0] & 5) throw op[1];
19886 value: op[0] ? op[1] : void 0,
19892 var __importStar = this && this.__importStar || function (mod) {
19893 if (mod && mod.__esModule) return mod;
19895 if (mod != null) for (var k in mod) {
19896 if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
19898 result["default"] = mod;
19902 Object.defineProperty(exports, "__esModule", {
19906 var fs = __importStar(fs$1);
19908 * define the possible values:
\r
19909 * section: [section]
\r
19910 * param: key=value
\r
19911 * comment: ;this is a comment
\r
19916 section: /^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$/,
19917 param: /^\s*([\w\.\-\_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$/,
19918 comment: /^\s*[#;].*$/
19921 * Parses an .ini file
\r
19922 * @param file The location of the .ini file
\r
19925 function parse(file) {
19926 return __awaiter(this, void 0, void 0, function () {
19927 return __generator(this, function (_a) {
19930 , new Promise(function (resolve, reject) {
19931 fs.readFile(file, 'utf8', function (err, data) {
19937 resolve(parseString(data));
19944 exports.parse = parse;
19946 function parseSync(file) {
19947 return parseString(fs.readFileSync(file, 'utf8'));
19950 exports.parseSync = parseSync;
19952 function parseString(data) {
19953 var sectionBody = {};
19954 var sectionName = null;
19955 var value = [[sectionName, sectionBody]];
19956 var lines = data.split(/\r\n|\r|\n/);
19957 lines.forEach(function (line) {
19960 if (regex.comment.test(line)) {
19964 if (regex.param.test(line)) {
19965 match = line.match(regex.param);
19966 sectionBody[match[1]] = match[2];
19967 } else if (regex.section.test(line)) {
19968 match = line.match(regex.section);
19969 sectionName = match[1];
19971 value.push([sectionName, sectionBody]);
19977 exports.parseString = parseString;
19979 unwrapExports(ini);
19980 var ini_1 = ini.parse;
19981 var ini_2 = ini.parseSync;
19982 var ini_3 = ini.parseString;
19984 var name$1 = "editorconfig";
19985 var version$1 = "0.15.3";
19986 var description$1 = "EditorConfig File Locator and Interpreter for Node.js";
19991 var main$1 = "src/index.js";
19992 var contributors = [
19993 "Hong Xu (topbug.net)",
19994 "Jed Mao (https://github.com/jedmao/)",
19995 "Trey Hunner (http://treyhunner.com)"
19997 var directories = {
20002 clean: "rimraf dist",
20003 prebuild: "npm run clean",
20005 pretest: "npm run lint && npm run build && npm run copy && cmake .",
20007 "pretest:ci": "npm run pretest",
20008 "test:ci": "ctest -VV --output-on-failure .",
20009 lint: "npm run eclint && npm run tslint",
20010 eclint: "eclint check --indent_size ignore \"src/**\"",
20011 tslint: "tslint --project tsconfig.json --exclude package.json",
20012 copy: "cpy .npmignore LICENSE README.md CHANGELOG.md dist && cpy bin/* dist/bin && cpy src/lib/fnmatch*.* dist/src/lib",
20013 prepub: "npm run lint && npm run build && npm run copy",
20014 pub: "npm publish ./dist"
20016 var repository$1 = {
20018 url: "git://github.com/editorconfig/editorconfig-core-js.git"
20020 var bugs = "https://github.com/editorconfig/editorconfig-core-js/issues";
20021 var author$1 = "EditorConfig Team";
20022 var license$1 = "MIT";
20023 var dependencies$1 = {
20024 commander: "^2.19.0",
20025 "lru-cache": "^4.1.5",
20029 var devDependencies$1 = {
20030 "@types/mocha": "^5.2.6",
20031 "@types/node": "^10.12.29",
20032 "@types/semver": "^5.5.0",
20033 "cpy-cli": "^2.0.0",
20039 typescript: "^3.3.3333"
20043 version: version$1,
20044 description: description$1,
20045 keywords: keywords,
20047 contributors: contributors,
20048 directories: directories,
20049 scripts: scripts$1,
20050 repository: repository$1,
20053 license: license$1,
20054 dependencies: dependencies$1,
20055 devDependencies: devDependencies$1
20058 var _package$3 = /*#__PURE__*/Object.freeze({
20061 version: version$1,
20062 description: description$1,
20063 keywords: keywords,
20065 contributors: contributors,
20066 directories: directories,
20067 scripts: scripts$1,
20068 repository: repository$1,
20071 license: license$1,
20072 dependencies: dependencies$1,
20073 devDependencies: devDependencies$1,
20074 'default': _package$2
20077 var require$$4 = getCjsExportFromNamespace(_package$3);
20079 var src = createCommonjsModule(function (module, exports) {
20081 var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
20082 return new (P || (P = Promise))(function (resolve, reject) {
20083 function fulfilled(value) {
20085 step(generator.next(value));
20091 function rejected(value) {
20093 step(generator["throw"](value));
20099 function step(result) {
20100 result.done ? resolve(result.value) : new P(function (resolve) {
20101 resolve(result.value);
20102 }).then(fulfilled, rejected);
20105 step((generator = generator.apply(thisArg, _arguments || [])).next());
20109 var __generator = this && this.__generator || function (thisArg, body) {
20112 sent: function sent() {
20113 if (t[0] & 1) throw t[1];
20127 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
20132 return function (v) {
20133 return step([n, v]);
20137 function step(op) {
20138 if (f) throw new TypeError("Generator is already executing.");
20142 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;
20143 if (y = 0, t) op = [op[0] & 2, t.value];
20172 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
20177 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
20182 if (op[0] === 6 && _.label < t[1]) {
20188 if (t && _.label < t[2]) {
20196 if (t[2]) _.ops.pop();
20203 op = body.call(thisArg, _);
20212 if (op[0] & 5) throw op[1];
20214 value: op[0] ? op[1] : void 0,
20220 var __importStar = this && this.__importStar || function (mod) {
20221 if (mod && mod.__esModule) return mod;
20223 if (mod != null) for (var k in mod) {
20224 if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
20226 result["default"] = mod;
20230 var __importDefault = this && this.__importDefault || function (mod) {
20231 return mod && mod.__esModule ? mod : {
20236 Object.defineProperty(exports, "__esModule", {
20240 var fs = __importStar(fs$1);
20242 var path = __importStar(path$2);
20244 var semver = __importStar(semver$1);
20246 var fnmatch_1 = __importDefault(fnmatch);
20248 exports.parseString = ini.parseString;
20250 var package_json_1 = __importDefault(require$$4);
20254 indent_style: true,
20256 insert_final_newline: true,
20257 trim_trailing_whitespace: true,
20261 function fnmatch$1(filepath, glob) {
20262 var matchOptions = {
20267 glob = glob.replace(/\*\*/g, '{*,**/**/**}');
20268 return fnmatch_1.default(filepath, glob, matchOptions);
20271 function getConfigFileNames(filepath, options) {
20275 filepath = path.dirname(filepath);
20276 paths.push(path.join(filepath, options.config));
20277 } while (filepath !== options.root);
20282 function processMatches(matches, version) {
20283 // Set indent_size to 'tab' if indent_size is unspecified and
20284 // indent_style is set to 'tab'.
20285 if ('indent_style' in matches && matches.indent_style === 'tab' && !('indent_size' in matches) && semver.gte(version, '0.10.0')) {
20286 matches.indent_size = 'tab';
20287 } // Set tab_width to indent_size if indent_size is specified and
20288 // tab_width is unspecified
20291 if ('indent_size' in matches && !('tab_width' in matches) && matches.indent_size !== 'tab') {
20292 matches.tab_width = matches.indent_size;
20293 } // Set indent_size to tab_width if indent_size is 'tab'
20296 if ('indent_size' in matches && 'tab_width' in matches && matches.indent_size === 'tab') {
20297 matches.indent_size = matches.tab_width;
20303 function processOptions(options, filepath) {
20304 if (options === void 0) {
20309 config: options.config || '.editorconfig',
20310 version: options.version || package_json_1.default.version,
20311 root: path.resolve(options.root || path.parse(filepath).root)
20315 function buildFullGlob(pathPrefix, glob) {
20316 switch (glob.indexOf('/')) {
20318 glob = '**/' + glob;
20322 glob = glob.substring(1);
20326 return path.join(pathPrefix, glob);
20329 function extendProps(props, options) {
20330 if (props === void 0) {
20334 if (options === void 0) {
20338 for (var key in options) {
20339 if (options.hasOwnProperty(key)) {
20340 var value = options[key];
20341 var key2 = key.toLowerCase();
20342 var value2 = value;
20344 if (knownProps[key2]) {
20345 value2 = value.toLowerCase();
20349 value2 = JSON.parse(value);
20352 if (typeof value === 'undefined' || value === null) {
20353 // null and undefined are values specific to JSON (no special meaning
20354 // in editorconfig) & should just be returned as regular strings.
20355 value2 = String(value);
20358 props[key2] = value2;
20365 function parseFromConfigs(configs, filepath, options) {
20366 return processMatches(configs.reverse().reduce(function (matches, file) {
20367 var pathPrefix = path.dirname(file.name);
20368 file.contents.forEach(function (section) {
20369 var glob = section[0];
20370 var options2 = section[1];
20376 var fullGlob = buildFullGlob(pathPrefix, glob);
20378 if (!fnmatch$1(filepath, fullGlob)) {
20382 matches = extendProps(matches, options2);
20385 }, {}), options.version);
20388 function getConfigsForFiles(files) {
20391 for (var i in files) {
20392 if (files.hasOwnProperty(i)) {
20393 var file = files[i];
20394 var contents = ini.parseString(file.contents);
20400 if ((contents[0][1].root || '').toLowerCase() === 'true') {
20409 function readConfigFiles(filepaths) {
20410 return __awaiter(this, void 0, void 0, function () {
20411 return __generator(this, function (_a) {
20414 , Promise.all(filepaths.map(function (name) {
20415 return new Promise(function (resolve) {
20416 fs.readFile(name, 'utf8', function (err, data) {
20419 contents: err ? '' : data
20428 function readConfigFilesSync(filepaths) {
20431 filepaths.forEach(function (filepath) {
20433 file = fs.readFileSync(filepath, 'utf8');
20446 function opts(filepath, options) {
20447 if (options === void 0) {
20451 var resolvedFilePath = path.resolve(filepath);
20452 return [resolvedFilePath, processOptions(options, resolvedFilePath)];
20455 function parseFromFiles(filepath, files, options) {
20456 if (options === void 0) {
20460 return __awaiter(this, void 0, void 0, function () {
20461 var _a, resolvedFilePath, processedOptions;
20463 return __generator(this, function (_b) {
20464 _a = opts(filepath, options), resolvedFilePath = _a[0], processedOptions = _a[1];
20467 , files.then(getConfigsForFiles).then(function (configs) {
20468 return parseFromConfigs(configs, resolvedFilePath, processedOptions);
20474 exports.parseFromFiles = parseFromFiles;
20476 function parseFromFilesSync(filepath, files, options) {
20477 if (options === void 0) {
20481 var _a = opts(filepath, options),
20482 resolvedFilePath = _a[0],
20483 processedOptions = _a[1];
20485 return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
20488 exports.parseFromFilesSync = parseFromFilesSync;
20490 function parse(_filepath, _options) {
20491 if (_options === void 0) {
20495 return __awaiter(this, void 0, void 0, function () {
20496 var _a, resolvedFilePath, processedOptions, filepaths;
20498 return __generator(this, function (_b) {
20499 _a = opts(_filepath, _options), resolvedFilePath = _a[0], processedOptions = _a[1];
20500 filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
20503 , readConfigFiles(filepaths).then(getConfigsForFiles).then(function (configs) {
20504 return parseFromConfigs(configs, resolvedFilePath, processedOptions);
20510 exports.parse = parse;
20512 function parseSync(_filepath, _options) {
20513 if (_options === void 0) {
20517 var _a = opts(_filepath, _options),
20518 resolvedFilePath = _a[0],
20519 processedOptions = _a[1];
20521 var filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
20522 var files = readConfigFilesSync(filepaths);
20523 return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
20526 exports.parseSync = parseSync;
20528 unwrapExports(src);
20529 var src_1 = src.parseString;
20530 var src_2 = src.parseFromFiles;
20531 var src_3 = src.parseFromFilesSync;
20532 var src_4 = src.parse;
20533 var src_5 = src.parseSync;
20535 var editorconfigToPrettier = editorConfigToPrettier;
20537 function removeUnset(editorConfig) {
20539 var keys = Object.keys(editorConfig);
20541 for (var i = 0; i < keys.length; i++) {
20544 if (editorConfig[key] === "unset") {
20548 result[key] = editorConfig[key];
20554 function editorConfigToPrettier(editorConfig) {
20555 if (!editorConfig) {
20559 editorConfig = removeUnset(editorConfig);
20561 if (Object.keys(editorConfig).length === 0) {
20567 if (editorConfig.indent_style) {
20568 result.useTabs = editorConfig.indent_style === "tab";
20571 if (editorConfig.indent_size === "tab") {
20572 result.useTabs = true;
20575 if (result.useTabs && editorConfig.tab_width) {
20576 result.tabWidth = editorConfig.tab_width;
20577 } else if (editorConfig.indent_style === "space" && editorConfig.indent_size && editorConfig.indent_size !== "tab") {
20578 result.tabWidth = editorConfig.indent_size;
20579 } else if (editorConfig.tab_width !== undefined) {
20580 result.tabWidth = editorConfig.tab_width;
20583 if (editorConfig.max_line_length && editorConfig.max_line_length !== "off") {
20584 result.printWidth = editorConfig.max_line_length;
20587 if (editorConfig.quote_type === "single") {
20588 result.singleQuote = true;
20589 } else if (editorConfig.quote_type === "double") {
20590 result.singleQuote = false;
20593 if (["cr", "crlf", "lf"].indexOf(editorConfig.end_of_line) !== -1) {
20594 result.endOfLine = editorConfig.end_of_line;
20600 function markerExists(files, markers) {
20601 return markers.some(function (marker) {
20602 return files.some(function (file) {
20603 return file === marker;
20608 function traverseFolder(directory, levels, markers) {
20609 var files = fs$1.readdirSync(directory);
20611 if (levels === 0) {
20613 } else if (markerExists(files, markers)) {
20616 return traverseFolder(path$2.resolve(directory, '..'), levels - 1, markers);
20620 var findProjectRoot = function findRoot(dir, opts) {
20621 if (!dir) throw new Error("Directory not defined");
20623 var levels = opts.maxDepth || findRoot.MAX_DEPTH;
20624 var markers = opts.markers || findRoot.MARKERS;
20625 return traverseFolder(dir, levels, markers);
20629 var MARKERS = ['.git', '.hg'];
20630 findProjectRoot.MAX_DEPTH = MAX_DEPTH;
20631 findProjectRoot.MARKERS = MARKERS;
20633 var maybeParse = function maybeParse(filePath, config, parse) {
20634 // findProjectRoot will throw an error if we pass a nonexistent directory to
20635 // it, which is possible, for example, when the path is given via
20636 // --stdin-filepath. So, first, traverse up until we find an existing
20638 var dirPath = path$2.dirname(path$2.resolve(filePath));
20639 var fsRoot = path$2.parse(dirPath).root;
20641 while (dirPath !== fsRoot && !fs$1.existsSync(dirPath)) {
20642 dirPath = path$2.dirname(dirPath);
20645 var root = findProjectRoot(dirPath);
20646 return filePath && parse(filePath, {
20651 var editorconfigAsyncNoCache = function editorconfigAsyncNoCache(filePath, config) {
20652 return Promise.resolve(maybeParse(filePath, config, src.parse)).then(editorconfigToPrettier);
20655 var editorconfigAsyncWithCache = mem_1(editorconfigAsyncNoCache);
20657 var editorconfigSyncNoCache = function editorconfigSyncNoCache(filePath, config) {
20658 return editorconfigToPrettier(maybeParse(filePath, config, src.parseSync));
20661 var editorconfigSyncWithCache = mem_1(editorconfigSyncNoCache);
20663 function getLoadFunction(opts) {
20664 if (!opts.editorconfig) {
20665 return function () {
20671 return opts.cache ? editorconfigSyncWithCache : editorconfigSyncNoCache;
20674 return opts.cache ? editorconfigAsyncWithCache : editorconfigAsyncNoCache;
20677 function clearCache() {
20678 mem_1.clear(editorconfigSyncWithCache);
20679 mem_1.clear(editorconfigAsyncWithCache);
20682 var resolveConfigEditorconfig = {
20687 var ParserEND = 0x110000;
20691 function (_Error) {
20692 _inherits(ParserError, _Error);
20694 /* istanbul ignore next */
20695 function ParserError(msg, filename, linenumber) {
20698 _classCallCheck(this, ParserError);
20700 _this = _possibleConstructorReturn(this, _getPrototypeOf(ParserError).call(this, '[ParserError] ' + msg, filename, linenumber));
20701 _this.name = 'ParserError';
20702 _this.code = 'ParserError';
20703 if (Error.captureStackTrace) Error.captureStackTrace(_assertThisInitialized(_this), ParserError);
20707 return ParserError;
20708 }(_wrapNativeSuper(Error));
20710 var State = function State(parser) {
20711 _classCallCheck(this, State);
20713 this.parser = parser;
20715 this.returned = null;
20716 this.result = null;
20717 this.resultTable = null;
20718 this.resultArr = null;
20724 function Parser() {
20725 _classCallCheck(this, Parser);
20731 this.ctx = this.obj;
20736 this.state = new State(this.parseStart);
20739 _createClass(Parser, [{
20741 value: function parse(str) {
20742 /* istanbul ignore next */
20743 if (str.length === 0 || str.length == null) return;
20744 this._buf = String(str);
20749 while (getNext === false || this.nextChar()) {
20750 getNext = this.runOne();
20757 value: function nextChar() {
20758 if (this.char === 0x0A) {
20764 this.char = this._buf.codePointAt(this.ii);
20767 return this.haveBuffer();
20771 value: function haveBuffer() {
20772 return this.ii < this._buf.length;
20776 value: function runOne() {
20777 return this.state.parser.call(this, this.state.returned);
20781 value: function finish() {
20782 this.char = ParserEND;
20786 last = this.state.parser;
20788 } while (this.state.parser !== last);
20797 value: function next(fn) {
20798 /* istanbul ignore next */
20799 if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn));
20800 this.state.parser = fn;
20804 value: function goto(fn) {
20806 return this.runOne();
20810 value: function call(fn, returnWith) {
20811 if (returnWith) this.next(returnWith);
20812 this.stack.push(this.state);
20813 this.state = new State(fn);
20817 value: function callNow(fn, returnWith) {
20818 this.call(fn, returnWith);
20819 return this.runOne();
20823 value: function _return(value) {
20824 /* istanbul ignore next */
20825 if (this.stack.length === 0) throw this.error(new ParserError('Stack underflow'));
20826 if (value === undefined) value = this.state.buf;
20827 this.state = this.stack.pop();
20828 this.state.returned = value;
20832 value: function returnNow(value) {
20833 this.return(value);
20834 return this.runOne();
20838 value: function consume() {
20839 /* istanbul ignore next */
20840 if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer'));
20841 this.state.buf += this._buf[this.ii];
20845 value: function error(err) {
20846 err.line = this.line;
20847 err.col = this.col;
20848 err.pos = this.pos;
20851 /* istanbul ignore next */
20855 value: function parseStart() {
20856 throw new ParserError('Must declare a parseStart method');
20863 Parser.END = ParserEND;
20864 Parser.Error = ParserError;
20865 var parser$1 = Parser;
20867 var createDatetime = function createDatetime(value) {
20868 var date = new Date(value);
20869 /* istanbul ignore if */
20872 throw new TypeError('Invalid Datetime');
20878 var formatNum = function formatNum(d, num) {
20881 while (num.length < d) {
20888 var FloatingDateTime =
20891 _inherits(FloatingDateTime, _Date);
20893 function FloatingDateTime(value) {
20896 _classCallCheck(this, FloatingDateTime);
20898 _this = _possibleConstructorReturn(this, _getPrototypeOf(FloatingDateTime).call(this, value + 'Z'));
20899 _this.isFloating = true;
20903 _createClass(FloatingDateTime, [{
20904 key: "toISOString",
20905 value: function toISOString() {
20906 var date = `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`;
20907 var time = `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`;
20908 return `${date}T${time}`;
20912 return FloatingDateTime;
20913 }(_wrapNativeSuper(Date));
20915 var createDatetimeFloat = function createDatetimeFloat(value) {
20916 var date = new FloatingDateTime(value);
20917 /* istanbul ignore if */
20920 throw new TypeError('Invalid Datetime');
20926 var DateTime = global.Date;
20930 function (_DateTime) {
20931 _inherits(Date, _DateTime);
20933 function Date(value) {
20936 _classCallCheck(this, Date);
20938 _this = _possibleConstructorReturn(this, _getPrototypeOf(Date).call(this, value));
20939 _this.isDate = true;
20943 _createClass(Date, [{
20944 key: "toISOString",
20945 value: function toISOString() {
20946 return `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`;
20953 var createDate = function createDate(value) {
20954 var date = new Date$1(value);
20955 /* istanbul ignore if */
20958 throw new TypeError('Invalid Datetime');
20967 _inherits(Time, _Date);
20969 function Time(value) {
20972 _classCallCheck(this, Time);
20974 _this = _possibleConstructorReturn(this, _getPrototypeOf(Time).call(this, `0000-01-01T${value}Z`));
20975 _this.isTime = true;
20979 _createClass(Time, [{
20980 key: "toISOString",
20981 value: function toISOString() {
20982 return `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`;
20987 }(_wrapNativeSuper(Date));
20989 var createTime = function createTime(value) {
20990 var date = new Time(value);
20991 /* istanbul ignore if */
20994 throw new TypeError('Invalid Datetime');
21000 /* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */
21003 var tomlParser = makeParserClass(parser$1);
21004 var makeParserClass_1 = makeParserClass;
21008 function (_Error) {
21009 _inherits(TomlError, _Error);
21011 function TomlError(msg) {
21014 _classCallCheck(this, TomlError);
21016 _this = _possibleConstructorReturn(this, _getPrototypeOf(TomlError).call(this, msg));
21017 _this.name = 'TomlError';
21018 /* istanbul ignore next */
21020 if (Error.captureStackTrace) Error.captureStackTrace(_assertThisInitialized(_this), TomlError);
21021 _this.fromTOML = true;
21022 _this.wrapped = null;
21027 }(_wrapNativeSuper(Error));
21029 TomlError.wrap = function (err) {
21030 var terr = new TomlError(err.message);
21031 terr.code = err.code;
21032 terr.wrapped = err;
21036 var TomlError_1 = TomlError;
21040 var CTRL_CHAR_BOUNDARY = 0x1F; // the last non-character in the latin1 region of unicode, except DEL
21042 var CHAR_SP = 0x20;
21043 var CHAR_QUOT = 0x22;
21044 var CHAR_NUM = 0x23;
21045 var CHAR_APOS = 0x27;
21046 var CHAR_PLUS = 0x2B;
21047 var CHAR_COMMA = 0x2C;
21048 var CHAR_HYPHEN = 0x2D;
21049 var CHAR_PERIOD = 0x2E;
21054 var CHAR_COLON = 0x3A;
21055 var CHAR_EQUALS = 0x3D;
21062 var CHAR_LOWBAR = 0x5F;
21077 var CHAR_LCUB = 0x7B;
21078 var CHAR_RCUB = 0x7D;
21079 var CHAR_LSQB = 0x5B;
21080 var CHAR_BSOL = 0x5C;
21081 var CHAR_RSQB = 0x5D;
21082 var CHAR_DEL = 0x7F;
21083 var SURROGATE_FIRST = 0xD800;
21084 var SURROGATE_LAST = 0xDFFF;
21086 [CHAR_b]: '\u0008',
21087 [CHAR_t]: '\u0009',
21088 [CHAR_n]: '\u000A',
21089 [CHAR_f]: '\u000C',
21090 [CHAR_r]: '\u000D',
21091 [CHAR_QUOT]: '\u0022',
21092 [CHAR_BSOL]: '\u005C'
21095 function isDigit(cp) {
21096 return cp >= CHAR_0 && cp <= CHAR_9;
21099 function isHexit(cp) {
21100 return cp >= CHAR_A && cp <= CHAR_F || cp >= CHAR_a && cp <= CHAR_f || cp >= CHAR_0 && cp <= CHAR_9;
21103 function isBit(cp) {
21104 return cp === CHAR_1 || cp === CHAR_0;
21107 function isOctit(cp) {
21108 return cp >= CHAR_0 && cp <= CHAR_7;
21111 function isAlphaNumQuoteHyphen(cp) {
21112 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;
21115 function isAlphaNumHyphen(cp) {
21116 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;
21119 var _type = Symbol('type');
21121 var _declared = Symbol('declared');
21123 var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
21124 var defineProperty = Object.defineProperty;
21126 configurable: true,
21132 function hasKey(obj, key) {
21133 if (hasOwnProperty$1.call(obj, key)) return true;
21134 if (key === '__proto__') defineProperty(obj, '__proto__', descriptor);
21138 var INLINE_TABLE = Symbol('inline-table');
21140 function InlineTable() {
21141 return Object.defineProperties({}, {
21143 value: INLINE_TABLE
21148 function isInlineTable(obj) {
21149 if (obj === null || typeof obj !== 'object') return false;
21150 return obj[_type] === INLINE_TABLE;
21153 var TABLE = Symbol('table');
21156 return Object.defineProperties({}, {
21167 function isTable(obj) {
21168 if (obj === null || typeof obj !== 'object') return false;
21169 return obj[_type] === TABLE;
21172 var _contentType = Symbol('content-type');
21174 var INLINE_LIST = Symbol('inline-list');
21176 function InlineList(type) {
21177 return Object.defineProperties([], {
21187 function isInlineList(obj) {
21188 if (obj === null || typeof obj !== 'object') return false;
21189 return obj[_type] === INLINE_LIST;
21192 var LIST = Symbol('list');
21195 return Object.defineProperties([], {
21202 function isList(obj) {
21203 if (obj === null || typeof obj !== 'object') return false;
21204 return obj[_type] === LIST;
21205 } // in an eval, to let bundlers not slurp in a util proxy
21211 var utilInspect = eval("require('util').inspect");
21212 _custom = utilInspect.custom;
21214 /* eval require not available in transpiled bundle */
21216 /* istanbul ignore next */
21219 var _inspect = _custom || 'inspect';
21224 function BoxedBigInt(value) {
21225 _classCallCheck(this, BoxedBigInt);
21228 this.value = global.BigInt.asIntN(64, value);
21230 /* istanbul ignore next */
21234 Object.defineProperty(this, _type, {
21239 _createClass(BoxedBigInt, [{
21241 value: function isNaN() {
21242 return this.value === null;
21244 /* istanbul ignore next */
21248 value: function toString() {
21249 return String(this.value);
21251 /* istanbul ignore next */
21255 value: function value() {
21256 return `[BigInt: ${this.toString()}]}`;
21260 value: function valueOf() {
21265 return BoxedBigInt;
21268 var INTEGER = Symbol('integer');
21270 function Integer(_value) {
21271 var num = Number(_value); // -0 is a float thing, not an int thing
21273 if (Object.is(num, -0)) num = 0;
21274 /* istanbul ignore else */
21276 if (global.BigInt && !Number.isSafeInteger(num)) {
21277 return new BoxedBigInt(_value);
21279 /* istanbul ignore next */
21280 return Object.defineProperties(new Number(num), {
21282 value: function value() {
21283 return isNaN(this);
21290 value: function value() {
21291 return `[Integer: ${_value}]`;
21298 function isInteger(obj) {
21299 if (obj === null || typeof obj !== 'object') return false;
21300 return obj[_type] === INTEGER;
21303 var FLOAT = Symbol('float');
21305 function Float(_value2) {
21306 /* istanbul ignore next */
21307 return Object.defineProperties(new Number(_value2), {
21312 value: function value() {
21313 return `[Float: ${_value2}]`;
21319 function isFloat(obj) {
21320 if (obj === null || typeof obj !== 'object') return false;
21321 return obj[_type] === FLOAT;
21324 function tomlType(value) {
21325 var type = typeof value;
21327 if (type === 'object') {
21328 /* istanbul ignore if */
21329 if (value === null) return 'null';
21330 if (value instanceof Date) return 'datetime';
21331 /* istanbul ignore else */
21333 if (_type in value) {
21334 switch (value[_type]) {
21336 return 'inline-table';
21339 return 'inline-list';
21341 /* istanbul ignore next */
21346 /* istanbul ignore next */
21363 function makeParserClass(Parser) {
21366 function (_Parser) {
21367 _inherits(TOMLParser, _Parser);
21369 function TOMLParser() {
21372 _classCallCheck(this, TOMLParser);
21374 _this2 = _possibleConstructorReturn(this, _getPrototypeOf(TOMLParser).call(this));
21375 _this2.ctx = _this2.obj = Table();
21381 _createClass(TOMLParser, [{
21382 key: "atEndOfWord",
21383 value: function atEndOfWord() {
21384 return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine();
21387 key: "atEndOfLine",
21388 value: function atEndOfLine() {
21389 return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M;
21393 value: function parseStart() {
21394 if (this.char === Parser.END) {
21396 } else if (this.char === CHAR_LSQB) {
21397 return this.call(this.parseTableOrList);
21398 } else if (this.char === CHAR_NUM) {
21399 return this.call(this.parseComment);
21400 } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
21402 } else if (isAlphaNumQuoteHyphen(this.char)) {
21403 return this.callNow(this.parseAssignStatement);
21405 throw this.error(new TomlError(`Unknown character "${this.char}"`));
21407 } // HELPER, this strips any whitespace and comments to the end of the line
21408 // then RETURNS. Last state in a production.
21411 key: "parseWhitespaceToEOL",
21412 value: function parseWhitespaceToEOL() {
21413 if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
21415 } else if (this.char === CHAR_NUM) {
21416 return this.goto(this.parseComment);
21417 } else if (this.char === Parser.END || this.char === CTRL_J) {
21418 return this.return();
21420 throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line'));
21423 /* ASSIGNMENT: key = value */
21426 key: "parseAssignStatement",
21427 value: function parseAssignStatement() {
21428 return this.callNow(this.parseAssign, this.recordAssignStatement);
21431 key: "recordAssignStatement",
21432 value: function recordAssignStatement(kv) {
21433 var target = this.ctx;
21434 var finalKey = kv.key.pop();
21435 var _iteratorNormalCompletion = true;
21436 var _didIteratorError = false;
21437 var _iteratorError = undefined;
21440 for (var _iterator = kv.key[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
21441 var kw = _step.value;
21443 if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
21444 throw this.error(new TomlError("Can't redefine existing key"));
21447 target = target[kw] = target[kw] || Table();
21450 _didIteratorError = true;
21451 _iteratorError = err;
21454 if (!_iteratorNormalCompletion && _iterator.return != null) {
21455 _iterator.return();
21458 if (_didIteratorError) {
21459 throw _iteratorError;
21464 if (hasKey(target, finalKey)) {
21465 throw this.error(new TomlError("Can't redefine existing key"));
21466 } // unbox our numbers
21469 if (isInteger(kv.value) || isFloat(kv.value)) {
21470 target[finalKey] = kv.value.valueOf();
21472 target[finalKey] = kv.value;
21475 return this.goto(this.parseWhitespaceToEOL);
21477 /* ASSSIGNMENT expression, key = value possibly inside an inline table */
21480 key: "parseAssign",
21481 value: function parseAssign() {
21482 return this.callNow(this.parseKeyword, this.recordAssignKeyword);
21485 key: "recordAssignKeyword",
21486 value: function recordAssignKeyword(key) {
21487 if (this.state.resultTable) {
21488 this.state.resultTable.push(key);
21490 this.state.resultTable = [key];
21493 return this.goto(this.parseAssignKeywordPreDot);
21496 key: "parseAssignKeywordPreDot",
21497 value: function parseAssignKeywordPreDot() {
21498 if (this.char === CHAR_PERIOD) {
21499 return this.next(this.parseAssignKeywordPostDot);
21500 } else if (this.char !== CHAR_SP && this.char !== CTRL_I) {
21501 return this.goto(this.parseAssignEqual);
21505 key: "parseAssignKeywordPostDot",
21506 value: function parseAssignKeywordPostDot() {
21507 if (this.char !== CHAR_SP && this.char !== CTRL_I) {
21508 return this.callNow(this.parseKeyword, this.recordAssignKeyword);
21512 key: "parseAssignEqual",
21513 value: function parseAssignEqual() {
21514 if (this.char === CHAR_EQUALS) {
21515 return this.next(this.parseAssignPreValue);
21517 throw this.error(new TomlError('Invalid character, expected "="'));
21521 key: "parseAssignPreValue",
21522 value: function parseAssignPreValue() {
21523 if (this.char === CHAR_SP || this.char === CTRL_I) {
21526 return this.callNow(this.parseValue, this.recordAssignValue);
21530 key: "recordAssignValue",
21531 value: function recordAssignValue(value) {
21532 return this.returnNow({
21533 key: this.state.resultTable,
21537 /* COMMENTS: #...eol */
21540 key: "parseComment",
21541 value: function parseComment() {
21543 if (this.char === Parser.END || this.char === CTRL_J) {
21544 return this.return();
21546 } while (this.nextChar());
21548 /* TABLES AND LISTS, [foo] and [[foo]] */
21551 key: "parseTableOrList",
21552 value: function parseTableOrList() {
21553 if (this.char === CHAR_LSQB) {
21554 this.next(this.parseList);
21556 return this.goto(this.parseTable);
21559 /* TABLE [foo.bar.baz] */
21563 value: function parseTable() {
21564 this.ctx = this.obj;
21565 return this.goto(this.parseTableNext);
21568 key: "parseTableNext",
21569 value: function parseTableNext() {
21570 if (this.char === CHAR_SP || this.char === CTRL_I) {
21573 return this.callNow(this.parseKeyword, this.parseTableMore);
21577 key: "parseTableMore",
21578 value: function parseTableMore(keyword) {
21579 if (this.char === CHAR_SP || this.char === CTRL_I) {
21581 } else if (this.char === CHAR_RSQB) {
21582 if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {
21583 throw this.error(new TomlError("Can't redefine existing key"));
21585 this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table();
21586 this.ctx[_declared] = true;
21589 return this.next(this.parseWhitespaceToEOL);
21590 } else if (this.char === CHAR_PERIOD) {
21591 if (!hasKey(this.ctx, keyword)) {
21592 this.ctx = this.ctx[keyword] = Table();
21593 } else if (isTable(this.ctx[keyword])) {
21594 this.ctx = this.ctx[keyword];
21595 } else if (isList(this.ctx[keyword])) {
21596 this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
21598 throw this.error(new TomlError("Can't redefine existing key"));
21601 return this.next(this.parseTableNext);
21603 throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
21606 /* LIST [[a.b.c]] */
21610 value: function parseList() {
21611 this.ctx = this.obj;
21612 return this.goto(this.parseListNext);
21615 key: "parseListNext",
21616 value: function parseListNext() {
21617 if (this.char === CHAR_SP || this.char === CTRL_I) {
21620 return this.callNow(this.parseKeyword, this.parseListMore);
21624 key: "parseListMore",
21625 value: function parseListMore(keyword) {
21626 if (this.char === CHAR_SP || this.char === CTRL_I) {
21628 } else if (this.char === CHAR_RSQB) {
21629 if (!hasKey(this.ctx, keyword)) {
21630 this.ctx[keyword] = List();
21633 if (isInlineList(this.ctx[keyword])) {
21634 throw this.error(new TomlError("Can't extend an inline array"));
21635 } else if (isList(this.ctx[keyword])) {
21636 var next = Table();
21637 this.ctx[keyword].push(next);
21640 throw this.error(new TomlError("Can't redefine an existing key"));
21643 return this.next(this.parseListEnd);
21644 } else if (this.char === CHAR_PERIOD) {
21645 if (!hasKey(this.ctx, keyword)) {
21646 this.ctx = this.ctx[keyword] = Table();
21647 } else if (isInlineList(this.ctx[keyword])) {
21648 throw this.error(new TomlError("Can't extend an inline array"));
21649 } else if (isInlineTable(this.ctx[keyword])) {
21650 throw this.error(new TomlError("Can't extend an inline table"));
21651 } else if (isList(this.ctx[keyword])) {
21652 this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
21653 } else if (isTable(this.ctx[keyword])) {
21654 this.ctx = this.ctx[keyword];
21656 throw this.error(new TomlError("Can't redefine an existing key"));
21659 return this.next(this.parseListNext);
21661 throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
21665 key: "parseListEnd",
21666 value: function parseListEnd(keyword) {
21667 if (this.char === CHAR_RSQB) {
21668 return this.next(this.parseWhitespaceToEOL);
21670 throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
21673 /* VALUE string, number, boolean, inline list, inline object */
21677 value: function parseValue() {
21678 if (this.char === Parser.END) {
21679 throw this.error(new TomlError('Key without value'));
21680 } else if (this.char === CHAR_QUOT) {
21681 return this.next(this.parseDoubleString);
21684 if (this.char === CHAR_APOS) {
21685 return this.next(this.parseSingleString);
21686 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
21687 return this.goto(this.parseNumberSign);
21688 } else if (this.char === CHAR_i) {
21689 return this.next(this.parseInf);
21690 } else if (this.char === CHAR_n) {
21691 return this.next(this.parseNan);
21692 } else if (isDigit(this.char)) {
21693 return this.goto(this.parseNumberOrDateTime);
21694 } else if (this.char === CHAR_t || this.char === CHAR_f) {
21695 return this.goto(this.parseBoolean);
21696 } else if (this.char === CHAR_LSQB) {
21697 return this.call(this.parseInlineList, this.recordValue);
21698 } else if (this.char === CHAR_LCUB) {
21699 return this.call(this.parseInlineTable, this.recordValue);
21701 throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table'));
21705 key: "recordValue",
21706 value: function recordValue(value) {
21707 return this.returnNow(value);
21711 value: function parseInf() {
21712 if (this.char === CHAR_n) {
21713 return this.next(this.parseInf2);
21715 throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
21720 value: function parseInf2() {
21721 if (this.char === CHAR_f) {
21722 if (this.state.buf === '-') {
21723 return this.return(-Infinity);
21725 return this.return(Infinity);
21728 throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
21733 value: function parseNan() {
21734 if (this.char === CHAR_a) {
21735 return this.next(this.parseNan2);
21737 throw this.error(new TomlError('Unexpected character, expected "nan"'));
21742 value: function parseNan2() {
21743 if (this.char === CHAR_n) {
21744 return this.return(NaN);
21746 throw this.error(new TomlError('Unexpected character, expected "nan"'));
21749 /* KEYS, barewords or basic, literal, or dotted */
21752 key: "parseKeyword",
21753 value: function parseKeyword() {
21754 if (this.char === CHAR_QUOT) {
21755 return this.next(this.parseBasicString);
21756 } else if (this.char === CHAR_APOS) {
21757 return this.next(this.parseLiteralString);
21759 return this.goto(this.parseBareKey);
21762 /* KEYS: barewords */
21765 key: "parseBareKey",
21766 value: function parseBareKey() {
21768 if (this.char === Parser.END) {
21769 throw this.error(new TomlError('Key ended without value'));
21770 } else if (isAlphaNumHyphen(this.char)) {
21772 } else if (this.state.buf.length === 0) {
21773 throw this.error(new TomlError('Empty bare keys are not allowed'));
21775 return this.returnNow();
21777 } while (this.nextChar());
21779 /* STRINGS, single quoted (literal) */
21782 key: "parseSingleString",
21783 value: function parseSingleString() {
21784 if (this.char === CHAR_APOS) {
21785 return this.next(this.parseLiteralMultiStringMaybe);
21787 return this.goto(this.parseLiteralString);
21791 key: "parseLiteralString",
21792 value: function parseLiteralString() {
21794 if (this.char === CHAR_APOS) {
21795 return this.return();
21796 } else if (this.atEndOfLine()) {
21797 throw this.error(new TomlError('Unterminated string'));
21798 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
21799 throw this.errorControlCharInString();
21803 } while (this.nextChar());
21806 key: "parseLiteralMultiStringMaybe",
21807 value: function parseLiteralMultiStringMaybe() {
21808 if (this.char === CHAR_APOS) {
21809 return this.next(this.parseLiteralMultiString);
21811 return this.returnNow();
21815 key: "parseLiteralMultiString",
21816 value: function parseLiteralMultiString() {
21817 if (this.char === CTRL_M) {
21819 } else if (this.char === CTRL_J) {
21820 return this.next(this.parseLiteralMultiStringContent);
21822 return this.goto(this.parseLiteralMultiStringContent);
21826 key: "parseLiteralMultiStringContent",
21827 value: function parseLiteralMultiStringContent() {
21829 if (this.char === CHAR_APOS) {
21830 return this.next(this.parseLiteralMultiEnd);
21831 } else if (this.char === Parser.END) {
21832 throw this.error(new TomlError('Unterminated multi-line string'));
21833 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
21834 throw this.errorControlCharInString();
21838 } while (this.nextChar());
21841 key: "parseLiteralMultiEnd",
21842 value: function parseLiteralMultiEnd() {
21843 if (this.char === CHAR_APOS) {
21844 return this.next(this.parseLiteralMultiEnd2);
21846 this.state.buf += "'";
21847 return this.goto(this.parseLiteralMultiStringContent);
21851 key: "parseLiteralMultiEnd2",
21852 value: function parseLiteralMultiEnd2() {
21853 if (this.char === CHAR_APOS) {
21854 return this.return();
21856 this.state.buf += "''";
21857 return this.goto(this.parseLiteralMultiStringContent);
21860 /* STRINGS double quoted */
21863 key: "parseDoubleString",
21864 value: function parseDoubleString() {
21865 if (this.char === CHAR_QUOT) {
21866 return this.next(this.parseMultiStringMaybe);
21868 return this.goto(this.parseBasicString);
21872 key: "parseBasicString",
21873 value: function parseBasicString() {
21875 if (this.char === CHAR_BSOL) {
21876 return this.call(this.parseEscape, this.recordEscapeReplacement);
21877 } else if (this.char === CHAR_QUOT) {
21878 return this.return();
21879 } else if (this.atEndOfLine()) {
21880 throw this.error(new TomlError('Unterminated string'));
21881 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
21882 throw this.errorControlCharInString();
21886 } while (this.nextChar());
21889 key: "recordEscapeReplacement",
21890 value: function recordEscapeReplacement(replacement) {
21891 this.state.buf += replacement;
21892 return this.goto(this.parseBasicString);
21895 key: "parseMultiStringMaybe",
21896 value: function parseMultiStringMaybe() {
21897 if (this.char === CHAR_QUOT) {
21898 return this.next(this.parseMultiString);
21900 return this.returnNow();
21904 key: "parseMultiString",
21905 value: function parseMultiString() {
21906 if (this.char === CTRL_M) {
21908 } else if (this.char === CTRL_J) {
21909 return this.next(this.parseMultiStringContent);
21911 return this.goto(this.parseMultiStringContent);
21915 key: "parseMultiStringContent",
21916 value: function parseMultiStringContent() {
21918 if (this.char === CHAR_BSOL) {
21919 return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement);
21920 } else if (this.char === CHAR_QUOT) {
21921 return this.next(this.parseMultiEnd);
21922 } else if (this.char === Parser.END) {
21923 throw this.error(new TomlError('Unterminated multi-line string'));
21924 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
21925 throw this.errorControlCharInString();
21929 } while (this.nextChar());
21932 key: "errorControlCharInString",
21933 value: function errorControlCharInString() {
21934 var displayCode = '\\u00';
21936 if (this.char < 16) {
21937 displayCode += '0';
21940 displayCode += this.char.toString(16);
21941 return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`));
21944 key: "recordMultiEscapeReplacement",
21945 value: function recordMultiEscapeReplacement(replacement) {
21946 this.state.buf += replacement;
21947 return this.goto(this.parseMultiStringContent);
21950 key: "parseMultiEnd",
21951 value: function parseMultiEnd() {
21952 if (this.char === CHAR_QUOT) {
21953 return this.next(this.parseMultiEnd2);
21955 this.state.buf += '"';
21956 return this.goto(this.parseMultiStringContent);
21960 key: "parseMultiEnd2",
21961 value: function parseMultiEnd2() {
21962 if (this.char === CHAR_QUOT) {
21963 return this.return();
21965 this.state.buf += '""';
21966 return this.goto(this.parseMultiStringContent);
21970 key: "parseMultiEscape",
21971 value: function parseMultiEscape() {
21972 if (this.char === CTRL_M || this.char === CTRL_J) {
21973 return this.next(this.parseMultiTrim);
21974 } else if (this.char === CHAR_SP || this.char === CTRL_I) {
21975 return this.next(this.parsePreMultiTrim);
21977 return this.goto(this.parseEscape);
21981 key: "parsePreMultiTrim",
21982 value: function parsePreMultiTrim() {
21983 if (this.char === CHAR_SP || this.char === CTRL_I) {
21985 } else if (this.char === CTRL_M || this.char === CTRL_J) {
21986 return this.next(this.parseMultiTrim);
21988 throw this.error(new TomlError("Can't escape whitespace"));
21992 key: "parseMultiTrim",
21993 value: function parseMultiTrim() {
21994 // explicitly whitespace here, END should follow the same path as chars
21995 if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
21998 return this.returnNow();
22002 key: "parseEscape",
22003 value: function parseEscape() {
22004 if (this.char in escapes) {
22005 return this.return(escapes[this.char]);
22006 } else if (this.char === CHAR_u) {
22007 return this.call(this.parseSmallUnicode, this.parseUnicodeReturn);
22008 } else if (this.char === CHAR_U) {
22009 return this.call(this.parseLargeUnicode, this.parseUnicodeReturn);
22011 throw this.error(new TomlError('Unknown escape character: ' + this.char));
22015 key: "parseUnicodeReturn",
22016 value: function parseUnicodeReturn(char) {
22018 var codePoint = parseInt(char, 16);
22020 if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {
22021 throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved'));
22024 return this.returnNow(String.fromCodePoint(codePoint));
22026 throw this.error(TomlError.wrap(err));
22030 key: "parseSmallUnicode",
22031 value: function parseSmallUnicode() {
22032 if (!isHexit(this.char)) {
22033 throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'));
22036 if (this.state.buf.length >= 4) return this.return();
22040 key: "parseLargeUnicode",
22041 value: function parseLargeUnicode() {
22042 if (!isHexit(this.char)) {
22043 throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'));
22046 if (this.state.buf.length >= 8) return this.return();
22052 key: "parseNumberSign",
22053 value: function parseNumberSign() {
22055 return this.next(this.parseMaybeSignedInfOrNan);
22058 key: "parseMaybeSignedInfOrNan",
22059 value: function parseMaybeSignedInfOrNan() {
22060 if (this.char === CHAR_i) {
22061 return this.next(this.parseInf);
22062 } else if (this.char === CHAR_n) {
22063 return this.next(this.parseNan);
22065 return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart);
22069 key: "parseNumberIntegerStart",
22070 value: function parseNumberIntegerStart() {
22071 if (this.char === CHAR_0) {
22073 return this.next(this.parseNumberIntegerExponentOrDecimal);
22075 return this.goto(this.parseNumberInteger);
22079 key: "parseNumberIntegerExponentOrDecimal",
22080 value: function parseNumberIntegerExponentOrDecimal() {
22081 if (this.char === CHAR_PERIOD) {
22083 return this.call(this.parseNoUnder, this.parseNumberFloat);
22084 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22086 return this.next(this.parseNumberExponentSign);
22088 return this.returnNow(Integer(this.state.buf));
22092 key: "parseNumberInteger",
22093 value: function parseNumberInteger() {
22094 if (isDigit(this.char)) {
22096 } else if (this.char === CHAR_LOWBAR) {
22097 return this.call(this.parseNoUnder);
22098 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22100 return this.next(this.parseNumberExponentSign);
22101 } else if (this.char === CHAR_PERIOD) {
22103 return this.call(this.parseNoUnder, this.parseNumberFloat);
22105 var result = Integer(this.state.buf);
22106 /* istanbul ignore if */
22108 if (result.isNaN()) {
22109 throw this.error(new TomlError('Invalid number'));
22111 return this.returnNow(result);
22116 key: "parseNoUnder",
22117 value: function parseNoUnder() {
22118 if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) {
22119 throw this.error(new TomlError('Unexpected character, expected digit'));
22120 } else if (this.atEndOfWord()) {
22121 throw this.error(new TomlError('Incomplete number'));
22124 return this.returnNow();
22127 key: "parseNumberFloat",
22128 value: function parseNumberFloat() {
22129 if (this.char === CHAR_LOWBAR) {
22130 return this.call(this.parseNoUnder, this.parseNumberFloat);
22131 } else if (isDigit(this.char)) {
22133 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22135 return this.next(this.parseNumberExponentSign);
22137 return this.returnNow(Float(this.state.buf));
22141 key: "parseNumberExponentSign",
22142 value: function parseNumberExponentSign() {
22143 if (isDigit(this.char)) {
22144 return this.goto(this.parseNumberExponent);
22145 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
22147 this.call(this.parseNoUnder, this.parseNumberExponent);
22149 throw this.error(new TomlError('Unexpected character, expected -, + or digit'));
22153 key: "parseNumberExponent",
22154 value: function parseNumberExponent() {
22155 if (isDigit(this.char)) {
22157 } else if (this.char === CHAR_LOWBAR) {
22158 return this.call(this.parseNoUnder);
22160 return this.returnNow(Float(this.state.buf));
22163 /* NUMBERS or DATETIMES */
22166 key: "parseNumberOrDateTime",
22167 value: function parseNumberOrDateTime() {
22168 if (this.char === CHAR_0) {
22170 return this.next(this.parseNumberBaseOrDateTime);
22172 return this.goto(this.parseNumberOrDateTimeOnly);
22176 key: "parseNumberOrDateTimeOnly",
22177 value: function parseNumberOrDateTimeOnly() {
22178 // note, if two zeros are in a row then it MUST be a date
22179 if (this.char === CHAR_LOWBAR) {
22180 return this.call(this.parseNoUnder, this.parseNumberInteger);
22181 } else if (isDigit(this.char)) {
22183 if (this.state.buf.length > 4) this.next(this.parseNumberInteger);
22184 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22186 return this.next(this.parseNumberExponentSign);
22187 } else if (this.char === CHAR_PERIOD) {
22189 return this.call(this.parseNoUnder, this.parseNumberFloat);
22190 } else if (this.char === CHAR_HYPHEN) {
22191 return this.goto(this.parseDateTime);
22192 } else if (this.char === CHAR_COLON) {
22193 return this.goto(this.parseOnlyTimeHour);
22195 return this.returnNow(Integer(this.state.buf));
22199 key: "parseDateTimeOnly",
22200 value: function parseDateTimeOnly() {
22201 if (this.state.buf.length < 4) {
22202 if (isDigit(this.char)) {
22203 return this.consume();
22204 } else if (this.char === CHAR_COLON) {
22205 return this.goto(this.parseOnlyTimeHour);
22207 throw this.error(new TomlError('Expected digit while parsing year part of a date'));
22210 if (this.char === CHAR_HYPHEN) {
22211 return this.goto(this.parseDateTime);
22213 throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date'));
22218 key: "parseNumberBaseOrDateTime",
22219 value: function parseNumberBaseOrDateTime() {
22220 if (this.char === CHAR_b) {
22222 return this.call(this.parseNoUnder, this.parseIntegerBin);
22223 } else if (this.char === CHAR_o) {
22225 return this.call(this.parseNoUnder, this.parseIntegerOct);
22226 } else if (this.char === CHAR_x) {
22228 return this.call(this.parseNoUnder, this.parseIntegerHex);
22229 } else if (this.char === CHAR_PERIOD) {
22230 return this.goto(this.parseNumberInteger);
22231 } else if (isDigit(this.char)) {
22232 return this.goto(this.parseDateTimeOnly);
22234 return this.returnNow(Integer(this.state.buf));
22238 key: "parseIntegerHex",
22239 value: function parseIntegerHex() {
22240 if (isHexit(this.char)) {
22242 } else if (this.char === CHAR_LOWBAR) {
22243 return this.call(this.parseNoUnder);
22245 var result = Integer(this.state.buf);
22246 /* istanbul ignore if */
22248 if (result.isNaN()) {
22249 throw this.error(new TomlError('Invalid number'));
22251 return this.returnNow(result);
22256 key: "parseIntegerOct",
22257 value: function parseIntegerOct() {
22258 if (isOctit(this.char)) {
22260 } else if (this.char === CHAR_LOWBAR) {
22261 return this.call(this.parseNoUnder);
22263 var result = Integer(this.state.buf);
22264 /* istanbul ignore if */
22266 if (result.isNaN()) {
22267 throw this.error(new TomlError('Invalid number'));
22269 return this.returnNow(result);
22274 key: "parseIntegerBin",
22275 value: function parseIntegerBin() {
22276 if (isBit(this.char)) {
22278 } else if (this.char === CHAR_LOWBAR) {
22279 return this.call(this.parseNoUnder);
22281 var result = Integer(this.state.buf);
22282 /* istanbul ignore if */
22284 if (result.isNaN()) {
22285 throw this.error(new TomlError('Invalid number'));
22287 return this.returnNow(result);
22294 key: "parseDateTime",
22295 value: function parseDateTime() {
22296 // we enter here having just consumed the year and about to consume the hyphen
22297 if (this.state.buf.length < 4) {
22298 throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters'));
22301 this.state.result = this.state.buf;
22302 this.state.buf = '';
22303 return this.next(this.parseDateMonth);
22306 key: "parseDateMonth",
22307 value: function parseDateMonth() {
22308 if (this.char === CHAR_HYPHEN) {
22309 if (this.state.buf.length < 2) {
22310 throw this.error(new TomlError('Months less than 10 must be zero padded to two characters'));
22313 this.state.result += '-' + this.state.buf;
22314 this.state.buf = '';
22315 return this.next(this.parseDateDay);
22316 } else if (isDigit(this.char)) {
22319 throw this.error(new TomlError('Incomplete datetime'));
22323 key: "parseDateDay",
22324 value: function parseDateDay() {
22325 if (this.char === CHAR_T || this.char === CHAR_SP) {
22326 if (this.state.buf.length < 2) {
22327 throw this.error(new TomlError('Days less than 10 must be zero padded to two characters'));
22330 this.state.result += '-' + this.state.buf;
22331 this.state.buf = '';
22332 return this.next(this.parseStartTimeHour);
22333 } else if (this.atEndOfWord()) {
22334 return this.return(createDate(this.state.result + '-' + this.state.buf));
22335 } else if (isDigit(this.char)) {
22338 throw this.error(new TomlError('Incomplete datetime'));
22342 key: "parseStartTimeHour",
22343 value: function parseStartTimeHour() {
22344 if (this.atEndOfWord()) {
22345 return this.returnNow(createDate(this.state.result));
22347 return this.goto(this.parseTimeHour);
22351 key: "parseTimeHour",
22352 value: function parseTimeHour() {
22353 if (this.char === CHAR_COLON) {
22354 if (this.state.buf.length < 2) {
22355 throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'));
22358 this.state.result += 'T' + this.state.buf;
22359 this.state.buf = '';
22360 return this.next(this.parseTimeMin);
22361 } else if (isDigit(this.char)) {
22364 throw this.error(new TomlError('Incomplete datetime'));
22368 key: "parseTimeMin",
22369 value: function parseTimeMin() {
22370 if (this.state.buf.length < 2 && isDigit(this.char)) {
22372 } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
22373 this.state.result += ':' + this.state.buf;
22374 this.state.buf = '';
22375 return this.next(this.parseTimeSec);
22377 throw this.error(new TomlError('Incomplete datetime'));
22381 key: "parseTimeSec",
22382 value: function parseTimeSec() {
22383 if (isDigit(this.char)) {
22386 if (this.state.buf.length === 2) {
22387 this.state.result += ':' + this.state.buf;
22388 this.state.buf = '';
22389 return this.next(this.parseTimeZoneOrFraction);
22392 throw this.error(new TomlError('Incomplete datetime'));
22396 key: "parseOnlyTimeHour",
22397 value: function parseOnlyTimeHour() {
22398 /* istanbul ignore else */
22399 if (this.char === CHAR_COLON) {
22400 if (this.state.buf.length < 2) {
22401 throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'));
22404 this.state.result = this.state.buf;
22405 this.state.buf = '';
22406 return this.next(this.parseOnlyTimeMin);
22408 throw this.error(new TomlError('Incomplete time'));
22412 key: "parseOnlyTimeMin",
22413 value: function parseOnlyTimeMin() {
22414 if (this.state.buf.length < 2 && isDigit(this.char)) {
22416 } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
22417 this.state.result += ':' + this.state.buf;
22418 this.state.buf = '';
22419 return this.next(this.parseOnlyTimeSec);
22421 throw this.error(new TomlError('Incomplete time'));
22425 key: "parseOnlyTimeSec",
22426 value: function parseOnlyTimeSec() {
22427 if (isDigit(this.char)) {
22430 if (this.state.buf.length === 2) {
22431 return this.next(this.parseOnlyTimeFractionMaybe);
22434 throw this.error(new TomlError('Incomplete time'));
22438 key: "parseOnlyTimeFractionMaybe",
22439 value: function parseOnlyTimeFractionMaybe() {
22440 this.state.result += ':' + this.state.buf;
22442 if (this.char === CHAR_PERIOD) {
22443 this.state.buf = '';
22444 this.next(this.parseOnlyTimeFraction);
22446 return this.return(createTime(this.state.result));
22450 key: "parseOnlyTimeFraction",
22451 value: function parseOnlyTimeFraction() {
22452 if (isDigit(this.char)) {
22454 } else if (this.atEndOfWord()) {
22455 if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds'));
22456 return this.returnNow(createTime(this.state.result + '.' + this.state.buf));
22458 throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
22462 key: "parseTimeZoneOrFraction",
22463 value: function parseTimeZoneOrFraction() {
22464 if (this.char === CHAR_PERIOD) {
22466 this.next(this.parseDateTimeFraction);
22467 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
22469 this.next(this.parseTimeZoneHour);
22470 } else if (this.char === CHAR_Z) {
22472 return this.return(createDatetime(this.state.result + this.state.buf));
22473 } else if (this.atEndOfWord()) {
22474 return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf));
22476 throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
22480 key: "parseDateTimeFraction",
22481 value: function parseDateTimeFraction() {
22482 if (isDigit(this.char)) {
22484 } else if (this.state.buf.length === 1) {
22485 throw this.error(new TomlError('Expected digit in milliseconds'));
22486 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
22488 this.next(this.parseTimeZoneHour);
22489 } else if (this.char === CHAR_Z) {
22491 return this.return(createDatetime(this.state.result + this.state.buf));
22492 } else if (this.atEndOfWord()) {
22493 return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf));
22495 throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
22499 key: "parseTimeZoneHour",
22500 value: function parseTimeZoneHour() {
22501 if (isDigit(this.char)) {
22502 this.consume(); // FIXME: No more regexps
22504 if (/\d\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep);
22506 throw this.error(new TomlError('Unexpected character in datetime, expected digit'));
22510 key: "parseTimeZoneSep",
22511 value: function parseTimeZoneSep() {
22512 if (this.char === CHAR_COLON) {
22514 this.next(this.parseTimeZoneMin);
22516 throw this.error(new TomlError('Unexpected character in datetime, expected colon'));
22520 key: "parseTimeZoneMin",
22521 value: function parseTimeZoneMin() {
22522 if (isDigit(this.char)) {
22524 if (/\d\d$/.test(this.state.buf)) return this.return(createDatetime(this.state.result + this.state.buf));
22526 throw this.error(new TomlError('Unexpected character in datetime, expected digit'));
22532 key: "parseBoolean",
22533 value: function parseBoolean() {
22534 /* istanbul ignore else */
22535 if (this.char === CHAR_t) {
22537 return this.next(this.parseTrue_r);
22538 } else if (this.char === CHAR_f) {
22540 return this.next(this.parseFalse_a);
22544 key: "parseTrue_r",
22545 value: function parseTrue_r() {
22546 if (this.char === CHAR_r) {
22548 return this.next(this.parseTrue_u);
22550 throw this.error(new TomlError('Invalid boolean, expected true or false'));
22554 key: "parseTrue_u",
22555 value: function parseTrue_u() {
22556 if (this.char === CHAR_u) {
22558 return this.next(this.parseTrue_e);
22560 throw this.error(new TomlError('Invalid boolean, expected true or false'));
22564 key: "parseTrue_e",
22565 value: function parseTrue_e() {
22566 if (this.char === CHAR_e) {
22567 return this.return(true);
22569 throw this.error(new TomlError('Invalid boolean, expected true or false'));
22573 key: "parseFalse_a",
22574 value: function parseFalse_a() {
22575 if (this.char === CHAR_a) {
22577 return this.next(this.parseFalse_l);
22579 throw this.error(new TomlError('Invalid boolean, expected true or false'));
22583 key: "parseFalse_l",
22584 value: function parseFalse_l() {
22585 if (this.char === CHAR_l) {
22587 return this.next(this.parseFalse_s);
22589 throw this.error(new TomlError('Invalid boolean, expected true or false'));
22593 key: "parseFalse_s",
22594 value: function parseFalse_s() {
22595 if (this.char === CHAR_s) {
22597 return this.next(this.parseFalse_e);
22599 throw this.error(new TomlError('Invalid boolean, expected true or false'));
22603 key: "parseFalse_e",
22604 value: function parseFalse_e() {
22605 if (this.char === CHAR_e) {
22606 return this.return(false);
22608 throw this.error(new TomlError('Invalid boolean, expected true or false'));
22614 key: "parseInlineList",
22615 value: function parseInlineList() {
22616 if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
22618 } else if (this.char === Parser.END) {
22619 throw this.error(new TomlError('Unterminated inline array'));
22620 } else if (this.char === CHAR_NUM) {
22621 return this.call(this.parseComment);
22622 } else if (this.char === CHAR_RSQB) {
22623 return this.return(this.state.resultArr || InlineList());
22625 return this.callNow(this.parseValue, this.recordInlineListValue);
22629 key: "recordInlineListValue",
22630 value: function recordInlineListValue(value) {
22631 if (this.state.resultArr) {
22632 var listType = this.state.resultArr[_contentType];
22633 var valueType = tomlType(value);
22635 if (listType !== valueType) {
22636 throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`));
22639 this.state.resultArr = InlineList(tomlType(value));
22642 if (isFloat(value) || isInteger(value)) {
22643 // unbox now that we've verified they're ok
22644 this.state.resultArr.push(value.valueOf());
22646 this.state.resultArr.push(value);
22649 return this.goto(this.parseInlineListNext);
22652 key: "parseInlineListNext",
22653 value: function parseInlineListNext() {
22654 if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
22656 } else if (this.char === CHAR_NUM) {
22657 return this.call(this.parseComment);
22658 } else if (this.char === CHAR_COMMA) {
22659 return this.next(this.parseInlineList);
22660 } else if (this.char === CHAR_RSQB) {
22661 return this.goto(this.parseInlineList);
22663 throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'));
22669 key: "parseInlineTable",
22670 value: function parseInlineTable() {
22671 if (this.char === CHAR_SP || this.char === CTRL_I) {
22673 } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
22674 throw this.error(new TomlError('Unterminated inline array'));
22675 } else if (this.char === CHAR_RCUB) {
22676 return this.return(this.state.resultTable || InlineTable());
22678 if (!this.state.resultTable) this.state.resultTable = InlineTable();
22679 return this.callNow(this.parseAssign, this.recordInlineTableValue);
22683 key: "recordInlineTableValue",
22684 value: function recordInlineTableValue(kv) {
22685 var target = this.state.resultTable;
22686 var finalKey = kv.key.pop();
22687 var _iteratorNormalCompletion2 = true;
22688 var _didIteratorError2 = false;
22689 var _iteratorError2 = undefined;
22692 for (var _iterator2 = kv.key[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
22693 var kw = _step2.value;
22695 if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
22696 throw this.error(new TomlError("Can't redefine existing key"));
22699 target = target[kw] = target[kw] || Table();
22702 _didIteratorError2 = true;
22703 _iteratorError2 = err;
22706 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
22707 _iterator2.return();
22710 if (_didIteratorError2) {
22711 throw _iteratorError2;
22716 if (hasKey(target, finalKey)) {
22717 throw this.error(new TomlError("Can't redefine existing key"));
22720 if (isInteger(kv.value) || isFloat(kv.value)) {
22721 target[finalKey] = kv.value.valueOf();
22723 target[finalKey] = kv.value;
22726 return this.goto(this.parseInlineTableNext);
22729 key: "parseInlineTableNext",
22730 value: function parseInlineTableNext() {
22731 if (this.char === CHAR_SP || this.char === CTRL_I) {
22733 } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
22734 throw this.error(new TomlError('Unterminated inline array'));
22735 } else if (this.char === CHAR_COMMA) {
22736 return this.next(this.parseInlineTable);
22737 } else if (this.char === CHAR_RCUB) {
22738 return this.goto(this.parseInlineTable);
22740 throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'));
22750 tomlParser.makeParserClass = makeParserClass_1;
22751 tomlParser.TomlError = TomlError_1;
22753 var parsePrettyError = prettyError;
22755 function prettyError(err, buf) {
22756 /* istanbul ignore if */
22757 if (err.pos == null || err.line == null) return err;
22758 var msg = err.message;
22759 msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\n`;
22760 /* istanbul ignore else */
22762 if (buf && buf.split) {
22763 var lines = buf.split(/\n/);
22764 var lineNumWidth = String(Math.min(lines.length, err.line + 3)).length;
22765 var linePadding = ' ';
22767 while (linePadding.length < lineNumWidth) {
22768 linePadding += ' ';
22771 for (var ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {
22772 var lineNum = String(ii + 1);
22773 if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum;
22775 if (err.line === ii) {
22776 msg += lineNum + '> ' + lines[ii] + '\n';
22777 msg += linePadding + ' ';
22779 for (var hh = 0; hh < err.col; ++hh) {
22785 msg += lineNum + ': ' + lines[ii] + '\n';
22790 err.message = msg + '\n';
22794 var parseString_1 = parseString;
22796 function parseString(str) {
22797 if (global.Buffer && global.Buffer.isBuffer(str)) {
22798 str = str.toString('utf8');
22801 var parser = new tomlParser();
22805 return parser.finish();
22807 throw parsePrettyError(err, str);
22811 var loadToml = function loadToml(filePath, content) {
22813 return parseString_1(content);
22815 error.message = `TOML Error in ${filePath}:\n${error.message}`;
22820 var getExplorerMemoized = mem_1(function (opts) {
22821 var explorer = thirdParty.cosmiconfig("prettier", {
22823 transform: function transform(result) {
22824 if (result && result.config) {
22825 if (typeof result.config === "string") {
22826 var modulePath = resolve.sync(result.config, {
22827 basedir: path$2.dirname(result.filepath)
22829 result.config = require(modulePath);
22832 if (typeof result.config !== "object") {
22833 throw new Error(`Config is only allowed to be an object, ` + `but received ${typeof result.config} in "${result.filepath}"`);
22836 delete result.config.$schema;
22841 searchPlaces: ["package.json", ".prettierrc", ".prettierrc.json", ".prettierrc.yaml", ".prettierrc.yml", ".prettierrc.js", "prettier.config.js", ".prettierrc.toml"],
22847 var _load = opts.sync ? explorer.loadSync : explorer.load;
22849 var search = opts.sync ? explorer.searchSync : explorer.search;
22851 // cosmiconfig v4 interface
22852 load: function load(searchPath, configPath) {
22853 return configPath ? _load(configPath) : search(searchPath);
22857 /** @param {{ cache: boolean, sync: boolean }} opts */
22859 function getLoadFunction$1(opts) {
22860 // Normalize opts before passing to a memoized function
22861 opts = Object.assign({
22865 return getExplorerMemoized(opts).load;
22868 function _resolveConfig(filePath, opts, sync) {
22869 opts = Object.assign({
22873 cache: !!opts.useCache,
22875 editorconfig: !!opts.editorconfig
22877 var load = getLoadFunction$1(loadOpts);
22878 var loadEditorConfig = resolveConfigEditorconfig.getLoadFunction(loadOpts);
22879 var arr = [load, loadEditorConfig].map(function (l) {
22880 return l(filePath, opts.config);
22883 var unwrapAndMerge = function unwrapAndMerge(arr) {
22884 var result = arr[0];
22885 var editorConfigured = arr[1];
22886 var merged = Object.assign({}, editorConfigured, mergeOverrides(Object.assign({}, result), filePath));
22887 ["plugins", "pluginSearchDirs"].forEach(function (optionName) {
22888 if (Array.isArray(merged[optionName])) {
22889 merged[optionName] = merged[optionName].map(function (value) {
22890 return typeof value === "string" && value.startsWith(".") // relative path
22891 ? path$2.resolve(path$2.dirname(result.filepath), value) : value;
22896 if (!result && !editorConfigured) {
22903 if (loadOpts.sync) {
22904 return unwrapAndMerge(arr);
22907 return Promise.all(arr).then(unwrapAndMerge);
22910 var resolveConfig = function resolveConfig(filePath, opts) {
22911 return _resolveConfig(filePath, opts, false);
22914 resolveConfig.sync = function (filePath, opts) {
22915 return _resolveConfig(filePath, opts, true);
22918 function clearCache$1() {
22919 mem_1.clear(getExplorerMemoized);
22920 resolveConfigEditorconfig.clearCache();
22923 function resolveConfigFile(filePath) {
22924 var load = getLoadFunction$1({
22927 return load(filePath).then(function (result) {
22928 return result ? result.filepath : null;
22932 resolveConfigFile.sync = function (filePath) {
22933 var load = getLoadFunction$1({
22936 var result = load(filePath);
22937 return result ? result.filepath : null;
22940 function mergeOverrides(configResult, filePath) {
22941 var options = Object.assign({}, configResult.config);
22943 if (filePath && options.overrides) {
22944 var relativeFilePath = path$2.relative(path$2.dirname(configResult.filepath), filePath);
22945 var _iteratorNormalCompletion = true;
22946 var _didIteratorError = false;
22947 var _iteratorError = undefined;
22950 for (var _iterator = options.overrides[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
22951 var override = _step.value;
22953 if (pathMatchesGlobs(relativeFilePath, override.files, override.excludeFiles)) {
22954 Object.assign(options, override.options);
22958 _didIteratorError = true;
22959 _iteratorError = err;
22962 if (!_iteratorNormalCompletion && _iterator.return != null) {
22963 _iterator.return();
22966 if (_didIteratorError) {
22967 throw _iteratorError;
22973 delete options.overrides;
22975 } // Based on eslint: https://github.com/eslint/eslint/blob/master/lib/config/config-ops.js
22978 function pathMatchesGlobs(filePath, patterns, excludedPatterns) {
22979 var patternList = [].concat(patterns);
22980 var excludedPatternList = [].concat(excludedPatterns || []);
22985 return patternList.some(function (pattern) {
22986 return minimatch_1(filePath, pattern, opts);
22987 }) && !excludedPatternList.some(function (excludedPattern) {
22988 return minimatch_1(filePath, excludedPattern, opts);
22992 var resolveConfig_1 = {
22995 clearCache: clearCache$1
22999 * @typedef {{ ignorePath?: string, withNodeModules?: boolean, plugins: object }} FileInfoOptions
23000 * @typedef {{ ignored: boolean, inferredParser: string | null }} FileInfoResult
23004 * @param {string} filePath
23005 * @param {FileInfoOptions} opts
23006 * @returns {Promise<FileInfoResult>}
23008 * Please note that prettier.getFileInfo() expects opts.plugins to be an array of paths,
23009 * not an object. A transformation from this array to an object is automatically done
23010 * internally by the method wrapper. See withPlugins() in index.js.
23014 function getFileInfo(filePath, opts) {
23015 if (typeof filePath !== "string") {
23016 return Promise.reject(new TypeError(`expect \`filePath\` to be a string, got \`${typeof filePath}\``));
23019 return createIgnorer_1(opts.ignorePath, opts.withNodeModules).then(function (ignorer) {
23020 return _getFileInfo({
23022 filePath: normalizeFilePath(filePath, opts.ignorePath),
23023 plugins: opts.plugins,
23024 resolveConfig: opts.resolveConfig,
23030 * @param {string} filePath
23031 * @param {FileInfoOptions} opts
23032 * @returns {FileInfoResult}
23036 getFileInfo.sync = function (filePath, opts) {
23037 if (typeof filePath !== "string") {
23038 throw new TypeError(`expect \`filePath\` to be a string, got \`${typeof filePath}\``);
23041 var ignorer = createIgnorer_1.sync(opts.ignorePath, opts.withNodeModules);
23042 return _getFileInfo({
23044 filePath: normalizeFilePath(filePath, opts.ignorePath),
23045 plugins: opts.plugins,
23046 resolveConfig: opts.resolveConfig,
23051 function _getFileInfo(_ref) {
23052 var ignorer = _ref.ignorer,
23053 filePath = _ref.filePath,
23054 plugins = _ref.plugins,
23055 _ref$resolveConfig = _ref.resolveConfig,
23056 resolveConfig = _ref$resolveConfig === void 0 ? false : _ref$resolveConfig,
23057 _ref$sync = _ref.sync,
23058 sync = _ref$sync === void 0 ? false : _ref$sync;
23060 ignored: ignorer.ignores(filePath),
23061 inferredParser: options$1.inferParser(filePath, plugins) || null
23064 if (!fileInfo.inferredParser && resolveConfig) {
23066 return resolveConfig_1.resolveConfig(filePath).then(function (resolvedConfig) {
23067 if (resolvedConfig && resolvedConfig.parser) {
23068 fileInfo.inferredParser = resolvedConfig.parser;
23075 var resolvedConfig = resolveConfig_1.resolveConfig.sync(filePath);
23077 if (resolvedConfig && resolvedConfig.parser) {
23078 fileInfo.inferredParser = resolvedConfig.parser;
23085 function normalizeFilePath(filePath, ignorePath) {
23086 return ignorePath ? path$2.relative(path$2.dirname(ignorePath), filePath) : filePath;
23089 var getFileInfo_1 = getFileInfo;
23091 var lodash_uniqby = createCommonjsModule(function (module, exports) {
23093 * lodash (Custom Build) <https://lodash.com/>
23094 * Build: `lodash modularize exports="npm" -o ./`
23095 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
23096 * Released under MIT license <https://lodash.com/license>
23097 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
23098 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
23101 /** Used as the size to enable large array optimizations. */
23102 var LARGE_ARRAY_SIZE = 200;
23103 /** Used as the `TypeError` message for "Functions" methods. */
23105 var FUNC_ERROR_TEXT = 'Expected a function';
23106 /** Used to stand-in for `undefined` hash values. */
23108 var HASH_UNDEFINED = '__lodash_hash_undefined__';
23109 /** Used to compose bitmasks for comparison styles. */
23111 var UNORDERED_COMPARE_FLAG = 1,
23112 PARTIAL_COMPARE_FLAG = 2;
23113 /** Used as references for various `Number` constants. */
23115 var INFINITY = 1 / 0,
23116 MAX_SAFE_INTEGER = 9007199254740991;
23117 /** `Object#toString` result references. */
23119 var argsTag = '[object Arguments]',
23120 arrayTag = '[object Array]',
23121 boolTag = '[object Boolean]',
23122 dateTag = '[object Date]',
23123 errorTag = '[object Error]',
23124 funcTag = '[object Function]',
23125 genTag = '[object GeneratorFunction]',
23126 mapTag = '[object Map]',
23127 numberTag = '[object Number]',
23128 objectTag = '[object Object]',
23129 promiseTag = '[object Promise]',
23130 regexpTag = '[object RegExp]',
23131 setTag = '[object Set]',
23132 stringTag = '[object String]',
23133 symbolTag = '[object Symbol]',
23134 weakMapTag = '[object WeakMap]';
23135 var arrayBufferTag = '[object ArrayBuffer]',
23136 dataViewTag = '[object DataView]',
23137 float32Tag = '[object Float32Array]',
23138 float64Tag = '[object Float64Array]',
23139 int8Tag = '[object Int8Array]',
23140 int16Tag = '[object Int16Array]',
23141 int32Tag = '[object Int32Array]',
23142 uint8Tag = '[object Uint8Array]',
23143 uint8ClampedTag = '[object Uint8ClampedArray]',
23144 uint16Tag = '[object Uint16Array]',
23145 uint32Tag = '[object Uint32Array]';
23146 /** Used to match property names within property paths. */
23148 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
23149 reIsPlainProp = /^\w*$/,
23150 reLeadingDot = /^\./,
23151 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
23153 * Used to match `RegExp`
23154 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
23157 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
23158 /** Used to match backslashes in property paths. */
23160 var reEscapeChar = /\\(\\)?/g;
23161 /** Used to detect host constructors (Safari). */
23163 var reIsHostCtor = /^\[object .+?Constructor\]$/;
23164 /** Used to detect unsigned integer values. */
23166 var reIsUint = /^(?:0|[1-9]\d*)$/;
23167 /** Used to identify `toStringTag` values of typed arrays. */
23169 var typedArrayTags = {};
23170 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
23171 typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
23172 /** Detect free variable `global` from Node.js. */
23174 var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
23175 /** Detect free variable `self`. */
23177 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
23178 /** Used as a reference to the global object. */
23180 var root = freeGlobal || freeSelf || Function('return this')();
23181 /** Detect free variable `exports`. */
23183 var freeExports = exports && !exports.nodeType && exports;
23184 /** Detect free variable `module`. */
23186 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
23187 /** Detect the popular CommonJS extension `module.exports`. */
23189 var moduleExports = freeModule && freeModule.exports === freeExports;
23190 /** Detect free variable `process` from Node.js. */
23192 var freeProcess = moduleExports && freeGlobal.process;
23193 /** Used to access faster Node.js helpers. */
23195 var nodeUtil = function () {
23197 return freeProcess && freeProcess.binding('util');
23200 /* Node.js helper references. */
23203 var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
23205 * A specialized version of `_.includes` for arrays without support for
23206 * specifying an index to search from.
23209 * @param {Array} [array] The array to inspect.
23210 * @param {*} target The value to search for.
23211 * @returns {boolean} Returns `true` if `target` is found, else `false`.
23214 function arrayIncludes(array, value) {
23215 var length = array ? array.length : 0;
23216 return !!length && baseIndexOf(array, value, 0) > -1;
23219 * This function is like `arrayIncludes` except that it accepts a comparator.
23222 * @param {Array} [array] The array to inspect.
23223 * @param {*} target The value to search for.
23224 * @param {Function} comparator The comparator invoked per element.
23225 * @returns {boolean} Returns `true` if `target` is found, else `false`.
23229 function arrayIncludesWith(array, value, comparator) {
23231 length = array ? array.length : 0;
23233 while (++index < length) {
23234 if (comparator(value, array[index])) {
23242 * A specialized version of `_.some` for arrays without support for iteratee
23246 * @param {Array} [array] The array to iterate over.
23247 * @param {Function} predicate The function invoked per iteration.
23248 * @returns {boolean} Returns `true` if any element passes the predicate check,
23253 function arraySome(array, predicate) {
23255 length = array ? array.length : 0;
23257 while (++index < length) {
23258 if (predicate(array[index], index, array)) {
23266 * The base implementation of `_.findIndex` and `_.findLastIndex` without
23267 * support for iteratee shorthands.
23270 * @param {Array} array The array to inspect.
23271 * @param {Function} predicate The function invoked per iteration.
23272 * @param {number} fromIndex The index to search from.
23273 * @param {boolean} [fromRight] Specify iterating from right to left.
23274 * @returns {number} Returns the index of the matched value, else `-1`.
23278 function baseFindIndex(array, predicate, fromIndex, fromRight) {
23279 var length = array.length,
23280 index = fromIndex + (fromRight ? 1 : -1);
23282 while (fromRight ? index-- : ++index < length) {
23283 if (predicate(array[index], index, array)) {
23291 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
23294 * @param {Array} array The array to inspect.
23295 * @param {*} value The value to search for.
23296 * @param {number} fromIndex The index to search from.
23297 * @returns {number} Returns the index of the matched value, else `-1`.
23301 function baseIndexOf(array, value, fromIndex) {
23302 if (value !== value) {
23303 return baseFindIndex(array, baseIsNaN, fromIndex);
23306 var index = fromIndex - 1,
23307 length = array.length;
23309 while (++index < length) {
23310 if (array[index] === value) {
23318 * The base implementation of `_.isNaN` without support for number objects.
23321 * @param {*} value The value to check.
23322 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
23326 function baseIsNaN(value) {
23327 return value !== value;
23330 * The base implementation of `_.property` without support for deep paths.
23333 * @param {string} key The key of the property to get.
23334 * @returns {Function} Returns the new accessor function.
23338 function baseProperty(key) {
23339 return function (object) {
23340 return object == null ? undefined : object[key];
23344 * The base implementation of `_.times` without support for iteratee shorthands
23345 * or max array length checks.
23348 * @param {number} n The number of times to invoke `iteratee`.
23349 * @param {Function} iteratee The function invoked per iteration.
23350 * @returns {Array} Returns the array of results.
23354 function baseTimes(n, iteratee) {
23358 while (++index < n) {
23359 result[index] = iteratee(index);
23365 * The base implementation of `_.unary` without support for storing metadata.
23368 * @param {Function} func The function to cap arguments for.
23369 * @returns {Function} Returns the new capped function.
23373 function baseUnary(func) {
23374 return function (value) {
23375 return func(value);
23379 * Checks if a cache value for `key` exists.
23382 * @param {Object} cache The cache to query.
23383 * @param {string} key The key of the entry to check.
23384 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
23388 function cacheHas(cache, key) {
23389 return cache.has(key);
23392 * Gets the value at `key` of `object`.
23395 * @param {Object} [object] The object to query.
23396 * @param {string} key The key of the property to get.
23397 * @returns {*} Returns the property value.
23401 function getValue(object, key) {
23402 return object == null ? undefined : object[key];
23405 * Checks if `value` is a host object in IE < 9.
23408 * @param {*} value The value to check.
23409 * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
23413 function isHostObject(value) {
23414 // Many host objects are `Object` objects that can coerce to strings
23415 // despite having improperly defined `toString` methods.
23416 var result = false;
23418 if (value != null && typeof value.toString != 'function') {
23420 result = !!(value + '');
23427 * Converts `map` to its key-value pairs.
23430 * @param {Object} map The map to convert.
23431 * @returns {Array} Returns the key-value pairs.
23435 function mapToArray(map) {
23437 result = Array(map.size);
23438 map.forEach(function (value, key) {
23439 result[++index] = [key, value];
23444 * Creates a unary function that invokes `func` with its argument transformed.
23447 * @param {Function} func The function to wrap.
23448 * @param {Function} transform The argument transform.
23449 * @returns {Function} Returns the new function.
23453 function overArg(func, transform) {
23454 return function (arg) {
23455 return func(transform(arg));
23459 * Converts `set` to an array of its values.
23462 * @param {Object} set The set to convert.
23463 * @returns {Array} Returns the values.
23467 function setToArray(set) {
23469 result = Array(set.size);
23470 set.forEach(function (value) {
23471 result[++index] = value;
23475 /** Used for built-in method references. */
23478 var arrayProto = Array.prototype,
23479 funcProto = Function.prototype,
23480 objectProto = Object.prototype;
23481 /** Used to detect overreaching core-js shims. */
23483 var coreJsData = root['__core-js_shared__'];
23484 /** Used to detect methods masquerading as native. */
23486 var maskSrcKey = function () {
23487 var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
23488 return uid ? 'Symbol(src)_1.' + uid : '';
23490 /** Used to resolve the decompiled source of functions. */
23493 var funcToString = funcProto.toString;
23494 /** Used to check objects for own properties. */
23496 var hasOwnProperty = objectProto.hasOwnProperty;
23498 * Used to resolve the
23499 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
23503 var objectToString = objectProto.toString;
23504 /** Used to detect if a method is native. */
23506 var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
23507 /** Built-in value references. */
23509 var Symbol = root.Symbol,
23510 Uint8Array = root.Uint8Array,
23511 propertyIsEnumerable = objectProto.propertyIsEnumerable,
23512 splice = arrayProto.splice;
23513 /* Built-in method references for those with the same name as other `lodash` methods. */
23515 var nativeKeys = overArg(Object.keys, Object);
23516 /* Built-in method references that are verified to be native. */
23518 var DataView = getNative(root, 'DataView'),
23519 Map = getNative(root, 'Map'),
23520 Promise = getNative(root, 'Promise'),
23521 Set = getNative(root, 'Set'),
23522 WeakMap = getNative(root, 'WeakMap'),
23523 nativeCreate = getNative(Object, 'create');
23524 /** Used to detect maps, sets, and weakmaps. */
23526 var dataViewCtorString = toSource(DataView),
23527 mapCtorString = toSource(Map),
23528 promiseCtorString = toSource(Promise),
23529 setCtorString = toSource(Set),
23530 weakMapCtorString = toSource(WeakMap);
23531 /** Used to convert symbols to primitives and strings. */
23533 var symbolProto = Symbol ? Symbol.prototype : undefined,
23534 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
23535 symbolToString = symbolProto ? symbolProto.toString : undefined;
23537 * Creates a hash object.
23541 * @param {Array} [entries] The key-value pairs to cache.
23544 function Hash(entries) {
23546 length = entries ? entries.length : 0;
23549 while (++index < length) {
23550 var entry = entries[index];
23551 this.set(entry[0], entry[1]);
23555 * Removes all key-value entries from the hash.
23563 function hashClear() {
23564 this.__data__ = nativeCreate ? nativeCreate(null) : {};
23567 * Removes `key` and its value from the hash.
23572 * @param {Object} hash The hash to modify.
23573 * @param {string} key The key of the value to remove.
23574 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
23578 function hashDelete(key) {
23579 return this.has(key) && delete this.__data__[key];
23582 * Gets the hash value for `key`.
23587 * @param {string} key The key of the value to get.
23588 * @returns {*} Returns the entry value.
23592 function hashGet(key) {
23593 var data = this.__data__;
23595 if (nativeCreate) {
23596 var result = data[key];
23597 return result === HASH_UNDEFINED ? undefined : result;
23600 return hasOwnProperty.call(data, key) ? data[key] : undefined;
23603 * Checks if a hash value for `key` exists.
23608 * @param {string} key The key of the entry to check.
23609 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
23613 function hashHas(key) {
23614 var data = this.__data__;
23615 return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
23618 * Sets the hash `key` to `value`.
23623 * @param {string} key The key of the value to set.
23624 * @param {*} value The value to set.
23625 * @returns {Object} Returns the hash instance.
23629 function hashSet(key, value) {
23630 var data = this.__data__;
23631 data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value;
23633 } // Add methods to `Hash`.
23636 Hash.prototype.clear = hashClear;
23637 Hash.prototype['delete'] = hashDelete;
23638 Hash.prototype.get = hashGet;
23639 Hash.prototype.has = hashHas;
23640 Hash.prototype.set = hashSet;
23642 * Creates an list cache object.
23646 * @param {Array} [entries] The key-value pairs to cache.
23649 function ListCache(entries) {
23651 length = entries ? entries.length : 0;
23654 while (++index < length) {
23655 var entry = entries[index];
23656 this.set(entry[0], entry[1]);
23660 * Removes all key-value entries from the list cache.
23664 * @memberOf ListCache
23668 function listCacheClear() {
23669 this.__data__ = [];
23672 * Removes `key` and its value from the list cache.
23676 * @memberOf ListCache
23677 * @param {string} key The key of the value to remove.
23678 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
23682 function listCacheDelete(key) {
23683 var data = this.__data__,
23684 index = assocIndexOf(data, key);
23690 var lastIndex = data.length - 1;
23692 if (index == lastIndex) {
23695 splice.call(data, index, 1);
23701 * Gets the list cache value for `key`.
23705 * @memberOf ListCache
23706 * @param {string} key The key of the value to get.
23707 * @returns {*} Returns the entry value.
23711 function listCacheGet(key) {
23712 var data = this.__data__,
23713 index = assocIndexOf(data, key);
23714 return index < 0 ? undefined : data[index][1];
23717 * Checks if a list cache value for `key` exists.
23721 * @memberOf ListCache
23722 * @param {string} key The key of the entry to check.
23723 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
23727 function listCacheHas(key) {
23728 return assocIndexOf(this.__data__, key) > -1;
23731 * Sets the list cache `key` to `value`.
23735 * @memberOf ListCache
23736 * @param {string} key The key of the value to set.
23737 * @param {*} value The value to set.
23738 * @returns {Object} Returns the list cache instance.
23742 function listCacheSet(key, value) {
23743 var data = this.__data__,
23744 index = assocIndexOf(data, key);
23747 data.push([key, value]);
23749 data[index][1] = value;
23753 } // Add methods to `ListCache`.
23756 ListCache.prototype.clear = listCacheClear;
23757 ListCache.prototype['delete'] = listCacheDelete;
23758 ListCache.prototype.get = listCacheGet;
23759 ListCache.prototype.has = listCacheHas;
23760 ListCache.prototype.set = listCacheSet;
23762 * Creates a map cache object to store key-value pairs.
23766 * @param {Array} [entries] The key-value pairs to cache.
23769 function MapCache(entries) {
23771 length = entries ? entries.length : 0;
23774 while (++index < length) {
23775 var entry = entries[index];
23776 this.set(entry[0], entry[1]);
23780 * Removes all key-value entries from the map.
23784 * @memberOf MapCache
23788 function mapCacheClear() {
23790 'hash': new Hash(),
23791 'map': new (Map || ListCache)(),
23792 'string': new Hash()
23796 * Removes `key` and its value from the map.
23800 * @memberOf MapCache
23801 * @param {string} key The key of the value to remove.
23802 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
23806 function mapCacheDelete(key) {
23807 return getMapData(this, key)['delete'](key);
23810 * Gets the map value for `key`.
23814 * @memberOf MapCache
23815 * @param {string} key The key of the value to get.
23816 * @returns {*} Returns the entry value.
23820 function mapCacheGet(key) {
23821 return getMapData(this, key).get(key);
23824 * Checks if a map value for `key` exists.
23828 * @memberOf MapCache
23829 * @param {string} key The key of the entry to check.
23830 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
23834 function mapCacheHas(key) {
23835 return getMapData(this, key).has(key);
23838 * Sets the map `key` to `value`.
23842 * @memberOf MapCache
23843 * @param {string} key The key of the value to set.
23844 * @param {*} value The value to set.
23845 * @returns {Object} Returns the map cache instance.
23849 function mapCacheSet(key, value) {
23850 getMapData(this, key).set(key, value);
23852 } // Add methods to `MapCache`.
23855 MapCache.prototype.clear = mapCacheClear;
23856 MapCache.prototype['delete'] = mapCacheDelete;
23857 MapCache.prototype.get = mapCacheGet;
23858 MapCache.prototype.has = mapCacheHas;
23859 MapCache.prototype.set = mapCacheSet;
23862 * Creates an array cache object to store unique values.
23866 * @param {Array} [values] The values to cache.
23869 function SetCache(values) {
23871 length = values ? values.length : 0;
23872 this.__data__ = new MapCache();
23874 while (++index < length) {
23875 this.add(values[index]);
23879 * Adds `value` to the array cache.
23883 * @memberOf SetCache
23885 * @param {*} value The value to cache.
23886 * @returns {Object} Returns the cache instance.
23890 function setCacheAdd(value) {
23891 this.__data__.set(value, HASH_UNDEFINED);
23896 * Checks if `value` is in the array cache.
23900 * @memberOf SetCache
23901 * @param {*} value The value to search for.
23902 * @returns {number} Returns `true` if `value` is found, else `false`.
23906 function setCacheHas(value) {
23907 return this.__data__.has(value);
23908 } // Add methods to `SetCache`.
23911 SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
23912 SetCache.prototype.has = setCacheHas;
23914 * Creates a stack cache object to store key-value pairs.
23918 * @param {Array} [entries] The key-value pairs to cache.
23921 function Stack(entries) {
23922 this.__data__ = new ListCache(entries);
23925 * Removes all key-value entries from the stack.
23933 function stackClear() {
23934 this.__data__ = new ListCache();
23937 * Removes `key` and its value from the stack.
23942 * @param {string} key The key of the value to remove.
23943 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
23947 function stackDelete(key) {
23948 return this.__data__['delete'](key);
23951 * Gets the stack value for `key`.
23956 * @param {string} key The key of the value to get.
23957 * @returns {*} Returns the entry value.
23961 function stackGet(key) {
23962 return this.__data__.get(key);
23965 * Checks if a stack value for `key` exists.
23970 * @param {string} key The key of the entry to check.
23971 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
23975 function stackHas(key) {
23976 return this.__data__.has(key);
23979 * Sets the stack `key` to `value`.
23984 * @param {string} key The key of the value to set.
23985 * @param {*} value The value to set.
23986 * @returns {Object} Returns the stack cache instance.
23990 function stackSet(key, value) {
23991 var cache = this.__data__;
23993 if (cache instanceof ListCache) {
23994 var pairs = cache.__data__;
23996 if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
23997 pairs.push([key, value]);
24001 cache = this.__data__ = new MapCache(pairs);
24004 cache.set(key, value);
24006 } // Add methods to `Stack`.
24009 Stack.prototype.clear = stackClear;
24010 Stack.prototype['delete'] = stackDelete;
24011 Stack.prototype.get = stackGet;
24012 Stack.prototype.has = stackHas;
24013 Stack.prototype.set = stackSet;
24015 * Creates an array of the enumerable property names of the array-like `value`.
24018 * @param {*} value The value to query.
24019 * @param {boolean} inherited Specify returning inherited property names.
24020 * @returns {Array} Returns the array of property names.
24023 function arrayLikeKeys(value, inherited) {
24024 // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
24025 // Safari 9 makes `arguments.length` enumerable in strict mode.
24026 var result = isArray(value) || isArguments(value) ? baseTimes(value.length, String) : [];
24027 var length = result.length,
24028 skipIndexes = !!length;
24030 for (var key in value) {
24031 if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
24039 * Gets the index at which the `key` is found in `array` of key-value pairs.
24042 * @param {Array} array The array to inspect.
24043 * @param {*} key The key to search for.
24044 * @returns {number} Returns the index of the matched value, else `-1`.
24048 function assocIndexOf(array, key) {
24049 var length = array.length;
24052 if (eq(array[length][0], key)) {
24060 * The base implementation of `_.get` without support for default values.
24063 * @param {Object} object The object to query.
24064 * @param {Array|string} path The path of the property to get.
24065 * @returns {*} Returns the resolved value.
24069 function baseGet(object, path) {
24070 path = isKey(path, object) ? [path] : castPath(path);
24072 length = path.length;
24074 while (object != null && index < length) {
24075 object = object[toKey(path[index++])];
24078 return index && index == length ? object : undefined;
24081 * The base implementation of `getTag`.
24084 * @param {*} value The value to query.
24085 * @returns {string} Returns the `toStringTag`.
24089 function baseGetTag(value) {
24090 return objectToString.call(value);
24093 * The base implementation of `_.hasIn` without support for deep paths.
24096 * @param {Object} [object] The object to query.
24097 * @param {Array|string} key The key to check.
24098 * @returns {boolean} Returns `true` if `key` exists, else `false`.
24102 function baseHasIn(object, key) {
24103 return object != null && key in Object(object);
24106 * The base implementation of `_.isEqual` which supports partial comparisons
24107 * and tracks traversed objects.
24110 * @param {*} value The value to compare.
24111 * @param {*} other The other value to compare.
24112 * @param {Function} [customizer] The function to customize comparisons.
24113 * @param {boolean} [bitmask] The bitmask of comparison flags.
24114 * The bitmask may be composed of the following flags:
24115 * 1 - Unordered comparison
24116 * 2 - Partial comparison
24117 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
24118 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
24122 function baseIsEqual(value, other, customizer, bitmask, stack) {
24123 if (value === other) {
24127 if (value == null || other == null || !isObject(value) && !isObjectLike(other)) {
24128 return value !== value && other !== other;
24131 return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
24134 * A specialized version of `baseIsEqual` for arrays and objects which performs
24135 * deep comparisons and tracks traversed objects enabling objects with circular
24136 * references to be compared.
24139 * @param {Object} object The object to compare.
24140 * @param {Object} other The other object to compare.
24141 * @param {Function} equalFunc The function to determine equivalents of values.
24142 * @param {Function} [customizer] The function to customize comparisons.
24143 * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
24144 * for more details.
24145 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
24146 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
24150 function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
24151 var objIsArr = isArray(object),
24152 othIsArr = isArray(other),
24157 objTag = getTag(object);
24158 objTag = objTag == argsTag ? objectTag : objTag;
24162 othTag = getTag(other);
24163 othTag = othTag == argsTag ? objectTag : othTag;
24166 var objIsObj = objTag == objectTag && !isHostObject(object),
24167 othIsObj = othTag == objectTag && !isHostObject(other),
24168 isSameTag = objTag == othTag;
24170 if (isSameTag && !objIsObj) {
24171 stack || (stack = new Stack());
24172 return objIsArr || isTypedArray(object) ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
24175 if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
24176 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
24177 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
24179 if (objIsWrapped || othIsWrapped) {
24180 var objUnwrapped = objIsWrapped ? object.value() : object,
24181 othUnwrapped = othIsWrapped ? other.value() : other;
24182 stack || (stack = new Stack());
24183 return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack);
24191 stack || (stack = new Stack());
24192 return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
24195 * The base implementation of `_.isMatch` without support for iteratee shorthands.
24198 * @param {Object} object The object to inspect.
24199 * @param {Object} source The object of property values to match.
24200 * @param {Array} matchData The property names, values, and compare flags to match.
24201 * @param {Function} [customizer] The function to customize comparisons.
24202 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
24206 function baseIsMatch(object, source, matchData, customizer) {
24207 var index = matchData.length,
24209 noCustomizer = !customizer;
24211 if (object == null) {
24215 object = Object(object);
24218 var data = matchData[index];
24220 if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
24225 while (++index < length) {
24226 data = matchData[index];
24228 objValue = object[key],
24229 srcValue = data[1];
24231 if (noCustomizer && data[2]) {
24232 if (objValue === undefined && !(key in object)) {
24236 var stack = new Stack();
24239 var result = customizer(objValue, srcValue, key, object, source, stack);
24242 if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) : result)) {
24251 * The base implementation of `_.isNative` without bad shim checks.
24254 * @param {*} value The value to check.
24255 * @returns {boolean} Returns `true` if `value` is a native function,
24260 function baseIsNative(value) {
24261 if (!isObject(value) || isMasked(value)) {
24265 var pattern = isFunction(value) || isHostObject(value) ? reIsNative : reIsHostCtor;
24266 return pattern.test(toSource(value));
24269 * The base implementation of `_.isTypedArray` without Node.js optimizations.
24272 * @param {*} value The value to check.
24273 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
24277 function baseIsTypedArray(value) {
24278 return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
24281 * The base implementation of `_.iteratee`.
24284 * @param {*} [value=_.identity] The value to convert to an iteratee.
24285 * @returns {Function} Returns the iteratee.
24289 function baseIteratee(value) {
24290 // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
24291 // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
24292 if (typeof value == 'function') {
24296 if (value == null) {
24300 if (typeof value == 'object') {
24301 return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value);
24304 return property(value);
24307 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
24310 * @param {Object} object The object to query.
24311 * @returns {Array} Returns the array of property names.
24315 function baseKeys(object) {
24316 if (!isPrototype(object)) {
24317 return nativeKeys(object);
24322 for (var key in Object(object)) {
24323 if (hasOwnProperty.call(object, key) && key != 'constructor') {
24331 * The base implementation of `_.matches` which doesn't clone `source`.
24334 * @param {Object} source The object of property values to match.
24335 * @returns {Function} Returns the new spec function.
24339 function baseMatches(source) {
24340 var matchData = getMatchData(source);
24342 if (matchData.length == 1 && matchData[0][2]) {
24343 return matchesStrictComparable(matchData[0][0], matchData[0][1]);
24346 return function (object) {
24347 return object === source || baseIsMatch(object, source, matchData);
24351 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
24354 * @param {string} path The path of the property to get.
24355 * @param {*} srcValue The value to match.
24356 * @returns {Function} Returns the new spec function.
24360 function baseMatchesProperty(path, srcValue) {
24361 if (isKey(path) && isStrictComparable(srcValue)) {
24362 return matchesStrictComparable(toKey(path), srcValue);
24365 return function (object) {
24366 var objValue = get(object, path);
24367 return objValue === undefined && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG);
24371 * A specialized version of `baseProperty` which supports deep paths.
24374 * @param {Array|string} path The path of the property to get.
24375 * @returns {Function} Returns the new accessor function.
24379 function basePropertyDeep(path) {
24380 return function (object) {
24381 return baseGet(object, path);
24385 * The base implementation of `_.toString` which doesn't convert nullish
24386 * values to empty strings.
24389 * @param {*} value The value to process.
24390 * @returns {string} Returns the string.
24394 function baseToString(value) {
24395 // Exit early for strings to avoid a performance hit in some environments.
24396 if (typeof value == 'string') {
24400 if (isSymbol(value)) {
24401 return symbolToString ? symbolToString.call(value) : '';
24404 var result = value + '';
24405 return result == '0' && 1 / value == -INFINITY ? '-0' : result;
24408 * The base implementation of `_.uniqBy` without support for iteratee shorthands.
24411 * @param {Array} array The array to inspect.
24412 * @param {Function} [iteratee] The iteratee invoked per element.
24413 * @param {Function} [comparator] The comparator invoked per element.
24414 * @returns {Array} Returns the new duplicate free array.
24418 function baseUniq(array, iteratee, comparator) {
24420 includes = arrayIncludes,
24421 length = array.length,
24428 includes = arrayIncludesWith;
24429 } else if (length >= LARGE_ARRAY_SIZE) {
24430 var set = iteratee ? null : createSet(array);
24433 return setToArray(set);
24437 includes = cacheHas;
24438 seen = new SetCache();
24440 seen = iteratee ? [] : result;
24443 outer: while (++index < length) {
24444 var value = array[index],
24445 computed = iteratee ? iteratee(value) : value;
24446 value = comparator || value !== 0 ? value : 0;
24448 if (isCommon && computed === computed) {
24449 var seenIndex = seen.length;
24451 while (seenIndex--) {
24452 if (seen[seenIndex] === computed) {
24458 seen.push(computed);
24461 result.push(value);
24462 } else if (!includes(seen, computed, comparator)) {
24463 if (seen !== result) {
24464 seen.push(computed);
24467 result.push(value);
24474 * Casts `value` to a path array if it's not one.
24477 * @param {*} value The value to inspect.
24478 * @returns {Array} Returns the cast property path array.
24482 function castPath(value) {
24483 return isArray(value) ? value : stringToPath(value);
24486 * Creates a set object of `values`.
24489 * @param {Array} values The values to add to the set.
24490 * @returns {Object} Returns the new set.
24494 var createSet = !(Set && 1 / setToArray(new Set([, -0]))[1] == INFINITY) ? noop : function (values) {
24495 return new Set(values);
24498 * A specialized version of `baseIsEqualDeep` for arrays with support for
24499 * partial deep comparisons.
24502 * @param {Array} array The array to compare.
24503 * @param {Array} other The other array to compare.
24504 * @param {Function} equalFunc The function to determine equivalents of values.
24505 * @param {Function} customizer The function to customize comparisons.
24506 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
24507 * for more details.
24508 * @param {Object} stack Tracks traversed `array` and `other` objects.
24509 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
24512 function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
24513 var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
24514 arrLength = array.length,
24515 othLength = other.length;
24517 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
24519 } // Assume cyclic values are equal.
24522 var stacked = stack.get(array);
24524 if (stacked && stack.get(other)) {
24525 return stacked == other;
24530 seen = bitmask & UNORDERED_COMPARE_FLAG ? new SetCache() : undefined;
24531 stack.set(array, other);
24532 stack.set(other, array); // Ignore non-index properties.
24534 while (++index < arrLength) {
24535 var arrValue = array[index],
24536 othValue = other[index];
24539 var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
24542 if (compared !== undefined) {
24549 } // Recursively compare arrays (susceptible to call stack limits).
24553 if (!arraySome(other, function (othValue, othIndex) {
24554 if (!seen.has(othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
24555 return seen.add(othIndex);
24561 } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
24567 stack['delete'](array);
24568 stack['delete'](other);
24572 * A specialized version of `baseIsEqualDeep` for comparing objects of
24573 * the same `toStringTag`.
24575 * **Note:** This function only supports comparing values with tags of
24576 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
24579 * @param {Object} object The object to compare.
24580 * @param {Object} other The other object to compare.
24581 * @param {string} tag The `toStringTag` of the objects to compare.
24582 * @param {Function} equalFunc The function to determine equivalents of values.
24583 * @param {Function} customizer The function to customize comparisons.
24584 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
24585 * for more details.
24586 * @param {Object} stack Tracks traversed `object` and `other` objects.
24587 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
24591 function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
24594 if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
24598 object = object.buffer;
24599 other = other.buffer;
24601 case arrayBufferTag:
24602 if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
24611 // Coerce booleans to `1` or `0` and dates to milliseconds.
24612 // Invalid dates are coerced to `NaN`.
24613 return eq(+object, +other);
24616 return object.name == other.name && object.message == other.message;
24620 // Coerce regexes to strings and treat strings, primitives and objects,
24621 // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
24622 // for more details.
24623 return object == other + '';
24626 var convert = mapToArray;
24629 var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
24630 convert || (convert = setToArray);
24632 if (object.size != other.size && !isPartial) {
24634 } // Assume cyclic values are equal.
24637 var stacked = stack.get(object);
24640 return stacked == other;
24643 bitmask |= UNORDERED_COMPARE_FLAG; // Recursively compare objects (susceptible to call stack limits).
24645 stack.set(object, other);
24646 var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
24647 stack['delete'](object);
24651 if (symbolValueOf) {
24652 return symbolValueOf.call(object) == symbolValueOf.call(other);
24660 * A specialized version of `baseIsEqualDeep` for objects with support for
24661 * partial deep comparisons.
24664 * @param {Object} object The object to compare.
24665 * @param {Object} other The other object to compare.
24666 * @param {Function} equalFunc The function to determine equivalents of values.
24667 * @param {Function} customizer The function to customize comparisons.
24668 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
24669 * for more details.
24670 * @param {Object} stack Tracks traversed `object` and `other` objects.
24671 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
24675 function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
24676 var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
24677 objProps = keys(object),
24678 objLength = objProps.length,
24679 othProps = keys(other),
24680 othLength = othProps.length;
24682 if (objLength != othLength && !isPartial) {
24686 var index = objLength;
24689 var key = objProps[index];
24691 if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
24694 } // Assume cyclic values are equal.
24697 var stacked = stack.get(object);
24699 if (stacked && stack.get(other)) {
24700 return stacked == other;
24704 stack.set(object, other);
24705 stack.set(other, object);
24706 var skipCtor = isPartial;
24708 while (++index < objLength) {
24709 key = objProps[index];
24710 var objValue = object[key],
24711 othValue = other[key];
24714 var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
24715 } // Recursively compare objects (susceptible to call stack limits).
24718 if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack) : compared)) {
24723 skipCtor || (skipCtor = key == 'constructor');
24726 if (result && !skipCtor) {
24727 var objCtor = object.constructor,
24728 othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal.
24730 if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
24735 stack['delete'](object);
24736 stack['delete'](other);
24740 * Gets the data for `map`.
24743 * @param {Object} map The map to query.
24744 * @param {string} key The reference key.
24745 * @returns {*} Returns the map data.
24749 function getMapData(map, key) {
24750 var data = map.__data__;
24751 return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
24754 * Gets the property names, values, and compare flags of `object`.
24757 * @param {Object} object The object to query.
24758 * @returns {Array} Returns the match data of `object`.
24762 function getMatchData(object) {
24763 var result = keys(object),
24764 length = result.length;
24767 var key = result[length],
24768 value = object[key];
24769 result[length] = [key, value, isStrictComparable(value)];
24775 * Gets the native function at `key` of `object`.
24778 * @param {Object} object The object to query.
24779 * @param {string} key The key of the method to get.
24780 * @returns {*} Returns the function if it's native, else `undefined`.
24784 function getNative(object, key) {
24785 var value = getValue(object, key);
24786 return baseIsNative(value) ? value : undefined;
24789 * Gets the `toStringTag` of `value`.
24792 * @param {*} value The value to query.
24793 * @returns {string} Returns the `toStringTag`.
24797 var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11,
24798 // for data views in Edge < 14, and promises in Node.js.
24800 if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag || Promise && getTag(Promise.resolve()) != promiseTag || Set && getTag(new Set()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) {
24801 getTag = function getTag(value) {
24802 var result = objectToString.call(value),
24803 Ctor = result == objectTag ? value.constructor : undefined,
24804 ctorString = Ctor ? toSource(Ctor) : undefined;
24807 switch (ctorString) {
24808 case dataViewCtorString:
24809 return dataViewTag;
24811 case mapCtorString:
24814 case promiseCtorString:
24817 case setCtorString:
24820 case weakMapCtorString:
24829 * Checks if `path` exists on `object`.
24832 * @param {Object} object The object to query.
24833 * @param {Array|string} path The path to check.
24834 * @param {Function} hasFunc The function to check properties.
24835 * @returns {boolean} Returns `true` if `path` exists, else `false`.
24839 function hasPath(object, path, hasFunc) {
24840 path = isKey(path, object) ? [path] : castPath(path);
24843 length = path.length;
24845 while (++index < length) {
24846 var key = toKey(path[index]);
24848 if (!(result = object != null && hasFunc(object, key))) {
24852 object = object[key];
24859 var length = object ? object.length : 0;
24860 return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object));
24863 * Checks if `value` is a valid array-like index.
24866 * @param {*} value The value to check.
24867 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
24868 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
24872 function isIndex(value, length) {
24873 length = length == null ? MAX_SAFE_INTEGER : length;
24874 return !!length && (typeof value == 'number' || reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
24877 * Checks if `value` is a property name and not a property path.
24880 * @param {*} value The value to check.
24881 * @param {Object} [object] The object to query keys on.
24882 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
24886 function isKey(value, object) {
24887 if (isArray(value)) {
24891 var type = typeof value;
24893 if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) {
24897 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
24900 * Checks if `value` is suitable for use as unique object key.
24903 * @param {*} value The value to check.
24904 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
24908 function isKeyable(value) {
24909 var type = typeof value;
24910 return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
24913 * Checks if `func` has its source masked.
24916 * @param {Function} func The function to check.
24917 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
24921 function isMasked(func) {
24922 return !!maskSrcKey && maskSrcKey in func;
24925 * Checks if `value` is likely a prototype object.
24928 * @param {*} value The value to check.
24929 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
24933 function isPrototype(value) {
24934 var Ctor = value && value.constructor,
24935 proto = typeof Ctor == 'function' && Ctor.prototype || objectProto;
24936 return value === proto;
24939 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
24942 * @param {*} value The value to check.
24943 * @returns {boolean} Returns `true` if `value` if suitable for strict
24944 * equality comparisons, else `false`.
24948 function isStrictComparable(value) {
24949 return value === value && !isObject(value);
24952 * A specialized version of `matchesProperty` for source values suitable
24953 * for strict equality comparisons, i.e. `===`.
24956 * @param {string} key The key of the property to get.
24957 * @param {*} srcValue The value to match.
24958 * @returns {Function} Returns the new spec function.
24962 function matchesStrictComparable(key, srcValue) {
24963 return function (object) {
24964 if (object == null) {
24968 return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
24972 * Converts `string` to a property path array.
24975 * @param {string} string The string to convert.
24976 * @returns {Array} Returns the property path array.
24980 var stringToPath = memoize(function (string) {
24981 string = toString(string);
24984 if (reLeadingDot.test(string)) {
24988 string.replace(rePropName, function (match, number, quote, string) {
24989 result.push(quote ? string.replace(reEscapeChar, '$1') : number || match);
24994 * Converts `value` to a string key if it's not a string or symbol.
24997 * @param {*} value The value to inspect.
24998 * @returns {string|symbol} Returns the key.
25001 function toKey(value) {
25002 if (typeof value == 'string' || isSymbol(value)) {
25006 var result = value + '';
25007 return result == '0' && 1 / value == -INFINITY ? '-0' : result;
25010 * Converts `func` to its source code.
25013 * @param {Function} func The function to process.
25014 * @returns {string} Returns the source code.
25018 function toSource(func) {
25019 if (func != null) {
25021 return funcToString.call(func);
25032 * This method is like `_.uniq` except that it accepts `iteratee` which is
25033 * invoked for each element in `array` to generate the criterion by which
25034 * uniqueness is computed. The iteratee is invoked with one argument: (value).
25040 * @param {Array} array The array to inspect.
25041 * @param {Function} [iteratee=_.identity]
25042 * The iteratee invoked per element.
25043 * @returns {Array} Returns the new duplicate free array.
25046 * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
25049 * // The `_.property` iteratee shorthand.
25050 * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
25051 * // => [{ 'x': 1 }, { 'x': 2 }]
25055 function uniqBy(array, iteratee) {
25056 return array && array.length ? baseUniq(array, baseIteratee(iteratee)) : [];
25059 * Creates a function that memoizes the result of `func`. If `resolver` is
25060 * provided, it determines the cache key for storing the result based on the
25061 * arguments provided to the memoized function. By default, the first argument
25062 * provided to the memoized function is used as the map cache key. The `func`
25063 * is invoked with the `this` binding of the memoized function.
25065 * **Note:** The cache is exposed as the `cache` property on the memoized
25066 * function. Its creation may be customized by replacing the `_.memoize.Cache`
25067 * constructor with one whose instances implement the
25068 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
25069 * method interface of `delete`, `get`, `has`, and `set`.
25074 * @category Function
25075 * @param {Function} func The function to have its output memoized.
25076 * @param {Function} [resolver] The function to resolve the cache key.
25077 * @returns {Function} Returns the new memoized function.
25080 * var object = { 'a': 1, 'b': 2 };
25081 * var other = { 'c': 3, 'd': 4 };
25083 * var values = _.memoize(_.values);
25094 * // Modify the result cache.
25095 * values.cache.set(object, ['a', 'b']);
25099 * // Replace `_.memoize.Cache`.
25100 * _.memoize.Cache = WeakMap;
25104 function memoize(func, resolver) {
25105 if (typeof func != 'function' || resolver && typeof resolver != 'function') {
25106 throw new TypeError(FUNC_ERROR_TEXT);
25109 var memoized = function memoized() {
25110 var args = arguments,
25111 key = resolver ? resolver.apply(this, args) : args[0],
25112 cache = memoized.cache;
25114 if (cache.has(key)) {
25115 return cache.get(key);
25118 var result = func.apply(this, args);
25119 memoized.cache = cache.set(key, result);
25123 memoized.cache = new (memoize.Cache || MapCache)();
25125 } // Assign cache to `_.memoize`.
25128 memoize.Cache = MapCache;
25131 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
25132 * comparison between two values to determine if they are equivalent.
25138 * @param {*} value The value to compare.
25139 * @param {*} other The other value to compare.
25140 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
25143 * var object = { 'a': 1 };
25144 * var other = { 'a': 1 };
25146 * _.eq(object, object);
25149 * _.eq(object, other);
25155 * _.eq('a', Object('a'));
25162 function eq(value, other) {
25163 return value === other || value !== value && other !== other;
25166 * Checks if `value` is likely an `arguments` object.
25172 * @param {*} value The value to check.
25173 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
25177 * _.isArguments(function() { return arguments; }());
25180 * _.isArguments([1, 2, 3]);
25185 function isArguments(value) {
25186 // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
25187 return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
25190 * Checks if `value` is classified as an `Array` object.
25196 * @param {*} value The value to check.
25197 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
25200 * _.isArray([1, 2, 3]);
25203 * _.isArray(document.body.children);
25206 * _.isArray('abc');
25209 * _.isArray(_.noop);
25214 var isArray = Array.isArray;
25216 * Checks if `value` is array-like. A value is considered array-like if it's
25217 * not a function and has a `value.length` that's an integer greater than or
25218 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
25224 * @param {*} value The value to check.
25225 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
25228 * _.isArrayLike([1, 2, 3]);
25231 * _.isArrayLike(document.body.children);
25234 * _.isArrayLike('abc');
25237 * _.isArrayLike(_.noop);
25241 function isArrayLike(value) {
25242 return value != null && isLength(value.length) && !isFunction(value);
25245 * This method is like `_.isArrayLike` except that it also checks if `value`
25252 * @param {*} value The value to check.
25253 * @returns {boolean} Returns `true` if `value` is an array-like object,
25257 * _.isArrayLikeObject([1, 2, 3]);
25260 * _.isArrayLikeObject(document.body.children);
25263 * _.isArrayLikeObject('abc');
25266 * _.isArrayLikeObject(_.noop);
25271 function isArrayLikeObject(value) {
25272 return isObjectLike(value) && isArrayLike(value);
25275 * Checks if `value` is classified as a `Function` object.
25281 * @param {*} value The value to check.
25282 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
25288 * _.isFunction(/abc/);
25293 function isFunction(value) {
25294 // The use of `Object#toString` avoids issues with the `typeof` operator
25295 // in Safari 8-9 which returns 'object' for typed array and other constructors.
25296 var tag = isObject(value) ? objectToString.call(value) : '';
25297 return tag == funcTag || tag == genTag;
25300 * Checks if `value` is a valid array-like length.
25302 * **Note:** This method is loosely based on
25303 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
25309 * @param {*} value The value to check.
25310 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
25316 * _.isLength(Number.MIN_VALUE);
25319 * _.isLength(Infinity);
25327 function isLength(value) {
25328 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
25331 * Checks if `value` is the
25332 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
25333 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
25339 * @param {*} value The value to check.
25340 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
25346 * _.isObject([1, 2, 3]);
25349 * _.isObject(_.noop);
25352 * _.isObject(null);
25357 function isObject(value) {
25358 var type = typeof value;
25359 return !!value && (type == 'object' || type == 'function');
25362 * Checks if `value` is object-like. A value is object-like if it's not `null`
25363 * and has a `typeof` result of "object".
25369 * @param {*} value The value to check.
25370 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
25373 * _.isObjectLike({});
25376 * _.isObjectLike([1, 2, 3]);
25379 * _.isObjectLike(_.noop);
25382 * _.isObjectLike(null);
25387 function isObjectLike(value) {
25388 return !!value && typeof value == 'object';
25391 * Checks if `value` is classified as a `Symbol` primitive or object.
25397 * @param {*} value The value to check.
25398 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
25401 * _.isSymbol(Symbol.iterator);
25404 * _.isSymbol('abc');
25409 function isSymbol(value) {
25410 return typeof value == 'symbol' || isObjectLike(value) && objectToString.call(value) == symbolTag;
25413 * Checks if `value` is classified as a typed array.
25419 * @param {*} value The value to check.
25420 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
25423 * _.isTypedArray(new Uint8Array);
25426 * _.isTypedArray([]);
25431 var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
25433 * Converts `value` to a string. An empty string is returned for `null`
25434 * and `undefined` values. The sign of `-0` is preserved.
25440 * @param {*} value The value to process.
25441 * @returns {string} Returns the string.
25444 * _.toString(null);
25450 * _.toString([1, 2, 3]);
25454 function toString(value) {
25455 return value == null ? '' : baseToString(value);
25458 * Gets the value at `path` of `object`. If the resolved value is
25459 * `undefined`, the `defaultValue` is returned in its place.
25465 * @param {Object} object The object to query.
25466 * @param {Array|string} path The path of the property to get.
25467 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
25468 * @returns {*} Returns the resolved value.
25471 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
25473 * _.get(object, 'a[0].b.c');
25476 * _.get(object, ['a', '0', 'b', 'c']);
25479 * _.get(object, 'a.b.c', 'default');
25484 function get(object, path, defaultValue) {
25485 var result = object == null ? undefined : baseGet(object, path);
25486 return result === undefined ? defaultValue : result;
25489 * Checks if `path` is a direct or inherited property of `object`.
25495 * @param {Object} object The object to query.
25496 * @param {Array|string} path The path to check.
25497 * @returns {boolean} Returns `true` if `path` exists, else `false`.
25500 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
25502 * _.hasIn(object, 'a');
25505 * _.hasIn(object, 'a.b');
25508 * _.hasIn(object, ['a', 'b']);
25511 * _.hasIn(object, 'b');
25516 function hasIn(object, path) {
25517 return object != null && hasPath(object, path, baseHasIn);
25520 * Creates an array of the own enumerable property names of `object`.
25522 * **Note:** Non-object values are coerced to objects. See the
25523 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
25524 * for more details.
25530 * @param {Object} object The object to query.
25531 * @returns {Array} Returns the array of property names.
25539 * Foo.prototype.c = 3;
25542 * // => ['a', 'b'] (iteration order is not guaranteed)
25549 function keys(object) {
25550 return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
25553 * This method returns the first argument it receives.
25559 * @param {*} value Any value.
25560 * @returns {*} Returns `value`.
25563 * var object = { 'a': 1 };
25565 * console.log(_.identity(object) === object);
25570 function identity(value) {
25574 * This method returns `undefined`.
25582 * _.times(2, _.noop);
25583 * // => [undefined, undefined]
25587 function noop() {} // No operation performed.
25590 * Creates a function that returns the value at `path` of a given object.
25596 * @param {Array|string} path The path of the property to get.
25597 * @returns {Function} Returns the new accessor function.
25601 * { 'a': { 'b': 2 } },
25602 * { 'a': { 'b': 1 } }
25605 * _.map(objects, _.property('a.b'));
25608 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
25613 function property(path) {
25614 return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
25617 module.exports = uniqBy;
25620 var PENDING = 'pending';
25621 var SETTLED = 'settled';
25622 var FULFILLED = 'fulfilled';
25623 var REJECTED = 'rejected';
25625 var NOOP = function NOOP() {};
25627 var isNode = typeof global !== 'undefined' && typeof global.process !== 'undefined' && typeof global.process.emit === 'function';
25628 var asyncSetTimer = typeof setImmediate === 'undefined' ? setTimeout : setImmediate;
25629 var asyncQueue = [];
25632 function asyncFlush() {
25633 // run promise callbacks
25634 for (var i = 0; i < asyncQueue.length; i++) {
25635 asyncQueue[i][0](asyncQueue[i][1]);
25636 } // reset async asyncQueue
25640 asyncTimer = false;
25643 function asyncCall(callback, arg) {
25644 asyncQueue.push([callback, arg]);
25648 asyncSetTimer(asyncFlush, 0);
25652 function invokeResolver(resolver, promise) {
25653 function resolvePromise(value) {
25654 resolve$1(promise, value);
25657 function rejectPromise(reason) {
25658 reject(promise, reason);
25662 resolver(resolvePromise, rejectPromise);
25668 function invokeCallback(subscriber) {
25669 var owner = subscriber.owner;
25670 var settled = owner._state;
25671 var value = owner._data;
25672 var callback = subscriber[settled];
25673 var promise = subscriber.then;
25675 if (typeof callback === 'function') {
25676 settled = FULFILLED;
25679 value = callback(value);
25681 reject(promise, e);
25685 if (!handleThenable(promise, value)) {
25686 if (settled === FULFILLED) {
25687 resolve$1(promise, value);
25690 if (settled === REJECTED) {
25691 reject(promise, value);
25696 function handleThenable(promise, value) {
25700 if (promise === value) {
25701 throw new TypeError('A promises callback cannot return that same promise.');
25704 if (value && (typeof value === 'function' || typeof value === 'object')) {
25705 // then should be retrieved only once
25706 var then = value.then;
25708 if (typeof then === 'function') {
25709 then.call(value, function (val) {
25713 if (value === val) {
25714 fulfill(promise, val);
25716 resolve$1(promise, val);
25719 }, function (reason) {
25722 reject(promise, reason);
25730 reject(promise, e);
25739 function resolve$1(promise, value) {
25740 if (promise === value || !handleThenable(promise, value)) {
25741 fulfill(promise, value);
25745 function fulfill(promise, value) {
25746 if (promise._state === PENDING) {
25747 promise._state = SETTLED;
25748 promise._data = value;
25749 asyncCall(publishFulfillment, promise);
25753 function reject(promise, reason) {
25754 if (promise._state === PENDING) {
25755 promise._state = SETTLED;
25756 promise._data = reason;
25757 asyncCall(publishRejection, promise);
25761 function publish(promise) {
25762 promise._then = promise._then.forEach(invokeCallback);
25765 function publishFulfillment(promise) {
25766 promise._state = FULFILLED;
25770 function publishRejection(promise) {
25771 promise._state = REJECTED;
25774 if (!promise._handled && isNode) {
25775 global.process.emit('unhandledRejection', promise._data, promise);
25779 function notifyRejectionHandled(promise) {
25780 global.process.emit('rejectionHandled', promise);
25787 function Promise$1(resolver) {
25788 if (typeof resolver !== 'function') {
25789 throw new TypeError('Promise resolver ' + resolver + ' is not a function');
25792 if (this instanceof Promise$1 === false) {
25793 throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.');
25797 invokeResolver(resolver, this);
25800 Promise$1.prototype = {
25801 constructor: Promise$1,
25806 then: function then(onFulfillment, onRejection) {
25809 then: new this.constructor(NOOP),
25810 fulfilled: onFulfillment,
25811 rejected: onRejection
25814 if ((onRejection || onFulfillment) && !this._handled) {
25815 this._handled = true;
25817 if (this._state === REJECTED && isNode) {
25818 asyncCall(notifyRejectionHandled, this);
25822 if (this._state === FULFILLED || this._state === REJECTED) {
25823 // already resolved, call callback async
25824 asyncCall(invokeCallback, subscriber);
25827 this._then.push(subscriber);
25830 return subscriber.then;
25832 catch: function _catch(onRejection) {
25833 return this.then(null, onRejection);
25837 Promise$1.all = function (promises) {
25838 if (!Array.isArray(promises)) {
25839 throw new TypeError('You must pass an array to Promise.all().');
25842 return new Promise$1(function (resolve, reject) {
25846 function resolver(index) {
25848 return function (value) {
25849 results[index] = value;
25851 if (! --remaining) {
25857 for (var i = 0, promise; i < promises.length; i++) {
25858 promise = promises[i];
25860 if (promise && typeof promise.then === 'function') {
25861 promise.then(resolver(i), reject);
25863 results[i] = promise;
25873 Promise$1.race = function (promises) {
25874 if (!Array.isArray(promises)) {
25875 throw new TypeError('You must pass an array to Promise.race().');
25878 return new Promise$1(function (resolve, reject) {
25879 for (var i = 0, promise; i < promises.length; i++) {
25880 promise = promises[i];
25882 if (promise && typeof promise.then === 'function') {
25883 promise.then(resolve, reject);
25891 Promise$1.resolve = function (value) {
25892 if (value && typeof value === 'object' && value.constructor === Promise$1) {
25896 return new Promise$1(function (resolve) {
25901 Promise$1.reject = function (reason) {
25902 return new Promise$1(function (resolve, reject) {
25907 var pinkie = Promise$1;
25909 var pinkiePromise = typeof Promise === 'function' ? Promise : pinkie;
25911 var arrayUniq = createCommonjsModule(function (module) {
25912 // 1 - no Set type is defined
25914 function uniqNoSet(arr) {
25917 for (var i = 0; i < arr.length; i++) {
25918 if (ret.indexOf(arr[i]) === -1) {
25924 } // 2 - a simple Set type is defined
25927 function uniqSet(arr) {
25928 var seen = new Set();
25929 return arr.filter(function (el) {
25930 if (!seen.has(el)) {
25937 } // 3 - a standard Set type is defined and it has a forEach method
25940 function uniqSetWithForEach(arr) {
25942 new Set(arr).forEach(function (el) {
25946 } // V8 currently has a broken implementation
25947 // https://github.com/joyent/node/issues/8449
25950 function doesForEachActuallyWork() {
25952 new Set([true]).forEach(function (el) {
25955 return ret === true;
25958 if ('Set' in global) {
25959 if (typeof Set.prototype.forEach === 'function' && doesForEachActuallyWork()) {
25960 module.exports = uniqSetWithForEach;
25962 module.exports = uniqSet;
25965 module.exports = uniqNoSet;
25969 var arrayUnion = function arrayUnion() {
25970 return arrayUniq([].concat.apply([], arguments));
25978 /* eslint-disable no-unused-vars */
25980 var getOwnPropertySymbols = Object.getOwnPropertySymbols;
25981 var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
25982 var propIsEnumerable = Object.prototype.propertyIsEnumerable;
25984 function toObject(val) {
25985 if (val === null || val === undefined) {
25986 throw new TypeError('Object.assign cannot be called with null or undefined');
25989 return Object(val);
25992 function shouldUseNative() {
25994 if (!Object.assign) {
25996 } // Detect buggy property enumeration order in older V8 versions.
25997 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
26000 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
26004 if (Object.getOwnPropertyNames(test1)[0] === '5') {
26006 } // https://bugs.chromium.org/p/v8/issues/detail?id=3056
26011 for (var i = 0; i < 10; i++) {
26012 test2['_' + String.fromCharCode(i)] = i;
26015 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
26019 if (order2.join('') !== '0123456789') {
26021 } // https://bugs.chromium.org/p/v8/issues/detail?id=3056
26025 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
26026 test3[letter] = letter;
26029 if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') {
26035 // We don't expect any of the above to throw, but better to be safe.
26040 var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
26042 var to = toObject(target);
26045 for (var s = 1; s < arguments.length; s++) {
26046 from = Object(arguments[s]);
26048 for (var key in from) {
26049 if (hasOwnProperty$2.call(from, key)) {
26050 to[key] = from[key];
26054 if (getOwnPropertySymbols) {
26055 symbols = getOwnPropertySymbols(from);
26057 for (var i = 0; i < symbols.length; i++) {
26058 if (propIsEnumerable.call(from, symbols[i])) {
26059 to[symbols[i]] = from[symbols[i]];
26069 // Permission is hereby granted, free of charge, to any person obtaining a
26070 // copy of this software and associated documentation files (the
26071 // "Software"), to deal in the Software without restriction, including
26072 // without limitation the rights to use, copy, modify, merge, publish,
26073 // distribute, sublicense, and/or sell copies of the Software, and to permit
26074 // persons to whom the Software is furnished to do so, subject to the
26075 // following conditions:
26077 // The above copyright notice and this permission notice shall be included
26078 // in all copies or substantial portions of the Software.
26080 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
26081 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26082 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
26083 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
26084 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
26085 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
26086 // USE OR OTHER DEALINGS IN THE SOFTWARE.
26088 var isWindows = process.platform === 'win32'; // JavaScript implementation of realpath, ported from node pre-v6
26090 var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
26092 function rethrow() {
26093 // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
26094 // is fairly slow to generate.
26098 var backtrace = new Error();
26099 callback = debugCallback;
26100 } else callback = missingCallback;
26104 function debugCallback(err) {
26106 backtrace.message = err.message;
26108 missingCallback(err);
26112 function missingCallback(err) {
26114 if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
26115 else if (!process.noDeprecation) {
26116 var msg = 'fs: missing callback ' + (err.stack || err.message);
26117 if (process.traceDeprecation) console.trace(msg);else console.error(msg);
26123 function maybeCallback(cb) {
26124 return typeof cb === 'function' ? cb : rethrow();
26127 var normalize$3 = path$2.normalize; // Regexp that finds the next partion of a (partial) path
26128 // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
26131 var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
26133 var nextPartRe = /(.*?)(?:[\/]+|$)/g;
26134 } // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
26138 var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
26140 var splitRootRe = /^[\/]*/;
26143 var realpathSync = function realpathSync(p, cache) {
26144 // make p is absolute
26145 p = path$2.resolve(p);
26147 if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
26153 knownHard = {}; // current character position in p
26155 var pos; // the partial path so far, including a trailing slash if any
26157 var current; // the partial path without a trailing slash (except when pointing at a root)
26159 var base; // the partial path scanned in the previous round, with slash
26166 var m = splitRootRe.exec(p);
26170 previous = ''; // On windows, check that the root exists. On unix there is no need.
26172 if (isWindows && !knownHard[base]) {
26173 fs$1.lstatSync(base);
26174 knownHard[base] = true;
26176 } // walk down the path, swapping out linked pathparts for their real
26178 // NB: p.length changes.
26181 while (pos < p.length) {
26182 // find the next part
26183 nextPartRe.lastIndex = pos;
26184 var result = nextPartRe.exec(p);
26185 previous = current;
26186 current += result[0];
26187 base = previous + result[1];
26188 pos = nextPartRe.lastIndex; // continue if not a symlink
26190 if (knownHard[base] || cache && cache[base] === base) {
26196 if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
26197 // some known symbolic link. no need to stat again.
26198 resolvedLink = cache[base];
26200 var stat = fs$1.lstatSync(base);
26202 if (!stat.isSymbolicLink()) {
26203 knownHard[base] = true;
26204 if (cache) cache[base] = base;
26206 } // read the link if it wasn't read before
26207 // dev/ino always return 0 on windows, so skip the check.
26210 var linkTarget = null;
26213 var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
26215 if (seenLinks.hasOwnProperty(id)) {
26216 linkTarget = seenLinks[id];
26220 if (linkTarget === null) {
26221 fs$1.statSync(base);
26222 linkTarget = fs$1.readlinkSync(base);
26225 resolvedLink = path$2.resolve(previous, linkTarget); // track this, if given a cache.
26227 if (cache) cache[base] = resolvedLink;
26228 if (!isWindows) seenLinks[id] = linkTarget;
26229 } // resolve the link, then start over
26232 p = path$2.resolve(resolvedLink, p.slice(pos));
26236 if (cache) cache[original] = p;
26240 var realpath = function realpath(p, cache, cb) {
26241 if (typeof cb !== 'function') {
26242 cb = maybeCallback(cache);
26244 } // make p is absolute
26247 p = path$2.resolve(p);
26249 if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
26250 return process.nextTick(cb.bind(null, null, cache[p]));
26255 knownHard = {}; // current character position in p
26257 var pos; // the partial path so far, including a trailing slash if any
26259 var current; // the partial path without a trailing slash (except when pointing at a root)
26261 var base; // the partial path scanned in the previous round, with slash
26268 var m = splitRootRe.exec(p);
26272 previous = ''; // On windows, check that the root exists. On unix there is no need.
26274 if (isWindows && !knownHard[base]) {
26275 fs$1.lstat(base, function (err) {
26276 if (err) return cb(err);
26277 knownHard[base] = true;
26281 process.nextTick(LOOP);
26283 } // walk down the path, swapping out linked pathparts for their real
26288 // stop if scanned past end of path
26289 if (pos >= p.length) {
26290 if (cache) cache[original] = p;
26291 return cb(null, p);
26292 } // find the next part
26295 nextPartRe.lastIndex = pos;
26296 var result = nextPartRe.exec(p);
26297 previous = current;
26298 current += result[0];
26299 base = previous + result[1];
26300 pos = nextPartRe.lastIndex; // continue if not a symlink
26302 if (knownHard[base] || cache && cache[base] === base) {
26303 return process.nextTick(LOOP);
26306 if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
26307 // known symbolic link. no need to stat again.
26308 return gotResolvedLink(cache[base]);
26311 return fs$1.lstat(base, gotStat);
26314 function gotStat(err, stat) {
26315 if (err) return cb(err); // if not a symlink, skip to the next path part
26317 if (!stat.isSymbolicLink()) {
26318 knownHard[base] = true;
26319 if (cache) cache[base] = base;
26320 return process.nextTick(LOOP);
26321 } // stat & read the link if not read before
26322 // call gotTarget as soon as the link target is known
26323 // dev/ino always return 0 on windows, so skip the check.
26327 var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
26329 if (seenLinks.hasOwnProperty(id)) {
26330 return gotTarget(null, seenLinks[id], base);
26334 fs$1.stat(base, function (err) {
26335 if (err) return cb(err);
26336 fs$1.readlink(base, function (err, target) {
26337 if (!isWindows) seenLinks[id] = target;
26338 gotTarget(err, target);
26343 function gotTarget(err, target, base) {
26344 if (err) return cb(err);
26345 var resolvedLink = path$2.resolve(previous, target);
26346 if (cache) cache[base] = resolvedLink;
26347 gotResolvedLink(resolvedLink);
26350 function gotResolvedLink(resolvedLink) {
26351 // resolve the link, then start over
26352 p = path$2.resolve(resolvedLink, p.slice(pos));
26358 realpathSync: realpathSync,
26362 var fs_realpath = realpath$1;
26363 realpath$1.realpath = realpath$1;
26364 realpath$1.sync = realpathSync$1;
26365 realpath$1.realpathSync = realpathSync$1;
26366 realpath$1.monkeypatch = monkeypatch;
26367 realpath$1.unmonkeypatch = unmonkeypatch;
26368 var origRealpath = fs$1.realpath;
26369 var origRealpathSync = fs$1.realpathSync;
26370 var version$2 = process.version;
26371 var ok = /^v[0-5]\./.test(version$2);
26373 function newError(er) {
26374 return er && er.syscall === 'realpath' && (er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG');
26377 function realpath$1(p, cache, cb) {
26379 return origRealpath(p, cache, cb);
26382 if (typeof cache === 'function') {
26387 origRealpath(p, cache, function (er, result) {
26388 if (newError(er)) {
26389 old.realpath(p, cache, cb);
26396 function realpathSync$1(p, cache) {
26398 return origRealpathSync(p, cache);
26402 return origRealpathSync(p, cache);
26404 if (newError(er)) {
26405 return old.realpathSync(p, cache);
26412 function monkeypatch() {
26413 fs$1.realpath = realpath$1;
26414 fs$1.realpathSync = realpathSync$1;
26417 function unmonkeypatch() {
26418 fs$1.realpath = origRealpath;
26419 fs$1.realpathSync = origRealpathSync;
26422 var inherits_browser = createCommonjsModule(function (module) {
26423 if (typeof Object.create === 'function') {
26424 // implementation from standard node.js 'util' module
26425 module.exports = function inherits(ctor, superCtor) {
26427 ctor.super_ = superCtor;
26428 ctor.prototype = Object.create(superCtor.prototype, {
26439 // old school shim for old browsers
26440 module.exports = function inherits(ctor, superCtor) {
26442 ctor.super_ = superCtor;
26444 var TempCtor = function TempCtor() {};
26446 TempCtor.prototype = superCtor.prototype;
26447 ctor.prototype = new TempCtor();
26448 ctor.prototype.constructor = ctor;
26454 var inherits = createCommonjsModule(function (module) {
26457 /* istanbul ignore next */
26459 if (typeof util.inherits !== 'function') throw '';
26460 module.exports = util.inherits;
26462 /* istanbul ignore next */
26463 module.exports = inherits_browser;
26467 function posix(path) {
26468 return path.charAt(0) === '/';
26471 function win32(path) {
26472 // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
26473 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
26474 var result = splitDeviceRe.exec(path);
26475 var device = result[1] || '';
26476 var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute
26478 return Boolean(result[2] || isUnc);
26481 var pathIsAbsolute = process.platform === 'win32' ? win32 : posix;
26482 var posix_1 = posix;
26483 var win32_1 = win32;
26484 pathIsAbsolute.posix = posix_1;
26485 pathIsAbsolute.win32 = win32_1;
26487 var alphasort_1 = alphasort;
26488 var alphasorti_1 = alphasorti;
26489 var setopts_1 = setopts;
26490 var ownProp_1 = ownProp;
26491 var makeAbs_1 = makeAbs;
26492 var finish_1 = finish;
26494 var isIgnored_1 = isIgnored;
26495 var childrenIgnored_1 = childrenIgnored;
26497 function ownProp(obj, field) {
26498 return Object.prototype.hasOwnProperty.call(obj, field);
26501 var Minimatch$1 = minimatch_1.Minimatch;
26503 function alphasorti(a, b) {
26504 return a.toLowerCase().localeCompare(b.toLowerCase());
26507 function alphasort(a, b) {
26508 return a.localeCompare(b);
26511 function setupIgnores(self, options) {
26512 self.ignore = options.ignore || [];
26513 if (!Array.isArray(self.ignore)) self.ignore = [self.ignore];
26515 if (self.ignore.length) {
26516 self.ignore = self.ignore.map(ignoreMap);
26518 } // ignore patterns are always in dot:true mode.
26521 function ignoreMap(pattern) {
26522 var gmatcher = null;
26524 if (pattern.slice(-3) === '/**') {
26525 var gpattern = pattern.replace(/(\/\*\*)+$/, '');
26526 gmatcher = new Minimatch$1(gpattern, {
26532 matcher: new Minimatch$1(pattern, {
26539 function setopts(self, pattern, options) {
26540 if (!options) options = {}; // base-matching: just use globstar for that.
26542 if (options.matchBase && -1 === pattern.indexOf("/")) {
26543 if (options.noglobstar) {
26544 throw new Error("base matching requires globstar");
26547 pattern = "**/" + pattern;
26550 self.silent = !!options.silent;
26551 self.pattern = pattern;
26552 self.strict = options.strict !== false;
26553 self.realpath = !!options.realpath;
26554 self.realpathCache = options.realpathCache || Object.create(null);
26555 self.follow = !!options.follow;
26556 self.dot = !!options.dot;
26557 self.mark = !!options.mark;
26558 self.nodir = !!options.nodir;
26559 if (self.nodir) self.mark = true;
26560 self.sync = !!options.sync;
26561 self.nounique = !!options.nounique;
26562 self.nonull = !!options.nonull;
26563 self.nosort = !!options.nosort;
26564 self.nocase = !!options.nocase;
26565 self.stat = !!options.stat;
26566 self.noprocess = !!options.noprocess;
26567 self.absolute = !!options.absolute;
26568 self.maxLength = options.maxLength || Infinity;
26569 self.cache = options.cache || Object.create(null);
26570 self.statCache = options.statCache || Object.create(null);
26571 self.symlinks = options.symlinks || Object.create(null);
26572 setupIgnores(self, options);
26573 self.changedCwd = false;
26574 var cwd = process.cwd();
26575 if (!ownProp(options, "cwd")) self.cwd = cwd;else {
26576 self.cwd = path$2.resolve(options.cwd);
26577 self.changedCwd = self.cwd !== cwd;
26579 self.root = options.root || path$2.resolve(self.cwd, "/");
26580 self.root = path$2.resolve(self.root);
26581 if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/"); // TODO: is an absolute `cwd` supposed to be resolved against `root`?
26582 // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
26584 self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
26585 if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
26586 self.nomount = !!options.nomount; // disable comments and negation in Minimatch.
26587 // Note that they are not supported in Glob itself anyway.
26589 options.nonegate = true;
26590 options.nocomment = true;
26591 self.minimatch = new Minimatch$1(pattern, options);
26592 self.options = self.minimatch.options;
26595 function finish(self) {
26596 var nou = self.nounique;
26597 var all = nou ? [] : Object.create(null);
26599 for (var i = 0, l = self.matches.length; i < l; i++) {
26600 var matches = self.matches[i];
26602 if (!matches || Object.keys(matches).length === 0) {
26604 // do like the shell, and spit out the literal glob
26605 var literal = self.minimatch.globSet[i];
26606 if (nou) all.push(literal);else all[literal] = true;
26610 var m = Object.keys(matches);
26611 if (nou) all.push.apply(all, m);else m.forEach(function (m) {
26617 if (!nou) all = Object.keys(all);
26618 if (!self.nosort) all = all.sort(self.nocase ? alphasorti : alphasort); // at *some* point we statted all of these
26621 for (var i = 0; i < all.length; i++) {
26622 all[i] = self._mark(all[i]);
26626 all = all.filter(function (e) {
26627 var notDir = !/\/$/.test(e);
26628 var c = self.cache[e] || self.cache[makeAbs(self, e)];
26629 if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c);
26635 if (self.ignore.length) all = all.filter(function (m) {
26636 return !isIgnored(self, m);
26641 function mark(self, p) {
26642 var abs = makeAbs(self, p);
26643 var c = self.cache[abs];
26647 var isDir = c === 'DIR' || Array.isArray(c);
26648 var slash = p.slice(-1) === '/';
26649 if (isDir && !slash) m += '/';else if (!isDir && slash) m = m.slice(0, -1);
26652 var mabs = makeAbs(self, m);
26653 self.statCache[mabs] = self.statCache[abs];
26654 self.cache[mabs] = self.cache[abs];
26659 } // lotta situps...
26662 function makeAbs(self, f) {
26665 if (f.charAt(0) === '/') {
26666 abs = path$2.join(self.root, f);
26667 } else if (pathIsAbsolute(f) || f === '') {
26669 } else if (self.changedCwd) {
26670 abs = path$2.resolve(self.cwd, f);
26672 abs = path$2.resolve(f);
26675 if (process.platform === 'win32') abs = abs.replace(/\\/g, '/');
26677 } // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
26678 // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
26681 function isIgnored(self, path) {
26682 if (!self.ignore.length) return false;
26683 return self.ignore.some(function (item) {
26684 return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path));
26688 function childrenIgnored(self, path) {
26689 if (!self.ignore.length) return false;
26690 return self.ignore.some(function (item) {
26691 return !!(item.gmatcher && item.gmatcher.match(path));
26696 alphasort: alphasort_1,
26697 alphasorti: alphasorti_1,
26698 setopts: setopts_1,
26699 ownProp: ownProp_1,
26700 makeAbs: makeAbs_1,
26703 isIgnored: isIgnored_1,
26704 childrenIgnored: childrenIgnored_1
26707 var sync$1 = globSync;
26708 globSync.GlobSync = GlobSync;
26709 var setopts$1 = common$2.setopts;
26710 var ownProp$1 = common$2.ownProp;
26711 var childrenIgnored$1 = common$2.childrenIgnored;
26712 var isIgnored$1 = common$2.isIgnored;
26714 function globSync(pattern, options) {
26715 if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n' + 'See: https://github.com/isaacs/node-glob/issues/167');
26716 return new GlobSync(pattern, options).found;
26719 function GlobSync(pattern, options) {
26720 if (!pattern) throw new Error('must provide pattern');
26721 if (typeof options === 'function' || arguments.length === 3) throw new TypeError('callback provided to sync glob\n' + 'See: https://github.com/isaacs/node-glob/issues/167');
26722 if (!(this instanceof GlobSync)) return new GlobSync(pattern, options);
26723 setopts$1(this, pattern, options);
26724 if (this.noprocess) return this;
26725 var n = this.minimatch.set.length;
26726 this.matches = new Array(n);
26728 for (var i = 0; i < n; i++) {
26729 this._process(this.minimatch.set[i], i, false);
26735 GlobSync.prototype._finish = function () {
26736 assert$1(this instanceof GlobSync);
26738 if (this.realpath) {
26740 this.matches.forEach(function (matchset, index) {
26741 var set = self.matches[index] = Object.create(null);
26743 for (var p in matchset) {
26745 p = self._makeAbs(p);
26746 var real = fs_realpath.realpathSync(p, self.realpathCache);
26749 if (er.syscall === 'stat') set[self._makeAbs(p)] = true;else throw er;
26755 common$2.finish(this);
26758 GlobSync.prototype._process = function (pattern, index, inGlobStar) {
26759 assert$1(this instanceof GlobSync); // Get the first [n] parts of pattern that are all strings.
26763 while (typeof pattern[n] === 'string') {
26765 } // now n is the index of the first one that is *not* a string.
26766 // See if there's anything else
26772 // if not, then this is rather simple
26773 case pattern.length:
26774 this._processSimple(pattern.join('/'), index);
26779 // pattern *starts* with some non-trivial item.
26780 // going to readdir(cwd), but not include the prefix in matches.
26785 // pattern has some string bits in the front.
26786 // whatever it starts with, whether that's 'absolute' like /foo/bar,
26787 // or 'relative' like '../baz'
26788 prefix = pattern.slice(0, n).join('/');
26792 var remain = pattern.slice(n); // get the list of entries.
26795 if (prefix === null) read = '.';else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
26796 if (!prefix || !pathIsAbsolute(prefix)) prefix = '/' + prefix;
26798 } else read = prefix;
26800 var abs = this._makeAbs(read); //if ignored, skip processing
26803 if (childrenIgnored$1(this, read)) return;
26804 var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
26805 if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);else this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
26808 GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
26809 var entries = this._readdir(abs, inGlobStar); // if the abs isn't a dir, then nothing can match!
26812 if (!entries) return; // It will only match dot entries if it starts with a dot, or if
26813 // dot is set. Stuff like @(.foo|.bar) isn't allowed.
26815 var pn = remain[0];
26816 var negate = !!this.minimatch.negate;
26817 var rawGlob = pn._glob;
26818 var dotOk = this.dot || rawGlob.charAt(0) === '.';
26819 var matchedEntries = [];
26821 for (var i = 0; i < entries.length; i++) {
26822 var e = entries[i];
26824 if (e.charAt(0) !== '.' || dotOk) {
26827 if (negate && !prefix) {
26833 if (m) matchedEntries.push(e);
26837 var len = matchedEntries.length; // If there are no matched entries, then nothing matches.
26839 if (len === 0) return; // if this is the last remaining pattern bit, then no need for
26840 // an additional stat *unless* the user has specified mark or
26841 // stat explicitly. We know they exist, since readdir returned
26844 if (remain.length === 1 && !this.mark && !this.stat) {
26845 if (!this.matches[index]) this.matches[index] = Object.create(null);
26847 for (var i = 0; i < len; i++) {
26848 var e = matchedEntries[i];
26851 if (prefix.slice(-1) !== '/') e = prefix + '/' + e;else e = prefix + e;
26854 if (e.charAt(0) === '/' && !this.nomount) {
26855 e = path$2.join(this.root, e);
26858 this._emitMatch(index, e);
26859 } // This was the last one, and no stats were needed
26863 } // now test all matched entries as stand-ins for that part
26869 for (var i = 0; i < len; i++) {
26870 var e = matchedEntries[i];
26872 if (prefix) newPattern = [prefix, e];else newPattern = [e];
26874 this._process(newPattern.concat(remain), index, inGlobStar);
26878 GlobSync.prototype._emitMatch = function (index, e) {
26879 if (isIgnored$1(this, e)) return;
26881 var abs = this._makeAbs(e);
26883 if (this.mark) e = this._mark(e);
26885 if (this.absolute) {
26889 if (this.matches[index][e]) return;
26892 var c = this.cache[abs];
26893 if (c === 'DIR' || Array.isArray(c)) return;
26896 this.matches[index][e] = true;
26897 if (this.stat) this._stat(e);
26900 GlobSync.prototype._readdirInGlobStar = function (abs) {
26901 // follow all symlinked directories forever
26902 // just proceed as if this is a non-globstar situation
26903 if (this.follow) return this._readdir(abs, false);
26908 lstat = fs$1.lstatSync(abs);
26910 if (er.code === 'ENOENT') {
26911 // lstat failed, doesn't exist
26916 var isSym = lstat && lstat.isSymbolicLink();
26917 this.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file.
26918 // don't bother doing a readdir in that case.
26920 if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE';else entries = this._readdir(abs, false);
26924 GlobSync.prototype._readdir = function (abs, inGlobStar) {
26925 if (inGlobStar && !ownProp$1(this.symlinks, abs)) return this._readdirInGlobStar(abs);
26927 if (ownProp$1(this.cache, abs)) {
26928 var c = this.cache[abs];
26929 if (!c || c === 'FILE') return null;
26930 if (Array.isArray(c)) return c;
26934 return this._readdirEntries(abs, fs$1.readdirSync(abs));
26936 this._readdirError(abs, er);
26942 GlobSync.prototype._readdirEntries = function (abs, entries) {
26943 // if we haven't asked to stat everything, then just
26944 // assume that everything in there exists, so we can avoid
26945 // having to stat it a second time.
26946 if (!this.mark && !this.stat) {
26947 for (var i = 0; i < entries.length; i++) {
26948 var e = entries[i];
26949 if (abs === '/') e = abs + e;else e = abs + '/' + e;
26950 this.cache[e] = true;
26954 this.cache[abs] = entries; // mark and cache dir-ness
26959 GlobSync.prototype._readdirError = function (f, er) {
26960 // handle errors, and cache the information
26962 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
26965 // totally normal. means it *does* exist.
26966 var abs = this._makeAbs(f);
26968 this.cache[abs] = 'FILE';
26970 if (abs === this.cwdAbs) {
26971 var error = new Error(er.code + ' invalid cwd ' + this.cwd);
26972 error.path = this.cwd;
26973 error.code = er.code;
26979 case 'ENOENT': // not terribly unusual
26982 case 'ENAMETOOLONG':
26984 this.cache[this._makeAbs(f)] = false;
26988 // some unusual error. Treat as failure.
26989 this.cache[this._makeAbs(f)] = false;
26990 if (this.strict) throw er;
26991 if (!this.silent) console.error('glob error', er);
26996 GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
26997 var entries = this._readdir(abs, inGlobStar); // no entries means not a dir, so it can never have matches
26998 // foo.txt/** doesn't match foo.txt
27001 if (!entries) return; // test without the globstar, and with every child both below
27002 // and replacing the globstar.
27004 var remainWithoutGlobStar = remain.slice(1);
27005 var gspref = prefix ? [prefix] : [];
27006 var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state
27008 this._process(noGlobStar, index, false);
27010 var len = entries.length;
27011 var isSym = this.symlinks[abs]; // If it's a symlink, and we're in a globstar, then stop
27013 if (isSym && inGlobStar) return;
27015 for (var i = 0; i < len; i++) {
27016 var e = entries[i];
27017 if (e.charAt(0) === '.' && !this.dot) continue; // these two cases enter the inGlobStar state
27019 var instead = gspref.concat(entries[i], remainWithoutGlobStar);
27021 this._process(instead, index, true);
27023 var below = gspref.concat(entries[i], remain);
27025 this._process(below, index, true);
27029 GlobSync.prototype._processSimple = function (prefix, index) {
27030 // XXX review this. Shouldn't it be doing the mounting etc
27031 // before doing stat? kinda weird?
27032 var exists = this._stat(prefix);
27034 if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results
27036 if (!exists) return;
27038 if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
27039 var trail = /[\/\\]$/.test(prefix);
27041 if (prefix.charAt(0) === '/') {
27042 prefix = path$2.join(this.root, prefix);
27044 prefix = path$2.resolve(this.root, prefix);
27045 if (trail) prefix += '/';
27049 if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match
27051 this._emitMatch(index, prefix);
27052 }; // Returns either 'DIR', 'FILE', or false
27055 GlobSync.prototype._stat = function (f) {
27056 var abs = this._makeAbs(f);
27058 var needDir = f.slice(-1) === '/';
27059 if (f.length > this.maxLength) return false;
27061 if (!this.stat && ownProp$1(this.cache, abs)) {
27062 var c = this.cache[abs];
27063 if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it
27065 if (!needDir || c === 'DIR') return c;
27066 if (needDir && c === 'FILE') return false; // otherwise we have to stat, because maybe c=true
27067 // if we know it exists, but not what it is.
27069 var stat = this.statCache[abs];
27075 lstat = fs$1.lstatSync(abs);
27077 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
27078 this.statCache[abs] = false;
27083 if (lstat && lstat.isSymbolicLink()) {
27085 stat = fs$1.statSync(abs);
27094 this.statCache[abs] = stat;
27096 if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE';
27097 this.cache[abs] = this.cache[abs] || c;
27098 if (needDir && c === 'FILE') return false;
27102 GlobSync.prototype._mark = function (p) {
27103 return common$2.mark(this, p);
27106 GlobSync.prototype._makeAbs = function (f) {
27107 return common$2.makeAbs(this, f);
27110 // Returns a wrapper function that returns a wrapped callback
27111 // The wrapper function should do some stuff, and return a
27112 // presumably different callback function.
27113 // This makes sure that own properties are retained, so that
27114 // decorations and such are not lost along the way.
27115 var wrappy_1 = wrappy;
27117 function wrappy(fn, cb) {
27118 if (fn && cb) return wrappy(fn)(cb);
27119 if (typeof fn !== 'function') throw new TypeError('need wrapper function');
27120 Object.keys(fn).forEach(function (k) {
27121 wrapper[k] = fn[k];
27125 function wrapper() {
27126 var args = new Array(arguments.length);
27128 for (var i = 0; i < args.length; i++) {
27129 args[i] = arguments[i];
27132 var ret = fn.apply(this, args);
27133 var cb = args[args.length - 1];
27135 if (typeof ret === 'function' && ret !== cb) {
27136 Object.keys(cb).forEach(function (k) {
27145 var once_1 = wrappy_1(once);
27146 var strict = wrappy_1(onceStrict);
27147 once.proto = once(function () {
27148 Object.defineProperty(Function.prototype, 'once', {
27149 value: function value() {
27154 Object.defineProperty(Function.prototype, 'onceStrict', {
27155 value: function value() {
27156 return onceStrict(this);
27162 function once(fn) {
27163 var f = function f() {
27164 if (f.called) return f.value;
27166 return f.value = fn.apply(this, arguments);
27173 function onceStrict(fn) {
27174 var f = function f() {
27175 if (f.called) throw new Error(f.onceError);
27177 return f.value = fn.apply(this, arguments);
27180 var name = fn.name || 'Function wrapped with `once`';
27181 f.onceError = name + " shouldn't be called more than once";
27185 once_1.strict = strict;
27187 var reqs = Object.create(null);
27188 var inflight_1 = wrappy_1(inflight);
27190 function inflight(key, cb) {
27192 reqs[key].push(cb);
27196 return makeres(key);
27200 function makeres(key) {
27201 return once_1(function RES() {
27202 var cbs = reqs[key];
27203 var len = cbs.length;
27204 var args = slice(arguments); // XXX It's somewhat ambiguous whether a new callback added in this
27205 // pass should be queued for later execution if something in the
27206 // list of callbacks throws, or if it should just be discarded.
27207 // However, it's such an edge case that it hardly matters, and either
27208 // choice is likely as surprising as the other.
27209 // As it happens, we do go ahead and schedule it for later execution.
27212 for (var i = 0; i < len; i++) {
27213 cbs[i].apply(null, args);
27216 if (cbs.length > len) {
27217 // added more in the interim.
27218 // de-zalgo, just in case, but don't call again.
27219 cbs.splice(0, len);
27220 process.nextTick(function () {
27221 RES.apply(null, args);
27230 function slice(args) {
27231 var length = args.length;
27234 for (var i = 0; i < length; i++) {
27235 array[i] = args[i];
27242 // 1. Get the minimatch set
27243 // 2. For each pattern in the set, PROCESS(pattern, false)
27244 // 3. Store matches per-set, then uniq them
27246 // PROCESS(pattern, inGlobStar)
27247 // Get the first [n] items from pattern that are all strings
27248 // Join these together. This is PREFIX.
27249 // If there is no more remaining, then stat(PREFIX) and
27250 // add to matches if it succeeds. END.
27252 // If inGlobStar and PREFIX is symlink and points to dir
27253 // set ENTRIES = []
27254 // else readdir(PREFIX) as ENTRIES
27258 // If pattern[n] is GLOBSTAR
27259 // // handle the case where the globstar match is empty
27260 // // by pruning it out, and testing the resulting pattern
27261 // PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
27262 // // handle other cases.
27263 // for ENTRY in ENTRIES (not dotfiles)
27264 // // attach globstar + tail onto the entry
27265 // // Mark that this entry is a globstar match
27266 // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
27268 // else // not globstar
27269 // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
27270 // Test ENTRY against pattern[n]
27271 // If fails, continue
27272 // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
27275 // Cache all stats and readdirs results to minimize syscall. Since all
27276 // we ever care about is existence and directory-ness, we can just keep
27277 // `true` for files, and [children,...] for directories, or `false` for
27278 // things that don't exist.
27281 var EE = events$1.EventEmitter;
27282 var setopts$2 = common$2.setopts;
27283 var ownProp$2 = common$2.ownProp;
27284 var childrenIgnored$2 = common$2.childrenIgnored;
27285 var isIgnored$2 = common$2.isIgnored;
27287 function glob(pattern, options, cb) {
27288 if (typeof options === 'function') cb = options, options = {};
27289 if (!options) options = {};
27291 if (options.sync) {
27292 if (cb) throw new TypeError('callback provided to sync glob');
27293 return sync$1(pattern, options);
27296 return new Glob(pattern, options, cb);
27299 glob.sync = sync$1;
27300 var GlobSync$1 = glob.GlobSync = sync$1.GlobSync; // old api surface
27304 function extend(origin, add) {
27305 if (add === null || typeof add !== 'object') {
27309 var keys = Object.keys(add);
27310 var i = keys.length;
27313 origin[keys[i]] = add[keys[i]];
27319 glob.hasMagic = function (pattern, options_) {
27320 var options = extend({}, options_);
27321 options.noprocess = true;
27322 var g = new Glob(pattern, options);
27323 var set = g.minimatch.set;
27324 if (!pattern) return false;
27325 if (set.length > 1) return true;
27327 for (var j = 0; j < set[0].length; j++) {
27328 if (typeof set[0][j] !== 'string') return true;
27335 inherits(Glob, EE);
27337 function Glob(pattern, options, cb) {
27338 if (typeof options === 'function') {
27343 if (options && options.sync) {
27344 if (cb) throw new TypeError('callback provided to sync glob');
27345 return new GlobSync$1(pattern, options);
27348 if (!(this instanceof Glob)) return new Glob(pattern, options, cb);
27349 setopts$2(this, pattern, options);
27350 this._didRealPath = false; // process each pattern in the minimatch set
27352 var n = this.minimatch.set.length; // The matches are stored as {<filename>: true,...} so that
27353 // duplicates are automagically pruned.
27354 // Later, we do an Object.keys() on these.
27355 // Keep them as a list so we can fill in when nonull is set.
27357 this.matches = new Array(n);
27359 if (typeof cb === 'function') {
27361 this.on('error', cb);
27362 this.on('end', function (matches) {
27368 this._processing = 0;
27369 this._emitQueue = [];
27370 this._processQueue = [];
27371 this.paused = false;
27372 if (this.noprocess) return this;
27373 if (n === 0) return done();
27376 for (var i = 0; i < n; i++) {
27377 this._process(this.minimatch.set[i], i, false, done);
27383 --self._processing;
27385 if (self._processing <= 0) {
27387 process.nextTick(function () {
27397 Glob.prototype._finish = function () {
27398 assert$1(this instanceof Glob);
27399 if (this.aborted) return;
27400 if (this.realpath && !this._didRealpath) return this._realpath();
27401 common$2.finish(this);
27402 this.emit('end', this.found);
27405 Glob.prototype._realpath = function () {
27406 if (this._didRealpath) return;
27407 this._didRealpath = true;
27408 var n = this.matches.length;
27409 if (n === 0) return this._finish();
27412 for (var i = 0; i < this.matches.length; i++) {
27413 this._realpathSet(i, next);
27417 if (--n === 0) self._finish();
27421 Glob.prototype._realpathSet = function (index, cb) {
27422 var matchset = this.matches[index];
27423 if (!matchset) return cb();
27424 var found = Object.keys(matchset);
27426 var n = found.length;
27427 if (n === 0) return cb();
27428 var set = this.matches[index] = Object.create(null);
27429 found.forEach(function (p, i) {
27430 // If there's a problem with the stat, then it means that
27431 // one or more of the links in the realpath couldn't be
27432 // resolved. just return the abs value in that case.
27433 p = self._makeAbs(p);
27434 fs_realpath.realpath(p, self.realpathCache, function (er, real) {
27435 if (!er) set[real] = true;else if (er.syscall === 'stat') set[p] = true;else self.emit('error', er); // srsly wtf right here
27438 self.matches[index] = set;
27445 Glob.prototype._mark = function (p) {
27446 return common$2.mark(this, p);
27449 Glob.prototype._makeAbs = function (f) {
27450 return common$2.makeAbs(this, f);
27453 Glob.prototype.abort = function () {
27454 this.aborted = true;
27455 this.emit('abort');
27458 Glob.prototype.pause = function () {
27459 if (!this.paused) {
27460 this.paused = true;
27461 this.emit('pause');
27465 Glob.prototype.resume = function () {
27467 this.emit('resume');
27468 this.paused = false;
27470 if (this._emitQueue.length) {
27471 var eq = this._emitQueue.slice(0);
27473 this._emitQueue.length = 0;
27475 for (var i = 0; i < eq.length; i++) {
27478 this._emitMatch(e[0], e[1]);
27482 if (this._processQueue.length) {
27483 var pq = this._processQueue.slice(0);
27485 this._processQueue.length = 0;
27487 for (var i = 0; i < pq.length; i++) {
27489 this._processing--;
27491 this._process(p[0], p[1], p[2], p[3]);
27497 Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
27498 assert$1(this instanceof Glob);
27499 assert$1(typeof cb === 'function');
27500 if (this.aborted) return;
27501 this._processing++;
27504 this._processQueue.push([pattern, index, inGlobStar, cb]);
27507 } //console.error('PROCESS %d', this._processing, pattern)
27508 // Get the first [n] parts of pattern that are all strings.
27513 while (typeof pattern[n] === 'string') {
27515 } // now n is the index of the first one that is *not* a string.
27516 // see if there's anything else
27522 // if not, then this is rather simple
27523 case pattern.length:
27524 this._processSimple(pattern.join('/'), index, cb);
27529 // pattern *starts* with some non-trivial item.
27530 // going to readdir(cwd), but not include the prefix in matches.
27535 // pattern has some string bits in the front.
27536 // whatever it starts with, whether that's 'absolute' like /foo/bar,
27537 // or 'relative' like '../baz'
27538 prefix = pattern.slice(0, n).join('/');
27542 var remain = pattern.slice(n); // get the list of entries.
27545 if (prefix === null) read = '.';else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
27546 if (!prefix || !pathIsAbsolute(prefix)) prefix = '/' + prefix;
27548 } else read = prefix;
27550 var abs = this._makeAbs(read); //if ignored, skip _processing
27553 if (childrenIgnored$2(this, read)) return cb();
27554 var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
27555 if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
27558 Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
27561 this._readdir(abs, inGlobStar, function (er, entries) {
27562 return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
27566 Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
27567 // if the abs isn't a dir, then nothing can match!
27568 if (!entries) return cb(); // It will only match dot entries if it starts with a dot, or if
27569 // dot is set. Stuff like @(.foo|.bar) isn't allowed.
27571 var pn = remain[0];
27572 var negate = !!this.minimatch.negate;
27573 var rawGlob = pn._glob;
27574 var dotOk = this.dot || rawGlob.charAt(0) === '.';
27575 var matchedEntries = [];
27577 for (var i = 0; i < entries.length; i++) {
27578 var e = entries[i];
27580 if (e.charAt(0) !== '.' || dotOk) {
27583 if (negate && !prefix) {
27589 if (m) matchedEntries.push(e);
27591 } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
27594 var len = matchedEntries.length; // If there are no matched entries, then nothing matches.
27596 if (len === 0) return cb(); // if this is the last remaining pattern bit, then no need for
27597 // an additional stat *unless* the user has specified mark or
27598 // stat explicitly. We know they exist, since readdir returned
27601 if (remain.length === 1 && !this.mark && !this.stat) {
27602 if (!this.matches[index]) this.matches[index] = Object.create(null);
27604 for (var i = 0; i < len; i++) {
27605 var e = matchedEntries[i];
27608 if (prefix !== '/') e = prefix + '/' + e;else e = prefix + e;
27611 if (e.charAt(0) === '/' && !this.nomount) {
27612 e = path$2.join(this.root, e);
27615 this._emitMatch(index, e);
27616 } // This was the last one, and no stats were needed
27620 } // now test all matched entries as stand-ins for that part
27626 for (var i = 0; i < len; i++) {
27627 var e = matchedEntries[i];
27630 if (prefix !== '/') e = prefix + '/' + e;else e = prefix + e;
27633 this._process([e].concat(remain), index, inGlobStar, cb);
27639 Glob.prototype._emitMatch = function (index, e) {
27640 if (this.aborted) return;
27641 if (isIgnored$2(this, e)) return;
27644 this._emitQueue.push([index, e]);
27649 var abs = pathIsAbsolute(e) ? e : this._makeAbs(e);
27650 if (this.mark) e = this._mark(e);
27651 if (this.absolute) e = abs;
27652 if (this.matches[index][e]) return;
27655 var c = this.cache[abs];
27656 if (c === 'DIR' || Array.isArray(c)) return;
27659 this.matches[index][e] = true;
27660 var st = this.statCache[abs];
27661 if (st) this.emit('stat', e, st);
27662 this.emit('match', e);
27665 Glob.prototype._readdirInGlobStar = function (abs, cb) {
27666 if (this.aborted) return; // follow all symlinked directories forever
27667 // just proceed as if this is a non-globstar situation
27669 if (this.follow) return this._readdir(abs, false, cb);
27670 var lstatkey = 'lstat\0' + abs;
27672 var lstatcb = inflight_1(lstatkey, lstatcb_);
27673 if (lstatcb) fs$1.lstat(abs, lstatcb);
27675 function lstatcb_(er, lstat) {
27676 if (er && er.code === 'ENOENT') return cb();
27677 var isSym = lstat && lstat.isSymbolicLink();
27678 self.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file.
27679 // don't bother doing a readdir in that case.
27681 if (!isSym && lstat && !lstat.isDirectory()) {
27682 self.cache[abs] = 'FILE';
27684 } else self._readdir(abs, false, cb);
27688 Glob.prototype._readdir = function (abs, inGlobStar, cb) {
27689 if (this.aborted) return;
27690 cb = inflight_1('readdir\0' + abs + '\0' + inGlobStar, cb);
27691 if (!cb) return; //console.error('RD %j %j', +inGlobStar, abs)
27693 if (inGlobStar && !ownProp$2(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb);
27695 if (ownProp$2(this.cache, abs)) {
27696 var c = this.cache[abs];
27697 if (!c || c === 'FILE') return cb();
27698 if (Array.isArray(c)) return cb(null, c);
27700 fs$1.readdir(abs, readdirCb(this, abs, cb));
27703 function readdirCb(self, abs, cb) {
27704 return function (er, entries) {
27705 if (er) self._readdirError(abs, er, cb);else self._readdirEntries(abs, entries, cb);
27709 Glob.prototype._readdirEntries = function (abs, entries, cb) {
27710 if (this.aborted) return; // if we haven't asked to stat everything, then just
27711 // assume that everything in there exists, so we can avoid
27712 // having to stat it a second time.
27714 if (!this.mark && !this.stat) {
27715 for (var i = 0; i < entries.length; i++) {
27716 var e = entries[i];
27717 if (abs === '/') e = abs + e;else e = abs + '/' + e;
27718 this.cache[e] = true;
27722 this.cache[abs] = entries;
27723 return cb(null, entries);
27726 Glob.prototype._readdirError = function (f, er, cb) {
27727 if (this.aborted) return; // handle errors, and cache the information
27730 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
27733 // totally normal. means it *does* exist.
27734 var abs = this._makeAbs(f);
27736 this.cache[abs] = 'FILE';
27738 if (abs === this.cwdAbs) {
27739 var error = new Error(er.code + ' invalid cwd ' + this.cwd);
27740 error.path = this.cwd;
27741 error.code = er.code;
27742 this.emit('error', error);
27748 case 'ENOENT': // not terribly unusual
27751 case 'ENAMETOOLONG':
27753 this.cache[this._makeAbs(f)] = false;
27757 // some unusual error. Treat as failure.
27758 this.cache[this._makeAbs(f)] = false;
27761 this.emit('error', er); // If the error is handled, then we abort
27762 // if not, we threw out of here
27767 if (!this.silent) console.error('glob error', er);
27774 Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
27777 this._readdir(abs, inGlobStar, function (er, entries) {
27778 self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
27782 Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
27783 //console.error('pgs2', prefix, remain[0], entries)
27784 // no entries means not a dir, so it can never have matches
27785 // foo.txt/** doesn't match foo.txt
27786 if (!entries) return cb(); // test without the globstar, and with every child both below
27787 // and replacing the globstar.
27789 var remainWithoutGlobStar = remain.slice(1);
27790 var gspref = prefix ? [prefix] : [];
27791 var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state
27793 this._process(noGlobStar, index, false, cb);
27795 var isSym = this.symlinks[abs];
27796 var len = entries.length; // If it's a symlink, and we're in a globstar, then stop
27798 if (isSym && inGlobStar) return cb();
27800 for (var i = 0; i < len; i++) {
27801 var e = entries[i];
27802 if (e.charAt(0) === '.' && !this.dot) continue; // these two cases enter the inGlobStar state
27804 var instead = gspref.concat(entries[i], remainWithoutGlobStar);
27806 this._process(instead, index, true, cb);
27808 var below = gspref.concat(entries[i], remain);
27810 this._process(below, index, true, cb);
27816 Glob.prototype._processSimple = function (prefix, index, cb) {
27817 // XXX review this. Shouldn't it be doing the mounting etc
27818 // before doing stat? kinda weird?
27821 this._stat(prefix, function (er, exists) {
27822 self._processSimple2(prefix, index, er, exists, cb);
27826 Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
27827 //console.error('ps2', prefix, exists)
27828 if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results
27830 if (!exists) return cb();
27832 if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
27833 var trail = /[\/\\]$/.test(prefix);
27835 if (prefix.charAt(0) === '/') {
27836 prefix = path$2.join(this.root, prefix);
27838 prefix = path$2.resolve(this.root, prefix);
27839 if (trail) prefix += '/';
27843 if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match
27845 this._emitMatch(index, prefix);
27848 }; // Returns either 'DIR', 'FILE', or false
27851 Glob.prototype._stat = function (f, cb) {
27852 var abs = this._makeAbs(f);
27854 var needDir = f.slice(-1) === '/';
27855 if (f.length > this.maxLength) return cb();
27857 if (!this.stat && ownProp$2(this.cache, abs)) {
27858 var c = this.cache[abs];
27859 if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it
27861 if (!needDir || c === 'DIR') return cb(null, c);
27862 if (needDir && c === 'FILE') return cb(); // otherwise we have to stat, because maybe c=true
27863 // if we know it exists, but not what it is.
27865 var stat = this.statCache[abs];
27867 if (stat !== undefined) {
27868 if (stat === false) return cb(null, stat);else {
27869 var type = stat.isDirectory() ? 'DIR' : 'FILE';
27870 if (needDir && type === 'FILE') return cb();else return cb(null, type, stat);
27875 var statcb = inflight_1('stat\0' + abs, lstatcb_);
27876 if (statcb) fs$1.lstat(abs, statcb);
27878 function lstatcb_(er, lstat) {
27879 if (lstat && lstat.isSymbolicLink()) {
27880 // If it's a symlink, then treat it as the target, unless
27881 // the target does not exist, then treat it as a file.
27882 return fs$1.stat(abs, function (er, stat) {
27883 if (er) self._stat2(f, abs, null, lstat, cb);else self._stat2(f, abs, er, stat, cb);
27886 self._stat2(f, abs, er, lstat, cb);
27891 Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
27892 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
27893 this.statCache[abs] = false;
27897 var needDir = f.slice(-1) === '/';
27898 this.statCache[abs] = stat;
27899 if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat);
27901 if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE';
27902 this.cache[abs] = this.cache[abs] || c;
27903 if (needDir && c === 'FILE') return cb();
27904 return cb(null, c, stat);
27907 var pify_1 = createCommonjsModule(function (module) {
27909 var processFn = function processFn(fn, P, opts) {
27910 return function () {
27912 var args = new Array(arguments.length);
27914 for (var i = 0; i < arguments.length; i++) {
27915 args[i] = arguments[i];
27918 return new P(function (resolve, reject) {
27919 args.push(function (err, result) {
27922 } else if (opts.multiArgs) {
27923 var results = new Array(arguments.length - 1);
27925 for (var i = 1; i < arguments.length; i++) {
27926 results[i - 1] = arguments[i];
27934 fn.apply(that, args);
27939 var pify = module.exports = function (obj, P, opts) {
27940 if (typeof P !== 'function') {
27946 opts.exclude = opts.exclude || [/.+Sync$/];
27948 var filter = function filter(key) {
27949 var match = function match(pattern) {
27950 return typeof pattern === 'string' ? key === pattern : pattern.test(key);
27953 return opts.include ? opts.include.some(match) : !opts.exclude.some(match);
27956 var ret = typeof obj === 'function' ? function () {
27957 if (opts.excludeMain) {
27958 return obj.apply(this, arguments);
27961 return processFn(obj, P, opts).apply(this, arguments);
27963 return Object.keys(obj).reduce(function (ret, key) {
27965 ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x;
27973 var globP = pify_1(glob_1, pinkiePromise).bind(glob_1);
27975 function isNegative(pattern) {
27976 return pattern[0] === '!';
27979 function isString(value) {
27980 return typeof value === 'string';
27983 function assertPatternsInput(patterns) {
27984 if (!patterns.every(isString)) {
27985 throw new TypeError('patterns must be a string or an array of strings');
27989 function generateGlobTasks(patterns, opts) {
27990 patterns = [].concat(patterns);
27991 assertPatternsInput(patterns);
27992 var globTasks = [];
27993 opts = objectAssign({
27994 cache: Object.create(null),
27995 statCache: Object.create(null),
27996 realpathCache: Object.create(null),
27997 symlinks: Object.create(null),
28000 patterns.forEach(function (pattern, i) {
28001 if (isNegative(pattern)) {
28005 var ignore = patterns.slice(i).filter(isNegative).map(function (pattern) {
28006 return pattern.slice(1);
28010 opts: objectAssign({}, opts, {
28011 ignore: opts.ignore.concat(ignore)
28018 var globby = function globby(patterns, opts) {
28022 globTasks = generateGlobTasks(patterns, opts);
28024 return pinkiePromise.reject(err);
28027 return pinkiePromise.all(globTasks.map(function (task) {
28028 return globP(task.pattern, task.opts);
28029 })).then(function (paths) {
28030 return arrayUnion.apply(null, paths);
28034 var sync$2 = function sync(patterns, opts) {
28035 var globTasks = generateGlobTasks(patterns, opts);
28036 return globTasks.reduce(function (matches, task) {
28037 return arrayUnion(matches, glob_1.sync(task.pattern, task.opts));
28041 var generateGlobTasks_1 = generateGlobTasks;
28043 var hasMagic = function hasMagic(patterns, opts) {
28044 return [].concat(patterns).some(function (pattern) {
28045 return glob_1.hasMagic(pattern, opts);
28048 globby.sync = sync$2;
28049 globby.generateGlobTasks = generateGlobTasks_1;
28050 globby.hasMagic = hasMagic;
28052 var addLeadingComment$2 = utilShared.addLeadingComment,
28053 addTrailingComment$2 = utilShared.addTrailingComment,
28054 addDanglingComment$2 = utilShared.addDanglingComment;
28056 function handleOwnLineComment(comment, text, options, ast, isLastComment) {
28057 var precedingNode = comment.precedingNode,
28058 enclosingNode = comment.enclosingNode,
28059 followingNode = comment.followingNode;
28061 if (handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleMemberExpressionComments(enclosingNode, followingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleImportSpecifierComments(enclosingNode, comment) || handleForComments(enclosingNode, precedingNode, comment) || handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) || handleAssignmentPatternComments(enclosingNode, comment) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options)) {
28068 function handleEndOfLineComment(comment, text, options, ast, isLastComment) {
28069 var precedingNode = comment.precedingNode,
28070 enclosingNode = comment.enclosingNode,
28071 followingNode = comment.followingNode;
28073 if (handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) || handleImportSpecifierComments(enclosingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleLabeledStatementComments(enclosingNode, comment) || handleCallExpressionComments(precedingNode, enclosingNode, comment) || handlePropertyComments(enclosingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleTypeAliasComments(enclosingNode, followingNode, comment) || handleVariableDeclaratorComments(enclosingNode, followingNode, comment)) {
28080 function handleRemainingComment(comment, text, options, ast, isLastComment) {
28081 var precedingNode = comment.precedingNode,
28082 enclosingNode = comment.enclosingNode,
28083 followingNode = comment.followingNode;
28085 if (handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) || handleCommentInEmptyParens(text, enclosingNode, comment, options) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleCommentAfterArrowParams(text, enclosingNode, comment, options) || handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) || handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) || handleBreakAndContinueStatementComments(enclosingNode, comment)) {
28092 function addBlockStatementFirstComment(node, comment) {
28093 var body = node.body.filter(function (n) {
28094 return n.type !== "EmptyStatement";
28097 if (body.length === 0) {
28098 addDanglingComment$2(node, comment);
28100 addLeadingComment$2(body[0], comment);
28104 function addBlockOrNotComment(node, comment) {
28105 if (node.type === "BlockStatement") {
28106 addBlockStatementFirstComment(node, comment);
28108 addLeadingComment$2(node, comment);
28110 } // There are often comments before the else clause of if statements like
28116 // They are being attached as leading comments of the BlockExpression which
28117 // is not well printed. What we want is to instead move the comment inside
28118 // of the block and make it leadingComment of the first element of the block
28119 // or dangling comment of the block if there is nothing inside
28128 function handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
28129 if (!enclosingNode || enclosingNode.type !== "IfStatement" || !followingNode) {
28131 } // We unfortunately have no way using the AST or location of nodes to know
28132 // if the comment is positioned before the condition parenthesis:
28133 // if (a /* comment */) {}
28134 // The only workaround I found is to look at the next character to see if
28138 var nextCharacter = util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd);
28140 if (nextCharacter === ")") {
28141 addTrailingComment$2(precedingNode, comment);
28143 } // Comments before `else`:
28144 // - treat as trailing comments of the consequent, if it's a BlockStatement
28145 // - treat as a dangling comment otherwise
28148 if (precedingNode === enclosingNode.consequent && followingNode === enclosingNode.alternate) {
28149 if (precedingNode.type === "BlockStatement") {
28150 addTrailingComment$2(precedingNode, comment);
28152 addDanglingComment$2(enclosingNode, comment);
28158 if (followingNode.type === "BlockStatement") {
28159 addBlockStatementFirstComment(followingNode, comment);
28163 if (followingNode.type === "IfStatement") {
28164 addBlockOrNotComment(followingNode.consequent, comment);
28166 } // For comments positioned after the condition parenthesis in an if statement
28167 // before the consequent without brackets on, such as
28168 // if (a) /* comment */ true,
28169 // we look at the next character to see if the following node
28170 // is the consequent for the if statement
28173 if (enclosingNode.consequent === followingNode) {
28174 addLeadingComment$2(followingNode, comment);
28181 function handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
28182 if (!enclosingNode || enclosingNode.type !== "WhileStatement" || !followingNode) {
28184 } // We unfortunately have no way using the AST or location of nodes to know
28185 // if the comment is positioned before the condition parenthesis:
28186 // while (a /* comment */) {}
28187 // The only workaround I found is to look at the next character to see if
28191 var nextCharacter = util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd);
28193 if (nextCharacter === ")") {
28194 addTrailingComment$2(precedingNode, comment);
28198 if (followingNode.type === "BlockStatement") {
28199 addBlockStatementFirstComment(followingNode, comment);
28204 } // Same as IfStatement but for TryStatement
28207 function handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) {
28208 if (!enclosingNode || enclosingNode.type !== "TryStatement" && enclosingNode.type !== "CatchClause" || !followingNode) {
28212 if (enclosingNode.type === "CatchClause" && precedingNode) {
28213 addTrailingComment$2(precedingNode, comment);
28217 if (followingNode.type === "BlockStatement") {
28218 addBlockStatementFirstComment(followingNode, comment);
28222 if (followingNode.type === "TryStatement") {
28223 addBlockOrNotComment(followingNode.finalizer, comment);
28227 if (followingNode.type === "CatchClause") {
28228 addBlockOrNotComment(followingNode.body, comment);
28235 function handleMemberExpressionComments(enclosingNode, followingNode, comment) {
28236 if (enclosingNode && (enclosingNode.type === "MemberExpression" || enclosingNode.type === "OptionalMemberExpression") && followingNode && followingNode.type === "Identifier") {
28237 addLeadingComment$2(enclosingNode, comment);
28244 function handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) {
28245 var isSameLineAsPrecedingNode = precedingNode && !util.hasNewlineInRange(text, options.locEnd(precedingNode), options.locStart(comment));
28247 if ((!precedingNode || !isSameLineAsPrecedingNode) && enclosingNode && enclosingNode.type === "ConditionalExpression" && followingNode) {
28248 addLeadingComment$2(followingNode, comment);
28255 function handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) {
28256 if (enclosingNode && (enclosingNode.type === "ObjectProperty" || enclosingNode.type === "Property") && enclosingNode.shorthand && enclosingNode.key === precedingNode && enclosingNode.value.type === "AssignmentPattern") {
28257 addTrailingComment$2(enclosingNode.value.left, comment);
28264 function handleClassComments(enclosingNode, precedingNode, followingNode, comment) {
28265 if (enclosingNode && (enclosingNode.type === "ClassDeclaration" || enclosingNode.type === "ClassExpression") && enclosingNode.decorators && enclosingNode.decorators.length > 0 && !(followingNode && followingNode.type === "Decorator")) {
28266 if (!enclosingNode.decorators || enclosingNode.decorators.length === 0) {
28267 addLeadingComment$2(enclosingNode, comment);
28269 addTrailingComment$2(enclosingNode.decorators[enclosingNode.decorators.length - 1], comment);
28278 function handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) {
28279 // This is only needed for estree parsers (flow, typescript) to attach
28280 // after a method name:
28281 // obj = { fn /*comment*/() {} };
28282 if (enclosingNode && precedingNode && (enclosingNode.type === "Property" || enclosingNode.type === "MethodDefinition") && precedingNode.type === "Identifier" && enclosingNode.key === precedingNode && // special Property case: { key: /*comment*/(value) };
28283 // comment should be attached to value instead of key
28284 util.getNextNonSpaceNonCommentCharacter(text, precedingNode, options.locEnd) !== ":") {
28285 addTrailingComment$2(precedingNode, comment);
28287 } // Print comments between decorators and class methods as a trailing comment
28288 // on the decorator node instead of the method node
28291 if (precedingNode && enclosingNode && precedingNode.type === "Decorator" && (enclosingNode.type === "ClassMethod" || enclosingNode.type === "ClassProperty" || enclosingNode.type === "TSAbstractClassProperty" || enclosingNode.type === "TSAbstractMethodDefinition" || enclosingNode.type === "MethodDefinition")) {
28292 addTrailingComment$2(precedingNode, comment);
28299 function handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) {
28300 if (util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== "(") {
28304 if (precedingNode && enclosingNode && (enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ClassMethod" || enclosingNode.type === "MethodDefinition" || enclosingNode.type === "ObjectMethod")) {
28305 addTrailingComment$2(precedingNode, comment);
28312 function handleCommentAfterArrowParams(text, enclosingNode, comment, options) {
28313 if (!(enclosingNode && enclosingNode.type === "ArrowFunctionExpression")) {
28317 var index = utilShared.getNextNonSpaceNonCommentCharacterIndex(text, comment, options);
28319 if (text.substr(index, 2) === "=>") {
28320 addDanglingComment$2(enclosingNode, comment);
28327 function handleCommentInEmptyParens(text, enclosingNode, comment, options) {
28328 if (util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== ")") {
28330 } // Only add dangling comments to fix the case when no params are present,
28331 // i.e. a function without any argument.
28334 if (enclosingNode && ((enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ArrowFunctionExpression" || enclosingNode.type === "ClassMethod" || enclosingNode.type === "ObjectMethod") && enclosingNode.params.length === 0 || (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression" || enclosingNode.type === "NewExpression") && enclosingNode.arguments.length === 0)) {
28335 addDanglingComment$2(enclosingNode, comment);
28339 if (enclosingNode && enclosingNode.type === "MethodDefinition" && enclosingNode.value.params.length === 0) {
28340 addDanglingComment$2(enclosingNode.value, comment);
28347 function handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
28348 // Type definitions functions
28349 if (precedingNode && precedingNode.type === "FunctionTypeParam" && enclosingNode && enclosingNode.type === "FunctionTypeAnnotation" && followingNode && followingNode.type !== "FunctionTypeParam") {
28350 addTrailingComment$2(precedingNode, comment);
28352 } // Real functions
28355 if (precedingNode && (precedingNode.type === "Identifier" || precedingNode.type === "AssignmentPattern") && enclosingNode && (enclosingNode.type === "ArrowFunctionExpression" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "ObjectMethod" || enclosingNode.type === "ClassMethod") && util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) === ")") {
28356 addTrailingComment$2(precedingNode, comment);
28360 if (enclosingNode && enclosingNode.type === "FunctionDeclaration" && followingNode && followingNode.type === "BlockStatement") {
28361 var functionParamRightParenIndex = function () {
28362 if (enclosingNode.params.length !== 0) {
28363 return util.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(util.getLast(enclosingNode.params)));
28366 var functionParamLeftParenIndex = util.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(enclosingNode.id));
28367 return util.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, functionParamLeftParenIndex + 1);
28370 if (options.locStart(comment) > functionParamRightParenIndex) {
28371 addBlockStatementFirstComment(followingNode, comment);
28379 function handleImportSpecifierComments(enclosingNode, comment) {
28380 if (enclosingNode && enclosingNode.type === "ImportSpecifier") {
28381 addLeadingComment$2(enclosingNode, comment);
28388 function handleLabeledStatementComments(enclosingNode, comment) {
28389 if (enclosingNode && enclosingNode.type === "LabeledStatement") {
28390 addLeadingComment$2(enclosingNode, comment);
28397 function handleBreakAndContinueStatementComments(enclosingNode, comment) {
28398 if (enclosingNode && (enclosingNode.type === "ContinueStatement" || enclosingNode.type === "BreakStatement") && !enclosingNode.label) {
28399 addTrailingComment$2(enclosingNode, comment);
28406 function handleCallExpressionComments(precedingNode, enclosingNode, comment) {
28407 if (enclosingNode && (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression") && precedingNode && enclosingNode.callee === precedingNode && enclosingNode.arguments.length > 0) {
28408 addLeadingComment$2(enclosingNode.arguments[0], comment);
28415 function handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) {
28416 if (enclosingNode && (enclosingNode.type === "UnionTypeAnnotation" || enclosingNode.type === "TSUnionType")) {
28417 addTrailingComment$2(precedingNode, comment);
28424 function handlePropertyComments(enclosingNode, comment) {
28425 if (enclosingNode && (enclosingNode.type === "Property" || enclosingNode.type === "ObjectProperty")) {
28426 addLeadingComment$2(enclosingNode, comment);
28433 function handleOnlyComments(enclosingNode, ast, comment, isLastComment) {
28434 // With Flow the enclosingNode is undefined so use the AST instead.
28435 if (ast && ast.body && ast.body.length === 0) {
28436 if (isLastComment) {
28437 addDanglingComment$2(ast, comment);
28439 addLeadingComment$2(ast, comment);
28443 } else if (enclosingNode && enclosingNode.type === "Program" && enclosingNode.body.length === 0 && enclosingNode.directives && enclosingNode.directives.length === 0) {
28444 if (isLastComment) {
28445 addDanglingComment$2(enclosingNode, comment);
28447 addLeadingComment$2(enclosingNode, comment);
28456 function handleForComments(enclosingNode, precedingNode, comment) {
28457 if (enclosingNode && (enclosingNode.type === "ForInStatement" || enclosingNode.type === "ForOfStatement")) {
28458 addLeadingComment$2(enclosingNode, comment);
28465 function handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) {
28466 if (precedingNode && precedingNode.type === "ImportSpecifier" && enclosingNode && enclosingNode.type === "ImportDeclaration" && util.hasNewline(text, options.locEnd(comment))) {
28467 addTrailingComment$2(precedingNode, comment);
28474 function handleAssignmentPatternComments(enclosingNode, comment) {
28475 if (enclosingNode && enclosingNode.type === "AssignmentPattern") {
28476 addLeadingComment$2(enclosingNode, comment);
28483 function handleTypeAliasComments(enclosingNode, followingNode, comment) {
28484 if (enclosingNode && enclosingNode.type === "TypeAlias") {
28485 addLeadingComment$2(enclosingNode, comment);
28492 function handleVariableDeclaratorComments(enclosingNode, followingNode, comment) {
28493 if (enclosingNode && (enclosingNode.type === "VariableDeclarator" || enclosingNode.type === "AssignmentExpression") && followingNode && (followingNode.type === "ObjectExpression" || followingNode.type === "ArrayExpression" || followingNode.type === "TemplateLiteral" || followingNode.type === "TaggedTemplateExpression")) {
28494 addLeadingComment$2(followingNode, comment);
28501 function handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) {
28502 if (!enclosingNode || enclosingNode.type !== "TSMappedType") {
28506 if (followingNode && followingNode.type === "TSTypeParameter" && followingNode.name) {
28507 addLeadingComment$2(followingNode.name, comment);
28511 if (precedingNode && precedingNode.type === "TSTypeParameter" && precedingNode.constraint) {
28512 addTrailingComment$2(precedingNode.constraint, comment);
28519 function isBlockComment(comment) {
28520 return comment.type === "Block" || comment.type === "CommentBlock";
28523 function hasLeadingComment(node) {
28524 var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {
28528 if (node.leadingComments) {
28529 return node.leadingComments.some(fn);
28532 if (node.comments) {
28533 return node.comments.some(function (comment) {
28534 return comment.leading && fn(comment);
28542 handleOwnLineComment,
28543 handleEndOfLineComment,
28544 handleRemainingComment,
28549 var isBlockComment$1 = comments$1.isBlockComment,
28550 hasLeadingComment$1 = comments$1.hasLeadingComment;
28551 var _require$$1$builders = doc.builders,
28552 indent$2 = _require$$1$builders.indent,
28553 join$2 = _require$$1$builders.join,
28554 hardline$3 = _require$$1$builders.hardline,
28555 softline$1 = _require$$1$builders.softline,
28556 literalline$1 = _require$$1$builders.literalline,
28557 concat$4 = _require$$1$builders.concat,
28558 group$1 = _require$$1$builders.group,
28559 dedentToRoot$1 = _require$$1$builders.dedentToRoot,
28560 _require$$1$utils = doc.utils,
28561 mapDoc$3 = _require$$1$utils.mapDoc,
28562 stripTrailingHardline$1 = _require$$1$utils.stripTrailingHardline;
28564 function embed(path, print, textToDoc, options) {
28565 var node = path.getValue();
28566 var parent = path.getParentNode();
28567 var parentParent = path.getParentNode(1);
28569 switch (node.type) {
28570 case "TemplateLiteral":
28572 var isCss = [isStyledJsx, isStyledComponents, isCssProp, isAngularComponentStyles].some(function (isIt) {
28577 // Get full template literal with expressions replaced by placeholders
28578 var rawQuasis = node.quasis.map(function (q) {
28579 return q.value.raw;
28581 var placeholderID = 0;
28582 var text = rawQuasis.reduce(function (prevVal, currVal, idx) {
28583 return idx == 0 ? currVal : prevVal + "@prettier-placeholder-" + placeholderID++ + "-id" + currVal;
28585 var doc = textToDoc(text, {
28588 return transformCssDoc(doc, path, print);
28591 * react-relay and graphql-tag
28593 * graphql.experimental`...`
28596 * This intentionally excludes Relay Classic tags, as Prettier does not
28597 * support Relay Classic formatting.
28601 if (isGraphQL(path)) {
28602 var expressionDocs = node.expressions ? path.map(print, "expressions") : [];
28603 var numQuasis = node.quasis.length;
28605 if (numQuasis === 1 && node.quasis[0].value.raw.trim() === "") {
28611 for (var i = 0; i < numQuasis; i++) {
28612 var templateElement = node.quasis[i];
28613 var isFirst = i === 0;
28614 var isLast = i === numQuasis - 1;
28615 var _text = templateElement.value.cooked; // Bail out if any of the quasis have an invalid escape sequence
28616 // (which would make the `cooked` value be `null` or `undefined`)
28618 if (typeof _text !== "string") {
28622 var lines = _text.split("\n");
28624 var numLines = lines.length;
28625 var expressionDoc = expressionDocs[i];
28626 var startsWithBlankLine = numLines > 2 && lines[0].trim() === "" && lines[1].trim() === "";
28627 var endsWithBlankLine = numLines > 2 && lines[numLines - 1].trim() === "" && lines[numLines - 2].trim() === "";
28628 var commentsAndWhitespaceOnly = lines.every(function (line) {
28629 return /^\s*(?:#[^\r\n]*)?$/.test(line);
28630 }); // Bail out if an interpolation occurs within a comment.
28632 if (!isLast && /#[^\r\n]*$/.test(lines[numLines - 1])) {
28638 if (commentsAndWhitespaceOnly) {
28639 _doc = printGraphqlComments(lines);
28641 _doc = stripTrailingHardline$1(textToDoc(_text, {
28647 _doc = escapeTemplateCharacters(_doc, false);
28649 if (!isFirst && startsWithBlankLine) {
28655 if (!isLast && endsWithBlankLine) {
28658 } else if (!isFirst && !isLast && startsWithBlankLine) {
28662 if (expressionDoc) {
28663 parts.push(concat$4(["${", expressionDoc, "}"]));
28667 return concat$4(["`", indent$2(concat$4([hardline$3, join$2(hardline$3, parts)])), hardline$3, "`"]);
28670 var htmlParser = isHtml(path) ? "html" : isAngularComponentTemplate(path) ? "angular" : undefined;
28673 return printHtmlTemplateLiteral(path, print, textToDoc, htmlParser, options.embeddedInHtml);
28679 case "TemplateElement":
28685 if (parentParent && parentParent.type === "TaggedTemplateExpression" && parent.quasis.length === 1 && parentParent.tag.type === "Identifier" && (parentParent.tag.name === "md" || parentParent.tag.name === "markdown")) {
28686 var _text2 = parent.quasis[0].value.raw.replace(/((?:\\\\)*)\\`/g, function (_, backslashes) {
28687 return "\\".repeat(backslashes.length / 2) + "`";
28690 var indentation = getIndentation(_text2);
28691 var hasIndent = indentation !== "";
28692 return concat$4([hasIndent ? indent$2(concat$4([softline$1, printMarkdown(_text2.replace(new RegExp(`^${indentation}`, "gm"), ""))])) : concat$4([literalline$1, dedentToRoot$1(printMarkdown(_text2))]), softline$1]);
28699 function printMarkdown(text) {
28700 var doc = textToDoc(text, {
28701 parser: "markdown",
28702 __inJsTemplate: true
28704 return stripTrailingHardline$1(escapeTemplateCharacters(doc, true));
28708 function getIndentation(str) {
28709 var firstMatchedIndent = str.match(/^([^\S\n]*)\S/m);
28710 return firstMatchedIndent === null ? "" : firstMatchedIndent[1];
28713 function uncook(cookedValue) {
28714 return cookedValue.replace(/([\\`]|\$\{)/g, "\\$1");
28717 function escapeTemplateCharacters(doc, raw) {
28718 return mapDoc$3(doc, function (currentDoc) {
28719 if (!currentDoc.parts) {
28724 currentDoc.parts.forEach(function (part) {
28725 if (typeof part === "string") {
28726 parts.push(raw ? part.replace(/(\\*)`/g, "$1$1\\`") : uncook(part));
28731 return Object.assign({}, currentDoc, {
28737 function transformCssDoc(quasisDoc, path, print) {
28738 var parentNode = path.getValue();
28739 var isEmpty = parentNode.quasis.length === 1 && !parentNode.quasis[0].value.raw.trim();
28745 var expressionDocs = parentNode.expressions ? path.map(print, "expressions") : [];
28746 var newDoc = replacePlaceholders(quasisDoc, expressionDocs);
28747 /* istanbul ignore if */
28750 throw new Error("Couldn't insert all the expressions");
28753 return concat$4(["`", indent$2(concat$4([hardline$3, stripTrailingHardline$1(newDoc)])), softline$1, "`"]);
28754 } // Search all the placeholders in the quasisDoc tree
28755 // and replace them with the expression docs one by one
28756 // returns a new doc with all the placeholders replaced,
28757 // or null if it couldn't replace any expression
28760 function replacePlaceholders(quasisDoc, expressionDocs) {
28761 if (!expressionDocs || !expressionDocs.length) {
28765 var expressions = expressionDocs.slice();
28766 var replaceCounter = 0;
28767 var newDoc = mapDoc$3(quasisDoc, function (doc) {
28768 if (!doc || !doc.parts || !doc.parts.length) {
28772 var parts = doc.parts;
28773 var atIndex = parts.indexOf("@");
28774 var placeholderIndex = atIndex + 1;
28776 if (atIndex > -1 && typeof parts[placeholderIndex] === "string" && parts[placeholderIndex].startsWith("prettier-placeholder")) {
28777 // If placeholder is split, join it
28778 var at = parts[atIndex];
28779 var placeholder = parts[placeholderIndex];
28780 var rest = parts.slice(placeholderIndex + 1);
28781 parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest);
28784 var atPlaceholderIndex = parts.findIndex(function (part) {
28785 return typeof part === "string" && part.startsWith("@prettier-placeholder");
28788 if (atPlaceholderIndex > -1) {
28789 var _placeholder = parts[atPlaceholderIndex];
28791 var _rest = parts.slice(atPlaceholderIndex + 1);
28793 var placeholderMatch = _placeholder.match(/@prettier-placeholder-(.+)-id([\s\S]*)/);
28795 var placeholderID = placeholderMatch[1]; // When the expression has a suffix appended, like:
28796 // animation: linear ${time}s ease-out;
28798 var suffix = placeholderMatch[2];
28799 var expression = expressions[placeholderID];
28801 parts = parts.slice(0, atPlaceholderIndex).concat(["${", expression, "}" + suffix]).concat(_rest);
28804 return Object.assign({}, doc, {
28808 return expressions.length === replaceCounter ? newDoc : null;
28811 function printGraphqlComments(lines) {
28813 var seenComment = false;
28814 lines.map(function (textLine) {
28815 return textLine.trim();
28816 }).forEach(function (textLine, i, array) {
28817 // Lines are either whitespace only, or a comment (with potential whitespace
28818 // around it). Drop whitespace-only lines.
28819 if (textLine === "") {
28823 if (array[i - 1] === "" && seenComment) {
28824 // If a non-first comment is preceded by a blank (whitespace only) line,
28825 // add in a blank line.
28826 parts.push(concat$4([hardline$3, textLine]));
28828 parts.push(textLine);
28831 seenComment = true;
28832 }); // If `lines` was whitespace only, return `null`.
28834 return parts.length === 0 ? null : join$2(hardline$3, parts);
28837 * Template literal in these contexts:
28838 * <style jsx>{`div{color:red}`}</style>
28845 function isStyledJsx(path) {
28846 var node = path.getValue();
28847 var parent = path.getParentNode();
28848 var parentParent = path.getParentNode(1);
28849 return parentParent && node.quasis && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXElement" && parentParent.openingElement.name.name === "style" && parentParent.openingElement.attributes.some(function (attribute) {
28850 return attribute.name.name === "jsx";
28851 }) || 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");
28854 * Angular Components can have:
28855 * - Inline HTML template
28856 * - Inline CSS styles
28858 * ...which are both within template literals somewhere
28859 * inside of the Component decorator factory.
28863 * template: `<div>...</div>`,
28864 * styles: [`h1 { color: blue; }`]
28869 function isAngularComponentStyles(path) {
28870 return isPathMatch(path, [function (node) {
28871 return node.type === "TemplateLiteral";
28872 }, function (node, name) {
28873 return node.type === "ArrayExpression" && name === "elements";
28874 }, function (node, name) {
28875 return node.type === "Property" && node.key.type === "Identifier" && node.key.name === "styles" && name === "value";
28876 }].concat(getAngularComponentObjectExpressionPredicates()));
28879 function isAngularComponentTemplate(path) {
28880 return isPathMatch(path, [function (node) {
28881 return node.type === "TemplateLiteral";
28882 }, function (node, name) {
28883 return node.type === "Property" && node.key.type === "Identifier" && node.key.name === "template" && name === "value";
28884 }].concat(getAngularComponentObjectExpressionPredicates()));
28887 function getAngularComponentObjectExpressionPredicates() {
28888 return [function (node, name) {
28889 return node.type === "ObjectExpression" && name === "properties";
28890 }, function (node, name) {
28891 return node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "Component" && name === "arguments";
28892 }, function (node, name) {
28893 return node.type === "Decorator" && name === "expression";
28897 * styled-components template literals
28901 function isStyledComponents(path) {
28902 var parent = path.getParentNode();
28904 if (!parent || parent.type !== "TaggedTemplateExpression") {
28908 var tag = parent.tag;
28910 switch (tag.type) {
28911 case "MemberExpression":
28912 return (// styled.foo``
28913 isStyledIdentifier(tag.object) || // Component.extend``
28914 isStyledExtend(tag)
28917 case "CallExpression":
28918 return (// styled(Component)``
28919 isStyledIdentifier(tag.callee) || tag.callee.type === "MemberExpression" && (tag.callee.object.type === "MemberExpression" && ( // styled.foo.attrs({})``
28920 isStyledIdentifier(tag.callee.object.object) || // Component.extend.attrs({})``
28921 isStyledExtend(tag.callee.object)) || // styled(Component).attrs({})``
28922 tag.callee.object.type === "CallExpression" && isStyledIdentifier(tag.callee.object.callee))
28927 return tag.name === "css";
28934 * JSX element with CSS prop
28938 function isCssProp(path) {
28939 var parent = path.getParentNode();
28940 var parentParent = path.getParentNode(1);
28941 return parentParent && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" && parentParent.name.type === "JSXIdentifier" && parentParent.name.name === "css";
28944 function isStyledIdentifier(node) {
28945 return node.type === "Identifier" && node.name === "styled";
28948 function isStyledExtend(node) {
28949 return /^[A-Z]/.test(node.object.name) && node.property.name === "extend";
28952 * react-relay and graphql-tag
28954 * graphql.experimental`...`
28956 * GraphQL comment block
28958 * This intentionally excludes Relay Classic tags, as Prettier does not
28959 * support Relay Classic formatting.
28963 function isGraphQL(path) {
28964 var node = path.getValue();
28965 var parent = path.getParentNode();
28966 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");
28969 function hasLanguageComment(node, languageName) {
28970 // This checks for a leading comment that is exactly `/* GraphQL */`
28971 // In order to be in line with other implementations of this comment tag
28972 // we will not trim the comment value and we will expect exactly one space on
28973 // either side of the GraphQL string
28974 // Also see ./clean.js
28975 return hasLeadingComment$1(node, function (comment) {
28976 return isBlockComment$1(comment) && comment.value === ` ${languageName} `;
28980 function isPathMatch(path, predicateStack) {
28981 var stack = path.stack.slice();
28983 var node = stack.pop();
28984 var _iteratorNormalCompletion = true;
28985 var _didIteratorError = false;
28986 var _iteratorError = undefined;
28989 for (var _iterator = predicateStack[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
28990 var predicate = _step.value;
28992 if (node === undefined) {
28994 } // skip index/array
28997 if (typeof name === "number") {
28998 name = stack.pop();
28999 node = stack.pop();
29002 if (!predicate(node, name)) {
29006 name = stack.pop();
29007 node = stack.pop();
29010 _didIteratorError = true;
29011 _iteratorError = err;
29014 if (!_iteratorNormalCompletion && _iterator.return != null) {
29015 _iterator.return();
29018 if (_didIteratorError) {
29019 throw _iteratorError;
29028 * - HTML comment block
29032 function isHtml(path) {
29033 var node = path.getValue();
29034 return hasLanguageComment(node, "HTML") || isPathMatch(path, [function (node) {
29035 return node.type === "TemplateLiteral";
29036 }, function (node, name) {
29037 return node.type === "TaggedTemplateExpression" && node.tag.type === "Identifier" && node.tag.name === "html" && name === "quasi";
29039 } // The counter is needed to distinguish nested embeds.
29042 var htmlTemplateLiteralCounter = 0;
29044 function printHtmlTemplateLiteral(path, print, textToDoc, parser, escapeClosingScriptTag) {
29045 var node = path.getValue();
29046 var counter = htmlTemplateLiteralCounter;
29047 htmlTemplateLiteralCounter = htmlTemplateLiteralCounter + 1 >>> 0;
29049 var composePlaceholder = function composePlaceholder(index) {
29050 return `PRETTIER_HTML_PLACEHOLDER_${index}_${counter}_IN_JS`;
29053 var text = node.quasis.map(function (quasi, index, quasis) {
29054 return index === quasis.length - 1 ? quasi.value.cooked : quasi.value.cooked + composePlaceholder(index);
29056 var expressionDocs = path.map(print, "expressions");
29058 if (expressionDocs.length === 0 && text.trim().length === 0) {
29062 var placeholderRegex = RegExp(composePlaceholder("(\\d+)"), "g");
29063 var contentDoc = mapDoc$3(stripTrailingHardline$1(textToDoc(text, {
29065 })), function (doc) {
29066 if (typeof doc !== "string") {
29071 var components = doc.split(placeholderRegex);
29073 for (var i = 0; i < components.length; i++) {
29074 var component = components[i];
29078 component = uncook(component);
29080 if (escapeClosingScriptTag) {
29081 component = component.replace(/<\/(script)\b/gi, "<\\/$1");
29084 parts.push(component);
29090 var placeholderIndex = +component;
29091 parts.push(concat$4(["${", group$1(expressionDocs[placeholderIndex]), "}"]));
29094 return concat$4(parts);
29096 return group$1(concat$4(["`", indent$2(concat$4([hardline$3, group$1(contentDoc)])), softline$1, "`"]));
29099 var embed_1 = embed;
29101 function clean(ast, newObj, parent) {
29102 ["range", "raw", "comments", "leadingComments", "trailingComments", "extra", "start", "end", "flags", "errors"].forEach(function (name) {
29103 delete newObj[name];
29106 if (ast.type === "BigIntLiteral") {
29107 newObj.value = newObj.value.toLowerCase();
29108 } // We remove extra `;` and add them when needed
29111 if (ast.type === "EmptyStatement") {
29113 } // We move text around, including whitespaces and add {" "}
29116 if (ast.type === "JSXText") {
29120 if (ast.type === "JSXExpressionContainer" && ast.expression.type === "Literal" && ast.expression.value === " ") {
29122 } // We remove unneeded parens around same-operator LogicalExpressions
29125 if (isUnbalancedLogicalTree(newObj)) {
29126 return rebalanceLogicalTree(newObj);
29127 } // (TypeScript) Ignore `static` in `constructor(static p) {}`
29128 // and `export` in `constructor(export p) {}`
29131 if (ast.type === "TSParameterProperty" && ast.accessibility === null && !ast.readonly) {
29133 type: "Identifier",
29134 name: ast.parameter.name,
29135 typeAnnotation: newObj.parameter.typeAnnotation,
29136 decorators: newObj.decorators
29138 } // (TypeScript) ignore empty `specifiers` array
29141 if (ast.type === "TSNamespaceExportDeclaration" && ast.specifiers && ast.specifiers.length === 0) {
29142 delete newObj.specifiers;
29143 } // We convert <div></div> to <div />
29146 if (ast.type === "JSXOpeningElement") {
29147 delete newObj.selfClosing;
29150 if (ast.type === "JSXElement") {
29151 delete newObj.closingElement;
29152 } // We change {'key': value} into {key: value}
29155 if ((ast.type === "Property" || ast.type === "ObjectProperty" || ast.type === "MethodDefinition" || ast.type === "ClassProperty" || ast.type === "TSPropertySignature" || ast.type === "ObjectTypeProperty") && typeof ast.key === "object" && ast.key && (ast.key.type === "Literal" || ast.key.type === "StringLiteral" || ast.key.type === "Identifier")) {
29159 if (ast.type === "OptionalMemberExpression" && ast.optional === false) {
29160 newObj.type = "MemberExpression";
29161 delete newObj.optional;
29162 } // Remove raw and cooked values from TemplateElement when it's CSS
29166 if (ast.type === "JSXElement" && ast.openingElement.name.name === "style" && ast.openingElement.attributes.some(function (attr) {
29167 return attr.name.name === "jsx";
29169 var templateLiterals = newObj.children.filter(function (child) {
29170 return child.type === "JSXExpressionContainer" && child.expression.type === "TemplateLiteral";
29171 }).map(function (container) {
29172 return container.expression;
29174 var quasis = templateLiterals.reduce(function (quasis, templateLiteral) {
29175 return quasis.concat(templateLiteral.quasis);
29177 quasis.forEach(function (q) {
29178 return delete q.value;
29180 } // CSS template literals in css prop
29183 if (ast.type === "JSXAttribute" && ast.name.name === "css" && ast.value.type === "JSXExpressionContainer" && ast.value.expression.type === "TemplateLiteral") {
29184 newObj.value.expression.quasis.forEach(function (q) {
29185 return delete q.value;
29187 } // Angular Components: Inline HTML template and Inline CSS styles
29190 var expression = ast.expression || ast.callee;
29192 if (ast.type === "Decorator" && expression.type === "CallExpression" && expression.callee.name === "Component" && expression.arguments.length === 1) {
29193 var astProps = ast.expression.arguments[0].properties;
29194 newObj.expression.arguments[0].properties.forEach(function (prop, index) {
29195 var templateLiteral = null;
29197 switch (astProps[index].key.name) {
29199 if (prop.value.type === "ArrayExpression") {
29200 templateLiteral = prop.value.elements[0];
29206 if (prop.value.type === "TemplateLiteral") {
29207 templateLiteral = prop.value;
29213 if (templateLiteral) {
29214 templateLiteral.quasis.forEach(function (q) {
29215 return delete q.value;
29219 } // styled-components, graphql, markdown
29222 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")) {
29223 newObj.quasi.quasis.forEach(function (quasi) {
29224 return delete quasi.value;
29228 if (ast.type === "TemplateLiteral") {
29229 // This checks for a leading comment that is exactly `/* GraphQL */`
29230 // In order to be in line with other implementations of this comment tag
29231 // we will not trim the comment value and we will expect exactly one space on
29232 // either side of the GraphQL string
29233 // Also see ./embed.js
29234 var hasLanguageComment = ast.leadingComments && ast.leadingComments.some(function (comment) {
29235 return comment.type === "CommentBlock" && ["GraphQL", "HTML"].some(function (languageName) {
29236 return comment.value === ` ${languageName} `;
29240 if (hasLanguageComment || parent.type === "CallExpression" && parent.callee.name === "graphql") {
29241 newObj.quasis.forEach(function (quasi) {
29242 return delete quasi.value;
29248 function isUnbalancedLogicalTree(newObj) {
29249 return newObj.type === "LogicalExpression" && newObj.right.type === "LogicalExpression" && newObj.operator === newObj.right.operator;
29252 function rebalanceLogicalTree(newObj) {
29253 if (isUnbalancedLogicalTree(newObj)) {
29254 return rebalanceLogicalTree({
29255 type: "LogicalExpression",
29256 operator: newObj.operator,
29257 left: rebalanceLogicalTree({
29258 type: "LogicalExpression",
29259 operator: newObj.operator,
29261 right: newObj.right.left,
29264 right: newObj.right.right,
29272 var clean_1 = clean;
29274 var detectNewline = createCommonjsModule(function (module) {
29276 module.exports = function (str) {
29277 if (typeof str !== 'string') {
29278 throw new TypeError('Expected a string');
29281 var newlines = str.match(/(?:\r?\n)/g) || [];
29283 if (newlines.length === 0) {
29287 var crlf = newlines.filter(function (el) {
29288 return el === '\r\n';
29290 var lf = newlines.length - crlf;
29291 return crlf > lf ? '\r\n' : '\n';
29294 module.exports.graceful = function (str) {
29295 return module.exports(str) || '\n';
29298 var detectNewline_1 = detectNewline.graceful;
29300 var build = createCommonjsModule(function (module, exports) {
29302 Object.defineProperty(exports, '__esModule', {
29305 exports.extract = extract;
29306 exports.strip = strip;
29307 exports.parse = parse;
29308 exports.parseWithComments = parseWithComments;
29309 exports.print = print;
29314 _os = function _os() {
29321 function _detectNewline() {
29322 var data = _interopRequireDefault(detectNewline);
29324 _detectNewline = function _detectNewline() {
29331 function _interopRequireDefault(obj) {
29332 return obj && obj.__esModule ? obj : {
29337 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
29339 * This source code is licensed under the MIT license found in the
29340 * LICENSE file in the root directory of this source tree.
29344 var commentEndRe = /\*\/$/;
29345 var commentStartRe = /^\/\*\*/;
29346 var docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/;
29347 var lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g;
29348 var ltrimNewlineRe = /^(\r?\n)+/;
29349 var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
29350 var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
29351 var stringStartRe = /(\r?\n|^) *\* ?/g;
29353 function extract(contents) {
29354 var match = contents.match(docblockRe);
29355 return match ? match[0].trimLeft() : '';
29358 function strip(contents) {
29359 var match = contents.match(docblockRe);
29360 return match && match[0] ? contents.substring(match[0].length) : contents;
29363 function parse(docblock) {
29364 return parseWithComments(docblock).pragmas;
29367 function parseWithComments(docblock) {
29368 var line = (0, _detectNewline().default)(docblock) || _os().EOL;
29370 docblock = docblock.replace(commentStartRe, '').replace(commentEndRe, '').replace(stringStartRe, '$1'); // Normalize multi-line directives
29374 while (prev !== docblock) {
29376 docblock = docblock.replace(multilineRe, `${line}$1 $2${line}`);
29379 docblock = docblock.replace(ltrimNewlineRe, '').trimRight();
29380 var result = Object.create(null);
29381 var comments = docblock.replace(propertyRe, '').replace(ltrimNewlineRe, '').trimRight();
29384 while (match = propertyRe.exec(docblock)) {
29385 // strip linecomments from pragmas
29386 var nextPragma = match[2].replace(lineCommentRe, '');
29388 if (typeof result[match[1]] === 'string' || Array.isArray(result[match[1]])) {
29389 result[match[1]] = [].concat(result[match[1]], nextPragma);
29391 result[match[1]] = nextPragma;
29401 function print(_ref) {
29402 var _ref$comments = _ref.comments,
29403 comments = _ref$comments === void 0 ? '' : _ref$comments,
29404 _ref$pragmas = _ref.pragmas,
29405 pragmas = _ref$pragmas === void 0 ? {} : _ref$pragmas;
29407 var line = (0, _detectNewline().default)(comments) || _os().EOL;
29412 var keys = Object.keys(pragmas);
29413 var printedObject = keys.map(function (key) {
29414 return printKeyValues(key, pragmas[key]);
29415 }).reduce(function (arr, next) {
29416 return arr.concat(next);
29417 }, []).map(function (keyValue) {
29418 return start + ' ' + keyValue + line;
29422 if (keys.length === 0) {
29426 if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) {
29427 var value = pragmas[keys[0]];
29428 return `${head} ${printKeyValues(keys[0], value)[0]}${tail}`;
29432 var printedComments = comments.split(line).map(function (textLine) {
29433 return `${start} ${textLine}`;
29434 }).join(line) + line;
29435 return head + line + (comments ? printedComments : '') + (comments && keys.length ? start + line : '') + printedObject + tail;
29438 function printKeyValues(key, valueOrArray) {
29439 return [].concat(valueOrArray).map(function (value) {
29440 return `@${key} ${value}`.trim();
29444 unwrapExports(build);
29445 var build_1 = build.extract;
29446 var build_2 = build.strip;
29447 var build_3 = build.parse;
29448 var build_4 = build.parseWithComments;
29449 var build_5 = build.print;
29451 function hasPragma(text) {
29452 var pragmas = Object.keys(build.parse(build.extract(text)));
29453 return pragmas.indexOf("prettier") !== -1 || pragmas.indexOf("format") !== -1;
29456 function insertPragma(text) {
29457 var parsedDocblock = build.parseWithComments(build.extract(text));
29458 var pragmas = Object.assign({
29460 }, parsedDocblock.pragmas);
29461 var newDocblock = build.print({
29463 comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines
29465 }).replace(/(\r\n|\r)/g, "\n"); // normalise newlines (mitigate use of os.EOL by jest-docblock)
29467 var strippedText = build.strip(text);
29468 var separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n";
29469 return newDocblock + separatingNewlines + strippedText;
29477 var getLast$1 = util.getLast,
29478 hasNewline$2 = util.hasNewline,
29479 hasNewlineInRange$1 = util.hasNewlineInRange,
29480 hasIgnoreComment$1 = util.hasIgnoreComment,
29481 hasNodeIgnoreComment$1 = util.hasNodeIgnoreComment,
29482 skipWhitespace$1 = util.skipWhitespace;
29483 var isIdentifierName = utils$1.keyword.isIdentifierNameES5; // We match any whitespace except line terminators because
29484 // Flow annotation comments cannot be split across lines. For example:
29487 // : any */).foo = 5;
29489 // is not picked up by Flow (see https://github.com/facebook/flow/issues/7050), so
29490 // removing the newline would create a type annotation that the user did not intend
29493 var NON_LINE_TERMINATING_WHITE_SPACE = "(?:(?=.)\\s)";
29494 var FLOW_SHORTHAND_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*:`);
29495 var FLOW_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*::`);
29497 function hasFlowShorthandAnnotationComment(node) {
29498 // https://flow.org/en/docs/types/comments/
29499 // Syntax example: const r = new (window.Request /*: Class<Request> */)("");
29500 return node.extra && node.extra.parenthesized && node.trailingComments && node.trailingComments[0].value.match(FLOW_SHORTHAND_ANNOTATION);
29503 function hasFlowAnnotationComment(comments) {
29504 return comments && comments[0].value.match(FLOW_ANNOTATION);
29507 function hasNode(node, fn) {
29508 if (!node || typeof node !== "object") {
29512 if (Array.isArray(node)) {
29513 return node.some(function (value) {
29514 return hasNode(value, fn);
29518 var result = fn(node);
29519 return typeof result === "boolean" ? result : Object.keys(node).some(function (key) {
29520 return hasNode(node[key], fn);
29524 function hasNakedLeftSide(node) {
29525 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";
29528 function getLeftSide(node) {
29529 if (node.expressions) {
29530 return node.expressions[0];
29533 return node.left || node.test || node.callee || node.object || node.tag || node.argument || node.expression;
29536 function getLeftSidePathName(path, node) {
29537 if (node.expressions) {
29538 return ["expressions", 0];
29561 if (node.argument) {
29562 return ["argument"];
29565 if (node.expression) {
29566 return ["expression"];
29569 throw new Error("Unexpected node has no left side", node);
29572 function isLiteral(node) {
29573 return node.type === "BooleanLiteral" || node.type === "DirectiveLiteral" || node.type === "Literal" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "RegExpLiteral" || node.type === "StringLiteral" || node.type === "TemplateLiteral" || node.type === "TSTypeLiteral" || node.type === "JSXText";
29576 function isNumericLiteral(node) {
29577 return node.type === "NumericLiteral" || node.type === "Literal" && typeof node.value === "number";
29580 function isStringLiteral(node) {
29581 return node.type === "StringLiteral" || node.type === "Literal" && typeof node.value === "string";
29584 function isObjectType(n) {
29585 return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral";
29588 function isFunctionOrArrowExpression(node) {
29589 return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
29592 function isFunctionOrArrowExpressionWithBody(node) {
29593 return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement";
29596 function isTemplateLiteral(node) {
29597 return node.type === "TemplateLiteral";
29598 } // `inject` is used in AngularJS 1.x, `async` in Angular 2+
29599 // example: https://docs.angularjs.org/guide/unit-testing#using-beforeall-
29602 function isAngularTestWrapper(node) {
29603 return (node.type === "CallExpression" || node.type === "OptionalCallExpression") && node.callee.type === "Identifier" && (node.callee.name === "async" || node.callee.name === "inject" || node.callee.name === "fakeAsync");
29606 function isJSXNode(node) {
29607 return node.type === "JSXElement" || node.type === "JSXFragment";
29610 function isTheOnlyJSXElementInMarkdown(options, path) {
29611 if (options.parentParser !== "markdown" && options.parentParser !== "mdx") {
29615 var node = path.getNode();
29617 if (!node.expression || !isJSXNode(node.expression)) {
29621 var parent = path.getParentNode();
29622 return parent.type === "Program" && parent.body.length == 1;
29623 } // Detect an expression node representing `{" "}`
29626 function isJSXWhitespaceExpression(node) {
29627 return node.type === "JSXExpressionContainer" && isLiteral(node.expression) && node.expression.value === " " && !node.expression.comments;
29630 function isMemberExpressionChain(node) {
29631 if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") {
29635 if (node.object.type === "Identifier") {
29639 return isMemberExpressionChain(node.object);
29642 function isGetterOrSetter(node) {
29643 return node.kind === "get" || node.kind === "set";
29646 function sameLocStart(nodeA, nodeB, options) {
29647 return options.locStart(nodeA) === options.locStart(nodeB);
29648 } // TODO: This is a bad hack and we need a better way to distinguish between
29649 // arrow functions and otherwise
29652 function isFunctionNotation(node, options) {
29653 return isGetterOrSetter(node) || sameLocStart(node, node.value, options);
29654 } // Hack to differentiate between the following two which have the same ast
29655 // type T = { method: () => void };
29656 // type T = { method(): void };
29659 function isObjectTypePropertyAFunction(node, options) {
29660 return (node.type === "ObjectTypeProperty" || node.type === "ObjectTypeInternalSlot") && node.value.type === "FunctionTypeAnnotation" && !node.static && !isFunctionNotation(node, options);
29661 } // Hack to differentiate between the following two which have the same ast
29662 // declare function f(a): void;
29663 // var f: (a) => void;
29666 function isTypeAnnotationAFunction(node, options) {
29667 return (node.type === "TypeAnnotation" || node.type === "TSTypeAnnotation") && node.typeAnnotation.type === "FunctionTypeAnnotation" && !node.static && !sameLocStart(node, node.typeAnnotation, options);
29670 function isBinaryish(node) {
29671 return node.type === "BinaryExpression" || node.type === "LogicalExpression" || node.type === "NGPipeExpression";
29674 function isMemberish(node) {
29675 return node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "BindExpression" && node.object;
29678 function isSimpleFlowType(node) {
29679 var flowTypeAnnotations = ["AnyTypeAnnotation", "NullLiteralTypeAnnotation", "GenericTypeAnnotation", "ThisTypeAnnotation", "NumberTypeAnnotation", "VoidTypeAnnotation", "EmptyTypeAnnotation", "MixedTypeAnnotation", "BooleanTypeAnnotation", "BooleanLiteralTypeAnnotation", "StringTypeAnnotation"];
29680 return node && flowTypeAnnotations.indexOf(node.type) !== -1 && !(node.type === "GenericTypeAnnotation" && node.typeParameters);
29683 var unitTestRe = /^(skip|[fx]?(it|describe|test))$/;
29685 function isSkipOrOnlyBlock(node) {
29686 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");
29689 function isUnitTestSetUp(n) {
29690 var unitTestSetUpRe = /^(before|after)(Each|All)$/;
29691 return n.callee.type === "Identifier" && unitTestSetUpRe.test(n.callee.name) && n.arguments.length === 1;
29692 } // eg; `describe("some string", (done) => {})`
29695 function isTestCall(n, parent) {
29696 if (n.type !== "CallExpression") {
29700 if (n.arguments.length === 1) {
29701 if (isAngularTestWrapper(n) && parent && isTestCall(parent)) {
29702 return isFunctionOrArrowExpression(n.arguments[0]);
29705 if (isUnitTestSetUp(n)) {
29706 return isAngularTestWrapper(n.arguments[0]);
29708 } else if (n.arguments.length === 2 || n.arguments.length === 3) {
29709 if ((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name) || isSkipOrOnlyBlock(n)) && (isTemplateLiteral(n.arguments[0]) || isStringLiteral(n.arguments[0]))) {
29710 // it("name", () => { ... }, 2500)
29711 if (n.arguments[2] && !isNumericLiteral(n.arguments[2])) {
29715 return (n.arguments.length === 2 ? isFunctionOrArrowExpression(n.arguments[1]) : isFunctionOrArrowExpressionWithBody(n.arguments[1]) && n.arguments[1].params.length <= 1) || isAngularTestWrapper(n.arguments[1]);
29722 function hasLeadingComment$2(node) {
29723 return node.comments && node.comments.some(function (comment) {
29724 return comment.leading;
29728 function hasTrailingComment(node) {
29729 return node.comments && node.comments.some(function (comment) {
29730 return comment.trailing;
29734 function isCallOrOptionalCallExpression(node) {
29735 return node.type === "CallExpression" || node.type === "OptionalCallExpression";
29738 function hasDanglingComments(node) {
29739 return node.comments && node.comments.some(function (comment) {
29740 return !comment.leading && !comment.trailing;
29743 /** identify if an angular expression seems to have side effects */
29746 function hasNgSideEffect(path) {
29747 return hasNode(path.getValue(), function (node) {
29748 switch (node.type) {
29752 case "CallExpression":
29753 case "OptionalCallExpression":
29754 case "AssignmentExpression":
29760 function isNgForOf(node, index, parentNode) {
29761 return node.type === "NGMicrosyntaxKeyedExpression" && node.key.name === "of" && index === 1 && parentNode.body[0].type === "NGMicrosyntaxLet" && parentNode.body[0].value === null;
29763 /** @param node {import("estree").TemplateLiteral} */
29766 function isSimpleTemplateLiteral(node) {
29767 if (node.expressions.length === 0) {
29771 return node.expressions.every(function (expr) {
29772 // Disallow comments since printDocToString can't print them here
29773 if (expr.comments) {
29775 } // Allow `x` and `this`
29778 if (expr.type === "Identifier" || expr.type === "ThisExpression") {
29780 } // Allow `a.b.c`, `a.b[c]`, and `this.x.y`
29783 if (expr.type === "MemberExpression" || expr.type === "OptionalMemberExpression") {
29786 while (head.type === "MemberExpression" || head.type === "OptionalMemberExpression") {
29787 if (head.property.type !== "Identifier" && head.property.type !== "Literal" && head.property.type !== "StringLiteral" && head.property.type !== "NumericLiteral") {
29791 head = head.object;
29793 if (head.comments) {
29798 if (head.type === "Identifier" || head.type === "ThisExpression") {
29809 function getFlowVariance(path) {
29810 if (!path.variance) {
29812 } // Babel 7.0 currently uses variance node type, and flow should
29813 // follow suit soon:
29814 // https://github.com/babel/babel/issues/4722
29817 var variance = path.variance.kind || path.variance;
29819 switch (variance) {
29827 /* istanbul ignore next */
29832 function classPropMayCauseASIProblems(path) {
29833 var node = path.getNode();
29835 if (node.type !== "ClassProperty") {
29839 var name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today
29840 // so isn't properly tested yet.
29842 if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) {
29847 function classChildNeedsASIProtection(node) {
29852 if (node.static || node.accessibility // TypeScript
29857 if (!node.computed) {
29858 var name = node.key && node.key.name;
29860 if (name === "in" || name === "instanceof") {
29865 switch (node.type) {
29866 case "ClassProperty":
29867 case "TSAbstractClassProperty":
29868 return node.computed;
29870 case "MethodDefinition": // Flow
29872 case "TSAbstractMethodDefinition": // TypeScript
29874 case "ClassMethod":
29875 case "ClassPrivateMethod":
29878 var isAsync = node.value ? node.value.async : node.async;
29879 var isGenerator = node.value ? node.value.generator : node.generator;
29881 if (isAsync || node.kind === "get" || node.kind === "set") {
29885 if (node.computed || isGenerator) {
29892 case "TSIndexSignature":
29896 /* istanbul ignore next */
29901 function getTypeScriptMappedTypeModifier(tokenNode, keyword) {
29902 if (tokenNode === "+") {
29903 return "+" + keyword;
29904 } else if (tokenNode === "-") {
29905 return "-" + keyword;
29911 function hasNewlineBetweenOrAfterDecorators(node, options) {
29912 return hasNewlineInRange$1(options.originalText, options.locStart(node.decorators[0]), options.locEnd(getLast$1(node.decorators))) || hasNewline$2(options.originalText, options.locEnd(getLast$1(node.decorators)));
29913 } // Only space, newline, carriage return, and tab are treated as whitespace
29917 var jsxWhitespaceChars = " \n\r\t";
29918 var matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)");
29919 var containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]"); // Meaningful if it contains non-whitespace characters,
29920 // or it contains whitespace without a new line.
29922 function isMeaningfulJSXText(node) {
29923 return isLiteral(node) && (containsNonJsxWhitespaceRegex.test(rawText(node)) || !/\n/.test(rawText(node)));
29926 function hasJsxIgnoreComment(path) {
29927 var node = path.getValue();
29928 var parent = path.getParentNode();
29930 if (!parent || !node || !isJSXNode(node) || !isJSXNode(parent)) {
29932 } // Lookup the previous sibling, ignoring any empty JSXText elements
29935 var index = parent.children.indexOf(node);
29936 var prevSibling = null;
29938 for (var i = index; i > 0; i--) {
29939 var candidate = parent.children[i - 1];
29941 if (candidate.type === "JSXText" && !isMeaningfulJSXText(candidate)) {
29945 prevSibling = candidate;
29949 return prevSibling && prevSibling.type === "JSXExpressionContainer" && prevSibling.expression.type === "JSXEmptyExpression" && prevSibling.expression.comments && prevSibling.expression.comments.find(function (comment) {
29950 return comment.value.trim() === "prettier-ignore";
29954 function isEmptyJSXElement(node) {
29955 if (node.children.length === 0) {
29959 if (node.children.length > 1) {
29961 } // if there is one text child and does not contain any meaningful text
29962 // we can treat the element as empty.
29965 var child = node.children[0];
29966 return isLiteral(child) && !isMeaningfulJSXText(child);
29969 function hasPrettierIgnore(path) {
29970 return hasIgnoreComment$1(path) || hasJsxIgnoreComment(path);
29973 function isLastStatement(path) {
29974 var parent = path.getParentNode();
29980 var node = path.getValue();
29981 var body = (parent.body || parent.consequent).filter(function (stmt) {
29982 return stmt.type !== "EmptyStatement";
29984 return body && body[body.length - 1] === node;
29987 function isFlowAnnotationComment(text, typeAnnotation, options) {
29988 var start = options.locStart(typeAnnotation);
29989 var end = skipWhitespace$1(text, options.locEnd(typeAnnotation));
29990 return text.substr(start, 2) === "/*" && text.substr(end, 2) === "*/";
29993 function hasLeadingOwnLineComment(text, node, options) {
29994 if (isJSXNode(node)) {
29995 return hasNodeIgnoreComment$1(node);
29998 var res = node.comments && node.comments.some(function (comment) {
29999 return comment.leading && hasNewline$2(text, options.locEnd(comment));
30002 } // This recurses the return argument, looking for the first token
30003 // (the leftmost leaf node) and, if it (or its parents) has any
30004 // leadingComments, returns true (so it can be wrapped in parens).
30007 function returnArgumentHasLeadingComment(options, argument) {
30008 if (hasLeadingOwnLineComment(options.originalText, argument, options)) {
30012 if (hasNakedLeftSide(argument)) {
30013 var leftMost = argument;
30016 while (newLeftMost = getLeftSide(leftMost)) {
30017 leftMost = newLeftMost;
30019 if (hasLeadingOwnLineComment(options.originalText, leftMost, options)) {
30028 function isStringPropSafeToCoerceToIdentifier(node, options) {
30029 return isStringLiteral(node.key) && isIdentifierName(node.key.value) && options.parser !== "json" && !(options.parser === "typescript" && node.type === "ClassProperty");
30032 function isJestEachTemplateLiteral(node, parentNode) {
30034 * describe.each`table`(name, fn)
30035 * describe.only.each`table`(name, fn)
30036 * describe.skip.each`table`(name, fn)
30037 * test.each`table`(name, fn)
30038 * test.only.each`table`(name, fn)
30039 * test.skip.each`table`(name, fn)
30041 * Ref: https://github.com/facebook/jest/pull/6102
30043 var jestEachTriggerRegex = /^[xf]?(describe|it|test)$/;
30044 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));
30047 function templateLiteralHasNewLines(template) {
30048 return template.quasis.some(function (quasi) {
30049 return quasi.value.raw.includes("\n");
30053 function isTemplateOnItsOwnLine(n, text, options) {
30054 return (n.type === "TemplateLiteral" && templateLiteralHasNewLines(n) || n.type === "TaggedTemplateExpression" && templateLiteralHasNewLines(n.quasi)) && !hasNewline$2(text, options.locStart(n), {
30059 function needsHardlineAfterDanglingComment(node) {
30060 if (!node.comments) {
30064 var lastDanglingComment = getLast$1(node.comments.filter(function (comment) {
30065 return !comment.leading && !comment.trailing;
30067 return lastDanglingComment && !comments$1.isBlockComment(lastDanglingComment);
30068 } // If we have nested conditional expressions, we want to print them in JSX mode
30069 // if there's at least one JSXElement somewhere in the tree.
30071 // A conditional expression chain like this should be printed in normal mode,
30072 // because there aren't JSXElements anywhere in it:
30074 // isA ? "A" : isB ? "B" : isC ? "C" : "Unknown";
30076 // But a conditional expression chain like this should be printed in JSX mode,
30077 // because there is a JSXElement in the last ConditionalExpression:
30079 // isA ? "A" : isB ? "B" : isC ? "C" : <span className="warning">Unknown</span>;
30081 // This type of ConditionalExpression chain is structured like this in the AST:
30083 // ConditionalExpression {
30085 // consequent: ...,
30086 // alternate: ConditionalExpression {
30088 // consequent: ...,
30089 // alternate: ConditionalExpression {
30091 // consequent: ...,
30097 // We want to traverse over that shape and convert it into a flat structure so
30098 // that we can find if there's a JSXElement somewhere inside.
30101 function getConditionalChainContents(node) {
30102 // Given this code:
30104 // // Using a ConditionalExpression as the consequent is uncommon, but should
30106 // A ? B : C ? D : E ? F ? G : H : I
30108 // which has this AST:
30110 // ConditionalExpression {
30111 // test: Identifier(A),
30112 // consequent: Identifier(B),
30113 // alternate: ConditionalExpression {
30114 // test: Identifier(C),
30115 // consequent: Identifier(D),
30116 // alternate: ConditionalExpression {
30117 // test: Identifier(E),
30118 // consequent: ConditionalExpression {
30119 // test: Identifier(F),
30120 // consequent: Identifier(G),
30121 // alternate: Identifier(H),
30123 // alternate: Identifier(I),
30128 // we should return this Array:
30142 // This loses the information about whether each node was the test,
30143 // consequent, or alternate, but we don't care about that here- we are only
30144 // flattening this structure to find if there's any JSXElements inside.
30145 var nonConditionalExpressions = [];
30147 function recurse(node) {
30148 if (node.type === "ConditionalExpression") {
30149 recurse(node.test);
30150 recurse(node.consequent);
30151 recurse(node.alternate);
30153 nonConditionalExpressions.push(node);
30158 return nonConditionalExpressions;
30161 function conditionalExpressionChainContainsJSX(node) {
30162 return Boolean(getConditionalChainContents(node).find(isJSXNode));
30163 } // Logic to check for args with multiple anonymous functions. For instance,
30164 // the following call should be split on multiple lines for readability:
30165 // source.pipe(map((x) => x + x), filter((x) => x % 2 === 0))
30168 function isFunctionCompositionArgs(args) {
30169 if (args.length <= 1) {
30174 var _iteratorNormalCompletion = true;
30175 var _didIteratorError = false;
30176 var _iteratorError = undefined;
30179 for (var _iterator = args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
30180 var arg = _step.value;
30182 if (isFunctionOrArrowExpression(arg)) {
30188 } else if (isCallOrOptionalCallExpression(arg)) {
30189 var _iteratorNormalCompletion2 = true;
30190 var _didIteratorError2 = false;
30191 var _iteratorError2 = undefined;
30194 for (var _iterator2 = arg.arguments[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
30195 var childArg = _step2.value;
30197 if (isFunctionOrArrowExpression(childArg)) {
30202 _didIteratorError2 = true;
30203 _iteratorError2 = err;
30206 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
30207 _iterator2.return();
30210 if (_didIteratorError2) {
30211 throw _iteratorError2;
30218 _didIteratorError = true;
30219 _iteratorError = err;
30222 if (!_iteratorNormalCompletion && _iterator.return != null) {
30223 _iterator.return();
30226 if (_didIteratorError) {
30227 throw _iteratorError;
30233 } // Logic to determine if a call is a “long curried function call”.
30234 // See https://github.com/prettier/prettier/issues/1420.
30236 // `connect(a, b, c)(d)`
30237 // In the above call expression, the second call is the parent node and the
30238 // first call is the current node.
30241 function isLongCurriedCallExpression(path) {
30242 var node = path.getValue();
30243 var parent = path.getParentNode();
30244 return isCallOrOptionalCallExpression(node) && isCallOrOptionalCallExpression(parent) && parent.callee === node && node.arguments.length > parent.arguments.length && parent.arguments.length > 0;
30247 function rawText(node) {
30248 return node.extra ? node.extra.raw : node.raw;
30251 function identity(x) {
30255 function isTSXFile(options) {
30256 return options.filepath && /\.tsx$/i.test(options.filepath);
30260 classChildNeedsASIProtection,
30261 classPropMayCauseASIProblems,
30262 conditionalExpressionChainContainsJSX,
30264 getLeftSidePathName,
30265 getTypeScriptMappedTypeModifier,
30266 hasDanglingComments,
30267 hasFlowAnnotationComment,
30268 hasFlowShorthandAnnotationComment,
30269 hasLeadingComment: hasLeadingComment$2,
30270 hasLeadingOwnLineComment,
30272 hasNewlineBetweenOrAfterDecorators,
30276 hasTrailingComment,
30279 isCallOrOptionalCallExpression,
30281 isFlowAnnotationComment,
30282 isFunctionCompositionArgs,
30283 isFunctionNotation,
30284 isFunctionOrArrowExpression,
30286 isJestEachTemplateLiteral,
30288 isJSXWhitespaceExpression,
30291 isLongCurriedCallExpression,
30292 isMeaningfulJSXText,
30293 isMemberExpressionChain,
30298 isObjectTypePropertyAFunction,
30300 isSimpleTemplateLiteral,
30302 isStringPropSafeToCoerceToIdentifier,
30303 isTemplateOnItsOwnLine,
30305 isTheOnlyJSXElementInMarkdown,
30307 isTypeAnnotationAFunction,
30308 matchJsxWhitespaceRegex,
30309 needsHardlineAfterDanglingComment,
30311 returnArgumentHasLeadingComment
30314 var getLeftSidePathName$1 = utils$2.getLeftSidePathName,
30315 hasFlowShorthandAnnotationComment$1 = utils$2.hasFlowShorthandAnnotationComment,
30316 hasNakedLeftSide$1 = utils$2.hasNakedLeftSide,
30317 hasNode$1 = utils$2.hasNode;
30319 function hasClosureCompilerTypeCastComment(text, path) {
30320 // https://github.com/google/closure-compiler/wiki/Annotating-Types#type-casts
30321 // Syntax example: var x = /** @type {string} */ (fruit);
30322 var n = path.getValue();
30323 return isParenthesized(n) && (hasTypeCastComment(n) || hasAncestorTypeCastComment(0)); // for sub-item: /** @type {array} */ (numberOrString).map(x => x);
30325 function hasAncestorTypeCastComment(index) {
30326 var ancestor = path.getParentNode(index);
30327 return ancestor && !isParenthesized(ancestor) ? hasTypeCastComment(ancestor) || hasAncestorTypeCastComment(index + 1) : false;
30330 function hasTypeCastComment(node) {
30331 return node.comments && node.comments.some(function (comment) {
30332 return comment.leading && comments$1.isBlockComment(comment) && isTypeCastComment(comment.value);
30336 function isParenthesized(node) {
30337 // Closure typecast comments only really make sense when _not_ using
30338 // typescript or flow parsers, so we take advantage of the babel parser's
30339 // parenthesized expressions.
30340 return node.extra && node.extra.parenthesized;
30343 function isTypeCastComment(comment) {
30344 var cleaned = comment.trim().split("\n").map(function (line) {
30345 return line.replace(/^[\s*]+/, "");
30346 }).join(" ").trim();
30348 if (!/^@type\s*\{[^]+\}$/.test(cleaned)) {
30352 var isCompletelyClosed = false;
30353 var unpairedBracketCount = 0;
30354 var _iteratorNormalCompletion = true;
30355 var _didIteratorError = false;
30356 var _iteratorError = undefined;
30359 for (var _iterator = cleaned[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
30360 var char = _step.value;
30362 if (char === "{") {
30363 if (isCompletelyClosed) {
30367 unpairedBracketCount++;
30368 } else if (char === "}") {
30369 if (unpairedBracketCount === 0) {
30373 unpairedBracketCount--;
30375 if (unpairedBracketCount === 0) {
30376 isCompletelyClosed = true;
30381 _didIteratorError = true;
30382 _iteratorError = err;
30385 if (!_iteratorNormalCompletion && _iterator.return != null) {
30386 _iterator.return();
30389 if (_didIteratorError) {
30390 throw _iteratorError;
30395 return unpairedBracketCount === 0;
30399 function needsParens(path, options) {
30400 var parent = path.getParentNode();
30406 var name = path.getName();
30407 var node = path.getNode(); // If the value of this path is some child of a Node and not a Node
30408 // itself, then it doesn't need parentheses. Only Node objects (in
30409 // fact, only Expression nodes) need parentheses.
30411 if (path.getValue() !== node) {
30413 } // to avoid unexpected `}}` in HTML interpolations
30416 if (options.__isInHtmlInterpolation && !options.bracketSpacing && endsWithRightBracket(node) && isFollowedByRightBracket(path)) {
30418 } // Only statements don't need parentheses.
30421 if (isStatement(node)) {
30423 } // Closure compiler requires that type casted expressions to be surrounded by
30427 if (hasClosureCompilerTypeCastComment(options.originalText, path)) {
30431 if ( // Preserve parens if we have a Flow annotation comment, unless we're using the Flow
30432 // parser. The Flow parser turns Flow comments into type annotation nodes in its
30433 // AST, which we handle separately.
30434 options.parser !== "flow" && hasFlowShorthandAnnotationComment$1(path.getValue())) {
30436 } // Identifiers never need parentheses.
30439 if (node.type === "Identifier") {
30440 // ...unless those identifiers are embed placeholders. They might be substituted by complex
30441 // expressions, so the parens around them should not be dropped. Example (JS-in-HTML-in-JS):
30442 // let tpl = html`<script> f((${expr}) / 2); </script>`;
30443 // If the inner JS formatter removes the parens, the expression might change its meaning:
30444 // f((a + b) / 2) vs f(a + b / 2)
30445 if (node.extra && node.extra.parenthesized && /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(node.name)) {
30452 if (parent.type === "ParenthesizedExpression") {
30454 } // Add parens around the extends clause of a class. It is needed for almost
30455 // all expressions.
30458 if ((parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node && (node.type === "ArrowFunctionExpression" || node.type === "AssignmentExpression" || node.type === "AwaitExpression" || node.type === "BinaryExpression" || node.type === "ConditionalExpression" || node.type === "LogicalExpression" || node.type === "NewExpression" || node.type === "ObjectExpression" || node.type === "ParenthesizedExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "UnaryExpression" || node.type === "UpdateExpression" || node.type === "YieldExpression")) {
30460 } // `export default function` or `export default class` can't be followed by
30461 // anything after. So an expression like `export default (function(){}).toString()`
30462 // needs to be followed by a parentheses
30465 if (parent.type === "ExportDefaultDeclaration") {
30466 return shouldWrapFunctionForExportDefault(path, options);
30469 if (parent.type === "Decorator" && parent.expression === node) {
30470 var hasCallExpression = false;
30471 var hasMemberExpression = false;
30472 var current = node;
30475 switch (current.type) {
30476 case "MemberExpression":
30477 hasMemberExpression = true;
30478 current = current.object;
30481 case "CallExpression":
30484 hasMemberExpression ||
30486 hasCallExpression) {
30490 hasCallExpression = true;
30491 current = current.callee;
30505 if (parent.type === "ArrowFunctionExpression" && parent.body === node && node.type !== "SequenceExpression" && // these have parens added anyway
30506 util.startsWithNoLookaheadToken(node,
30507 /* forbidFunctionClassAndDoExpr */
30508 false) || parent.type === "ExpressionStatement" && util.startsWithNoLookaheadToken(node,
30509 /* forbidFunctionClassAndDoExpr */
30514 switch (node.type) {
30515 case "SpreadElement":
30516 case "SpreadProperty":
30517 return parent.type === "MemberExpression" && name === "object" && parent.object === node;
30519 case "UpdateExpression":
30520 if (parent.type === "UnaryExpression") {
30521 return node.prefix && (node.operator === "++" && parent.operator === "+" || node.operator === "--" && parent.operator === "-");
30524 // else fallthrough
30526 case "UnaryExpression":
30527 switch (parent.type) {
30528 case "UnaryExpression":
30529 return node.operator === parent.operator && (node.operator === "+" || node.operator === "-");
30531 case "BindExpression":
30534 case "MemberExpression":
30535 case "OptionalMemberExpression":
30536 return name === "object";
30538 case "TaggedTemplateExpression":
30541 case "NewExpression":
30542 case "CallExpression":
30543 case "OptionalCallExpression":
30544 return name === "callee";
30546 case "BinaryExpression":
30547 return parent.operator === "**" && name === "left";
30549 case "TSNonNullExpression":
30556 case "BinaryExpression":
30558 if (parent.type === "UpdateExpression") {
30562 var isLeftOfAForStatement = function isLeftOfAForStatement(node) {
30566 var _parent = path.getParentNode(i++);
30572 if (_parent.type === "ForStatement" && _parent.init === node) {
30582 if (node.operator === "in" && isLeftOfAForStatement(node)) {
30588 case "TSTypeAssertion":
30589 case "TSAsExpression":
30590 case "LogicalExpression":
30591 switch (parent.type) {
30592 case "ConditionalExpression":
30593 return node.type === "TSAsExpression";
30595 case "CallExpression":
30596 case "NewExpression":
30597 case "OptionalCallExpression":
30598 return name === "callee";
30600 case "ClassExpression":
30601 case "ClassDeclaration":
30602 return name === "superClass" && parent.superClass === node;
30604 case "TSTypeAssertion":
30605 case "TaggedTemplateExpression":
30606 case "UnaryExpression":
30607 case "JSXSpreadAttribute":
30608 case "SpreadElement":
30609 case "SpreadProperty":
30610 case "BindExpression":
30611 case "AwaitExpression":
30612 case "TSAsExpression":
30613 case "TSNonNullExpression":
30614 case "UpdateExpression":
30617 case "MemberExpression":
30618 case "OptionalMemberExpression":
30619 return name === "object";
30621 case "AssignmentExpression":
30622 return parent.left === node && (node.type === "TSTypeAssertion" || node.type === "TSAsExpression");
30624 case "LogicalExpression":
30625 if (node.type === "LogicalExpression") {
30626 return parent.operator !== node.operator;
30629 // else fallthrough
30631 case "BinaryExpression":
30633 if (!node.operator && node.type !== "TSTypeAssertion") {
30637 var po = parent.operator;
30638 var pp = util.getPrecedence(po);
30639 var no = node.operator;
30640 var np = util.getPrecedence(no);
30646 if (pp === np && name === "right") {
30647 assert$1.strictEqual(parent.right, node);
30651 if (pp === np && !util.shouldFlatten(po, no)) {
30655 if (pp < np && no === "%") {
30656 return po === "+" || po === "-";
30657 } // Add parenthesis when working with bitwise operators
30658 // It's not strictly needed but helps with code understanding
30661 if (util.isBitwiseOperator(po)) {
30672 case "SequenceExpression":
30673 switch (parent.type) {
30674 case "ReturnStatement":
30677 case "ForStatement":
30678 // Although parentheses wouldn't hurt around sequence
30679 // expressions in the head of for loops, traditional style
30680 // dictates that e.g. i++, j++ should not be wrapped with
30684 case "ExpressionStatement":
30685 return name !== "expression";
30687 case "ArrowFunctionExpression":
30688 // We do need parentheses, but SequenceExpressions are handled
30689 // specially when printing bodies of arrow functions.
30690 return name !== "body";
30693 // Otherwise err on the side of overparenthesization, adding
30694 // explicit exceptions above if this proves overzealous.
30698 case "YieldExpression":
30699 if (parent.type === "UnaryExpression" || parent.type === "AwaitExpression" || parent.type === "TSAsExpression" || parent.type === "TSNonNullExpression") {
30703 // else fallthrough
30705 case "AwaitExpression":
30706 switch (parent.type) {
30707 case "TaggedTemplateExpression":
30708 case "UnaryExpression":
30709 case "BinaryExpression":
30710 case "LogicalExpression":
30711 case "SpreadElement":
30712 case "SpreadProperty":
30713 case "TSAsExpression":
30714 case "TSNonNullExpression":
30715 case "BindExpression":
30718 case "MemberExpression":
30719 case "OptionalMemberExpression":
30720 return name === "object";
30722 case "NewExpression":
30723 case "CallExpression":
30724 case "OptionalCallExpression":
30725 return name === "callee";
30727 case "ConditionalExpression":
30728 return parent.test === node;
30734 case "TSConditionalType":
30735 if (parent.type === "TSConditionalType" && node === parent.extendsType) {
30741 case "TSFunctionType":
30742 case "TSConstructorType":
30743 if (parent.type === "TSConditionalType" && node === parent.checkType) {
30749 case "TSUnionType":
30750 case "TSIntersectionType":
30751 if (parent.type === "TSUnionType" || parent.type === "TSIntersectionType") {
30757 case "TSTypeOperator":
30758 case "TSInferType":
30759 return parent.type === "TSArrayType" || parent.type === "TSOptionalType" || parent.type === "TSRestType" || parent.type === "TSIndexedAccessType" && node === parent.objectType || parent.type === "TSTypeOperator";
30761 case "ArrayTypeAnnotation":
30762 return parent.type === "NullableTypeAnnotation";
30764 case "IntersectionTypeAnnotation":
30765 case "UnionTypeAnnotation":
30766 return parent.type === "ArrayTypeAnnotation" || parent.type === "NullableTypeAnnotation" || parent.type === "IntersectionTypeAnnotation" || parent.type === "UnionTypeAnnotation";
30768 case "NullableTypeAnnotation":
30769 return parent.type === "ArrayTypeAnnotation";
30771 case "FunctionTypeAnnotation":
30773 var ancestor = parent.type === "NullableTypeAnnotation" ? path.getParentNode(1) : parent;
30774 return ancestor.type === "UnionTypeAnnotation" || ancestor.type === "IntersectionTypeAnnotation" || ancestor.type === "ArrayTypeAnnotation" || // We should check ancestor's parent to know whether the parentheses
30775 // are really needed, but since ??T doesn't make sense this check
30776 // will almost never be true.
30777 ancestor.type === "NullableTypeAnnotation";
30780 case "StringLiteral":
30781 case "NumericLiteral":
30783 if (typeof node.value === "string" && parent.type === "ExpressionStatement" && ( // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2
30784 // See corresponding workaround in printer.js case: "Literal"
30785 options.parser !== "typescript" && !parent.directive || options.parser === "typescript" && options.originalText.substr(options.locStart(node) - 1, 1) === "(")) {
30786 // To avoid becoming a directive
30787 var grandParent = path.getParentNode(1);
30788 return grandParent.type === "Program" || grandParent.type === "BlockStatement";
30791 return parent.type === "MemberExpression" && typeof node.value === "number" && name === "object" && parent.object === node;
30793 case "AssignmentExpression":
30795 var _grandParent = path.getParentNode(1);
30797 if (parent.type === "ArrowFunctionExpression" && parent.body === node) {
30799 } else if (parent.type === "ClassProperty" && parent.key === node && parent.computed) {
30801 } else if (parent.type === "TSPropertySignature" && parent.name === node) {
30803 } else if (parent.type === "ForStatement" && (parent.init === node || parent.update === node)) {
30805 } else if (parent.type === "ExpressionStatement") {
30806 return node.left.type === "ObjectPattern";
30807 } else if (parent.type === "TSPropertySignature" && parent.key === node) {
30809 } else if (parent.type === "AssignmentExpression") {
30811 } else if (parent.type === "SequenceExpression" && _grandParent && _grandParent.type === "ForStatement" && (_grandParent.init === parent || _grandParent.update === parent)) {
30813 } else if (parent.type === "Property" && parent.value === node) {
30815 } else if (parent.type === "NGChainedExpression") {
30822 case "ConditionalExpression":
30823 switch (parent.type) {
30824 case "TaggedTemplateExpression":
30825 case "UnaryExpression":
30826 case "SpreadElement":
30827 case "SpreadProperty":
30828 case "BinaryExpression":
30829 case "LogicalExpression":
30830 case "NGPipeExpression":
30831 case "ExportDefaultDeclaration":
30832 case "AwaitExpression":
30833 case "JSXSpreadAttribute":
30834 case "TSTypeAssertion":
30835 case "TypeCastExpression":
30836 case "TSAsExpression":
30837 case "TSNonNullExpression":
30840 case "NewExpression":
30841 case "CallExpression":
30842 case "OptionalCallExpression":
30843 return name === "callee";
30845 case "ConditionalExpression":
30846 return name === "test" && parent.test === node;
30848 case "MemberExpression":
30849 case "OptionalMemberExpression":
30850 return name === "object";
30856 case "FunctionExpression":
30857 switch (parent.type) {
30858 case "NewExpression":
30859 case "CallExpression":
30860 case "OptionalCallExpression":
30861 // Not always necessary, but it's clearer to the reader if IIFEs are wrapped in parentheses.
30862 // Is necessary if it is `expression` of `ExpressionStatement`.
30863 return name === "callee";
30865 case "TaggedTemplateExpression":
30867 // This is basically a kind of IIFE.
30873 case "ArrowFunctionExpression":
30874 switch (parent.type) {
30875 case "NewExpression":
30876 case "CallExpression":
30877 case "OptionalCallExpression":
30878 return name === "callee";
30880 case "MemberExpression":
30881 case "OptionalMemberExpression":
30882 return name === "object";
30884 case "TSAsExpression":
30885 case "BindExpression":
30886 case "TaggedTemplateExpression":
30887 case "UnaryExpression":
30888 case "LogicalExpression":
30889 case "BinaryExpression":
30890 case "AwaitExpression":
30891 case "TSTypeAssertion":
30894 case "ConditionalExpression":
30895 return name === "test";
30901 case "ClassExpression":
30902 switch (parent.type) {
30903 case "NewExpression":
30904 return name === "callee" && parent.callee === node;
30910 case "OptionalMemberExpression":
30911 case "OptionalCallExpression":
30912 if ((parent.type === "MemberExpression" && name === "object" || parent.type === "CallExpression" && name === "callee") && // workaround for https://github.com/facebook/flow/issues/8159
30913 !(options.parser === "flow" && parent.range[0] === node.range[0])) {
30919 case "CallExpression":
30920 case "MemberExpression":
30921 case "TaggedTemplateExpression":
30922 case "TSNonNullExpression":
30923 if ((parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee") {
30927 switch (object.type) {
30928 case "CallExpression":
30929 case "OptionalCallExpression":
30932 case "MemberExpression":
30933 case "OptionalMemberExpression":
30934 case "BindExpression":
30935 object = object.object;
30937 // tagged templates are basically member expressions from a grammar perspective
30938 // see https://tc39.github.io/ecma262/#prod-MemberExpression
30940 case "TaggedTemplateExpression":
30941 object = object.tag;
30944 case "TSNonNullExpression":
30945 object = object.expression;
30956 case "BindExpression":
30957 return (parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && name === "object";
30959 case "NGPipeExpression":
30960 if (parent.type === "NGRoot" || parent.type === "NGMicrosyntaxExpression" || parent.type === "ObjectProperty" || parent.type === "ArrayExpression" || (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.arguments[name] === node || parent.type === "NGPipeExpression" && name === "right" || parent.type === "MemberExpression" && name === "property" || parent.type === "AssignmentExpression") {
30966 case "JSXFragment":
30968 return name === "callee" || parent.type !== "ArrayExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "AssignmentExpression" && parent.type !== "AssignmentPattern" && parent.type !== "BinaryExpression" && parent.type !== "CallExpression" && 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 !== "TypeCastExpression" && parent.type !== "VariableDeclarator";
30970 case "TypeAnnotation":
30971 return name === "returnType" && parent.type === "ArrowFunctionExpression" && includesFunctionTypeInObjectType(node);
30977 function isStatement(node) {
30978 return node.type === "BlockStatement" || node.type === "BreakStatement" || node.type === "ClassBody" || node.type === "ClassDeclaration" || node.type === "ClassMethod" || node.type === "ClassProperty" || node.type === "ClassPrivateProperty" || node.type === "ContinueStatement" || node.type === "DebuggerStatement" || node.type === "DeclareClass" || node.type === "DeclareExportAllDeclaration" || node.type === "DeclareExportDeclaration" || node.type === "DeclareFunction" || node.type === "DeclareInterface" || node.type === "DeclareModule" || node.type === "DeclareModuleExports" || node.type === "DeclareVariable" || node.type === "DoWhileStatement" || node.type === "EnumDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExpressionStatement" || node.type === "ForAwaitStatement" || 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";
30981 function includesFunctionTypeInObjectType(node) {
30982 return hasNode$1(node, function (n1) {
30983 return n1.type === "ObjectTypeAnnotation" && hasNode$1(n1, function (n2) {
30984 return n2.type === "FunctionTypeAnnotation" || undefined;
30989 function endsWithRightBracket(node) {
30990 switch (node.type) {
30991 case "ObjectExpression":
30999 function isFollowedByRightBracket(path) {
31000 var node = path.getValue();
31001 var parent = path.getParentNode();
31002 var name = path.getName();
31004 switch (parent.type) {
31005 case "NGPipeExpression":
31006 if (typeof name === "number" && parent.arguments[name] === node && parent.arguments.length - 1 === name) {
31007 return path.callParent(isFollowedByRightBracket);
31012 case "ObjectProperty":
31013 if (name === "value") {
31014 var parentParent = path.getParentNode(1);
31015 return parentParent.properties[parentParent.properties.length - 1] === parent;
31020 case "BinaryExpression":
31021 case "LogicalExpression":
31022 if (name === "right") {
31023 return path.callParent(isFollowedByRightBracket);
31028 case "ConditionalExpression":
31029 if (name === "alternate") {
31030 return path.callParent(isFollowedByRightBracket);
31035 case "UnaryExpression":
31036 if (parent.prefix) {
31037 return path.callParent(isFollowedByRightBracket);
31046 function shouldWrapFunctionForExportDefault(path, options) {
31047 var node = path.getValue();
31048 var parent = path.getParentNode();
31050 if (node.type === "FunctionExpression" || node.type === "ClassExpression") {
31051 return parent.type === "ExportDefaultDeclaration" || // in some cases the function is already wrapped
31052 // (e.g. `export default (function() {})();`)
31053 // in this case we don't need to add extra parens
31054 !needsParens(path, options);
31057 if (!hasNakedLeftSide$1(node) || parent.type !== "ExportDefaultDeclaration" && needsParens(path, options)) {
31061 return path.call.apply(path, [function (childPath) {
31062 return shouldWrapFunctionForExportDefault(childPath, options);
31063 }].concat(getLeftSidePathName$1(path, node)));
31066 var needsParens_1 = needsParens;
31068 var _require$$0$builders$1 = doc.builders,
31069 concat$5 = _require$$0$builders$1.concat,
31070 join$3 = _require$$0$builders$1.join,
31071 line$1 = _require$$0$builders$1.line;
31073 function printHtmlBinding(path, options, print) {
31074 var node = path.getValue();
31076 if (options.__onHtmlBindingRoot && path.getName() === null) {
31077 options.__onHtmlBindingRoot(node);
31080 if (node.type !== "File") {
31084 if (options.__isVueForBindingLeft) {
31085 return path.call(function (functionDeclarationPath) {
31086 var _functionDeclarationP = functionDeclarationPath.getValue(),
31087 params = _functionDeclarationP.params;
31089 return concat$5([params.length > 1 ? "(" : "", join$3(concat$5([",", line$1]), functionDeclarationPath.map(print, "params")), params.length > 1 ? ")" : ""]);
31090 }, "program", "body", 0);
31093 if (options.__isVueSlotScope) {
31094 return path.call(function (functionDeclarationPath) {
31095 return join$3(concat$5([",", line$1]), functionDeclarationPath.map(print, "params"));
31096 }, "program", "body", 0);
31098 } // based on https://github.com/prettier/prettier/blob/master/src/language-html/syntax-vue.js isVueEventBindingExpression()
31101 function isVueEventBindingExpression(node) {
31102 switch (node.type) {
31103 case "MemberExpression":
31104 switch (node.property.type) {
31106 case "NumericLiteral":
31107 case "StringLiteral":
31108 return isVueEventBindingExpression(node.object);
31121 var htmlBinding = {
31122 isVueEventBindingExpression,
31126 function preprocess(ast, options) {
31127 switch (options.parser) {
31130 case "json-stringify":
31131 case "__js_expression":
31132 case "__vue_expression":
31133 return Object.assign({}, ast, {
31134 type: options.parser.startsWith("__") ? "JsExpressionRoot" : "JsonRoot",
31144 var preprocess_1 = preprocess;
31146 var getParentExportDeclaration$1 = util.getParentExportDeclaration,
31147 isExportDeclaration$1 = util.isExportDeclaration,
31148 shouldFlatten$1 = util.shouldFlatten,
31149 getNextNonSpaceNonCommentCharacter$1 = util.getNextNonSpaceNonCommentCharacter,
31150 hasNewline$3 = util.hasNewline,
31151 hasNewlineInRange$2 = util.hasNewlineInRange,
31152 getLast$2 = util.getLast,
31153 getStringWidth$2 = util.getStringWidth,
31154 printString$1 = util.printString,
31155 printNumber$1 = util.printNumber,
31156 hasIgnoreComment$2 = util.hasIgnoreComment,
31157 hasNodeIgnoreComment$2 = util.hasNodeIgnoreComment,
31158 getPenultimate$1 = util.getPenultimate,
31159 startsWithNoLookaheadToken$1 = util.startsWithNoLookaheadToken,
31160 getIndentSize$1 = util.getIndentSize,
31161 matchAncestorTypes$1 = util.matchAncestorTypes,
31162 getPreferredQuote$1 = util.getPreferredQuote;
31163 var isNextLineEmpty$2 = utilShared.isNextLineEmpty,
31164 isNextLineEmptyAfterIndex$1 = utilShared.isNextLineEmptyAfterIndex,
31165 getNextNonSpaceNonCommentCharacterIndex$2 = utilShared.getNextNonSpaceNonCommentCharacterIndex;
31166 var insertPragma$1 = pragma.insertPragma;
31167 var printHtmlBinding$1 = htmlBinding.printHtmlBinding,
31168 isVueEventBindingExpression$1 = htmlBinding.isVueEventBindingExpression;
31169 var classChildNeedsASIProtection$1 = utils$2.classChildNeedsASIProtection,
31170 classPropMayCauseASIProblems$1 = utils$2.classPropMayCauseASIProblems,
31171 conditionalExpressionChainContainsJSX$1 = utils$2.conditionalExpressionChainContainsJSX,
31172 getFlowVariance$1 = utils$2.getFlowVariance,
31173 getLeftSidePathName$2 = utils$2.getLeftSidePathName,
31174 getTypeScriptMappedTypeModifier$1 = utils$2.getTypeScriptMappedTypeModifier,
31175 hasDanglingComments$1 = utils$2.hasDanglingComments,
31176 hasFlowAnnotationComment$1 = utils$2.hasFlowAnnotationComment,
31177 hasFlowShorthandAnnotationComment$2 = utils$2.hasFlowShorthandAnnotationComment,
31178 hasLeadingComment$3 = utils$2.hasLeadingComment,
31179 hasLeadingOwnLineComment$1 = utils$2.hasLeadingOwnLineComment,
31180 hasNakedLeftSide$2 = utils$2.hasNakedLeftSide,
31181 hasNewlineBetweenOrAfterDecorators$1 = utils$2.hasNewlineBetweenOrAfterDecorators,
31182 hasNgSideEffect$1 = utils$2.hasNgSideEffect,
31183 hasPrettierIgnore$1 = utils$2.hasPrettierIgnore,
31184 hasTrailingComment$1 = utils$2.hasTrailingComment,
31185 identity$1 = utils$2.identity,
31186 isBinaryish$1 = utils$2.isBinaryish,
31187 isCallOrOptionalCallExpression$1 = utils$2.isCallOrOptionalCallExpression,
31188 isEmptyJSXElement$1 = utils$2.isEmptyJSXElement,
31189 isFlowAnnotationComment$1 = utils$2.isFlowAnnotationComment,
31190 isFunctionCompositionArgs$1 = utils$2.isFunctionCompositionArgs,
31191 isFunctionNotation$1 = utils$2.isFunctionNotation,
31192 isFunctionOrArrowExpression$1 = utils$2.isFunctionOrArrowExpression,
31193 isGetterOrSetter$1 = utils$2.isGetterOrSetter,
31194 isJestEachTemplateLiteral$1 = utils$2.isJestEachTemplateLiteral,
31195 isJSXNode$1 = utils$2.isJSXNode,
31196 isJSXWhitespaceExpression$1 = utils$2.isJSXWhitespaceExpression,
31197 isLastStatement$1 = utils$2.isLastStatement,
31198 isLiteral$1 = utils$2.isLiteral,
31199 isLongCurriedCallExpression$1 = utils$2.isLongCurriedCallExpression,
31200 isMeaningfulJSXText$1 = utils$2.isMeaningfulJSXText,
31201 isMemberExpressionChain$1 = utils$2.isMemberExpressionChain,
31202 isMemberish$1 = utils$2.isMemberish,
31203 isNgForOf$1 = utils$2.isNgForOf,
31204 isNumericLiteral$1 = utils$2.isNumericLiteral,
31205 isObjectType$1 = utils$2.isObjectType,
31206 isObjectTypePropertyAFunction$1 = utils$2.isObjectTypePropertyAFunction,
31207 isSimpleFlowType$1 = utils$2.isSimpleFlowType,
31208 isSimpleTemplateLiteral$1 = utils$2.isSimpleTemplateLiteral,
31209 isStringLiteral$1 = utils$2.isStringLiteral,
31210 isStringPropSafeToCoerceToIdentifier$1 = utils$2.isStringPropSafeToCoerceToIdentifier,
31211 isTemplateOnItsOwnLine$1 = utils$2.isTemplateOnItsOwnLine,
31212 isTestCall$1 = utils$2.isTestCall,
31213 isTheOnlyJSXElementInMarkdown$1 = utils$2.isTheOnlyJSXElementInMarkdown,
31214 isTSXFile$1 = utils$2.isTSXFile,
31215 isTypeAnnotationAFunction$1 = utils$2.isTypeAnnotationAFunction,
31216 matchJsxWhitespaceRegex$1 = utils$2.matchJsxWhitespaceRegex,
31217 needsHardlineAfterDanglingComment$1 = utils$2.needsHardlineAfterDanglingComment,
31218 rawText$1 = utils$2.rawText,
31219 returnArgumentHasLeadingComment$1 = utils$2.returnArgumentHasLeadingComment;
31220 var needsQuoteProps = new WeakMap();
31221 var _require$$5$builders = doc.builders,
31222 concat$6 = _require$$5$builders.concat,
31223 join$4 = _require$$5$builders.join,
31224 line$2 = _require$$5$builders.line,
31225 hardline$4 = _require$$5$builders.hardline,
31226 softline$2 = _require$$5$builders.softline,
31227 literalline$2 = _require$$5$builders.literalline,
31228 group$2 = _require$$5$builders.group,
31229 indent$3 = _require$$5$builders.indent,
31230 align$1 = _require$$5$builders.align,
31231 conditionalGroup$1 = _require$$5$builders.conditionalGroup,
31232 fill$2 = _require$$5$builders.fill,
31233 ifBreak$1 = _require$$5$builders.ifBreak,
31234 breakParent$2 = _require$$5$builders.breakParent,
31235 lineSuffixBoundary$1 = _require$$5$builders.lineSuffixBoundary,
31236 addAlignmentToDoc$2 = _require$$5$builders.addAlignmentToDoc,
31237 dedent$1 = _require$$5$builders.dedent,
31238 _require$$5$utils = doc.utils,
31239 willBreak$1 = _require$$5$utils.willBreak,
31240 isLineNext$1 = _require$$5$utils.isLineNext,
31241 isEmpty$1 = _require$$5$utils.isEmpty,
31242 removeLines$1 = _require$$5$utils.removeLines,
31243 printDocToString$2 = doc.printer.printDocToString;
31246 function shouldPrintComma(options, level) {
31247 level = level || "es5";
31249 switch (options.trailingComma) {
31251 if (level === "all") {
31258 if (level === "es5") {
31270 function genericPrint(path, options, printPath, args) {
31271 var node = path.getValue();
31272 var needsParens = false;
31273 var linesWithoutParens = printPathNoParens(path, options, printPath, args);
31275 if (!node || isEmpty$1(linesWithoutParens)) {
31276 return linesWithoutParens;
31279 var parentExportDecl = getParentExportDeclaration$1(path);
31280 var decorators = [];
31282 if (node.type === "ClassMethod" || node.type === "ClassPrivateMethod" || node.type === "ClassProperty" || node.type === "TSAbstractClassProperty" || node.type === "ClassPrivateProperty" || node.type === "MethodDefinition" || node.type === "TSAbstractMethodDefinition") ; else if (node.decorators && node.decorators.length > 0 && // If the parent node is an export declaration and the decorator
31283 // was written before the export, the export will be responsible
31284 // for printing the decorators.
31285 !(parentExportDecl && options.locStart(parentExportDecl, {
31286 ignoreDecorators: true
31287 }) > options.locStart(node.decorators[0]))) {
31288 var shouldBreak = node.type === "ClassExpression" || node.type === "ClassDeclaration" || hasNewlineBetweenOrAfterDecorators$1(node, options);
31289 var separator = shouldBreak ? hardline$4 : line$2;
31290 path.each(function (decoratorPath) {
31291 var decorator = decoratorPath.getValue();
31293 if (decorator.expression) {
31294 decorator = decorator.expression;
31296 decorator = decorator.callee;
31299 decorators.push(printPath(decoratorPath), separator);
31302 if (parentExportDecl) {
31303 decorators.unshift(hardline$4);
31305 } 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,
31306 // otherwise they are printed by the node.declaration
31307 options.locStart(node, {
31308 ignoreDecorators: true
31309 }) > options.locStart(node.declaration.decorators[0])) {
31310 // Export declarations are responsible for printing any decorators
31311 // that logically apply to node.declaration.
31312 path.each(function (decoratorPath) {
31313 var decorator = decoratorPath.getValue();
31314 var prefix = decorator.type === "Decorator" ? "" : "@";
31315 decorators.push(prefix, printPath(decoratorPath), hardline$4);
31316 }, "declaration", "decorators");
31318 // Nodes with decorators can't have parentheses, so we can avoid
31319 // computing pathNeedsParens() except in this case.
31320 needsParens = needsParens_1(path, options);
31326 parts.unshift("(");
31329 parts.push(linesWithoutParens);
31332 var _node = path.getValue();
31334 if (hasFlowShorthandAnnotationComment$2(_node)) {
31336 parts.push(_node.trailingComments[0].value.trimLeft());
31338 _node.trailingComments[0].printed = true;
31344 if (decorators.length > 0) {
31345 return group$2(concat$6(decorators.concat(parts)));
31348 return concat$6(parts);
31351 function printDecorators(path, options, print) {
31352 var node = path.getValue();
31353 return group$2(concat$6([join$4(line$2, path.map(print, "decorators")), hasNewlineBetweenOrAfterDecorators$1(node, options) ? hardline$4 : line$2]));
31356 * The following is the shared logic for
31357 * ternary operators, namely ConditionalExpression
31358 * and TSConditionalType
31359 * @typedef {Object} OperatorOptions
31360 * @property {() => Array<string | Doc>} beforeParts - Parts to print before the `?`.
31361 * @property {(breakClosingParen: boolean) => Array<string | Doc>} afterParts - Parts to print after the conditional expression.
31362 * @property {boolean} shouldCheckJsx - Whether to check for and print in JSX mode.
31363 * @property {string} conditionalNodeType - The type of the conditional expression node, ie "ConditionalExpression" or "TSConditionalType".
31364 * @property {string} consequentNodePropertyName - The property at which the consequent node can be found on the main node, eg "consequent".
31365 * @property {string} alternateNodePropertyName - The property at which the alternate node can be found on the main node, eg "alternate".
31366 * @property {string} testNodePropertyName - The property at which the test node can be found on the main node, eg "test".
31367 * @property {boolean} breakNested - Whether to break all nested ternaries when one breaks.
31368 * @param {FastPath} path - The path to the ConditionalExpression/TSConditionalType node.
31369 * @param {Options} options - Prettier options
31370 * @param {Function} print - Print function to call recursively
31371 * @param {OperatorOptions} operatorOptions
31376 function printTernaryOperator(path, options, print, operatorOptions) {
31377 var node = path.getValue();
31378 var testNode = node[operatorOptions.testNodePropertyName];
31379 var consequentNode = node[operatorOptions.consequentNodePropertyName];
31380 var alternateNode = node[operatorOptions.alternateNodePropertyName];
31381 var parts = []; // We print a ConditionalExpression in either "JSX mode" or "normal mode".
31382 // See tests/jsx/conditional-expression.js for more info.
31384 var jsxMode = false;
31385 var parent = path.getParentNode();
31386 var forceNoIndent = parent.type === operatorOptions.conditionalNodeType; // Find the outermost non-ConditionalExpression parent, and the outermost
31387 // ConditionalExpression parent. We'll use these to determine if we should
31388 // print in JSX mode.
31391 var previousParent;
31395 previousParent = currentParent || node;
31396 currentParent = path.getParentNode(i);
31398 } while (currentParent && currentParent.type === operatorOptions.conditionalNodeType);
31400 var firstNonConditionalParent = currentParent || parent;
31401 var lastConditionalParent = previousParent;
31403 if (operatorOptions.shouldCheckJsx && (isJSXNode$1(testNode) || isJSXNode$1(consequentNode) || isJSXNode$1(alternateNode) || conditionalExpressionChainContainsJSX$1(lastConditionalParent))) {
31405 forceNoIndent = true; // Even though they don't need parens, we wrap (almost) everything in
31406 // parens when using ?: within JSX, because the parens are analogous to
31407 // curly braces in an if statement.
31409 var wrap = function wrap(doc) {
31410 return concat$6([ifBreak$1("(", ""), indent$3(concat$6([softline$2, doc])), softline$2, ifBreak$1(")", "")]);
31411 }; // The only things we don't wrap are:
31412 // * Nested conditional expressions in alternates
31416 var isNull = function isNull(node) {
31417 return node.type === "NullLiteral" || node.type === "Literal" && node.value === null;
31420 parts.push(" ? ", isNull(consequentNode) ? path.call(print, operatorOptions.consequentNodePropertyName) : wrap(path.call(print, operatorOptions.consequentNodePropertyName)), " : ", alternateNode.type === operatorOptions.conditionalNodeType || isNull(alternateNode) ? path.call(print, operatorOptions.alternateNodePropertyName) : wrap(path.call(print, operatorOptions.alternateNodePropertyName)));
31423 var part = concat$6([line$2, "? ", consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$1("", "(") : "", align$1(2, path.call(print, operatorOptions.consequentNodePropertyName)), consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$1("", ")") : "", line$2, ": ", alternateNode.type === operatorOptions.conditionalNodeType ? path.call(print, operatorOptions.alternateNodePropertyName) : align$1(2, path.call(print, operatorOptions.alternateNodePropertyName))]);
31424 parts.push(parent.type !== operatorOptions.conditionalNodeType || parent[operatorOptions.alternateNodePropertyName] === node ? part : options.useTabs ? dedent$1(indent$3(part)) : align$1(Math.max(0, options.tabWidth - 2), part));
31425 } // We want a whole chain of ConditionalExpressions to all
31426 // break if any of them break. That means we should only group around the
31427 // outer-most ConditionalExpression.
31430 var maybeGroup = function maybeGroup(doc) {
31431 return operatorOptions.breakNested ? parent === firstNonConditionalParent ? group$2(doc) : doc : group$2(doc);
31432 }; // Break the closing paren to keep the chain right after it:
31439 var breakClosingParen = !jsxMode && (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression" || parent.type === "NGPipeExpression" && parent.left === node && operatorOptions.breakNested) && !parent.computed;
31440 return maybeGroup(concat$6([].concat(function (testDoc) {
31452 parent.type === operatorOptions.conditionalNodeType && parent[operatorOptions.alternateNodePropertyName] === node ? align$1(2, testDoc) : testDoc
31454 }(concat$6(operatorOptions.beforeParts())), forceNoIndent ? concat$6(parts) : indent$3(concat$6(parts)), operatorOptions.afterParts(breakClosingParen))));
31457 function printPathNoParens(path, options, print, args) {
31458 var n = path.getValue();
31459 var semi = options.semi ? ";" : "";
31465 if (typeof n === "string") {
31469 var htmlBinding = printHtmlBinding$1(path, options, print);
31472 return htmlBinding;
31478 case "JsExpressionRoot":
31479 return path.call(print, "node");
31482 return concat$6([path.call(print, "node"), hardline$4]);
31485 // Print @babel/parser's InterpreterDirective here so that
31486 // leading comments on the `Program` node get printed after the hashbang.
31487 if (n.program && n.program.interpreter) {
31488 parts.push(path.call(function (programPath) {
31489 return programPath.call(print, "interpreter");
31493 parts.push(path.call(print, "program"));
31494 return concat$6(parts);
31498 if (n.directives) {
31499 path.each(function (childPath) {
31500 parts.push(print(childPath), semi, hardline$4);
31502 if (isNextLineEmpty$2(options.originalText, childPath.getValue(), options)) {
31503 parts.push(hardline$4);
31508 parts.push(path.call(function (bodyPath) {
31509 return printStatementSequence(bodyPath, options, print);
31511 parts.push(comments.printDanglingComments(path, options,
31513 true)); // Only force a trailing newline if there were any contents.
31515 if (n.body.length || n.comments) {
31516 parts.push(hardline$4);
31519 return concat$6(parts);
31520 // Babel extension.
31522 case "EmptyStatement":
31525 case "ExpressionStatement":
31526 // Detect Flow-parsed directives
31528 return concat$6([nodeStr(n.expression, options, true), semi]);
31531 if (options.parser === "__vue_event_binding") {
31532 var parent = path.getParentNode();
31534 if (parent.type === "Program" && parent.body.length === 1 && parent.body[0] === n) {
31535 return concat$6([path.call(print, "expression"), isVueEventBindingExpression$1(n.expression) ? ";" : ""]);
31537 } // Do not append semicolon after the only JSX element in a program
31540 return concat$6([path.call(print, "expression"), isTheOnlyJSXElementInMarkdown$1(options, path) ? "" : semi]);
31541 // Babel extension.
31543 case "ParenthesizedExpression":
31544 return concat$6(["(", path.call(print, "expression"), ")"]);
31546 case "AssignmentExpression":
31547 return printAssignment(n.left, path.call(print, "left"), concat$6([" ", n.operator]), n.right, path.call(print, "right"), options);
31549 case "BinaryExpression":
31550 case "LogicalExpression":
31551 case "NGPipeExpression":
31553 var _parent = path.getParentNode();
31555 var parentParent = path.getParentNode(1);
31556 var isInsideParenthesis = n !== _parent.body && (_parent.type === "IfStatement" || _parent.type === "WhileStatement" || _parent.type === "SwitchStatement" || _parent.type === "DoWhileStatement");
31558 var _parts = printBinaryishExpressions(path, print, options,
31560 false, isInsideParenthesis); // if (
31561 // this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft
31564 // looks super weird, we want to break the children if the parent breaks
31567 // this.hasPlugin("dynamicImports") &&
31568 // this.lookahead().type === tt.parenLeft
31572 if (isInsideParenthesis) {
31573 return concat$6(_parts);
31574 } // Break between the parens in
31575 // unaries or in a member or specific call expression, i.e.
31584 if ((_parent.type === "CallExpression" || _parent.type === "OptionalCallExpression") && _parent.callee === n || _parent.type === "UnaryExpression" || (_parent.type === "MemberExpression" || _parent.type === "OptionalMemberExpression") && !_parent.computed) {
31585 return group$2(concat$6([indent$3(concat$6([softline$2, concat$6(_parts)])), softline$2]));
31586 } // Avoid indenting sub-expressions in some cases where the first sub-expression is already
31587 // indented accordingly. We should indent sub-expressions where the first case isn't indented.
31590 var shouldNotIndent = _parent.type === "ReturnStatement" || _parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" || 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 !== "CallExpression" && parentParent.type !== "OptionalCallExpression";
31591 var shouldIndentIfInlining = _parent.type === "AssignmentExpression" || _parent.type === "VariableDeclarator" || _parent.type === "ClassProperty" || _parent.type === "TSAbstractClassProperty" || _parent.type === "ClassPrivateProperty" || _parent.type === "ObjectProperty" || _parent.type === "Property";
31592 var samePrecedenceSubExpression = isBinaryish$1(n.left) && shouldFlatten$1(n.operator, n.left.operator);
31594 if (shouldNotIndent || shouldInlineLogicalExpression(n) && !samePrecedenceSubExpression || !shouldInlineLogicalExpression(n) && shouldIndentIfInlining) {
31595 return group$2(concat$6(_parts));
31598 if (_parts.length === 0) {
31600 } // If the right part is a JSX node, we include it in a separate group to
31601 // prevent it breaking the whole chain, so we can print the expression like:
31610 var hasJSX = isJSXNode$1(n.right);
31611 var rest = concat$6(hasJSX ? _parts.slice(1, -1) : _parts.slice(1));
31612 var groupId = Symbol("logicalChain-" + ++uid);
31613 var chain = group$2(concat$6([// Don't include the initial expression in the indentation
31614 // level. The first item is guaranteed to be the first
31615 // left-most expression.
31616 _parts.length > 0 ? _parts[0] : "", indent$3(rest)]), {
31624 var jsxPart = getLast$2(_parts);
31625 return group$2(concat$6([chain, ifBreak$1(indent$3(jsxPart), jsxPart, {
31630 case "AssignmentPattern":
31631 return concat$6([path.call(print, "left"), " = ", path.call(print, "right")]);
31633 case "TSTypeAssertion":
31635 var shouldBreakAfterCast = !(n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression");
31636 var castGroup = group$2(concat$6(["<", indent$3(concat$6([softline$2, path.call(print, "typeAnnotation")])), softline$2, ">"]));
31637 var exprContents = concat$6([ifBreak$1("("), indent$3(concat$6([softline$2, path.call(print, "expression")])), softline$2, ifBreak$1(")")]);
31639 if (shouldBreakAfterCast) {
31640 return conditionalGroup$1([concat$6([castGroup, path.call(print, "expression")]), concat$6([castGroup, group$2(exprContents, {
31642 })]), concat$6([castGroup, path.call(print, "expression")])]);
31645 return group$2(concat$6([castGroup, path.call(print, "expression")]));
31648 case "OptionalMemberExpression":
31649 case "MemberExpression":
31651 var _parent2 = path.getParentNode();
31653 var firstNonMemberParent;
31657 firstNonMemberParent = path.getParentNode(i);
31659 } while (firstNonMemberParent && (firstNonMemberParent.type === "MemberExpression" || firstNonMemberParent.type === "OptionalMemberExpression" || firstNonMemberParent.type === "TSNonNullExpression"));
31661 var 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" && _parent2.type !== "MemberExpression" && _parent2.type !== "OptionalMemberExpression";
31662 return concat$6([path.call(print, "object"), shouldInline ? printMemberLookup(path, options, print) : group$2(indent$3(concat$6([softline$2, printMemberLookup(path, options, print)])))]);
31665 case "MetaProperty":
31666 return concat$6([path.call(print, "meta"), ".", path.call(print, "property")]);
31668 case "BindExpression":
31670 parts.push(path.call(print, "object"));
31673 parts.push(group$2(indent$3(concat$6([softline$2, printBindExpressionCallee(path, options, print)]))));
31674 return concat$6(parts);
31678 return concat$6([n.name, printOptionalToken(path), printTypeAnnotation(path, options, print)]);
31681 case "V8IntrinsicIdentifier":
31682 return concat$6(["%", n.name]);
31684 case "SpreadElement":
31685 case "SpreadElementPattern":
31686 case "RestProperty":
31687 case "SpreadProperty":
31688 case "SpreadPropertyPattern":
31689 case "RestElement":
31690 case "ObjectTypeSpreadProperty":
31691 return concat$6(["...", path.call(print, "argument"), printTypeAnnotation(path, options, print)]);
31693 case "FunctionDeclaration":
31694 case "FunctionExpression":
31695 parts.push(printFunctionDeclaration(path, print, options));
31701 return concat$6(parts);
31703 case "ArrowFunctionExpression":
31706 parts.push("async ");
31709 if (shouldPrintParamsWithoutParens(path, options)) {
31710 parts.push(path.call(print, "params", 0));
31712 parts.push(group$2(concat$6([printFunctionParams(path, print, options,
31714 args && (args.expandLastArg || args.expandFirstArg),
31715 /* printTypeParams */
31716 true), printReturnType(path, print, options)])));
31719 var dangling = comments.printDanglingComments(path, options,
31721 true, function (comment) {
31722 var nextCharacter = getNextNonSpaceNonCommentCharacterIndex$2(options.originalText, comment, options);
31723 return options.originalText.substr(nextCharacter, 2) === "=>";
31727 parts.push(" ", dangling);
31731 var body = path.call(function (bodyPath) {
31732 return print(bodyPath, args);
31733 }, "body"); // We want to always keep these types of nodes on the same line
31736 if (!hasLeadingOwnLineComment$1(options.originalText, n.body, options) && (n.body.type === "ArrayExpression" || n.body.type === "ObjectExpression" || n.body.type === "BlockStatement" || isJSXNode$1(n.body) || isTemplateOnItsOwnLine$1(n.body, options.originalText, options) || n.body.type === "ArrowFunctionExpression" || n.body.type === "DoExpression")) {
31737 return group$2(concat$6([concat$6(parts), " ", body]));
31738 } // We handle sequence expressions as the body of arrows specially,
31739 // so that the required parentheses end up on their own lines.
31742 if (n.body.type === "SequenceExpression") {
31743 return group$2(concat$6([concat$6(parts), group$2(concat$6([" (", indent$3(concat$6([softline$2, body])), softline$2, ")"]))]));
31744 } // if the arrow function is expanded as last argument, we are adding a
31745 // level of indentation and need to add a softline to align the closing )
31746 // with the opening (, or if it's inside a JSXExpression (e.g. an attribute)
31747 // we should align the expression's closing } with the line with the opening {.
31750 var shouldAddSoftLine = (args && args.expandLastArg || path.getParentNode().type === "JSXExpressionContainer") && !(n.comments && n.comments.length);
31751 var printTrailingComma = args && args.expandLastArg && shouldPrintComma(options, "all"); // In order to avoid confusion between
31755 var shouldAddParens = n.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken$1(n.body,
31756 /* forbidFunctionAndClass */
31758 return group$2(concat$6([concat$6(parts), group$2(concat$6([indent$3(concat$6([line$2, shouldAddParens ? ifBreak$1("", "(") : "", body, shouldAddParens ? ifBreak$1("", ")") : ""])), shouldAddSoftLine ? concat$6([ifBreak$1(printTrailingComma ? "," : ""), softline$2]) : ""]))]));
31761 case "YieldExpression":
31762 parts.push("yield");
31769 parts.push(" ", path.call(print, "argument"));
31772 return concat$6(parts);
31774 case "AwaitExpression":
31776 parts.push("await ", path.call(print, "argument"));
31778 var _parent3 = path.getParentNode();
31780 if ((_parent3.type === "CallExpression" || _parent3.type === "OptionalCallExpression") && _parent3.callee === n || (_parent3.type === "MemberExpression" || _parent3.type === "OptionalMemberExpression") && _parent3.object === n) {
31781 return group$2(concat$6([indent$3(concat$6([softline$2, concat$6(parts)])), softline$2]));
31784 return concat$6(parts);
31787 case "ImportSpecifier":
31788 if (n.importKind) {
31789 parts.push(path.call(print, "importKind"), " ");
31792 parts.push(path.call(print, "imported"));
31794 if (n.local && n.local.name !== n.imported.name) {
31795 parts.push(" as ", path.call(print, "local"));
31798 return concat$6(parts);
31800 case "ExportSpecifier":
31801 parts.push(path.call(print, "local"));
31803 if (n.exported && n.exported.name !== n.local.name) {
31804 parts.push(" as ", path.call(print, "exported"));
31807 return concat$6(parts);
31809 case "ImportNamespaceSpecifier":
31810 parts.push("* as ");
31811 parts.push(path.call(print, "local"));
31812 return concat$6(parts);
31814 case "ImportDefaultSpecifier":
31815 return path.call(print, "local");
31817 case "TSExportAssignment":
31818 return concat$6(["export = ", path.call(print, "expression"), semi]);
31820 case "ExportDefaultDeclaration":
31821 case "ExportNamedDeclaration":
31822 return printExportDeclaration(path, options, print);
31824 case "ExportAllDeclaration":
31825 parts.push("export ");
31827 if (n.exportKind === "type") {
31828 parts.push("type ");
31831 parts.push("* from ", path.call(print, "source"), semi);
31832 return concat$6(parts);
31834 case "ExportNamespaceSpecifier":
31835 case "ExportDefaultSpecifier":
31836 return path.call(print, "exported");
31838 case "ImportDeclaration":
31840 parts.push("import ");
31842 if (n.importKind && n.importKind !== "value") {
31843 parts.push(n.importKind + " ");
31846 var standalones = [];
31849 if (n.specifiers && n.specifiers.length > 0) {
31850 path.each(function (specifierPath) {
31851 var value = specifierPath.getValue();
31853 if (value.type === "ImportDefaultSpecifier" || value.type === "ImportNamespaceSpecifier") {
31854 standalones.push(print(specifierPath));
31856 grouped.push(print(specifierPath));
31860 if (standalones.length > 0) {
31861 parts.push(join$4(", ", standalones));
31864 if (standalones.length > 0 && grouped.length > 0) {
31868 if (grouped.length === 1 && standalones.length === 0 && n.specifiers && !n.specifiers.some(function (node) {
31869 return node.comments;
31871 parts.push(concat$6(["{", options.bracketSpacing ? " " : "", concat$6(grouped), options.bracketSpacing ? " " : "", "}"]));
31872 } else if (grouped.length >= 1) {
31873 parts.push(group$2(concat$6(["{", indent$3(concat$6([options.bracketSpacing ? line$2 : softline$2, join$4(concat$6([",", line$2]), grouped)])), ifBreak$1(shouldPrintComma(options) ? "," : ""), options.bracketSpacing ? line$2 : softline$2, "}"])));
31876 parts.push(" from ");
31877 } else if (n.importKind && n.importKind === "type" || // import {} from 'x'
31878 /{\s*}/.test(options.originalText.slice(options.locStart(n), options.locStart(n.source)))) {
31879 parts.push("{} from ");
31882 parts.push(path.call(print, "source"), semi);
31883 return concat$6(parts);
31889 case "TSModuleBlock":
31890 case "BlockStatement":
31892 var naked = path.call(function (bodyPath) {
31893 return printStatementSequence(bodyPath, options, print);
31895 var hasContent = n.body.find(function (node) {
31896 return node.type !== "EmptyStatement";
31898 var hasDirectives = n.directives && n.directives.length > 0;
31900 var _parent4 = path.getParentNode();
31902 var _parentParent = path.getParentNode(1);
31904 if (!hasContent && !hasDirectives && !hasDanglingComments$1(n) && (_parent4.type === "ArrowFunctionExpression" || _parent4.type === "FunctionExpression" || _parent4.type === "FunctionDeclaration" || _parent4.type === "ObjectMethod" || _parent4.type === "ClassMethod" || _parent4.type === "ClassPrivateMethod" || _parent4.type === "ForStatement" || _parent4.type === "WhileStatement" || _parent4.type === "DoWhileStatement" || _parent4.type === "DoExpression" || _parent4.type === "CatchClause" && !_parentParent.finalizer || _parent4.type === "TSModuleDeclaration")) {
31908 parts.push("{"); // Babel 6
31910 if (hasDirectives) {
31911 path.each(function (childPath) {
31912 parts.push(indent$3(concat$6([hardline$4, print(childPath), semi])));
31914 if (isNextLineEmpty$2(options.originalText, childPath.getValue(), options)) {
31915 parts.push(hardline$4);
31921 parts.push(indent$3(concat$6([hardline$4, naked])));
31924 parts.push(comments.printDanglingComments(path, options));
31925 parts.push(hardline$4, "}");
31926 return concat$6(parts);
31929 case "ReturnStatement":
31930 parts.push("return");
31933 if (returnArgumentHasLeadingComment$1(options, n.argument)) {
31934 parts.push(concat$6([" (", indent$3(concat$6([hardline$4, path.call(print, "argument")])), hardline$4, ")"]));
31935 } else if (n.argument.type === "LogicalExpression" || n.argument.type === "BinaryExpression" || n.argument.type === "SequenceExpression") {
31936 parts.push(group$2(concat$6([ifBreak$1(" (", " "), indent$3(concat$6([softline$2, path.call(print, "argument")])), softline$2, ifBreak$1(")")])));
31938 parts.push(" ", path.call(print, "argument"));
31942 if (hasDanglingComments$1(n)) {
31943 parts.push(" ", comments.printDanglingComments(path, options,
31949 return concat$6(parts);
31951 case "NewExpression":
31952 case "OptionalCallExpression":
31953 case "CallExpression":
31955 var isNew = n.type === "NewExpression";
31956 var optional = printOptionalToken(path);
31958 if ( // We want to keep CommonJS- and AMD-style require calls, and AMD-style
31959 // define calls, as a unit.
31960 // e.g. `define(["some/lib", (lib) => {`
31961 !isNew && n.callee.type === "Identifier" && (n.callee.name === "require" || n.callee.name === "define") || // Template literals as single arguments
31962 n.arguments.length === 1 && isTemplateOnItsOwnLine$1(n.arguments[0], options.originalText, options) || // Keep test declarations on a single line
31963 // e.g. `it('long name', () => {`
31964 !isNew && isTestCall$1(n, path.getParentNode())) {
31965 return concat$6([isNew ? "new " : "", path.call(print, "callee"), optional, printFunctionTypeParameters(path, options, print), concat$6(["(", join$4(", ", path.map(print, "arguments")), ")"])]);
31966 } // Inline Flow annotation comments following Identifiers in Call nodes need to
31967 // stay with the Identifier. For example:
31969 // foo /*:: <SomeGeneric> */(bar);
31971 // Here, we ensure that such comments stay between the Identifier and the Callee.
31974 var isIdentifierWithFlowAnnotation = n.callee.type === "Identifier" && hasFlowAnnotationComment$1(n.callee.trailingComments);
31976 if (isIdentifierWithFlowAnnotation) {
31977 n.callee.trailingComments[0].printed = true;
31978 } // We detect calls on member lookups and possibly print them in a
31979 // special chain format. See `printMemberChain` for more info.
31982 if (!isNew && isMemberish$1(n.callee)) {
31983 return printMemberChain(path, options, print);
31986 var contents = concat$6([isNew ? "new " : "", path.call(print, "callee"), optional, isIdentifierWithFlowAnnotation ? `/*:: ${n.callee.trailingComments[0].value.substring(2).trim()} */` : "", printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]); // We group here when the callee is itself a call expression.
31987 // See `isLongCurriedCallExpression` for more info.
31989 if (isCallOrOptionalCallExpression$1(n.callee)) {
31990 return group$2(contents);
31996 case "TSInterfaceDeclaration":
31998 parts.push("declare ");
32001 parts.push(n.abstract ? "abstract " : "", printTypeScriptModifiers(path, options, print), "interface ", path.call(print, "id"), n.typeParameters ? path.call(print, "typeParameters") : "", " ");
32003 if (n.extends && n.extends.length) {
32004 parts.push(group$2(indent$3(concat$6([softline$2, "extends ", (n.extends.length === 1 ? identity$1 : indent$3)(join$4(concat$6([",", line$2]), path.map(print, "extends"))), " "]))));
32007 parts.push(path.call(print, "body"));
32008 return concat$6(parts);
32010 case "ObjectTypeInternalSlot":
32011 return concat$6([n.static ? "static " : "", "[[", path.call(print, "id"), "]]", printOptionalToken(path), n.method ? "" : ": ", path.call(print, "value")]);
32013 case "ObjectExpression":
32014 case "ObjectPattern":
32015 case "ObjectTypeAnnotation":
32016 case "TSInterfaceBody":
32017 case "TSTypeLiteral":
32019 var propertiesField;
32021 if (n.type === "TSTypeLiteral") {
32022 propertiesField = "members";
32023 } else if (n.type === "TSInterfaceBody") {
32024 propertiesField = "body";
32026 propertiesField = "properties";
32029 var isTypeAnnotation = n.type === "ObjectTypeAnnotation";
32032 if (isTypeAnnotation) {
32033 fields.push("indexers", "callProperties", "internalSlots");
32036 fields.push(propertiesField);
32037 var firstProperty = fields.map(function (field) {
32038 return n[field][0];
32039 }).sort(function (a, b) {
32040 return options.locStart(a) - options.locStart(b);
32043 var _parent5 = path.getParentNode(0);
32045 var isFlowInterfaceLikeBody = isTypeAnnotation && _parent5 && (_parent5.type === "InterfaceDeclaration" || _parent5.type === "DeclareInterface" || _parent5.type === "DeclareClass") && path.getName() === "body";
32046 var shouldBreak = n.type === "TSInterfaceBody" || isFlowInterfaceLikeBody || n.type === "ObjectPattern" && _parent5.type !== "FunctionDeclaration" && _parent5.type !== "FunctionExpression" && _parent5.type !== "ArrowFunctionExpression" && _parent5.type !== "ObjectMethod" && _parent5.type !== "ClassMethod" && _parent5.type !== "ClassPrivateMethod" && _parent5.type !== "AssignmentPattern" && _parent5.type !== "CatchClause" && n.properties.some(function (property) {
32047 return property.value && (property.value.type === "ObjectPattern" || property.value.type === "ArrayPattern");
32048 }) || n.type !== "ObjectPattern" && firstProperty && hasNewlineInRange$2(options.originalText, options.locStart(n), options.locStart(firstProperty));
32049 var separator = isFlowInterfaceLikeBody ? ";" : n.type === "TSInterfaceBody" || n.type === "TSTypeLiteral" ? ifBreak$1(semi, ";") : ",";
32050 var leftBrace = n.exact ? "{|" : "{";
32051 var rightBrace = n.exact ? "|}" : "}"; // Unfortunately, things are grouped together in the ast can be
32052 // interleaved in the source code. So we need to reorder them before
32055 var propsAndLoc = [];
32056 fields.forEach(function (field) {
32057 path.each(function (childPath) {
32058 var node = childPath.getValue();
32061 printed: print(childPath),
32062 loc: options.locStart(node)
32066 var separatorParts = [];
32067 var props = propsAndLoc.sort(function (a, b) {
32068 return a.loc - b.loc;
32069 }).map(function (prop) {
32070 var result = concat$6(separatorParts.concat(group$2(prop.printed)));
32071 separatorParts = [separator, line$2];
32073 if ((prop.node.type === "TSPropertySignature" || prop.node.type === "TSMethodSignature" || prop.node.type === "TSConstructSignatureDeclaration") && hasNodeIgnoreComment$2(prop.node)) {
32074 separatorParts.shift();
32077 if (isNextLineEmpty$2(options.originalText, prop.node, options)) {
32078 separatorParts.push(hardline$4);
32085 props.push(concat$6(separatorParts.concat(group$2("..."))));
32088 var lastElem = getLast$2(n[propertiesField]);
32089 var canHaveTrailingSeparator = !(lastElem && (lastElem.type === "RestProperty" || lastElem.type === "RestElement" || hasNodeIgnoreComment$2(lastElem) || n.inexact));
32092 if (props.length === 0) {
32093 if (!hasDanglingComments$1(n)) {
32094 return concat$6([leftBrace, rightBrace, printTypeAnnotation(path, options, print)]);
32097 content = group$2(concat$6([leftBrace, comments.printDanglingComments(path, options), softline$2, rightBrace, printOptionalToken(path), printTypeAnnotation(path, options, print)]));
32099 content = concat$6([leftBrace, indent$3(concat$6([options.bracketSpacing ? line$2 : softline$2, concat$6(props)])), ifBreak$1(canHaveTrailingSeparator && (separator !== "," || shouldPrintComma(options)) ? separator : ""), concat$6([options.bracketSpacing ? line$2 : softline$2, rightBrace]), printOptionalToken(path), printTypeAnnotation(path, options, print)]);
32100 } // If we inline the object as first argument of the parent, we don't want
32101 // to create another group so that the object breaks before the return
32105 var parentParentParent = path.getParentNode(2);
32107 if (n.type === "ObjectPattern" && _parent5 && shouldHugArguments(_parent5) && !n.decorators && _parent5.params[0] === n || shouldHugType(n) && parentParentParent && shouldHugArguments(parentParentParent) && parentParentParent.params[0].typeAnnotation && parentParentParent.params[0].typeAnnotation.typeAnnotation === n) {
32111 return group$2(content, {
32117 case "ObjectProperty": // Non-standard AST node type.
32120 if (n.method || n.kind === "get" || n.kind === "set") {
32121 return printMethod(path, options, print);
32125 parts.push(path.call(print, "value"));
32127 parts.push(printAssignment(n.key, printPropertyKey(path, options, print), ":", n.value, path.call(print, "value"), options));
32130 return concat$6(parts);
32133 case "ClassMethod":
32134 case "ClassPrivateMethod":
32135 case "MethodDefinition":
32136 case "TSAbstractMethodDefinition":
32137 if (n.decorators && n.decorators.length !== 0) {
32138 parts.push(printDecorators(path, options, print));
32141 if (n.accessibility) {
32142 parts.push(n.accessibility + " ");
32146 parts.push("static ");
32149 if (n.type === "TSAbstractMethodDefinition") {
32150 parts.push("abstract ");
32153 parts.push(printMethod(path, options, print));
32154 return concat$6(parts);
32156 case "ObjectMethod":
32157 return printMethod(path, options, print);
32160 return concat$6(["@", path.call(print, "expression"), path.call(print, "callee")]);
32162 case "ArrayExpression":
32163 case "ArrayPattern":
32164 if (n.elements.length === 0) {
32165 if (!hasDanglingComments$1(n)) {
32168 parts.push(group$2(concat$6(["[", comments.printDanglingComments(path, options), softline$2, "]"])));
32171 var _lastElem = getLast$2(n.elements);
32173 var canHaveTrailingComma = !(_lastElem && _lastElem.type === "RestElement"); // JavaScript allows you to have empty elements in an array which
32174 // changes its length based on the number of commas. The algorithm
32175 // is that if the last argument is null, we need to force insert
32176 // a comma to ensure JavaScript recognizes it.
32177 // [,].length === 1
32178 // [1,].length === 1
32179 // [1,,].length === 2
32181 // Note that getLast returns null if the array is empty, but
32182 // we already check for an empty array just above so we are safe
32184 var needsForcedTrailingComma = canHaveTrailingComma && _lastElem === null;
32186 var _shouldBreak = n.elements.length > 1 && n.elements.every(function (element, i, elements) {
32187 var elementType = element && element.type;
32189 if (elementType !== "ArrayExpression" && elementType !== "ObjectExpression") {
32193 var nextElement = elements[i + 1];
32195 if (nextElement && elementType !== nextElement.type) {
32199 var itemsKey = elementType === "ArrayExpression" ? "elements" : "properties";
32200 return element[itemsKey] && element[itemsKey].length > 1;
32203 parts.push(group$2(concat$6(["[", indent$3(concat$6([softline$2, printArrayItems(path, options, "elements", print)])), needsForcedTrailingComma ? "," : "", ifBreak$1(canHaveTrailingComma && !needsForcedTrailingComma && shouldPrintComma(options) ? "," : ""), comments.printDanglingComments(path, options,
32205 true), softline$2, "]"]), {
32206 shouldBreak: _shouldBreak
32210 parts.push(printOptionalToken(path), printTypeAnnotation(path, options, print));
32211 return concat$6(parts);
32213 case "SequenceExpression":
32215 var _parent6 = path.getParentNode(0);
32217 if (_parent6.type === "ExpressionStatement" || _parent6.type === "ForStatement") {
32218 // For ExpressionStatements and for-loop heads, which are among
32219 // the few places a SequenceExpression appears unparenthesized, we want
32220 // to indent expressions after the first.
32222 path.each(function (p) {
32223 if (p.getName() === 0) {
32224 _parts2.push(print(p));
32226 _parts2.push(",", indent$3(concat$6([line$2, print(p)])));
32229 return group$2(concat$6(_parts2));
32232 return group$2(concat$6([join$4(concat$6([",", line$2]), path.map(print, "expressions"))]));
32235 case "ThisExpression":
32241 case "NullLiteral":
32242 // Babel 6 Literal split
32245 case "RegExpLiteral":
32246 // Babel 6 Literal split
32247 return printRegex(n);
32249 case "NumericLiteral":
32250 // Babel 6 Literal split
32251 return printNumber$1(n.extra.raw);
32253 case "BigIntLiteral":
32254 // babel: n.extra.raw, typescript: n.raw, flow: n.bigint
32255 return (n.bigint || (n.extra ? n.extra.raw : n.raw)).toLowerCase();
32257 case "BooleanLiteral": // Babel 6 Literal split
32259 case "StringLiteral": // Babel 6 Literal split
32264 return printRegex(n.regex);
32267 if (typeof n.value === "number") {
32268 return printNumber$1(n.raw);
32271 if (typeof n.value !== "string") {
32272 return "" + n.value;
32273 } // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2
32274 // See corresponding workaround in needs-parens.js
32277 var grandParent = path.getParentNode(1);
32278 var isTypeScriptDirective = options.parser === "typescript" && typeof n.value === "string" && grandParent && (grandParent.type === "Program" || grandParent.type === "BlockStatement");
32279 return nodeStr(n, options, isTypeScriptDirective);
32283 return path.call(print, "value");
32286 case "DirectiveLiteral":
32287 return nodeStr(n, options);
32289 case "UnaryExpression":
32290 parts.push(n.operator);
32292 if (/[a-z]$/.test(n.operator)) {
32296 if (n.argument.comments && n.argument.comments.length > 0) {
32297 parts.push(group$2(concat$6(["(", indent$3(concat$6([softline$2, path.call(print, "argument")])), softline$2, ")"])));
32299 parts.push(path.call(print, "argument"));
32302 return concat$6(parts);
32304 case "UpdateExpression":
32305 parts.push(path.call(print, "argument"), n.operator);
32311 return concat$6(parts);
32313 case "ConditionalExpression":
32314 return printTernaryOperator(path, options, print, {
32315 beforeParts: function beforeParts() {
32316 return [path.call(print, "test")];
32318 afterParts: function afterParts(breakClosingParen) {
32319 return [breakClosingParen ? softline$2 : ""];
32321 shouldCheckJsx: true,
32322 conditionalNodeType: "ConditionalExpression",
32323 consequentNodePropertyName: "consequent",
32324 alternateNodePropertyName: "alternate",
32325 testNodePropertyName: "test",
32329 case "VariableDeclaration":
32331 var printed = path.map(function (childPath) {
32332 return print(childPath);
32333 }, "declarations"); // We generally want to terminate all variable declarations with a
32334 // semicolon, except when they in the () part of for loops.
32336 var parentNode = path.getParentNode();
32337 var isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement" || parentNode.type === "ForAwaitStatement";
32338 var hasValue = n.declarations.some(function (decl) {
32343 if (printed.length === 1 && !n.declarations[0].comments) {
32344 firstVariable = printed[0];
32345 } else if (printed.length > 0) {
32346 // Indent first var to comply with eslint one-var rule
32347 firstVariable = indent$3(printed[0]);
32350 parts = [n.declare ? "declare " : "", n.kind, firstVariable ? concat$6([" ", firstVariable]) : "", indent$3(concat$6(printed.slice(1).map(function (p) {
32351 return concat$6([",", hasValue && !isParentForLoop ? hardline$4 : line$2, p]);
32354 if (!(isParentForLoop && parentNode.body !== n)) {
32358 return group$2(concat$6(parts));
32361 case "TSTypeAliasDeclaration":
32364 parts.push("declare ");
32367 var _printed = printAssignmentRight(n.id, n.typeAnnotation, n.typeAnnotation && path.call(print, "typeAnnotation"), options);
32369 parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", _printed, semi);
32370 return group$2(concat$6(parts));
32373 case "VariableDeclarator":
32374 return printAssignment(n.id, path.call(print, "id"), " =", n.init, n.init && path.call(print, "init"), options);
32376 case "WithStatement":
32377 return group$2(concat$6(["with (", path.call(print, "object"), ")", adjustClause(n.body, path.call(print, "body"))]));
32379 case "IfStatement":
32381 var con = adjustClause(n.consequent, path.call(print, "consequent"));
32382 var opening = group$2(concat$6(["if (", group$2(concat$6([indent$3(concat$6([softline$2, path.call(print, "test")])), softline$2])), ")", con]));
32383 parts.push(opening);
32386 var commentOnOwnLine = hasTrailingComment$1(n.consequent) && n.consequent.comments.some(function (comment) {
32387 return comment.trailing && !comments$1.isBlockComment(comment);
32388 }) || needsHardlineAfterDanglingComment$1(n);
32389 var elseOnSameLine = n.consequent.type === "BlockStatement" && !commentOnOwnLine;
32390 parts.push(elseOnSameLine ? " " : hardline$4);
32392 if (hasDanglingComments$1(n)) {
32393 parts.push(comments.printDanglingComments(path, options, true), commentOnOwnLine ? hardline$4 : " ");
32396 parts.push("else", group$2(adjustClause(n.alternate, path.call(print, "alternate"), n.alternate.type === "IfStatement")));
32399 return concat$6(parts);
32402 case "ForStatement":
32404 var _body = adjustClause(n.body, path.call(print, "body")); // We want to keep dangling comments above the loop to stay consistent.
32405 // Any comment positioned between the for statement and the parentheses
32406 // is going to be printed before the statement.
32409 var _dangling = comments.printDanglingComments(path, options,
32413 var printedComments = _dangling ? concat$6([_dangling, softline$2]) : "";
32415 if (!n.init && !n.test && !n.update) {
32416 return concat$6([printedComments, group$2(concat$6(["for (;;)", _body]))]);
32419 return concat$6([printedComments, group$2(concat$6(["for (", group$2(concat$6([indent$3(concat$6([softline$2, path.call(print, "init"), ";", line$2, path.call(print, "test"), ";", line$2, path.call(print, "update")])), softline$2])), ")", _body]))]);
32422 case "WhileStatement":
32423 return group$2(concat$6(["while (", group$2(concat$6([indent$3(concat$6([softline$2, path.call(print, "test")])), softline$2])), ")", adjustClause(n.body, path.call(print, "body"))]));
32425 case "ForInStatement":
32426 // Note: esprima can't actually parse "for each (".
32427 return group$2(concat$6([n.each ? "for each (" : "for (", path.call(print, "left"), " in ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))]));
32429 case "ForOfStatement":
32430 case "ForAwaitStatement":
32432 // Babel 7 removed ForAwaitStatement in favor of ForOfStatement
32433 // with `"await": true`:
32434 // https://github.com/estree/estree/pull/138
32435 var isAwait = n.type === "ForAwaitStatement" || n.await;
32436 return group$2(concat$6(["for", isAwait ? " await" : "", " (", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))]));
32439 case "DoWhileStatement":
32441 var clause = adjustClause(n.body, path.call(print, "body"));
32442 var doBody = group$2(concat$6(["do", clause]));
32445 if (n.body.type === "BlockStatement") {
32448 parts.push(hardline$4);
32451 parts.push("while (");
32452 parts.push(group$2(concat$6([indent$3(concat$6([softline$2, path.call(print, "test")])), softline$2])), ")", semi);
32453 return concat$6(parts);
32456 case "DoExpression":
32457 return concat$6(["do ", path.call(print, "body")]);
32459 case "BreakStatement":
32460 parts.push("break");
32463 parts.push(" ", path.call(print, "label"));
32467 return concat$6(parts);
32469 case "ContinueStatement":
32470 parts.push("continue");
32473 parts.push(" ", path.call(print, "label"));
32477 return concat$6(parts);
32479 case "LabeledStatement":
32480 if (n.body.type === "EmptyStatement") {
32481 return concat$6([path.call(print, "label"), ":;"]);
32484 return concat$6([path.call(print, "label"), ": ", path.call(print, "body")]);
32486 case "TryStatement":
32487 return concat$6(["try ", path.call(print, "block"), n.handler ? concat$6([" ", path.call(print, "handler")]) : "", n.finalizer ? concat$6([" finally ", path.call(print, "finalizer")]) : ""]);
32489 case "CatchClause":
32491 var hasComments = n.param.comments && n.param.comments.some(function (comment) {
32492 return !comments$1.isBlockComment(comment) || comment.leading && hasNewline$3(options.originalText, options.locEnd(comment)) || comment.trailing && hasNewline$3(options.originalText, options.locStart(comment), {
32496 var param = path.call(print, "param");
32497 return concat$6(["catch ", hasComments ? concat$6(["(", indent$3(concat$6([softline$2, param])), softline$2, ") "]) : concat$6(["(", param, ") "]), path.call(print, "body")]);
32500 return concat$6(["catch ", path.call(print, "body")]);
32502 case "ThrowStatement":
32503 return concat$6(["throw ", path.call(print, "argument"), semi]);
32504 // Note: ignoring n.lexical because it has no printing consequences.
32506 case "SwitchStatement":
32507 return concat$6([group$2(concat$6(["switch (", indent$3(concat$6([softline$2, path.call(print, "discriminant")])), softline$2, ")"])), " {", n.cases.length > 0 ? indent$3(concat$6([hardline$4, join$4(hardline$4, path.map(function (casePath) {
32508 var caseNode = casePath.getValue();
32509 return concat$6([casePath.call(print), n.cases.indexOf(caseNode) !== n.cases.length - 1 && isNextLineEmpty$2(options.originalText, caseNode, options) ? hardline$4 : ""]);
32510 }, "cases"))])) : "", hardline$4, "}"]);
32515 parts.push("case ", path.call(print, "test"), ":");
32517 parts.push("default:");
32520 var consequent = n.consequent.filter(function (node) {
32521 return node.type !== "EmptyStatement";
32524 if (consequent.length > 0) {
32525 var cons = path.call(function (consequentPath) {
32526 return printStatementSequence(consequentPath, options, print);
32528 parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? concat$6([" ", cons]) : indent$3(concat$6([hardline$4, cons])));
32531 return concat$6(parts);
32533 // JSX extensions below.
32535 case "DebuggerStatement":
32536 return concat$6(["debugger", semi]);
32538 case "JSXAttribute":
32539 parts.push(path.call(print, "name"));
32544 if (isStringLiteral$1(n.value)) {
32545 var raw = rawText$1(n.value); // Unescape all quotes so we get an accurate preferred quote
32547 var final = raw.replace(/'/g, "'").replace(/"/g, '"');
32548 var quote = getPreferredQuote$1(final, options.jsxSingleQuote ? "'" : '"');
32550 var _escape = quote === "'" ? "'" : """;
32552 final = final.slice(1, -1).replace(new RegExp(quote, "g"), _escape);
32553 res = concat$6([quote, final, quote]);
32555 res = path.call(print, "value");
32558 parts.push("=", res);
32561 return concat$6(parts);
32563 case "JSXIdentifier":
32564 return "" + n.name;
32566 case "JSXNamespacedName":
32567 return join$4(":", [path.call(print, "namespace"), path.call(print, "name")]);
32569 case "JSXMemberExpression":
32570 return join$4(".", [path.call(print, "object"), path.call(print, "property")]);
32572 case "TSQualifiedName":
32573 return join$4(".", [path.call(print, "left"), path.call(print, "right")]);
32575 case "JSXSpreadAttribute":
32576 case "JSXSpreadChild":
32578 return concat$6(["{", path.call(function (p) {
32579 var printed = concat$6(["...", print(p)]);
32580 var n = p.getValue();
32582 if (!n.comments || !n.comments.length) {
32586 return concat$6([indent$3(concat$6([softline$2, comments.printComments(p, function () {
32588 }, options)])), softline$2]);
32589 }, n.type === "JSXSpreadAttribute" ? "argument" : "expression"), "}"]);
32592 case "JSXExpressionContainer":
32594 var _parent7 = path.getParentNode(0);
32596 var preventInline = _parent7.type === "JSXAttribute" && n.expression.comments && n.expression.comments.length > 0;
32598 var _shouldInline = !preventInline && (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 === "JSXEmptyExpression" || n.expression.type === "TemplateLiteral" || n.expression.type === "TaggedTemplateExpression" || n.expression.type === "DoExpression" || isJSXNode$1(_parent7) && (n.expression.type === "ConditionalExpression" || isBinaryish$1(n.expression)));
32600 if (_shouldInline) {
32601 return group$2(concat$6(["{", path.call(print, "expression"), lineSuffixBoundary$1, "}"]));
32604 return group$2(concat$6(["{", indent$3(concat$6([softline$2, path.call(print, "expression")])), softline$2, lineSuffixBoundary$1, "}"]));
32607 case "JSXFragment":
32610 var elem = comments.printComments(path, function () {
32611 return printJSXElement(path, options, print);
32613 return maybeWrapJSXElementInParens(path, elem, options);
32616 case "JSXOpeningElement":
32618 var _n = path.getValue();
32620 var 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
32622 if (_n.selfClosing && !_n.attributes.length && !nameHasComments) {
32623 return concat$6(["<", path.call(print, "name"), path.call(print, "typeParameters"), " />"]);
32624 } // don't break up opening elements with a single long text attribute
32627 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:
32636 !nameHasComments && (!_n.attributes[0].comments || !_n.attributes[0].comments.length)) {
32637 return group$2(concat$6(["<", path.call(print, "name"), path.call(print, "typeParameters"), " ", concat$6(path.map(print, "attributes")), _n.selfClosing ? " />" : ">"]));
32640 var lastAttrHasTrailingComments = _n.attributes.length && hasTrailingComment$1(getLast$2(_n.attributes));
32641 var bracketSameLine = // Simple tags (no attributes and no comment in tag name) should be
32642 // kept unbroken regardless of `jsxBracketSameLine`
32643 !_n.attributes.length && !nameHasComments || options.jsxBracketSameLine && ( // We should print the bracket in a new line for the following cases:
32650 !nameHasComments || _n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a
32651 // string literal with newlines
32653 var _shouldBreak2 = _n.attributes && _n.attributes.some(function (attr) {
32654 return attr.value && isStringLiteral$1(attr.value) && attr.value.value.includes("\n");
32657 return group$2(concat$6(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$6([indent$3(concat$6(path.map(function (attr) {
32658 return concat$6([line$2, print(attr)]);
32659 }, "attributes"))), _n.selfClosing ? line$2 : bracketSameLine ? ">" : softline$2]), _n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), {
32660 shouldBreak: _shouldBreak2
32664 case "JSXClosingElement":
32665 return concat$6(["</", path.call(print, "name"), ">"]);
32667 case "JSXOpeningFragment":
32668 case "JSXClosingFragment":
32670 var hasComment = n.comments && n.comments.length;
32671 var hasOwnLineComment = hasComment && !n.comments.every(comments$1.isBlockComment);
32672 var isOpeningFragment = n.type === "JSXOpeningFragment";
32673 return concat$6([isOpeningFragment ? "<" : "</", indent$3(concat$6([hasOwnLineComment ? hardline$4 : hasComment && !isOpeningFragment ? " " : "", comments.printDanglingComments(path, options, true)])), hasOwnLineComment ? hardline$4 : "", ">"]);
32677 /* istanbul ignore next */
32678 throw new Error("JSXTest should be handled by JSXElement");
32680 case "JSXEmptyExpression":
32682 var requiresHardline = n.comments && !n.comments.every(comments$1.isBlockComment);
32683 return concat$6([comments.printDanglingComments(path, options,
32685 !requiresHardline), requiresHardline ? hardline$4 : ""]);
32689 if (!n.comments && n.body.length === 0) {
32693 return concat$6(["{", n.body.length > 0 ? indent$3(concat$6([hardline$4, path.call(function (bodyPath) {
32694 return printStatementSequence(bodyPath, options, print);
32695 }, "body")])) : comments.printDanglingComments(path, options), hardline$4, "}"]);
32697 case "ClassProperty":
32698 case "TSAbstractClassProperty":
32699 case "ClassPrivateProperty":
32701 if (n.decorators && n.decorators.length !== 0) {
32702 parts.push(printDecorators(path, options, print));
32705 if (n.accessibility) {
32706 parts.push(n.accessibility + " ");
32710 parts.push("declare ");
32714 parts.push("static ");
32717 if (n.type === "TSAbstractClassProperty") {
32718 parts.push("abstract ");
32722 parts.push("readonly ");
32725 var variance = getFlowVariance$1(n);
32728 parts.push(variance);
32731 parts.push(printPropertyKey(path, options, print), printOptionalToken(path), printTypeAnnotation(path, options, print));
32734 parts.push(" =", printAssignmentRight(n.key, n.value, path.call(print, "value"), options));
32738 return group$2(concat$6(parts));
32741 case "ClassDeclaration":
32742 case "ClassExpression":
32744 parts.push("declare ");
32747 parts.push(concat$6(printClass(path, options, print)));
32748 return concat$6(parts);
32750 case "TSInterfaceHeritage":
32751 parts.push(path.call(print, "expression"));
32753 if (n.typeParameters) {
32754 parts.push(path.call(print, "typeParameters"));
32757 return concat$6(parts);
32759 case "TemplateElement":
32760 return join$4(literalline$2, n.value.raw.split(/\r?\n/g));
32762 case "TemplateLiteral":
32764 var expressions = path.map(print, "expressions");
32766 var _parentNode = path.getParentNode();
32768 if (isJestEachTemplateLiteral$1(n, _parentNode)) {
32769 var _printed2 = printJestEachTemplateLiteral(n, expressions, options);
32776 var isSimple = isSimpleTemplateLiteral$1(n);
32779 expressions = expressions.map(function (doc) {
32780 return printDocToString$2(doc, Object.assign({}, options, {
32781 printWidth: Infinity
32786 parts.push(lineSuffixBoundary$1, "`");
32787 path.each(function (childPath) {
32788 var i = childPath.getName();
32789 parts.push(print(childPath));
32791 if (i < expressions.length) {
32792 // For a template literal of the following form:
32799 // the expression is on its own line (there is a \n in the previous
32800 // quasi literal), therefore we want to indent the JavaScript
32801 // expression inside at the beginning of ${ instead of the beginning
32803 var tabWidth = options.tabWidth;
32804 var quasi = childPath.getValue();
32805 var indentSize = getIndentSize$1(quasi.value.raw, tabWidth);
32806 var _printed3 = expressions[i];
32809 // Breaks at the template element boundaries (${ and }) are preferred to breaking
32810 // in the middle of a MemberExpression
32811 if (n.expressions[i].comments && n.expressions[i].comments.length || n.expressions[i].type === "MemberExpression" || n.expressions[i].type === "OptionalMemberExpression" || n.expressions[i].type === "ConditionalExpression") {
32812 _printed3 = concat$6([indent$3(concat$6([softline$2, _printed3])), softline$2]);
32816 var aligned = indentSize === 0 && quasi.value.raw.endsWith("\n") ? align$1(-Infinity, _printed3) : addAlignmentToDoc$2(_printed3, indentSize, tabWidth);
32817 parts.push(group$2(concat$6(["${", aligned, lineSuffixBoundary$1, "}"])));
32821 return concat$6(parts);
32823 // These types are unprintable because they serve as abstract
32824 // supertypes for other (printable) types.
32826 case "TaggedTemplateExpression":
32827 return concat$6([path.call(print, "tag"), path.call(print, "typeParameters"), path.call(print, "quasi")]);
32831 case "SourceLocation":
32837 case "Declaration":
32839 case "NamedSpecifier":
32841 case "MemberTypeAnnotation": // Flow
32844 /* istanbul ignore next */
32845 throw new Error("unprintable type: " + JSON.stringify(n.type));
32846 // Type Annotations for Facebook Flow, typically stripped out or
32847 // transformed away before printing.
32849 case "TypeAnnotation":
32850 case "TSTypeAnnotation":
32851 if (n.typeAnnotation) {
32852 return path.call(print, "typeAnnotation");
32854 /* istanbul ignore next */
32859 case "TSTupleType":
32860 case "TupleTypeAnnotation":
32862 var typesField = n.type === "TSTupleType" ? "elementTypes" : "types";
32863 return group$2(concat$6(["[", indent$3(concat$6([softline$2, printArrayItems(path, options, typesField, print)])), ifBreak$1(shouldPrintComma(options, "all") ? "," : ""), comments.printDanglingComments(path, options,
32865 true), softline$2, "]"]));
32868 case "ExistsTypeAnnotation":
32871 case "EmptyTypeAnnotation":
32874 case "AnyTypeAnnotation":
32877 case "MixedTypeAnnotation":
32880 case "ArrayTypeAnnotation":
32881 return concat$6([path.call(print, "elementType"), "[]"]);
32883 case "BooleanTypeAnnotation":
32886 case "BooleanLiteralTypeAnnotation":
32887 return "" + n.value;
32889 case "DeclareClass":
32890 return printFlowDeclaration(path, printClass(path, options, print));
32892 case "TSDeclareFunction":
32893 // For TypeScript the TSDeclareFunction node shares the AST
32894 // structure with FunctionDeclaration
32895 return concat$6([n.declare ? "declare " : "", printFunctionDeclaration(path, print, options), semi]);
32897 case "DeclareFunction":
32898 return printFlowDeclaration(path, ["function ", path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), semi]);
32900 case "DeclareModule":
32901 return printFlowDeclaration(path, ["module ", path.call(print, "id"), " ", path.call(print, "body")]);
32903 case "DeclareModuleExports":
32904 return printFlowDeclaration(path, ["module.exports", ": ", path.call(print, "typeAnnotation"), semi]);
32906 case "DeclareVariable":
32907 return printFlowDeclaration(path, ["var ", path.call(print, "id"), semi]);
32909 case "DeclareExportAllDeclaration":
32910 return concat$6(["declare export * from ", path.call(print, "source")]);
32912 case "DeclareExportDeclaration":
32913 return concat$6(["declare ", printExportDeclaration(path, options, print)]);
32915 case "DeclareOpaqueType":
32918 parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters"));
32921 parts.push(": ", path.call(print, "supertype"));
32925 parts.push(" = ", path.call(print, "impltype"));
32930 if (n.type === "DeclareOpaqueType") {
32931 return printFlowDeclaration(path, parts);
32934 return concat$6(parts);
32937 case "EnumDeclaration":
32938 return concat$6(["enum ", path.call(print, "id"), " ", path.call(print, "body")]);
32940 case "EnumBooleanBody":
32941 case "EnumNumberBody":
32942 case "EnumStringBody":
32943 case "EnumSymbolBody":
32945 if (n.type === "EnumSymbolBody" || n.explicitType) {
32949 case "EnumBooleanBody":
32953 case "EnumNumberBody":
32957 case "EnumStringBody":
32961 case "EnumSymbolBody":
32966 parts.push("of ", type, " ");
32969 if (n.members.length === 0) {
32970 parts.push(group$2(concat$6(["{", comments.printDanglingComments(path, options), softline$2, "}"])));
32972 parts.push(group$2(concat$6(["{", indent$3(concat$6([hardline$4, printArrayItems(path, options, "members", print), shouldPrintComma(options) ? "," : ""])), comments.printDanglingComments(path, options,
32974 true), hardline$4, "}"])));
32977 return concat$6(parts);
32980 case "EnumBooleanMember":
32981 case "EnumNumberMember":
32982 case "EnumStringMember":
32983 return concat$6([path.call(print, "id"), " = ", typeof n.init === "object" ? path.call(print, "init") : String(n.init)]);
32985 case "EnumDefaultedMember":
32986 return path.call(print, "id");
32988 case "FunctionTypeAnnotation":
32989 case "TSFunctionType":
32991 // FunctionTypeAnnotation is ambiguous:
32992 // declare function foo(a: B): void; OR
32993 // var A: (a: B) => void;
32994 var _parent8 = path.getParentNode(0);
32996 var _parentParent2 = path.getParentNode(1);
32998 var _parentParentParent = path.getParentNode(2);
33000 var isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !((_parent8.type === "ObjectTypeProperty" || _parent8.type === "ObjectTypeInternalSlot") && !getFlowVariance$1(_parent8) && !_parent8.optional && options.locStart(_parent8) === options.locStart(n) || _parent8.type === "ObjectTypeCallProperty" || _parentParentParent && _parentParentParent.type === "DeclareFunction");
33001 var needsColon = isArrowFunctionTypeAnnotation && (_parent8.type === "TypeAnnotation" || _parent8.type === "TSTypeAnnotation"); // Sadly we can't put it inside of FastPath::needsColon because we are
33002 // printing ":" as part of the expression and it would put parenthesis
33005 var needsParens = needsColon && isArrowFunctionTypeAnnotation && (_parent8.type === "TypeAnnotation" || _parent8.type === "TSTypeAnnotation") && _parentParent2.type === "ArrowFunctionExpression";
33007 if (isObjectTypePropertyAFunction$1(_parent8, options)) {
33008 isArrowFunctionTypeAnnotation = true;
33016 parts.push(printFunctionParams(path, print, options,
33019 /* printTypeParams */
33020 true)); // The returnType is not wrapped in a TypeAnnotation, so the colon
33021 // needs to be added separately.
33023 if (n.returnType || n.predicate || n.typeAnnotation) {
33024 parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType"), path.call(print, "predicate"), path.call(print, "typeAnnotation"));
33031 return group$2(concat$6(parts));
33035 return concat$6(["...", path.call(print, "typeAnnotation")]);
33037 case "TSOptionalType":
33038 return concat$6([path.call(print, "typeAnnotation"), "?"]);
33040 case "FunctionTypeParam":
33041 return concat$6([path.call(print, "name"), printOptionalToken(path), n.name ? ": " : "", path.call(print, "typeAnnotation")]);
33043 case "GenericTypeAnnotation":
33044 return concat$6([path.call(print, "id"), path.call(print, "typeParameters")]);
33046 case "DeclareInterface":
33047 case "InterfaceDeclaration":
33048 case "InterfaceTypeAnnotation":
33050 if (n.type === "DeclareInterface" || n.declare) {
33051 parts.push("declare ");
33054 parts.push("interface");
33056 if (n.type === "DeclareInterface" || n.type === "InterfaceDeclaration") {
33057 parts.push(" ", path.call(print, "id"), path.call(print, "typeParameters"));
33060 if (n["extends"].length > 0) {
33061 parts.push(group$2(indent$3(concat$6([line$2, "extends ", (n.extends.length === 1 ? identity$1 : indent$3)(join$4(concat$6([",", line$2]), path.map(print, "extends")))]))));
33064 parts.push(" ", path.call(print, "body"));
33065 return group$2(concat$6(parts));
33068 case "ClassImplements":
33069 case "InterfaceExtends":
33070 return concat$6([path.call(print, "id"), path.call(print, "typeParameters")]);
33072 case "TSClassImplements":
33073 return concat$6([path.call(print, "expression"), path.call(print, "typeParameters")]);
33075 case "TSIntersectionType":
33076 case "IntersectionTypeAnnotation":
33078 var types = path.map(print, "types");
33080 var wasIndented = false;
33082 for (var _i = 0; _i < types.length; ++_i) {
33084 result.push(types[_i]);
33085 } else if (isObjectType$1(n.types[_i - 1]) && isObjectType$1(n.types[_i])) {
33086 // If both are objects, don't indent
33087 result.push(concat$6([" & ", wasIndented ? indent$3(types[_i]) : types[_i]]));
33088 } else if (!isObjectType$1(n.types[_i - 1]) && !isObjectType$1(n.types[_i])) {
33089 // If no object is involved, go to the next line if it breaks
33090 result.push(indent$3(concat$6([" &", line$2, types[_i]])));
33092 // If you go from object to non-object or vis-versa, then inline it
33094 wasIndented = true;
33097 result.push(" & ", _i > 1 ? indent$3(types[_i]) : types[_i]);
33101 return group$2(concat$6(result));
33104 case "TSUnionType":
33105 case "UnionTypeAnnotation":
33107 // single-line variation
33109 // multi-line variation
33113 var _parent9 = path.getParentNode(); // If there's a leading comment, the parent is doing the indentation
33116 var shouldIndent = _parent9.type !== "TypeParameterInstantiation" && _parent9.type !== "TSTypeParameterInstantiation" && _parent9.type !== "GenericTypeAnnotation" && _parent9.type !== "TSTypeReference" && _parent9.type !== "TSTypeAssertion" && _parent9.type !== "TupleTypeAnnotation" && _parent9.type !== "TSTupleType" && !(_parent9.type === "FunctionTypeParam" && !_parent9.name) && !((_parent9.type === "TypeAlias" || _parent9.type === "VariableDeclarator" || _parent9.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment$1(options.originalText, n, options)); // {
33119 // should be inlined and not be printed in the multi-line variant
33121 var shouldHug = shouldHugType(n); // We want to align the children but without its comment, so it looks like
33126 var _printed4 = path.map(function (typePath) {
33127 var printedType = typePath.call(print);
33130 printedType = align$1(2, printedType);
33133 return comments.printComments(typePath, function () {
33134 return printedType;
33139 return join$4(" | ", _printed4);
33142 var shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment$1(options.originalText, n, options);
33143 var code = concat$6([ifBreak$1(concat$6([shouldAddStartLine ? line$2 : "", "| "])), join$4(concat$6([line$2, "| "]), _printed4)]);
33145 if (needsParens_1(path, options)) {
33146 return group$2(concat$6([indent$3(code), softline$2]));
33149 if (_parent9.type === "TupleTypeAnnotation" && _parent9.types.length > 1 || _parent9.type === "TSTupleType" && _parent9.elementTypes.length > 1) {
33150 return group$2(concat$6([indent$3(concat$6([ifBreak$1(concat$6(["(", softline$2])), code])), softline$2, ifBreak$1(")")]));
33153 return group$2(shouldIndent ? indent$3(code) : code);
33156 case "NullableTypeAnnotation":
33157 return concat$6(["?", path.call(print, "typeAnnotation")]);
33159 case "TSNullKeyword":
33160 case "NullLiteralTypeAnnotation":
33163 case "ThisTypeAnnotation":
33166 case "NumberTypeAnnotation":
33169 case "ObjectTypeCallProperty":
33171 parts.push("static ");
33174 parts.push(path.call(print, "value"));
33175 return concat$6(parts);
33177 case "ObjectTypeIndexer":
33179 var _variance = getFlowVariance$1(n);
33181 return concat$6([_variance || "", "[", path.call(print, "id"), n.id ? ": " : "", path.call(print, "key"), "]: ", path.call(print, "value")]);
33184 case "ObjectTypeProperty":
33186 var _variance2 = getFlowVariance$1(n);
33191 modifier = "proto ";
33192 } else if (n.static) {
33193 modifier = "static ";
33196 return concat$6([modifier, isGetterOrSetter$1(n) ? n.kind + " " : "", _variance2 || "", printPropertyKey(path, options, print), printOptionalToken(path), isFunctionNotation$1(n, options) ? "" : ": ", path.call(print, "value")]);
33199 case "QualifiedTypeIdentifier":
33200 return concat$6([path.call(print, "qualification"), ".", path.call(print, "id")]);
33202 case "StringLiteralTypeAnnotation":
33203 return nodeStr(n, options);
33205 case "NumberLiteralTypeAnnotation":
33206 assert$1.strictEqual(typeof n.value, "number");
33208 if (n.extra != null) {
33209 return printNumber$1(n.extra.raw);
33212 return printNumber$1(n.raw);
33214 case "StringTypeAnnotation":
33217 case "DeclareTypeAlias":
33220 if (n.type === "DeclareTypeAlias" || n.declare) {
33221 parts.push("declare ");
33224 var _printed5 = printAssignmentRight(n.id, n.right, path.call(print, "right"), options);
33226 parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", _printed5, semi);
33227 return group$2(concat$6(parts));
33230 case "TypeCastExpression":
33232 var value = path.getValue(); // Flow supports a comment syntax for specifying type annotations: https://flow.org/en/docs/types/comments/.
33233 // Unfortunately, its parser doesn't differentiate between comment annotations and regular
33234 // annotations when producing an AST. So to preserve parentheses around type casts that use
33235 // the comment syntax, we need to hackily read the source itself to see if the code contains
33236 // a type annotation comment.
33238 // Note that we're able to use the normal whitespace regex here because the Flow parser has
33239 // already deemed this AST node to be a type cast. Only the Babel parser needs the
33240 // non-line-break whitespace regex, which is why hasFlowShorthandAnnotationComment() is
33241 // implemented differently.
33243 var commentSyntax = value && value.typeAnnotation && value.typeAnnotation.range && options.originalText.substring(value.typeAnnotation.range[0]).match(/^\/\*\s*:/);
33244 return concat$6(["(", path.call(print, "expression"), commentSyntax ? " /*" : "", ": ", path.call(print, "typeAnnotation"), commentSyntax ? " */" : "", ")"]);
33247 case "TypeParameterDeclaration":
33248 case "TypeParameterInstantiation":
33250 var _value = path.getValue();
33252 var commentStart = _value.range ? options.originalText.substring(0, _value.range[0]).lastIndexOf("/*") : -1; // As noted in the TypeCastExpression comments above, we're able to use a normal whitespace regex here
33253 // because we know for sure that this is a type definition.
33255 var _commentSyntax = commentStart >= 0 && options.originalText.substring(commentStart).match(/^\/\*\s*::/);
33257 if (_commentSyntax) {
33258 return concat$6(["/*:: ", printTypeParameters(path, options, print, "params"), " */"]);
33261 return printTypeParameters(path, options, print, "params");
33264 case "TSTypeParameterDeclaration":
33265 case "TSTypeParameterInstantiation":
33266 return printTypeParameters(path, options, print, "params");
33268 case "TSTypeParameter":
33269 case "TypeParameter":
33271 var _parent10 = path.getParentNode();
33273 if (_parent10.type === "TSMappedType") {
33274 parts.push("[", path.call(print, "name"));
33276 if (n.constraint) {
33277 parts.push(" in ", path.call(print, "constraint"));
33281 return concat$6(parts);
33284 var _variance3 = getFlowVariance$1(n);
33287 parts.push(_variance3);
33290 parts.push(path.call(print, "name"));
33294 parts.push(path.call(print, "bound"));
33297 if (n.constraint) {
33298 parts.push(" extends ", path.call(print, "constraint"));
33301 if (n["default"]) {
33302 parts.push(" = ", path.call(print, "default"));
33303 } // Keep comma if the file extension is .tsx and
33304 // has one type parameter that isn't extend with any types.
33305 // Because, otherwise formatted result will be invalid as tsx.
33308 var _grandParent = path.getNode(2);
33310 if (_parent10.params && _parent10.params.length === 1 && isTSXFile$1(options) && !n.constraint && _grandParent.type === "ArrowFunctionExpression") {
33314 return concat$6(parts);
33317 case "TypeofTypeAnnotation":
33318 return concat$6(["typeof ", path.call(print, "argument")]);
33320 case "VoidTypeAnnotation":
33323 case "InferredPredicate":
33325 // Unhandled types below. If encountered, nodes of these types should
33326 // be either left alone or desugared into AST types that are fully
33327 // supported by the pretty-printer.
33329 case "DeclaredPredicate":
33330 return concat$6(["%checks(", path.call(print, "value"), ")"]);
33332 case "TSAbstractKeyword":
33335 case "TSAnyKeyword":
33338 case "TSAsyncKeyword":
33341 case "TSBooleanKeyword":
33344 case "TSBigIntKeyword":
33347 case "TSConstKeyword":
33350 case "TSDeclareKeyword":
33353 case "TSExportKeyword":
33356 case "TSNeverKeyword":
33359 case "TSNumberKeyword":
33362 case "TSObjectKeyword":
33365 case "TSProtectedKeyword":
33366 return "protected";
33368 case "TSPrivateKeyword":
33371 case "TSPublicKeyword":
33374 case "TSReadonlyKeyword":
33377 case "TSSymbolKeyword":
33380 case "TSStaticKeyword":
33383 case "TSStringKeyword":
33386 case "TSUndefinedKeyword":
33387 return "undefined";
33389 case "TSUnknownKeyword":
33392 case "TSVoidKeyword":
33395 case "TSAsExpression":
33396 return concat$6([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]);
33398 case "TSArrayType":
33399 return concat$6([path.call(print, "elementType"), "[]"]);
33401 case "TSPropertySignature":
33404 parts.push("export ");
33407 if (n.accessibility) {
33408 parts.push(n.accessibility + " ");
33412 parts.push("static ");
33416 parts.push("readonly ");
33419 parts.push(printPropertyKey(path, options, print), printOptionalToken(path));
33421 if (n.typeAnnotation) {
33423 parts.push(path.call(print, "typeAnnotation"));
33424 } // This isn't valid semantically, but it's in the AST so we can print it.
33427 if (n.initializer) {
33428 parts.push(" = ", path.call(print, "initializer"));
33431 return concat$6(parts);
33434 case "TSParameterProperty":
33435 if (n.accessibility) {
33436 parts.push(n.accessibility + " ");
33440 parts.push("export ");
33444 parts.push("static ");
33448 parts.push("readonly ");
33451 parts.push(path.call(print, "parameter"));
33452 return concat$6(parts);
33454 case "TSTypeReference":
33455 return concat$6([path.call(print, "typeName"), printTypeParameters(path, options, print, "typeParameters")]);
33457 case "TSTypeQuery":
33458 return concat$6(["typeof ", path.call(print, "exprName")]);
33460 case "TSIndexSignature":
33462 var _parent11 = path.getParentNode();
33464 return concat$6([n.export ? "export " : "", n.accessibility ? concat$6([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", "[", n.parameters ? concat$6(path.map(print, "parameters")) : "", "]: ", path.call(print, "typeAnnotation"), _parent11.type === "ClassBody" ? semi : ""]);
33467 case "TSTypePredicate":
33468 return concat$6([n.asserts ? "asserts " : "", path.call(print, "parameterName"), n.typeAnnotation ? concat$6([" is ", path.call(print, "typeAnnotation")]) : ""]);
33470 case "TSNonNullExpression":
33471 return concat$6([path.call(print, "expression"), "!"]);
33476 case "TSImportType":
33477 return concat$6([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, "parameter"), ")", !n.qualifier ? "" : concat$6([".", path.call(print, "qualifier")]), printTypeParameters(path, options, print, "typeParameters")]);
33479 case "TSLiteralType":
33480 return path.call(print, "literal");
33482 case "TSIndexedAccessType":
33483 return concat$6([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]);
33485 case "TSConstructSignatureDeclaration":
33486 case "TSCallSignatureDeclaration":
33487 case "TSConstructorType":
33489 if (n.type !== "TSCallSignatureDeclaration") {
33490 parts.push("new ");
33493 parts.push(group$2(printFunctionParams(path, print, options,
33496 /* printTypeParams */
33499 if (n.returnType) {
33500 var isType = n.type === "TSConstructorType";
33501 parts.push(isType ? " => " : ": ", path.call(print, "returnType"));
33504 return concat$6(parts);
33507 case "TSTypeOperator":
33508 return concat$6([n.operator, " ", path.call(print, "typeAnnotation")]);
33510 case "TSMappedType":
33512 var _shouldBreak3 = hasNewlineInRange$2(options.originalText, options.locStart(n), options.locEnd(n));
33514 return group$2(concat$6(["{", indent$3(concat$6([options.bracketSpacing ? line$2 : softline$2, n.readonly ? concat$6([getTypeScriptMappedTypeModifier$1(n.readonly, "readonly"), " "]) : "", printTypeScriptModifiers(path, options, print), path.call(print, "typeParameter"), n.optional ? getTypeScriptMappedTypeModifier$1(n.optional, "?") : "", ": ", path.call(print, "typeAnnotation"), ifBreak$1(semi, "")])), comments.printDanglingComments(path, options,
33516 true), options.bracketSpacing ? line$2 : softline$2, "}"]), {
33517 shouldBreak: _shouldBreak3
33521 case "TSMethodSignature":
33522 parts.push(n.accessibility ? concat$6([n.accessibility, " "]) : "", n.export ? "export " : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.computed ? "[" : "", path.call(print, "key"), n.computed ? "]" : "", printOptionalToken(path), printFunctionParams(path, print, options,
33525 /* printTypeParams */
33528 if (n.returnType) {
33529 parts.push(": ", path.call(print, "returnType"));
33532 return group$2(concat$6(parts));
33534 case "TSNamespaceExportDeclaration":
33535 parts.push("export as namespace ", path.call(print, "id"));
33537 if (options.semi) {
33541 return group$2(concat$6(parts));
33543 case "TSEnumDeclaration":
33545 parts.push("declare ");
33549 parts.push(printTypeScriptModifiers(path, options, print));
33553 parts.push("const ");
33556 parts.push("enum ", path.call(print, "id"), " ");
33558 if (n.members.length === 0) {
33559 parts.push(group$2(concat$6(["{", comments.printDanglingComments(path, options), softline$2, "}"])));
33561 parts.push(group$2(concat$6(["{", indent$3(concat$6([hardline$4, printArrayItems(path, options, "members", print), shouldPrintComma(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options,
33563 true), hardline$4, "}"])));
33566 return concat$6(parts);
33568 case "TSEnumMember":
33569 parts.push(path.call(print, "id"));
33571 if (n.initializer) {
33572 parts.push(" = ", path.call(print, "initializer"));
33575 return concat$6(parts);
33577 case "TSImportEqualsDeclaration":
33579 parts.push("export ");
33582 parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference"));
33584 if (options.semi) {
33588 return group$2(concat$6(parts));
33590 case "TSExternalModuleReference":
33591 return concat$6(["require(", path.call(print, "expression"), ")"]);
33593 case "TSModuleDeclaration":
33595 var _parent12 = path.getParentNode();
33597 var isExternalModule = isLiteral$1(n.id);
33598 var parentIsDeclaration = _parent12.type === "TSModuleDeclaration";
33599 var bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration";
33601 if (parentIsDeclaration) {
33605 parts.push("declare ");
33608 parts.push(printTypeScriptModifiers(path, options, print));
33609 var textBetweenNodeAndItsId = options.originalText.slice(options.locStart(n), options.locStart(n.id)); // Global declaration looks like this:
33610 // (declare)? global { ... }
33612 var isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId);
33614 if (!isGlobalDeclaration) {
33615 parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace ");
33619 parts.push(path.call(print, "id"));
33621 if (bodyIsDeclaration) {
33622 parts.push(path.call(print, "body"));
33623 } else if (n.body) {
33624 parts.push(" ", group$2(path.call(print, "body")));
33629 return concat$6(parts);
33632 case "PrivateName":
33633 return concat$6(["#", path.call(print, "id")]);
33635 case "TSConditionalType":
33636 return printTernaryOperator(path, options, print, {
33637 beforeParts: function beforeParts() {
33638 return [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")];
33640 afterParts: function afterParts() {
33643 shouldCheckJsx: false,
33644 conditionalNodeType: "TSConditionalType",
33645 consequentNodePropertyName: "trueType",
33646 alternateNodePropertyName: "falseType",
33647 testNodePropertyName: "checkType",
33651 case "TSInferType":
33652 return concat$6(["infer", " ", path.call(print, "typeParameter")]);
33654 case "InterpreterDirective":
33655 parts.push("#!", n.value, hardline$4);
33657 if (isNextLineEmpty$2(options.originalText, n, options)) {
33658 parts.push(hardline$4);
33661 return concat$6(parts);
33664 return concat$6([].concat(path.call(print, "node"), !n.node.comments || n.node.comments.length === 0 ? [] : concat$6([" //", n.node.comments[0].value.trimRight()])));
33666 case "NGChainedExpression":
33667 return group$2(join$4(concat$6([";", line$2]), path.map(function (childPath) {
33668 return hasNgSideEffect$1(childPath) ? print(childPath) : concat$6(["(", print(childPath), ")"]);
33669 }, "expressions")));
33671 case "NGEmptyExpression":
33674 case "NGQuotedExpression":
33675 return concat$6([n.prefix, ":", n.value]);
33677 case "NGMicrosyntax":
33678 return concat$6(path.map(function (childPath, index) {
33679 return concat$6([index === 0 ? "" : isNgForOf$1(childPath.getValue(), index, n) ? " " : concat$6([";", line$2]), print(childPath)]);
33682 case "NGMicrosyntaxKey":
33683 return /^[a-z_$][a-z0-9_$]*(-[a-z_$][a-z0-9_$])*$/i.test(n.name) ? n.name : JSON.stringify(n.name);
33685 case "NGMicrosyntaxExpression":
33686 return concat$6([path.call(print, "expression"), n.alias === null ? "" : concat$6([" as ", path.call(print, "alias")])]);
33688 case "NGMicrosyntaxKeyedExpression":
33690 var index = path.getName();
33692 var _parentNode2 = path.getParentNode();
33694 var shouldNotPrintColon = isNgForOf$1(n, index, _parentNode2) || (index === 1 && (n.key.name === "then" || n.key.name === "else") || index === 2 && n.key.name === "else" && _parentNode2.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && _parentNode2.body[index - 1].key.name === "then") && _parentNode2.body[0].type === "NGMicrosyntaxExpression";
33695 return concat$6([path.call(print, "key"), shouldNotPrintColon ? " " : ": ", path.call(print, "expression")]);
33698 case "NGMicrosyntaxLet":
33699 return concat$6(["let ", path.call(print, "key"), n.value === null ? "" : concat$6([" = ", path.call(print, "value")])]);
33701 case "NGMicrosyntaxAs":
33702 return concat$6([path.call(print, "key"), " as ", path.call(print, "alias")]);
33704 case "ArgumentPlaceholder":
33708 /* istanbul ignore next */
33709 throw new Error("unknown type: " + JSON.stringify(n.type));
33713 function printStatementSequence(path, options, print) {
33715 var bodyNode = path.getNode();
33716 var isClass = bodyNode.type === "ClassBody";
33717 path.map(function (stmtPath, i) {
33718 var stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy
33719 // "statements," it's safer simply to skip them.
33721 /* istanbul ignore if */
33725 } // Skip printing EmptyStatement nodes to avoid leaving stray
33726 // semicolons lying around.
33729 if (stmt.type === "EmptyStatement") {
33733 var stmtPrinted = print(stmtPath);
33734 var text = options.originalText;
33735 var parts = []; // in no-semi mode, prepend statement with semicolon if it might break ASI
33736 // don't prepend the only JSX element in a program with semicolon
33738 if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown$1(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options)) {
33739 if (stmt.comments && stmt.comments.some(function (comment) {
33740 return comment.leading;
33742 parts.push(print(stmtPath, {
33746 parts.push(";", stmtPrinted);
33749 parts.push(stmtPrinted);
33752 if (!options.semi && isClass) {
33753 if (classPropMayCauseASIProblems$1(stmtPath)) {
33755 } else if (stmt.type === "ClassProperty") {
33756 var nextChild = bodyNode.body[i + 1];
33758 if (classChildNeedsASIProtection$1(nextChild)) {
33764 if (isNextLineEmpty$2(text, stmt, options) && !isLastStatement$1(stmtPath)) {
33765 parts.push(hardline$4);
33768 printed.push(concat$6(parts));
33770 return join$4(hardline$4, printed);
33773 function printPropertyKey(path, options, print) {
33774 var node = path.getNode();
33776 if (node.computed) {
33777 return concat$6(["[", path.call(print, "key"), "]"]);
33780 var parent = path.getParentNode();
33781 var key = node.key;
33783 if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) {
33784 var objectHasStringProp = (parent.properties || parent.body || parent.members).some(function (prop) {
33785 return !prop.computed && prop.key && isStringLiteral$1(prop.key) && !isStringPropSafeToCoerceToIdentifier$1(prop, options);
33787 needsQuoteProps.set(parent, objectHasStringProp);
33790 if (key.type === "Identifier" && (options.parser === "json" || options.quoteProps === "consistent" && needsQuoteProps.get(parent))) {
33792 var prop = printString$1(JSON.stringify(key.name), options);
33793 return path.call(function (keyPath) {
33794 return comments.printComments(keyPath, function () {
33800 if (isStringPropSafeToCoerceToIdentifier$1(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) {
33802 return path.call(function (keyPath) {
33803 return comments.printComments(keyPath, function () {
33809 return path.call(print, "key");
33812 function printMethod(path, options, print) {
33813 var node = path.getNode();
33814 var kind = node.kind;
33815 var value = node.value || node;
33818 if (!kind || kind === "init" || kind === "method" || kind === "constructor") {
33820 parts.push("async ");
33823 if (value.generator) {
33827 assert$1.ok(kind === "get" || kind === "set");
33828 parts.push(kind, " ");
33831 parts.push(printPropertyKey(path, options, print), node.optional || node.key.optional ? "?" : "", node === value ? printMethodInternal(path, options, print) : path.call(function (path) {
33832 return printMethodInternal(path, options, print);
33834 return concat$6(parts);
33837 function printMethodInternal(path, options, print) {
33838 var parts = [printFunctionTypeParameters(path, options, print), group$2(concat$6([printFunctionParams(path, print, options), printReturnType(path, print, options)]))];
33840 if (path.getNode().body) {
33841 parts.push(" ", path.call(print, "body"));
33843 parts.push(options.semi ? ";" : "");
33846 return concat$6(parts);
33849 function couldGroupArg(arg) {
33850 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
33851 // https://github.com/prettier/prettier/issues/4070
33852 // export class Thing implements OtherThing {
33853 // do: (type: Type) => Provider<Prop> = memoize(
33854 // (type: ObjectType): Provider<Opts> => {}
33857 // https://github.com/prettier/prettier/issues/6099
33858 // app.get("/", (req, res): void => {
33859 // res.send("Hello World!");
33861 !arg.returnType || !arg.returnType.typeAnnotation || arg.returnType.typeAnnotation.type !== "TSTypeReference") && (arg.body.type === "BlockStatement" || arg.body.type === "ArrowFunctionExpression" || arg.body.type === "ObjectExpression" || arg.body.type === "ArrayExpression" || arg.body.type === "CallExpression" || arg.body.type === "OptionalCallExpression" || arg.body.type === "ConditionalExpression" || isJSXNode$1(arg.body));
33864 function shouldGroupLastArg(args) {
33865 var lastArg = getLast$2(args);
33866 var penultimateArg = getPenultimate$1(args);
33867 return !hasLeadingComment$3(lastArg) && !hasTrailingComment$1(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type,
33868 // disable last element expansion.
33869 !penultimateArg || penultimateArg.type !== lastArg.type);
33872 function shouldGroupFirstArg(args) {
33873 if (args.length !== 2) {
33877 var firstArg = args[0];
33878 var secondArg = args[1];
33879 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);
33882 function printJestEachTemplateLiteral(node, expressions, options) {
33885 * ${1} | ${1} | ${2}
33886 * ${1} | ${2} | ${3}
33887 * ${2} | ${1} | ${3}
33889 var headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/);
33891 if (headerNames.length > 1 || headerNames.some(function (headerName) {
33892 return headerName.length !== 0;
33895 var stringifiedExpressions = expressions.map(function (doc) {
33896 return "${" + printDocToString$2(doc, Object.assign({}, options, {
33897 printWidth: Infinity,
33899 })).formatted + "}";
33902 hasLineBreak: false,
33906 for (var i = 1; i < node.quasis.length; i++) {
33907 var row = tableBody[tableBody.length - 1];
33908 var correspondingExpression = stringifiedExpressions[i - 1];
33909 row.cells.push(correspondingExpression);
33911 if (correspondingExpression.indexOf("\n") !== -1) {
33912 row.hasLineBreak = true;
33915 if (node.quasis[i].value.raw.indexOf("\n") !== -1) {
33917 hasLineBreak: false,
33923 var maxColumnCount = tableBody.reduce(function (maxColumnCount, row) {
33924 return Math.max(maxColumnCount, row.cells.length);
33925 }, headerNames.length);
33926 var maxColumnWidths = Array.from(new Array(maxColumnCount), function () {
33931 }].concat(tableBody.filter(function (row) {
33932 return row.cells.length !== 0;
33934 table.filter(function (row) {
33935 return !row.hasLineBreak;
33936 }).forEach(function (row) {
33937 row.cells.forEach(function (cell, index) {
33938 maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$2(cell));
33941 parts.push(lineSuffixBoundary$1, "`", indent$3(concat$6([hardline$4, join$4(hardline$4, table.map(function (row) {
33942 return join$4(" | ", row.cells.map(function (cell, index) {
33943 return row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$2(cell));
33945 }))])), hardline$4, "`");
33946 return concat$6(parts);
33950 function printArgumentsList(path, options, print) {
33951 var node = path.getValue();
33952 var args = node.arguments;
33954 if (args.length === 0) {
33955 return concat$6(["(", comments.printDanglingComments(path, options,
33958 } // useEffect(() => { ... }, [foo, bar, baz])
33961 if (args.length === 2 && args[0].type === "ArrowFunctionExpression" && args[0].params.length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && !args.find(function (arg) {
33962 return arg.comments;
33964 return concat$6(["(", path.call(print, "arguments", 0), ", ", path.call(print, "arguments", 1), ")"]);
33973 function shouldBreakForArrowFunctionInArguments(arg, argPath) {
33974 if (!arg || arg.type !== "ArrowFunctionExpression" || !arg.body || arg.body.type !== "BlockStatement" || !arg.params || arg.params.length < 1) {
33978 var shouldBreak = false;
33979 argPath.each(function (paramPath) {
33980 var printed = concat$6([print(paramPath)]);
33981 shouldBreak = shouldBreak || willBreak$1(printed);
33983 return shouldBreak;
33986 var anyArgEmptyLine = false;
33987 var shouldBreakForArrowFunction = false;
33988 var hasEmptyLineFollowingFirstArg = false;
33989 var lastArgIndex = args.length - 1;
33990 var printedArguments = path.map(function (argPath, index) {
33991 var arg = argPath.getNode();
33992 var parts = [print(argPath)];
33994 if (index === lastArgIndex) ; else if (isNextLineEmpty$2(options.originalText, arg, options)) {
33996 hasEmptyLineFollowingFirstArg = true;
33999 anyArgEmptyLine = true;
34000 parts.push(",", hardline$4, hardline$4);
34002 parts.push(",", line$2);
34005 shouldBreakForArrowFunction = shouldBreakForArrowFunctionInArguments(arg, argPath);
34006 return concat$6(parts);
34008 var maybeTrailingComma = // Dynamic imports cannot have trailing commas
34009 !(node.callee && node.callee.type === "Import") && shouldPrintComma(options, "all") ? "," : "";
34011 function allArgsBrokenOut() {
34012 return group$2(concat$6(["(", indent$3(concat$6([line$2, concat$6(printedArguments)])), maybeTrailingComma, line$2, ")"]), {
34017 if (isFunctionCompositionArgs$1(args)) {
34018 return allArgsBrokenOut();
34021 var shouldGroupFirst = shouldGroupFirstArg(args);
34022 var shouldGroupLast = shouldGroupLastArg(args);
34024 if (shouldGroupFirst || shouldGroupLast) {
34025 var shouldBreak = (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$1) : printedArguments.slice(0, -1).some(willBreak$1)) || anyArgEmptyLine || shouldBreakForArrowFunction; // We want to print the last argument with a special flag
34027 var printedExpanded;
34029 path.each(function (argPath) {
34030 if (shouldGroupFirst && i === 0) {
34031 printedExpanded = [concat$6([argPath.call(function (p) {
34033 expandFirstArg: true
34035 }), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$4 : line$2, hasEmptyLineFollowingFirstArg ? hardline$4 : ""])].concat(printedArguments.slice(1));
34038 if (shouldGroupLast && i === args.length - 1) {
34039 printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(function (p) {
34041 expandLastArg: true
34048 var somePrintedArgumentsWillBreak = printedArguments.some(willBreak$1);
34049 var simpleConcat = concat$6(["(", concat$6(printedExpanded), ")"]);
34050 return concat$6([somePrintedArgumentsWillBreak ? breakParent$2 : "", conditionalGroup$1([!somePrintedArgumentsWillBreak && !node.typeArguments && !node.typeParameters ? simpleConcat : ifBreak$1(allArgsBrokenOut(), simpleConcat), shouldGroupFirst ? concat$6(["(", group$2(printedExpanded[0], {
34052 }), concat$6(printedExpanded.slice(1)), ")"]) : concat$6(["(", concat$6(printedArguments.slice(0, -1)), group$2(getLast$2(printedExpanded), {
34054 }), ")"]), allArgsBrokenOut()], {
34059 var contents = concat$6(["(", indent$3(concat$6([softline$2, concat$6(printedArguments)])), ifBreak$1(maybeTrailingComma), softline$2, ")"]);
34061 if (isLongCurriedCallExpression$1(path)) {
34062 // By not wrapping the arguments in a group, the printer prioritizes
34063 // breaking up these arguments rather than the args of the parent call.
34067 return group$2(contents, {
34068 shouldBreak: printedArguments.some(willBreak$1) || anyArgEmptyLine
34072 function printTypeAnnotation(path, options, print) {
34073 var node = path.getValue();
34075 if (!node.typeAnnotation) {
34079 var parentNode = path.getParentNode();
34080 var isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite;
34081 var isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node;
34083 if (isFlowAnnotationComment$1(options.originalText, node.typeAnnotation, options)) {
34084 return concat$6([" /*: ", path.call(print, "typeAnnotation"), " */"]);
34087 return concat$6([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path.call(print, "typeAnnotation")]);
34090 function printFunctionTypeParameters(path, options, print) {
34091 var fun = path.getValue();
34093 if (fun.typeArguments) {
34094 return path.call(print, "typeArguments");
34097 if (fun.typeParameters) {
34098 return path.call(print, "typeParameters");
34104 function printFunctionParams(path, print, options, expandArg, printTypeParams) {
34105 var fun = path.getValue();
34106 var parent = path.getParentNode();
34107 var paramsField = fun.parameters ? "parameters" : "params";
34108 var isParametersInTestCall = isTestCall$1(parent);
34109 var shouldHugParameters = shouldHugArguments(fun);
34110 var shouldExpandParameters = expandArg && !(fun[paramsField] && fun[paramsField].some(function (n) {
34113 var typeParams = printTypeParams ? printFunctionTypeParameters(path, options, print) : "";
34116 if (fun[paramsField]) {
34117 var lastArgIndex = fun[paramsField].length - 1;
34118 printed = path.map(function (childPath, index) {
34120 var param = childPath.getValue();
34121 parts.push(print(childPath));
34123 if (index === lastArgIndex) {
34125 parts.push(",", line$2);
34127 } else if (isParametersInTestCall || shouldHugParameters || shouldExpandParameters) {
34129 } else if (isNextLineEmpty$2(options.originalText, param, options)) {
34130 parts.push(",", hardline$4, hardline$4);
34132 parts.push(",", line$2);
34135 return concat$6(parts);
34140 printed.push(concat$6(["...", path.call(print, "rest")]));
34143 if (printed.length === 0) {
34144 return concat$6([typeParams, "(", comments.printDanglingComments(path, options,
34146 true, function (comment) {
34147 return getNextNonSpaceNonCommentCharacter$1(options.originalText, comment, options.locEnd) === ")";
34151 var lastParam = getLast$2(fun[paramsField]); // If the parent is a call with the first/last argument expansion and this is the
34152 // params of the first/last argument, we don't want the arguments to break and instead
34153 // want the whole expression to be on a new line.
34156 // verylongcall( verylongcall((
34162 if (shouldExpandParameters) {
34163 return group$2(concat$6([removeLines$1(typeParams), "(", concat$6(printed.map(removeLines$1)), ")"]));
34164 } // Single object destructuring should hug
34173 var hasNotParameterDecorator = fun[paramsField].every(function (param) {
34174 return !param.decorators;
34177 if (shouldHugParameters && hasNotParameterDecorator) {
34178 return concat$6([typeParams, "(", concat$6(printed), ")"]);
34179 } // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
34182 if (isParametersInTestCall) {
34183 return concat$6([typeParams, "(", concat$6(printed), ")"]);
34186 var isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction$1(parent, options) || isTypeAnnotationAFunction$1(parent, options) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === fun) && fun[paramsField].length === 1 && fun[paramsField][0].name === null && fun[paramsField][0].typeAnnotation && fun.typeParameters === null && isSimpleFlowType$1(fun[paramsField][0].typeAnnotation) && !fun.rest;
34188 if (isFlowShorthandWithOneArg) {
34189 if (options.arrowParens === "always") {
34190 return concat$6(["(", concat$6(printed), ")"]);
34193 return concat$6(printed);
34196 var canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest;
34197 return concat$6([typeParams, "(", indent$3(concat$6([softline$2, concat$6(printed)])), ifBreak$1(canHaveTrailingComma && shouldPrintComma(options, "all") ? "," : ""), softline$2, ")"]);
34200 function shouldPrintParamsWithoutParens(path, options) {
34201 if (options.arrowParens === "always") {
34205 if (options.arrowParens === "avoid") {
34206 var node = path.getValue();
34207 return canPrintParamsWithoutParens(node);
34208 } // Fallback default; should be unreachable
34214 function canPrintParamsWithoutParens(node) {
34215 return node.params.length === 1 && !node.rest && !node.typeParameters && !hasDanglingComments$1(node) && node.params[0].type === "Identifier" && !node.params[0].typeAnnotation && !node.params[0].comments && !node.params[0].optional && !node.predicate && !node.returnType;
34218 function printFunctionDeclaration(path, print, options) {
34219 var n = path.getValue();
34223 parts.push("async ");
34226 parts.push("function");
34233 parts.push(" ", path.call(print, "id"));
34236 parts.push(printFunctionTypeParameters(path, options, print), group$2(concat$6([printFunctionParams(path, print, options), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body"));
34237 return concat$6(parts);
34240 function printReturnType(path, print, options) {
34241 var n = path.getValue();
34242 var returnType = path.call(print, "returnType");
34244 if (n.returnType && isFlowAnnotationComment$1(options.originalText, n.returnType, options)) {
34245 return concat$6([" /*: ", returnType, " */"]);
34248 var parts = [returnType]; // prepend colon to TypeScript type annotation
34250 if (n.returnType && n.returnType.typeAnnotation) {
34251 parts.unshift(": ");
34255 // The return type will already add the colon, but otherwise we
34256 // need to do it ourselves
34257 parts.push(n.returnType ? " " : ": ", path.call(print, "predicate"));
34260 return concat$6(parts);
34263 function printExportDeclaration(path, options, print) {
34264 var decl = path.getValue();
34265 var semi = options.semi ? ";" : "";
34266 var parts = ["export "];
34267 var isDefault = decl["default"] || decl.type === "ExportDefaultDeclaration";
34270 parts.push("default ");
34273 parts.push(comments.printDanglingComments(path, options,
34277 if (needsHardlineAfterDanglingComment$1(decl)) {
34278 parts.push(hardline$4);
34281 if (decl.declaration) {
34282 parts.push(path.call(print, "declaration"));
34284 if (isDefault && decl.declaration.type !== "ClassDeclaration" && decl.declaration.type !== "FunctionDeclaration" && decl.declaration.type !== "TSInterfaceDeclaration" && decl.declaration.type !== "DeclareClass" && decl.declaration.type !== "DeclareFunction" && decl.declaration.type !== "TSDeclareFunction") {
34288 if (decl.specifiers && decl.specifiers.length > 0) {
34289 var specifiers = [];
34290 var defaultSpecifiers = [];
34291 var namespaceSpecifiers = [];
34292 path.each(function (specifierPath) {
34293 var specifierType = path.getValue().type;
34295 if (specifierType === "ExportSpecifier") {
34296 specifiers.push(print(specifierPath));
34297 } else if (specifierType === "ExportDefaultSpecifier") {
34298 defaultSpecifiers.push(print(specifierPath));
34299 } else if (specifierType === "ExportNamespaceSpecifier") {
34300 namespaceSpecifiers.push(concat$6(["* as ", print(specifierPath)]));
34303 var isNamespaceFollowed = namespaceSpecifiers.length !== 0 && specifiers.length !== 0;
34304 var isDefaultFollowed = defaultSpecifiers.length !== 0 && (namespaceSpecifiers.length !== 0 || specifiers.length !== 0);
34305 var canBreak = specifiers.length > 1 || defaultSpecifiers.length > 0 || decl.specifiers && decl.specifiers.some(function (node) {
34306 return node.comments;
34310 if (specifiers.length !== 0) {
34312 printed = group$2(concat$6(["{", indent$3(concat$6([options.bracketSpacing ? line$2 : softline$2, join$4(concat$6([",", line$2]), specifiers)])), ifBreak$1(shouldPrintComma(options) ? "," : ""), options.bracketSpacing ? line$2 : softline$2, "}"]));
34314 printed = concat$6(["{", options.bracketSpacing ? " " : "", concat$6(specifiers), options.bracketSpacing ? " " : "", "}"]);
34318 parts.push(decl.exportKind === "type" ? "type " : "", concat$6(defaultSpecifiers), concat$6([isDefaultFollowed ? ", " : ""]), concat$6(namespaceSpecifiers), concat$6([isNamespaceFollowed ? ", " : ""]), printed);
34324 parts.push(" from ", path.call(print, "source"));
34330 return concat$6(parts);
34333 function printFlowDeclaration(path, parts) {
34334 var parentExportDecl = getParentExportDeclaration$1(path);
34336 if (parentExportDecl) {
34337 assert$1.strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
34339 // If the parent node has type DeclareExportDeclaration, then it
34340 // will be responsible for printing the "declare" token. Otherwise
34341 // it needs to be printed with this non-exported declaration node.
34342 parts.unshift("declare ");
34345 return concat$6(parts);
34348 function printTypeScriptModifiers(path, options, print) {
34349 var n = path.getValue();
34351 if (!n.modifiers || !n.modifiers.length) {
34355 return concat$6([join$4(" ", path.map(print, "modifiers")), " "]);
34358 function printTypeParameters(path, options, print, paramsKey) {
34359 var n = path.getValue();
34361 if (!n[paramsKey]) {
34363 } // for TypeParameterDeclaration typeParameters is a single node
34366 if (!Array.isArray(n[paramsKey])) {
34367 return path.call(print, paramsKey);
34370 var grandparent = path.getNode(2);
34371 var greatGreatGrandParent = path.getNode(4);
34372 var isParameterInTestCall = grandparent != null && isTestCall$1(grandparent);
34373 var shouldInline = isParameterInTestCall || n[paramsKey].length === 0 || n[paramsKey].length === 1 && (shouldHugType(n[paramsKey][0]) || n[paramsKey][0].type === "GenericTypeAnnotation" && shouldHugType(n[paramsKey][0].id) || n[paramsKey][0].type === "TSTypeReference" && shouldHugType(n[paramsKey][0].typeName) || n[paramsKey][0].type === "NullableTypeAnnotation" || // See https://github.com/prettier/prettier/pull/6467 for the context.
34374 greatGreatGrandParent && greatGreatGrandParent.type === "VariableDeclarator" && grandparent && grandparent.type === "TSTypeAnnotation" && n[paramsKey][0].type !== "TSUnionType" && n[paramsKey][0].type !== "UnionTypeAnnotation" && n[paramsKey][0].type !== "TSConditionalType" && n[paramsKey][0].type !== "TSMappedType");
34376 if (shouldInline) {
34377 return concat$6(["<", join$4(", ", path.map(print, paramsKey)), ">"]);
34380 return group$2(concat$6(["<", indent$3(concat$6([softline$2, join$4(concat$6([",", line$2]), path.map(print, paramsKey))])), ifBreak$1(options.parser !== "typescript" && shouldPrintComma(options, "all") ? "," : ""), softline$2, ">"]));
34383 function printClass(path, options, print) {
34384 var n = path.getValue();
34388 parts.push("abstract ");
34391 parts.push("class");
34394 parts.push(" ", path.call(print, "id"));
34397 parts.push(path.call(print, "typeParameters"));
34398 var partsGroup = [];
34400 if (n.superClass) {
34401 var printed = concat$6(["extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters")]); // Keep old behaviour of extends in same line
34402 // If there is only on extends and there are not comments
34404 if ((!n.implements || n.implements.length === 0) && (!n.superClass.comments || n.superClass.comments.length === 0)) {
34405 parts.push(concat$6([" ", path.call(function (superClass) {
34406 return comments.printComments(superClass, function () {
34409 }, "superClass")]));
34411 partsGroup.push(group$2(concat$6([line$2, path.call(function (superClass) {
34412 return comments.printComments(superClass, function () {
34415 }, "superClass")])));
34417 } else if (n.extends && n.extends.length > 0) {
34418 parts.push(" extends ", join$4(", ", path.map(print, "extends")));
34421 if (n["mixins"] && n["mixins"].length > 0) {
34422 partsGroup.push(line$2, "mixins ", group$2(indent$3(join$4(concat$6([",", line$2]), path.map(print, "mixins")))));
34425 if (n["implements"] && n["implements"].length > 0) {
34426 partsGroup.push(line$2, "implements", group$2(indent$3(concat$6([line$2, join$4(concat$6([",", line$2]), path.map(print, "implements"))]))));
34429 if (partsGroup.length > 0) {
34430 parts.push(group$2(indent$3(concat$6(partsGroup))));
34433 if (n.body && n.body.comments && hasLeadingOwnLineComment$1(options.originalText, n.body, options)) {
34434 parts.push(hardline$4);
34439 parts.push(path.call(print, "body"));
34443 function printOptionalToken(path) {
34444 var node = path.getValue();
34446 if (!node.optional || // It's an optional computed method parsed by typescript-estree.
34447 // "?" is printed in `printMethod`.
34448 node.type === "Identifier" && node === path.getParentNode().key) {
34452 if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) {
34459 function printMemberLookup(path, options, print) {
34460 var property = path.call(print, "property");
34461 var n = path.getValue();
34462 var optional = printOptionalToken(path);
34465 return concat$6([optional, ".", property]);
34468 if (!n.property || isNumericLiteral$1(n.property)) {
34469 return concat$6([optional, "[", property, "]"]);
34472 return group$2(concat$6([optional, "[", indent$3(concat$6([softline$2, property])), softline$2, "]"]));
34475 function printBindExpressionCallee(path, options, print) {
34476 return concat$6(["::", path.call(print, "callee")]);
34477 } // We detect calls on member expressions specially to format a
34478 // common pattern better. The pattern we are looking for is this:
34481 // .map(x => x + 1)
34482 // .filter(x => x > 10)
34483 // .some(x => x % 2)
34485 // The way it is structured in the AST is via a nested sequence of
34486 // MemberExpression and CallExpression. We need to traverse the AST
34487 // and make groups out of it to print it in the desired way.
34490 function printMemberChain(path, options, print) {
34491 // The first phase is to linearize the AST by traversing it down.
34494 // has the following AST structure:
34495 // CallExpression(MemberExpression(CallExpression(Identifier)))
34496 // and we transform it into
34497 // [Identifier, CallExpression, MemberExpression, CallExpression]
34498 var printedNodes = []; // Here we try to retain one typed empty line after each call expression or
34499 // the first group whether it is in parentheses or not
34501 function shouldInsertEmptyLineAfter(node) {
34502 var originalText = options.originalText;
34503 var nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$2(originalText, node, options);
34504 var nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty
34505 // line after that parenthesis
34507 if (nextChar == ")") {
34508 return isNextLineEmptyAfterIndex$1(originalText, nextCharIndex + 1, options);
34511 return isNextLineEmpty$2(originalText, node, options);
34514 function rec(path) {
34515 var node = path.getValue();
34517 if ((node.type === "CallExpression" || node.type === "OptionalCallExpression") && (isMemberish$1(node.callee) || node.callee.type === "CallExpression" || node.callee.type === "OptionalCallExpression")) {
34518 printedNodes.unshift({
34520 printed: concat$6([comments.printComments(path, function () {
34521 return concat$6([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]);
34522 }, options), shouldInsertEmptyLineAfter(node) ? hardline$4 : ""])
34524 path.call(function (callee) {
34525 return rec(callee);
34527 } else if (isMemberish$1(node)) {
34528 printedNodes.unshift({
34530 needsParens: needsParens_1(path, options),
34531 printed: comments.printComments(path, function () {
34532 return node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup(path, options, print) : printBindExpressionCallee(path, options, print);
34535 path.call(function (object) {
34536 return rec(object);
34538 } else if (node.type === "TSNonNullExpression") {
34539 printedNodes.unshift({
34541 printed: comments.printComments(path, function () {
34545 path.call(function (expression) {
34546 return rec(expression);
34549 printedNodes.unshift({
34551 printed: path.call(print)
34554 } // Note: the comments of the root node have already been printed, so we
34555 // need to extract this first call without printing them as they would
34556 // if handled inside of the recursive call.
34559 var node = path.getValue();
34560 printedNodes.unshift({
34562 printed: concat$6([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)])
34564 path.call(function (callee) {
34565 return rec(callee);
34566 }, "callee"); // Once we have a linear list of printed nodes, we want to create groups out
34570 // will be grouped as
34572 // [Identifier, CallExpression],
34573 // [MemberExpression, MemberExpression, CallExpression],
34574 // [MemberExpression, CallExpression],
34575 // [MemberExpression],
34577 // so that we can print it as
34582 // The first group is the first node followed by
34583 // - as many CallExpression as possible
34584 // < fn()()() >.something()
34585 // - as many array accessors as possible
34586 // < fn()[0][1][2] >.something()
34587 // - then, as many MemberExpression as possible but the last one
34588 // < this.items >.something()
34591 var currentGroup = [printedNodes[0]];
34594 for (; i < printedNodes.length; ++i) {
34595 if (printedNodes[i].node.type === "TSNonNullExpression" || printedNodes[i].node.type === "OptionalCallExpression" || printedNodes[i].node.type === "CallExpression" || (printedNodes[i].node.type === "MemberExpression" || printedNodes[i].node.type === "OptionalMemberExpression") && printedNodes[i].node.computed && isNumericLiteral$1(printedNodes[i].node.property)) {
34596 currentGroup.push(printedNodes[i]);
34602 if (printedNodes[0].node.type !== "CallExpression" && printedNodes[0].node.type !== "OptionalCallExpression") {
34603 for (; i + 1 < printedNodes.length; ++i) {
34604 if (isMemberish$1(printedNodes[i].node) && isMemberish$1(printedNodes[i + 1].node)) {
34605 currentGroup.push(printedNodes[i]);
34612 groups.push(currentGroup);
34613 currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by
34614 // a sequence of CallExpression. To compute it, we keep adding things to the
34615 // group until we has seen a CallExpression in the past and reach a
34616 // MemberExpression
34618 var hasSeenCallExpression = false;
34620 for (; i < printedNodes.length; ++i) {
34621 if (hasSeenCallExpression && isMemberish$1(printedNodes[i].node)) {
34622 // [0] should be appended at the end of the group instead of the
34623 // beginning of the next one
34624 if (printedNodes[i].node.computed && isNumericLiteral$1(printedNodes[i].node.property)) {
34625 currentGroup.push(printedNodes[i]);
34629 groups.push(currentGroup);
34631 hasSeenCallExpression = false;
34634 if (printedNodes[i].node.type === "CallExpression" || printedNodes[i].node.type === "OptionalCallExpression") {
34635 hasSeenCallExpression = true;
34638 currentGroup.push(printedNodes[i]);
34640 if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(function (comment) {
34641 return comment.trailing;
34643 groups.push(currentGroup);
34645 hasSeenCallExpression = false;
34649 if (currentGroup.length > 0) {
34650 groups.push(currentGroup);
34651 } // There are cases like Object.keys(), Observable.of(), _.values() where
34652 // they are the subject of all the chained calls and therefore should
34653 // be kept on the same line:
34655 // Object.keys(items)
34659 // In order to detect those cases, we use an heuristic: if the first
34660 // node is an identifier with the name starting with a capital
34661 // letter or just a sequence of _$. The rationale is that they are
34662 // likely to be factories.
34665 function isFactory(name) {
34666 return /^[A-Z]|^[_$]+$/.test(name);
34667 } // In case the Identifier is shorter than tab width, we can keep the
34668 // first call in a single line, if it's an ExpressionStatement.
34670 // d3.scaleLinear()
34671 // .domain([0, 100])
34672 // .range([0, width]);
34676 function isShort(name) {
34677 return name.length <= options.tabWidth;
34680 function shouldNotWrap(groups) {
34681 var parent = path.getParentNode();
34682 var isExpression = parent && parent.type === "ExpressionStatement";
34683 var hasComputed = groups[1].length && groups[1][0].node.computed;
34685 if (groups[0].length === 1) {
34686 var firstNode = groups[0][0].node;
34687 return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpression && isShort(firstNode.name) || hasComputed);
34690 var lastNode = getLast$2(groups[0]).node;
34691 return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed);
34694 var shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups);
34696 function printGroup(printedGroup) {
34697 var printed = printedGroup.map(function (tuple) {
34698 return tuple.printed;
34699 }); // Checks if the last node (i.e. the parent node) needs parens and print
34702 if (printedGroup.length > 0 && printedGroup[printedGroup.length - 1].needsParens) {
34703 return concat$6(["("].concat(_toConsumableArray$1(printed), [")"]));
34706 return concat$6(printed);
34709 function printIndentedGroup(groups) {
34710 if (groups.length === 0) {
34714 return indent$3(group$2(concat$6([hardline$4, join$4(hardline$4, groups.map(printGroup))])));
34717 var printedGroups = groups.map(printGroup);
34718 var oneLine = concat$6(printedGroups);
34719 var cutoff = shouldMerge ? 3 : 2;
34720 var flatGroups = groups.slice(0, cutoff).reduce(function (res, group) {
34721 return res.concat(group);
34723 var hasComment = flatGroups.slice(1, -1).some(function (node) {
34724 return hasLeadingComment$3(node.node);
34725 }) || flatGroups.slice(0, -1).some(function (node) {
34726 return hasTrailingComment$1(node.node);
34727 }) || groups[cutoff] && hasLeadingComment$3(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just
34728 // render everything concatenated together.
34730 if (groups.length <= cutoff && !hasComment) {
34731 if (isLongCurriedCallExpression$1(path)) {
34735 return group$2(oneLine);
34736 } // Find out the last node in the first group and check if it has an
34737 // empty line after
34740 var lastNodeBeforeIndent = getLast$2(shouldMerge ? groups.slice(1, 2)[0] : groups[0]).node;
34741 var shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== "CallExpression" && lastNodeBeforeIndent.type !== "OptionalCallExpression" && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
34742 var expanded = concat$6([printGroup(groups[0]), shouldMerge ? concat$6(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$4 : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]);
34743 var callExpressions = printedNodes.map(function (_ref) {
34744 var node = _ref.node;
34746 }).filter(isCallOrOptionalCallExpression$1); // We don't want to print in one line if there's:
34748 // * 3 or more chained calls.
34749 // * Any group but the last one has a hard line.
34750 // If the last group is a function it's okay to inline if it fits.
34752 if (hasComment || callExpressions.length >= 3 || printedGroups.slice(0, -1).some(willBreak$1) ||
34754 * scopes.filter(scope => scope.value !== '').map((scope, i) => {
34755 * // multi line content
34758 function (lastGroupDoc, lastGroupNode) {
34759 return isCallOrOptionalCallExpression$1(lastGroupNode) && willBreak$1(lastGroupDoc);
34760 }(getLast$2(printedGroups), getLast$2(getLast$2(groups)).node) && callExpressions.slice(0, -1).some(function (n) {
34761 return n.arguments.some(isFunctionOrArrowExpression$1);
34763 return group$2(expanded);
34766 return concat$6([// We only need to check `oneLine` because if `expanded` is chosen
34767 // that means that the parent group has already been broken
34769 willBreak$1(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$2 : "", conditionalGroup$1([oneLine, expanded])]);
34772 function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
34773 if (isFacebookTranslationTag) {
34777 if (childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement) {
34778 return child.length === 1 ? softline$2 : hardline$4;
34784 function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
34785 if (isFacebookTranslationTag) {
34789 if (child.length === 1) {
34790 return childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement ? hardline$4 : softline$2;
34794 } // JSX Children are strange, mostly for two reasons:
34795 // 1. JSX reads newlines into string values, instead of skipping them like JS
34796 // 2. up to one whitespace between elements within a line is significant,
34797 // but not between lines.
34799 // Leading, trailing, and lone whitespace all need to
34800 // turn themselves into the rather ugly `{' '}` when breaking.
34802 // We print JSX using the `fill` doc primitive.
34803 // This requires that we give it an array of alternating
34804 // content and whitespace elements.
34805 // To ensure this we add dummy `""` content elements as needed.
34808 function printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag) {
34809 var n = path.getValue();
34810 var children = []; // using `map` instead of `each` because it provides `i`
34812 path.map(function (childPath, i) {
34813 var child = childPath.getValue();
34815 if (isLiteral$1(child)) {
34816 var text = rawText$1(child); // Contains a non-whitespace character
34818 if (isMeaningfulJSXText$1(child)) {
34819 var words = text.split(matchJsxWhitespaceRegex$1); // Starts with whitespace
34821 if (words[0] === "") {
34825 if (/\n/.test(words[0])) {
34826 var next = n.children[i + 1];
34827 children.push(separatorWithWhitespace(isFacebookTranslationTag, words[1], child, next));
34829 children.push(jsxWhitespace);
34835 var endWhitespace; // Ends with whitespace
34837 if (getLast$2(words) === "") {
34839 endWhitespace = words.pop();
34840 } // This was whitespace only without a new line.
34843 if (words.length === 0) {
34847 words.forEach(function (word, i) {
34849 children.push(line$2);
34851 children.push(word);
34855 if (endWhitespace !== undefined) {
34856 if (/\n/.test(endWhitespace)) {
34857 var _next = n.children[i + 1];
34858 children.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$2(children), child, _next));
34860 children.push(jsxWhitespace);
34863 var _next2 = n.children[i + 1];
34864 children.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$2(children), child, _next2));
34866 } else if (/\n/.test(text)) {
34867 // Keep (up to one) blank line between tags/expressions/text.
34868 // Note: We don't keep blank lines between text elements.
34869 if (text.match(/\n/g).length > 1) {
34871 children.push(hardline$4);
34875 children.push(jsxWhitespace);
34878 var printedChild = print(childPath);
34879 children.push(printedChild);
34880 var _next3 = n.children[i + 1];
34882 var directlyFollowedByMeaningfulText = _next3 && isMeaningfulJSXText$1(_next3);
34884 if (directlyFollowedByMeaningfulText) {
34885 var firstWord = rawText$1(_next3).trim().split(matchJsxWhitespaceRegex$1)[0];
34886 children.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord, child, _next3));
34888 children.push(hardline$4);
34893 } // JSX expands children from the inside-out, instead of the outside-in.
34894 // This is both to break children before attributes,
34895 // and to ensure that when children break, their parents do as well.
34897 // Any element that is written without any newlines and fits on a single line
34898 // is left that way.
34899 // Not only that, any user-written-line containing multiple JSX siblings
34900 // should also be kept on one line if possible,
34901 // so each user-written-line is wrapped in its own group.
34903 // Elements that contain newlines or don't fit on a single line (recursively)
34904 // are fully-split, using hardline and shouldBreak: true.
34906 // To support that case properly, all leading and trailing spaces
34907 // are stripped from the list of children, and replaced with a single hardline.
34910 function printJSXElement(path, options, print) {
34911 var n = path.getValue();
34913 if (n.type === "JSXElement" && isEmptyJSXElement$1(n)) {
34914 return concat$6([path.call(print, "openingElement"), path.call(print, "closingElement")]);
34917 var openingLines = n.type === "JSXElement" ? path.call(print, "openingElement") : path.call(print, "openingFragment");
34918 var closingLines = n.type === "JSXElement" ? path.call(print, "closingElement") : path.call(print, "closingFragment");
34920 if (n.children.length === 1 && n.children[0].type === "JSXExpressionContainer" && (n.children[0].expression.type === "TemplateLiteral" || n.children[0].expression.type === "TaggedTemplateExpression")) {
34921 return concat$6([openingLines, concat$6(path.map(print, "children")), closingLines]);
34922 } // Convert `{" "}` to text nodes containing a space.
34923 // This makes it easy to turn them into `jsxWhitespace` which
34924 // can then print as either a space or `{" "}` when breaking.
34927 n.children = n.children.map(function (child) {
34928 if (isJSXWhitespaceExpression$1(child)) {
34938 var containsTag = n.children.filter(isJSXNode$1).length > 0;
34939 var containsMultipleExpressions = n.children.filter(function (child) {
34940 return child.type === "JSXExpressionContainer";
34942 var containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true.
34944 var forcedBreak = willBreak$1(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions;
34945 var rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}';
34946 var jsxWhitespace = ifBreak$1(concat$6([rawJsxWhitespace, softline$2]), " ");
34947 var isFacebookTranslationTag = n.openingElement && n.openingElement.name && n.openingElement.name.name === "fbt";
34948 var children = printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag);
34949 var containsText = n.children.filter(function (child) {
34950 return isMeaningfulJSXText$1(child);
34951 }).length > 0; // We can end up we multiple whitespace elements with empty string
34952 // content between them.
34953 // We need to remove empty whitespace and softlines before JSX whitespace
34954 // to get the correct output.
34956 for (var i = children.length - 2; i >= 0; i--) {
34957 var isPairOfEmptyStrings = children[i] === "" && children[i + 1] === "";
34958 var isPairOfHardlines = children[i] === hardline$4 && children[i + 1] === "" && children[i + 2] === hardline$4;
34959 var isLineFollowedByJSXWhitespace = (children[i] === softline$2 || children[i] === hardline$4) && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
34960 var isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$2 || children[i + 2] === hardline$4);
34961 var isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
34962 var isPairOfHardOrSoftLines = children[i] === softline$2 && children[i + 1] === "" && children[i + 2] === hardline$4 || children[i] === hardline$4 && children[i + 1] === "" && children[i + 2] === softline$2;
34964 if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace || isPairOfHardOrSoftLines) {
34965 children.splice(i, 2);
34966 } else if (isJSXWhitespaceFollowedByLine) {
34967 children.splice(i + 1, 2);
34969 } // Trim trailing lines (or empty strings)
34972 while (children.length && (isLineNext$1(getLast$2(children)) || isEmpty$1(getLast$2(children)))) {
34974 } // Trim leading lines (or empty strings)
34977 while (children.length && (isLineNext$1(children[0]) || isEmpty$1(children[0])) && (isLineNext$1(children[1]) || isEmpty$1(children[1]))) {
34980 } // Tweak how we format children if outputting this element over multiple lines.
34981 // Also detect whether we will force this element to output over multiple lines.
34984 var multilineChildren = [];
34985 children.forEach(function (child, i) {
34986 // There are a number of situations where we need to ensure we display
34987 // whitespace as `{" "}` when outputting this element over multiple lines.
34988 if (child === jsxWhitespace) {
34989 if (i === 1 && children[i - 1] === "") {
34990 if (children.length === 2) {
34991 // Solitary whitespace
34992 multilineChildren.push(rawJsxWhitespace);
34994 } // Leading whitespace
34997 multilineChildren.push(concat$6([rawJsxWhitespace, hardline$4]));
34999 } else if (i === children.length - 1) {
35000 // Trailing whitespace
35001 multilineChildren.push(rawJsxWhitespace);
35003 } else if (children[i - 1] === "" && children[i - 2] === hardline$4) {
35004 // Whitespace after line break
35005 multilineChildren.push(rawJsxWhitespace);
35010 multilineChildren.push(child);
35012 if (willBreak$1(child)) {
35013 forcedBreak = true;
35015 }); // If there is text we use `fill` to fit as much onto each line as possible.
35016 // When there is no text (just tags and expressions) we use `group`
35017 // to output each on a separate line.
35019 var content = containsText ? fill$2(multilineChildren) : group$2(concat$6(multilineChildren), {
35022 var multiLineElem = group$2(concat$6([openingLines, indent$3(concat$6([hardline$4, content])), hardline$4, closingLines]));
35025 return multiLineElem;
35028 return conditionalGroup$1([group$2(concat$6([openingLines, concat$6(children), closingLines])), multiLineElem]);
35031 function maybeWrapJSXElementInParens(path, elem, options) {
35032 var parent = path.getParentNode();
35038 var NO_WRAP_PARENTS = {
35039 ArrayExpression: true,
35040 JSXAttribute: true,
35042 JSXExpressionContainer: true,
35044 ExpressionStatement: true,
35045 CallExpression: true,
35046 OptionalCallExpression: true,
35047 ConditionalExpression: true,
35048 JsExpressionRoot: true
35051 if (NO_WRAP_PARENTS[parent.type]) {
35055 var shouldBreak = matchAncestorTypes$1(path, ["ArrowFunctionExpression", "CallExpression", "JSXExpressionContainer"]) || matchAncestorTypes$1(path, ["ArrowFunctionExpression", "OptionalCallExpression", "JSXExpressionContainer"]);
35056 var needsParens = needsParens_1(path, options);
35057 return group$2(concat$6([needsParens ? "" : ifBreak$1("("), indent$3(concat$6([softline$2, elem])), softline$2, needsParens ? "" : ifBreak$1(")")]), {
35062 function shouldInlineLogicalExpression(node) {
35063 if (node.type !== "LogicalExpression") {
35067 if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) {
35071 if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) {
35075 if (isJSXNode$1(node.right)) {
35080 } // For binary expressions to be consistent, we need to group
35081 // subsequent operators with the same precedence level under a single
35082 // group. Otherwise they will be nested such that some of them break
35083 // onto new lines but not all. Operators with the same precedence
35084 // level should either all break or not. Because we group them by
35085 // precedence level and the AST is structured based on precedence
35086 // level, things are naturally broken up correctly, i.e. `&&` is
35087 // broken before `+`.
35090 function printBinaryishExpressions(path, print, options, isNested, isInsideParenthesis) {
35092 var node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same.
35094 if (isBinaryish$1(node)) {
35095 // Put all operators with the same precedence level in the same
35096 // group. The reason we only need to do this with the `left`
35097 // expression is because given an expression like `1 + 2 - 3`, it
35098 // is always parsed like `((1 + 2) - 3)`, meaning the `left` side
35099 // is where the rest of the expression will exist. Binary
35100 // expressions on the right side mean they have a difference
35101 // precedence level and should be treated as a separate group, so
35102 // print them normally. (This doesn't hold for the `**` operator,
35103 // which is unique in that it is right-associative.)
35104 if (shouldFlatten$1(node.operator, node.left.operator)) {
35105 // Flatten them out by recursively calling this function.
35106 parts = parts.concat(path.call(function (left) {
35107 return printBinaryishExpressions(left, print, options,
35109 true, isInsideParenthesis);
35112 parts.push(path.call(print, "left"));
35115 var shouldInline = shouldInlineLogicalExpression(node);
35116 var lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment$1(options.originalText, node.right, options);
35117 var operator = node.type === "NGPipeExpression" ? "|" : node.operator;
35118 var rightSuffix = node.type === "NGPipeExpression" && node.arguments.length !== 0 ? group$2(indent$3(concat$6([softline$2, ": ", join$4(concat$6([softline$2, ":", ifBreak$1(" ")]), path.map(print, "arguments").map(function (arg) {
35119 return align$1(2, group$2(arg));
35121 var right = shouldInline ? concat$6([operator, " ", path.call(print, "right"), rightSuffix]) : concat$6([lineBeforeOperator ? softline$2 : "", operator, lineBeforeOperator ? " " : line$2, path.call(print, "right"), rightSuffix]); // If there's only a single binary expression, we want to create a group
35122 // in order to avoid having a small right part like -1 be on its own line.
35124 var parent = path.getParentNode();
35125 var shouldGroup = !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type;
35126 parts.push(" ", shouldGroup ? group$2(right) : right); // The root comments are already printed, but we need to manually print
35127 // the other ones since we don't call the normal print on BinaryExpression,
35128 // only for the left and right parts
35130 if (isNested && node.comments) {
35131 parts = comments.printComments(path, function () {
35132 return concat$6(parts);
35136 // Our stopping case. Simply print the node normally.
35137 parts.push(path.call(print));
35143 function printAssignmentRight(leftNode, rightNode, printedRight, options) {
35144 if (hasLeadingOwnLineComment$1(options.originalText, rightNode, options)) {
35145 return indent$3(concat$6([hardline$4, printedRight]));
35148 var canBreak = isBinaryish$1(rightNode) && !shouldInlineLogicalExpression(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish$1(rightNode.test) && !shouldInlineLogicalExpression(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || rightNode.type === "ClassExpression" && rightNode.decorators && rightNode.decorators.length || (leftNode.type === "Identifier" || isStringLiteral$1(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral$1(rightNode) || isMemberExpressionChain$1(rightNode)) && // do not put values on a separate line from the key in json
35149 options.parser !== "json" && options.parser !== "json5" || rightNode.type === "SequenceExpression";
35152 return group$2(indent$3(concat$6([line$2, printedRight])));
35155 return concat$6([" ", printedRight]);
35158 function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) {
35160 return printedLeft;
35163 var printed = printAssignmentRight(leftNode, rightNode, printedRight, options);
35164 return group$2(concat$6([printedLeft, operator, printed]));
35167 function adjustClause(node, clause, forceSpace) {
35168 if (node.type === "EmptyStatement") {
35172 if (node.type === "BlockStatement" || forceSpace) {
35173 return concat$6([" ", clause]);
35176 return indent$3(concat$6([line$2, clause]));
35179 function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) {
35180 var raw = rawText$1(node);
35181 var isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral";
35182 return printString$1(raw, options, isDirectiveLiteral);
35185 function printRegex(node) {
35186 var flags = node.flags.split("").sort().join("");
35187 return `/${node.pattern}/${flags}`;
35190 function exprNeedsASIProtection(path, options) {
35191 var node = path.getValue();
35192 var maybeASIProblem = needsParens_1(path, options) || node.type === "ParenthesizedExpression" || node.type === "TypeCastExpression" || node.type === "ArrowFunctionExpression" && !shouldPrintParamsWithoutParens(path, options) || node.type === "ArrayExpression" || node.type === "ArrayPattern" || node.type === "UnaryExpression" && node.prefix && (node.operator === "+" || node.operator === "-") || node.type === "TemplateLiteral" || node.type === "TemplateElement" || isJSXNode$1(node) || node.type === "BindExpression" && !node.object || node.type === "RegExpLiteral" || node.type === "Literal" && node.pattern || node.type === "Literal" && node.regex;
35194 if (maybeASIProblem) {
35198 if (!hasNakedLeftSide$2(node)) {
35202 return path.call.apply(path, [function (childPath) {
35203 return exprNeedsASIProtection(childPath, options);
35204 }].concat(getLeftSidePathName$2(path, node)));
35207 function stmtNeedsASIProtection(path, options) {
35208 var node = path.getNode();
35210 if (node.type !== "ExpressionStatement") {
35214 return path.call(function (childPath) {
35215 return exprNeedsASIProtection(childPath, options);
35219 function shouldHugType(node) {
35220 if (isSimpleFlowType$1(node) || isObjectType$1(node)) {
35224 if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") {
35225 var voidCount = node.types.filter(function (n) {
35226 return n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword";
35228 var objectCount = node.types.filter(function (n) {
35229 return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}>
35230 n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference";
35233 if (node.types.length - 1 === voidCount && objectCount > 0) {
35241 function shouldHugArguments(fun) {
35242 return fun && fun.params && fun.params.length === 1 && !fun.params[0].comments && (fun.params[0].type === "ObjectPattern" || fun.params[0].type === "ArrayPattern" || fun.params[0].type === "Identifier" && fun.params[0].typeAnnotation && (fun.params[0].typeAnnotation.type === "TypeAnnotation" || fun.params[0].typeAnnotation.type === "TSTypeAnnotation") && isObjectType$1(fun.params[0].typeAnnotation.typeAnnotation) || fun.params[0].type === "FunctionTypeParam" && isObjectType$1(fun.params[0].typeAnnotation) || fun.params[0].type === "AssignmentPattern" && (fun.params[0].left.type === "ObjectPattern" || fun.params[0].left.type === "ArrayPattern") && (fun.params[0].right.type === "Identifier" || fun.params[0].right.type === "ObjectExpression" && fun.params[0].right.properties.length === 0 || fun.params[0].right.type === "ArrayExpression" && fun.params[0].right.elements.length === 0)) && !fun.rest;
35245 function printArrayItems(path, options, printPath, print) {
35246 var printedElements = [];
35247 var separatorParts = [];
35248 path.each(function (childPath) {
35249 printedElements.push(concat$6(separatorParts));
35250 printedElements.push(group$2(print(childPath)));
35251 separatorParts = [",", line$2];
35253 if (childPath.getValue() && isNextLineEmpty$2(options.originalText, childPath.getValue(), options)) {
35254 separatorParts.push(softline$2);
35257 return concat$6(printedElements);
35260 function willPrintOwnComments(path
35263 var node = path.getValue();
35264 var parent = path.getParentNode();
35265 return (node && (isJSXNode$1(node) || hasFlowShorthandAnnotationComment$2(node) || parent && (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && (hasFlowAnnotationComment$1(node.leadingComments) || hasFlowAnnotationComment$1(node.trailingComments))) || parent && (parent.type === "JSXSpreadAttribute" || parent.type === "JSXSpreadChild" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node)) && !hasIgnoreComment$2(path);
35268 function canAttachComment(node) {
35269 return node.type && node.type !== "CommentBlock" && node.type !== "CommentLine" && node.type !== "Line" && node.type !== "Block" && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import";
35272 function printComment$1(commentPath, options) {
35273 var comment = commentPath.getValue();
35275 switch (comment.type) {
35276 case "CommentBlock":
35279 if (isIndentableBlockComment(comment)) {
35280 var printed = printIndentableBlockComment(comment); // We need to prevent an edge case of a previous trailing comment
35281 // printed as a `lineSuffix` which causes the comments to be
35282 // interleaved. See https://github.com/prettier/prettier/issues/4412
35284 if (comment.trailing && !hasNewline$3(options.originalText, options.locStart(comment), {
35287 return concat$6([hardline$4, printed]);
35293 var isInsideFlowComment = options.originalText.substr(options.locEnd(comment) - 3, 3) === "*-/";
35294 return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/");
35297 case "CommentLine":
35299 // Print shebangs with the proper comment characters
35300 if (options.originalText.slice(options.locStart(comment)).startsWith("#!")) {
35301 return "#!" + comment.value.trimRight();
35304 return "//" + comment.value.trimRight();
35307 throw new Error("Not a comment: " + JSON.stringify(comment));
35311 function isIndentableBlockComment(comment) {
35312 // If the comment has multiple lines and every line starts with a star
35313 // we can fix the indentation of each line. The stars in the `/*` and
35314 // `*/` delimiters are not included in the comment value, so add them
35316 var lines = `*${comment.value}*`.split("\n");
35317 return lines.length > 1 && lines.every(function (line) {
35318 return line.trim()[0] === "*";
35322 function printIndentableBlockComment(comment) {
35323 var lines = comment.value.split("\n");
35324 return concat$6(["/*", join$4(hardline$4, lines.map(function (line, index) {
35325 return index === 0 ? line.trimRight() : " " + (index < lines.length - 1 ? line.trim() : line.trimLeft());
35329 var printerEstree = {
35330 preprocess: preprocess_1,
35331 print: genericPrint,
35333 insertPragma: insertPragma$1,
35334 massageAstNode: clean_1,
35335 hasPrettierIgnore: hasPrettierIgnore$1,
35336 willPrintOwnComments,
35338 printComment: printComment$1,
35339 isBlockComment: comments$1.isBlockComment,
35341 ownLine: comments$1.handleOwnLineComment,
35342 endOfLine: comments$1.handleEndOfLineComment,
35343 remaining: comments$1.handleRemainingComment
35347 var _require$$0$builders$2 = doc.builders,
35348 concat$7 = _require$$0$builders$2.concat,
35349 hardline$5 = _require$$0$builders$2.hardline,
35350 indent$4 = _require$$0$builders$2.indent,
35351 join$5 = _require$$0$builders$2.join;
35353 function genericPrint$1(path, options, print) {
35354 var node = path.getValue();
35356 switch (node.type) {
35358 return concat$7([path.call(print, "node"), hardline$5]);
35360 case "ArrayExpression":
35361 return node.elements.length === 0 ? "[]" : concat$7(["[", indent$4(concat$7([hardline$5, join$5(concat$7([",", hardline$5]), path.map(print, "elements"))])), hardline$5, "]"]);
35363 case "ObjectExpression":
35364 return node.properties.length === 0 ? "{}" : concat$7(["{", indent$4(concat$7([hardline$5, join$5(concat$7([",", hardline$5]), path.map(print, "properties"))])), hardline$5, "}"]);
35366 case "ObjectProperty":
35367 return concat$7([path.call(print, "key"), ": ", path.call(print, "value")]);
35369 case "UnaryExpression":
35370 return concat$7([node.operator === "+" ? "" : node.operator, path.call(print, "argument")]);
35372 case "NullLiteral":
35375 case "BooleanLiteral":
35376 return node.value ? "true" : "false";
35378 case "StringLiteral":
35379 case "NumericLiteral":
35380 return JSON.stringify(node.value);
35383 return JSON.stringify(node.name);
35386 /* istanbul ignore next */
35387 throw new Error("unknown type: " + JSON.stringify(node.type));
35391 function clean$1(node, newNode
35394 delete newNode.start;
35395 delete newNode.end;
35396 delete newNode.extra;
35397 delete newNode.loc;
35398 delete newNode.comments;
35399 delete newNode.errors;
35401 if (node.type === "Identifier") {
35403 type: "StringLiteral",
35408 if (node.type === "UnaryExpression" && node.operator === "+") {
35409 return newNode.argument;
35413 var printerEstreeJson = {
35414 preprocess: preprocess_1,
35415 print: genericPrint$1,
35416 massageAstNode: clean$1
35419 var CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
35421 var commonOptions = {
35424 category: CATEGORY_COMMON,
35427 description: "Print spaces between brackets.",
35428 oppositeDescription: "Do not print spaces between brackets."
35432 category: CATEGORY_COMMON,
35435 description: "Use single quotes instead of double quotes."
35439 category: CATEGORY_COMMON,
35448 description: "How to wrap prose.",
35452 description: "Wrap prose if it exceeds the print width."
35456 description: "Do not wrap prose."
35460 description: "Wrap prose as-is."
35463 deprecated: "1.9.0",
35467 deprecated: "1.9.0",
35473 var CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
35478 category: CATEGORY_JAVASCRIPT,
35481 description: "Include parentheses around a sole arrow function parameter.",
35484 description: "Omit parens when possible. Example: `x => x`"
35487 description: "Always include parens. Example: `(x) => x`"
35490 bracketSpacing: commonOptions.bracketSpacing,
35491 jsxBracketSameLine: {
35493 category: CATEGORY_JAVASCRIPT,
35496 description: "Put > on the last line instead of at a new line."
35500 category: CATEGORY_JAVASCRIPT,
35503 description: "Print semicolons.",
35504 oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them."
35506 singleQuote: commonOptions.singleQuote,
35509 category: CATEGORY_JAVASCRIPT,
35512 description: "Use single quotes in JSX."
35516 category: CATEGORY_JAVASCRIPT,
35518 default: "as-needed",
35519 description: "Change when properties in objects are quoted.",
35521 value: "as-needed",
35522 description: "Only add quotes around object properties where required."
35524 value: "consistent",
35525 description: "If at least one property in an object requires quotes, quote all properties."
35528 description: "Respect the input use of quotes in object properties."
35533 category: CATEGORY_JAVASCRIPT,
35542 description: "Print trailing commas wherever possible when multi-line.",
35545 description: "No trailing commas."
35548 description: "Trailing commas where valid in ES5 (objects, arrays, etc.)"
35551 description: "Trailing commas wherever possible (including function arguments)."
35554 deprecated: "0.19.0",
35558 deprecated: "0.19.0",
35564 var createLanguage = function createLanguage(linguistData, transform) {
35567 for (var key in linguistData) {
35568 var newKey = key === "languageId" ? "linguistLanguageId" : key;
35569 language[newKey] = linguistData[key];
35572 return transform(language);
35575 var name$2 = "JavaScript";
35576 var type = "programming";
35577 var tmScope = "source.js";
35578 var aceMode = "javascript";
35579 var codemirrorMode = "javascript";
35580 var codemirrorMimeType = "text/javascript";
35581 var color = "#f1e05a";
35611 var interpreters = [
35620 var languageId = 183;
35626 codemirrorMode: codemirrorMode,
35627 codemirrorMimeType: codemirrorMimeType,
35630 extensions: extensions,
35631 filenames: filenames,
35632 interpreters: interpreters,
35633 languageId: languageId
35636 var JavaScript$1 = /*#__PURE__*/Object.freeze({
35642 codemirrorMode: codemirrorMode,
35643 codemirrorMimeType: codemirrorMimeType,
35646 extensions: extensions,
35647 filenames: filenames,
35648 interpreters: interpreters,
35649 languageId: languageId,
35650 'default': JavaScript
35653 var name$3 = "JSX";
35654 var type$1 = "programming";
35655 var group$3 = "JavaScript";
35656 var extensions$1 = [
35659 var tmScope$1 = "source.js.jsx";
35660 var aceMode$1 = "javascript";
35661 var codemirrorMode$1 = "jsx";
35662 var codemirrorMimeType$1 = "text/jsx";
35663 var languageId$1 = 178;
35668 extensions: extensions$1,
35669 tmScope: tmScope$1,
35670 aceMode: aceMode$1,
35671 codemirrorMode: codemirrorMode$1,
35672 codemirrorMimeType: codemirrorMimeType$1,
35673 languageId: languageId$1
35676 var JSX$1 = /*#__PURE__*/Object.freeze({
35681 extensions: extensions$1,
35682 tmScope: tmScope$1,
35683 aceMode: aceMode$1,
35684 codemirrorMode: codemirrorMode$1,
35685 codemirrorMimeType: codemirrorMimeType$1,
35686 languageId: languageId$1,
35690 var name$4 = "TypeScript";
35691 var type$2 = "programming";
35692 var color$1 = "#2b7489";
35696 var interpreters$1 = [
35700 var extensions$2 = [
35703 var tmScope$2 = "source.ts";
35704 var aceMode$2 = "typescript";
35705 var codemirrorMode$2 = "javascript";
35706 var codemirrorMimeType$2 = "application/typescript";
35707 var languageId$2 = 378;
35712 aliases: aliases$1,
35713 interpreters: interpreters$1,
35714 extensions: extensions$2,
35715 tmScope: tmScope$2,
35716 aceMode: aceMode$2,
35717 codemirrorMode: codemirrorMode$2,
35718 codemirrorMimeType: codemirrorMimeType$2,
35719 languageId: languageId$2
35722 var TypeScript$1 = /*#__PURE__*/Object.freeze({
35727 aliases: aliases$1,
35728 interpreters: interpreters$1,
35729 extensions: extensions$2,
35730 tmScope: tmScope$2,
35731 aceMode: aceMode$2,
35732 codemirrorMode: codemirrorMode$2,
35733 codemirrorMimeType: codemirrorMimeType$2,
35734 languageId: languageId$2,
35735 'default': TypeScript
35738 var name$5 = "TSX";
35739 var type$3 = "programming";
35740 var group$4 = "TypeScript";
35741 var extensions$3 = [
35744 var tmScope$3 = "source.tsx";
35745 var aceMode$3 = "javascript";
35746 var codemirrorMode$3 = "jsx";
35747 var codemirrorMimeType$3 = "text/jsx";
35748 var languageId$3 = 94901924;
35753 extensions: extensions$3,
35754 tmScope: tmScope$3,
35755 aceMode: aceMode$3,
35756 codemirrorMode: codemirrorMode$3,
35757 codemirrorMimeType: codemirrorMimeType$3,
35758 languageId: languageId$3
35761 var TSX$1 = /*#__PURE__*/Object.freeze({
35766 extensions: extensions$3,
35767 tmScope: tmScope$3,
35768 aceMode: aceMode$3,
35769 codemirrorMode: codemirrorMode$3,
35770 codemirrorMimeType: codemirrorMimeType$3,
35771 languageId: languageId$3,
35775 var name$6 = "JSON";
35776 var type$4 = "data";
35777 var tmScope$4 = "source.json";
35778 var aceMode$4 = "json";
35779 var codemirrorMode$4 = "javascript";
35780 var codemirrorMimeType$4 = "application/json";
35781 var searchable = false;
35782 var extensions$4 = [
35789 ".JSON-tmLanguage",
35800 var filenames$1 = [
35809 var languageId$4 = 174;
35813 tmScope: tmScope$4,
35814 aceMode: aceMode$4,
35815 codemirrorMode: codemirrorMode$4,
35816 codemirrorMimeType: codemirrorMimeType$4,
35817 searchable: searchable,
35818 extensions: extensions$4,
35819 filenames: filenames$1,
35820 languageId: languageId$4
35823 var _JSON$1 = /*#__PURE__*/Object.freeze({
35827 tmScope: tmScope$4,
35828 aceMode: aceMode$4,
35829 codemirrorMode: codemirrorMode$4,
35830 codemirrorMimeType: codemirrorMimeType$4,
35831 searchable: searchable,
35832 extensions: extensions$4,
35833 filenames: filenames$1,
35834 languageId: languageId$4,
35838 var name$7 = "JSON with Comments";
35839 var type$5 = "data";
35840 var group$5 = "JSON";
35841 var tmScope$5 = "source.js";
35842 var aceMode$5 = "javascript";
35843 var codemirrorMode$5 = "javascript";
35844 var codemirrorMimeType$5 = "text/javascript";
35848 var extensions$5 = [
35850 ".sublime-commands",
35851 ".sublime-completions",
35855 ".sublime-mousemap",
35856 ".sublime-project",
35857 ".sublime-settings",
35859 ".sublime-workspace",
35860 ".sublime_metrics",
35863 var filenames$2 = [
35870 "language-configuration.json",
35873 var languageId$5 = 423;
35874 var JSON_with_Comments = {
35878 tmScope: tmScope$5,
35879 aceMode: aceMode$5,
35880 codemirrorMode: codemirrorMode$5,
35881 codemirrorMimeType: codemirrorMimeType$5,
35882 aliases: aliases$2,
35883 extensions: extensions$5,
35884 filenames: filenames$2,
35885 languageId: languageId$5
35888 var JSON_with_Comments$1 = /*#__PURE__*/Object.freeze({
35893 tmScope: tmScope$5,
35894 aceMode: aceMode$5,
35895 codemirrorMode: codemirrorMode$5,
35896 codemirrorMimeType: codemirrorMimeType$5,
35897 aliases: aliases$2,
35898 extensions: extensions$5,
35899 filenames: filenames$2,
35900 languageId: languageId$5,
35901 'default': JSON_with_Comments
35904 var name$8 = "JSON5";
35905 var type$6 = "data";
35906 var extensions$6 = [
35909 var tmScope$6 = "source.js";
35910 var aceMode$6 = "javascript";
35911 var codemirrorMode$6 = "javascript";
35912 var codemirrorMimeType$6 = "application/json";
35913 var languageId$6 = 175;
35917 extensions: extensions$6,
35918 tmScope: tmScope$6,
35919 aceMode: aceMode$6,
35920 codemirrorMode: codemirrorMode$6,
35921 codemirrorMimeType: codemirrorMimeType$6,
35922 languageId: languageId$6
35925 var JSON5$1 = /*#__PURE__*/Object.freeze({
35929 extensions: extensions$6,
35930 tmScope: tmScope$6,
35931 aceMode: aceMode$6,
35932 codemirrorMode: codemirrorMode$6,
35933 codemirrorMimeType: codemirrorMimeType$6,
35934 languageId: languageId$6,
35938 var require$$0$2 = getCjsExportFromNamespace(JavaScript$1);
35940 var require$$1 = getCjsExportFromNamespace(JSX$1);
35942 var require$$2 = getCjsExportFromNamespace(TypeScript$1);
35944 var require$$3 = getCjsExportFromNamespace(TSX$1);
35946 var require$$4$1 = getCjsExportFromNamespace(_JSON$1);
35948 var require$$5 = getCjsExportFromNamespace(JSON_with_Comments$1);
35950 var require$$6 = getCjsExportFromNamespace(JSON5$1);
35952 var languages = [createLanguage(require$$0$2, function (data) {
35953 return Object.assign(data, {
35955 parsers: ["babel", "flow"],
35956 vscodeLanguageIds: ["javascript", "mongo"],
35957 interpreters: data.interpreters.concat(["nodejs"])
35959 }), createLanguage(require$$0$2, function (data) {
35960 return Object.assign(data, {
35963 parsers: ["babel", "flow"],
35964 vscodeLanguageIds: ["javascript"],
35967 extensions: [".js.flow"]
35969 }), createLanguage(require$$1, function (data) {
35970 return Object.assign(data, {
35972 parsers: ["babel", "flow"],
35973 vscodeLanguageIds: ["javascriptreact"]
35975 }), createLanguage(require$$2, function (data) {
35976 return Object.assign(data, {
35978 parsers: ["typescript"],
35979 vscodeLanguageIds: ["typescript"]
35981 }), createLanguage(require$$3, function (data) {
35982 return Object.assign(data, {
35984 parsers: ["typescript"],
35985 vscodeLanguageIds: ["typescriptreact"]
35987 }), createLanguage(require$$4$1, function (data) {
35988 return Object.assign(data, {
35989 name: "JSON.stringify",
35991 parsers: ["json-stringify"],
35992 vscodeLanguageIds: ["json"],
35994 // .json file defaults to json instead of json-stringify
35995 filenames: ["package.json", "package-lock.json", "composer.json"]
35997 }), createLanguage(require$$4$1, function (data) {
35998 return Object.assign(data, {
36001 vscodeLanguageIds: ["json"],
36002 filenames: data.filenames.concat([".prettierrc"])
36004 }), createLanguage(require$$5, function (data) {
36005 return Object.assign(data, {
36008 vscodeLanguageIds: ["jsonc"],
36009 filenames: data.filenames.concat([".eslintrc"])
36011 }), createLanguage(require$$6, function (data) {
36012 return Object.assign(data, {
36014 parsers: ["json5"],
36015 vscodeLanguageIds: ["json5"]
36019 estree: printerEstree,
36020 "estree-json": printerEstreeJson
36024 options: options$2,
36179 var htmlTagNames = /*#__PURE__*/Object.freeze({
36184 var htmlTagNames$1 = getCjsExportFromNamespace(htmlTagNames);
36186 function clean$2(ast, newObj, parent) {
36187 ["raw", // front-matter
36188 "raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(function (name) {
36189 delete newObj[name];
36192 if (ast.type === "yaml") {
36193 delete newObj.value;
36194 } // --insert-pragma
36197 if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0 && ( // first non-front-matter comment
36198 parent.nodes[0] === ast || (parent.nodes[0].type === "yaml" || parent.nodes[0].type === "toml") && parent.nodes[1] === ast)) {
36204 delete newObj.text; // standalone pragma
36206 if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) {
36211 if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") {
36212 delete newObj.value;
36215 if (ast.type === "css-rule") {
36216 delete newObj.params;
36219 if (ast.type === "selector-combinator") {
36220 newObj.value = newObj.value.replace(/\s+/g, " ");
36223 if (ast.type === "media-feature") {
36224 newObj.value = newObj.value.replace(/ /g, "");
36227 if (ast.type === "value-word" && (ast.isColor && ast.isHex || ["initial", "inherit", "unset", "revert"].indexOf(newObj.value.replace().toLowerCase()) !== -1) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || ast.type === "selector-pseudo") {
36228 newObj.value = newObj.value.toLowerCase();
36231 if (ast.type === "css-decl") {
36232 newObj.prop = newObj.prop.toLowerCase();
36235 if (ast.type === "css-atrule" || ast.type === "css-import") {
36236 newObj.name = newObj.name.toLowerCase();
36239 if (ast.type === "value-number") {
36240 newObj.unit = newObj.unit.toLowerCase();
36243 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) {
36244 newObj.value = cleanCSSStrings(newObj.value);
36247 if (ast.type === "selector-attribute") {
36248 newObj.attribute = newObj.attribute.trim();
36250 if (newObj.namespace) {
36251 if (typeof newObj.namespace === "string") {
36252 newObj.namespace = newObj.namespace.trim();
36254 if (newObj.namespace.length === 0) {
36255 newObj.namespace = true;
36260 if (newObj.value) {
36261 newObj.value = newObj.value.trim().replace(/^['"]|['"]$/g, "");
36262 delete newObj.quoted;
36266 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) {
36267 newObj.value = newObj.value.replace(/([\d.eE+-]+)([a-zA-Z]*)/g, function (match, numStr, unit) {
36268 var num = Number(numStr);
36269 return isNaN(num) ? match : num + unit.toLowerCase();
36273 if (ast.type === "selector-tag") {
36274 var lowercasedValue = ast.value.toLowerCase();
36276 if (htmlTagNames$1.indexOf(lowercasedValue) !== -1) {
36277 newObj.value = lowercasedValue;
36280 if (["from", "to"].indexOf(lowercasedValue) !== -1) {
36281 newObj.value = lowercasedValue;
36283 } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func`
36286 if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") {
36287 delete newObj.value;
36288 } // Workaround for SCSS nested properties
36291 if (ast.type === "selector-unknown") {
36292 delete newObj.value;
36296 function cleanCSSStrings(value) {
36297 return value.replace(/'/g, '"').replace(/\\([^a-fA-F\d])/g, "$1");
36300 var clean_1$1 = clean$2;
36302 var _require$$0$builders$3 = doc.builders,
36303 hardline$6 = _require$$0$builders$3.hardline,
36304 literalline$3 = _require$$0$builders$3.literalline,
36305 concat$8 = _require$$0$builders$3.concat,
36306 markAsRoot$1 = _require$$0$builders$3.markAsRoot,
36307 mapDoc$4 = doc.utils.mapDoc;
36309 function embed$1(path, print, textToDoc
36312 var node = path.getValue();
36314 if (node.type === "yaml") {
36315 return markAsRoot$1(concat$8(["---", hardline$6, node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
36317 })) : "", "---", hardline$6]));
36322 function replaceNewlinesWithLiterallines(doc) {
36323 return mapDoc$4(doc, function (currentDoc) {
36324 return typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$8(currentDoc.split(/(\n)/g).map(function (v, i) {
36325 return i % 2 === 0 ? v : literalline$3;
36331 var embed_1$1 = embed$1;
36333 var DELIMITER_MAP = {
36338 function parse$3(text) {
36339 var delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp).join("|");
36340 var match = text.match( // trailing spaces after delimiters are allowed
36341 new RegExp(`^(${delimiterRegex})[^\\n\\S]*\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)`));
36343 if (match === null) {
36350 var raw = match[0].replace(/\n$/, "");
36351 var delimiter = match[1];
36352 var value = match[2];
36355 type: DELIMITER_MAP[delimiter],
36359 content: match[0].replace(/[^\n]/g, " ") + text.slice(match[0].length)
36363 var frontMatter = parse$3;
36365 function hasPragma$1(text) {
36366 return pragma.hasPragma(frontMatter(text).content);
36369 function insertPragma$2(text) {
36370 var _parseFrontMatter = frontMatter(text),
36371 frontMatter$1 = _parseFrontMatter.frontMatter,
36372 content = _parseFrontMatter.content;
36374 return (frontMatter$1 ? frontMatter$1.raw + "\n\n" : "") + pragma.insertPragma(content);
36378 hasPragma: hasPragma$1,
36379 insertPragma: insertPragma$2
36382 var colorAdjusterFunctions = ["red", "green", "blue", "alpha", "a", "rgb", "hue", "h", "saturation", "s", "lightness", "l", "whiteness", "w", "blackness", "b", "tint", "shade", "blend", "blenda", "contrast", "hsl", "hsla", "hwb", "hwba"];
36384 function getAncestorCounter(path, typeOrTypes) {
36385 var types = [].concat(typeOrTypes);
36389 while (ancestorNode = path.getParentNode(++counter)) {
36390 if (types.indexOf(ancestorNode.type) !== -1) {
36398 function getAncestorNode(path, typeOrTypes) {
36399 var counter = getAncestorCounter(path, typeOrTypes);
36400 return counter === -1 ? null : path.getParentNode(counter);
36403 function getPropOfDeclNode(path) {
36404 var declAncestorNode = getAncestorNode(path, "css-decl");
36405 return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase();
36408 function isSCSS(parser, text) {
36409 var hasExplicitParserChoice = parser === "less" || parser === "scss";
36410 var IS_POSSIBLY_SCSS = /(\w\s*: [^}:]+|#){|@import[^\n]+(url|,)/;
36411 return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text);
36414 function isWideKeywords(value) {
36415 return ["initial", "inherit", "unset", "revert"].indexOf(value.toLowerCase()) !== -1;
36418 function isKeyframeAtRuleKeywords(path, value) {
36419 var atRuleAncestorNode = getAncestorNode(path, "css-atrule");
36420 return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].indexOf(value.toLowerCase()) !== -1;
36423 function maybeToLowerCase(value) {
36424 return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase();
36427 function insideValueFunctionNode(path, functionName) {
36428 var funcAncestorNode = getAncestorNode(path, "value-func");
36429 return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName;
36432 function insideICSSRuleNode(path) {
36433 var ruleAncestorNode = getAncestorNode(path, "css-rule");
36434 return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export"));
36437 function insideAtRuleNode(path, atRuleNameOrAtRuleNames) {
36438 var atRuleNames = [].concat(atRuleNameOrAtRuleNames);
36439 var atRuleAncestorNode = getAncestorNode(path, "css-atrule");
36440 return atRuleAncestorNode && atRuleNames.indexOf(atRuleAncestorNode.name.toLowerCase()) !== -1;
36443 function insideURLFunctionInImportAtRuleNode(path) {
36444 var node = path.getValue();
36445 var atRuleAncestorNode = getAncestorNode(path, "css-atrule");
36446 return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2;
36449 function isURLFunctionNode(node) {
36450 return node.type === "value-func" && node.value.toLowerCase() === "url";
36453 function isLastNode(path, node) {
36454 var parentNode = path.getParentNode();
36460 var nodes = parentNode.nodes;
36461 return nodes && nodes.indexOf(node) === nodes.length - 1;
36464 function isHTMLTag(value) {
36465 return htmlTagNames$1.indexOf(value.toLowerCase()) !== -1;
36468 function isDetachedRulesetDeclarationNode(node) {
36469 // If a Less file ends up being parsed with the SCSS parser, Less
36470 // variable declarations will be parsed as atrules with names ending
36471 // with a colon, so keep the original case then.
36472 if (!node.selector) {
36476 return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value);
36479 function isForKeywordNode(node) {
36480 return node.type === "value-word" && ["from", "through", "end"].indexOf(node.value) !== -1;
36483 function isIfElseKeywordNode(node) {
36484 return node.type === "value-word" && ["and", "or", "not"].indexOf(node.value) !== -1;
36487 function isEachKeywordNode(node) {
36488 return node.type === "value-word" && node.value === "in";
36491 function isMultiplicationNode(node) {
36492 return node.type === "value-operator" && node.value === "*";
36495 function isDivisionNode(node) {
36496 return node.type === "value-operator" && node.value === "/";
36499 function isAdditionNode(node) {
36500 return node.type === "value-operator" && node.value === "+";
36503 function isSubtractionNode(node) {
36504 return node.type === "value-operator" && node.value === "-";
36507 function isModuloNode(node) {
36508 return node.type === "value-operator" && node.value === "%";
36511 function isMathOperatorNode(node) {
36512 return isMultiplicationNode(node) || isDivisionNode(node) || isAdditionNode(node) || isSubtractionNode(node) || isModuloNode(node);
36515 function isEqualityOperatorNode(node) {
36516 return node.type === "value-word" && ["==", "!="].indexOf(node.value) !== -1;
36519 function isRelationalOperatorNode(node) {
36520 return node.type === "value-word" && ["<", ">", "<=", ">="].indexOf(node.value) !== -1;
36523 function isSCSSControlDirectiveNode(node) {
36524 return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].indexOf(node.name) !== -1;
36527 function isSCSSNestedPropertyNode(node) {
36528 if (!node.selector) {
36532 return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":");
36535 function isDetachedRulesetCallNode(node) {
36536 return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params);
36539 function isTemplatePlaceholderNode(node) {
36540 return node.name.startsWith("prettier-placeholder");
36543 function isTemplatePropNode(node) {
36544 return node.prop.startsWith("@prettier-placeholder");
36547 function isPostcssSimpleVarNode(currentNode, nextNode) {
36548 return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before;
36551 function hasComposesNode(node) {
36552 return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes";
36555 function hasParensAroundNode(node) {
36556 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;
36559 function hasEmptyRawBefore(node) {
36560 return node.raws && node.raws.before === "";
36563 function isKeyValuePairNode(node) {
36564 return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon";
36567 function isKeyValuePairInParenGroupNode(node) {
36568 return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode(node.groups[0]);
36571 function isSCSSMapItemNode(path) {
36572 var node = path.getValue(); // Ignore empty item (i.e. `$key: ()`)
36574 if (node.groups.length === 0) {
36578 var parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`)
36580 if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) {
36584 var declNode = getAncestorNode(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`)
36586 if (declNode && declNode.prop && declNode.prop.startsWith("$")) {
36588 } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`)
36591 if (isKeyValuePairInParenGroupNode(parentParentNode)) {
36593 } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`)
36596 if (parentParentNode.type === "value-func") {
36603 function isInlineValueCommentNode(node) {
36604 return node.type === "value-comment" && node.inline;
36607 function isHashNode(node) {
36608 return node.type === "value-word" && node.value === "#";
36611 function isLeftCurlyBraceNode(node) {
36612 return node.type === "value-word" && node.value === "{";
36615 function isRightCurlyBraceNode(node) {
36616 return node.type === "value-word" && node.value === "}";
36619 function isWordNode(node) {
36620 return ["value-word", "value-atword"].indexOf(node.type) !== -1;
36623 function isColonNode(node) {
36624 return node.type === "value-colon";
36627 function isMediaAndSupportsKeywords(node) {
36628 return node.value && ["not", "and", "or"].indexOf(node.value.toLowerCase()) !== -1;
36631 function isColorAdjusterFuncNode(node) {
36632 if (node.type !== "value-func") {
36636 return colorAdjusterFunctions.indexOf(node.value.toLowerCase()) !== -1;
36640 getAncestorCounter,
36644 insideValueFunctionNode,
36645 insideICSSRuleNode,
36647 insideURLFunctionInImportAtRuleNode,
36648 isKeyframeAtRuleKeywords,
36653 isSCSSControlDirectiveNode,
36654 isDetachedRulesetDeclarationNode,
36655 isRelationalOperatorNode,
36656 isEqualityOperatorNode,
36657 isMultiplicationNode,
36662 isMathOperatorNode,
36666 isIfElseKeywordNode,
36668 hasParensAroundNode,
36670 isSCSSNestedPropertyNode,
36671 isDetachedRulesetCallNode,
36672 isTemplatePlaceholderNode,
36673 isTemplatePropNode,
36674 isPostcssSimpleVarNode,
36675 isKeyValuePairNode,
36676 isKeyValuePairInParenGroupNode,
36678 isInlineValueCommentNode,
36680 isLeftCurlyBraceNode,
36681 isRightCurlyBraceNode,
36684 isMediaAndSupportsKeywords,
36685 isColorAdjusterFuncNode
36688 var insertPragma$3 = pragma$1.insertPragma;
36689 var printNumber$2 = util.printNumber,
36690 printString$2 = util.printString,
36691 hasIgnoreComment$3 = util.hasIgnoreComment,
36692 hasNewline$4 = util.hasNewline;
36693 var isNextLineEmpty$3 = utilShared.isNextLineEmpty;
36694 var _require$$3$builders = doc.builders,
36695 concat$9 = _require$$3$builders.concat,
36696 join$6 = _require$$3$builders.join,
36697 line$3 = _require$$3$builders.line,
36698 hardline$7 = _require$$3$builders.hardline,
36699 softline$3 = _require$$3$builders.softline,
36700 group$6 = _require$$3$builders.group,
36701 fill$3 = _require$$3$builders.fill,
36702 indent$5 = _require$$3$builders.indent,
36703 dedent$2 = _require$$3$builders.dedent,
36704 ifBreak$2 = _require$$3$builders.ifBreak,
36705 removeLines$2 = doc.utils.removeLines;
36706 var getAncestorNode$1 = utils$3.getAncestorNode,
36707 getPropOfDeclNode$1 = utils$3.getPropOfDeclNode,
36708 maybeToLowerCase$1 = utils$3.maybeToLowerCase,
36709 insideValueFunctionNode$1 = utils$3.insideValueFunctionNode,
36710 insideICSSRuleNode$1 = utils$3.insideICSSRuleNode,
36711 insideAtRuleNode$1 = utils$3.insideAtRuleNode,
36712 insideURLFunctionInImportAtRuleNode$1 = utils$3.insideURLFunctionInImportAtRuleNode,
36713 isKeyframeAtRuleKeywords$1 = utils$3.isKeyframeAtRuleKeywords,
36714 isHTMLTag$1 = utils$3.isHTMLTag,
36715 isWideKeywords$1 = utils$3.isWideKeywords,
36716 isSCSS$1 = utils$3.isSCSS,
36717 isLastNode$1 = utils$3.isLastNode,
36718 isSCSSControlDirectiveNode$1 = utils$3.isSCSSControlDirectiveNode,
36719 isDetachedRulesetDeclarationNode$1 = utils$3.isDetachedRulesetDeclarationNode,
36720 isRelationalOperatorNode$1 = utils$3.isRelationalOperatorNode,
36721 isEqualityOperatorNode$1 = utils$3.isEqualityOperatorNode,
36722 isMultiplicationNode$1 = utils$3.isMultiplicationNode,
36723 isDivisionNode$1 = utils$3.isDivisionNode,
36724 isAdditionNode$1 = utils$3.isAdditionNode,
36725 isSubtractionNode$1 = utils$3.isSubtractionNode,
36726 isMathOperatorNode$1 = utils$3.isMathOperatorNode,
36727 isEachKeywordNode$1 = utils$3.isEachKeywordNode,
36728 isForKeywordNode$1 = utils$3.isForKeywordNode,
36729 isURLFunctionNode$1 = utils$3.isURLFunctionNode,
36730 isIfElseKeywordNode$1 = utils$3.isIfElseKeywordNode,
36731 hasComposesNode$1 = utils$3.hasComposesNode,
36732 hasParensAroundNode$1 = utils$3.hasParensAroundNode,
36733 hasEmptyRawBefore$1 = utils$3.hasEmptyRawBefore,
36734 isKeyValuePairNode$1 = utils$3.isKeyValuePairNode,
36735 isDetachedRulesetCallNode$1 = utils$3.isDetachedRulesetCallNode,
36736 isTemplatePlaceholderNode$1 = utils$3.isTemplatePlaceholderNode,
36737 isTemplatePropNode$1 = utils$3.isTemplatePropNode,
36738 isPostcssSimpleVarNode$1 = utils$3.isPostcssSimpleVarNode,
36739 isSCSSMapItemNode$1 = utils$3.isSCSSMapItemNode,
36740 isInlineValueCommentNode$1 = utils$3.isInlineValueCommentNode,
36741 isHashNode$1 = utils$3.isHashNode,
36742 isLeftCurlyBraceNode$1 = utils$3.isLeftCurlyBraceNode,
36743 isRightCurlyBraceNode$1 = utils$3.isRightCurlyBraceNode,
36744 isWordNode$1 = utils$3.isWordNode,
36745 isColonNode$1 = utils$3.isColonNode,
36746 isMediaAndSupportsKeywords$1 = utils$3.isMediaAndSupportsKeywords,
36747 isColorAdjusterFuncNode$1 = utils$3.isColorAdjusterFuncNode;
36749 function shouldPrintComma$1(options) {
36750 switch (options.trailingComma) {
36761 function genericPrint$2(path, options, print) {
36762 var node = path.getValue();
36763 /* istanbul ignore if */
36769 if (typeof node === "string") {
36773 switch (node.type) {
36776 return concat$9([node.raw, hardline$7]);
36780 var nodes = printNodeSequence(path, options, print);
36782 if (nodes.parts.length) {
36783 return concat$9([nodes, hardline$7]);
36789 case "css-comment":
36791 if (node.raws.content) {
36792 return node.raws.content;
36795 var text = options.originalText.slice(options.locStart(node), options.locEnd(node));
36796 var rawText = node.raws.text || node.text; // Workaround a bug where the location is off.
36797 // https://github.com/postcss/postcss-scss/issues/63
36799 if (text.indexOf(rawText) === -1) {
36800 if (node.raws.inline) {
36801 return concat$9(["// ", rawText]);
36804 return concat$9(["/* ", rawText, " */"]);
36812 return concat$9([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$9([" {", node.nodes.length > 0 ? indent$5(concat$9([hardline$7, printNodeSequence(path, options, print)])) : "", hardline$7, "}", isDetachedRulesetDeclarationNode$1(node) ? ";" : ""]) : ";"]);
36817 var parentNode = path.getParentNode();
36818 return concat$9([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode$1(path) ? node.prop : maybeToLowerCase$1(node.prop), node.raws.between.trim() === ":" ? ":" : node.raws.between.trim(), node.extend ? "" : " ", hasComposesNode$1(node) ? removeLines$2(path.call(print, "value")) : path.call(print, "value"), node.raws.important ? node.raws.important.replace(/\s*!\s*important/i, " !important") : node.important ? " !important" : "", node.raws.scssDefault ? node.raws.scssDefault.replace(/\s*!default/i, " !default") : node.scssDefault ? " !default" : "", node.raws.scssGlobal ? node.raws.scssGlobal.replace(/\s*!global/i, " !global") : node.scssGlobal ? " !global" : "", node.nodes ? concat$9([" {", indent$5(concat$9([softline$3, printNodeSequence(path, options, print)])), softline$3, "}"]) : isTemplatePropNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : ";"]);
36823 var _parentNode = path.getParentNode();
36825 return concat$9(["@", // If a Less file ends up being parsed with the SCSS parser, Less
36826 // variable declarations will be parsed as at-rules with names ending
36827 // with a colon, so keep the original case then.
36828 isDetachedRulesetCallNode$1(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase$1(node.name), node.params ? concat$9([isDetachedRulesetCallNode$1(node) ? "" : isTemplatePlaceholderNode$1(node) && /^\s*\n/.test(node.raws.afterName) ? /^\s*\n\s*\n/.test(node.raws.afterName) ? concat$9([hardline$7, hardline$7]) : hardline$7 : " ", path.call(print, "params")]) : "", node.selector ? indent$5(concat$9([" ", path.call(print, "selector")])) : "", node.value ? group$6(concat$9([" ", path.call(print, "value"), isSCSSControlDirectiveNode$1(node) ? hasParensAroundNode$1(node) ? " " : line$3 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$9([isSCSSControlDirectiveNode$1(node) ? "" : " ", "{", indent$5(concat$9([node.nodes.length > 0 ? softline$3 : "", printNodeSequence(path, options, print)])), softline$3, "}"]) : isTemplatePlaceholderNode$1(node) && !_parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : ";"]);
36830 // postcss-media-query-parser
36832 case "media-query-list":
36835 path.each(function (childPath) {
36836 var node = childPath.getValue();
36838 if (node.type === "media-query" && node.value === "") {
36842 parts.push(childPath.call(print));
36844 return group$6(indent$5(join$6(line$3, parts)));
36847 case "media-query":
36849 return concat$9([join$6(" ", path.map(print, "nodes")), isLastNode$1(path, node) ? "" : ","]);
36854 return adjustNumbers(adjustStrings(node.value, options));
36857 case "media-feature-expression":
36863 return concat$9(["(", concat$9(path.map(print, "nodes")), ")"]);
36866 case "media-feature":
36868 return maybeToLowerCase$1(adjustStrings(node.value.replace(/ +/g, " "), options));
36871 case "media-colon":
36873 return concat$9([node.value, " "]);
36876 case "media-value":
36878 return adjustNumbers(adjustStrings(node.value, options));
36881 case "media-keyword":
36883 return adjustStrings(node.value, options);
36888 return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options);
36891 case "media-unknown":
36895 // postcss-selector-parser
36897 case "selector-root":
36899 return group$6(concat$9([insideAtRuleNode$1(path, "custom-selector") ? concat$9([getAncestorNode$1(path, "css-atrule").customSelector, line$3]) : "", join$6(concat$9([",", insideAtRuleNode$1(path, ["extend", "custom-selector", "nest"]) ? line$3 : hardline$7]), path.map(print, "nodes"))]));
36902 case "selector-selector":
36904 return group$6(indent$5(concat$9(path.map(print, "nodes"))));
36907 case "selector-comment":
36912 case "selector-string":
36914 return adjustStrings(node.value, options);
36917 case "selector-tag":
36919 var _parentNode2 = path.getParentNode();
36921 var index = _parentNode2 && _parentNode2.nodes.indexOf(node);
36923 var prevNode = index && _parentNode2.nodes[index - 1];
36924 return concat$9([node.namespace ? concat$9([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isHTMLTag$1(node.value) || isKeyframeAtRuleKeywords$1(path, node.value) ? node.value.toLowerCase() : node.value)]);
36927 case "selector-id":
36929 return concat$9(["#", node.value]);
36932 case "selector-class":
36934 return concat$9([".", adjustNumbers(adjustStrings(node.value, options))]);
36937 case "selector-attribute":
36939 return concat$9(["[", node.namespace ? concat$9([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.attribute.trim(), node.operator ? node.operator : "", node.value ? quoteAttributeValue(adjustStrings(node.value.trim(), options), options) : "", node.insensitive ? " i" : "", "]"]);
36942 case "selector-combinator":
36944 if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") {
36945 var _parentNode3 = path.getParentNode();
36947 var _leading = _parentNode3.type === "selector-selector" && _parentNode3.nodes[0] === node ? "" : line$3;
36949 return concat$9([_leading, node.value, isLastNode$1(path, node) ? "" : " "]);
36952 var leading = node.value.trim().startsWith("(") ? line$3 : "";
36953 var value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$3;
36954 return concat$9([leading, value]);
36957 case "selector-universal":
36959 return concat$9([node.namespace ? concat$9([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]);
36962 case "selector-pseudo":
36964 return concat$9([maybeToLowerCase$1(node.value), node.nodes && node.nodes.length > 0 ? concat$9(["(", join$6(", ", path.map(print, "nodes")), ")"]) : ""]);
36967 case "selector-nesting":
36972 case "selector-unknown":
36974 var ruleAncestorNode = getAncestorNode$1(path, "css-rule"); // Nested SCSS property
36976 if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) {
36977 return adjustNumbers(adjustStrings(maybeToLowerCase$1(node.value), options));
36982 // postcss-values-parser
36984 case "value-value":
36987 return path.call(print, "group");
36990 case "value-comment":
36992 return concat$9([node.inline ? "//" : "/*", node.value, node.inline ? "" : "*/"]);
36995 case "value-comma_group":
36997 var _parentNode4 = path.getParentNode();
36999 var parentParentNode = path.getParentNode(1);
37000 var declAncestorProp = getPropOfDeclNode$1(path);
37001 var isGridValue = declAncestorProp && _parentNode4.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template"));
37002 var atRuleAncestorNode = getAncestorNode$1(path, "css-atrule");
37003 var isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode$1(atRuleAncestorNode);
37004 var printed = path.map(print, "groups");
37006 var insideURLFunction = insideValueFunctionNode$1(path, "url");
37007 var insideSCSSInterpolationInString = false;
37008 var didBreak = false;
37010 for (var i = 0; i < node.groups.length; ++i) {
37011 _parts.push(printed[i]); // Ignore value inside `url()`
37014 if (insideURLFunction) {
37018 var iPrevNode = node.groups[i - 1];
37019 var iNode = node.groups[i];
37020 var iNextNode = node.groups[i + 1];
37021 var iNextNextNode = node.groups[i + 2]; // Ignore after latest node (i.e. before semicolon)
37025 } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`)
37028 var isStartSCSSInterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{");
37029 var isEndingSCSSInterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}");
37031 if (isStartSCSSInterpolationInString || isEndingSCSSInterpolationInString) {
37032 insideSCSSInterpolationInString = !insideSCSSInterpolationInString;
37036 if (insideSCSSInterpolationInString) {
37038 } // Ignore colon (i.e. `:`)
37041 if (isColonNode$1(iNode) || isColonNode$1(iNextNode)) {
37043 } // Ignore `@` in Less (i.e. `@@var;`)
37046 if (iNode.type === "value-atword" && iNode.value === "") {
37048 } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`)
37051 if (iNode.value === "~") {
37053 } // Ignore escape `\`
37056 if (iNode.value && iNode.value.indexOf("\\") !== -1 && iNextNode && iNextNode.type !== "value-comment") {
37058 } // Ignore escaped `/`
37061 if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") {
37063 } // Ignore `\` (i.e. `$variable: \@small;`)
37066 if (iNode.value === "\\") {
37068 } // Ignore `$$` (i.e. `background-color: $$(style)Color;`)
37071 if (isPostcssSimpleVarNode$1(iNode, iNextNode)) {
37073 } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`)
37076 if (isHashNode$1(iNode) || isLeftCurlyBraceNode$1(iNode) || isRightCurlyBraceNode$1(iNextNode) || isLeftCurlyBraceNode$1(iNextNode) && hasEmptyRawBefore$1(iNextNode) || isRightCurlyBraceNode$1(iNode) && hasEmptyRawBefore$1(iNextNode)) {
37078 } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`)
37081 if (iNode.value === "--" && isHashNode$1(iNextNode)) {
37083 } // Formatting math operations
37086 var isMathOperator = isMathOperatorNode$1(iNode);
37087 var isNextMathOperator = isMathOperatorNode$1(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is
37088 // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`)
37089 // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`)
37091 if ((isMathOperator && isHashNode$1(iNextNode) || isNextMathOperator && isRightCurlyBraceNode$1(iNode)) && hasEmptyRawBefore$1(iNextNode)) {
37093 } // Print spaces before and after addition and subtraction math operators as is in `calc` function
37094 // due to the fact that it is not valid syntax
37095 // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`)
37098 if (insideValueFunctionNode$1(path, "calc") && (isAdditionNode$1(iNode) || isAdditionNode$1(iNextNode) || isSubtractionNode$1(iNode) || isSubtractionNode$1(iNextNode)) && hasEmptyRawBefore$1(iNextNode)) {
37100 } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`)
37101 // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is.
37104 var isColorAdjusterNode = (isAdditionNode$1(iNode) || isSubtractionNode$1(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode$1(parentParentNode) && !hasEmptyRawBefore$1(iNextNode);
37105 var requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode$1(iNextNextNode) || iNode.type === "value-func" || isWordNode$1(iNode);
37106 var requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode$1(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode$1(iPrevNode); // Formatting `/`, `+`, `-` sign
37108 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)))) {
37110 } // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`)
37113 if (isInlineValueCommentNode$1(iNode)) {
37114 _parts.push(hardline$7);
37117 } // Handle keywords in SCSS control directive
37120 if (isControlDirective && (isEqualityOperatorNode$1(iNextNode) || isRelationalOperatorNode$1(iNextNode) || isIfElseKeywordNode$1(iNextNode) || isEachKeywordNode$1(iNode) || isForKeywordNode$1(iNode))) {
37124 } // At-rule `namespace` should be in one line
37127 if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") {
37131 } // Formatting `grid` property
37135 if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) {
37136 _parts.push(hardline$7);
37144 } // Add `space` before next math operation
37145 // Note: `grip` property have `/` delimiter and it is not math operation, so
37146 // `grid` property handles above
37149 if (isNextMathOperator) {
37153 } // Be default all values go through `line`
37156 _parts.push(line$3);
37160 _parts.unshift(hardline$7);
37163 if (isControlDirective) {
37164 return group$6(indent$5(concat$9(_parts)));
37165 } // Indent is not needed for import url when url is very long
37166 // and node has two groups
37167 // when type is value-comma_group
37168 // example @import url("verylongurl") projection,tv
37171 if (insideURLFunctionInImportAtRuleNode$1(path)) {
37172 return group$6(fill$3(_parts));
37175 return group$6(indent$5(fill$3(_parts)));
37178 case "value-paren_group":
37180 var _parentNode5 = path.getParentNode();
37182 if (_parentNode5 && isURLFunctionNode$1(_parentNode5) && (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:"))) {
37183 return concat$9([node.open ? path.call(print, "open") : "", join$6(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]);
37187 var _printed = path.map(print, "groups");
37191 for (var _i = 0; _i < _printed.length; _i++) {
37193 res.push(concat$9([",", line$3]));
37196 res.push(_printed[_i]);
37199 return group$6(indent$5(fill$3(res)));
37202 var isSCSSMapItem = isSCSSMapItemNode$1(path);
37203 return group$6(concat$9([node.open ? path.call(print, "open") : "", indent$5(concat$9([softline$3, join$6(concat$9([",", line$3]), path.map(function (childPath) {
37204 var node = childPath.getValue();
37205 var printed = print(childPath); // Key/Value pair in open paren already indented
37207 if (isKeyValuePairNode$1(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") {
37208 printed.contents.contents.parts[1] = group$6(printed.contents.contents.parts[1]);
37209 return group$6(dedent$2(printed));
37213 }, "groups"))])), ifBreak$2(isSCSS$1(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma$1(options) ? "," : ""), softline$3, node.close ? path.call(print, "close") : ""]), {
37214 shouldBreak: isSCSSMapItem
37220 return concat$9([node.value, insideAtRuleNode$1(path, "supports") && isMediaAndSupportsKeywords$1(node) ? " " : "", path.call(print, "group")]);
37223 case "value-paren":
37228 case "value-number":
37230 return concat$9([printCssNumber(node.value), maybeToLowerCase$1(node.unit)]);
37233 case "value-operator":
37240 if (node.isColor && node.isHex || isWideKeywords$1(node.value)) {
37241 return node.value.toLowerCase();
37247 case "value-colon":
37249 return concat$9([node.value, // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`)
37250 insideValueFunctionNode$1(path, "url") ? "" : line$3]);
37253 case "value-comma":
37255 return concat$9([node.value, " "]);
37258 case "value-string":
37260 return printString$2(node.raws.quote + node.value + node.raws.quote, options);
37263 case "value-atword":
37265 return concat$9(["@", node.value]);
37268 case "value-unicode-range":
37273 case "value-unknown":
37279 /* istanbul ignore next */
37280 throw new Error(`Unknown postcss type ${JSON.stringify(node.type)}`);
37284 function printNodeSequence(path, options, print) {
37285 var node = path.getValue();
37288 path.map(function (pathChild) {
37289 var prevNode = node.nodes[i - 1];
37291 if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") {
37292 var childNode = pathChild.getValue();
37293 parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode)));
37295 parts.push(pathChild.call(print));
37298 if (i !== node.nodes.length - 1) {
37299 if (node.nodes[i + 1].type === "css-comment" && !hasNewline$4(options.originalText, options.locStart(node.nodes[i + 1]), {
37301 }) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml" || node.nodes[i + 1].type === "css-atrule" && node.nodes[i + 1].name === "else" && node.nodes[i].type !== "css-comment") {
37304 parts.push(hardline$7);
37306 if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), options) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml") {
37307 parts.push(hardline$7);
37314 return concat$9(parts);
37317 var STRING_REGEX$1 = /(['"])(?:(?!\1)[^\\]|\\[\s\S])*\1/g;
37318 var NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g;
37319 var STANDARD_UNIT_REGEX = /[a-zA-Z]+/g;
37320 var WORD_PART_REGEX = /[$@]?[a-zA-Z_\u0080-\uFFFF][\w\-\u0080-\uFFFF]*/g;
37321 var ADJUST_NUMBERS_REGEX = RegExp(STRING_REGEX$1.source + `|` + `(${WORD_PART_REGEX.source})?` + `(${NUMBER_REGEX.source})` + `(${STANDARD_UNIT_REGEX.source})?`, "g");
37323 function adjustStrings(value, options) {
37324 return value.replace(STRING_REGEX$1, function (match) {
37325 return printString$2(match, options);
37329 function quoteAttributeValue(value, options) {
37330 var quote = options.singleQuote ? "'" : '"';
37331 return value.includes('"') || value.includes("'") ? value : quote + value + quote;
37334 function adjustNumbers(value) {
37335 return value.replace(ADJUST_NUMBERS_REGEX, function (match, quote, wordPart, number, unit) {
37336 return !wordPart && number ? (wordPart || "") + printCssNumber(number) + maybeToLowerCase$1(unit || "") : match;
37340 function printCssNumber(rawNumber) {
37341 return printNumber$2(rawNumber) // Remove trailing `.0`.
37342 .replace(/\.0(?=$|e)/, "");
37345 var printerPostcss = {
37346 print: genericPrint$2,
37348 insertPragma: insertPragma$3,
37349 hasPrettierIgnore: hasIgnoreComment$3,
37350 massageAstNode: clean_1$1
37354 singleQuote: commonOptions.singleQuote
37357 var name$9 = "CSS";
37358 var type$7 = "markup";
37359 var tmScope$7 = "source.css";
37360 var aceMode$7 = "css";
37361 var codemirrorMode$7 = "css";
37362 var codemirrorMimeType$7 = "text/css";
37363 var color$2 = "#563d7c";
37364 var extensions$7 = [
37367 var languageId$7 = 50;
37371 tmScope: tmScope$7,
37372 aceMode: aceMode$7,
37373 codemirrorMode: codemirrorMode$7,
37374 codemirrorMimeType: codemirrorMimeType$7,
37376 extensions: extensions$7,
37377 languageId: languageId$7
37380 var CSS$1 = /*#__PURE__*/Object.freeze({
37384 tmScope: tmScope$7,
37385 aceMode: aceMode$7,
37386 codemirrorMode: codemirrorMode$7,
37387 codemirrorMimeType: codemirrorMimeType$7,
37389 extensions: extensions$7,
37390 languageId: languageId$7,
37394 var name$a = "PostCSS";
37395 var type$8 = "markup";
37396 var tmScope$8 = "source.postcss";
37397 var group$7 = "CSS";
37398 var extensions$8 = [
37401 var aceMode$8 = "text";
37402 var languageId$8 = 262764437;
37406 tmScope: tmScope$8,
37408 extensions: extensions$8,
37409 aceMode: aceMode$8,
37410 languageId: languageId$8
37413 var PostCSS$1 = /*#__PURE__*/Object.freeze({
37417 tmScope: tmScope$8,
37419 extensions: extensions$8,
37420 aceMode: aceMode$8,
37421 languageId: languageId$8,
37425 var name$b = "Less";
37426 var type$9 = "markup";
37427 var group$8 = "CSS";
37428 var extensions$9 = [
37431 var tmScope$9 = "source.css.less";
37432 var aceMode$9 = "less";
37433 var codemirrorMode$8 = "css";
37434 var codemirrorMimeType$8 = "text/css";
37435 var languageId$9 = 198;
37440 extensions: extensions$9,
37441 tmScope: tmScope$9,
37442 aceMode: aceMode$9,
37443 codemirrorMode: codemirrorMode$8,
37444 codemirrorMimeType: codemirrorMimeType$8,
37445 languageId: languageId$9
37448 var Less$1 = /*#__PURE__*/Object.freeze({
37453 extensions: extensions$9,
37454 tmScope: tmScope$9,
37455 aceMode: aceMode$9,
37456 codemirrorMode: codemirrorMode$8,
37457 codemirrorMimeType: codemirrorMimeType$8,
37458 languageId: languageId$9,
37462 var name$c = "SCSS";
37463 var type$a = "markup";
37464 var tmScope$a = "source.css.scss";
37465 var group$9 = "CSS";
37466 var aceMode$a = "scss";
37467 var codemirrorMode$9 = "css";
37468 var codemirrorMimeType$9 = "text/x-scss";
37469 var extensions$a = [
37472 var languageId$a = 329;
37476 tmScope: tmScope$a,
37478 aceMode: aceMode$a,
37479 codemirrorMode: codemirrorMode$9,
37480 codemirrorMimeType: codemirrorMimeType$9,
37481 extensions: extensions$a,
37482 languageId: languageId$a
37485 var SCSS$1 = /*#__PURE__*/Object.freeze({
37489 tmScope: tmScope$a,
37491 aceMode: aceMode$a,
37492 codemirrorMode: codemirrorMode$9,
37493 codemirrorMimeType: codemirrorMimeType$9,
37494 extensions: extensions$a,
37495 languageId: languageId$a,
37499 var require$$0$3 = getCjsExportFromNamespace(CSS$1);
37501 var require$$1$1 = getCjsExportFromNamespace(PostCSS$1);
37503 var require$$2$1 = getCjsExportFromNamespace(Less$1);
37505 var require$$3$1 = getCjsExportFromNamespace(SCSS$1);
37507 var languages$1 = [createLanguage(require$$0$3, function (data) {
37508 return Object.assign(data, {
37511 vscodeLanguageIds: ["css"]
37513 }), createLanguage(require$$1$1, function (data) {
37514 return Object.assign(data, {
37517 vscodeLanguageIds: ["postcss"],
37518 extensions: data.extensions.concat(".postcss")
37520 }), createLanguage(require$$2$1, function (data) {
37521 return Object.assign(data, {
37524 vscodeLanguageIds: ["less"]
37526 }), createLanguage(require$$3$1, function (data) {
37527 return Object.assign(data, {
37530 vscodeLanguageIds: ["scss"]
37534 postcss: printerPostcss
37536 var languageCss = {
37537 languages: languages$1,
37538 options: options$3,
37539 printers: printers$1
37542 var _require$$0$builders$4 = doc.builders,
37543 concat$a = _require$$0$builders$4.concat,
37544 join$7 = _require$$0$builders$4.join,
37545 softline$4 = _require$$0$builders$4.softline,
37546 hardline$8 = _require$$0$builders$4.hardline,
37547 line$4 = _require$$0$builders$4.line,
37548 group$a = _require$$0$builders$4.group,
37549 indent$6 = _require$$0$builders$4.indent,
37550 ifBreak$3 = _require$$0$builders$4.ifBreak; // http://w3c.github.io/html/single-page.html#void-elements
37552 var voidTags = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]; // Formatter based on @glimmerjs/syntax's built-in test formatter:
37553 // https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts
37555 function printChildren(path, options, print) {
37556 return concat$a(path.map(function (childPath, childIndex) {
37557 var childNode = path.getValue();
37558 var isFirstNode = childIndex === 0;
37559 var isLastNode = childIndex == path.getParentNode(0).children.length - 1;
37560 var isLastNodeInMultiNodeList = isLastNode && !isFirstNode;
37561 var isWhitespace = isWhitespaceNode(childNode);
37563 if (isWhitespace && isLastNodeInMultiNodeList) {
37564 return print(childPath, options, print);
37565 } else if (isFirstNode) {
37566 return concat$a([softline$4, print(childPath, options, print)]);
37569 return print(childPath, options, print);
37573 function print(path, options, print) {
37574 var n = path.getValue();
37575 /* istanbul ignore if*/
37586 return group$a(concat$a(path.map(print, "body").filter(function (text) {
37587 return text !== "";
37591 case "ElementNode":
37593 var tagFirstChar = n.tag[0];
37594 var isLocal = n.tag.indexOf(".") !== -1;
37595 var isGlimmerComponent = tagFirstChar.toUpperCase() === tagFirstChar || isLocal;
37596 var hasChildren = n.children.length > 0;
37597 var hasNonWhitespaceChildren = n.children.some(function (n) {
37598 return !isWhitespaceNode(n);
37600 var isVoid = isGlimmerComponent && (!hasChildren || !hasNonWhitespaceChildren) || voidTags.indexOf(n.tag) !== -1;
37601 var closeTagForNoBreak = isVoid ? concat$a([" />", softline$4]) : ">";
37602 var closeTagForBreak = isVoid ? "/>" : ">";
37604 var _getParams = function _getParams(path, print) {
37605 return indent$6(concat$a([n.attributes.length ? line$4 : "", join$7(line$4, path.map(print, "attributes")), n.modifiers.length ? line$4 : "", join$7(line$4, path.map(print, "modifiers")), n.comments.length ? line$4 : "", join$7(line$4, path.map(print, "comments"))]));
37608 var nextNode = getNextNode(path);
37609 return concat$a([group$a(concat$a(["<", n.tag, _getParams(path, print), n.blockParams.length ? ` as |${n.blockParams.join(" ")}|` : "", ifBreak$3(softline$4, ""), ifBreak$3(closeTagForBreak, closeTagForNoBreak)])), !isVoid ? group$a(concat$a([hasNonWhitespaceChildren ? indent$6(printChildren(path, options, print)) : "", ifBreak$3(hasChildren ? hardline$8 : "", ""), concat$a(["</", n.tag, ">"])])) : "", nextNode && nextNode.type === "ElementNode" ? hardline$8 : ""]);
37612 case "BlockStatement":
37614 var pp = path.getParentNode(1);
37615 var isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if";
37616 var hasElseIf = n.inverse && n.inverse.body.length === 1 && n.inverse.body[0].type === "BlockStatement" && n.inverse.body[0].path.parts[0] === "if";
37617 var indentElse = hasElseIf ? function (a) {
37622 return concat$a([isElseIf ? concat$a(["{{else ", printPathParams(path, print), "}}"]) : printOpenBlock(path, print), indent$6(concat$a([hardline$8, path.call(print, "program")])), n.inverse && !hasElseIf ? concat$a([hardline$8, "{{else}}"]) : "", n.inverse ? indentElse(concat$a([hardline$8, path.call(print, "inverse")])) : "", isElseIf ? "" : concat$a([hardline$8, printCloseBlock(path, print)])]);
37623 } else if (isElseIf) {
37624 return concat$a([concat$a(["{{else ", printPathParams(path, print), "}}"]), indent$6(concat$a([hardline$8, path.call(print, "program")]))]);
37627 var _hasNonWhitespaceChildren = n.program.body.some(function (n) {
37628 return !isWhitespaceNode(n);
37631 return concat$a([printOpenBlock(path, print), group$a(concat$a([indent$6(concat$a([softline$4, path.call(print, "program")])), _hasNonWhitespaceChildren ? hardline$8 : softline$4, printCloseBlock(path, print)]))]);
37634 case "ElementModifierStatement":
37635 case "MustacheStatement":
37637 var _pp = path.getParentNode(1);
37639 var isConcat = _pp && _pp.type === "ConcatStatement";
37640 return group$a(concat$a([n.escaped === false ? "{{{" : "{{", printPathParams(path, print, {
37642 }), isConcat ? "" : softline$4, n.escaped === false ? "}}}" : "}}"]));
37645 case "SubExpression":
37647 var params = getParams(path, print);
37648 var printedParams = params.length > 0 ? indent$6(concat$a([line$4, group$a(join$7(line$4, params))])) : "";
37649 return group$a(concat$a(["(", printPath(path, print), printedParams, softline$4, ")"]));
37654 var isText = n.value.type === "TextNode";
37656 if (isText && n.value.loc.start.column === n.value.loc.end.column) {
37657 return concat$a([n.name]);
37660 var value = path.call(print, "value");
37661 var quotedValue = isText ? printStringLiteral(value.parts.join(), options) : value;
37662 return concat$a([n.name, "=", quotedValue]);
37665 case "ConcatStatement":
37667 return concat$a(['"', group$a(indent$6(join$7(softline$4, path.map(function (partPath) {
37668 return print(partPath);
37669 }, "parts").filter(function (a) {
37676 return concat$a([join$7(line$4, path.map(print, "pairs"))]);
37681 return concat$a([n.key, "=", path.call(print, "value")]);
37686 var maxLineBreaksToPreserve = 2;
37687 var isFirstElement = !getPreviousNode(path);
37688 var isLastElement = !getNextNode(path);
37689 var isWhitespaceOnly = !/\S/.test(n.chars);
37690 var lineBreaksCount = countNewLines(n.chars);
37691 var hasBlockParent = path.getParentNode(0).type === "Block";
37692 var hasElementParent = path.getParentNode(0).type === "ElementNode";
37693 var hasTemplateParent = path.getParentNode(0).type === "Template";
37694 var leadingLineBreaksCount = countLeadingNewLines(n.chars);
37695 var trailingLineBreaksCount = countTrailingNewLines(n.chars);
37697 if ((isFirstElement || isLastElement) && isWhitespaceOnly && (hasBlockParent || hasElementParent || hasTemplateParent)) {
37701 if (isWhitespaceOnly && lineBreaksCount) {
37702 leadingLineBreaksCount = Math.min(lineBreaksCount, maxLineBreaksToPreserve);
37703 trailingLineBreaksCount = 0;
37705 if (isNextNodeOfType(path, "ElementNode") || isNextNodeOfType(path, "BlockStatement")) {
37706 trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1);
37709 if (isPreviousNodeOfSomeType(path, ["ElementNode"]) || isPreviousNodeOfSomeType(path, ["BlockStatement"])) {
37710 leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1);
37714 var leadingSpace = "";
37715 var trailingSpace = ""; // preserve a space inside of an attribute node where whitespace present,
37716 // when next to mustache statement.
37718 var inAttrNode = path.stack.indexOf("attributes") >= 0;
37721 var parentNode = path.getParentNode(0);
37723 var _isConcat = parentNode.type === "ConcatStatement";
37726 var parts = parentNode.parts;
37727 var partIndex = parts.indexOf(n);
37729 if (partIndex > 0) {
37730 var partType = parts[partIndex - 1].type;
37731 var isMustache = partType === "MustacheStatement";
37734 leadingSpace = " ";
37738 if (partIndex < parts.length - 1) {
37739 var _partType = parts[partIndex + 1].type;
37741 var _isMustache = _partType === "MustacheStatement";
37744 trailingSpace = " ";
37749 if (trailingLineBreaksCount === 0 && isNextNodeOfType(path, "MustacheStatement")) {
37750 trailingSpace = " ";
37753 if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType(path, ["MustacheStatement"])) {
37754 leadingSpace = " ";
37757 if (isFirstElement) {
37758 leadingLineBreaksCount = 0;
37762 if (isLastElement) {
37763 trailingLineBreaksCount = 0;
37764 trailingSpace = "";
37768 return concat$a([].concat(_toConsumableArray$1(generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve)), [n.chars.replace(/^[\s ]+/g, leadingSpace).replace(/[\s ]+$/, trailingSpace)], _toConsumableArray$1(generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve))).filter(Boolean));
37771 case "MustacheCommentStatement":
37773 var dashes = n.value.indexOf("}}") > -1 ? "--" : "";
37774 return concat$a(["{{!", dashes, n.value, dashes, "}}"]);
37777 case "PathExpression":
37782 case "BooleanLiteral":
37784 return String(n.value);
37787 case "CommentStatement":
37789 return concat$a(["<!--", n.value, "-->"]);
37792 case "StringLiteral":
37794 return printStringLiteral(n.value, options);
37797 case "NumberLiteral":
37799 return String(n.value);
37802 case "UndefinedLiteral":
37804 return "undefined";
37807 case "NullLiteral":
37812 /* istanbul ignore next */
37815 throw new Error("unknown glimmer type: " + JSON.stringify(n.type));
37819 * Prints a string literal with the correct surrounding quotes based on
37820 * `options.singleQuote` and the number of escaped quotes contained in
37821 * the string literal. This function is the glimmer equivalent of `printString`
37822 * in `common/util`, but has differences because of the way escaped characters
37823 * are treated in hbs string literals.
37824 * @param {string} stringLiteral - the string literal value
37825 * @param {object} options - the prettier options object
37829 function printStringLiteral(stringLiteral, options) {
37838 var preferred = options.singleQuote ? single : double;
37839 var alternate = preferred === single ? double : single;
37840 var shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for
37841 // enclosing the string, we might want to enclose with the alternate quote
37842 // instead, to minimize the number of escaped quotes.
37844 if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) {
37845 var numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length;
37846 var numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length;
37847 shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes;
37850 var enclosingQuote = shouldUseAlternateQuote ? alternate : preferred;
37851 var escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, `\\${enclosingQuote.quote}`);
37852 return `${enclosingQuote.quote}${escapedStringLiteral}${enclosingQuote.quote}`;
37855 function printPath(path, print) {
37856 return path.call(print, "path");
37859 function getParams(path, print) {
37860 var node = path.getValue();
37863 if (node.params.length > 0) {
37864 parts = parts.concat(path.map(print, "params"));
37867 if (node.hash && node.hash.pairs.length > 0) {
37868 parts.push(path.call(print, "hash"));
37874 function printPathParams(path, print, options) {
37876 options = Object.assign({
37879 parts.push(printPath(path, print));
37880 parts = parts.concat(getParams(path, print));
37882 if (!options.group) {
37883 return indent$6(join$7(line$4, parts));
37886 return indent$6(group$a(join$7(line$4, parts)));
37889 function printBlockParams(path) {
37890 var block = path.getValue();
37892 if (!block.program || !block.program.blockParams.length) {
37896 return concat$a([" as |", block.program.blockParams.join(" "), "|"]);
37899 function printOpenBlock(path, print) {
37900 return group$a(concat$a(["{{#", printPathParams(path, print), printBlockParams(path), softline$4, "}}"]));
37903 function printCloseBlock(path, print) {
37904 return concat$a(["{{/", path.call(print, "path"), "}}"]);
37907 function isWhitespaceNode(node) {
37908 return node.type === "TextNode" && !/\S/.test(node.chars);
37911 function getPreviousNode(path) {
37912 var node = path.getValue();
37913 var parentNode = path.getParentNode(0);
37914 var children = parentNode.children || parentNode.body;
37917 var nodeIndex = children.indexOf(node);
37919 if (nodeIndex > 0) {
37920 var previousNode = children[nodeIndex - 1];
37921 return previousNode;
37926 function getNextNode(path) {
37927 var node = path.getValue();
37928 var parentNode = path.getParentNode(0);
37929 var children = parentNode.children || parentNode.body;
37932 var nodeIndex = children.indexOf(node);
37934 if (nodeIndex < children.length) {
37935 var nextNode = children[nodeIndex + 1];
37941 function isPreviousNodeOfSomeType(path, types) {
37942 var previousNode = getPreviousNode(path);
37944 if (previousNode) {
37945 return types.some(function (type) {
37946 return previousNode.type === type;
37953 function isNextNodeOfType(path, type) {
37954 var nextNode = getNextNode(path);
37955 return nextNode && nextNode.type === type;
37958 function clean$3(ast, newObj) {
37960 delete newObj.selfClosing; // (Glimmer/HTML) ignore TextNode whitespace
37962 if (ast.type === "TextNode") {
37963 if (ast.chars.replace(/\s+/, "") === "") {
37967 newObj.chars = ast.chars.replace(/^\s+/, "").replace(/\s+$/, "");
37971 function countNewLines(string) {
37972 /* istanbul ignore next */
37973 string = typeof string === "string" ? string : "";
37974 return string.split("\n").length - 1;
37977 function countLeadingNewLines(string) {
37978 /* istanbul ignore next */
37979 string = typeof string === "string" ? string : "";
37980 var newLines = (string.match(/^([^\S\r\n]*[\r\n])+/g) || [])[0] || "";
37981 return countNewLines(newLines);
37984 function countTrailingNewLines(string) {
37985 /* istanbul ignore next */
37986 string = typeof string === "string" ? string : "";
37987 var newLines = (string.match(/([\r\n][^\S\r\n]*)+$/g) || [])[0] || "";
37988 return countNewLines(newLines);
37991 function generateHardlines() {
37992 var number = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
37993 var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
37994 return new Array(Math.min(number, max)).fill(hardline$8);
37997 var printerGlimmer = {
37999 massageAstNode: clean$3
38002 var name$d = "Handlebars";
38003 var type$b = "markup";
38004 var group$b = "HTML";
38009 var extensions$b = [
38013 var tmScope$b = "text.html.handlebars";
38014 var aceMode$b = "handlebars";
38015 var languageId$b = 155;
38020 aliases: aliases$3,
38021 extensions: extensions$b,
38022 tmScope: tmScope$b,
38023 aceMode: aceMode$b,
38024 languageId: languageId$b
38027 var Handlebars$1 = /*#__PURE__*/Object.freeze({
38032 aliases: aliases$3,
38033 extensions: extensions$b,
38034 tmScope: tmScope$b,
38035 aceMode: aceMode$b,
38036 languageId: languageId$b,
38037 'default': Handlebars
38040 var require$$0$4 = getCjsExportFromNamespace(Handlebars$1);
38042 var languages$2 = [createLanguage(require$$0$4, function (data) {
38043 return Object.assign(data, {
38046 parsers: ["glimmer"],
38047 vscodeLanguageIds: ["handlebars"]
38051 glimmer: printerGlimmer
38053 var languageHandlebars = {
38054 languages: languages$2,
38055 printers: printers$2
38058 function hasPragma$2(text) {
38059 return /^\s*#[^\n\S]*@(format|prettier)\s*(\n|$)/.test(text);
38062 function insertPragma$4(text) {
38063 return "# @format\n\n" + text;
38067 hasPragma: hasPragma$2,
38068 insertPragma: insertPragma$4
38071 var _require$$0$builders$5 = doc.builders,
38072 concat$b = _require$$0$builders$5.concat,
38073 join$8 = _require$$0$builders$5.join,
38074 hardline$9 = _require$$0$builders$5.hardline,
38075 line$5 = _require$$0$builders$5.line,
38076 softline$5 = _require$$0$builders$5.softline,
38077 group$c = _require$$0$builders$5.group,
38078 indent$7 = _require$$0$builders$5.indent,
38079 ifBreak$4 = _require$$0$builders$5.ifBreak;
38080 var hasIgnoreComment$4 = util.hasIgnoreComment;
38081 var isNextLineEmpty$4 = utilShared.isNextLineEmpty;
38082 var insertPragma$5 = pragma$2.insertPragma;
38084 function genericPrint$3(path, options, print) {
38085 var n = path.getValue();
38091 if (typeof n === "string") {
38099 path.map(function (pathChild, index) {
38100 parts.push(concat$b([pathChild.call(print)]));
38102 if (index !== n.definitions.length - 1) {
38103 parts.push(hardline$9);
38105 if (isNextLineEmpty$4(options.originalText, pathChild.getValue(), options)) {
38106 parts.push(hardline$9);
38110 return concat$b([concat$b(parts), hardline$9]);
38113 case "OperationDefinition":
38115 var hasOperation = options.originalText[options.locStart(n)] !== "{";
38116 var hasName = !!n.name;
38117 return concat$b([hasOperation ? n.operation : "", hasOperation && hasName ? concat$b([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.map(print, "variableDefinitions"))])), softline$5, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]);
38120 case "FragmentDefinition":
38122 return concat$b(["fragment ", path.call(print, "name"), n.variableDefinitions && n.variableDefinitions.length ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.map(print, "variableDefinitions"))])), softline$5, ")"])) : "", " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
38125 case "SelectionSet":
38127 return concat$b(["{", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(function (selectionsPath) {
38128 return printSequence(selectionsPath, options, print);
38129 }, "selections"))])), hardline$9, "}"]);
38134 return group$c(concat$b([n.alias ? concat$b([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.call(function (argsPath) {
38135 return printSequence(argsPath, options, print);
38136 }, "arguments"))])), softline$5, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")]));
38144 case "StringValue":
38147 return concat$b(['"""', hardline$9, join$8(hardline$9, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$9, '"""']);
38150 return concat$b(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']);
38160 case "BooleanValue":
38162 return n.value ? "true" : "false";
38172 return concat$b(["$", path.call(print, "name")]);
38177 return group$c(concat$b(["[", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.map(print, "values"))])), softline$5, "]"]));
38180 case "ObjectValue":
38182 return group$c(concat$b(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.map(print, "fields"))])), softline$5, ifBreak$4("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"]));
38185 case "ObjectField":
38188 return concat$b([path.call(print, "name"), ": ", path.call(print, "value")]);
38193 return concat$b(["@", path.call(print, "name"), n.arguments.length > 0 ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.call(function (argsPath) {
38194 return printSequence(argsPath, options, print);
38195 }, "arguments"))])), softline$5, ")"])) : ""]);
38200 return path.call(print, "name");
38203 case "VariableDefinition":
38205 return concat$b([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$b([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
38208 case "TypeExtensionDefinition":
38210 return concat$b(["extend ", path.call(print, "definition")]);
38213 case "ObjectTypeExtension":
38214 case "ObjectTypeDefinition":
38216 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$b([" implements ", join$8(determineInterfaceSeparator(options.originalText.substr(options.locStart(n), options.locEnd(n))), path.map(print, "interfaces"))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$b([" {", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(function (fieldsPath) {
38217 return printSequence(fieldsPath, options, print);
38218 }, "fields"))])), hardline$9, "}"]) : ""]);
38221 case "FieldDefinition":
38223 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", path.call(print, "name"), n.arguments.length > 0 ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.call(function (argsPath) {
38224 return printSequence(argsPath, options, print);
38225 }, "arguments"))])), softline$5, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]);
38228 case "DirectiveDefinition":
38230 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$c(concat$b(["(", indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", ", "), softline$5]), path.call(function (argsPath) {
38231 return printSequence(argsPath, options, print);
38232 }, "arguments"))])), softline$5, ")"])) : "", concat$b([" on ", join$8(" | ", path.map(print, "locations"))])]);
38235 case "EnumTypeExtension":
38236 case "EnumTypeDefinition":
38238 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$b([" {", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(function (valuesPath) {
38239 return printSequence(valuesPath, options, print);
38240 }, "values"))])), hardline$9, "}"]) : ""]);
38243 case "EnumValueDefinition":
38245 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", path.call(print, "name"), printDirectives(path, print, n)]);
38248 case "InputValueDefinition":
38250 return concat$b([path.call(print, "description"), n.description ? n.description.block ? hardline$9 : line$5 : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$b([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
38253 case "InputObjectTypeExtension":
38254 case "InputObjectTypeDefinition":
38256 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$b([" {", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(function (fieldsPath) {
38257 return printSequence(fieldsPath, options, print);
38258 }, "fields"))])), hardline$9, "}"]) : ""]);
38261 case "SchemaDefinition":
38263 return concat$b(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(function (opsPath) {
38264 return printSequence(opsPath, options, print);
38265 }, "operationTypes"))])) : "", hardline$9, "}"]);
38268 case "OperationTypeDefinition":
38270 return concat$b([path.call(print, "operation"), ": ", path.call(print, "type")]);
38273 case "InterfaceTypeExtension":
38274 case "InterfaceTypeDefinition":
38276 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$b([" {", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(function (fieldsPath) {
38277 return printSequence(fieldsPath, options, print);
38278 }, "fields"))])), hardline$9, "}"]) : ""]);
38281 case "FragmentSpread":
38283 return concat$b(["...", path.call(print, "name"), printDirectives(path, print, n)]);
38286 case "InlineFragment":
38288 return concat$b(["...", n.typeCondition ? concat$b([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
38291 case "UnionTypeExtension":
38292 case "UnionTypeDefinition":
38294 return group$c(concat$b([path.call(print, "description"), n.description ? hardline$9 : "", group$c(concat$b([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$b([" =", ifBreak$4("", " "), indent$7(concat$b([ifBreak$4(concat$b([line$5, " "])), join$8(concat$b([line$5, "| "]), path.map(print, "types"))]))]) : ""]))]));
38297 case "ScalarTypeExtension":
38298 case "ScalarTypeDefinition":
38300 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]);
38303 case "NonNullType":
38305 return concat$b([path.call(print, "type"), "!"]);
38310 return concat$b(["[", path.call(print, "type"), "]"]);
38314 /* istanbul ignore next */
38315 throw new Error("unknown graphql type: " + JSON.stringify(n.kind));
38319 function printDirectives(path, print, n) {
38320 if (n.directives.length === 0) {
38324 return concat$b([" ", group$c(indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", " "), softline$5]), path.map(print, "directives"))])))]);
38327 function printSequence(sequencePath, options, print) {
38328 var count = sequencePath.getValue().length;
38329 return sequencePath.map(function (path, i) {
38330 var printed = print(path);
38332 if (isNextLineEmpty$4(options.originalText, path.getValue(), options) && i < count - 1) {
38333 return concat$b([printed, hardline$9]);
38340 function canAttachComment$1(node) {
38341 return node.kind && node.kind !== "Comment";
38344 function printComment$2(commentPath) {
38345 var comment = commentPath.getValue();
38347 if (comment.kind === "Comment") {
38348 return "#" + comment.value.trimRight();
38351 throw new Error("Not a comment: " + JSON.stringify(comment));
38354 function determineInterfaceSeparator(originalSource) {
38355 var start = originalSource.indexOf("implements");
38357 if (start === -1) {
38358 throw new Error("Must implement interfaces: " + originalSource);
38361 var end = originalSource.indexOf("{");
38364 end = originalSource.length;
38367 return originalSource.substr(start, end).includes("&") ? " & " : ", ";
38370 function clean$4(node, newNode
38373 delete newNode.loc;
38374 delete newNode.comments;
38377 var printerGraphql = {
38378 print: genericPrint$3,
38379 massageAstNode: clean$4,
38380 hasPrettierIgnore: hasIgnoreComment$4,
38381 insertPragma: insertPragma$5,
38382 printComment: printComment$2,
38383 canAttachComment: canAttachComment$1
38387 bracketSpacing: commonOptions.bracketSpacing
38390 var name$e = "GraphQL";
38391 var type$c = "data";
38392 var extensions$c = [
38397 var tmScope$c = "source.graphql";
38398 var aceMode$c = "text";
38399 var languageId$c = 139;
38403 extensions: extensions$c,
38404 tmScope: tmScope$c,
38405 aceMode: aceMode$c,
38406 languageId: languageId$c
38409 var GraphQL$1 = /*#__PURE__*/Object.freeze({
38413 extensions: extensions$c,
38414 tmScope: tmScope$c,
38415 aceMode: aceMode$c,
38416 languageId: languageId$c,
38420 var require$$0$5 = getCjsExportFromNamespace(GraphQL$1);
38422 var languages$3 = [createLanguage(require$$0$5, function (data) {
38423 return Object.assign(data, {
38425 parsers: ["graphql"],
38426 vscodeLanguageIds: ["graphql"]
38430 graphql: printerGraphql
38432 var languageGraphql = {
38433 languages: languages$3,
38434 options: options$4,
38435 printers: printers$3
38439 "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]",
38440 "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]",
38441 "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]"
38444 var cjkPattern = json.cjkPattern,
38445 kPattern = json.kPattern,
38446 punctuationPattern = json.punctuationPattern;
38447 var getLast$3 = util.getLast;
38448 var INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"];
38449 var INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]);
38450 var kRegex = new RegExp(kPattern);
38451 var punctuationRegex = new RegExp(punctuationPattern);
38453 * split text into whitespaces and words
38454 * @param {string} text
38455 * @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>}
38458 function splitText(text, options) {
38459 var KIND_NON_CJK = "non-cjk";
38460 var KIND_CJ_LETTER = "cj-letter";
38461 var KIND_K_LETTER = "k-letter";
38462 var KIND_CJK_PUNCTUATION = "cjk-punctuation";
38464 (options.proseWrap === "preserve" ? text : text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")).split(/([ \t\n]+)/).forEach(function (token, index, tokens) {
38466 if (index % 2 === 1) {
38468 type: "whitespace",
38469 value: /\n/.test(token) ? "\n" : " "
38472 } // word separated by whitespace
38475 if ((index === 0 || index === tokens.length - 1) && token === "") {
38479 token.split(new RegExp(`(${cjkPattern})`)).forEach(function (innerToken, innerIndex, innerTokens) {
38480 if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") {
38485 if (innerIndex % 2 === 0) {
38486 if (innerToken !== "") {
38490 kind: KIND_NON_CJK,
38491 hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
38492 hasTrailingPunctuation: punctuationRegex.test(getLast$3(innerToken))
38500 appendNode(punctuationRegex.test(innerToken) ? {
38503 kind: KIND_CJK_PUNCTUATION,
38504 hasLeadingPunctuation: true,
38505 hasTrailingPunctuation: true
38509 kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER,
38510 hasLeadingPunctuation: false,
38511 hasTrailingPunctuation: false
38517 function appendNode(node) {
38518 var lastNode = getLast$3(nodes);
38520 if (lastNode && lastNode.type === "word") {
38521 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) {
38523 type: "whitespace",
38526 } else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace
38527 ![lastNode.value, node.value].some(function (value) {
38528 return /\u3000/.test(value);
38531 type: "whitespace",
38539 function isBetween(kind1, kind2) {
38540 return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1;
38545 function getOrderedListItemInfo(orderListItem, originalText) {
38546 var _originalText$slice$m = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/),
38547 _originalText$slice$m2 = _slicedToArray(_originalText$slice$m, 4),
38548 numberText = _originalText$slice$m2[1],
38549 marker = _originalText$slice$m2[2],
38550 leadingSpaces = _originalText$slice$m2[3];
38557 } // workaround for https://github.com/remarkjs/remark/issues/351
38558 // leading and trailing newlines are stripped by remark
38561 function getFencedCodeBlockValue(node, originalText) {
38562 var text = originalText.slice(node.position.start.offset, node.position.end.offset);
38563 var leadingSpaceCount = text.match(/^\s*/)[0].length;
38564 var replaceRegex = new RegExp(`^\\s{0,${leadingSpaceCount}}`);
38565 var lineContents = text.split("\n");
38566 var markerStyle = text[leadingSpaceCount]; // ` or ~
38568 var marker = text.slice(leadingSpaceCount).match(new RegExp(`^[${markerStyle}]+`))[0]; // https://spec.commonmark.org/0.28/#example-104: Closing fences may be indented by 0-3 spaces
38569 // https://spec.commonmark.org/0.28/#example-93: The closing code fence must be at least as long as the opening fence
38571 var hasEndMarker = new RegExp(`^\\s{0,3}${marker}`).test(lineContents[lineContents.length - 1].slice(getIndent(lineContents.length - 1)));
38572 return lineContents.slice(1, hasEndMarker ? -1 : undefined).map(function (x, i) {
38573 return x.slice(getIndent(i + 1)).replace(replaceRegex, "");
38576 function getIndent(lineIndex) {
38577 return node.position.indent[lineIndex - 1] - 1;
38581 function mapAst(ast, handler) {
38582 return function preorder(node, index, parentStack) {
38583 parentStack = parentStack || [];
38584 var newNode = handler(node, index, parentStack);
38586 if (Array.isArray(newNode)) {
38590 newNode = Object.assign({}, newNode);
38592 if (newNode.children) {
38593 newNode.children = newNode.children.reduce(function (nodes, child, index) {
38594 var newNodes = preorder(child, index, [newNode].concat(parentStack));
38596 if (!Array.isArray(newNodes)) {
38597 newNodes = [newNodes];
38600 nodes.push.apply(nodes, newNodes);
38606 }(ast, null, null);
38612 punctuationPattern,
38613 getFencedCodeBlockValue,
38614 getOrderedListItemInfo,
38616 INLINE_NODE_WRAPPER_TYPES
38619 var _require$$0$builders$6 = doc.builders,
38620 hardline$a = _require$$0$builders$6.hardline,
38621 literalline$4 = _require$$0$builders$6.literalline,
38622 concat$c = _require$$0$builders$6.concat,
38623 markAsRoot$2 = _require$$0$builders$6.markAsRoot,
38624 mapDoc$5 = doc.utils.mapDoc;
38625 var getFencedCodeBlockValue$1 = utils$4.getFencedCodeBlockValue;
38627 function embed$2(path, print, textToDoc, options) {
38628 var node = path.getValue();
38630 if (node.type === "code" && node.lang !== null) {
38631 // only look for the first string so as to support [markdown-preview-enhanced](https://shd101wyy.github.io/markdown-preview-enhanced/#/code-chunk)
38632 var langMatch = node.lang.match(/^[A-Za-z0-9_-]+/);
38633 var lang = langMatch ? langMatch[0] : "";
38634 var parser = getParserName(lang);
38637 var styleUnit = options.__inJsTemplate ? "~" : "`";
38638 var style = styleUnit.repeat(Math.max(3, util.getMaxContinuousCount(node.value, styleUnit) + 1));
38639 var doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), {
38642 return markAsRoot$2(concat$c([style, node.lang, hardline$a, replaceNewlinesWithLiterallines(doc), style]));
38646 if (node.type === "yaml") {
38647 return markAsRoot$2(concat$c(["---", hardline$a, node.value && node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
38649 })) : "", "---"]));
38653 switch (node.type) {
38654 case "importExport":
38655 return textToDoc(node.value, {
38660 return textToDoc(node.value, {
38661 parser: "__js_expression"
38667 function getParserName(lang) {
38668 var supportInfo = support.getSupportInfo(null, {
38669 plugins: options.plugins
38671 var language = supportInfo.languages.find(function (language) {
38672 return language.name.toLowerCase() === lang || language.aliases && language.aliases.indexOf(lang) !== -1 || language.extensions && language.extensions.find(function (ext) {
38673 return ext.substring(1) === lang;
38678 return language.parsers[0];
38684 function replaceNewlinesWithLiterallines(doc) {
38685 return mapDoc$5(doc, function (currentDoc) {
38686 return typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$c(currentDoc.split(/(\n)/g).map(function (v, i) {
38687 return i % 2 === 0 ? v : literalline$4;
38693 var embed_1$2 = embed$2;
38695 var pragmas = ["format", "prettier"];
38697 function startWithPragma(text) {
38698 var pragma = `@(${pragmas.join("|")})`;
38699 var regex = new RegExp([`<!--\\s*${pragma}\\s*-->`, `<!--.*\r?\n[\\s\\S]*(^|\n)[^\\S\n]*${pragma}[^\\S\n]*($|\n)[\\s\\S]*\n.*-->`].join("|"), "m");
38700 var matched = text.match(regex);
38701 return matched && matched.index === 0;
38706 hasPragma: function hasPragma(text) {
38707 return startWithPragma(frontMatter(text).content.trimLeft());
38709 insertPragma: function insertPragma(text) {
38710 var extracted = frontMatter(text);
38711 var pragma = `<!-- @${pragmas[0]} -->`;
38712 return extracted.frontMatter ? `${extracted.frontMatter.raw}\n\n${pragma}\n\n${extracted.content}` : `${pragma}\n\n${extracted.content}`;
38716 var getOrderedListItemInfo$1 = utils$4.getOrderedListItemInfo,
38717 mapAst$1 = utils$4.mapAst,
38718 splitText$1 = utils$4.splitText; // 0x0 ~ 0x10ffff
38719 // eslint-disable-next-line no-control-regex
38721 var isSingleCharRegex = /^([\u0000-\uffff]|[\ud800-\udbff][\udc00-\udfff])$/;
38723 function preprocess$1(ast, options) {
38724 ast = restoreUnescapedCharacter(ast, options);
38725 ast = mergeContinuousTexts(ast);
38726 ast = transformInlineCode(ast);
38727 ast = transformIndentedCodeblockAndMarkItsParentList(ast, options);
38728 ast = markAlignedList(ast, options);
38729 ast = splitTextIntoSentences(ast, options);
38730 ast = transformImportExport(ast);
38731 ast = mergeContinuousImportExport(ast);
38735 function transformImportExport(ast) {
38736 return mapAst$1(ast, function (node) {
38737 if (node.type !== "import" && node.type !== "export") {
38741 return Object.assign({}, node, {
38742 type: "importExport"
38747 function transformInlineCode(ast) {
38748 return mapAst$1(ast, function (node) {
38749 if (node.type !== "inlineCode") {
38753 return Object.assign({}, node, {
38754 value: node.value.replace(/\s+/g, " ")
38759 function restoreUnescapedCharacter(ast, options) {
38760 return mapAst$1(ast, function (node) {
38761 return node.type !== "text" ? node : Object.assign({}, node, {
38762 value: node.value !== "*" && node.value !== "_" && node.value !== "$" && // handle these cases in printer
38763 isSingleCharRegex.test(node.value) && node.position.end.offset - node.position.start.offset !== node.value.length ? options.originalText.slice(node.position.start.offset, node.position.end.offset) : node.value
38768 function mergeContinuousImportExport(ast) {
38769 return mergeChildren(ast, function (prevNode, node) {
38770 return prevNode.type === "importExport" && node.type === "importExport";
38771 }, function (prevNode, node) {
38773 type: "importExport",
38774 value: prevNode.value + "\n\n" + node.value,
38776 start: prevNode.position.start,
38777 end: node.position.end
38783 function mergeChildren(ast, shouldMerge, mergeNode) {
38784 return mapAst$1(ast, function (node) {
38785 if (!node.children) {
38789 var children = node.children.reduce(function (current, child) {
38790 var lastChild = current[current.length - 1];
38792 if (lastChild && shouldMerge(lastChild, child)) {
38793 current.splice(-1, 1, mergeNode(lastChild, child));
38795 current.push(child);
38800 return Object.assign({}, node, {
38806 function mergeContinuousTexts(ast) {
38807 return mergeChildren(ast, function (prevNode, node) {
38808 return prevNode.type === "text" && node.type === "text";
38809 }, function (prevNode, node) {
38812 value: prevNode.value + node.value,
38814 start: prevNode.position.start,
38815 end: node.position.end
38821 function splitTextIntoSentences(ast, options) {
38822 return mapAst$1(ast, function (node, index, _ref) {
38823 var _ref2 = _slicedToArray(_ref, 1),
38824 parentNode = _ref2[0];
38826 if (node.type !== "text") {
38830 var value = node.value;
38832 if (parentNode.type === "paragraph") {
38834 value = value.trimLeft();
38837 if (index === parentNode.children.length - 1) {
38838 value = value.trimRight();
38844 position: node.position,
38845 children: splitText$1(value, options)
38850 function transformIndentedCodeblockAndMarkItsParentList(ast, options) {
38851 return mapAst$1(ast, function (node, index, parentStack) {
38852 if (node.type === "code") {
38853 // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it
38854 var isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset));
38855 node.isIndented = isIndented;
38858 for (var i = 0; i < parentStack.length; i++) {
38859 var parent = parentStack[i]; // no need to check checked items
38861 if (parent.hasIndentedCodeblock) {
38865 if (parent.type === "list") {
38866 parent.hasIndentedCodeblock = true;
38876 function markAlignedList(ast, options) {
38877 return mapAst$1(ast, function (node, index, parentStack) {
38878 if (node.type === "list" && node.children.length !== 0) {
38879 // if one of its parents is not aligned, it's not possible to be aligned in sub-lists
38880 for (var i = 0; i < parentStack.length; i++) {
38881 var parent = parentStack[i];
38883 if (parent.type === "list" && !parent.isAligned) {
38884 node.isAligned = false;
38889 node.isAligned = isAligned(node);
38895 function getListItemStart(listItem) {
38896 return listItem.children.length === 0 ? -1 : listItem.children[0].position.start.column - 1;
38899 function isAligned(list) {
38900 if (!list.ordered) {
38908 var _list$children = _slicedToArray(list.children, 2),
38909 firstItem = _list$children[0],
38910 secondItem = _list$children[1];
38912 var firstInfo = getOrderedListItemInfo$1(firstItem, options.originalText);
38914 if (firstInfo.leadingSpaces.length > 1) {
38924 var firstStart = getListItemStart(firstItem);
38926 if (firstStart === -1) {
38936 if (list.children.length === 1) {
38946 return firstStart % options.tabWidth === 0;
38949 var secondStart = getListItemStart(secondItem);
38951 if (firstStart !== secondStart) {
38962 if (firstStart % options.tabWidth === 0) {
38982 var secondInfo = getOrderedListItemInfo$1(secondItem, options.originalText);
38983 return secondInfo.leadingSpaces.length > 1;
38987 var preprocess_1$1 = preprocess$1;
38989 var _require$$0$builders$7 = doc.builders,
38990 breakParent$3 = _require$$0$builders$7.breakParent,
38991 concat$d = _require$$0$builders$7.concat,
38992 join$9 = _require$$0$builders$7.join,
38993 line$6 = _require$$0$builders$7.line,
38994 literalline$5 = _require$$0$builders$7.literalline,
38995 markAsRoot$3 = _require$$0$builders$7.markAsRoot,
38996 hardline$b = _require$$0$builders$7.hardline,
38997 softline$6 = _require$$0$builders$7.softline,
38998 ifBreak$5 = _require$$0$builders$7.ifBreak,
38999 fill$4 = _require$$0$builders$7.fill,
39000 align$2 = _require$$0$builders$7.align,
39001 indent$8 = _require$$0$builders$7.indent,
39002 group$d = _require$$0$builders$7.group,
39003 mapDoc$6 = doc.utils.mapDoc,
39004 printDocToString$3 = doc.printer.printDocToString;
39005 var getFencedCodeBlockValue$2 = utils$4.getFencedCodeBlockValue,
39006 getOrderedListItemInfo$2 = utils$4.getOrderedListItemInfo,
39007 splitText$2 = utils$4.splitText,
39008 punctuationPattern$1 = utils$4.punctuationPattern,
39009 INLINE_NODE_TYPES$1 = utils$4.INLINE_NODE_TYPES,
39010 INLINE_NODE_WRAPPER_TYPES$1 = utils$4.INLINE_NODE_WRAPPER_TYPES;
39011 var replaceEndOfLineWith$1 = util.replaceEndOfLineWith;
39012 var TRAILING_HARDLINE_NODES = ["importExport"];
39013 var SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"];
39014 var SIBLING_NODE_TYPES = ["listItem", "definition", "footnoteDefinition", "jsx"];
39016 function genericPrint$4(path, options, print) {
39017 var node = path.getValue();
39019 if (shouldRemainTheSameContent(path)) {
39020 return concat$d(splitText$2(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(function (node) {
39021 return node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options);
39025 switch (node.type) {
39027 if (node.children.length === 0) {
39031 return concat$d([normalizeDoc(printRoot(path, options, print)), TRAILING_HARDLINE_NODES.indexOf(getLastDescendantNode(node).type) === -1 ? hardline$b : ""]);
39034 return printChildren$1(path, options, print, {
39035 postprocessor: fill$4
39039 return printChildren$1(path, options, print);
39042 return node.value.replace(/[*$]/g, "\\$&") // escape all `*` and `$` (math)
39043 .replace(new RegExp([`(^|${punctuationPattern$1})(_+)`, `(_+)(${punctuationPattern$1}|$)`].join("|"), "g"), function (_, text1, underscore1, underscore2, text2) {
39044 return (underscore1 ? `${text1}${underscore1}` : `${underscore2}${text2}`).replace(/_/g, "\\_");
39046 // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
39050 var parentNode = path.getParentNode();
39051 var index = parentNode.children.indexOf(node);
39052 var nextNode = parentNode.children[index + 1];
39053 var proseWrap = // leading char that may cause different syntax
39054 nextNode && /^>|^([-+*]|#{1,6}|[0-9]+[.)])$/.test(nextNode.value) ? "never" : options.proseWrap;
39055 return printLine(path, node.value, {
39062 var _parentNode = path.getParentNode();
39064 var _index = _parentNode.children.indexOf(node);
39066 var prevNode = _parentNode.children[_index - 1];
39067 var _nextNode = _parentNode.children[_index + 1];
39068 var hasPrevOrNextWord = // `1*2*3` is considered emphasis but `1_2_3` is not
39069 prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && util.getLast(prevNode.children).type === "word" && !util.getLast(prevNode.children).hasTrailingPunctuation || _nextNode && _nextNode.type === "sentence" && _nextNode.children.length > 0 && _nextNode.children[0].type === "word" && !_nextNode.children[0].hasLeadingPunctuation;
39070 var style = hasPrevOrNextWord || getAncestorNode$2(path, "emphasis") ? "*" : "_";
39071 return concat$d([style, printChildren$1(path, options, print), style]);
39075 return concat$d(["**", printChildren$1(path, options, print), "**"]);
39078 return concat$d(["~~", printChildren$1(path, options, print), "~~"]);
39082 var backtickCount = util.getMinNotPresentContinuousCount(node.value, "`");
39084 var _style = "`".repeat(backtickCount || 1);
39086 var gap = backtickCount ? " " : "";
39087 return concat$d([_style, gap, node.value, gap, _style]);
39091 switch (options.originalText[node.position.start.offset]) {
39094 var mailto = "mailto:";
39095 var url = // <hello@example.com> is parsed as { url: "mailto:hello@example.com" }
39096 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;
39097 return concat$d(["<", url, ">"]);
39101 return concat$d(["[", printChildren$1(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
39104 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
39108 return concat$d(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
39111 return concat$d(["> ", align$2("> ", printChildren$1(path, options, print))]);
39114 return concat$d(["#".repeat(node.depth) + " ", printChildren$1(path, options, print)]);
39118 if (node.isIndented) {
39119 // indented code block
39120 var alignment = " ".repeat(4);
39121 return align$2(alignment, concat$d([alignment, concat$d(replaceEndOfLineWith$1(node.value, hardline$b))]));
39122 } // fenced code block
39125 var styleUnit = options.__inJsTemplate ? "~" : "`";
39127 var _style2 = styleUnit.repeat(Math.max(3, util.getMaxContinuousCount(node.value, styleUnit) + 1));
39129 return concat$d([_style2, node.lang || "", hardline$b, concat$d(replaceEndOfLineWith$1(getFencedCodeBlockValue$2(node, options.originalText), hardline$b)), hardline$b, _style2]);
39134 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
39138 var _parentNode2 = path.getParentNode();
39140 var value = _parentNode2.type === "root" && util.getLast(_parentNode2.children) === node ? node.value.trimRight() : node.value;
39141 var isHtmlComment = /^<!--[\s\S]*-->$/.test(value);
39142 return concat$d(replaceEndOfLineWith$1(value, isHtmlComment ? hardline$b : markAsRoot$3(literalline$5)));
39147 var nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode());
39148 var isGitDiffFriendlyOrderedList = node.ordered && node.children.length > 1 && +getOrderedListItemInfo$2(node.children[1], options.originalText).numberText === 1;
39149 return printChildren$1(path, options, print, {
39150 processor: function processor(childPath, index) {
39151 var prefix = getPrefix();
39152 return concat$d([prefix, align$2(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]);
39154 function getPrefix() {
39155 var rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* ";
39156 return node.isAligned ||
39157 /* workaround for https://github.com/remarkjs/remark/issues/315 */
39158 node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix;
39164 case "thematicBreak":
39166 var counter = getAncestorCounter$1(path, "list");
39168 if (counter === -1) {
39172 var _nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1));
39174 return _nthSiblingIndex % 2 === 0 ? "***" : "---";
39177 case "linkReference":
39178 return concat$d(["[", printChildren$1(path, options, print), "]", node.referenceType === "full" ? concat$d(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]);
39180 case "imageReference":
39181 switch (node.referenceType) {
39183 return concat$d(["![", node.alt || "", "][", node.identifier, "]"]);
39186 return concat$d(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]);
39191 var lineOrSpace = options.proseWrap === "always" ? line$6 : " ";
39192 return group$d(concat$d([concat$d(["[", node.identifier, "]:"]), indent$8(concat$d([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$d([lineOrSpace, printTitle(node.title, options, false)])]))]));
39196 return concat$d(["[^", printChildren$1(path, options, print), "]"]);
39198 case "footnoteReference":
39199 return concat$d(["[^", node.identifier, "]"]);
39201 case "footnoteDefinition":
39203 var _nextNode2 = path.getParentNode().children[path.getName() + 1];
39204 var 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);
39205 return concat$d(["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$1(path, options, print) : group$d(concat$d([align$2(" ".repeat(options.tabWidth), printChildren$1(path, options, print, {
39206 processor: function processor(childPath, index) {
39207 return index === 0 ? group$d(concat$d([softline$6, softline$6, childPath.call(print)])) : childPath.call(print);
39209 })), _nextNode2 && _nextNode2.type === "footnoteDefinition" ? softline$6 : ""]))]);
39213 return printTable(path, options, print);
39216 return printChildren$1(path, options, print);
39219 return /\s/.test(options.originalText[node.position.start.offset]) ? concat$d([" ", markAsRoot$3(literalline$5)]) : concat$d(["\\", hardline$b]);
39222 return concat$d(replaceEndOfLineWith$1(node.value, hardline$b));
39225 case "importExport":
39228 // fallback to the original text if multiparser failed
39231 return concat$d(["$$", hardline$b, node.value ? concat$d([concat$d(replaceEndOfLineWith$1(node.value, hardline$b)), hardline$b]) : "", "$$"]);
39235 // remark-math trims content but we don't want to remove whitespaces
39236 // since it's very possible that it's recognized as math accidentally
39237 return options.originalText.slice(options.locStart(node), options.locEnd(node));
39240 case "tableRow": // handled in "table"
39242 case "listItem": // handled in "list"
39245 throw new Error(`Unknown markdown type ${JSON.stringify(node.type)}`);
39249 function printListItem(path, options, print, listPrefix) {
39250 var node = path.getValue();
39251 var prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
39252 return concat$d([prefix, printChildren$1(path, options, print, {
39253 processor: function processor(childPath, index) {
39254 if (index === 0 && childPath.getValue().type !== "list") {
39255 return align$2(" ".repeat(prefix.length), childPath.call(print));
39258 var alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
39260 return concat$d([alignment, align$2(alignment, childPath.call(print))]);
39265 function alignListPrefix(prefix, options) {
39266 var additionalSpaces = getAdditionalSpaces();
39267 return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block
39270 function getAdditionalSpaces() {
39271 var restSpaces = prefix.length % options.tabWidth;
39272 return restSpaces === 0 ? 0 : options.tabWidth - restSpaces;
39276 function getNthListSiblingIndex(node, parentNode) {
39277 return getNthSiblingIndex(node, parentNode, function (siblingNode) {
39278 return siblingNode.ordered === node.ordered;
39282 function getNthSiblingIndex(node, parentNode, condition) {
39283 condition = condition || function () {
39288 var _iteratorNormalCompletion = true;
39289 var _didIteratorError = false;
39290 var _iteratorError = undefined;
39293 for (var _iterator = parentNode.children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
39294 var childNode = _step.value;
39296 if (childNode.type === node.type && condition(childNode)) {
39302 if (childNode === node) {
39307 _didIteratorError = true;
39308 _iteratorError = err;
39311 if (!_iteratorNormalCompletion && _iterator.return != null) {
39312 _iterator.return();
39315 if (_didIteratorError) {
39316 throw _iteratorError;
39322 function getAncestorCounter$1(path, typeOrTypes) {
39323 var types = [].concat(typeOrTypes);
39327 while (ancestorNode = path.getParentNode(++counter)) {
39328 if (types.indexOf(ancestorNode.type) !== -1) {
39336 function getAncestorNode$2(path, typeOrTypes) {
39337 var counter = getAncestorCounter$1(path, typeOrTypes);
39338 return counter === -1 ? null : path.getParentNode(counter);
39341 function printLine(path, value, options) {
39342 if (options.proseWrap === "preserve" && value === "\n") {
39346 var isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES);
39347 return value !== "" ? isBreakable ? line$6 : " " : isBreakable ? softline$6 : "";
39350 function printTable(path, options, print) {
39351 var hardlineWithoutBreakParent = hardline$b.parts[0];
39352 var node = path.getValue();
39353 var contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } }
39355 path.map(function (rowPath) {
39356 var rowContents = [];
39357 rowPath.map(function (cellPath) {
39358 rowContents.push(printDocToString$3(cellPath.call(print), options).formatted);
39360 contents.push(rowContents);
39361 }, "children"); // Get the width of each column
39363 var columnMaxWidths = contents.reduce(function (currentWidths, rowContents) {
39364 return currentWidths.map(function (width, columnIndex) {
39365 return Math.max(width, util.getStringWidth(rowContents[columnIndex]));
39367 }, contents[0].map(function () {
39369 }) // minimum width = 3 (---, :--, :-:, --:)
39371 var alignedTable = join$9(hardlineWithoutBreakParent, [printRow(contents[0]), printSeparator(), join$9(hardlineWithoutBreakParent, contents.slice(1).map(function (rowContents) {
39372 return printRow(rowContents);
39375 if (options.proseWrap !== "never") {
39376 return concat$d([breakParent$3, alignedTable]);
39377 } // Only if the --prose-wrap never is set and it exceeds the print width.
39380 var compactTable = join$9(hardlineWithoutBreakParent, [printRow(contents[0],
39382 true), printSeparator(
39384 true), join$9(hardlineWithoutBreakParent, contents.slice(1).map(function (rowContents) {
39385 return printRow(rowContents,
39389 return concat$d([breakParent$3, group$d(ifBreak$5(compactTable, alignedTable))]);
39391 function printSeparator(isCompact) {
39392 return concat$d(["| ", join$9(" | ", columnMaxWidths.map(function (width, index) {
39393 var spaces = isCompact ? 3 : width;
39395 switch (node.align[index]) {
39397 return ":" + "-".repeat(spaces - 1);
39400 return "-".repeat(spaces - 1) + ":";
39403 return ":" + "-".repeat(spaces - 2) + ":";
39406 return "-".repeat(spaces);
39411 function printRow(rowContents, isCompact) {
39412 return concat$d(["| ", join$9(" | ", isCompact ? rowContents : rowContents.map(function (rowContent, columnIndex) {
39413 switch (node.align[columnIndex]) {
39415 return alignRight(rowContent, columnMaxWidths[columnIndex]);
39418 return alignCenter(rowContent, columnMaxWidths[columnIndex]);
39421 return alignLeft(rowContent, columnMaxWidths[columnIndex]);
39426 function alignLeft(text, width) {
39427 var spaces = width - util.getStringWidth(text);
39428 return concat$d([text, " ".repeat(spaces)]);
39431 function alignRight(text, width) {
39432 var spaces = width - util.getStringWidth(text);
39433 return concat$d([" ".repeat(spaces), text]);
39436 function alignCenter(text, width) {
39437 var spaces = width - util.getStringWidth(text);
39438 var left = Math.floor(spaces / 2);
39439 var right = spaces - left;
39440 return concat$d([" ".repeat(left), text, " ".repeat(right)]);
39444 function printRoot(path, options, print) {
39445 /** @typedef {{ index: number, offset: number }} IgnorePosition */
39447 /** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */
39448 var ignoreRanges = [];
39449 /** @type {IgnorePosition | null} */
39451 var ignoreStart = null;
39452 var children = path.getValue().children;
39453 children.forEach(function (childNode, index) {
39454 switch (isPrettierIgnore(childNode)) {
39456 if (ignoreStart === null) {
39459 offset: childNode.position.end.offset
39466 if (ignoreStart !== null) {
39467 ignoreRanges.push({
39468 start: ignoreStart,
39471 offset: childNode.position.start.offset
39474 ignoreStart = null;
39480 return printChildren$1(path, options, print, {
39481 processor: function processor(childPath, index) {
39482 if (ignoreRanges.length !== 0) {
39483 var ignoreRange = ignoreRanges[0];
39485 if (index === ignoreRange.start.index) {
39486 return concat$d([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]);
39489 if (ignoreRange.start.index < index && index < ignoreRange.end.index) {
39493 if (index === ignoreRange.end.index) {
39494 ignoreRanges.shift();
39499 return childPath.call(print);
39504 function printChildren$1(path, options, print, events) {
39505 events = events || {};
39506 var postprocessor = events.postprocessor || concat$d;
39508 var processor = events.processor || function (childPath) {
39509 return childPath.call(print);
39512 var node = path.getValue();
39515 path.map(function (childPath, index) {
39516 var childNode = childPath.getValue();
39517 var result = processor(childPath, index);
39519 if (result !== false) {
39522 prevNode: lastChildNode,
39527 if (!shouldNotPrePrintHardline(childNode, data)) {
39528 parts.push(hardline$b);
39530 if (lastChildNode && TRAILING_HARDLINE_NODES.indexOf(lastChildNode.type) !== -1) {
39531 if (shouldPrePrintTripleHardline(childNode, data)) {
39532 parts.push(hardline$b);
39535 if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
39536 parts.push(hardline$b);
39539 if (shouldPrePrintTripleHardline(childNode, data)) {
39540 parts.push(hardline$b);
39545 parts.push(result);
39546 lastChildNode = childNode;
39549 return postprocessor(parts);
39552 function getLastDescendantNode(node) {
39553 var current = node;
39555 while (current.children && current.children.length !== 0) {
39556 current = current.children[current.children.length - 1];
39561 /** @return {false | 'next' | 'start' | 'end'} */
39564 function isPrettierIgnore(node) {
39565 if (node.type !== "html") {
39569 var match = node.value.match(/^<!--\s*prettier-ignore(?:-(start|end))?\s*-->$/);
39570 return match === null ? false : match[1] ? match[1] : "next";
39573 function isInlineNode(node) {
39574 return node && INLINE_NODE_TYPES$1.indexOf(node.type) !== -1;
39577 function isEndsWithHardLine(node) {
39578 return node && /\n+$/.test(node.value);
39581 function last(nodes) {
39582 return nodes && nodes[nodes.length - 1];
39585 function shouldNotPrePrintHardline(node, _ref) {
39586 var parentNode = _ref.parentNode,
39587 parts = _ref.parts,
39588 prevNode = _ref.prevNode;
39589 var isFirstNode = parts.length === 0;
39590 var isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES$1.indexOf(parentNode.type) !== -1;
39591 var isAfterHardlineNode = prevNode && (isEndsWithHardLine(prevNode) || isEndsWithHardLine(last(prevNode.children)));
39592 return isFirstNode || isInlineNode(node) || isInlineHTML || isAfterHardlineNode;
39595 function shouldPrePrintDoubleHardline(node, _ref2) {
39596 var parentNode = _ref2.parentNode,
39597 prevNode = _ref2.prevNode;
39598 var prevNodeType = prevNode && prevNode.type;
39599 var nodeType = node.type;
39600 var isSequence = prevNodeType === nodeType;
39601 var isSiblingNode = isSequence && SIBLING_NODE_TYPES.indexOf(nodeType) !== -1;
39602 var isInTightListItem = parentNode.type === "listItem" && !parentNode.loose;
39603 var isPrevNodeLooseListItem = prevNodeType === "listItem" && prevNode.loose;
39604 var isPrevNodePrettierIgnore = isPrettierIgnore(prevNode) === "next";
39605 var isBlockHtmlWithoutBlankLineBetweenPrevHtml = nodeType === "html" && prevNodeType === "html" && prevNode.position.end.line + 1 === node.position.start.line;
39606 var isJsxInlineSibling = prevNodeType === "jsx" && isInlineNode(node) || nodeType === "jsx" && isInlineNode(prevNode);
39607 return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml || isJsxInlineSibling);
39610 function shouldPrePrintTripleHardline(node, data) {
39611 var isPrevNodeList = data.prevNode && data.prevNode.type === "list";
39612 var isIndentedCode = node.type === "code" && node.isIndented;
39613 return isPrevNodeList && isIndentedCode;
39616 function shouldRemainTheSameContent(path) {
39617 var ancestorNode = getAncestorNode$2(path, ["linkReference", "imageReference"]);
39618 return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full");
39621 function normalizeDoc(doc) {
39622 return mapDoc$6(doc, function (currentDoc) {
39623 if (!currentDoc.parts) {
39627 if (currentDoc.type === "concat" && currentDoc.parts.length === 1) {
39628 return currentDoc.parts[0];
39632 currentDoc.parts.forEach(function (part) {
39633 if (part.type === "concat") {
39634 parts.push.apply(parts, part.parts);
39635 } else if (part !== "") {
39639 return Object.assign({}, currentDoc, {
39640 parts: normalizeParts(parts)
39645 function printUrl(url, dangerousCharOrChars) {
39646 var dangerousChars = [" "].concat(dangerousCharOrChars || []);
39647 return new RegExp(dangerousChars.map(function (x) {
39649 }).join("|")).test(url) ? `<${url}>` : url;
39652 function printTitle(title, options, printSpace) {
39653 if (printSpace == null) {
39662 return " " + printTitle(title, options, false);
39665 if (title.includes('"') && title.includes("'") && !title.includes(")")) {
39666 return `(${title})`; // avoid escaped quotes
39667 } // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split
39670 var singleCount = title.split("'").length - 1;
39671 var doubleCount = title.split('"').length - 1;
39672 var quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"';
39673 title = title.replace(new RegExp(`(${quote})`, "g"), "\\$1");
39674 return `${quote}${title}${quote}`;
39677 function normalizeParts(parts) {
39678 return parts.reduce(function (current, part) {
39679 var lastPart = util.getLast(current);
39681 if (typeof lastPart === "string" && typeof part === "string") {
39682 current.splice(-1, 1, lastPart + part);
39684 current.push(part);
39691 function clamp(value, min, max) {
39692 return value < min ? min : value > max ? max : value;
39695 function clean$5(ast, newObj, parent) {
39696 delete newObj.position;
39697 delete newObj.raw; // front-matter
39700 if (ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") {
39701 delete newObj.value;
39704 if (ast.type === "list") {
39705 delete newObj.isAligned;
39706 } // texts can be splitted or merged
39709 if (ast.type === "text") {
39713 if (ast.type === "inlineCode") {
39714 newObj.value = ast.value.replace(/[ \t\n]+/g, " ");
39715 } // for insert pragma
39718 if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || (parent.children[0].type === "yaml" || parent.children[0].type === "toml") && parent.children[1] === ast) && ast.type === "html" && pragma$3.startWithPragma(ast.value)) {
39723 function hasPrettierIgnore$2(path) {
39724 var index = +path.getName();
39730 var prevNode = path.getParentNode().children[index - 1];
39731 return isPrettierIgnore(prevNode) === "next";
39734 var printerMarkdown = {
39735 preprocess: preprocess_1$1,
39736 print: genericPrint$4,
39738 massageAstNode: clean$5,
39739 hasPrettierIgnore: hasPrettierIgnore$2,
39740 insertPragma: pragma$3.insertPragma
39744 proseWrap: commonOptions.proseWrap,
39745 singleQuote: commonOptions.singleQuote
39748 var name$f = "Markdown";
39749 var type$d = "prose";
39753 var aceMode$d = "markdown";
39754 var codemirrorMode$a = "gfm";
39755 var codemirrorMimeType$a = "text/x-gfm";
39757 var extensions$d = [
39769 var filenames$3 = [
39772 var tmScope$d = "source.gfm";
39773 var languageId$d = 222;
39777 aliases: aliases$4,
39778 aceMode: aceMode$d,
39779 codemirrorMode: codemirrorMode$a,
39780 codemirrorMimeType: codemirrorMimeType$a,
39782 extensions: extensions$d,
39783 filenames: filenames$3,
39784 tmScope: tmScope$d,
39785 languageId: languageId$d
39788 var Markdown$1 = /*#__PURE__*/Object.freeze({
39792 aliases: aliases$4,
39793 aceMode: aceMode$d,
39794 codemirrorMode: codemirrorMode$a,
39795 codemirrorMimeType: codemirrorMimeType$a,
39797 extensions: extensions$d,
39798 filenames: filenames$3,
39799 tmScope: tmScope$d,
39800 languageId: languageId$d,
39801 'default': Markdown
39804 var require$$0$6 = getCjsExportFromNamespace(Markdown$1);
39806 var languages$4 = [createLanguage(require$$0$6, function (data) {
39807 return Object.assign(data, {
39809 parsers: ["remark"],
39810 vscodeLanguageIds: ["markdown"],
39811 filenames: data.filenames.concat(["README"]),
39812 extensions: data.extensions.filter(function (extension) {
39813 return extension !== ".mdx";
39816 }), createLanguage(require$$0$6, function (data) {
39817 return Object.assign(data, {
39821 vscodeLanguageIds: ["mdx"],
39823 extensions: [".mdx"]
39827 mdast: printerMarkdown
39829 var languageMarkdown = {
39830 languages: languages$4,
39831 options: options$5,
39832 printers: printers$4
39835 var clean$6 = function clean(ast, newNode) {
39836 delete newNode.sourceSpan;
39837 delete newNode.startSourceSpan;
39838 delete newNode.endSourceSpan;
39839 delete newNode.nameSpan;
39840 delete newNode.valueSpan;
39842 if (ast.type === "text" || ast.type === "comment") {
39844 } // may be formatted by multiparser
39847 if (ast.type === "yaml" || ast.type === "toml") {
39851 if (ast.type === "attribute") {
39852 delete newNode.value;
39855 if (ast.type === "docType") {
39856 delete newNode.value;
39861 "CSS_DISPLAY_TAGS": {
39864 "basefont": "none",
39865 "datalist": "none",
39870 "noframes": "none",
39876 "template": "inline",
39881 "address": "block",
39882 "blockquote": "block",
39886 "figcaption": "block",
39892 "listing": "block",
39895 "plaintext": "block",
39898 "slot": "contents",
39901 "article": "block",
39911 "section": "block",
39920 "caption": "table-caption",
39921 "colgroup": "table-column-group",
39922 "col": "table-column",
39923 "thead": "table-header-group",
39924 "tbody": "table-row-group",
39925 "tfoot": "table-footer-group",
39927 "td": "table-cell",
39928 "th": "table-cell",
39929 "fieldset": "block",
39930 "button": "inline-block",
39931 "video": "inline-block",
39932 "audio": "inline-block"
39934 "CSS_DISPLAY_DEFAULT": "inline",
39935 "CSS_WHITE_SPACE_TAGS": {
39937 "plaintext": "pre",
39941 "table": "initial",
39942 "textarea": "pre-wrap"
39944 "CSS_WHITE_SPACE_DEFAULT": "normal"
40170 "allowpaymentrequest",
40552 basefont: basefont,
40554 blockquote: blockquote,
40561 colgroup: colgroup,
40571 fieldset: fieldset,
40575 frameset: frameset,
40600 optgroup: optgroup,
40606 progress: progress,
40616 textarea: textarea,
40627 var htmlElementAttributes = /*#__PURE__*/Object.freeze({
40635 basefont: basefont,
40637 blockquote: blockquote,
40644 colgroup: colgroup,
40654 fieldset: fieldset,
40658 frameset: frameset,
40683 optgroup: optgroup,
40689 progress: progress,
40699 textarea: textarea,
40711 var htmlElementAttributes$1 = getCjsExportFromNamespace(htmlElementAttributes);
40713 var CSS_DISPLAY_TAGS = json$1.CSS_DISPLAY_TAGS,
40714 CSS_DISPLAY_DEFAULT = json$1.CSS_DISPLAY_DEFAULT,
40715 CSS_WHITE_SPACE_TAGS = json$1.CSS_WHITE_SPACE_TAGS,
40716 CSS_WHITE_SPACE_DEFAULT = json$1.CSS_WHITE_SPACE_DEFAULT;
40717 var HTML_TAGS = arrayToMap(htmlTagNames$1);
40718 var HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes$1, arrayToMap);
40720 function arrayToMap(array) {
40721 var map = Object.create(null);
40722 var _iteratorNormalCompletion = true;
40723 var _didIteratorError = false;
40724 var _iteratorError = undefined;
40727 for (var _iterator = array[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
40728 var value = _step.value;
40732 _didIteratorError = true;
40733 _iteratorError = err;
40736 if (!_iteratorNormalCompletion && _iterator.return != null) {
40737 _iterator.return();
40740 if (_didIteratorError) {
40741 throw _iteratorError;
40749 function mapObject(object, fn) {
40750 var newObject = Object.create(null);
40752 for (var _i = 0, _Object$keys = Object.keys(object); _i < _Object$keys.length; _i++) {
40753 var key = _Object$keys[_i];
40754 newObject[key] = fn(object[key], key);
40760 function shouldPreserveContent(node, options) {
40761 if (node.type === "element" && node.fullName === "template" && node.attrMap.lang && node.attrMap.lang !== "html") {
40763 } // unterminated node in ie conditional comment
40764 // e.g. <!--[if lt IE 9]><html><![endif]-->
40767 if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) {
40769 } // incomplete html in ie conditional comment
40770 // e.g. <!--[if lt IE 9]></div><![endif]-->
40773 if (node.type === "ieConditionalComment" && !node.complete) {
40775 } // top-level elements (excluding <template>, <style> and <script>) in Vue SFC are considered custom block
40776 // custom blocks can be written in other languages so we should preserve them to not break the code
40779 if (options.parser === "vue" && node.type === "element" && node.parent.type === "root" && ["template", "style", "script", // vue parser can be used for vue dom template as well, so we should still format top-level <html>
40780 "html"].indexOf(node.fullName) === -1) {
40782 } // TODO: handle non-text children in <pre>
40785 if (isPreLikeNode(node) && node.children.some(function (child) {
40786 return child.type !== "text" && child.type !== "interpolation";
40794 function hasPrettierIgnore$3(node) {
40795 if (node.type === "attribute" || isTextLikeNode(node)) {
40799 if (!node.parent) {
40803 if (typeof node.index !== "number" || node.index === 0) {
40807 var prevNode = node.parent.children[node.index - 1];
40808 return isPrettierIgnore$1(prevNode);
40811 function isPrettierIgnore$1(node) {
40812 return node.type === "comment" && node.value.trim() === "prettier-ignore";
40815 function getPrettierIgnoreAttributeCommentData(value) {
40816 var match = value.trim().match(/^prettier-ignore-attribute(?:\s+([^]+))?$/);
40826 return match[1].split(/\s+/);
40828 /** there's no opening/closing tag or it's considered not breakable */
40831 function isTextLikeNode(node) {
40832 return node.type === "text" || node.type === "comment";
40835 function isScriptLikeTag(node) {
40836 return node.type === "element" && (node.fullName === "script" || node.fullName === "style" || node.fullName === "svg:style");
40839 function isFrontMatterNode(node) {
40840 return node.type === "yaml" || node.type === "toml";
40843 function canHaveInterpolation(node) {
40844 return node.children && !isScriptLikeTag(node);
40847 function isWhitespaceSensitiveNode(node) {
40848 return isScriptLikeTag(node) || node.type === "interpolation" || isIndentationSensitiveNode(node);
40851 function isIndentationSensitiveNode(node) {
40852 return getNodeCssStyleWhiteSpace(node).startsWith("pre");
40855 function isLeadingSpaceSensitiveNode(node) {
40856 var isLeadingSpaceSensitive = _isLeadingSpaceSensitiveNode();
40858 if (isLeadingSpaceSensitive && !node.prev && node.parent && node.parent.tagDefinition && node.parent.tagDefinition.ignoreFirstLf) {
40859 return node.type === "interpolation";
40862 return isLeadingSpaceSensitive;
40864 function _isLeadingSpaceSensitiveNode() {
40865 if (isFrontMatterNode(node)) {
40869 if ((node.type === "text" || node.type === "interpolation") && node.prev && (node.prev.type === "text" || node.prev.type === "interpolation")) {
40873 if (!node.parent || node.parent.cssDisplay === "none") {
40877 if (isPreLikeNode(node.parent)) {
40881 if (!node.prev && (node.parent.type === "root" || isScriptLikeTag(node.parent) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
40885 if (node.prev && !isNextLeadingSpaceSensitiveCssDisplay(node.prev.cssDisplay)) {
40893 function isTrailingSpaceSensitiveNode(node) {
40894 if (isFrontMatterNode(node)) {
40898 if ((node.type === "text" || node.type === "interpolation") && node.next && (node.next.type === "text" || node.next.type === "interpolation")) {
40902 if (!node.parent || node.parent.cssDisplay === "none") {
40906 if (isPreLikeNode(node.parent)) {
40910 if (!node.next && (node.parent.type === "root" || isScriptLikeTag(node.parent) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
40914 if (node.next && !isPrevTrailingSpaceSensitiveCssDisplay(node.next.cssDisplay)) {
40921 function isDanglingSpaceSensitiveNode(node) {
40922 return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag(node);
40925 function forceNextEmptyLine(node) {
40926 return isFrontMatterNode(node) || node.next && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line;
40928 /** firstChild leadingSpaces and lastChild trailingSpaces */
40931 function forceBreakContent(node) {
40932 return forceBreakChildren(node) || node.type === "element" && node.children.length !== 0 && (["body", "script", "style"].indexOf(node.name) !== -1 || node.children.some(function (child) {
40933 return hasNonTextChild(child);
40934 })) || node.firstChild && node.firstChild === node.lastChild && hasLeadingLineBreak(node.firstChild) && (!node.lastChild.isTrailingSpaceSensitive || hasTrailingLineBreak(node.lastChild));
40936 /** spaces between children */
40939 function forceBreakChildren(node) {
40940 return node.type === "element" && node.children.length !== 0 && (["html", "head", "ul", "ol", "select"].indexOf(node.name) !== -1 || node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell");
40943 function preferHardlineAsLeadingSpaces(node) {
40944 return preferHardlineAsSurroundingSpaces(node) || node.prev && preferHardlineAsTrailingSpaces(node.prev) || hasSurroundingLineBreak(node);
40947 function preferHardlineAsTrailingSpaces(node) {
40948 return preferHardlineAsSurroundingSpaces(node) || node.type === "element" && node.fullName === "br" || hasSurroundingLineBreak(node);
40951 function hasSurroundingLineBreak(node) {
40952 return hasLeadingLineBreak(node) && hasTrailingLineBreak(node);
40955 function hasLeadingLineBreak(node) {
40956 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);
40959 function hasTrailingLineBreak(node) {
40960 return node.hasTrailingSpaces && (node.next ? node.next.sourceSpan.start.line > node.sourceSpan.end.line : node.parent.type === "root" || node.parent.endSourceSpan.start.line > node.sourceSpan.end.line);
40963 function preferHardlineAsSurroundingSpaces(node) {
40964 switch (node.type) {
40965 case "ieConditionalComment":
40971 return ["script", "select"].indexOf(node.name) !== -1;
40977 function getLastDescendant(node) {
40978 return node.lastChild ? getLastDescendant(node.lastChild) : node;
40981 function hasNonTextChild(node) {
40982 return node.children && node.children.some(function (child) {
40983 return child.type !== "text";
40987 function inferScriptParser(node) {
40988 if (node.name === "script" && !node.attrMap.src) {
40989 if (!node.attrMap.lang && !node.attrMap.type || node.attrMap.type === "module" || node.attrMap.type === "text/javascript" || node.attrMap.type === "text/babel" || node.attrMap.type === "application/javascript") {
40993 if (node.attrMap.type === "application/x-typescript" || node.attrMap.lang === "ts" || node.attrMap.lang === "tsx") {
40994 return "typescript";
40997 if (node.attrMap.type === "text/markdown") {
41001 if (node.attrMap.type.endsWith("json") || node.attrMap.type.endsWith("importmap")) {
41006 if (node.name === "style") {
41007 if (!node.attrMap.lang || node.attrMap.lang === "postcss" || node.attrMap.lang === "css") {
41011 if (node.attrMap.lang === "scss") {
41015 if (node.attrMap.lang === "less") {
41023 function isBlockLikeCssDisplay(cssDisplay) {
41024 return cssDisplay === "block" || cssDisplay === "list-item" || cssDisplay.startsWith("table");
41027 function isFirstChildLeadingSpaceSensitiveCssDisplay(cssDisplay) {
41028 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
41031 function isLastChildTrailingSpaceSensitiveCssDisplay(cssDisplay) {
41032 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
41035 function isPrevTrailingSpaceSensitiveCssDisplay(cssDisplay) {
41036 return !isBlockLikeCssDisplay(cssDisplay);
41039 function isNextLeadingSpaceSensitiveCssDisplay(cssDisplay) {
41040 return !isBlockLikeCssDisplay(cssDisplay);
41043 function isDanglingSpaceSensitiveCssDisplay(cssDisplay) {
41044 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
41047 function isPreLikeNode(node) {
41048 return getNodeCssStyleWhiteSpace(node).startsWith("pre");
41051 function countParents(path) {
41052 var predicate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {
41057 for (var i = path.stack.length - 1; i >= 0; i--) {
41058 var value = path.stack[i];
41060 if (value && typeof value === "object" && !Array.isArray(value) && predicate(value)) {
41068 function hasParent(node, fn) {
41069 var current = node;
41076 current = current.parent;
41082 function getNodeCssStyleDisplay(node, options) {
41083 if (node.prev && node.prev.type === "comment") {
41084 // <!-- display: block -->
41085 var match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/);
41092 var isInSvgForeignObject = false;
41094 if (node.type === "element" && node.namespace === "svg") {
41095 if (hasParent(node, function (parent) {
41096 return parent.fullName === "svg:foreignObject";
41098 isInSvgForeignObject = true;
41100 return node.name === "svg" ? "inline-block" : "block";
41104 switch (options.htmlWhitespaceSensitivity) {
41112 return node.type === "element" && (!node.namespace || isInSvgForeignObject) && CSS_DISPLAY_TAGS[node.name] || CSS_DISPLAY_DEFAULT;
41116 function getNodeCssStyleWhiteSpace(node) {
41117 return node.type === "element" && !node.namespace && CSS_WHITE_SPACE_TAGS[node.name] || CSS_WHITE_SPACE_DEFAULT;
41120 function getMinIndentation(text) {
41121 var minIndentation = Infinity;
41122 var _iteratorNormalCompletion2 = true;
41123 var _didIteratorError2 = false;
41124 var _iteratorError2 = undefined;
41127 for (var _iterator2 = text.split("\n")[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
41128 var lineText = _step2.value;
41130 if (lineText.length === 0) {
41134 if (/\S/.test(lineText[0])) {
41138 var indentation = lineText.match(/^\s*/)[0].length;
41140 if (lineText.length === indentation) {
41144 if (indentation < minIndentation) {
41145 minIndentation = indentation;
41149 _didIteratorError2 = true;
41150 _iteratorError2 = err;
41153 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
41154 _iterator2.return();
41157 if (_didIteratorError2) {
41158 throw _iteratorError2;
41163 return minIndentation === Infinity ? 0 : minIndentation;
41166 function dedentString(text) {
41167 var minIndent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : getMinIndentation(text);
41168 return minIndent === 0 ? text : text.split("\n").map(function (lineText) {
41169 return lineText.slice(minIndent);
41173 function normalizeParts$1(parts) {
41175 var restParts = parts.slice();
41177 while (restParts.length !== 0) {
41178 var part = restParts.shift();
41184 if (part.type === "concat") {
41185 Array.prototype.unshift.apply(restParts, part.parts);
41189 if (newParts.length !== 0 && typeof newParts[newParts.length - 1] === "string" && typeof part === "string") {
41190 newParts.push(newParts.pop() + part);
41194 newParts.push(part);
41200 function identity$2(x) {
41204 function shouldNotPrintClosingTag(node, options) {
41205 return !node.isSelfClosing && !node.endSourceSpan && (hasPrettierIgnore$3(node) || shouldPreserveContent(node.parent, options));
41208 function countChars(text, char) {
41211 for (var i = 0; i < text.length; i++) {
41212 if (text[i] === char) {
41220 function unescapeQuoteEntities(text) {
41221 return text.replace(/'/g, "'").replace(/"/g, '"');
41225 HTML_ELEMENT_ATTRIBUTES,
41227 canHaveInterpolation,
41231 forceBreakChildren,
41233 forceNextEmptyLine,
41235 getNodeCssStyleDisplay,
41236 getNodeCssStyleWhiteSpace,
41237 getPrettierIgnoreAttributeCommentData,
41238 hasPrettierIgnore: hasPrettierIgnore$3,
41239 identity: identity$2,
41241 isDanglingSpaceSensitiveNode,
41243 isIndentationSensitiveNode,
41244 isLeadingSpaceSensitiveNode,
41248 isTrailingSpaceSensitiveNode,
41249 isWhitespaceSensitiveNode,
41250 normalizeParts: normalizeParts$1,
41251 preferHardlineAsLeadingSpaces,
41252 preferHardlineAsTrailingSpaces,
41253 shouldNotPrintClosingTag,
41254 shouldPreserveContent,
41255 unescapeQuoteEntities
41258 var canHaveInterpolation$1 = utils$5.canHaveInterpolation,
41259 getNodeCssStyleDisplay$1 = utils$5.getNodeCssStyleDisplay,
41260 isDanglingSpaceSensitiveNode$1 = utils$5.isDanglingSpaceSensitiveNode,
41261 isIndentationSensitiveNode$1 = utils$5.isIndentationSensitiveNode,
41262 isLeadingSpaceSensitiveNode$1 = utils$5.isLeadingSpaceSensitiveNode,
41263 isTrailingSpaceSensitiveNode$1 = utils$5.isTrailingSpaceSensitiveNode,
41264 isWhitespaceSensitiveNode$1 = utils$5.isWhitespaceSensitiveNode;
41265 var PREPROCESS_PIPELINE = [removeIgnorableFirstLf, mergeIeConditonalStartEndCommentIntoElementOpeningTag, mergeCdataIntoText, extractInterpolation, extractWhitespaces, addCssDisplay, addIsSelfClosing, addHasHtmComponentClosingTag, addIsSpaceSensitive, mergeSimpleElementIntoText];
41267 function preprocess$2(ast, options) {
41268 var _iteratorNormalCompletion = true;
41269 var _didIteratorError = false;
41270 var _iteratorError = undefined;
41273 for (var _iterator = PREPROCESS_PIPELINE[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
41274 var fn = _step.value;
41275 ast = fn(ast, options);
41278 _didIteratorError = true;
41279 _iteratorError = err;
41282 if (!_iteratorNormalCompletion && _iterator.return != null) {
41283 _iterator.return();
41286 if (_didIteratorError) {
41287 throw _iteratorError;
41295 function removeIgnorableFirstLf(ast
41298 return ast.map(function (node) {
41299 if (node.type === "element" && node.tagDefinition.ignoreFirstLf && node.children.length !== 0 && node.children[0].type === "text" && node.children[0].value[0] === "\n") {
41300 var text = node.children[0];
41301 return node.clone({
41302 children: text.value.length === 1 ? node.children.slice(1) : [].concat(text.clone({
41303 value: text.value.slice(1)
41304 }), node.children.slice(1))
41312 function mergeIeConditonalStartEndCommentIntoElementOpeningTag(ast
41316 * <!--[if ...]><!--><target><!--<![endif]-->
41318 var isTarget = function isTarget(node) {
41319 return 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;
41322 return ast.map(function (node) {
41323 if (node.children) {
41324 var isTargetResults = node.children.map(isTarget);
41326 if (isTargetResults.some(Boolean)) {
41327 var newChildren = [];
41329 for (var i = 0; i < node.children.length; i++) {
41330 var child = node.children[i];
41332 if (isTargetResults[i + 1]) {
41333 // ieConditionalStartComment
41337 if (isTargetResults[i]) {
41338 var ieConditionalStartComment = child.prev;
41339 var ieConditionalEndComment = child.firstChild;
41340 var ParseSourceSpan = child.sourceSpan.constructor;
41341 var startSourceSpan = new ParseSourceSpan(ieConditionalStartComment.sourceSpan.start, ieConditionalEndComment.sourceSpan.end);
41342 var sourceSpan = new ParseSourceSpan(startSourceSpan.start, child.sourceSpan.end);
41343 newChildren.push(child.clone({
41344 condition: ieConditionalStartComment.condition,
41347 children: child.children.slice(1)
41352 newChildren.push(child);
41355 return node.clone({
41356 children: newChildren
41365 function mergeNodeIntoText(ast, shouldMerge, getValue) {
41366 return ast.map(function (node) {
41367 if (node.children) {
41368 var shouldMergeResults = node.children.map(shouldMerge);
41370 if (shouldMergeResults.some(Boolean)) {
41371 var newChildren = [];
41373 for (var i = 0; i < node.children.length; i++) {
41374 var child = node.children[i];
41376 if (child.type !== "text" && !shouldMergeResults[i]) {
41377 newChildren.push(child);
41381 var newChild = child.type === "text" ? child : child.clone({
41383 value: getValue(child)
41386 if (newChildren.length === 0 || newChildren[newChildren.length - 1].type !== "text") {
41387 newChildren.push(newChild);
41391 var lastChild = newChildren.pop();
41392 var ParseSourceSpan = lastChild.sourceSpan.constructor;
41393 newChildren.push(lastChild.clone({
41394 value: lastChild.value + newChild.value,
41395 sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, newChild.sourceSpan.end)
41399 return node.clone({
41400 children: newChildren
41409 function mergeCdataIntoText(ast
41412 return mergeNodeIntoText(ast, function (node) {
41413 return node.type === "cdata";
41414 }, function (node) {
41415 return `<![CDATA[${node.value}]]>`;
41419 function mergeSimpleElementIntoText(ast
41422 var isSimpleElement = function isSimpleElement(node) {
41423 return node.type === "element" && node.attrs.length === 0 && node.children.length === 1 && node.firstChild.type === "text" && // \xA0: non-breaking whitespace
41424 !/[^\S\xA0]/.test(node.children[0].value) && !node.firstChild.hasLeadingSpaces && !node.firstChild.hasTrailingSpaces && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces && node.prev && node.prev.type === "text" && node.next && node.next.type === "text";
41427 return ast.map(function (node) {
41428 if (node.children) {
41429 var isSimpleElementResults = node.children.map(isSimpleElement);
41431 if (isSimpleElementResults.some(Boolean)) {
41432 var newChildren = [];
41434 for (var i = 0; i < node.children.length; i++) {
41435 var child = node.children[i];
41437 if (isSimpleElementResults[i]) {
41438 var lastChild = newChildren.pop();
41439 var nextChild = node.children[++i];
41440 var ParseSourceSpan = node.sourceSpan.constructor;
41441 var isTrailingSpaceSensitive = nextChild.isTrailingSpaceSensitive,
41442 hasTrailingSpaces = nextChild.hasTrailingSpaces;
41443 newChildren.push(lastChild.clone({
41444 value: lastChild.value + `<${child.rawName}>` + child.firstChild.value + `</${child.rawName}>` + nextChild.value,
41445 sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, nextChild.sourceSpan.end),
41446 isTrailingSpaceSensitive,
41450 newChildren.push(child);
41454 return node.clone({
41455 children: newChildren
41464 function extractInterpolation(ast, options) {
41465 if (options.parser === "html") {
41469 var interpolationRegex = /\{\{([\s\S]+?)\}\}/g;
41470 return ast.map(function (node) {
41471 if (!canHaveInterpolation$1(node)) {
41475 var newChildren = [];
41476 var _iteratorNormalCompletion2 = true;
41477 var _didIteratorError2 = false;
41478 var _iteratorError2 = undefined;
41481 for (var _iterator2 = node.children[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
41482 var child = _step2.value;
41484 if (child.type !== "text") {
41485 newChildren.push(child);
41489 var ParseSourceSpan = child.sourceSpan.constructor;
41490 var startSourceSpan = child.sourceSpan.start;
41491 var endSourceSpan = null;
41492 var components = child.value.split(interpolationRegex);
41494 for (var i = 0; i < components.length; i++, startSourceSpan = endSourceSpan) {
41495 var value = components[i];
41498 endSourceSpan = startSourceSpan.moveBy(value.length);
41500 if (value.length !== 0) {
41504 sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan)
41511 endSourceSpan = startSourceSpan.moveBy(value.length + 4); // `{{` + `}}`
41514 type: "interpolation",
41515 sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan),
41516 children: value.length === 0 ? [] : [{
41519 sourceSpan: new ParseSourceSpan(startSourceSpan.moveBy(2), endSourceSpan.moveBy(-2))
41525 _didIteratorError2 = true;
41526 _iteratorError2 = err;
41529 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
41530 _iterator2.return();
41533 if (_didIteratorError2) {
41534 throw _iteratorError2;
41539 return node.clone({
41540 children: newChildren
41545 * - add `hasLeadingSpaces` field
41546 * - add `hasTrailingSpaces` field
41547 * - add `hasDanglingSpaces` field for parent nodes
41548 * - add `isWhitespaceSensitive`, `isIndentationSensitive` field for text nodes
41549 * - remove insensitive whitespaces
41553 function extractWhitespaces(ast
41556 var TYPE_WHITESPACE = "whitespace";
41557 return ast.map(function (node) {
41558 if (!node.children) {
41562 if (node.children.length === 0 || node.children.length === 1 && node.children[0].type === "text" && node.children[0].value.trim().length === 0) {
41563 return node.clone({
41565 hasDanglingSpaces: node.children.length !== 0
41569 var isWhitespaceSensitive = isWhitespaceSensitiveNode$1(node);
41570 var isIndentationSensitive = isIndentationSensitiveNode$1(node);
41571 return node.clone({
41572 isWhitespaceSensitive,
41573 isIndentationSensitive,
41574 children: node.children // extract whitespace nodes
41575 .reduce(function (newChildren, child) {
41576 if (child.type !== "text" || isWhitespaceSensitive) {
41577 return newChildren.concat(child);
41580 var localChildren = [];
41582 var _child$value$match = child.value.match(/^(\s*)([\s\S]*?)(\s*)$/),
41583 _child$value$match2 = _slicedToArray(_child$value$match, 4),
41584 leadingSpaces = _child$value$match2[1],
41585 text = _child$value$match2[2],
41586 trailingSpaces = _child$value$match2[3];
41588 if (leadingSpaces) {
41589 localChildren.push({
41590 type: TYPE_WHITESPACE
41594 var ParseSourceSpan = child.sourceSpan.constructor;
41597 localChildren.push({
41600 sourceSpan: new ParseSourceSpan(child.sourceSpan.start.moveBy(leadingSpaces.length), child.sourceSpan.end.moveBy(-trailingSpaces.length))
41604 if (trailingSpaces) {
41605 localChildren.push({
41606 type: TYPE_WHITESPACE
41610 return newChildren.concat(localChildren);
41611 }, []) // set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
41612 .reduce(function (newChildren, child, i, children) {
41613 if (child.type === TYPE_WHITESPACE) {
41614 return newChildren;
41617 var hasLeadingSpaces = i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
41618 var hasTrailingSpaces = i !== children.length - 1 && children[i + 1].type === TYPE_WHITESPACE;
41619 return newChildren.concat(Object.assign({}, child, {
41628 function addIsSelfClosing(ast
41631 return ast.map(function (node) {
41632 return Object.assign(node, {
41633 isSelfClosing: !node.children || node.type === "element" && (node.tagDefinition.isVoid || // self-closing
41634 node.startSourceSpan === node.endSourceSpan)
41639 function addHasHtmComponentClosingTag(ast, options) {
41640 return ast.map(function (node) {
41641 return node.type !== "element" ? node : Object.assign(node, {
41642 hasHtmComponentClosingTag: node.endSourceSpan && /^<\s*\/\s*\/\s*>$/.test(options.originalText.slice(node.endSourceSpan.start.offset, node.endSourceSpan.end.offset))
41647 function addCssDisplay(ast, options) {
41648 return ast.map(function (node) {
41649 return Object.assign(node, {
41650 cssDisplay: getNodeCssStyleDisplay$1(node, options)
41655 * - add `isLeadingSpaceSensitive` field
41656 * - add `isTrailingSpaceSensitive` field
41657 * - add `isDanglingSpaceSensitive` field for parent nodes
41661 function addIsSpaceSensitive(ast
41664 return ast.map(function (node) {
41665 if (!node.children) {
41669 if (node.children.length === 0) {
41670 return node.clone({
41671 isDanglingSpaceSensitive: isDanglingSpaceSensitiveNode$1(node)
41675 return node.clone({
41676 children: node.children.map(function (child) {
41677 return Object.assign({}, child, {
41678 isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode$1(child),
41679 isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode$1(child)
41681 }).map(function (child, index, children) {
41682 return Object.assign({}, child, {
41683 isLeadingSpaceSensitive: index === 0 ? child.isLeadingSpaceSensitive : children[index - 1].isTrailingSpaceSensitive && child.isLeadingSpaceSensitive,
41684 isTrailingSpaceSensitive: index === children.length - 1 ? child.isTrailingSpaceSensitive : children[index + 1].isLeadingSpaceSensitive && child.isTrailingSpaceSensitive
41691 var preprocess_1$2 = preprocess$2;
41693 function hasPragma$3(text) {
41694 return /^\s*<!--\s*@(format|prettier)\s*-->/.test(text);
41697 function insertPragma$6(text) {
41698 return "<!-- @format -->\n\n" + text.replace(/^\s*\n/, "");
41702 hasPragma: hasPragma$3,
41703 insertPragma: insertPragma$6
41706 var _require$$0$builders$8 = doc.builders,
41707 concat$e = _require$$0$builders$8.concat,
41708 group$e = _require$$0$builders$8.group;
41710 * v-for="... in ..."
41711 * v-for="... of ..."
41712 * v-for="(..., ...) in ..."
41713 * v-for="(..., ...) of ..."
41716 function printVueFor(value, textToDoc) {
41717 var _parseVueFor = parseVueFor(value),
41718 left = _parseVueFor.left,
41719 operator = _parseVueFor.operator,
41720 right = _parseVueFor.right;
41722 return concat$e([group$e(textToDoc(`function _(${left}) {}`, {
41724 __isVueForBindingLeft: true
41725 })), " ", operator, " ", textToDoc(right, {
41726 parser: "__js_expression"
41728 } // modified from https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/parser/index.js#L370-L387
41731 function parseVueFor(value) {
41732 var forAliasRE = /([^]*?)\s+(in|of)\s+([^]*)/;
41733 var forIteratorRE = /,([^,}\]]*)(?:,([^,}\]]*))?$/;
41734 var stripParensRE = /^\(|\)$/g;
41735 var inMatch = value.match(forAliasRE);
41742 res.for = inMatch[3].trim();
41743 var alias = inMatch[1].trim().replace(stripParensRE, "");
41744 var iteratorMatch = alias.match(forIteratorRE);
41746 if (iteratorMatch) {
41747 res.alias = alias.replace(forIteratorRE, "");
41748 res.iterator1 = iteratorMatch[1].trim();
41750 if (iteratorMatch[2]) {
41751 res.iterator2 = iteratorMatch[2].trim();
41758 left: `${[res.alias, res.iterator1, res.iterator2].filter(Boolean).join(",")}`,
41759 operator: inMatch[2],
41764 function printVueSlotScope(value, textToDoc) {
41765 return textToDoc(`function _(${value}) {}`, {
41767 __isVueSlotScope: true
41771 function isVueEventBindingExpression$2(eventBindingValue) {
41772 // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/codegen/events.js#L3-L4
41773 // arrow function or anonymous function
41774 var fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; // simple member expression chain (a, a.b, a['b'], a["b"], a[0], a[b])
41776 var simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/; // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/helpers.js#L104
41778 var value = eventBindingValue.trim();
41779 return fnExpRE.test(value) || simplePathRE.test(value);
41783 isVueEventBindingExpression: isVueEventBindingExpression$2,
41788 var parseSrcset = createCommonjsModule(function (module) {
41792 * By Alex Bell | MIT License
41794 * JS Parser for the string value that appears in markup <img srcset="here">
41796 * @returns Array [{url: _, d: _, w: _, h:_}, ...]
41798 * Based super duper closely on the reference algorithm at:
41799 * https://html.spec.whatwg.org/multipage/embedded-content.html#parse-a-srcset-attribute
41801 * Most comments are copied in directly from the spec
41802 * (except for comments in parens).
41804 (function (root, factory) {
41805 if ( module.exports) {
41806 // Node. Does not work with strict CommonJS, but
41807 // only CommonJS-like environments that support module.exports,
41809 module.exports = factory();
41811 // Browser globals (root is window)
41812 root.parseSrcset = factory();
41814 })(this, function () {
41815 // 1. Let input be the value passed to this algorithm.
41816 return function (input, options) {
41817 var logger = options && options.logger || console; // UTILITY FUNCTIONS
41818 // Manual is faster than RegEx
41819 // http://bjorn.tipling.com/state-and-regular-expressions-in-javascript
41820 // http://jsperf.com/whitespace-character/5
41822 function isSpace(c) {
41823 return c === "\u0020" || // space
41824 c === "\u0009" || // horizontal tab
41825 c === "\u000A" || // new line
41826 c === "\u000C" || // form feed
41827 c === "\u000D"; // carriage return
41830 function collectCharacters(regEx) {
41832 match = regEx.exec(input.substring(pos));
41836 pos += chars.length;
41841 var inputLength = input.length,
41842 // (Don't use \s, to avoid matching non-breaking space)
41843 regexLeadingSpaces = /^[ \t\n\r\u000c]+/,
41844 regexLeadingCommasOrSpaces = /^[, \t\n\r\u000c]+/,
41845 regexLeadingNotSpaces = /^[^ \t\n\r\u000c]+/,
41846 regexTrailingCommas = /[,]+$/,
41847 regexNonNegativeInteger = /^\d+$/,
41848 // ( Positive or negative or unsigned integers or decimals, without or without exponents.
41849 // Must include at least one digit.
41850 // According to spec tests any decimal point must be followed by a digit.
41851 // No leading plus sign is allowed.)
41852 // https://html.spec.whatwg.org/multipage/infrastructure.html#valid-floating-point-number
41853 regexFloatingPoint = /^-?(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/,
41859 // 2. Let position be a pointer into input, initially pointing at the start
41862 // 3. Let candidates be an initially empty source set.
41863 candidates = []; // 4. Splitting loop: Collect a sequence of characters that are space
41864 // characters or U+002C COMMA characters. If any U+002C COMMA characters
41865 // were collected, that is a parse error.
41868 collectCharacters(regexLeadingCommasOrSpaces); // 5. If position is past the end of input, return candidates and abort these steps.
41870 if (pos >= inputLength) {
41871 return candidates; // (we're done, this is the sole return path)
41872 } // 6. Collect a sequence of characters that are not space characters,
41873 // and let that be url.
41876 url = collectCharacters(regexLeadingNotSpaces); // 7. Let descriptors be a new empty list.
41878 descriptors = []; // 8. If url ends with a U+002C COMMA character (,), follow these substeps:
41879 // (1). Remove all trailing U+002C COMMA characters from url. If this removed
41880 // more than one character, that is a parse error.
41882 if (url.slice(-1) === ",") {
41883 url = url.replace(regexTrailingCommas, ""); // (Jump ahead to step 9 to skip tokenization and just push the candidate).
41885 parseDescriptors(); // Otherwise, follow these substeps:
41888 } // (close else of step 8)
41889 // 16. Return to the step labeled splitting loop.
41891 } // (Close of big while loop.)
41894 * Tokenizes descriptor properties prior to parsing
41895 * Returns undefined.
41899 function tokenize() {
41900 // 8.1. Descriptor tokeniser: Skip whitespace
41901 collectCharacters(regexLeadingSpaces); // 8.2. Let current descriptor be the empty string.
41903 currentDescriptor = ""; // 8.3. Let state be in descriptor.
41905 state = "in descriptor";
41908 // 8.4. Let c be the character at position.
41909 c = input.charAt(pos); // Do the following depending on the value of state.
41910 // For the purpose of this step, "EOF" is a special character representing
41911 // that position is past the end of input.
41914 if (state === "in descriptor") {
41915 // Do the following, depending on the value of c:
41917 // If current descriptor is not empty, append current descriptor to
41918 // descriptors and let current descriptor be the empty string.
41919 // Set state to after descriptor.
41921 if (currentDescriptor) {
41922 descriptors.push(currentDescriptor);
41923 currentDescriptor = "";
41924 state = "after descriptor";
41925 } // U+002C COMMA (,)
41926 // Advance position to the next character in input. If current descriptor
41927 // is not empty, append current descriptor to descriptors. Jump to the step
41928 // labeled descriptor parser.
41930 } else if (c === ",") {
41933 if (currentDescriptor) {
41934 descriptors.push(currentDescriptor);
41937 parseDescriptors();
41938 return; // U+0028 LEFT PARENTHESIS (()
41939 // Append c to current descriptor. Set state to in parens.
41940 } else if (c === "\u0028") {
41941 currentDescriptor = currentDescriptor + c;
41942 state = "in parens"; // EOF
41943 // If current descriptor is not empty, append current descriptor to
41944 // descriptors. Jump to the step labeled descriptor parser.
41945 } else if (c === "") {
41946 if (currentDescriptor) {
41947 descriptors.push(currentDescriptor);
41950 parseDescriptors();
41951 return; // Anything else
41952 // Append c to current descriptor.
41954 currentDescriptor = currentDescriptor + c;
41955 } // (end "in descriptor"
41958 } else if (state === "in parens") {
41959 // U+0029 RIGHT PARENTHESIS ())
41960 // Append c to current descriptor. Set state to in descriptor.
41962 currentDescriptor = currentDescriptor + c;
41963 state = "in descriptor"; // EOF
41964 // Append current descriptor to descriptors. Jump to the step labeled
41965 // descriptor parser.
41966 } else if (c === "") {
41967 descriptors.push(currentDescriptor);
41968 parseDescriptors();
41969 return; // Anything else
41970 // Append c to current descriptor.
41972 currentDescriptor = currentDescriptor + c;
41973 } // After descriptor
41975 } else if (state === "after descriptor") {
41976 // Do the following, depending on the value of c:
41977 // Space character: Stay in this state.
41978 if (isSpace(c)) ; else if (c === "") {
41979 parseDescriptors();
41980 return; // Anything else
41981 // Set state to in descriptor. Set position to the previous character in input.
41983 state = "in descriptor";
41986 } // Advance position to the next character in input.
41989 pos += 1; // Repeat this step.
41990 } // (close while true loop)
41994 * Adds descriptor properties to a candidate, pushes to the candidates array
41995 * @return undefined
41997 // Declared outside of the while loop so that it's only created once.
42000 function parseDescriptors() {
42001 // 9. Descriptor parser: Let error be no.
42002 var pError = false,
42003 // 10. Let width be absent.
42004 // 11. Let density be absent.
42005 // 12. Let future-compat-h be absent. (We're implementing it now as h)
42015 floatVal; // 13. For each descriptor in descriptors, run the appropriate set of steps
42016 // from the following list:
42018 for (i = 0; i < descriptors.length; i++) {
42019 desc = descriptors[i];
42020 lastChar = desc[desc.length - 1];
42021 value = desc.substring(0, desc.length - 1);
42022 intVal = parseInt(value, 10);
42023 floatVal = parseFloat(value); // If the descriptor consists of a valid non-negative integer followed by
42024 // a U+0077 LATIN SMALL LETTER W character
42026 if (regexNonNegativeInteger.test(value) && lastChar === "w") {
42027 // If width and density are not both absent, then let error be yes.
42030 } // Apply the rules for parsing non-negative integers to the descriptor.
42031 // If the result is zero, let error be yes.
42032 // Otherwise, let width be the result.
42035 if (intVal === 0) {
42039 } // If the descriptor consists of a valid floating-point number followed by
42040 // a U+0078 LATIN SMALL LETTER X character
42042 } else if (regexFloatingPoint.test(value) && lastChar === "x") {
42043 // If width, density and future-compat-h are not all absent, then let error
42047 } // Apply the rules for parsing floating-point number values to the descriptor.
42048 // If the result is less than zero, let error be yes. Otherwise, let density
42052 if (floatVal < 0) {
42056 } // If the descriptor consists of a valid non-negative integer followed by
42057 // a U+0068 LATIN SMALL LETTER H character
42059 } else if (regexNonNegativeInteger.test(value) && lastChar === "h") {
42060 // If height and density are not both absent, then let error be yes.
42063 } // Apply the rules for parsing non-negative integers to the descriptor.
42064 // If the result is zero, let error be yes. Otherwise, let future-compat-h
42068 if (intVal === 0) {
42072 } // Anything else, Let error be yes.
42077 } // (close step 13 for loop)
42078 // 15. If error is still no, then append a new image source to candidates whose
42079 // URL is url, associated with a width width if not absent and a pixel
42080 // density density if not absent. Otherwise, there is a parse error.
42084 candidate.url = url;
42098 candidates.push(candidate);
42099 } else if (logger && logger.error) {
42100 logger.error("Invalid srcset descriptor found in '" + input + "' at '" + desc + "'.");
42102 } // (close parseDescriptors fn)
42108 var _require$$0$builders$9 = doc.builders,
42109 concat$f = _require$$0$builders$9.concat,
42110 ifBreak$6 = _require$$0$builders$9.ifBreak,
42111 join$a = _require$$0$builders$9.join,
42112 line$7 = _require$$0$builders$9.line;
42114 function printImgSrcset(value) {
42115 var srcset = parseSrcset(value, {
42118 throw new Error(message);
42123 var hasW = srcset.some(function (src) {
42126 var hasH = srcset.some(function (src) {
42129 var hasX = srcset.some(function (src) {
42133 if (hasW + hasH + hasX !== 1) {
42134 throw new Error(`Mixed descriptor in srcset is not supported`);
42137 var key = hasW ? "w" : hasH ? "h" : "d";
42138 var unit = hasW ? "w" : hasH ? "h" : "x";
42140 var getMax = function getMax(values) {
42141 return Math.max.apply(Math, values);
42144 var urls = srcset.map(function (src) {
42147 var maxUrlLength = getMax(urls.map(function (url) {
42150 var descriptors = srcset.map(function (src) {
42152 }).map(function (descriptor) {
42153 return descriptor ? descriptor.toString() : "";
42155 var descriptorLeftLengths = descriptors.map(function (descriptor) {
42156 var index = descriptor.indexOf(".");
42157 return index === -1 ? descriptor.length : index;
42159 var maxDescriptorLeftLength = getMax(descriptorLeftLengths);
42160 return join$a(concat$f([",", line$7]), urls.map(function (url, index) {
42162 var descriptor = descriptors[index];
42165 var urlPadding = maxUrlLength - url.length + 1;
42166 var descriptorPadding = maxDescriptorLeftLength - descriptorLeftLengths[index];
42167 var alignment = " ".repeat(urlPadding + descriptorPadding);
42168 parts.push(ifBreak$6(alignment, " "), descriptor + unit);
42171 return concat$f(parts);
42175 var syntaxAttribute = {
42179 var builders = doc.builders,
42180 _require$$0$utils = doc.utils,
42181 stripTrailingHardline$2 = _require$$0$utils.stripTrailingHardline,
42182 mapDoc$7 = _require$$0$utils.mapDoc;
42183 var breakParent$4 = builders.breakParent,
42184 dedentToRoot$2 = builders.dedentToRoot,
42185 fill$5 = builders.fill,
42186 group$f = builders.group,
42187 hardline$c = builders.hardline,
42188 ifBreak$7 = builders.ifBreak,
42189 indent$9 = builders.indent,
42190 join$b = builders.join,
42191 line$8 = builders.line,
42192 literalline$6 = builders.literalline,
42193 markAsRoot$4 = builders.markAsRoot,
42194 softline$7 = builders.softline;
42195 var countChars$1 = utils$5.countChars,
42196 countParents$1 = utils$5.countParents,
42197 dedentString$1 = utils$5.dedentString,
42198 forceBreakChildren$1 = utils$5.forceBreakChildren,
42199 forceBreakContent$1 = utils$5.forceBreakContent,
42200 forceNextEmptyLine$1 = utils$5.forceNextEmptyLine,
42201 getLastDescendant$1 = utils$5.getLastDescendant,
42202 getPrettierIgnoreAttributeCommentData$1 = utils$5.getPrettierIgnoreAttributeCommentData,
42203 hasPrettierIgnore$4 = utils$5.hasPrettierIgnore,
42204 inferScriptParser$1 = utils$5.inferScriptParser,
42205 isScriptLikeTag$1 = utils$5.isScriptLikeTag,
42206 isTextLikeNode$1 = utils$5.isTextLikeNode,
42207 normalizeParts$2 = utils$5.normalizeParts,
42208 preferHardlineAsLeadingSpaces$1 = utils$5.preferHardlineAsLeadingSpaces,
42209 shouldNotPrintClosingTag$1 = utils$5.shouldNotPrintClosingTag,
42210 shouldPreserveContent$1 = utils$5.shouldPreserveContent,
42211 unescapeQuoteEntities$1 = utils$5.unescapeQuoteEntities;
42212 var replaceEndOfLineWith$2 = util.replaceEndOfLineWith;
42213 var insertPragma$7 = pragma$4.insertPragma;
42214 var printVueFor$1 = syntaxVue.printVueFor,
42215 printVueSlotScope$1 = syntaxVue.printVueSlotScope,
42216 isVueEventBindingExpression$3 = syntaxVue.isVueEventBindingExpression;
42217 var printImgSrcset$1 = syntaxAttribute.printImgSrcset;
42219 function concat$g(parts) {
42220 var newParts = normalizeParts$2(parts);
42221 return newParts.length === 0 ? "" : newParts.length === 1 ? newParts[0] : builders.concat(newParts);
42224 function embed$4(path, print, textToDoc, options) {
42225 var node = path.getValue();
42227 switch (node.type) {
42230 if (isScriptLikeTag$1(node.parent)) {
42231 var parser = inferScriptParser$1(node.parent);
42234 var value = parser === "markdown" ? dedentString$1(node.value.replace(/^[^\S\n]*?\n/, "")) : node.value;
42235 return builders.concat([concat$g([breakParent$4, printOpeningTagPrefix(node, options), stripTrailingHardline$2(textToDoc(value, {
42237 })), printClosingTagSuffix(node, options)])]);
42239 } else if (node.parent.type === "interpolation") {
42240 return concat$g([indent$9(concat$g([line$8, textToDoc(node.value, Object.assign({
42241 __isInHtmlInterpolation: true // to avoid unexpected `}}`
42243 }, options.parser === "angular" ? {
42244 parser: "__ng_interpolation",
42245 trailingComma: "none"
42246 } : options.parser === "vue" ? {
42247 parser: "__vue_expression"
42249 parser: "__js_expression"
42250 }))])), node.parent.next && needsToBorrowPrevClosingTagEndMarker(node.parent.next) ? " " : line$8]);
42260 } // lit-html: html`<my-element obj=${obj}></my-element>`
42263 if (/^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
42264 return concat$g([node.rawName, "=", node.value]);
42265 } // lwc: html`<my-element data-for={value}></my-element>`
42268 if (options.parser === "lwc") {
42269 var interpolationRegex = /^\{[\s\S]*\}$/;
42271 if (interpolationRegex.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
42272 return concat$g([node.rawName, "=", node.value]);
42276 var embeddedAttributeValueDoc = printEmbeddedAttributeValue(node, function (code, opts) {
42277 return (// strictly prefer single quote to avoid unnecessary html entity escape
42278 textToDoc(code, Object.assign({
42279 __isInHtmlAttribute: true
42284 if (embeddedAttributeValueDoc) {
42285 return concat$g([node.rawName, '="', group$f(mapDoc$7(embeddedAttributeValueDoc, function (doc) {
42286 return typeof doc === "string" ? doc.replace(/"/g, """) : doc;
42294 return markAsRoot$4(concat$g(["---", hardline$c, node.value.trim().length === 0 ? "" : textToDoc(node.value, {
42300 function genericPrint$5(path, options, print) {
42301 var node = path.getValue();
42303 switch (node.type) {
42305 // use original concat to not break stripTrailingHardline
42306 return builders.concat([group$f(printChildren$2(path, options, print)), hardline$c]);
42309 case "ieConditionalComment":
42320 * exception: break if the opening tag breaks
42331 var shouldHugContent = node.children.length === 1 && node.firstChild.type === "interpolation" && node.firstChild.isLeadingSpaceSensitive && !node.firstChild.hasLeadingSpaces && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces;
42332 var attrGroupId = Symbol("element-attr-group-id");
42333 return concat$g([group$f(concat$g([group$f(printOpeningTag(path, options, print), {
42335 }), node.children.length === 0 ? node.hasDanglingSpaces && node.isDanglingSpaceSensitive ? line$8 : "" : concat$g([forceBreakContent$1(node) ? breakParent$4 : "", function (childrenDoc) {
42336 return shouldHugContent ? ifBreak$7(indent$9(childrenDoc), childrenDoc, {
42337 groupId: attrGroupId
42338 }) : isScriptLikeTag$1(node) && node.parent.type === "root" && options.parser === "vue" && !options.vueIndentScriptAndStyle ? childrenDoc : indent$9(childrenDoc);
42339 }(concat$g([shouldHugContent ? ifBreak$7(softline$7, "", {
42340 groupId: attrGroupId
42341 }) : node.firstChild.hasLeadingSpaces && node.firstChild.isLeadingSpaceSensitive ? line$8 : node.firstChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive ? dedentToRoot$2(softline$7) : softline$7, printChildren$2(path, options, print)])), (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? " " : "" : shouldHugContent ? ifBreak$7(softline$7, "", {
42342 groupId: attrGroupId
42343 }) : node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? line$8 : (node.lastChild.type === "comment" || node.lastChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive) && new RegExp(`\\n\\s{${options.tabWidth * countParents$1(path, function (n) {
42344 return n.parent && n.parent.type !== "root";
42345 })}}$`).test(node.lastChild.value) ?
42354 "" : softline$7])])), printClosingTag(node, options)]);
42357 case "ieConditionalStartComment":
42358 case "ieConditionalEndComment":
42359 return concat$g([printOpeningTagStart(node), printClosingTagEnd(node)]);
42361 case "interpolation":
42362 return concat$g([printOpeningTagStart(node, options), concat$g(path.map(print, "children")), printClosingTagEnd(node, options)]);
42366 if (node.parent.type === "interpolation") {
42367 // replace the trailing literalline with hardline for better readability
42368 var trailingNewlineRegex = /\n[^\S\n]*?$/;
42369 var hasTrailingNewline = trailingNewlineRegex.test(node.value);
42370 var value = hasTrailingNewline ? node.value.replace(trailingNewlineRegex, "") : node.value;
42371 return concat$g([concat$g(replaceEndOfLineWith$2(value, literalline$6)), hasTrailingNewline ? hardline$c : ""]);
42374 return fill$5(normalizeParts$2([].concat(printOpeningTagPrefix(node, options), getTextValueParts(node), printClosingTagSuffix(node, options))));
42378 return concat$g([group$f(concat$g([printOpeningTagStart(node, options), " ", node.value.replace(/^html\b/i, "html").replace(/\s+/g, " ")])), printClosingTagEnd(node, options)]);
42382 return concat$g([printOpeningTagPrefix(node, options), concat$g(replaceEndOfLineWith$2(options.originalText.slice(options.locStart(node), options.locEnd(node)), literalline$6)), printClosingTagSuffix(node, options)]);
42387 if (node.value === null) {
42388 return node.rawName;
42391 var _value = unescapeQuoteEntities$1(node.value);
42393 var singleQuoteCount = countChars$1(_value, "'");
42394 var doubleQuoteCount = countChars$1(_value, '"');
42395 var quote = singleQuoteCount < doubleQuoteCount ? "'" : '"';
42396 return concat$g([node.rawName, concat$g(["=", quote, concat$g(replaceEndOfLineWith$2(quote === '"' ? _value.replace(/"/g, """) : _value.replace(/'/g, "'"), literalline$6)), quote])]);
42401 return concat$g(replaceEndOfLineWith$2(node.raw, literalline$6));
42404 throw new Error(`Unexpected node type ${node.type}`);
42408 function printChildren$2(path, options, print) {
42409 var node = path.getValue();
42411 if (forceBreakChildren$1(node)) {
42412 return concat$g([breakParent$4, concat$g(path.map(function (childPath) {
42413 var childNode = childPath.getValue();
42414 var prevBetweenLine = !childNode.prev ? "" : printBetweenLine(childNode.prev, childNode);
42415 return concat$g([!prevBetweenLine ? "" : concat$g([prevBetweenLine, forceNextEmptyLine$1(childNode.prev) ? hardline$c : ""]), printChild(childPath)]);
42419 var groupIds = node.children.map(function () {
42422 return concat$g(path.map(function (childPath, childIndex) {
42423 var childNode = childPath.getValue();
42425 if (isTextLikeNode$1(childNode)) {
42426 if (childNode.prev && isTextLikeNode$1(childNode.prev)) {
42427 var _prevBetweenLine = printBetweenLine(childNode.prev, childNode);
42429 if (_prevBetweenLine) {
42430 if (forceNextEmptyLine$1(childNode.prev)) {
42431 return concat$g([hardline$c, hardline$c, printChild(childPath)]);
42434 return concat$g([_prevBetweenLine, printChild(childPath)]);
42438 return printChild(childPath);
42441 var prevParts = [];
42442 var leadingParts = [];
42443 var trailingParts = [];
42444 var nextParts = [];
42445 var prevBetweenLine = childNode.prev ? printBetweenLine(childNode.prev, childNode) : "";
42446 var nextBetweenLine = childNode.next ? printBetweenLine(childNode, childNode.next) : "";
42448 if (prevBetweenLine) {
42449 if (forceNextEmptyLine$1(childNode.prev)) {
42450 prevParts.push(hardline$c, hardline$c);
42451 } else if (prevBetweenLine === hardline$c) {
42452 prevParts.push(hardline$c);
42454 if (isTextLikeNode$1(childNode.prev)) {
42455 leadingParts.push(prevBetweenLine);
42457 leadingParts.push(ifBreak$7("", softline$7, {
42458 groupId: groupIds[childIndex - 1]
42464 if (nextBetweenLine) {
42465 if (forceNextEmptyLine$1(childNode)) {
42466 if (isTextLikeNode$1(childNode.next)) {
42467 nextParts.push(hardline$c, hardline$c);
42469 } else if (nextBetweenLine === hardline$c) {
42470 if (isTextLikeNode$1(childNode.next)) {
42471 nextParts.push(hardline$c);
42474 trailingParts.push(nextBetweenLine);
42478 return concat$g([].concat(prevParts, group$f(concat$g([concat$g(leadingParts), group$f(concat$g([printChild(childPath), concat$g(trailingParts)]), {
42479 id: groupIds[childIndex]
42480 })])), nextParts));
42483 function printChild(childPath) {
42484 var child = childPath.getValue();
42486 if (hasPrettierIgnore$4(child)) {
42487 return concat$g([].concat(printOpeningTagPrefix(child, options), replaceEndOfLineWith$2(options.originalText.slice(options.locStart(child) + (child.prev && needsToBorrowNextOpeningTagStartMarker(child.prev) ? printOpeningTagStartMarker(child).length : 0), options.locEnd(child) - (child.next && needsToBorrowPrevClosingTagEndMarker(child.next) ? printClosingTagEndMarker(child, options).length : 0)), literalline$6), printClosingTagSuffix(child, options)));
42490 if (shouldPreserveContent$1(child, options)) {
42491 return concat$g([].concat(printOpeningTagPrefix(child, options), group$f(printOpeningTag(childPath, options, print)), replaceEndOfLineWith$2(options.originalText.slice(child.startSourceSpan.end.offset + (child.firstChild && needsToBorrowParentOpeningTagEndMarker(child.firstChild) ? -printOpeningTagEndMarker(child).length : 0), child.endSourceSpan.start.offset + (child.lastChild && needsToBorrowParentClosingTagStartMarker(child.lastChild) ? printClosingTagStartMarker(child, options).length : needsToBorrowLastChildClosingTagEndMarker(child) ? -printClosingTagEndMarker(child.lastChild, options).length : 0)), literalline$6), printClosingTag(child, options), printClosingTagSuffix(child, options)));
42494 return print(childPath);
42497 function printBetweenLine(prevNode, nextNode) {
42498 return isTextLikeNode$1(prevNode) && isTextLikeNode$1(nextNode) ? prevNode.isTrailingSpaceSensitive ? prevNode.hasTrailingSpaces ? preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$c : line$8 : "" : preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$c : softline$7 : needsToBorrowNextOpeningTagStartMarker(prevNode) && (
42504 nextNode.firstChild ||
42510 nextNode.isSelfClosing ||
42516 nextNode.type === "element" && nextNode.attrs.length !== 0) ||
42523 prevNode.type === "element" && prevNode.isSelfClosing && needsToBorrowPrevClosingTagEndMarker(nextNode) ? "" : !nextNode.isLeadingSpaceSensitive || preferHardlineAsLeadingSpaces$1(nextNode) ||
42525 * Want to write us a letter? Use our<a
42526 * ><b><a>mailing address</a></b></a
42530 needsToBorrowPrevClosingTagEndMarker(nextNode) && prevNode.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild) && prevNode.lastChild.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild.lastChild) ? hardline$c : nextNode.hasLeadingSpaces ? line$8 : softline$7;
42534 function printOpeningTag(path, options, print) {
42535 var node = path.getValue();
42536 var forceNotToBreakAttrContent = node.type === "element" && node.fullName === "script" && node.attrs.length === 1 && node.attrs[0].fullName === "src" && node.children.length === 0;
42537 return concat$g([printOpeningTagStart(node, options), !node.attrs || node.attrs.length === 0 ? node.isSelfClosing ?
42542 " " : "" : concat$g([indent$9(concat$g([forceNotToBreakAttrContent ? " " : line$8, join$b(line$8, function (ignoreAttributeData) {
42543 var hasPrettierIgnoreAttribute = typeof ignoreAttributeData === "boolean" ? function () {
42544 return ignoreAttributeData;
42545 } : Array.isArray(ignoreAttributeData) ? function (attr) {
42546 return ignoreAttributeData.indexOf(attr.rawName) !== -1;
42550 return path.map(function (attrPath) {
42551 var attr = attrPath.getValue();
42552 return hasPrettierIgnoreAttribute(attr) ? concat$g(replaceEndOfLineWith$2(options.originalText.slice(options.locStart(attr), options.locEnd(attr)), literalline$6)) : print(attrPath);
42554 }(node.prev && node.prev.type === "comment" && getPrettierIgnoreAttributeCommentData$1(node.prev.value)))])),
42561 node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ||
42568 node.isSelfClosing && needsToBorrowLastChildClosingTagEndMarker(node.parent) ? "" : node.isSelfClosing ? forceNotToBreakAttrContent ? " " : line$8 : forceNotToBreakAttrContent ? "" : softline$7]), node.isSelfClosing ? "" : printOpeningTagEnd(node)]);
42571 function printOpeningTagStart(node, options) {
42572 return node.prev && needsToBorrowNextOpeningTagStartMarker(node.prev) ? "" : concat$g([printOpeningTagPrefix(node, options), printOpeningTagStartMarker(node)]);
42575 function printOpeningTagEnd(node) {
42576 return node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ? "" : printOpeningTagEndMarker(node);
42579 function printClosingTag(node, options) {
42580 return concat$g([node.isSelfClosing ? "" : printClosingTagStart(node, options), printClosingTagEnd(node, options)]);
42583 function printClosingTagStart(node, options) {
42584 return node.lastChild && needsToBorrowParentClosingTagStartMarker(node.lastChild) ? "" : concat$g([printClosingTagPrefix(node, options), printClosingTagStartMarker(node, options)]);
42587 function printClosingTagEnd(node, options) {
42588 return (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? "" : concat$g([printClosingTagEndMarker(node, options), printClosingTagSuffix(node, options)]);
42591 function needsToBorrowNextOpeningTagStartMarker(node) {
42597 return node.next && !isTextLikeNode$1(node.next) && isTextLikeNode$1(node) && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces;
42600 function needsToBorrowParentOpeningTagEndMarker(node) {
42610 return !node.prev && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
42613 function needsToBorrowPrevClosingTagEndMarker(node) {
42623 return node.prev && !isTextLikeNode$1(node.prev) && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
42626 function needsToBorrowLastChildClosingTagEndMarker(node) {
42634 return node.lastChild && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces && !isTextLikeNode$1(getLastDescendant$1(node.lastChild));
42637 function needsToBorrowParentClosingTagStartMarker(node) {
42649 return !node.next && !node.hasTrailingSpaces && node.isTrailingSpaceSensitive && isTextLikeNode$1(getLastDescendant$1(node));
42652 function printOpeningTagPrefix(node, options) {
42653 return needsToBorrowParentOpeningTagEndMarker(node) ? printOpeningTagEndMarker(node.parent) : needsToBorrowPrevClosingTagEndMarker(node) ? printClosingTagEndMarker(node.prev, options) : "";
42656 function printClosingTagPrefix(node, options) {
42657 return needsToBorrowLastChildClosingTagEndMarker(node) ? printClosingTagEndMarker(node.lastChild, options) : "";
42660 function printClosingTagSuffix(node, options) {
42661 return needsToBorrowParentClosingTagStartMarker(node) ? printClosingTagStartMarker(node.parent, options) : needsToBorrowNextOpeningTagStartMarker(node) ? printOpeningTagStartMarker(node.next) : "";
42664 function printOpeningTagStartMarker(node) {
42665 switch (node.type) {
42666 case "ieConditionalComment":
42667 case "ieConditionalStartComment":
42668 return `<!--[if ${node.condition}`;
42670 case "ieConditionalEndComment":
42673 case "interpolation":
42677 return "<!DOCTYPE";
42680 if (node.condition) {
42681 return `<!--[if ${node.condition}]><!--><${node.rawName}`;
42687 return `<${node.rawName}`;
42691 function printOpeningTagEndMarker(node) {
42692 assert$1(!node.isSelfClosing);
42694 switch (node.type) {
42695 case "ieConditionalComment":
42699 if (node.condition) {
42700 return `><!--<![endif]-->`;
42710 function printClosingTagStartMarker(node, options) {
42711 assert$1(!node.isSelfClosing);
42713 if (shouldNotPrintClosingTag$1(node, options)) {
42717 switch (node.type) {
42718 case "ieConditionalComment":
42722 if (node.hasHtmComponentClosingTag) {
42729 return `</${node.rawName}`;
42733 function printClosingTagEndMarker(node, options) {
42734 if (shouldNotPrintClosingTag$1(node, options)) {
42738 switch (node.type) {
42739 case "ieConditionalComment":
42740 case "ieConditionalEndComment":
42741 return `[endif]-->`;
42743 case "ieConditionalStartComment":
42746 case "interpolation":
42750 if (node.isSelfClosing) {
42761 function getTextValueParts(node) {
42762 var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : node.value;
42763 return node.parent.isWhitespaceSensitive ? node.parent.isIndentationSensitive ? replaceEndOfLineWith$2(value, literalline$6) : replaceEndOfLineWith$2(dedentString$1(value.replace(/^\s*?\n|\n\s*?$/g, "")), hardline$c) : // https://infra.spec.whatwg.org/#ascii-whitespace
42764 join$b(line$8, value.split(/[\t\n\f\r ]+/)).parts;
42767 function printEmbeddedAttributeValue(node, originalTextToDoc, options) {
42768 var isKeyMatched = function isKeyMatched(patterns) {
42769 return new RegExp(patterns.join("|")).test(node.fullName);
42772 var getValue = function getValue() {
42773 return unescapeQuoteEntities$1(node.value);
42776 var shouldHug = false;
42778 var __onHtmlBindingRoot = function __onHtmlBindingRoot(root) {
42779 var 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;
42781 if (rootNode && (rootNode.type === "ObjectExpression" || rootNode.type === "ArrayExpression")) {
42786 var printHug = function printHug(doc) {
42787 return group$f(doc);
42790 var printExpand = function printExpand(doc) {
42791 return group$f(concat$g([indent$9(concat$g([softline$7, doc])), softline$7]));
42794 var printMaybeHug = function printMaybeHug(doc) {
42795 return shouldHug ? printHug(doc) : printExpand(doc);
42798 var textToDoc = function textToDoc(code, opts) {
42799 return originalTextToDoc(code, Object.assign({
42800 __onHtmlBindingRoot
42804 if (node.fullName === "srcset" && (node.parent.fullName === "img" || node.parent.fullName === "source")) {
42805 return printExpand(printImgSrcset$1(getValue()));
42808 if (options.parser === "vue") {
42809 if (node.fullName === "v-for") {
42810 return printVueFor$1(getValue(), textToDoc);
42813 if (node.fullName === "slot-scope") {
42814 return printVueSlotScope$1(getValue(), textToDoc);
42817 * @click="jsStatement"
42818 * @click="jsExpression"
42819 * v-on:click="jsStatement"
42820 * v-on:click="jsExpression"
42824 var vueEventBindingPatterns = ["^@", "^v-on:"];
42826 * :class="vueExpression"
42827 * v-bind:id="vueExpression"
42830 var vueExpressionBindingPatterns = ["^:", "^v-bind:"];
42832 * v-if="jsExpression"
42835 var jsExpressionBindingPatterns = ["^v-"];
42837 if (isKeyMatched(vueEventBindingPatterns)) {
42838 var value = getValue();
42839 return printMaybeHug(isVueEventBindingExpression$3(value) ? textToDoc(value, {
42840 parser: "__js_expression"
42841 }) : stripTrailingHardline$2(textToDoc(value, {
42842 parser: "__vue_event_binding"
42846 if (isKeyMatched(vueExpressionBindingPatterns)) {
42847 return printMaybeHug(textToDoc(getValue(), {
42848 parser: "__vue_expression"
42852 if (isKeyMatched(jsExpressionBindingPatterns)) {
42853 return printMaybeHug(textToDoc(getValue(), {
42854 parser: "__js_expression"
42859 if (options.parser === "angular") {
42860 var ngTextToDoc = function ngTextToDoc(code, opts) {
42861 return (// angular does not allow trailing comma
42862 textToDoc(code, Object.assign({
42863 trailingComma: "none"
42868 * *directive="angularDirective"
42872 var ngDirectiveBindingPatterns = ["^\\*"];
42874 * (click)="angularStatement"
42875 * on-click="angularStatement"
42878 var ngStatementBindingPatterns = ["^\\(.+\\)$", "^on-"];
42880 * [target]="angularExpression"
42881 * bind-target="angularExpression"
42882 * [(target)]="angularExpression"
42883 * bindon-target="angularExpression"
42886 var ngExpressionBindingPatterns = ["^\\[.+\\]$", "^bind(on)?-"];
42888 * i18n="longDescription"
42889 * i18n-attr="longDescription"
42892 var ngI18nPatterns = ["^i18n(-.+)?$"];
42894 if (isKeyMatched(ngStatementBindingPatterns)) {
42895 return printMaybeHug(ngTextToDoc(getValue(), {
42896 parser: "__ng_action"
42900 if (isKeyMatched(ngExpressionBindingPatterns)) {
42901 return printMaybeHug(ngTextToDoc(getValue(), {
42902 parser: "__ng_binding"
42906 if (isKeyMatched(ngI18nPatterns)) {
42907 return printExpand(fill$5(getTextValueParts(node, getValue())));
42910 if (isKeyMatched(ngDirectiveBindingPatterns)) {
42911 return printMaybeHug(ngTextToDoc(getValue(), {
42912 parser: "__ng_directive"
42916 var interpolationRegex = /\{\{([\s\S]+?)\}\}/g;
42918 var _value2 = getValue();
42920 if (interpolationRegex.test(_value2)) {
42923 _value2.split(interpolationRegex).forEach(function (part, index) {
42924 if (index % 2 === 0) {
42925 parts.push(concat$g(replaceEndOfLineWith$2(part, literalline$6)));
42928 parts.push(group$f(concat$g(["{{", indent$9(concat$g([line$8, ngTextToDoc(part, {
42929 parser: "__ng_interpolation",
42930 __isInHtmlInterpolation: true // to avoid unexpected `}}`
42932 })])), line$8, "}}"])));
42934 parts.push("{{", concat$g(replaceEndOfLineWith$2(part, literalline$6)), "}}");
42939 return group$f(concat$g(parts));
42946 var printerHtml = {
42947 preprocess: preprocess_1$2,
42948 print: genericPrint$5,
42949 insertPragma: insertPragma$7,
42950 massageAstNode: clean$6,
42954 var CATEGORY_HTML = "HTML"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
42957 htmlWhitespaceSensitivity: {
42959 category: CATEGORY_HTML,
42962 description: "How to handle whitespaces in HTML.",
42965 description: "Respect the default value of CSS display property."
42968 description: "Whitespaces are considered sensitive."
42971 description: "Whitespaces are considered insensitive."
42974 vueIndentScriptAndStyle: {
42976 category: CATEGORY_HTML,
42979 description: "Indent script and style tags in Vue files."
42983 var name$g = "HTML";
42984 var type$e = "markup";
42985 var tmScope$e = "text.html.basic";
42986 var aceMode$e = "html";
42987 var codemirrorMode$b = "htmlmixed";
42988 var codemirrorMimeType$b = "text/html";
42989 var color$3 = "#e34c26";
42993 var extensions$e = [
43002 var languageId$e = 146;
43006 tmScope: tmScope$e,
43007 aceMode: aceMode$e,
43008 codemirrorMode: codemirrorMode$b,
43009 codemirrorMimeType: codemirrorMimeType$b,
43011 aliases: aliases$5,
43012 extensions: extensions$e,
43013 languageId: languageId$e
43016 var HTML$1 = /*#__PURE__*/Object.freeze({
43020 tmScope: tmScope$e,
43021 aceMode: aceMode$e,
43022 codemirrorMode: codemirrorMode$b,
43023 codemirrorMimeType: codemirrorMimeType$b,
43025 aliases: aliases$5,
43026 extensions: extensions$e,
43027 languageId: languageId$e,
43031 var name$h = "Vue";
43032 var type$f = "markup";
43033 var color$4 = "#2c3e50";
43034 var extensions$f = [
43037 var tmScope$f = "text.html.vue";
43038 var aceMode$f = "html";
43039 var languageId$f = 391;
43044 extensions: extensions$f,
43045 tmScope: tmScope$f,
43046 aceMode: aceMode$f,
43047 languageId: languageId$f
43050 var Vue$1 = /*#__PURE__*/Object.freeze({
43055 extensions: extensions$f,
43056 tmScope: tmScope$f,
43057 aceMode: aceMode$f,
43058 languageId: languageId$f,
43062 var require$$0$7 = getCjsExportFromNamespace(HTML$1);
43064 var require$$1$2 = getCjsExportFromNamespace(Vue$1);
43066 var languages$5 = [createLanguage(require$$0$7, function (data) {
43067 return Object.assign(data, {
43070 parsers: ["angular"],
43071 vscodeLanguageIds: ["html"],
43072 extensions: [".component.html"],
43075 }), createLanguage(require$$0$7, function (data) {
43076 return Object.assign(data, {
43079 vscodeLanguageIds: ["html"],
43080 extensions: data.extensions.concat([".mjml" // MJML is considered XML in Linguist but it should be formatted as HTML
43083 }), createLanguage(require$$0$7, function (data) {
43084 return Object.assign(data, {
43085 name: "Lightning Web Components",
43088 vscodeLanguageIds: ["html"],
43092 }), createLanguage(require$$1$2, function (data) {
43093 return Object.assign(data, {
43096 vscodeLanguageIds: ["vue"]
43102 var languageHtml = {
43103 languages: languages$5,
43104 printers: printers$5,
43108 function isPragma(text) {
43109 return /^\s*@(prettier|format)\s*$/.test(text);
43112 function hasPragma$4(text) {
43113 return /^\s*#[^\n\S]*@(prettier|format)\s*?(\n|$)/.test(text);
43116 function insertPragma$8(text) {
43117 return `# @format\n\n${text}`;
43122 hasPragma: hasPragma$4,
43123 insertPragma: insertPragma$8
43126 var getLast$4 = util.getLast;
43128 function getAncestorCount(path, filter) {
43130 var pathStackLength = path.stack.length - 1;
43132 for (var i = 0; i < pathStackLength; i++) {
43133 var value = path.stack[i];
43135 if (isNode$1(value) && filter(value)) {
43143 * @param {any} value
43144 * @param {string[]=} types
43148 function isNode$1(value, types) {
43149 return value && typeof value.type === "string" && (!types || types.indexOf(value.type) !== -1);
43152 function mapNode(node, callback, parent) {
43153 return callback("children" in node ? Object.assign({}, node, {
43154 children: node.children.map(function (childNode) {
43155 return mapNode(childNode, callback, node);
43157 }) : node, parent);
43160 function defineShortcut(x, key, getter) {
43161 Object.defineProperty(x, key, {
43167 function isNextLineEmpty$5(node, text) {
43168 var newlineCount = 0;
43169 var textLength = text.length;
43171 for (var i = node.position.end.offset - 1; i < textLength; i++) {
43172 var char = text[i];
43174 if (char === "\n") {
43178 if (newlineCount === 1 && /\S/.test(char)) {
43182 if (newlineCount === 2) {
43190 function isLastDescendantNode(path) {
43191 var node = path.getValue();
43193 switch (node.type) {
43200 var pathStackLength = path.stack.length;
43202 for (var i = 1; i < pathStackLength; i++) {
43203 var item = path.stack[i];
43204 var parentItem = path.stack[i - 1];
43206 if (Array.isArray(parentItem) && typeof item === "number" && item !== parentItem.length - 1) {
43214 function getLastDescendantNode$1(node) {
43215 return "children" in node && node.children.length !== 0 ? getLastDescendantNode$1(getLast$4(node.children)) : node;
43218 function isPrettierIgnore$2(comment) {
43219 return comment.value.trim() === "prettier-ignore";
43222 function hasPrettierIgnore$5(path) {
43223 var node = path.getValue();
43225 if (node.type === "documentBody") {
43226 var document = path.getParentNode();
43227 return hasEndComments(document.head) && isPrettierIgnore$2(getLast$4(document.head.endComments));
43230 return hasLeadingComments(node) && isPrettierIgnore$2(getLast$4(node.leadingComments));
43233 function isEmptyNode(node) {
43234 return (!node.children || node.children.length === 0) && !hasComments(node);
43237 function hasComments(node) {
43238 return hasLeadingComments(node) || hasMiddleComments(node) || hasIndicatorComment(node) || hasTrailingComment$2(node) || hasEndComments(node);
43241 function hasLeadingComments(node) {
43242 return node && node.leadingComments && node.leadingComments.length !== 0;
43245 function hasMiddleComments(node) {
43246 return node && node.middleComments && node.middleComments.length !== 0;
43249 function hasIndicatorComment(node) {
43250 return node && node.indicatorComment;
43253 function hasTrailingComment$2(node) {
43254 return node && node.trailingComment;
43257 function hasEndComments(node) {
43258 return node && node.endComments && node.endComments.length !== 0;
43261 * " a b c d e f " -> [" a b", "c d", "e f "]
43265 function splitWithSingleSpace(text) {
43267 var lastPart = undefined;
43268 var _iteratorNormalCompletion = true;
43269 var _didIteratorError = false;
43270 var _iteratorError = undefined;
43273 for (var _iterator = text.split(/( +)/g)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
43274 var part = _step.value;
43276 if (part !== " ") {
43277 if (lastPart === " ") {
43280 parts.push((parts.pop() || "") + part);
43282 } else if (lastPart === undefined) {
43289 _didIteratorError = true;
43290 _iteratorError = err;
43293 if (!_iteratorNormalCompletion && _iterator.return != null) {
43294 _iterator.return();
43297 if (_didIteratorError) {
43298 throw _iteratorError;
43303 if (lastPart === " ") {
43304 parts.push((parts.pop() || "") + " ");
43307 if (parts[0] === "") {
43309 parts.unshift(" " + (parts.shift() || ""));
43315 function getFlowScalarLineContents(nodeType, content, options) {
43316 var rawLineContents = content.split("\n").map(function (lineContent, index, lineContents) {
43317 return index === 0 && index === lineContents.length - 1 ? lineContent : index !== 0 && index !== lineContents.length - 1 ? lineContent.trim() : index === 0 ? lineContent.trimRight() : lineContent.trimLeft();
43320 if (options.proseWrap === "preserve") {
43321 return rawLineContents.map(function (lineContent) {
43322 return lineContent.length === 0 ? [] : [lineContent];
43326 return rawLineContents.map(function (lineContent) {
43327 return lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent);
43328 }).reduce(function (reduced, lineContentWords, index) {
43329 return index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !( // trailing backslash in quoteDouble should be preserved
43330 nodeType === "quoteDouble" && getLast$4(getLast$4(reduced)).endsWith("\\")) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]);
43331 }, []).map(function (lineContentWords) {
43332 return options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords;
43336 function getBlockValueLineContents(node, _ref) {
43337 var parentIndent = _ref.parentIndent,
43338 isLastDescendant = _ref.isLastDescendant,
43339 options = _ref.options;
43340 var content = node.position.start.line === node.position.end.line ? "" : options.originalText.slice(node.position.start.offset, node.position.end.offset) // exclude open line `>` or `|`
43341 .match(/^[^\n]*?\n([\s\S]*)$/)[1];
43342 var leadingSpaceCount = node.indent === null ? function (match) {
43343 return match ? match[1].length : Infinity;
43344 }(content.match(/^( *)\S/m)) : node.indent - 1 + parentIndent;
43345 var rawLineContents = content.split("\n").map(function (lineContent) {
43346 return lineContent.slice(leadingSpaceCount);
43349 if (options.proseWrap === "preserve" || node.type === "blockLiteral") {
43350 return removeUnnecessaryTrailingNewlines(rawLineContents.map(function (lineContent) {
43351 return lineContent.length === 0 ? [] : [lineContent];
43355 return removeUnnecessaryTrailingNewlines(rawLineContents.map(function (lineContent) {
43356 return lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent);
43357 }).reduce(function (reduced, lineContentWords, index) {
43358 return index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !/^\s/.test(lineContentWords[0]) && !/^\s|\s$/.test(getLast$4(reduced)) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]);
43359 }, []).map(function (lineContentWords) {
43360 return lineContentWords.reduce(function (reduced, word) {
43361 return (// disallow trailing spaces
43362 reduced.length !== 0 && /\s$/.test(getLast$4(reduced)) ? reduced.concat(reduced.pop() + " " + word) : reduced.concat(word)
43365 }).map(function (lineContentWords) {
43366 return options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords;
43369 function removeUnnecessaryTrailingNewlines(lineContents) {
43370 if (node.chomping === "keep") {
43371 return getLast$4(lineContents).length === 0 ? lineContents.slice(0, -1) : lineContents;
43374 var trailingNewlineCount = 0;
43376 for (var i = lineContents.length - 1; i >= 0; i--) {
43377 if (lineContents[i].length === 0) {
43378 trailingNewlineCount++;
43384 return trailingNewlineCount === 0 ? lineContents : trailingNewlineCount >= 2 && !isLastDescendant ? // next empty line
43385 lineContents.slice(0, -(trailingNewlineCount - 1)) : lineContents.slice(0, -trailingNewlineCount);
43390 getLast: getLast$4,
43396 isNextLineEmpty: isNextLineEmpty$5,
43397 isLastDescendantNode,
43398 getBlockValueLineContents,
43399 getFlowScalarLineContents,
43400 getLastDescendantNode: getLastDescendantNode$1,
43401 hasPrettierIgnore: hasPrettierIgnore$5,
43402 hasLeadingComments,
43404 hasIndicatorComment,
43405 hasTrailingComment: hasTrailingComment$2,
43409 var insertPragma$9 = pragma$5.insertPragma,
43410 isPragma$1 = pragma$5.isPragma;
43411 var getAncestorCount$1 = utils$6.getAncestorCount,
43412 getBlockValueLineContents$1 = utils$6.getBlockValueLineContents,
43413 getFlowScalarLineContents$1 = utils$6.getFlowScalarLineContents,
43414 getLast$5 = utils$6.getLast,
43415 getLastDescendantNode$2 = utils$6.getLastDescendantNode,
43416 hasLeadingComments$1 = utils$6.hasLeadingComments,
43417 hasMiddleComments$1 = utils$6.hasMiddleComments,
43418 hasIndicatorComment$1 = utils$6.hasIndicatorComment,
43419 hasTrailingComment$3 = utils$6.hasTrailingComment,
43420 hasEndComments$1 = utils$6.hasEndComments,
43421 hasPrettierIgnore$6 = utils$6.hasPrettierIgnore,
43422 isLastDescendantNode$1 = utils$6.isLastDescendantNode,
43423 isNextLineEmpty$6 = utils$6.isNextLineEmpty,
43424 isNode$2 = utils$6.isNode,
43425 isEmptyNode$1 = utils$6.isEmptyNode,
43426 defineShortcut$1 = utils$6.defineShortcut,
43427 mapNode$1 = utils$6.mapNode;
43428 var docBuilders$2 = doc.builders;
43429 var conditionalGroup$2 = docBuilders$2.conditionalGroup,
43430 breakParent$5 = docBuilders$2.breakParent,
43431 concat$h = docBuilders$2.concat,
43432 dedent$3 = docBuilders$2.dedent,
43433 dedentToRoot$3 = docBuilders$2.dedentToRoot,
43434 fill$6 = docBuilders$2.fill,
43435 group$g = docBuilders$2.group,
43436 hardline$d = docBuilders$2.hardline,
43437 ifBreak$8 = docBuilders$2.ifBreak,
43438 join$c = docBuilders$2.join,
43439 line$9 = docBuilders$2.line,
43440 lineSuffix$2 = docBuilders$2.lineSuffix,
43441 literalline$7 = docBuilders$2.literalline,
43442 markAsRoot$5 = docBuilders$2.markAsRoot,
43443 softline$8 = docBuilders$2.softline;
43444 var replaceEndOfLineWith$3 = util.replaceEndOfLineWith;
43446 function preprocess$3(ast) {
43447 return mapNode$1(ast, defineShortcuts);
43450 function defineShortcuts(node) {
43451 switch (node.type) {
43453 defineShortcut$1(node, "head", function () {
43454 return node.children[0];
43456 defineShortcut$1(node, "body", function () {
43457 return node.children[1];
43461 case "documentBody":
43462 case "sequenceItem":
43463 case "flowSequenceItem":
43465 case "mappingValue":
43466 defineShortcut$1(node, "content", function () {
43467 return node.children[0];
43471 case "mappingItem":
43472 case "flowMappingItem":
43473 defineShortcut$1(node, "key", function () {
43474 return node.children[0];
43476 defineShortcut$1(node, "value", function () {
43477 return node.children[1];
43485 function genericPrint$6(path, options, print) {
43486 var node = path.getValue();
43487 var parentNode = path.getParentNode();
43488 var tag = !node.tag ? "" : path.call(print, "tag");
43489 var anchor = !node.anchor ? "" : path.call(print, "anchor");
43490 var nextEmptyLine = isNode$2(node, ["mapping", "sequence", "comment", "directive", "mappingItem", "sequenceItem"]) && !isLastDescendantNode$1(path) ? printNextEmptyLine(path, options.originalText) : "";
43491 return concat$h([node.type !== "mappingValue" && hasLeadingComments$1(node) ? concat$h([join$c(hardline$d, path.map(print, "leadingComments")), hardline$d]) : "", tag, tag && anchor ? " " : "", anchor, tag || anchor ? isNode$2(node, ["sequence", "mapping"]) && !hasMiddleComments$1(node) ? hardline$d : " " : "", hasMiddleComments$1(node) ? concat$h([node.middleComments.length === 1 ? "" : hardline$d, join$c(hardline$d, path.map(print, "middleComments")), hardline$d]) : "", hasPrettierIgnore$6(path) ? concat$h(replaceEndOfLineWith$3(options.originalText.slice(node.position.start.offset, node.position.end.offset), literalline$7)) : group$g(_print(node, parentNode, path, options, print)), hasTrailingComment$3(node) && !isNode$2(node, ["document", "documentHead"]) ? lineSuffix$2(concat$h([node.type === "mappingValue" && !node.content ? "" : " ", parentNode.type === "mappingKey" && path.getParentNode(2).type === "mapping" && isInlineNode$1(node) ? "" : breakParent$5, path.call(print, "trailingComment")])) : "", nextEmptyLine, hasEndComments$1(node) && !isNode$2(node, ["documentHead", "documentBody"]) ? align$3(node.type === "sequenceItem" ? 2 : 0, concat$h([hardline$d, join$c(hardline$d, path.map(print, "endComments"))])) : ""]);
43494 function _print(node, parentNode, path, options, print) {
43495 switch (node.type) {
43497 return concat$h([join$c(hardline$d, path.map(function (childPath, index) {
43498 var document = node.children[index];
43499 var nextDocument = node.children[index + 1];
43500 return concat$h([print(childPath), shouldPrintDocumentEndMarker(document, nextDocument) ? concat$h([hardline$d, "...", hasTrailingComment$3(document) ? concat$h([" ", path.call(print, "trailingComment")]) : ""]) : !nextDocument || hasTrailingComment$3(nextDocument.head) ? "" : concat$h([hardline$d, "---"])]);
43501 }, "children")), node.children.length === 0 || function (lastDescendantNode) {
43502 return isNode$2(lastDescendantNode, ["blockLiteral", "blockFolded"]) && lastDescendantNode.chomping === "keep";
43503 }(getLastDescendantNode$2(node)) ? "" : hardline$d]);
43507 var nextDocument = parentNode.children[path.getName() + 1];
43508 return join$c(hardline$d, [shouldPrintDocumentHeadEndMarker(node, nextDocument, parentNode, options) === "head" ? join$c(hardline$d, [node.head.children.length === 0 && node.head.endComments.length === 0 ? "" : path.call(print, "head"), concat$h(["---", hasTrailingComment$3(node.head) ? concat$h([" ", path.call(print, "head", "trailingComment")]) : ""])].filter(Boolean)) : "", shouldPrintDocumentBody(node) ? path.call(print, "body") : ""].filter(Boolean));
43511 case "documentHead":
43512 return join$c(hardline$d, [].concat(path.map(print, "children"), path.map(print, "endComments")));
43514 case "documentBody":
43516 var children = join$c(hardline$d, path.map(print, "children")).parts;
43517 var endComments = join$c(hardline$d, path.map(print, "endComments")).parts;
43518 var separator = children.length === 0 || endComments.length === 0 ? "" : function (lastDescendantNode) {
43519 return isNode$2(lastDescendantNode, ["blockFolded", "blockLiteral"]) ? lastDescendantNode.chomping === "keep" ? // there's already a newline printed at the end of blockValue (chomping=keep, lastDescendant=true)
43520 "" : // an extra newline for better readability
43521 concat$h([hardline$d, hardline$d]) : hardline$d;
43522 }(getLastDescendantNode$2(node));
43523 return concat$h([].concat(children, separator, endComments));
43527 return concat$h(["%", join$c(" ", [node.name].concat(node.parameters))]);
43530 return concat$h(["#", node.value]);
43533 return concat$h(["*", node.value]);
43536 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
43539 return concat$h(["&", node.value]);
43542 return printFlowScalarContent(node.type, options.originalText.slice(node.position.start.offset, node.position.end.offset), options);
43544 case "quoteDouble":
43545 case "quoteSingle":
43547 var singleQuote = "'";
43548 var doubleQuote = '"';
43549 var raw = options.originalText.slice(node.position.start.offset + 1, node.position.end.offset - 1);
43551 if (node.type === "quoteSingle" && raw.includes("\\") || node.type === "quoteDouble" && /\\[^"]/.test(raw)) {
43552 // only quoteDouble can use escape chars
43553 // and quoteSingle do not need to escape backslashes
43554 var originalQuote = node.type === "quoteDouble" ? doubleQuote : singleQuote;
43555 return concat$h([originalQuote, printFlowScalarContent(node.type, raw, options), originalQuote]);
43556 } else if (raw.includes(doubleQuote)) {
43557 return concat$h([singleQuote, printFlowScalarContent(node.type, node.type === "quoteDouble" ? raw // double quote needs to be escaped by backslash in quoteDouble
43558 .replace(/\\"/g, doubleQuote).replace(/'/g, singleQuote.repeat(2)) : raw, options), singleQuote]);
43561 if (raw.includes(singleQuote)) {
43562 return concat$h([doubleQuote, printFlowScalarContent(node.type, node.type === "quoteSingle" ? // single quote needs to be escaped by 2 single quotes in quoteSingle
43563 raw.replace(/''/g, singleQuote) : raw, options), doubleQuote]);
43566 var quote = options.singleQuote ? singleQuote : doubleQuote;
43567 return concat$h([quote, printFlowScalarContent(node.type, raw, options), quote]);
43570 case "blockFolded":
43571 case "blockLiteral":
43573 var parentIndent = getAncestorCount$1(path, function (ancestorNode) {
43574 return isNode$2(ancestorNode, ["sequence", "mapping"]);
43576 var isLastDescendant = isLastDescendantNode$1(path);
43577 return concat$h([node.type === "blockFolded" ? ">" : "|", node.indent === null ? "" : node.indent.toString(), node.chomping === "clip" ? "" : node.chomping === "keep" ? "+" : "-", hasIndicatorComment$1(node) ? concat$h([" ", path.call(print, "indicatorComment")]) : "", (node.indent === null ? dedent$3 : dedentToRoot$3)(align$3(node.indent === null ? options.tabWidth : node.indent - 1 + parentIndent, concat$h(getBlockValueLineContents$1(node, {
43581 }).reduce(function (reduced, lineWords, index, lineContents) {
43582 return reduced.concat(index === 0 ? hardline$d : "", fill$6(join$c(line$9, lineWords).parts), index !== lineContents.length - 1 ? lineWords.length === 0 ? hardline$d : markAsRoot$5(literalline$7) : node.chomping === "keep" && isLastDescendant ? lineWords.length === 0 ? dedentToRoot$3(hardline$d) : dedentToRoot$3(literalline$7) : "");
43587 return join$c(hardline$d, path.map(print, "children"));
43589 case "sequenceItem":
43590 return concat$h(["- ", align$3(2, !node.content ? "" : path.call(print, "content"))]);
43593 return !node.content ? "" : path.call(print, "content");
43595 case "mappingValue":
43596 return !node.content ? "" : path.call(print, "content");
43599 return join$c(hardline$d, path.map(print, "children"));
43601 case "mappingItem":
43602 case "flowMappingItem":
43604 var isEmptyMappingKey = isEmptyNode$1(node.key);
43605 var isEmptyMappingValue = isEmptyNode$1(node.value);
43607 if (isEmptyMappingKey && isEmptyMappingValue) {
43608 return concat$h([": "]);
43611 var key = path.call(print, "key");
43612 var value = path.call(print, "value");
43614 if (isEmptyMappingValue) {
43615 return node.type === "flowMappingItem" && parentNode.type === "flowMapping" ? key : node.type === "mappingItem" && isAbsolutelyPrintedAsSingleLineNode(node.key.content, options) && !hasTrailingComment$3(node.key.content) && (!parentNode.tag || parentNode.tag.value !== "tag:yaml.org,2002:set") ? concat$h([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ":"]) : concat$h(["? ", align$3(2, key)]);
43618 if (isEmptyMappingKey) {
43619 return concat$h([": ", align$3(2, value)]);
43622 var groupId = Symbol("mappingKey");
43623 var forceExplicitKey = hasLeadingComments$1(node.value) || !isInlineNode$1(node.key.content);
43624 return forceExplicitKey ? concat$h(["? ", align$3(2, key), hardline$d, join$c("", path.map(print, "value", "leadingComments").map(function (comment) {
43625 return concat$h([comment, hardline$d]);
43626 })), ": ", align$3(2, value)]) : // force singleline
43627 isSingleLineNode(node.key.content) && !hasLeadingComments$1(node.key.content) && !hasMiddleComments$1(node.key.content) && !hasTrailingComment$3(node.key.content) && !hasEndComments$1(node.key) && !hasLeadingComments$1(node.value.content) && !hasMiddleComments$1(node.value.content) && !hasEndComments$1(node.value) && isAbsolutelyPrintedAsSingleLineNode(node.value.content, options) ? concat$h([key, needsSpaceInFrontOfMappingValue(node) ? " " : "", ": ", value]) : conditionalGroup$2([concat$h([group$g(concat$h([ifBreak$8("? "), group$g(align$3(2, key), {
43629 })])), ifBreak$8(concat$h([hardline$d, ": ", align$3(2, value)]), indent(concat$h([needsSpaceInFrontOfMappingValue(node) ? " " : "", ":", hasLeadingComments$1(node.value.content) || hasEndComments$1(node.value) && node.value.content && !isNode$2(node.value.content, ["mapping", "sequence"]) || parentNode.type === "mapping" && hasTrailingComment$3(node.key.content) && isInlineNode$1(node.value.content) || isNode$2(node.value.content, ["mapping", "sequence"]) && node.value.content.tag === null && node.value.content.anchor === null ? hardline$d : !node.value.content ? "" : line$9, value])), {
43634 case "flowMapping":
43635 case "flowSequence":
43637 var openMarker = node.type === "flowMapping" ? "{" : "[";
43638 var closeMarker = node.type === "flowMapping" ? "}" : "]";
43639 var bracketSpacing = node.type === "flowMapping" && node.children.length !== 0 && options.bracketSpacing ? line$9 : softline$8;
43641 var isLastItemEmptyMappingItem = node.children.length !== 0 && function (lastItem) {
43642 return lastItem.type === "flowMappingItem" && isEmptyNode$1(lastItem.key) && isEmptyNode$1(lastItem.value);
43643 }(getLast$5(node.children));
43645 return concat$h([openMarker, indent(concat$h([bracketSpacing, concat$h(path.map(function (childPath, index) {
43646 return concat$h([print(childPath), index === node.children.length - 1 ? "" : concat$h([",", line$9, node.children[index].position.start.line !== node.children[index + 1].position.start.line ? printNextEmptyLine(childPath, options.originalText) : ""])]);
43647 }, "children")), ifBreak$8(",", "")])), isLastItemEmptyMappingItem ? "" : bracketSpacing, closeMarker]);
43650 case "flowSequenceItem":
43651 return path.call(print, "content");
43652 // istanbul ignore next
43655 throw new Error(`Unexpected node type ${node.type}`);
43658 function indent(doc) {
43659 return docBuilders$2.align(" ".repeat(options.tabWidth), doc);
43663 function align$3(n, doc) {
43664 return typeof n === "number" && n > 0 ? docBuilders$2.align(" ".repeat(n), doc) : docBuilders$2.align(n, doc);
43667 function isInlineNode$1(node) {
43672 switch (node.type) {
43674 case "quoteDouble":
43675 case "quoteSingle":
43677 case "flowMapping":
43678 case "flowSequence":
43686 function isSingleLineNode(node) {
43691 switch (node.type) {
43693 case "quoteDouble":
43694 case "quoteSingle":
43695 return node.position.start.line === node.position.end.line;
43705 function shouldPrintDocumentBody(document) {
43706 return document.body.children.length !== 0 || hasEndComments$1(document.body);
43709 function shouldPrintDocumentEndMarker(document, nextDocument) {
43712 *... # trailingComment
43714 hasTrailingComment$3(document) || nextDocument && (
43720 nextDocument.head.children.length !== 0 ||
43726 hasEndComments$1(nextDocument.head))
43730 function shouldPrintDocumentHeadEndMarker(document, nextDocument, root, options) {
43734 * preserve the first document head end marker
43736 root.children[0] === document && /---(\s|$)/.test(options.originalText.slice(options.locStart(document), options.locStart(document) + 4)) ||
43741 document.head.children.length !== 0 ||
43746 hasEndComments$1(document.head) ||
43748 * --- # trailing comment
43750 hasTrailingComment$3(document.head)) {
43754 if (shouldPrintDocumentEndMarker(document, nextDocument)) {
43758 return nextDocument ? "root" : false;
43761 function isAbsolutelyPrintedAsSingleLineNode(node, options) {
43766 switch (node.type) {
43768 case "quoteSingle":
43769 case "quoteDouble":
43779 if (options.proseWrap === "preserve") {
43780 return node.position.start.line === node.position.end.line;
43783 if ( // backslash-newline
43784 /\\$/m.test(options.originalText.slice(node.position.start.offset, node.position.end.offset))) {
43788 switch (options.proseWrap) {
43790 return node.value.indexOf("\n") === -1;
43793 return !/[\n ]/.test(node.value);
43794 // istanbul ignore next
43801 function needsSpaceInFrontOfMappingValue(node) {
43802 return node.key.content && node.key.content.type === "alias";
43805 function printNextEmptyLine(path, originalText) {
43806 var node = path.getValue();
43807 var root = path.stack[0];
43808 root.isNextEmptyLinePrintedChecklist = root.isNextEmptyLinePrintedChecklist || [];
43810 if (!root.isNextEmptyLinePrintedChecklist[node.position.end.line]) {
43811 if (isNextLineEmpty$6(node, originalText)) {
43812 root.isNextEmptyLinePrintedChecklist[node.position.end.line] = true;
43820 function printFlowScalarContent(nodeType, content, options) {
43821 var lineContents = getFlowScalarLineContents$1(nodeType, content, options);
43822 return join$c(hardline$d, lineContents.map(function (lineContentWords) {
43823 return fill$6(join$c(line$9, lineContentWords).parts);
43827 function clean$7(node, newNode
43830 if (isNode$2(newNode)) {
43831 delete newNode.position;
43833 switch (newNode.type) {
43836 if (isPragma$1(newNode.value)) {
43842 case "quoteDouble":
43843 case "quoteSingle":
43844 newNode.type = "quote";
43850 var printerYaml = {
43851 preprocess: preprocess$3,
43852 print: genericPrint$6,
43853 massageAstNode: clean$7,
43854 insertPragma: insertPragma$9
43858 bracketSpacing: commonOptions.bracketSpacing,
43859 singleQuote: commonOptions.singleQuote,
43860 proseWrap: commonOptions.proseWrap
43863 var name$i = "YAML";
43864 var type$g = "data";
43865 var tmScope$g = "source.yaml";
43869 var extensions$g = [
43877 ".yaml-tmlanguage",
43880 var filenames$4 = [
43886 var aceMode$g = "yaml";
43887 var codemirrorMode$c = "yaml";
43888 var codemirrorMimeType$c = "text/x-yaml";
43889 var languageId$g = 407;
43893 tmScope: tmScope$g,
43894 aliases: aliases$6,
43895 extensions: extensions$g,
43896 filenames: filenames$4,
43897 aceMode: aceMode$g,
43898 codemirrorMode: codemirrorMode$c,
43899 codemirrorMimeType: codemirrorMimeType$c,
43900 languageId: languageId$g
43903 var YAML$1 = /*#__PURE__*/Object.freeze({
43907 tmScope: tmScope$g,
43908 aliases: aliases$6,
43909 extensions: extensions$g,
43910 filenames: filenames$4,
43911 aceMode: aceMode$g,
43912 codemirrorMode: codemirrorMode$c,
43913 codemirrorMimeType: codemirrorMimeType$c,
43914 languageId: languageId$g,
43918 var require$$0$8 = getCjsExportFromNamespace(YAML$1);
43920 var languages$6 = [createLanguage(require$$0$8, function (data) {
43921 return Object.assign(data, {
43924 vscodeLanguageIds: ["yaml"]
43927 var languageYaml = {
43928 languages: languages$6,
43935 // plugin will look for `eval("require")()` and transform to `require()` in the bundle,
43936 // and rewrite the paths to require from the top-level.
43937 // We need to list the parsers and getters so we can load them only when necessary.
43940 var internalPlugins = [// JS
43945 return require("./parser-babylon").parsers.babel;
43948 get "babel-flow"() {
43949 return require("./parser-babylon").parsers["babel-flow"];
43953 return require("./parser-babylon").parsers.babel;
43957 return require("./parser-babylon").parsers.json;
43961 return require("./parser-babylon").parsers.json5;
43964 get "json-stringify"() {
43965 return require("./parser-babylon").parsers["json-stringify"];
43968 get __js_expression() {
43969 return require("./parser-babylon").parsers.__js_expression;
43972 get __vue_expression() {
43973 return require("./parser-babylon").parsers.__vue_expression;
43976 get __vue_event_binding() {
43977 return require("./parser-babylon").parsers.__vue_event_binding;
43982 return require("./parser-flow").parsers.flow;
43987 return require("./parser-typescript").parsers.typescript;
43991 * TODO: Remove this old alias in a major version
43993 get "typescript-eslint"() {
43994 return require("./parser-typescript").parsers.typescript;
43997 // JS - Angular Action
43998 get __ng_action() {
43999 return require("./parser-angular").parsers.__ng_action;
44002 // JS - Angular Binding
44003 get __ng_binding() {
44004 return require("./parser-angular").parsers.__ng_binding;
44007 // JS - Angular Interpolation
44008 get __ng_interpolation() {
44009 return require("./parser-angular").parsers.__ng_interpolation;
44012 // JS - Angular Directive
44013 get __ng_directive() {
44014 return require("./parser-angular").parsers.__ng_directive;
44021 // TODO: switch these to just `postcss` and use `language` instead.
44023 return require("./parser-postcss").parsers.css;
44027 return require("./parser-postcss").parsers.css;
44031 return require("./parser-postcss").parsers.css;
44036 languageHandlebars, {
44039 return require("./parser-glimmer").parsers.glimmer;
44047 return require("./parser-graphql").parsers.graphql;
44052 languageMarkdown, {
44055 return require("./parser-markdown").parsers.remark;
44058 // TODO: Delete this in 2.0
44060 return require("./parser-markdown").parsers.remark;
44064 return require("./parser-markdown").parsers.mdx;
44072 return require("./parser-html").parsers.html;
44077 return require("./parser-html").parsers.vue;
44082 return require("./parser-html").parsers.angular;
44085 // Lightning Web Components
44087 return require("./parser-html").parsers.lwc;
44095 return require("./parser-yaml").parsers.yaml;
44101 var partition = function partition(array, fn) {
44104 array.forEach(function (item) {
44114 function loadPlugins(plugins, pluginSearchDirs) {
44119 if (!pluginSearchDirs) {
44120 pluginSearchDirs = [];
44121 } // unless pluginSearchDirs are provided, auto-load plugins from node_modules that are parent to Prettier
44124 if (!pluginSearchDirs.length) {
44125 var autoLoadDir = thirdParty.findParentDir(__dirname, "node_modules");
44128 pluginSearchDirs = [autoLoadDir];
44132 var _partition = partition(plugins, function (plugin) {
44133 return typeof plugin === "string";
44135 _partition2 = _slicedToArray(_partition, 2),
44136 externalPluginNames = _partition2[0],
44137 externalPluginInstances = _partition2[1];
44139 var externalManualLoadPluginInfos = externalPluginNames.map(function (pluginName) {
44144 requirePath = resolve.sync(path$2.resolve(process.cwd(), pluginName));
44146 // try node modules
44147 requirePath = resolve.sync(pluginName, {
44148 basedir: process.cwd()
44157 var externalAutoLoadPluginInfos = pluginSearchDirs.map(function (pluginSearchDir) {
44158 var resolvedPluginSearchDir = path$2.resolve(process.cwd(), pluginSearchDir);
44159 var nodeModulesDir = path$2.resolve(resolvedPluginSearchDir, "node_modules"); // In some fringe cases (ex: files "mounted" as virtual directories), the
44160 // isDirectory(resolvedPluginSearchDir) check might be false even though
44161 // the node_modules actually exists.
44163 if (!isDirectory(nodeModulesDir) && !isDirectory(resolvedPluginSearchDir)) {
44164 throw new Error(`${pluginSearchDir} does not exist or is not a directory`);
44167 return findPluginsInNodeModules(nodeModulesDir).map(function (pluginName) {
44170 requirePath: resolve.sync(pluginName, {
44171 basedir: resolvedPluginSearchDir
44175 }).reduce(function (a, b) {
44176 return a.concat(b);
44178 var externalPlugins = lodash_uniqby(externalManualLoadPluginInfos.concat(externalAutoLoadPluginInfos), "requirePath").map(function (externalPluginInfo) {
44179 return Object.assign({
44180 name: externalPluginInfo.name
44181 }, require(externalPluginInfo.requirePath));
44182 }).concat(externalPluginInstances);
44183 return internalPlugins.concat(externalPlugins);
44186 function findPluginsInNodeModules(nodeModulesDir) {
44187 var pluginPackageJsonPaths = globby.sync(["prettier-plugin-*/package.json", "@*/prettier-plugin-*/package.json", "@prettier/plugin-*/package.json"], {
44188 cwd: nodeModulesDir
44190 return pluginPackageJsonPaths.map(path$2.dirname);
44193 function isDirectory(dir) {
44195 return fs$1.statSync(dir).isDirectory();
44201 var loadPlugins_1 = loadPlugins;
44203 var version$3 = require$$0.version;
44204 var getSupportInfo$2 = support.getSupportInfo; // Luckily `opts` is always the 2nd argument
44206 function _withPlugins(fn) {
44207 return function () {
44208 var args = Array.from(arguments);
44209 var opts = args[1] || {};
44210 args[1] = Object.assign({}, opts, {
44211 plugins: loadPlugins_1(opts.plugins, opts.pluginSearchDirs)
44213 return fn.apply(null, args);
44217 function withPlugins(fn) {
44218 var resultingFn = _withPlugins(fn);
44221 resultingFn.sync = _withPlugins(fn.sync);
44224 return resultingFn;
44227 var formatWithCursor = withPlugins(core.formatWithCursor);
44231 format(text, opts) {
44232 return formatWithCursor(text, opts).formatted;
44235 check: function check(text, opts) {
44236 var formatted = formatWithCursor(text, opts).formatted;
44237 return formatted === text;
44240 resolveConfig: resolveConfig_1.resolveConfig,
44241 resolveConfigFile: resolveConfig_1.resolveConfigFile,
44242 clearConfigCache: resolveConfig_1.clearCache,
44243 getFileInfo: withPlugins(getFileInfo_1),
44244 getSupportInfo: withPlugins(getSupportInfo$2),
44245 version: version$3,
44248 /* istanbul ignore next */
44250 parse: withPlugins(core.parse),
44251 formatAST: withPlugins(core.formatAST),
44252 formatDoc: withPlugins(core.formatDoc),
44253 printToDoc: withPlugins(core.printToDoc),
44254 printDocToString: withPlugins(core.printDocToString)
44258 var prettier = src$1;
44261 // The index of the current character
44263 // The current character
44275 error = function error(m) {
44276 // Call error when something is wrong.
44278 name: 'SyntaxError',
44284 next = function next(c) {
44285 // If a c parameter is provided, verify that it matches the current character.
44286 if (c && c !== ch) {
44287 error("Expected '" + c + "' instead of '" + ch + "'");
44288 } // Get the next character. When there are no more characters,
44289 // return the empty string.
44292 ch = text.charAt(at);
44296 number$1 = function number() {
44297 // Parse a number value.
44306 while (ch >= '0' && ch <= '9') {
44314 while (next() && ch >= '0' && ch <= '9') {
44319 if (ch === 'e' || ch === 'E') {
44323 if (ch === '-' || ch === '+') {
44328 while (ch >= '0' && ch <= '9') {
44336 if (!isFinite(number)) {
44337 error("Bad number");
44342 string$1 = function string() {
44343 // Parse a string value.
44347 uffff; // When parsing for string values, we must look for " and \ characters.
44354 } else if (ch === '\\') {
44360 for (i = 0; i < 4; i += 1) {
44361 hex = parseInt(next(), 16);
44363 if (!isFinite(hex)) {
44367 uffff = uffff * 16 + hex;
44370 string += String.fromCharCode(uffff);
44371 } else if (typeof escapee[ch] === 'string') {
44372 string += escapee[ch];
44382 error("Bad string");
44384 white = function white() {
44385 // Skip whitespace.
44386 while (ch && ch <= ' ') {
44390 word = function word() {
44391 // true, false, or null.
44416 error("Unexpected '" + ch + "'");
44419 // Place holder for the value function.
44420 array$2 = function array() {
44421 // Parse an array value.
44430 return array; // empty array
44434 array.push(value());
44447 error("Bad array");
44449 object$1 = function object() {
44450 // Parse an object value.
44460 return object; // empty object
44468 if (Object.hasOwnProperty.call(object, key)) {
44469 error('Duplicate key "' + key + '"');
44472 object[key] = value();
44485 error("Bad object");
44488 value = function value() {
44489 // Parse a JSON value. It could be an object, an array, a string, a number,
44507 return ch >= '0' && ch <= '9' ? number$1() : word();
44509 }; // Return the json_parse function. It will have access to all of the above
44510 // functions and variables.
44513 var parse$4 = function parse(source, reviver) {
44522 error("Syntax error");
44523 } // If there is a reviver function, we recursively walk the new structure,
44524 // passing each name/value pair to the reviver function for possible
44525 // transformation, starting with a temporary root object that holds the result
44526 // in an empty key. If there is not a reviver function, we simply return the
44530 return typeof reviver === 'function' ? function walk(holder, key) {
44533 value = holder[key];
44535 if (value && typeof value === 'object') {
44537 if (Object.prototype.hasOwnProperty.call(value, k)) {
44538 v = walk(value, k);
44540 if (v !== undefined) {
44549 return reviver.call(holder, key, value);
44555 var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
44559 // table of character substitutions
44570 function quote(string) {
44571 // If the string contains no control characters, no quote characters, and no
44572 // backslash characters, then we can safely slap some quotes around it.
44573 // Otherwise we must also replace the offending characters with safe escape
44575 escapable.lastIndex = 0;
44576 return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
44578 return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
44579 }) + '"' : '"' + string + '"';
44582 function str(key, holder) {
44583 // Produce a string from holder[key].
44585 // The loop counter.
44589 // The member value.
44593 value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value.
44595 if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
44596 value = value.toJSON(key);
44597 } // If we were called with a replacer function, then call the replacer to
44598 // obtain a replacement value.
44601 if (typeof rep === 'function') {
44602 value = rep.call(holder, key, value);
44603 } // What happens next depends on the value's type.
44606 switch (typeof value) {
44608 return quote(value);
44611 // JSON numbers must be finite. Encode non-finite numbers as null.
44612 return isFinite(value) ? String(value) : 'null';
44616 // If the value is a boolean or null, convert it to a string. Note:
44617 // typeof null does not produce 'null'. The case is included here in
44618 // the remote chance that this gets fixed someday.
44619 return String(value);
44622 if (!value) return 'null';
44624 partial = []; // Array.isArray
44626 if (Object.prototype.toString.apply(value) === '[object Array]') {
44627 length = value.length;
44629 for (i = 0; i < length; i += 1) {
44630 partial[i] = str(i, value) || 'null';
44631 } // Join all of the elements together, separated with commas, and
44632 // wrap them in brackets.
44635 v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']';
44638 } // If the replacer is an array, use it to select the members to be
44642 if (rep && typeof rep === 'object') {
44643 length = rep.length;
44645 for (i = 0; i < length; i += 1) {
44648 if (typeof k === 'string') {
44652 partial.push(quote(k) + (gap ? ': ' : ':') + v);
44657 // Otherwise, iterate through all of the keys in the object.
44659 if (Object.prototype.hasOwnProperty.call(value, k)) {
44663 partial.push(quote(k) + (gap ? ': ' : ':') + v);
44667 } // Join all of the member texts together, separated with commas,
44668 // and wrap them in braces.
44671 v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}';
44677 var stringify = function stringify(value, replacer, space) {
44680 indent$a = ''; // If the space parameter is a number, make an indent string containing that
44683 if (typeof space === 'number') {
44684 for (i = 0; i < space; i += 1) {
44687 } // If the space parameter is a string, it will be used as the indent string.
44688 else if (typeof space === 'string') {
44690 } // If there is a replacer, it must be a function or an array.
44691 // Otherwise, throw an error.
44696 if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) {
44697 throw new Error('JSON.stringify');
44698 } // Make a fake root object containing our value under the key of ''.
44699 // Return the result of stringifying the value.
44707 var parse$5 = parse$4;
44708 var stringify$1 = stringify;
44711 stringify: stringify$1
44714 var json$2 = typeof JSON !== 'undefined' ? JSON : jsonify;
44716 var jsonStableStringify = function jsonStableStringify(obj, opts) {
44717 if (!opts) opts = {};
44718 if (typeof opts === 'function') opts = {
44721 var space = opts.space || '';
44722 if (typeof space === 'number') space = Array(space + 1).join(' ');
44723 var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false;
44725 var replacer = opts.replacer || function (key, value) {
44729 var cmp = opts.cmp && function (f) {
44730 return function (node) {
44731 return function (a, b) {
44740 return f(aobj, bobj);
44746 return function stringify(parent, key, node, level) {
44747 var indent = space ? '\n' + new Array(level + 1).join(space) : '';
44748 var colonSeparator = space ? ': ' : ':';
44750 if (node && node.toJSON && typeof node.toJSON === 'function') {
44751 node = node.toJSON();
44754 node = replacer.call(parent, key, node);
44756 if (node === undefined) {
44760 if (typeof node !== 'object' || node === null) {
44761 return json$2.stringify(node);
44764 if (isArray$1(node)) {
44767 for (var i = 0; i < node.length; i++) {
44768 var item = stringify(node, i, node[i], level + 1) || json$2.stringify(null);
44769 out.push(indent + space + item);
44772 return '[' + out.join(',') + indent + ']';
44774 if (seen.indexOf(node) !== -1) {
44775 if (cycles) return json$2.stringify('__cycle__');
44776 throw new TypeError('Converting circular structure to JSON');
44777 } else seen.push(node);
44779 var keys = objectKeys(node).sort(cmp && cmp(node));
44782 for (var i = 0; i < keys.length; i++) {
44784 var value = stringify(node, key, node[key], level + 1);
44785 if (!value) continue;
44786 var keyValue = json$2.stringify(key) + colonSeparator + value;
44787 out.push(indent + space + keyValue);
44790 seen.splice(seen.indexOf(node), 1);
44791 return '{' + out.join(',') + indent + '}';
44798 var isArray$1 = Array.isArray || function (x) {
44799 return {}.toString.call(x) === '[object Array]';
44802 var objectKeys = Object.keys || function (obj) {
44803 var has = Object.prototype.hasOwnProperty || function () {
44809 for (var key in obj) {
44810 if (has.call(obj, key)) keys.push(key);
44816 var preserveCamelCase = function preserveCamelCase(string) {
44817 var isLastCharLower = false;
44818 var isLastCharUpper = false;
44819 var isLastLastCharUpper = false;
44821 for (var i = 0; i < string.length; i++) {
44822 var character = string[i];
44824 if (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) {
44825 string = string.slice(0, i) + '-' + string.slice(i);
44826 isLastCharLower = false;
44827 isLastLastCharUpper = isLastCharUpper;
44828 isLastCharUpper = true;
44830 } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) {
44831 string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
44832 isLastLastCharUpper = isLastCharUpper;
44833 isLastCharUpper = false;
44834 isLastCharLower = true;
44836 isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character;
44837 isLastLastCharUpper = isLastCharUpper;
44838 isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character;
44845 var camelCase = function camelCase(input, options) {
44846 if (!(typeof input === 'string' || Array.isArray(input))) {
44847 throw new TypeError('Expected the input to be `string | string[]`');
44850 options = Object.assign({
44854 var postProcess = function postProcess(x) {
44855 return options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x;
44858 if (Array.isArray(input)) {
44859 input = input.map(function (x) {
44861 }).filter(function (x) {
44865 input = input.trim();
44868 if (input.length === 0) {
44872 if (input.length === 1) {
44873 return options.pascalCase ? input.toUpperCase() : input.toLowerCase();
44876 var hasUpperCase = input !== input.toLowerCase();
44878 if (hasUpperCase) {
44879 input = preserveCamelCase(input);
44882 input = input.replace(/^[_.\- ]+/, '').toLowerCase().replace(/[_.\- ]+(\w|$)/g, function (_, p1) {
44883 return p1.toUpperCase();
44884 }).replace(/\d+(\w|$)/g, function (m) {
44885 return m.toUpperCase();
44887 return postProcess(input);
44890 var camelcase = camelCase; // TODO: Remove this for the next major release
44892 var default_1$6 = camelCase;
44893 camelcase.default = default_1$6;
44896 * dashify <https://github.com/jonschlinkert/dashify>
44898 * Copyright (c) 2015-2017, Jon Schlinkert.
44899 * Released under the MIT License.
44902 var dashify = function dashify(str, options) {
44903 if (typeof str !== 'string') throw new TypeError('expected a string');
44904 return str.trim().replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\W/g, function (m) {
44905 return /[À-ž]/.test(m) ? m : '-';
44906 }).replace(/^-+|-+$/g, '').replace(/-{2,}/g, function (m) {
44907 return options && options.condense ? '-' : m;
44911 var minimist = function minimist(args, opts) {
44912 if (!opts) opts = {};
44919 if (typeof opts['unknown'] === 'function') {
44920 flags.unknownFn = opts['unknown'];
44923 if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
44924 flags.allBools = true;
44926 [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
44927 flags.bools[key] = true;
44932 Object.keys(opts.alias || {}).forEach(function (key) {
44933 aliases[key] = [].concat(opts.alias[key]);
44934 aliases[key].forEach(function (x) {
44935 aliases[x] = [key].concat(aliases[key].filter(function (y) {
44940 [].concat(opts.string).filter(Boolean).forEach(function (key) {
44941 flags.strings[key] = true;
44943 if (aliases[key]) {
44944 flags.strings[aliases[key]] = true;
44947 var defaults = opts['default'] || {};
44951 Object.keys(flags.bools).forEach(function (key) {
44952 setArg(key, defaults[key] === undefined ? false : defaults[key]);
44956 if (args.indexOf('--') !== -1) {
44957 notFlags = args.slice(args.indexOf('--') + 1);
44958 args = args.slice(0, args.indexOf('--'));
44961 function argDefined(key, arg) {
44962 return flags.allBools && /^--[^=]+$/.test(arg) || flags.strings[key] || flags.bools[key] || aliases[key];
44965 function setArg(key, val, arg) {
44966 if (arg && flags.unknownFn && !argDefined(key, arg)) {
44967 if (flags.unknownFn(arg) === false) return;
44970 var value = !flags.strings[key] && isNumber(val) ? Number(val) : val;
44971 setKey(argv, key.split('.'), value);
44972 (aliases[key] || []).forEach(function (x) {
44973 setKey(argv, x.split('.'), value);
44977 function setKey(obj, keys, value) {
44979 keys.slice(0, -1).forEach(function (key) {
44980 if (o[key] === undefined) o[key] = {};
44983 var key = keys[keys.length - 1];
44985 if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
44987 } else if (Array.isArray(o[key])) {
44988 o[key].push(value);
44990 o[key] = [o[key], value];
44994 function aliasIsBoolean(key) {
44995 return aliases[key].some(function (x) {
44996 return flags.bools[x];
45000 for (var i = 0; i < args.length; i++) {
45003 if (/^--.+=/.test(arg)) {
45004 // Using [\s\S] instead of . because js doesn't support the
45005 // 'dotall' regex modifier. See:
45006 // http://stackoverflow.com/a/1068308/13216
45007 var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
45011 if (flags.bools[key]) {
45012 value = value !== 'false';
45015 setArg(key, value, arg);
45016 } else if (/^--no-.+/.test(arg)) {
45017 var key = arg.match(/^--no-(.+)/)[1];
45018 setArg(key, false, arg);
45019 } else if (/^--.+/.test(arg)) {
45020 var key = arg.match(/^--(.+)/)[1];
45021 var next = args[i + 1];
45023 if (next !== undefined && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
45024 setArg(key, next, arg);
45026 } else if (/^(true|false)$/.test(next)) {
45027 setArg(key, next === 'true', arg);
45030 setArg(key, flags.strings[key] ? '' : true, arg);
45032 } else if (/^-[^-]+/.test(arg)) {
45033 var letters = arg.slice(1, -1).split('');
45034 var broken = false;
45036 for (var j = 0; j < letters.length; j++) {
45037 var next = arg.slice(j + 2);
45039 if (next === '-') {
45040 setArg(letters[j], next, arg);
45044 if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
45045 setArg(letters[j], next.split('=')[1], arg);
45050 if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
45051 setArg(letters[j], next, arg);
45056 if (letters[j + 1] && letters[j + 1].match(/\W/)) {
45057 setArg(letters[j], arg.slice(j + 2), arg);
45061 setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
45065 var key = arg.slice(-1)[0];
45067 if (!broken && key !== '-') {
45068 if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
45069 setArg(key, args[i + 1], arg);
45071 } else if (args[i + 1] && /true|false/.test(args[i + 1])) {
45072 setArg(key, args[i + 1] === 'true', arg);
45075 setArg(key, flags.strings[key] ? '' : true, arg);
45079 if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
45080 argv._.push(flags.strings['_'] || !isNumber(arg) ? arg : Number(arg));
45083 if (opts.stopEarly) {
45084 argv._.push.apply(argv._, args.slice(i + 1));
45091 Object.keys(defaults).forEach(function (key) {
45092 if (!hasKey$1(argv, key.split('.'))) {
45093 setKey(argv, key.split('.'), defaults[key]);
45094 (aliases[key] || []).forEach(function (x) {
45095 setKey(argv, x.split('.'), defaults[key]);
45101 argv['--'] = new Array();
45102 notFlags.forEach(function (key) {
45103 argv['--'].push(key);
45106 notFlags.forEach(function (key) {
45114 function hasKey$1(obj, keys) {
45116 keys.slice(0, -1).forEach(function (key) {
45119 var key = keys[keys.length - 1];
45123 function isNumber(x) {
45124 if (typeof x === 'number') return true;
45125 if (/^0x[0-9a-f]+$/i.test(x)) return true;
45126 return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
45129 var PLACEHOLDER = null;
45131 * unspecified boolean flag without default value is parsed as `undefined` instead of `false`
45134 var minimist_1 = function minimist_1(args, options) {
45135 var boolean = options.boolean || [];
45136 var defaults = options.default || {};
45137 var booleanWithoutDefault = boolean.filter(function (key) {
45138 return !(key in defaults);
45140 var newDefaults = Object.assign({}, defaults, booleanWithoutDefault.reduce(function (reduced, key) {
45141 return Object.assign(reduced, {
45145 var parsed = minimist(args, Object.assign({}, options, {
45146 default: newDefaults
45148 return Object.keys(parsed).reduce(function (reduced, key) {
45149 if (parsed[key] !== PLACEHOLDER) {
45150 reduced[key] = parsed[key];
45157 var categoryOrder = [coreOptions.CATEGORY_OUTPUT, coreOptions.CATEGORY_FORMAT, coreOptions.CATEGORY_CONFIG, coreOptions.CATEGORY_EDITOR, coreOptions.CATEGORY_OTHER];
45161 * // The type of the option. For 'choice', see also `choices` below.
45162 * // When passing a type other than the ones listed below, the option is
45163 * // treated as taking any string as argument, and `--option <${type}>` will
45164 * // be displayed in --help.
45165 * type: "boolean" | "choice" | "int" | string;
45167 * // Default value to be passed to the minimist option `default`.
45170 * // Alias name to be passed to the minimist option `alias`.
45173 * // For grouping options by category in --help.
45174 * category?: string;
45176 * // Description to be displayed in --help. If omitted, the option won't be
45177 * // shown at all in --help (but see also `oppositeDescription` below).
45178 * description?: string;
45180 * // Description for `--no-${name}` to be displayed in --help. If omitted,
45181 * // `--no-${name}` won't be shown.
45182 * oppositeDescription?: string;
45184 * // Indicate if this option is simply passed to the API.
45185 * // true: use camelified name as the API option name.
45186 * // string: use this value as the API option name.
45187 * forwardToApi?: boolean | string;
45189 * // Indicate that a CLI flag should be an array when forwarded to the API.
45192 * // Specify available choices for validation. They will also be displayed
45193 * // in --help as <a|b|c>.
45194 * // Use an object instead of a string if a choice is deprecated and should
45195 * // be treated as `redirect` instead, or if you'd like to add description for
45199 * | { value: string, description?: string, deprecated?: boolean, redirect?: string }
45202 * // If the option has a value that is an exception to the regular value
45203 * // constraints, indicate that value here (or use a function for more
45205 * exception?: ((value: any) => boolean);
45207 * // Indicate that the option is deprecated. Use a string to add an extra
45208 * // message to --help for the option, for example to suggest a replacement
45210 * deprecated?: true | string;
45214 * Note: The options below are sorted alphabetically.
45220 category: coreOptions.CATEGORY_OUTPUT,
45222 description: dedent_1`
45223 Check if the given files are formatted, print a human-friendly summary
45224 message and paths to unformatted files (see also --list-different).
45228 // The supports-color package (a sub sub dependency) looks directly at
45229 // `process.argv` for `--no-color` and such-like options. The reason it is
45230 // listed here is to avoid "Ignored unknown option: --no-color" warnings.
45231 // See https://github.com/chalk/supports-color/#info for more information.
45234 description: "Colorize error messages.",
45235 oppositeDescription: "Do not colorize error messages."
45239 category: coreOptions.CATEGORY_CONFIG,
45240 description: "Path to a Prettier configuration file (.prettierrc, package.json, prettier.config.js).",
45241 oppositeDescription: "Do not look for a configuration file.",
45242 exception: function exception(value) {
45243 return value === false;
45246 "config-precedence": {
45248 category: coreOptions.CATEGORY_CONFIG,
45249 default: "cli-override",
45251 value: "cli-override",
45252 description: "CLI options take precedence over config file"
45254 value: "file-override",
45255 description: "Config file take precedence over CLI options"
45257 value: "prefer-file",
45258 description: dedent_1`
45259 If a config file is found will evaluate it and ignore other CLI options.
45260 If no config file is found CLI options will evaluate as normal.
45263 description: "Define in which order config files and CLI options should be evaluated."
45265 "debug-benchmark": {
45266 // Run the formatting benchmarks. Requires 'benchmark' module to be installed.
45270 // Run the formatting once again on the formatted output, throw if different.
45273 "debug-print-doc": {
45277 // Repeat the formatting a few times and measure the average duration.
45283 category: coreOptions.CATEGORY_CONFIG,
45284 description: "Take .editorconfig into account when parsing configuration.",
45285 oppositeDescription: "Don't take .editorconfig into account when parsing configuration.",
45288 "find-config-path": {
45290 category: coreOptions.CATEGORY_CONFIG,
45291 description: "Find and print the path to a configuration file for the given input file."
45295 description: dedent_1`
45296 Extract the following info (as JSON) for a given file path. Reported fields:
45297 * ignored (boolean) - true if file path is filtered by --ignore-path
45298 * inferredParser (string | null) - name of parser inferred from file path
45304 description: dedent_1`
45305 Show CLI usage, or details about the given flag.
45306 Example: --help write
45308 exception: function exception(value) {
45309 return value === "";
45314 category: coreOptions.CATEGORY_CONFIG,
45315 default: ".prettierignore",
45316 description: "Path to a file with patterns describing files to ignore."
45318 "list-different": {
45320 category: coreOptions.CATEGORY_OUTPUT,
45322 description: "Print the names of files that are different from Prettier's formatting (see also --check)."
45326 description: "What level of logs to report.",
45328 choices: ["silent", "error", "warn", "log", "debug"]
45332 description: "Force reading input from stdin."
45336 description: "Print support information as JSON."
45341 description: "Print Prettier version."
45343 "with-node-modules": {
45345 category: coreOptions.CATEGORY_CONFIG,
45346 description: "Process files inside 'node_modules' directory."
45350 category: coreOptions.CATEGORY_OUTPUT,
45351 description: "Edit files in-place. (Beware!)"
45354 var usageSummary = dedent_1`
45355 Usage: prettier [options] [file/glob ...]
45357 By default, output is written to stdout.
45358 Stdin is read if it is piped to Prettier and no files are given.
45362 options: options$8,
45366 // which causes unwanted lines in the output. An additional check for isCI() helps.
45367 // See https://github.com/prettier/prettier/issues/5801
45370 var isTty = function isTTY() {
45371 return process.stdout.isTTY && !thirdParty.isCI();
45374 var OPTION_USAGE_THRESHOLD = 25;
45375 var CHOICE_USAGE_MARGIN = 3;
45376 var CHOICE_USAGE_INDENTATION = 2;
45378 function getOptions(argv, detailedOptions) {
45379 return detailedOptions.filter(function (option) {
45380 return option.forwardToApi;
45381 }).reduce(function (current, option) {
45382 return Object.assign(current, {
45383 [option.forwardToApi]: argv[option.name]
45388 function cliifyOptions(object, apiDetailedOptionMap) {
45389 return Object.keys(object || {}).reduce(function (output, key) {
45390 var apiOption = apiDetailedOptionMap[key];
45391 var cliKey = apiOption ? apiOption.name : key;
45392 output[dashify(cliKey)] = object[key];
45397 function diff(a, b) {
45398 return require$$0$1.createTwoFilesPatch("", "", a, b, "", "", {
45403 function handleError(context, filename, error) {
45404 if (error instanceof errors.UndefinedParserError) {
45405 if (context.argv["write"] && isTty()) {
45406 readline$1.clearLine(process.stdout, 0);
45407 readline$1.cursorTo(process.stdout, 0, null);
45410 if (!context.argv["check"] && !context.argv["list-different"]) {
45411 process.exitCode = 2;
45414 context.logger.error(error.message);
45418 if (context.argv["write"]) {
45419 // Add newline to split errors from filename line.
45420 process.stdout.write("\n");
45423 var isParseError = Boolean(error && error.loc);
45424 var isValidationError = /^Invalid \S+ value\./.test(error && error.message);
45426 if (isParseError) {
45427 // `invalid.js: SyntaxError: Unexpected token (1:1)`.
45428 context.logger.error(`${filename}: ${String(error)}`);
45429 } else if (isValidationError || error instanceof errors.ConfigError) {
45430 // `Invalid printWidth value. Expected an integer, but received 0.5.`
45431 context.logger.error(error.message); // If validation fails for one file, it will fail for all of them.
45434 } else if (error instanceof errors.DebugError) {
45435 // `invalid.js: Some debug error message`
45436 context.logger.error(`${filename}: ${error.message}`);
45438 // `invalid.js: Error: Some unexpected error\n[stack trace]`
45439 context.logger.error(filename + ": " + (error.stack || error));
45440 } // Don't exit the process if one file failed
45443 process.exitCode = 2;
45446 function logResolvedConfigPathOrDie(context) {
45447 var configFile = prettier.resolveConfigFile.sync(context.argv["find-config-path"]);
45450 context.logger.log(path$2.relative(process.cwd(), configFile));
45456 function logFileInfoOrDie(context) {
45458 ignorePath: context.argv["ignore-path"],
45459 withNodeModules: context.argv["with-node-modules"],
45460 plugins: context.argv["plugin"],
45461 pluginSearchDirs: context.argv["plugin-search-dir"]
45463 context.logger.log(prettier.format(jsonStableStringify(prettier.getFileInfo.sync(context.argv["file-info"], options)), {
45468 function writeOutput(context, result, options) {
45469 // Don't use `console.log` here since it adds an extra newline at the end.
45470 process.stdout.write(context.argv["debug-check"] ? result.filepath : result.formatted);
45472 if (options && options.cursorOffset >= 0) {
45473 process.stderr.write(result.cursorOffset + "\n");
45477 function listDifferent(context, input, options, filename) {
45478 if (!context.argv["check"] && !context.argv["list-different"]) {
45483 if (!options.filepath && !options.parser) {
45484 throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
45487 if (!prettier.check(input, options)) {
45488 if (!context.argv["write"]) {
45489 context.logger.log(filename);
45490 process.exitCode = 1;
45494 context.logger.error(error.message);
45500 function format$1(context, input, opt) {
45501 if (!opt.parser && !opt.filepath) {
45502 throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
45505 if (context.argv["debug-print-doc"]) {
45506 var doc = prettier.__debug.printToDoc(input, opt);
45509 formatted: prettier.__debug.formatDoc(doc)
45513 if (context.argv["debug-check"]) {
45514 var pp = prettier.format(input, opt);
45515 var pppp = prettier.format(pp, opt);
45518 throw new errors.DebugError("prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp));
45520 var _stringify = function _stringify(obj) {
45521 return JSON.stringify(obj, null, 2);
45524 var ast = _stringify(prettier.__debug.parse(input, opt,
45528 var past = _stringify(prettier.__debug.parse(pp, opt,
45532 if (ast !== past) {
45533 var MAX_AST_SIZE = 2097152; // 2MB
45535 var astDiff = ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE ? "AST diff too large to render" : diff(ast, past);
45536 throw new errors.DebugError("ast(input) !== ast(prettier(input))\n" + astDiff + "\n" + diff(input, pp));
45542 filepath: opt.filepath || "(stdin)\n"
45545 /* istanbul ignore if */
45548 if (context.argv["debug-benchmark"]) {
45552 benchmark = require("benchmark");
45554 context.logger.debug("'--debug-benchmark' requires the 'benchmark' package to be installed.");
45558 context.logger.debug("'--debug-benchmark' option found, measuring formatWithCursor with 'benchmark' module.");
45559 var suite = new benchmark.Suite();
45560 suite.add("format", function () {
45561 prettier.formatWithCursor(input, opt);
45562 }).on("cycle", function (event) {
45564 benchmark: String(event.target),
45565 hz: event.target.hz,
45566 ms: event.target.times.cycle * 1000
45568 context.logger.debug("'--debug-benchmark' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
45572 } else if (context.argv["debug-repeat"] > 0) {
45573 var repeat = context.argv["debug-repeat"];
45574 context.logger.debug("'--debug-repeat' option found, running formatWithCursor " + repeat + " times."); // should be using `performance.now()`, but only `Date` is cross-platform enough
45576 var now = Date.now ? function () {
45579 return +new Date();
45583 for (var i = 0; i < repeat; ++i) {
45584 var startMs = now();
45585 prettier.formatWithCursor(input, opt);
45586 totalMs += now() - startMs;
45589 var averageMs = totalMs / repeat;
45592 hz: 1000 / averageMs,
45595 context.logger.debug("'--debug-repeat' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
45598 return prettier.formatWithCursor(input, opt);
45601 function getOptionsOrDie(context, filePath) {
45603 if (context.argv["config"] === false) {
45604 context.logger.debug("'--no-config' option found, skip loading config file.");
45608 context.logger.debug(context.argv["config"] ? `load config file from '${context.argv["config"]}'` : `resolve config from '${filePath}'`);
45609 var options = prettier.resolveConfig.sync(filePath, {
45610 editorconfig: context.argv["editorconfig"],
45611 config: context.argv["config"]
45613 context.logger.debug("loaded options `" + JSON.stringify(options) + "`");
45616 context.logger.error(`Invalid configuration file \`${filePath}\`: ` + error.message);
45621 function getOptionsForFile(context, filepath) {
45622 var options = getOptionsOrDie(context, filepath);
45623 var hasPlugins = options && options.plugins;
45626 pushContextPlugins(context, options.plugins);
45629 var appliedOptions = Object.assign({
45631 }, applyConfigPrecedence(context, options && optionsNormalizer.normalizeApiOptions(options, context.supportOptions, {
45632 logger: context.logger
45634 context.logger.debug(`applied config-precedence (${context.argv["config-precedence"]}): ` + `${JSON.stringify(appliedOptions)}`);
45637 popContextPlugins(context);
45640 return appliedOptions;
45643 function parseArgsToOptions(context, overrideDefaults) {
45644 var minimistOptions = createMinimistOptions(context.detailedOptions);
45645 var apiDetailedOptionMap = createApiDetailedOptionMap(context.detailedOptions);
45646 return getOptions(optionsNormalizer.normalizeCliOptions(minimist_1(context.args, Object.assign({
45647 string: minimistOptions.string,
45648 boolean: minimistOptions.boolean,
45649 default: cliifyOptions(overrideDefaults, apiDetailedOptionMap)
45650 })), context.detailedOptions, {
45652 }), context.detailedOptions);
45655 function applyConfigPrecedence(context, options) {
45657 switch (context.argv["config-precedence"]) {
45658 case "cli-override":
45659 return parseArgsToOptions(context, options);
45661 case "file-override":
45662 return Object.assign({}, parseArgsToOptions(context), options);
45664 case "prefer-file":
45665 return options || parseArgsToOptions(context);
45668 context.logger.error(error.toString());
45673 function formatStdin(context) {
45674 var filepath = context.argv["stdin-filepath"] ? path$2.resolve(process.cwd(), context.argv["stdin-filepath"]) : process.cwd();
45675 var ignorer = createIgnorerFromContextOrDie(context);
45676 var relativeFilepath = path$2.relative(process.cwd(), filepath);
45677 thirdParty.getStream(process.stdin).then(function (input) {
45678 if (relativeFilepath && ignorer.filter([relativeFilepath]).length === 0) {
45679 writeOutput(context, {
45685 var options = getOptionsForFile(context, filepath);
45687 if (listDifferent(context, input, options, "(stdin)")) {
45691 writeOutput(context, format$1(context, input, options), options);
45692 }).catch(function (error) {
45693 handleError(context, relativeFilepath || "stdin", error);
45697 function createIgnorerFromContextOrDie(context) {
45699 return createIgnorer_1.sync(context.argv["ignore-path"], context.argv["with-node-modules"]);
45701 context.logger.error(e.message);
45706 function eachFilename(context, patterns, callback) {
45707 // The '!./' globs are due to https://github.com/prettier/prettier/issues/2110
45708 var ignoreNodeModules = context.argv["with-node-modules"] !== true;
45710 if (ignoreNodeModules) {
45711 patterns = patterns.concat(["!**/node_modules/**", "!./node_modules/**"]);
45714 patterns = patterns.concat(["!**/.{git,svn,hg}/**", "!./.{git,svn,hg}/**"]);
45717 var filePaths = globby.sync(patterns, {
45720 }).map(function (filePath) {
45721 return path$2.relative(process.cwd(), filePath);
45724 if (filePaths.length === 0) {
45725 context.logger.error(`No matching files. Patterns tried: ${patterns.join(" ")}`);
45726 process.exitCode = 2;
45730 filePaths.forEach(function (filePath) {
45731 return callback(filePath);
45734 context.logger.error(`Unable to expand glob patterns: ${patterns.join(" ")}\n${error.message}`); // Don't exit the process if one pattern failed
45736 process.exitCode = 2;
45740 function formatFiles(context) {
45741 // The ignorer will be used to filter file paths after the glob is checked,
45742 // before any files are actually written
45743 var ignorer = createIgnorerFromContextOrDie(context);
45744 var numberOfUnformattedFilesFound = 0;
45746 if (context.argv["check"]) {
45747 context.logger.log("Checking formatting...");
45750 eachFilename(context, context.filePatterns, function (filename) {
45751 var fileIgnored = ignorer.filter([filename]).length === 0;
45753 if (fileIgnored && (context.argv["debug-check"] || context.argv["write"] || context.argv["check"] || context.argv["list-different"])) {
45757 var options = Object.assign(getOptionsForFile(context, filename), {
45762 context.logger.log(filename, {
45770 input = fs$1.readFileSync(filename, "utf8");
45772 // Add newline to split errors from filename line.
45773 context.logger.log("");
45774 context.logger.error(`Unable to read file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
45776 process.exitCode = 2;
45781 writeOutput(context, {
45787 var start = Date.now();
45792 result = format$1(context, input, Object.assign({}, options, {
45795 output = result.formatted;
45797 handleError(context, filename, error);
45801 var isDifferent = output !== input;
45804 // Remove previously printed filename to log it with duration.
45805 readline$1.clearLine(process.stdout, 0);
45806 readline$1.cursorTo(process.stdout, 0, null);
45809 if (context.argv["write"]) {
45810 // Don't write the file if it won't change in order not to invalidate
45811 // mtime based caches.
45813 if (!context.argv["check"] && !context.argv["list-different"]) {
45814 context.logger.log(`${filename} ${Date.now() - start}ms`);
45818 fs$1.writeFileSync(filename, output, "utf8");
45820 context.logger.error(`Unable to write file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
45822 process.exitCode = 2;
45824 } else if (!context.argv["check"] && !context.argv["list-different"]) {
45825 context.logger.log(`${chalk.grey(filename)} ${Date.now() - start}ms`);
45827 } else if (context.argv["debug-check"]) {
45828 if (result.filepath) {
45829 context.logger.log(result.filepath);
45831 process.exitCode = 2;
45833 } else if (!context.argv["check"] && !context.argv["list-different"]) {
45834 writeOutput(context, result, options);
45837 if ((context.argv["check"] || context.argv["list-different"]) && isDifferent) {
45838 context.logger.log(filename);
45839 numberOfUnformattedFilesFound += 1;
45841 }); // Print check summary based on expected exit code
45843 if (context.argv["check"]) {
45844 context.logger.log(numberOfUnformattedFilesFound === 0 ? "All matched files use Prettier code style!" : context.argv["write"] ? "Code style issues fixed in the above file(s)." : "Code style issues found in the above file(s). Forgot to run Prettier?");
45845 } // Ensure non-zero exitCode when using --check/list-different is not combined with --write
45848 if ((context.argv["check"] || context.argv["list-different"]) && numberOfUnformattedFilesFound > 0 && !process.exitCode && !context.argv["write"]) {
45849 process.exitCode = 1;
45853 function getOptionsWithOpposites(options) {
45854 // Add --no-foo after --foo.
45855 var optionsWithOpposites = options.map(function (option) {
45856 return [option.description ? option : null, option.oppositeDescription ? Object.assign({}, option, {
45857 name: `no-${option.name}`,
45859 description: option.oppositeDescription
45862 return flattenArray(optionsWithOpposites).filter(Boolean);
45865 function createUsage(context) {
45866 var options = getOptionsWithOpposites(context.detailedOptions).filter( // remove unnecessary option (e.g. `semi`, `color`, etc.), which is only used for --help <flag>
45867 function (option) {
45868 return !(option.type === "boolean" && option.oppositeDescription && !option.name.startsWith("no-"));
45870 var groupedOptions = groupBy(options, function (option) {
45871 return option.category;
45873 var firstCategories = constant.categoryOrder.slice(0, -1);
45874 var lastCategories = constant.categoryOrder.slice(-1);
45875 var restCategories = Object.keys(groupedOptions).filter(function (category) {
45876 return firstCategories.indexOf(category) === -1 && lastCategories.indexOf(category) === -1;
45878 var allCategories = firstCategories.concat(restCategories, lastCategories);
45879 var optionsUsage = allCategories.map(function (category) {
45880 var categoryOptions = groupedOptions[category].map(function (option) {
45881 return createOptionUsage(context, option, OPTION_USAGE_THRESHOLD);
45883 return `${category} options:\n\n${indent$b(categoryOptions, 2)}`;
45885 return [constant.usageSummary].concat(optionsUsage, [""]).join("\n\n");
45888 function createOptionUsage(context, option, threshold) {
45889 var header = createOptionUsageHeader(option);
45890 var optionDefaultValue = getOptionDefaultValue(context, option.name);
45891 return createOptionUsageRow(header, `${option.description}${optionDefaultValue === undefined ? "" : `\nDefaults to ${createDefaultValueDisplay(optionDefaultValue)}.`}`, threshold);
45894 function createDefaultValueDisplay(value) {
45895 return Array.isArray(value) ? `[${value.map(createDefaultValueDisplay).join(", ")}]` : value;
45898 function createOptionUsageHeader(option) {
45899 var name = `--${option.name}`;
45900 var alias = option.alias ? `-${option.alias},` : null;
45901 var type = createOptionUsageType(option);
45902 return [alias, name, type].filter(Boolean).join(" ");
45905 function createOptionUsageRow(header, content, threshold) {
45906 var separator = header.length >= threshold ? `\n${" ".repeat(threshold)}` : " ".repeat(threshold - header.length);
45907 var description = content.replace(/\n/g, `\n${" ".repeat(threshold)}`);
45908 return `${header}${separator}${description}`;
45911 function createOptionUsageType(option) {
45912 switch (option.type) {
45917 return `<${option.choices.filter(function (choice) {
45918 return choice.since !== null;
45919 }).filter(function (choice) {
45920 return !choice.deprecated;
45921 }).map(function (choice) {
45922 return choice.value;
45926 return `<${option.type}>`;
45930 function flattenArray(array) {
45931 return [].concat.apply([], array);
45934 function createChoiceUsages(choices, margin, indentation) {
45935 var activeChoices = choices.filter(function (choice) {
45936 return !choice.deprecated && choice.since !== null;
45938 var threshold = activeChoices.map(function (choice) {
45939 return choice.value.length;
45940 }).reduce(function (current, length) {
45941 return Math.max(current, length);
45943 return activeChoices.map(function (choice) {
45944 return indent$b(createOptionUsageRow(choice.value, choice.description, threshold), indentation);
45948 function createDetailedUsage(context, flag) {
45949 var option = getOptionsWithOpposites(context.detailedOptions).find(function (option) {
45950 return option.name === flag || option.alias === flag;
45952 var header = createOptionUsageHeader(option);
45953 var description = `\n\n${indent$b(option.description, 2)}`;
45954 var choices = option.type !== "choice" ? "" : `\n\nValid options:\n\n${createChoiceUsages(option.choices, CHOICE_USAGE_MARGIN, CHOICE_USAGE_INDENTATION).join("\n")}`;
45955 var optionDefaultValue = getOptionDefaultValue(context, option.name);
45956 var defaults = optionDefaultValue !== undefined ? `\n\nDefault: ${createDefaultValueDisplay(optionDefaultValue)}` : "";
45957 var pluginDefaults = option.pluginDefaults && Object.keys(option.pluginDefaults).length ? `\nPlugin defaults:${Object.keys(option.pluginDefaults).map(function (key) {
45958 return `\n* ${key}: ${createDefaultValueDisplay(option.pluginDefaults[key])}`;
45960 return `${header}${description}${choices}${defaults}${pluginDefaults}`;
45963 function getOptionDefaultValue(context, optionName) {
45965 if (!(optionName in context.detailedOptionMap)) {
45969 var option = context.detailedOptionMap[optionName];
45971 if (option.default !== undefined) {
45972 return option.default;
45975 var optionCamelName = camelcase(optionName);
45977 if (optionCamelName in context.apiDefaultOptions) {
45978 return context.apiDefaultOptions[optionCamelName];
45984 function indent$b(str, spaces) {
45985 return str.replace(/^/gm, " ".repeat(spaces));
45988 function groupBy(array, getKey) {
45989 return array.reduce(function (obj, item) {
45990 var key = getKey(item);
45991 var previousItems = key in obj ? obj[key] : [];
45992 return Object.assign({}, obj, {
45993 [key]: previousItems.concat(item)
45995 }, Object.create(null));
45998 function pick(object, keys) {
45999 return !keys ? object : keys.reduce(function (reduced, key) {
46000 return Object.assign(reduced, {
46006 function createLogger(logLevel) {
46008 warn: createLogFunc("warn", "yellow"),
46009 error: createLogFunc("error", "red"),
46010 debug: createLogFunc("debug", "blue"),
46011 log: createLogFunc("log")
46014 function createLogFunc(loggerName, color) {
46015 if (!shouldLog(loggerName)) {
46016 return function () {};
46019 var prefix = color ? `[${chalk[color](loggerName)}] ` : "";
46020 return function (message, opts) {
46021 opts = Object.assign({
46024 var stream = process[loggerName === "log" ? "stdout" : "stderr"];
46025 stream.write(message.replace(/^/gm, prefix) + (opts.newline ? "\n" : ""));
46029 function shouldLog(loggerName) {
46030 switch (logLevel) {
46038 if (loggerName === "debug") {
46045 if (loggerName === "log") {
46052 if (loggerName === "warn") {
46059 return loggerName === "error";
46064 function normalizeDetailedOption(name, option) {
46065 return Object.assign({
46066 category: coreOptions.CATEGORY_OTHER
46068 choices: option.choices && option.choices.map(function (choice) {
46069 var newChoice = Object.assign({
46072 }, typeof choice === "object" ? choice : {
46076 if (newChoice.value === true) {
46077 newChoice.value = ""; // backward compatibility for original boolean option
46085 function normalizeDetailedOptionMap(detailedOptionMap) {
46086 return Object.keys(detailedOptionMap).sort().reduce(function (normalized, name) {
46087 var option = detailedOptionMap[name];
46088 return Object.assign(normalized, {
46089 [name]: normalizeDetailedOption(name, option)
46094 function createMinimistOptions(detailedOptions) {
46096 // we use vnopts' AliasSchema to handle aliases for better error messages
46098 boolean: detailedOptions.filter(function (option) {
46099 return option.type === "boolean";
46100 }).map(function (option) {
46101 return [option.name].concat(option.alias || []);
46102 }).reduce(function (a, b) {
46103 return a.concat(b);
46105 string: detailedOptions.filter(function (option) {
46106 return option.type !== "boolean";
46107 }).map(function (option) {
46108 return [option.name].concat(option.alias || []);
46109 }).reduce(function (a, b) {
46110 return a.concat(b);
46112 default: detailedOptions.filter(function (option) {
46113 return !option.deprecated;
46114 }).filter(function (option) {
46115 return !option.forwardToApi || option.name === "plugin" || option.name === "plugin-search-dir";
46116 }).filter(function (option) {
46117 return option.default !== undefined;
46118 }).reduce(function (current, option) {
46119 return Object.assign({
46120 [option.name]: option.default
46126 function createApiDetailedOptionMap(detailedOptions) {
46127 return detailedOptions.reduce(function (current, option) {
46128 return option.forwardToApi && option.forwardToApi !== option.name ? Object.assign(current, {
46129 [option.forwardToApi]: option
46134 function createDetailedOptionMap(supportOptions) {
46135 return supportOptions.reduce(function (reduced, option) {
46136 var newOption = Object.assign({}, option, {
46137 name: option.cliName || dashify(option.name),
46138 description: option.cliDescription || option.description,
46139 category: option.cliCategory || coreOptions.CATEGORY_FORMAT,
46140 forwardToApi: option.name
46143 if (option.deprecated) {
46144 delete newOption.forwardToApi;
46145 delete newOption.description;
46146 delete newOption.oppositeDescription;
46147 newOption.deprecated = true;
46150 return Object.assign(reduced, {
46151 [newOption.name]: newOption
46154 } //-----------------------------context-util-start-------------------------------
46157 * @typedef {Object} Context
46161 * @property filePatterns
46162 * @property supportOptions
46163 * @property detailedOptions
46164 * @property detailedOptionMap
46165 * @property apiDefaultOptions
46169 function createContext(args) {
46173 updateContextArgv(context);
46174 normalizeContextArgv(context, ["loglevel", "plugin", "plugin-search-dir"]);
46175 context.logger = createLogger(context.argv["loglevel"]);
46176 updateContextArgv(context, context.argv["plugin"], context.argv["plugin-search-dir"]);
46180 function initContext(context) {
46181 // split into 2 step so that we could wrap this in a `try..catch` in cli/index.js
46182 normalizeContextArgv(context);
46185 function updateContextOptions(context, plugins, pluginSearchDirs) {
46186 var supportOptions = prettier.getSupportInfo(null, {
46187 showDeprecated: true,
46188 showUnreleased: true,
46189 showInternal: true,
46193 var detailedOptionMap = normalizeDetailedOptionMap(Object.assign({}, createDetailedOptionMap(supportOptions), constant.options));
46194 var detailedOptions = arrayify(detailedOptionMap, "name");
46195 var apiDefaultOptions = supportOptions.filter(function (optionInfo) {
46196 return !optionInfo.deprecated;
46197 }).reduce(function (reduced, optionInfo) {
46198 return Object.assign(reduced, {
46199 [optionInfo.name]: optionInfo.default
46201 }, Object.assign({}, options$1.hiddenDefaults));
46202 context.supportOptions = supportOptions;
46203 context.detailedOptions = detailedOptions;
46204 context.detailedOptionMap = detailedOptionMap;
46205 context.apiDefaultOptions = apiDefaultOptions;
46208 function pushContextPlugins(context, plugins, pluginSearchDirs) {
46209 context._supportOptions = context.supportOptions;
46210 context._detailedOptions = context.detailedOptions;
46211 context._detailedOptionMap = context.detailedOptionMap;
46212 context._apiDefaultOptions = context.apiDefaultOptions;
46213 updateContextOptions(context, plugins, pluginSearchDirs);
46216 function popContextPlugins(context) {
46217 context.supportOptions = context._supportOptions;
46218 context.detailedOptions = context._detailedOptions;
46219 context.detailedOptionMap = context._detailedOptionMap;
46220 context.apiDefaultOptions = context._apiDefaultOptions;
46223 function updateContextArgv(context, plugins, pluginSearchDirs) {
46224 pushContextPlugins(context, plugins, pluginSearchDirs);
46225 var minimistOptions = createMinimistOptions(context.detailedOptions);
46226 var argv = minimist_1(context.args, minimistOptions);
46227 context.argv = argv;
46228 context.filePatterns = argv["_"];
46231 function normalizeContextArgv(context, keys) {
46232 var detailedOptions = !keys ? context.detailedOptions : context.detailedOptions.filter(function (option) {
46233 return keys.indexOf(option.name) !== -1;
46235 var argv = !keys ? context.argv : pick(context.argv, keys);
46236 context.argv = optionsNormalizer.normalizeCliOptions(argv, detailedOptions, {
46237 logger: context.logger
46239 } //------------------------------context-util-end--------------------------------
46244 createDetailedOptionMap,
46245 createDetailedUsage,
46251 logResolvedConfigPathOrDie,
46253 normalizeDetailedOptionMap
46256 function run(args) {
46257 var context = util$2.createContext(args);
46260 util$2.initContext(context);
46261 context.logger.debug(`normalized argv: ${JSON.stringify(context.argv)}`);
46263 if (context.argv["check"] && context.argv["list-different"]) {
46264 context.logger.error("Cannot use --check and --list-different together.");
46268 if (context.argv["write"] && context.argv["debug-check"]) {
46269 context.logger.error("Cannot use --write and --debug-check together.");
46273 if (context.argv["find-config-path"] && context.filePatterns.length) {
46274 context.logger.error("Cannot use --find-config-path with multiple files");
46278 if (context.argv["file-info"] && context.filePatterns.length) {
46279 context.logger.error("Cannot use --file-info with multiple files");
46283 if (context.argv["version"]) {
46284 context.logger.log(prettier.version);
46288 if (context.argv["help"] !== undefined) {
46289 context.logger.log(typeof context.argv["help"] === "string" && context.argv["help"] !== "" ? util$2.createDetailedUsage(context, context.argv["help"]) : util$2.createUsage(context));
46293 if (context.argv["support-info"]) {
46294 context.logger.log(prettier.format(jsonStableStringify(prettier.getSupportInfo()), {
46300 var hasFilePatterns = context.filePatterns.length !== 0;
46301 var useStdin = context.argv["stdin"] || !hasFilePatterns && !process.stdin.isTTY;
46303 if (context.argv["find-config-path"]) {
46304 util$2.logResolvedConfigPathOrDie(context);
46305 } else if (context.argv["file-info"]) {
46306 util$2.logFileInfoOrDie(context);
46307 } else if (useStdin) {
46308 util$2.formatStdin(context);
46309 } else if (hasFilePatterns) {
46310 util$2.formatFiles(context);
46312 context.logger.log(util$2.createUsage(context));
46316 context.logger.error(error.message);
46325 cli.run(process.argv.slice(2));
46326 var prettier$1 = {};
46328 module.exports = prettier$1;