3 function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
5 var fs$1 = _interopDefault(require('fs'));
6 var os$1 = _interopDefault(require('os'));
7 var path$2 = _interopDefault(require('path'));
8 var assert$1 = _interopDefault(require('assert'));
9 var util$2 = _interopDefault(require('util'));
10 var events$1 = _interopDefault(require('events'));
12 var name = "prettier";
13 var version = "1.19.1";
14 var description = "Prettier is an opinionated code formatter";
16 prettier: "./bin/prettier.js"
18 var repository = "prettier/prettier";
19 var homepage = "https://prettier.io";
20 var author = "James Long";
22 var main = "./index.js";
27 "@angular/compiler": "8.2.13",
28 "@babel/code-frame": "7.5.5",
29 "@babel/parser": "7.7.3",
30 "@glimmer/syntax": "0.41.0",
31 "@iarna/toml": "2.2.3",
32 "@typescript-eslint/typescript-estree": "2.6.1",
33 "angular-estree-parser": "1.1.5",
34 "angular-html-parser": "1.3.0",
42 editorconfig: "0.15.3",
43 "editorconfig-to-prettier": "0.1.1",
44 "escape-string-regexp": "1.0.5",
46 "find-parent-dir": "0.3.0",
47 "find-project-root": "1.1.1",
48 "flow-parser": "0.111.3",
49 "get-stream": "4.1.0",
52 "html-element-attributes": "2.2.0",
53 "html-styles": "1.0.0",
54 "html-tag-names": "1.1.4",
57 "jest-docblock": "24.9.0",
58 "json-stable-stringify": "1.0.1",
60 "lines-and-columns": "1.1.6",
61 "linguist-languages": "7.6.0",
62 "lodash.uniqby": "4.7.0",
66 "n-readlines": "1.0.0",
67 "normalize-path": "3.0.0",
68 "parse-srcset": "ikatyang/parse-srcset#54eb9c1cb21db5c62b4d0e275d7249516df6f0ee",
69 "postcss-less": "2.0.0",
70 "postcss-media-query-parser": "0.2.3",
71 "postcss-scss": "2.0.0",
72 "postcss-selector-parser": "2.2.3",
73 "postcss-values-parser": "1.5.0",
74 "regexp-util": "1.2.2",
75 "remark-math": "1.0.6",
76 "remark-parse": "5.0.0",
79 "string-width": "4.1.0",
81 "unicode-regex": "3.0.0",
84 "yaml-unist-parser": "1.1.1"
86 var devDependencies = {
87 "@babel/core": "7.7.2",
88 "@babel/preset-env": "7.7.1",
89 "@rollup/plugin-alias": "2.2.0",
90 "@rollup/plugin-replace": "2.2.1",
91 "babel-loader": "8.0.6",
93 "builtin-modules": "3.1.0",
97 "eslint-config-prettier": "6.5.0",
98 "eslint-formatter-friendly": "7.0.0",
99 "eslint-plugin-import": "2.18.2",
100 "eslint-plugin-prettier": "3.1.1",
101 "eslint-plugin-react": "7.16.0",
104 "jest-junit": "9.0.0",
105 "jest-snapshot-serializer-ansi": "1.0.0",
106 "jest-snapshot-serializer-raw": "1.1.0",
107 "jest-watch-typeahead": "0.4.0",
113 "rollup-plugin-babel": "4.3.3",
114 "rollup-plugin-commonjs": "10.1.0",
115 "rollup-plugin-json": "4.0.0",
116 "rollup-plugin-node-globals": "1.4.0",
117 "rollup-plugin-node-resolve": "5.2.0",
118 "rollup-plugin-terser": "5.1.2",
120 "snapshot-diff": "0.4.0",
121 "strip-ansi": "5.2.0",
122 "synchronous-promise": "2.0.10",
124 "terser-webpack-plugin": "2.2.1",
128 prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1",
129 "prepare-release": "yarn && yarn build && yarn test:dist",
131 "test:dist": "node ./scripts/test-dist.js",
132 "test-integration": "jest tests_integration",
133 "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",
134 "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",
135 "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",
136 "check-types": "tsc",
137 lint: "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly",
138 "lint-docs": "prettylint {.,docs,website,website/blog}/*.md",
139 "lint-dist": "eslint --no-eslintrc --no-ignore --env=browser \"dist/!(bin-prettier|index|third-party).js\"",
140 build: "node --max-old-space-size=3072 ./scripts/build/build.js",
141 "build-docs": "node ./scripts/build-docs.js",
142 "check-deps": "node ./scripts/check-deps.js",
143 spellcheck: "npx -p cspell@4.0.31 cspell {bin,scripts,src}/**/*.js {docs,website/blog,changelog_unreleased}/**/*.md"
148 description: description,
150 repository: repository,
156 dependencies: dependencies,
157 devDependencies: devDependencies,
161 var _package$1 = /*#__PURE__*/Object.freeze({
165 description: description,
167 repository: repository,
173 dependencies: dependencies,
174 devDependencies: devDependencies,
182 diff: function diff(oldString, newString) {
183 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
184 var callback = options.callback;
186 if (typeof options === 'function') {
191 this.options = options;
194 function done(value) {
196 setTimeout(function () {
197 callback(undefined, value);
203 } // Allow subclasses to massage the input prior to running
206 oldString = this.castInput(oldString);
207 newString = this.castInput(newString);
208 oldString = this.removeEmpty(this.tokenize(oldString));
209 newString = this.removeEmpty(this.tokenize(newString));
210 var newLen = newString.length,
211 oldLen = oldString.length;
213 var maxEditLength = newLen + oldLen;
217 }]; // Seed editLength = 0, i.e. the content starts with the same values
219 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
221 if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
222 // Identity per the equality and tokenizer
224 value: this.join(newString),
225 count: newString.length
227 } // Main worker method. checks all permutations of a given edit length for acceptance.
230 function execEditLength() {
231 for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
232 var basePath = void 0;
234 var addPath = bestPath[diagonalPath - 1],
235 removePath = bestPath[diagonalPath + 1],
236 _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
239 // No one else is going to attempt to use this value, clear it
240 bestPath[diagonalPath - 1] = undefined;
243 var canAdd = addPath && addPath.newPos + 1 < newLen,
244 canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
246 if (!canAdd && !canRemove) {
247 // If this path is a terminal then prune
248 bestPath[diagonalPath] = undefined;
250 } // Select the diagonal that we want to branch from. We select the prior
251 // path whose position in the new string is the farthest from the origin
252 // and does not pass the bounds of the diff graph
255 if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
256 basePath = clonePath(removePath);
257 self.pushComponent(basePath.components, undefined, true);
259 basePath = addPath; // No need to clone, we've pulled it from the list
262 self.pushComponent(basePath.components, true, undefined);
265 _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
267 if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
268 return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
270 // Otherwise track this path as a potential candidate and continue.
271 bestPath[diagonalPath] = basePath;
276 } // Performs the length of edit iteration. Is a bit fugly as this has to support the
277 // sync and async mode which is never fun. Loops over execEditLength until a value
283 setTimeout(function () {
284 // This should not happen, but we want to be safe.
286 /* istanbul ignore next */
287 if (editLength > maxEditLength) {
291 if (!execEditLength()) {
297 while (editLength <= maxEditLength) {
298 var ret = execEditLength();
306 pushComponent: function pushComponent(components, added, removed) {
307 var last = components[components.length - 1];
309 if (last && last.added === added && last.removed === removed) {
310 // We need to clone here as the component clone operation is just
311 // as shallow array clone
312 components[components.length - 1] = {
313 count: last.count + 1,
325 extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
326 var newLen = newString.length,
327 oldLen = oldString.length,
328 newPos = basePath.newPos,
329 oldPos = newPos - diagonalPath,
332 while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
339 basePath.components.push({
344 basePath.newPos = newPos;
347 equals: function equals(left, right) {
348 if (this.options.comparator) {
349 return this.options.comparator(left, right);
351 return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
354 removeEmpty: function removeEmpty(array) {
357 for (var i = 0; i < array.length; i++) {
365 castInput: function castInput(value) {
368 tokenize: function tokenize(value) {
369 return value.split('');
371 join: function join(chars) {
372 return chars.join('');
376 function buildValues(diff, components, newString, oldString, useLongestToken) {
377 var componentPos = 0,
378 componentLen = components.length,
382 for (; componentPos < componentLen; componentPos++) {
383 var component = components[componentPos];
385 if (!component.removed) {
386 if (!component.added && useLongestToken) {
387 var value = newString.slice(newPos, newPos + component.count);
388 value = value.map(function (value, i) {
389 var oldValue = oldString[oldPos + i];
390 return oldValue.length > value.length ? oldValue : value;
392 component.value = diff.join(value);
394 component.value = diff.join(newString.slice(newPos, newPos + component.count));
397 newPos += component.count; // Common case
399 if (!component.added) {
400 oldPos += component.count;
403 component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
404 oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
405 // The diffing algorithm is tied to add then remove output and this is the simplest
406 // route to get the desired output with minimal overhead.
408 if (componentPos && components[componentPos - 1].added) {
409 var tmp = components[componentPos - 1];
410 components[componentPos - 1] = components[componentPos];
411 components[componentPos] = tmp;
414 } // Special case handle for when one terminal is ignored (i.e. whitespace).
415 // For this case we merge the terminal into the prior string and drop the change.
416 // This is only available for string mode.
419 var lastComponent = components[componentLen - 1];
421 if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
422 components[componentLen - 2].value += lastComponent.value;
429 function clonePath(path) {
432 components: path.components.slice(0)
436 var characterDiff = new Diff();
438 function diffChars(oldStr, newStr, options) {
439 return characterDiff.diff(oldStr, newStr, options);
442 function generateOptions(options, defaults) {
443 if (typeof options === 'function') {
444 defaults.callback = options;
445 } else if (options) {
446 for (var name in options) {
447 /* istanbul ignore else */
448 if (options.hasOwnProperty(name)) {
449 defaults[name] = options[name];
456 // Ranges and exceptions:
457 // Latin-1 Supplement, 0080–00FF
458 // - U+00D7 × Multiplication sign
459 // - U+00F7 ÷ Division sign
460 // Latin Extended-A, 0100–017F
461 // Latin Extended-B, 0180–024F
462 // IPA Extensions, 0250–02AF
463 // Spacing Modifier Letters, 02B0–02FF
464 // - U+02C7 ˇ ˇ Caron
465 // - U+02D8 ˘ ˘ Breve
466 // - U+02D9 ˙ ˙ Dot Above
467 // - U+02DA ˚ ˚ Ring Above
468 // - U+02DB ˛ ˛ Ogonek
469 // - U+02DC ˜ ˜ Small Tilde
470 // - U+02DD ˝ ˝ Double Acute Accent
471 // Latin Extended Additional, 1E00–1EFF
474 var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
475 var reWhitespace = /\S/;
476 var wordDiff = new Diff();
478 wordDiff.equals = function (left, right) {
479 if (this.options.ignoreCase) {
480 left = left.toLowerCase();
481 right = right.toLowerCase();
484 return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
487 wordDiff.tokenize = function (value) {
488 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.
490 for (var i = 0; i < tokens.length - 1; i++) {
491 // If we have an empty string in the next field and we have only word chars before and after, merge
492 if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
493 tokens[i] += tokens[i + 2];
494 tokens.splice(i + 1, 2);
502 function diffWords(oldStr, newStr, options) {
503 options = generateOptions(options, {
504 ignoreWhitespace: true
506 return wordDiff.diff(oldStr, newStr, options);
509 function diffWordsWithSpace(oldStr, newStr, options) {
510 return wordDiff.diff(oldStr, newStr, options);
513 var lineDiff = new Diff();
515 lineDiff.tokenize = function (value) {
517 linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
519 if (!linesAndNewlines[linesAndNewlines.length - 1]) {
520 linesAndNewlines.pop();
521 } // Merge the content and line separators into single tokens
524 for (var i = 0; i < linesAndNewlines.length; i++) {
525 var line = linesAndNewlines[i];
527 if (i % 2 && !this.options.newlineIsToken) {
528 retLines[retLines.length - 1] += line;
530 if (this.options.ignoreWhitespace) {
541 function diffLines(oldStr, newStr, callback) {
542 return lineDiff.diff(oldStr, newStr, callback);
545 function diffTrimmedLines(oldStr, newStr, callback) {
546 var options = generateOptions(callback, {
547 ignoreWhitespace: true
549 return lineDiff.diff(oldStr, newStr, options);
552 var sentenceDiff = new Diff();
554 sentenceDiff.tokenize = function (value) {
555 return value.split(/(\S.+?[.!?])(?=\s+|$)/);
558 function diffSentences(oldStr, newStr, callback) {
559 return sentenceDiff.diff(oldStr, newStr, callback);
562 var cssDiff = new Diff();
564 cssDiff.tokenize = function (value) {
565 return value.split(/([{}:;,]|\s+)/);
568 function diffCss(oldStr, newStr, callback) {
569 return cssDiff.diff(oldStr, newStr, callback);
572 function _typeof(obj) {
573 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
574 _typeof = function _typeof(obj) {
578 _typeof = function _typeof(obj) {
579 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
586 function _toConsumableArray(arr) {
587 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
590 function _arrayWithoutHoles(arr) {
591 if (Array.isArray(arr)) {
592 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
600 function _iterableToArray(iter) {
601 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
604 function _nonIterableSpread() {
605 throw new TypeError("Invalid attempt to spread non-iterable instance");
608 var objectPrototypeToString = Object.prototype.toString;
609 var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
610 // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
612 jsonDiff.useLongestToken = true;
613 jsonDiff.tokenize = lineDiff.tokenize;
615 jsonDiff.castInput = function (value) {
616 var _this$options = this.options,
617 undefinedReplacement = _this$options.undefinedReplacement,
618 _this$options$stringi = _this$options.stringifyReplacer,
619 stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
620 return typeof v === 'undefined' ? undefinedReplacement : v;
621 } : _this$options$stringi;
622 return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
625 jsonDiff.equals = function (left, right) {
626 return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
629 function diffJson(oldObj, newObj, options) {
630 return jsonDiff.diff(oldObj, newObj, options);
631 } // This function handles the presence of circular references by bailing out when encountering an
632 // object that is already on the "stack" of items being processed. Accepts an optional replacer
635 function canonicalize(obj, stack, replacementStack, replacer, key) {
637 replacementStack = replacementStack || [];
640 obj = replacer(key, obj);
645 for (i = 0; i < stack.length; i += 1) {
646 if (stack[i] === obj) {
647 return replacementStack[i];
651 var canonicalizedObj;
653 if ('[object Array]' === objectPrototypeToString.call(obj)) {
655 canonicalizedObj = new Array(obj.length);
656 replacementStack.push(canonicalizedObj);
658 for (i = 0; i < obj.length; i += 1) {
659 canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
663 replacementStack.pop();
664 return canonicalizedObj;
667 if (obj && obj.toJSON) {
671 if (_typeof(obj) === 'object' && obj !== null) {
673 canonicalizedObj = {};
674 replacementStack.push(canonicalizedObj);
680 /* istanbul ignore else */
681 if (obj.hasOwnProperty(_key)) {
682 sortedKeys.push(_key);
688 for (i = 0; i < sortedKeys.length; i += 1) {
689 _key = sortedKeys[i];
690 canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
694 replacementStack.pop();
696 canonicalizedObj = obj;
699 return canonicalizedObj;
702 var arrayDiff = new Diff();
704 arrayDiff.tokenize = function (value) {
705 return value.slice();
708 arrayDiff.join = arrayDiff.removeEmpty = function (value) {
712 function diffArrays(oldArr, newArr, callback) {
713 return arrayDiff.diff(oldArr, newArr, callback);
716 function parsePatch(uniDiff) {
717 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
718 var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
719 delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
723 function parseIndex() {
725 list.push(index); // Parse diff metadata
727 while (i < diffstr.length) {
728 var line = diffstr[i]; // File header found, end parsing diff metadata
730 if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
735 var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
738 index.index = header[1];
742 } // Parse file headers if they are defined. Unified diff requires them, but
743 // there's no technical issues to have an isolated hunk without file header
746 parseFileHeader(index);
747 parseFileHeader(index); // Parse hunks
751 while (i < diffstr.length) {
752 var _line = diffstr[i];
754 if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
756 } else if (/^@@/.test(_line)) {
757 index.hunks.push(parseHunk());
758 } else if (_line && options.strict) {
759 // Ignore unexpected content unless in strict mode
760 throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
765 } // Parses the --- and +++ headers, if none are found, no lines
769 function parseFileHeader(index) {
770 var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
773 var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
774 var data = fileHeader[2].split('\t', 2);
775 var fileName = data[0].replace(/\\\\/g, '\\');
777 if (/^".*"$/.test(fileName)) {
778 fileName = fileName.substr(1, fileName.length - 2);
781 index[keyPrefix + 'FileName'] = fileName;
782 index[keyPrefix + 'Header'] = (data[1] || '').trim();
786 // This assumes that we are at the start of a hunk.
789 function parseHunk() {
790 var chunkHeaderIndex = i,
791 chunkHeaderLine = diffstr[i++],
792 chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
794 oldStart: +chunkHeader[1],
795 oldLines: +chunkHeader[2] || 1,
796 newStart: +chunkHeader[3],
797 newLines: +chunkHeader[4] || 1,
804 for (; i < diffstr.length; i++) {
805 // Lines starting with '---' could be mistaken for the "remove line" operation
806 // But they could be the header for the next file. Therefore prune such cases out.
807 if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
811 var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
813 if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
814 hunk.lines.push(diffstr[i]);
815 hunk.linedelimiters.push(delimiters[i] || '\n');
817 if (operation === '+') {
819 } else if (operation === '-') {
821 } else if (operation === ' ') {
828 } // Handle the empty block count case
831 if (!addCount && hunk.newLines === 1) {
835 if (!removeCount && hunk.oldLines === 1) {
837 } // Perform optional sanity checking
840 if (options.strict) {
841 if (addCount !== hunk.newLines) {
842 throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
845 if (removeCount !== hunk.oldLines) {
846 throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
853 while (i < diffstr.length) {
858 } // Iterator that traverses in the range of [min, max], stepping
859 // by distance from a given start position. I.e. for [0, 4], with
860 // start of 2, this will iterate 2, 3, 1, 4, 0.
863 function distanceIterator(start, minLine, maxLine) {
864 var wantForward = true,
865 backwardExhausted = false,
866 forwardExhausted = false,
868 return function iterator() {
869 if (wantForward && !forwardExhausted) {
870 if (backwardExhausted) {
874 } // Check if trying to fit beyond text length, and if not, check it fits
875 // after offset location (or desired location on first iteration)
878 if (start + localOffset <= maxLine) {
882 forwardExhausted = true;
885 if (!backwardExhausted) {
886 if (!forwardExhausted) {
888 } // Check if trying to fit before text beginning, and if not, check it fits
889 // before offset location
892 if (minLine <= start - localOffset) {
893 return -localOffset++;
896 backwardExhausted = true;
898 } // We tried to fit hunk before text beginning and beyond text length, then
899 // hunk can't fit on the text. Return undefined
904 function applyPatch(source, uniDiff) {
905 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
907 if (typeof uniDiff === 'string') {
908 uniDiff = parsePatch(uniDiff);
911 if (Array.isArray(uniDiff)) {
912 if (uniDiff.length > 1) {
913 throw new Error('applyPatch only works with a single input.');
916 uniDiff = uniDiff[0];
917 } // Apply the diff to the input
920 var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
921 delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
922 hunks = uniDiff.hunks,
923 compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
924 return line === patchContent;
927 fuzzFactor = options.fuzzFactor || 0,
933 * Checks if the hunk exactly fits on the provided location
937 function hunkFits(hunk, toPos) {
938 for (var j = 0; j < hunk.lines.length; j++) {
939 var line = hunk.lines[j],
940 operation = line.length > 0 ? line[0] : ' ',
941 content = line.length > 0 ? line.substr(1) : line;
943 if (operation === ' ' || operation === '-') {
944 // Context sanity check
945 if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
948 if (errorCount > fuzzFactor) {
958 } // Search best fit offsets for each hunk based on the previous ones
961 for (var i = 0; i < hunks.length; i++) {
963 maxLine = lines.length - hunk.oldLines,
965 toPos = offset + hunk.oldStart - 1;
966 var iterator = distanceIterator(toPos, minLine, maxLine);
968 for (; localOffset !== undefined; localOffset = iterator()) {
969 if (hunkFits(hunk, toPos + localOffset)) {
970 hunk.offset = offset += localOffset;
975 if (localOffset === undefined) {
977 } // Set lower text limit to end of the current hunk, so next ones don't try
978 // to fit over already patched text
981 minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
982 } // Apply patch hunks
987 for (var _i = 0; _i < hunks.length; _i++) {
988 var _hunk = hunks[_i],
989 _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
991 diffOffset += _hunk.newLines - _hunk.oldLines;
994 // Creating a new file
998 for (var j = 0; j < _hunk.lines.length; j++) {
999 var line = _hunk.lines[j],
1000 operation = line.length > 0 ? line[0] : ' ',
1001 content = line.length > 0 ? line.substr(1) : line,
1002 delimiter = _hunk.linedelimiters[j];
1004 if (operation === ' ') {
1006 } else if (operation === '-') {
1007 lines.splice(_toPos, 1);
1008 delimiters.splice(_toPos, 1);
1009 /* istanbul ignore else */
1010 } else if (operation === '+') {
1011 lines.splice(_toPos, 0, content);
1012 delimiters.splice(_toPos, 0, delimiter);
1014 } else if (operation === '\\') {
1015 var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
1017 if (previousOperation === '+') {
1019 } else if (previousOperation === '-') {
1024 } // Handle EOFNL insertion/removal
1028 while (!lines[lines.length - 1]) {
1032 } else if (addEOFNL) {
1034 delimiters.push('\n');
1037 for (var _k = 0; _k < lines.length - 1; _k++) {
1038 lines[_k] = lines[_k] + delimiters[_k];
1041 return lines.join('');
1042 } // Wrapper that supports multiple file patches via callbacks.
1045 function applyPatches(uniDiff, options) {
1046 if (typeof uniDiff === 'string') {
1047 uniDiff = parsePatch(uniDiff);
1050 var currentIndex = 0;
1052 function processIndex() {
1053 var index = uniDiff[currentIndex++];
1056 return options.complete();
1059 options.loadFile(index, function (err, data) {
1061 return options.complete(err);
1064 var updatedContent = applyPatch(data, index, options);
1065 options.patched(index, updatedContent, function (err) {
1067 return options.complete(err);
1078 function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1083 if (typeof options.context === 'undefined') {
1084 options.context = 4;
1087 var diff = diffLines(oldStr, newStr, options);
1091 }); // Append an empty value to make cleanup easier
1093 function contextLines(lines) {
1094 return lines.map(function (entry) {
1100 var oldRangeStart = 0,
1106 var _loop = function _loop(i) {
1107 var current = diff[i],
1108 lines = current.lines || current.value.replace(/\n$/, '').split('\n');
1109 current.lines = lines;
1111 if (current.added || current.removed) {
1112 var _curRange; // If we have previous context, start with that
1115 if (!oldRangeStart) {
1116 var prev = diff[i - 1];
1117 oldRangeStart = oldLine;
1118 newRangeStart = newLine;
1121 curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
1122 oldRangeStart -= curRange.length;
1123 newRangeStart -= curRange.length;
1125 } // Output our changes
1128 (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
1129 return (current.added ? '+' : '-') + entry;
1130 }))); // Track the updated file position
1133 if (current.added) {
1134 newLine += lines.length;
1136 oldLine += lines.length;
1139 // Identical context lines. Track line changes
1140 if (oldRangeStart) {
1141 // Close out any changes that have been output (or join overlapping)
1142 if (lines.length <= options.context * 2 && i < diff.length - 2) {
1143 var _curRange2; // Overlapping
1146 (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
1148 var _curRange3; // end the range and output
1151 var contextSize = Math.min(lines.length, options.context);
1153 (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
1156 oldStart: oldRangeStart,
1157 oldLines: oldLine - oldRangeStart + contextSize,
1158 newStart: newRangeStart,
1159 newLines: newLine - newRangeStart + contextSize,
1163 if (i >= diff.length - 2 && lines.length <= options.context) {
1164 // EOF is inside this hunk
1165 var oldEOFNewline = /\n$/.test(oldStr);
1166 var newEOFNewline = /\n$/.test(newStr);
1167 var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
1169 if (!oldEOFNewline && noNlBeforeAdds) {
1170 // special case: old has no eol and no trailing context; no-nl can end up before adds
1171 curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
1174 if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
1175 curRange.push('\\ No newline at end of file');
1186 oldLine += lines.length;
1187 newLine += lines.length;
1191 for (var i = 0; i < diff.length; i++) {
1196 oldFileName: oldFileName,
1197 newFileName: newFileName,
1198 oldHeader: oldHeader,
1199 newHeader: newHeader,
1204 function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1205 var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
1208 if (oldFileName == newFileName) {
1209 ret.push('Index: ' + oldFileName);
1212 ret.push('===================================================================');
1213 ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
1214 ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
1216 for (var i = 0; i < diff.hunks.length; i++) {
1217 var hunk = diff.hunks[i];
1218 ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
1219 ret.push.apply(ret, hunk.lines);
1222 return ret.join('\n') + '\n';
1225 function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
1226 return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
1229 function arrayEqual(a, b) {
1230 if (a.length !== b.length) {
1234 return arrayStartsWith(a, b);
1237 function arrayStartsWith(array, start) {
1238 if (start.length > array.length) {
1242 for (var i = 0; i < start.length; i++) {
1243 if (start[i] !== array[i]) {
1251 function calcLineCount(hunk) {
1252 var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
1253 oldLines = _calcOldNewLineCount.oldLines,
1254 newLines = _calcOldNewLineCount.newLines;
1256 if (oldLines !== undefined) {
1257 hunk.oldLines = oldLines;
1259 delete hunk.oldLines;
1262 if (newLines !== undefined) {
1263 hunk.newLines = newLines;
1265 delete hunk.newLines;
1269 function merge(mine, theirs, base) {
1270 mine = loadPatch(mine, base);
1271 theirs = loadPatch(theirs, base);
1272 var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
1273 // Leaving sanity checks on this to the API consumer that may know more about the
1274 // meaning in their own context.
1276 if (mine.index || theirs.index) {
1277 ret.index = mine.index || theirs.index;
1280 if (mine.newFileName || theirs.newFileName) {
1281 if (!fileNameChanged(mine)) {
1282 // No header or no change in ours, use theirs (and ours if theirs does not exist)
1283 ret.oldFileName = theirs.oldFileName || mine.oldFileName;
1284 ret.newFileName = theirs.newFileName || mine.newFileName;
1285 ret.oldHeader = theirs.oldHeader || mine.oldHeader;
1286 ret.newHeader = theirs.newHeader || mine.newHeader;
1287 } else if (!fileNameChanged(theirs)) {
1288 // No header or no change in theirs, use ours
1289 ret.oldFileName = mine.oldFileName;
1290 ret.newFileName = mine.newFileName;
1291 ret.oldHeader = mine.oldHeader;
1292 ret.newHeader = mine.newHeader;
1294 // Both changed... figure it out
1295 ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
1296 ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
1297 ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
1298 ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
1308 while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
1309 var mineCurrent = mine.hunks[mineIndex] || {
1312 theirsCurrent = theirs.hunks[theirsIndex] || {
1316 if (hunkBefore(mineCurrent, theirsCurrent)) {
1317 // This patch does not overlap with any of the others, yay.
1318 ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
1320 theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
1321 } else if (hunkBefore(theirsCurrent, mineCurrent)) {
1322 // This patch does not overlap with any of the others, yay.
1323 ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
1325 mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
1327 // Overlap, merge as best we can
1329 oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
1331 newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
1335 mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
1338 ret.hunks.push(mergedHunk);
1345 function loadPatch(param, base) {
1346 if (typeof param === 'string') {
1347 if (/^@@/m.test(param) || /^Index:/m.test(param)) {
1348 return parsePatch(param)[0];
1352 throw new Error('Must provide a base reference or pass in a patch');
1355 return structuredPatch(undefined, undefined, base, param);
1361 function fileNameChanged(patch) {
1362 return patch.newFileName && patch.newFileName !== patch.oldFileName;
1365 function selectField(index, mine, theirs) {
1366 if (mine === theirs) {
1369 index.conflict = true;
1377 function hunkBefore(test, check) {
1378 return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
1381 function cloneHunk(hunk, offset) {
1383 oldStart: hunk.oldStart,
1384 oldLines: hunk.oldLines,
1385 newStart: hunk.newStart + offset,
1386 newLines: hunk.newLines,
1391 function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
1392 // This will generally result in a conflicted hunk, but there are cases where the context
1393 // is the only overlap where we can successfully merge the content here.
1400 offset: theirOffset,
1403 }; // Handle any leading content
1405 insertLeading(hunk, mine, their);
1406 insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
1408 while (mine.index < mine.lines.length && their.index < their.lines.length) {
1409 var mineCurrent = mine.lines[mine.index],
1410 theirCurrent = their.lines[their.index];
1412 if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
1413 // Both modified ...
1414 mutualChange(hunk, mine, their);
1415 } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
1416 var _hunk$lines; // Mine inserted
1419 (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
1420 } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
1421 var _hunk$lines2; // Theirs inserted
1424 (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
1425 } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
1426 // Mine removed or edited
1427 removal(hunk, mine, their);
1428 } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
1429 // Their removed or edited
1430 removal(hunk, their, mine, true);
1431 } else if (mineCurrent === theirCurrent) {
1433 hunk.lines.push(mineCurrent);
1438 conflict(hunk, collectChange(mine), collectChange(their));
1440 } // Now push anything that may be remaining
1443 insertTrailing(hunk, mine);
1444 insertTrailing(hunk, their);
1445 calcLineCount(hunk);
1448 function mutualChange(hunk, mine, their) {
1449 var myChanges = collectChange(mine),
1450 theirChanges = collectChange(their);
1452 if (allRemoves(myChanges) && allRemoves(theirChanges)) {
1453 // Special case for remove changes that are supersets of one another
1454 if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
1457 (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
1460 } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
1463 (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
1467 } else if (arrayEqual(myChanges, theirChanges)) {
1470 (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
1475 conflict(hunk, myChanges, theirChanges);
1478 function removal(hunk, mine, their, swap) {
1479 var myChanges = collectChange(mine),
1480 theirChanges = collectContext(their, myChanges);
1482 if (theirChanges.merged) {
1485 (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
1487 conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
1491 function conflict(hunk, mine, their) {
1492 hunk.conflict = true;
1500 function insertLeading(hunk, insert, their) {
1501 while (insert.offset < their.offset && insert.index < insert.lines.length) {
1502 var line = insert.lines[insert.index++];
1503 hunk.lines.push(line);
1508 function insertTrailing(hunk, insert) {
1509 while (insert.index < insert.lines.length) {
1510 var line = insert.lines[insert.index++];
1511 hunk.lines.push(line);
1515 function collectChange(state) {
1517 operation = state.lines[state.index][0];
1519 while (state.index < state.lines.length) {
1520 var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
1522 if (operation === '-' && line[0] === '+') {
1526 if (operation === line[0]) {
1537 function collectContext(state, matchChanges) {
1541 contextChanges = false,
1544 while (matchIndex < matchChanges.length && state.index < state.lines.length) {
1545 var change = state.lines[state.index],
1546 match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
1548 if (match[0] === '+') {
1552 contextChanges = contextChanges || change[0] !== ' ';
1554 matchIndex++; // Consume any additions in the other block as a conflict to attempt
1555 // to pull in the remaining context after this
1557 if (change[0] === '+') {
1560 while (change[0] === '+') {
1561 changes.push(change);
1562 change = state.lines[++state.index];
1566 if (match.substr(1) === change.substr(1)) {
1567 changes.push(change);
1574 if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
1582 while (matchIndex < matchChanges.length) {
1583 merged.push(matchChanges[matchIndex++]);
1592 function allRemoves(changes) {
1593 return changes.reduce(function (prev, change) {
1594 return prev && change[0] === '-';
1598 function skipRemoveSuperset(state, removeChanges, delta) {
1599 for (var i = 0; i < delta; i++) {
1600 var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
1602 if (state.lines[state.index + i] !== ' ' + changeContent) {
1607 state.index += delta;
1611 function calcOldNewLineCount(lines) {
1614 lines.forEach(function (line) {
1615 if (typeof line !== 'string') {
1616 var myCount = calcOldNewLineCount(line.mine);
1617 var theirCount = calcOldNewLineCount(line.theirs);
1619 if (oldLines !== undefined) {
1620 if (myCount.oldLines === theirCount.oldLines) {
1621 oldLines += myCount.oldLines;
1623 oldLines = undefined;
1627 if (newLines !== undefined) {
1628 if (myCount.newLines === theirCount.newLines) {
1629 newLines += myCount.newLines;
1631 newLines = undefined;
1635 if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
1639 if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
1648 } // See: http://code.google.com/p/google-diff-match-patch/wiki/API
1651 function convertChangesToDMP(changes) {
1656 for (var i = 0; i < changes.length; i++) {
1657 change = changes[i];
1661 } else if (change.removed) {
1667 ret.push([operation, change.value]);
1673 function convertChangesToXML(changes) {
1676 for (var i = 0; i < changes.length; i++) {
1677 var change = changes[i];
1681 } else if (change.removed) {
1685 ret.push(escapeHTML(change.value));
1689 } else if (change.removed) {
1694 return ret.join('');
1697 function escapeHTML(s) {
1699 n = n.replace(/&/g, '&');
1700 n = n.replace(/</g, '<');
1701 n = n.replace(/>/g, '>');
1702 n = n.replace(/"/g, '"');
1706 var index_es6 = /*#__PURE__*/Object.freeze({
1709 diffChars: diffChars,
1710 diffWords: diffWords,
1711 diffWordsWithSpace: diffWordsWithSpace,
1712 diffLines: diffLines,
1713 diffTrimmedLines: diffTrimmedLines,
1714 diffSentences: diffSentences,
1717 diffArrays: diffArrays,
1718 structuredPatch: structuredPatch,
1719 createTwoFilesPatch: createTwoFilesPatch,
1720 createPatch: createPatch,
1721 applyPatch: applyPatch,
1722 applyPatches: applyPatches,
1723 parsePatch: parsePatch,
1725 convertChangesToDMP: convertChangesToDMP,
1726 convertChangesToXML: convertChangesToXML,
1727 canonicalize: canonicalize
1731 * normalize-path <https://github.com/jonschlinkert/normalize-path>
1733 * Copyright (c) 2014-2018, Jon Schlinkert.
1734 * Released under the MIT License.
1736 var normalizePath = function normalizePath(path, stripTrailing) {
1737 if (typeof path !== 'string') {
1738 throw new TypeError('expected path to be a string');
1741 if (path === '\\' || path === '/') return '/';
1742 var len = path.length;
1743 if (len <= 1) return path; // ensure that win32 namespaces has two leading slashes, so that the path is
1744 // handled properly by the win32 version of path.parse() after being normalized
1745 // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
1749 if (len > 4 && path[3] === '\\') {
1752 if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
1753 path = path.slice(2);
1758 var segs = path.split(/[/\\]+/);
1760 if (stripTrailing !== false && segs[segs.length - 1] === '') {
1764 return prefix + segs.join('/');
1767 function _classCallCheck(instance, Constructor) {
1768 if (!(instance instanceof Constructor)) {
1769 throw new TypeError("Cannot call a class as a function");
1773 function _defineProperties(target, props) {
1774 for (var i = 0; i < props.length; i++) {
1775 var descriptor = props[i];
1776 descriptor.enumerable = descriptor.enumerable || false;
1777 descriptor.configurable = true;
1778 if ("value" in descriptor) descriptor.writable = true;
1779 Object.defineProperty(target, descriptor.key, descriptor);
1783 function _createClass(Constructor, protoProps, staticProps) {
1784 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
1785 if (staticProps) _defineProperties(Constructor, staticProps);
1789 function _inherits(subClass, superClass) {
1790 if (typeof superClass !== "function" && superClass !== null) {
1791 throw new TypeError("Super expression must either be null or a function");
1794 subClass.prototype = Object.create(superClass && superClass.prototype, {
1801 if (superClass) _setPrototypeOf(subClass, superClass);
1804 function _getPrototypeOf(o) {
1805 _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
1806 return o.__proto__ || Object.getPrototypeOf(o);
1808 return _getPrototypeOf(o);
1811 function _setPrototypeOf(o, p) {
1812 _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
1817 return _setPrototypeOf(o, p);
1820 function isNativeReflectConstruct() {
1821 if (typeof Reflect === "undefined" || !Reflect.construct) return false;
1822 if (Reflect.construct.sham) return false;
1823 if (typeof Proxy === "function") return true;
1826 Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
1833 function _construct(Parent, args, Class) {
1834 if (isNativeReflectConstruct()) {
1835 _construct = Reflect.construct;
1837 _construct = function _construct(Parent, args, Class) {
1839 a.push.apply(a, args);
1840 var Constructor = Function.bind.apply(Parent, a);
1841 var instance = new Constructor();
1842 if (Class) _setPrototypeOf(instance, Class.prototype);
1847 return _construct.apply(null, arguments);
1850 function _isNativeFunction(fn) {
1851 return Function.toString.call(fn).indexOf("[native code]") !== -1;
1854 function _wrapNativeSuper(Class) {
1855 var _cache = typeof Map === "function" ? new Map() : undefined;
1857 _wrapNativeSuper = function _wrapNativeSuper(Class) {
1858 if (Class === null || !_isNativeFunction(Class)) return Class;
1860 if (typeof Class !== "function") {
1861 throw new TypeError("Super expression must either be null or a function");
1864 if (typeof _cache !== "undefined") {
1865 if (_cache.has(Class)) return _cache.get(Class);
1867 _cache.set(Class, Wrapper);
1870 function Wrapper() {
1871 return _construct(Class, arguments, _getPrototypeOf(this).constructor);
1874 Wrapper.prototype = Object.create(Class.prototype, {
1882 return _setPrototypeOf(Wrapper, Class);
1885 return _wrapNativeSuper(Class);
1888 function _assertThisInitialized(self) {
1889 if (self === void 0) {
1890 throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
1896 function _possibleConstructorReturn(self, call) {
1897 if (call && (typeof call === "object" || typeof call === "function")) {
1901 return _assertThisInitialized(self);
1904 function _superPropBase(object, property) {
1905 while (!Object.prototype.hasOwnProperty.call(object, property)) {
1906 object = _getPrototypeOf(object);
1907 if (object === null) break;
1913 function _get(target, property, receiver) {
1914 if (typeof Reflect !== "undefined" && Reflect.get) {
1917 _get = function _get(target, property, receiver) {
1918 var base = _superPropBase(target, property);
1921 var desc = Object.getOwnPropertyDescriptor(base, property);
1924 return desc.get.call(receiver);
1931 return _get(target, property, receiver || target);
1934 function _slicedToArray(arr, i) {
1935 return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
1938 function _toConsumableArray$1(arr) {
1939 return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _nonIterableSpread$1();
1942 function _arrayWithoutHoles$1(arr) {
1943 if (Array.isArray(arr)) {
1944 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
1950 function _arrayWithHoles(arr) {
1951 if (Array.isArray(arr)) return arr;
1954 function _iterableToArray$1(iter) {
1955 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
1958 function _iterableToArrayLimit(arr, i) {
1959 if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
1969 for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
1970 _arr.push(_s.value);
1972 if (i && _arr.length === i) break;
1979 if (!_n && _i["return"] != null) _i["return"]();
1988 function _nonIterableSpread$1() {
1989 throw new TypeError("Invalid attempt to spread non-iterable instance");
1992 function _nonIterableRest() {
1993 throw new TypeError("Invalid attempt to destructure non-iterable instance");
2004 function LineByLine(file, options) {
2005 _classCallCheck(this, LineByLine);
2007 options = options || {};
2008 if (!options.readChunk) options.readChunk = 1024;
2010 if (!options.newLineCharacter) {
2011 options.newLineCharacter = 0x0a; //linux line ending
2013 options.newLineCharacter = options.newLineCharacter.charCodeAt(0);
2016 if (typeof file === 'number') {
2019 this.fd = fs$1.openSync(file, 'r');
2022 this.options = options;
2023 this.newLineCharacter = options.newLineCharacter;
2027 _createClass(LineByLine, [{
2028 key: "_searchInBuffer",
2029 value: function _searchInBuffer(buffer, hexNeedle) {
2032 for (var i = 0; i <= buffer.length; i++) {
2033 var b_byte = buffer[i];
2035 if (b_byte === hexNeedle) {
2045 value: function reset() {
2046 this.eofReached = false;
2047 this.linesCache = [];
2048 this.fdPosition = 0;
2052 value: function close() {
2053 fs$1.closeSync(this.fd);
2057 key: "_extractLines",
2058 value: function _extractLines(buffer) {
2061 var bufferPosition = 0;
2062 var lastNewLineBufferPosition = 0;
2065 var bufferPositionValue = buffer[bufferPosition++];
2067 if (bufferPositionValue === this.newLineCharacter) {
2068 line = buffer.slice(lastNewLineBufferPosition, bufferPosition);
2070 lastNewLineBufferPosition = bufferPosition;
2071 } else if (!bufferPositionValue) {
2076 var leftovers = buffer.slice(lastNewLineBufferPosition, bufferPosition);
2078 if (leftovers.length) {
2079 lines.push(leftovers);
2086 value: function _readChunk(lineLeftovers) {
2087 var totalBytesRead = 0;
2092 var readBuffer = new Buffer(this.options.readChunk);
2093 bytesRead = fs$1.readSync(this.fd, readBuffer, 0, this.options.readChunk, this.fdPosition);
2094 totalBytesRead = totalBytesRead + bytesRead;
2095 this.fdPosition = this.fdPosition + bytesRead;
2096 buffers.push(readBuffer);
2097 } while (bytesRead && this._searchInBuffer(buffers[buffers.length - 1], this.options.newLineCharacter) === -1);
2099 var bufferData = Buffer.concat(buffers);
2101 if (bytesRead < this.options.readChunk) {
2102 this.eofReached = true;
2103 bufferData = bufferData.slice(0, totalBytesRead);
2106 if (totalBytesRead) {
2107 this.linesCache = this._extractLines(bufferData);
2109 if (lineLeftovers) {
2110 this.linesCache[0] = Buffer.concat([lineLeftovers, this.linesCache[0]]);
2114 return totalBytesRead;
2118 value: function next() {
2119 if (!this.fd) return false;
2122 if (this.eofReached && this.linesCache.length === 0) {
2128 if (!this.linesCache.length) {
2129 bytesRead = this._readChunk();
2132 if (this.linesCache.length) {
2133 line = this.linesCache.shift();
2134 var lastLineCharacter = line[line.length - 1];
2136 if (lastLineCharacter !== 0x0a) {
2137 bytesRead = this._readChunk(line);
2140 line = this.linesCache.shift();
2145 if (this.eofReached && this.linesCache.length === 0) {
2149 if (line && line[line.length - 1] === this.newLineCharacter) {
2150 line = line.slice(0, line.length - 1);
2160 var readlines = LineByLine;
2165 _inherits(ConfigError, _Error);
2167 function ConfigError() {
2168 _classCallCheck(this, ConfigError);
2170 return _possibleConstructorReturn(this, _getPrototypeOf(ConfigError).apply(this, arguments));
2174 }(_wrapNativeSuper(Error));
2178 function (_Error2) {
2179 _inherits(DebugError, _Error2);
2181 function DebugError() {
2182 _classCallCheck(this, DebugError);
2184 return _possibleConstructorReturn(this, _getPrototypeOf(DebugError).apply(this, arguments));
2188 }(_wrapNativeSuper(Error));
2190 var UndefinedParserError =
2192 function (_Error3) {
2193 _inherits(UndefinedParserError, _Error3);
2195 function UndefinedParserError() {
2196 _classCallCheck(this, UndefinedParserError);
2198 return _possibleConstructorReturn(this, _getPrototypeOf(UndefinedParserError).apply(this, arguments));
2201 return UndefinedParserError;
2202 }(_wrapNativeSuper(Error));
2207 UndefinedParserError
2210 function unwrapExports (x) {
2211 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
2214 function createCommonjsModule(fn, module) {
2215 return module = { exports: {} }, fn(module, module.exports), module.exports;
2218 function getCjsExportFromNamespace (n) {
2219 return n && n['default'] || n;
2222 var semver = createCommonjsModule(function (module, exports) {
2223 exports = module.exports = SemVer;
2225 /* istanbul ignore next */
2227 if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) {
2228 debug = function debug() {
2229 var args = Array.prototype.slice.call(arguments, 0);
2230 args.unshift('SEMVER');
2231 console.log.apply(console, args);
2234 debug = function debug() {};
2235 } // Note: this is the semver.org version of the spec that it implements
2236 // Not necessarily the package version of this code.
2239 exports.SEMVER_SPEC_VERSION = '2.0.0';
2240 var MAX_LENGTH = 256;
2241 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
2242 /* istanbul ignore next */
2243 9007199254740991; // Max safe segment length for coercion.
2245 var MAX_SAFE_COMPONENT_LENGTH = 16; // The actual regexps go on exports.re
2247 var re = exports.re = [];
2248 var src = exports.src = [];
2249 var t = exports.tokens = {};
2254 } // The following Regular Expressions can be used for tokenizing,
2255 // validating, and parsing SemVer version strings.
2256 // ## Numeric Identifier
2257 // A single `0`, or a non-zero digit followed by zero or more digits.
2260 tok('NUMERICIDENTIFIER');
2261 src[t.NUMERICIDENTIFIER] = '0|[1-9]\\d*';
2262 tok('NUMERICIDENTIFIERLOOSE');
2263 src[t.NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier
2264 // Zero or more digits, followed by a letter or hyphen, and then zero or
2265 // more letters, digits, or hyphens.
2267 tok('NONNUMERICIDENTIFIER');
2268 src[t.NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version
2269 // Three dot-separated numeric identifiers.
2272 src[t.MAINVERSION] = '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')\\.' + '(' + src[t.NUMERICIDENTIFIER] + ')';
2273 tok('MAINVERSIONLOOSE');
2274 src[t.MAINVERSIONLOOSE] = '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[t.NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier
2275 // A numeric identifier, or a non-numeric identifier.
2277 tok('PRERELEASEIDENTIFIER');
2278 src[t.PRERELEASEIDENTIFIER] = '(?:' + src[t.NUMERICIDENTIFIER] + '|' + src[t.NONNUMERICIDENTIFIER] + ')';
2279 tok('PRERELEASEIDENTIFIERLOOSE');
2280 src[t.PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[t.NUMERICIDENTIFIERLOOSE] + '|' + src[t.NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version
2281 // Hyphen, followed by one or more dot-separated pre-release version
2285 src[t.PRERELEASE] = '(?:-(' + src[t.PRERELEASEIDENTIFIER] + '(?:\\.' + src[t.PRERELEASEIDENTIFIER] + ')*))';
2286 tok('PRERELEASELOOSE');
2287 src[t.PRERELEASELOOSE] = '(?:-?(' + src[t.PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[t.PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier
2288 // Any combination of digits, letters, or hyphens.
2290 tok('BUILDIDENTIFIER');
2291 src[t.BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata
2292 // Plus sign, followed by one or more period-separated build metadata
2296 src[t.BUILD] = '(?:\\+(' + src[t.BUILDIDENTIFIER] + '(?:\\.' + src[t.BUILDIDENTIFIER] + ')*))'; // ## Full Version String
2297 // A main version, followed optionally by a pre-release version and
2299 // Note that the only major, minor, patch, and pre-release sections of
2300 // the version string are capturing groups. The build metadata is not a
2301 // capturing group, because it should not ever be used in version
2306 src[t.FULLPLAIN] = 'v?' + src[t.MAINVERSION] + src[t.PRERELEASE] + '?' + src[t.BUILD] + '?';
2307 src[t.FULL] = '^' + src[t.FULLPLAIN] + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
2308 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
2309 // common in the npm registry.
2312 src[t.LOOSEPLAIN] = '[v=\\s]*' + src[t.MAINVERSIONLOOSE] + src[t.PRERELEASELOOSE] + '?' + src[t.BUILD] + '?';
2314 src[t.LOOSE] = '^' + src[t.LOOSEPLAIN] + '$';
2316 src[t.GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x".
2317 // Note that "x.x" is a valid xRange identifer, meaning "any version"
2318 // Only the first item is strictly required.
2320 tok('XRANGEIDENTIFIERLOOSE');
2321 src[t.XRANGEIDENTIFIERLOOSE] = src[t.NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
2322 tok('XRANGEIDENTIFIER');
2323 src[t.XRANGEIDENTIFIER] = src[t.NUMERICIDENTIFIER] + '|x|X|\\*';
2325 src[t.XRANGEPLAIN] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIER] + ')' + '(?:' + src[t.PRERELEASE] + ')?' + src[t.BUILD] + '?' + ')?)?';
2326 tok('XRANGEPLAINLOOSE');
2327 src[t.XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[t.XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[t.PRERELEASELOOSE] + ')?' + src[t.BUILD] + '?' + ')?)?';
2329 src[t.XRANGE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAIN] + '$';
2331 src[t.XRANGELOOSE] = '^' + src[t.GTLT] + '\\s*' + src[t.XRANGEPLAINLOOSE] + '$'; // Coercion.
2332 // Extract anything that could conceivably be a part of a valid semver
2335 src[t.COERCE] = '(^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])';
2337 re[t.COERCERTL] = new RegExp(src[t.COERCE], 'g'); // Tilde ranges.
2338 // Meaning is "reasonably at or greater than"
2341 src[t.LONETILDE] = '(?:~>?)';
2343 src[t.TILDETRIM] = '(\\s*)' + src[t.LONETILDE] + '\\s+';
2344 re[t.TILDETRIM] = new RegExp(src[t.TILDETRIM], 'g');
2345 var tildeTrimReplace = '$1~';
2347 src[t.TILDE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAIN] + '$';
2349 src[t.TILDELOOSE] = '^' + src[t.LONETILDE] + src[t.XRANGEPLAINLOOSE] + '$'; // Caret ranges.
2350 // Meaning is "at least and backwards compatible with"
2353 src[t.LONECARET] = '(?:\\^)';
2355 src[t.CARETTRIM] = '(\\s*)' + src[t.LONECARET] + '\\s+';
2356 re[t.CARETTRIM] = new RegExp(src[t.CARETTRIM], 'g');
2357 var caretTrimReplace = '$1^';
2359 src[t.CARET] = '^' + src[t.LONECARET] + src[t.XRANGEPLAIN] + '$';
2361 src[t.CARETLOOSE] = '^' + src[t.LONECARET] + src[t.XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version"
2363 tok('COMPARATORLOOSE');
2364 src[t.COMPARATORLOOSE] = '^' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + ')$|^$';
2366 src[t.COMPARATOR] = '^' + src[t.GTLT] + '\\s*(' + src[t.FULLPLAIN] + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing
2367 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
2369 tok('COMPARATORTRIM');
2370 src[t.COMPARATORTRIM] = '(\\s*)' + src[t.GTLT] + '\\s*(' + src[t.LOOSEPLAIN] + '|' + src[t.XRANGEPLAIN] + ')'; // this one has to use the /g flag
2372 re[t.COMPARATORTRIM] = new RegExp(src[t.COMPARATORTRIM], 'g');
2373 var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
2374 // Note that these all use the loose form, because they'll be
2375 // checked against either the strict or loose comparator form
2379 src[t.HYPHENRANGE] = '^\\s*(' + src[t.XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAIN] + ')' + '\\s*$';
2380 tok('HYPHENRANGELOOSE');
2381 src[t.HYPHENRANGELOOSE] = '^\\s*(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[t.XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all.
2384 src[t.STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects.
2385 // All are flag-free, unless they were created above with a flag.
2387 for (var i = 0; i < R; i++) {
2391 re[i] = new RegExp(src[i]);
2395 exports.parse = parse;
2397 function parse(version, options) {
2398 if (!options || typeof options !== 'object') {
2401 includePrerelease: false
2405 if (version instanceof SemVer) {
2409 if (typeof version !== 'string') {
2413 if (version.length > MAX_LENGTH) {
2417 var r = options.loose ? re[t.LOOSE] : re[t.FULL];
2419 if (!r.test(version)) {
2424 return new SemVer(version, options);
2430 exports.valid = valid;
2432 function valid(version, options) {
2433 var v = parse(version, options);
2434 return v ? v.version : null;
2437 exports.clean = clean;
2439 function clean(version, options) {
2440 var s = parse(version.trim().replace(/^[=v]+/, ''), options);
2441 return s ? s.version : null;
2444 exports.SemVer = SemVer;
2446 function SemVer(version, options) {
2447 if (!options || typeof options !== 'object') {
2450 includePrerelease: false
2454 if (version instanceof SemVer) {
2455 if (version.loose === options.loose) {
2458 version = version.version;
2460 } else if (typeof version !== 'string') {
2461 throw new TypeError('Invalid Version: ' + version);
2464 if (version.length > MAX_LENGTH) {
2465 throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters');
2468 if (!(this instanceof SemVer)) {
2469 return new SemVer(version, options);
2472 debug('SemVer', version, options);
2473 this.options = options;
2474 this.loose = !!options.loose;
2475 var m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
2478 throw new TypeError('Invalid Version: ' + version);
2481 this.raw = version; // these are actually numbers
2487 if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
2488 throw new TypeError('Invalid major version');
2491 if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
2492 throw new TypeError('Invalid minor version');
2495 if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
2496 throw new TypeError('Invalid patch version');
2497 } // numberify any prerelease numeric ids
2501 this.prerelease = [];
2503 this.prerelease = m[4].split('.').map(function (id) {
2504 if (/^[0-9]+$/.test(id)) {
2507 if (num >= 0 && num < MAX_SAFE_INTEGER) {
2516 this.build = m[5] ? m[5].split('.') : [];
2520 SemVer.prototype.format = function () {
2521 this.version = this.major + '.' + this.minor + '.' + this.patch;
2523 if (this.prerelease.length) {
2524 this.version += '-' + this.prerelease.join('.');
2527 return this.version;
2530 SemVer.prototype.toString = function () {
2531 return this.version;
2534 SemVer.prototype.compare = function (other) {
2535 debug('SemVer.compare', this.version, this.options, other);
2537 if (!(other instanceof SemVer)) {
2538 other = new SemVer(other, this.options);
2541 return this.compareMain(other) || this.comparePre(other);
2544 SemVer.prototype.compareMain = function (other) {
2545 if (!(other instanceof SemVer)) {
2546 other = new SemVer(other, this.options);
2549 return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
2552 SemVer.prototype.comparePre = function (other) {
2553 if (!(other instanceof SemVer)) {
2554 other = new SemVer(other, this.options);
2555 } // NOT having a prerelease is > having one
2558 if (this.prerelease.length && !other.prerelease.length) {
2560 } else if (!this.prerelease.length && other.prerelease.length) {
2562 } else if (!this.prerelease.length && !other.prerelease.length) {
2569 var a = this.prerelease[i];
2570 var b = other.prerelease[i];
2571 debug('prerelease compare', i, a, b);
2573 if (a === undefined && b === undefined) {
2575 } else if (b === undefined) {
2577 } else if (a === undefined) {
2579 } else if (a === b) {
2582 return compareIdentifiers(a, b);
2587 SemVer.prototype.compareBuild = function (other) {
2588 if (!(other instanceof SemVer)) {
2589 other = new SemVer(other, this.options);
2595 var a = this.build[i];
2596 var b = other.build[i];
2597 debug('prerelease compare', i, a, b);
2599 if (a === undefined && b === undefined) {
2601 } else if (b === undefined) {
2603 } else if (a === undefined) {
2605 } else if (a === b) {
2608 return compareIdentifiers(a, b);
2611 }; // preminor will bump the version up to the next minor release, and immediately
2612 // down to pre-release. premajor and prepatch work the same way.
2615 SemVer.prototype.inc = function (release, identifier) {
2618 this.prerelease.length = 0;
2622 this.inc('pre', identifier);
2626 this.prerelease.length = 0;
2629 this.inc('pre', identifier);
2633 // If this is already a prerelease, it will bump to the next version
2634 // drop any prereleases that might already exist, since they are not
2635 // relevant at this point.
2636 this.prerelease.length = 0;
2637 this.inc('patch', identifier);
2638 this.inc('pre', identifier);
2640 // If the input is a non-prerelease version, this acts the same as
2644 if (this.prerelease.length === 0) {
2645 this.inc('patch', identifier);
2648 this.inc('pre', identifier);
2652 // If this is a pre-major version, bump up to the same major version.
2653 // Otherwise increment major.
2654 // 1.0.0-5 bumps to 1.0.0
2655 // 1.1.0 bumps to 2.0.0
2656 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
2662 this.prerelease = [];
2666 // If this is a pre-minor version, bump up to the same minor version.
2667 // Otherwise increment minor.
2668 // 1.2.0-5 bumps to 1.2.0
2669 // 1.2.1 bumps to 1.3.0
2670 if (this.patch !== 0 || this.prerelease.length === 0) {
2675 this.prerelease = [];
2679 // If this is not a pre-release version, it will increment the patch.
2680 // If it is a pre-release it will bump up to the same patch version.
2681 // 1.2.0-5 patches to 1.2.0
2682 // 1.2.0 patches to 1.2.1
2683 if (this.prerelease.length === 0) {
2687 this.prerelease = [];
2689 // This probably shouldn't be used publicly.
2690 // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
2693 if (this.prerelease.length === 0) {
2694 this.prerelease = [0];
2696 var i = this.prerelease.length;
2699 if (typeof this.prerelease[i] === 'number') {
2700 this.prerelease[i]++;
2706 // didn't increment anything
2707 this.prerelease.push(0);
2712 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
2713 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
2714 if (this.prerelease[0] === identifier) {
2715 if (isNaN(this.prerelease[1])) {
2716 this.prerelease = [identifier, 0];
2719 this.prerelease = [identifier, 0];
2726 throw new Error('invalid increment argument: ' + release);
2730 this.raw = this.version;
2736 function inc(version, release, loose, identifier) {
2737 if (typeof loose === 'string') {
2743 return new SemVer(version, loose).inc(release, identifier).version;
2749 exports.diff = diff;
2751 function diff(version1, version2) {
2752 if (eq(version1, version2)) {
2755 var v1 = parse(version1);
2756 var v2 = parse(version2);
2759 if (v1.prerelease.length || v2.prerelease.length) {
2761 var defaultResult = 'prerelease';
2764 for (var key in v1) {
2765 if (key === 'major' || key === 'minor' || key === 'patch') {
2766 if (v1[key] !== v2[key]) {
2767 return prefix + key;
2772 return defaultResult; // may be undefined
2776 exports.compareIdentifiers = compareIdentifiers;
2777 var numeric = /^[0-9]+$/;
2779 function compareIdentifiers(a, b) {
2780 var anum = numeric.test(a);
2781 var bnum = numeric.test(b);
2788 return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
2791 exports.rcompareIdentifiers = rcompareIdentifiers;
2793 function rcompareIdentifiers(a, b) {
2794 return compareIdentifiers(b, a);
2797 exports.major = major;
2799 function major(a, loose) {
2800 return new SemVer(a, loose).major;
2803 exports.minor = minor;
2805 function minor(a, loose) {
2806 return new SemVer(a, loose).minor;
2809 exports.patch = patch;
2811 function patch(a, loose) {
2812 return new SemVer(a, loose).patch;
2815 exports.compare = compare;
2817 function compare(a, b, loose) {
2818 return new SemVer(a, loose).compare(new SemVer(b, loose));
2821 exports.compareLoose = compareLoose;
2823 function compareLoose(a, b) {
2824 return compare(a, b, true);
2827 exports.compareBuild = compareBuild;
2829 function compareBuild(a, b, loose) {
2830 var versionA = new SemVer(a, loose);
2831 var versionB = new SemVer(b, loose);
2832 return versionA.compare(versionB) || versionA.compareBuild(versionB);
2835 exports.rcompare = rcompare;
2837 function rcompare(a, b, loose) {
2838 return compare(b, a, loose);
2841 exports.sort = sort;
2843 function sort(list, loose) {
2844 return list.sort(function (a, b) {
2845 return exports.compareBuild(a, b, loose);
2849 exports.rsort = rsort;
2851 function rsort(list, loose) {
2852 return list.sort(function (a, b) {
2853 return exports.compareBuild(b, a, loose);
2859 function gt(a, b, loose) {
2860 return compare(a, b, loose) > 0;
2865 function lt(a, b, loose) {
2866 return compare(a, b, loose) < 0;
2871 function eq(a, b, loose) {
2872 return compare(a, b, loose) === 0;
2877 function neq(a, b, loose) {
2878 return compare(a, b, loose) !== 0;
2883 function gte(a, b, loose) {
2884 return compare(a, b, loose) >= 0;
2889 function lte(a, b, loose) {
2890 return compare(a, b, loose) <= 0;
2895 function cmp(a, op, b, loose) {
2898 if (typeof a === 'object') a = a.version;
2899 if (typeof b === 'object') b = b.version;
2903 if (typeof a === 'object') a = a.version;
2904 if (typeof b === 'object') b = b.version;
2910 return eq(a, b, loose);
2913 return neq(a, b, loose);
2916 return gt(a, b, loose);
2919 return gte(a, b, loose);
2922 return lt(a, b, loose);
2925 return lte(a, b, loose);
2928 throw new TypeError('Invalid operator: ' + op);
2932 exports.Comparator = Comparator;
2934 function Comparator(comp, options) {
2935 if (!options || typeof options !== 'object') {
2938 includePrerelease: false
2942 if (comp instanceof Comparator) {
2943 if (comp.loose === !!options.loose) {
2950 if (!(this instanceof Comparator)) {
2951 return new Comparator(comp, options);
2954 debug('comparator', comp, options);
2955 this.options = options;
2956 this.loose = !!options.loose;
2959 if (this.semver === ANY) {
2962 this.value = this.operator + this.semver.version;
2965 debug('comp', this);
2970 Comparator.prototype.parse = function (comp) {
2971 var r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
2972 var m = comp.match(r);
2975 throw new TypeError('Invalid comparator: ' + comp);
2978 this.operator = m[1] !== undefined ? m[1] : '';
2980 if (this.operator === '=') {
2982 } // if it literally is just '>' or '' then allow anything.
2988 this.semver = new SemVer(m[2], this.options.loose);
2992 Comparator.prototype.toString = function () {
2996 Comparator.prototype.test = function (version) {
2997 debug('Comparator.test', version, this.options.loose);
2999 if (this.semver === ANY || version === ANY) {
3003 if (typeof version === 'string') {
3005 version = new SemVer(version, this.options);
3011 return cmp(version, this.operator, this.semver, this.options);
3014 Comparator.prototype.intersects = function (comp, options) {
3015 if (!(comp instanceof Comparator)) {
3016 throw new TypeError('a Comparator is required');
3019 if (!options || typeof options !== 'object') {
3022 includePrerelease: false
3028 if (this.operator === '') {
3029 if (this.value === '') {
3033 rangeTmp = new Range(comp.value, options);
3034 return satisfies(this.value, rangeTmp, options);
3035 } else if (comp.operator === '') {
3036 if (comp.value === '') {
3040 rangeTmp = new Range(this.value, options);
3041 return satisfies(comp.semver, rangeTmp, options);
3044 var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>');
3045 var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<');
3046 var sameSemVer = this.semver.version === comp.semver.version;
3047 var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=');
3048 var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<');
3049 var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>');
3050 return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
3053 exports.Range = Range;
3055 function Range(range, options) {
3056 if (!options || typeof options !== 'object') {
3059 includePrerelease: false
3063 if (range instanceof Range) {
3064 if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
3067 return new Range(range.raw, options);
3071 if (range instanceof Comparator) {
3072 return new Range(range.value, options);
3075 if (!(this instanceof Range)) {
3076 return new Range(range, options);
3079 this.options = options;
3080 this.loose = !!options.loose;
3081 this.includePrerelease = !!options.includePrerelease; // First, split based on boolean or ||
3084 this.set = range.split(/\s*\|\|\s*/).map(function (range) {
3085 return this.parseRange(range.trim());
3086 }, this).filter(function (c) {
3087 // throw out any that are not relevant for whatever reason
3091 if (!this.set.length) {
3092 throw new TypeError('Invalid SemVer Range: ' + range);
3098 Range.prototype.format = function () {
3099 this.range = this.set.map(function (comps) {
3100 return comps.join(' ').trim();
3101 }).join('||').trim();
3105 Range.prototype.toString = function () {
3109 Range.prototype.parseRange = function (range) {
3110 var loose = this.options.loose;
3111 range = range.trim(); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
3113 var hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
3114 range = range.replace(hr, hyphenReplace);
3115 debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
3117 range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
3118 debug('comparator trim', range, re[t.COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3`
3120 range = range.replace(re[t.TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3`
3122 range = range.replace(re[t.CARETTRIM], caretTrimReplace); // normalize spaces
3124 range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and
3125 // ready to be split into comparators.
3127 var compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
3128 var set = range.split(' ').map(function (comp) {
3129 return parseComparator(comp, this.options);
3130 }, this).join(' ').split(/\s+/);
3132 if (this.options.loose) {
3133 // in loose mode, throw out any that are not valid comparators
3134 set = set.filter(function (comp) {
3135 return !!comp.match(compRe);
3139 set = set.map(function (comp) {
3140 return new Comparator(comp, this.options);
3145 Range.prototype.intersects = function (range, options) {
3146 if (!(range instanceof Range)) {
3147 throw new TypeError('a Range is required');
3150 return this.set.some(function (thisComparators) {
3151 return isSatisfiable(thisComparators, options) && range.set.some(function (rangeComparators) {
3152 return isSatisfiable(rangeComparators, options) && thisComparators.every(function (thisComparator) {
3153 return rangeComparators.every(function (rangeComparator) {
3154 return thisComparator.intersects(rangeComparator, options);
3159 }; // take a set of comparators and determine whether there
3160 // exists a version which can satisfy it
3163 function isSatisfiable(comparators, options) {
3165 var remainingComparators = comparators.slice();
3166 var testComparator = remainingComparators.pop();
3168 while (result && remainingComparators.length) {
3169 result = remainingComparators.every(function (otherComparator) {
3170 return testComparator.intersects(otherComparator, options);
3172 testComparator = remainingComparators.pop();
3176 } // Mostly just for testing and legacy API reasons
3179 exports.toComparators = toComparators;
3181 function toComparators(range, options) {
3182 return new Range(range, options).set.map(function (comp) {
3183 return comp.map(function (c) {
3185 }).join(' ').trim().split(' ');
3187 } // comprised of xranges, tildes, stars, and gtlt's at this point.
3188 // already replaced the hyphen ranges
3189 // turn into a set of JUST comparators.
3192 function parseComparator(comp, options) {
3193 debug('comp', comp, options);
3194 comp = replaceCarets(comp, options);
3195 debug('caret', comp);
3196 comp = replaceTildes(comp, options);
3197 debug('tildes', comp);
3198 comp = replaceXRanges(comp, options);
3199 debug('xrange', comp);
3200 comp = replaceStars(comp, options);
3201 debug('stars', comp);
3206 return !id || id.toLowerCase() === 'x' || id === '*';
3207 } // ~, ~> --> * (any, kinda silly)
3208 // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
3209 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
3210 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
3211 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
3212 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
3215 function replaceTildes(comp, options) {
3216 return comp.trim().split(/\s+/).map(function (comp) {
3217 return replaceTilde(comp, options);
3221 function replaceTilde(comp, options) {
3222 var r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
3223 return comp.replace(r, function (_, M, m, p, pr) {
3224 debug('tilde', comp, _, M, m, p, pr);
3229 } else if (isX(m)) {
3230 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
3231 } else if (isX(p)) {
3232 // ~1.2 == >=1.2.0 <1.3.0
3233 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
3235 debug('replaceTilde pr', pr);
3236 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0';
3238 // ~1.2.3 == >=1.2.3 <1.3.0
3239 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
3242 debug('tilde return', ret);
3245 } // ^ --> * (any, kinda silly)
3246 // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
3247 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
3248 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
3249 // ^1.2.3 --> >=1.2.3 <2.0.0
3250 // ^1.2.0 --> >=1.2.0 <2.0.0
3253 function replaceCarets(comp, options) {
3254 return comp.trim().split(/\s+/).map(function (comp) {
3255 return replaceCaret(comp, options);
3259 function replaceCaret(comp, options) {
3260 debug('caret', comp, options);
3261 var r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
3262 return comp.replace(r, function (_, M, m, p, pr) {
3263 debug('caret', comp, _, M, m, p, pr);
3268 } else if (isX(m)) {
3269 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
3270 } else if (isX(p)) {
3272 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
3274 ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
3277 debug('replaceCaret pr', pr);
3281 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1);
3283 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0';
3286 ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0';
3293 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1);
3295 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
3298 ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0';
3302 debug('caret return', ret);
3307 function replaceXRanges(comp, options) {
3308 debug('replaceXRanges', comp, options);
3309 return comp.split(/\s+/).map(function (comp) {
3310 return replaceXRange(comp, options);
3314 function replaceXRange(comp, options) {
3316 var r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
3317 return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
3318 debug('xRange', comp, ret, gtlt, M, m, p, pr);
3320 var xm = xM || isX(m);
3321 var xp = xm || isX(p);
3324 if (gtlt === '=' && anyX) {
3326 } // if we're including prereleases in the match, then we need
3327 // to fix this to -0, the lowest possible prerelease value
3330 pr = options.includePrerelease ? '-0' : '';
3333 if (gtlt === '>' || gtlt === '<') {
3334 // nothing is allowed
3337 // nothing is forbidden
3340 } else if (gtlt && anyX) {
3341 // we know patch is an x, because we have any x at all.
3352 // >1.2.3 => >= 1.2.4
3363 } else if (gtlt === '<=') {
3364 // <=0.7.x is actually <0.8.0, since any 0.7.x should
3365 // pass. Similarly, <=7.x is actually <8.0.0, etc.
3375 ret = gtlt + M + '.' + m + '.' + p + pr;
3377 ret = '>=' + M + '.0.0' + pr + ' <' + (+M + 1) + '.0.0' + pr;
3379 ret = '>=' + M + '.' + m + '.0' + pr + ' <' + M + '.' + (+m + 1) + '.0' + pr;
3382 debug('xRange return', ret);
3385 } // Because * is AND-ed with everything else in the comparator,
3386 // and '' means "any version", just remove the *s entirely.
3389 function replaceStars(comp, options) {
3390 debug('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets!
3392 return comp.trim().replace(re[t.STAR], '');
3393 } // This function is passed to string.replace(re[t.HYPHENRANGE])
3394 // M, m, patch, prerelease, build
3395 // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
3396 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
3397 // 1.2 - 3.4 => >=1.2.0 <3.5.0
3400 function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
3403 } else if (isX(fm)) {
3404 from = '>=' + fM + '.0.0';
3405 } else if (isX(fp)) {
3406 from = '>=' + fM + '.' + fm + '.0';
3413 } else if (isX(tm)) {
3414 to = '<' + (+tM + 1) + '.0.0';
3415 } else if (isX(tp)) {
3416 to = '<' + tM + '.' + (+tm + 1) + '.0';
3418 to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr;
3423 return (from + ' ' + to).trim();
3424 } // if ANY of the sets match ALL of its comparators, then pass
3427 Range.prototype.test = function (version) {
3432 if (typeof version === 'string') {
3434 version = new SemVer(version, this.options);
3440 for (var i = 0; i < this.set.length; i++) {
3441 if (testSet(this.set[i], version, this.options)) {
3449 function testSet(set, version, options) {
3450 for (var i = 0; i < set.length; i++) {
3451 if (!set[i].test(version)) {
3456 if (version.prerelease.length && !options.includePrerelease) {
3457 // Find the set of versions that are allowed to have prereleases
3458 // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
3459 // That should allow `1.2.3-pr.2` to pass.
3460 // However, `1.2.4-alpha.notready` should NOT be allowed,
3461 // even though it's within the range set by the comparators.
3462 for (i = 0; i < set.length; i++) {
3463 debug(set[i].semver);
3465 if (set[i].semver === ANY) {
3469 if (set[i].semver.prerelease.length > 0) {
3470 var allowed = set[i].semver;
3472 if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
3476 } // Version has a -pre, but it's not one of the ones we like.
3485 exports.satisfies = satisfies;
3487 function satisfies(version, range, options) {
3489 range = new Range(range, options);
3494 return range.test(version);
3497 exports.maxSatisfying = maxSatisfying;
3499 function maxSatisfying(versions, range, options) {
3504 var rangeObj = new Range(range, options);
3509 versions.forEach(function (v) {
3510 if (rangeObj.test(v)) {
3511 // satisfies(v, range, options)
3512 if (!max || maxSV.compare(v) === -1) {
3513 // compare(max, v, true)
3515 maxSV = new SemVer(max, options);
3522 exports.minSatisfying = minSatisfying;
3524 function minSatisfying(versions, range, options) {
3529 var rangeObj = new Range(range, options);
3534 versions.forEach(function (v) {
3535 if (rangeObj.test(v)) {
3536 // satisfies(v, range, options)
3537 if (!min || minSV.compare(v) === 1) {
3538 // compare(min, v, true)
3540 minSV = new SemVer(min, options);
3547 exports.minVersion = minVersion;
3549 function minVersion(range, loose) {
3550 range = new Range(range, loose);
3551 var minver = new SemVer('0.0.0');
3553 if (range.test(minver)) {
3557 minver = new SemVer('0.0.0-0');
3559 if (range.test(minver)) {
3565 for (var i = 0; i < range.set.length; ++i) {
3566 var comparators = range.set[i];
3567 comparators.forEach(function (comparator) {
3568 // Clone to avoid manipulating the comparator's semver object.
3569 var compver = new SemVer(comparator.semver.version);
3571 switch (comparator.operator) {
3573 if (compver.prerelease.length === 0) {
3576 compver.prerelease.push(0);
3579 compver.raw = compver.format();
3585 if (!minver || gt(minver, compver)) {
3593 /* Ignore maximum versions */
3596 /* istanbul ignore next */
3599 throw new Error('Unexpected operation: ' + comparator.operator);
3604 if (minver && range.test(minver)) {
3611 exports.validRange = validRange;
3613 function validRange(range, options) {
3615 // Return '*' instead of '' so that truthiness works.
3616 // This will throw if it's invalid anyway
3617 return new Range(range, options).range || '*';
3621 } // Determine if version is less than all the versions possible in the range
3626 function ltr(version, range, options) {
3627 return outside(version, range, '<', options);
3628 } // Determine if version is greater than all the versions possible in the range.
3633 function gtr(version, range, options) {
3634 return outside(version, range, '>', options);
3637 exports.outside = outside;
3639 function outside(version, range, hilo, options) {
3640 version = new SemVer(version, options);
3641 range = new Range(range, options);
3642 var gtfn, ltefn, ltfn, comp, ecomp;
3662 throw new TypeError('Must provide a hilo val of "<" or ">"');
3663 } // If it satisifes the range it is not outside
3666 if (satisfies(version, range, options)) {
3668 } // From now on, variable terms are as if we're in "gtr" mode.
3669 // but note that everything is flipped for the "ltr" function.
3672 for (var i = 0; i < range.set.length; ++i) {
3673 var comparators = range.set[i];
3676 comparators.forEach(function (comparator) {
3677 if (comparator.semver === ANY) {
3678 comparator = new Comparator('>=0.0.0');
3681 high = high || comparator;
3682 low = low || comparator;
3684 if (gtfn(comparator.semver, high.semver, options)) {
3686 } else if (ltfn(comparator.semver, low.semver, options)) {
3689 }); // If the edge version comparator has a operator then our version
3692 if (high.operator === comp || high.operator === ecomp) {
3694 } // If the lowest version comparator has an operator and our version
3695 // is less than it then it isn't higher than the range
3698 if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
3700 } else if (low.operator === ecomp && ltfn(version, low.semver)) {
3708 exports.prerelease = prerelease;
3710 function prerelease(version, options) {
3711 var parsed = parse(version, options);
3712 return parsed && parsed.prerelease.length ? parsed.prerelease : null;
3715 exports.intersects = intersects;
3717 function intersects(r1, r2, options) {
3718 r1 = new Range(r1, options);
3719 r2 = new Range(r2, options);
3720 return r1.intersects(r2);
3723 exports.coerce = coerce;
3725 function coerce(version, options) {
3726 if (version instanceof SemVer) {
3730 if (typeof version === 'number') {
3731 version = String(version);
3734 if (typeof version !== 'string') {
3738 options = options || {};
3742 match = version.match(re[t.COERCE]);
3744 // Find the right-most coercible string that does not share
3745 // a terminus with a more left-ward coercible string.
3746 // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
3748 // Walk through the string checking with a /g regexp
3749 // Manually set the index so as to pick up overlapping matches.
3750 // Stop when we get a match that ends at the string end, since no
3751 // coercible string can be more right-ward without the same terminus.
3754 while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) {
3755 if (!match || next.index + next[0].length !== match.index + match[0].length) {
3759 re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
3760 } // leave it in a clean state
3763 re[t.COERCERTL].lastIndex = -1;
3766 if (match === null) {
3770 return parse(match[2] + '.' + (match[3] || '0') + '.' + (match[4] || '0'), options);
3773 var semver_1 = semver.SEMVER_SPEC_VERSION;
3774 var semver_2 = semver.re;
3775 var semver_3 = semver.src;
3776 var semver_4 = semver.tokens;
3777 var semver_5 = semver.parse;
3778 var semver_6 = semver.valid;
3779 var semver_7 = semver.clean;
3780 var semver_8 = semver.SemVer;
3781 var semver_9 = semver.inc;
3782 var semver_10 = semver.diff;
3783 var semver_11 = semver.compareIdentifiers;
3784 var semver_12 = semver.rcompareIdentifiers;
3785 var semver_13 = semver.major;
3786 var semver_14 = semver.minor;
3787 var semver_15 = semver.patch;
3788 var semver_16 = semver.compare;
3789 var semver_17 = semver.compareLoose;
3790 var semver_18 = semver.compareBuild;
3791 var semver_19 = semver.rcompare;
3792 var semver_20 = semver.sort;
3793 var semver_21 = semver.rsort;
3794 var semver_22 = semver.gt;
3795 var semver_23 = semver.lt;
3796 var semver_24 = semver.eq;
3797 var semver_25 = semver.neq;
3798 var semver_26 = semver.gte;
3799 var semver_27 = semver.lte;
3800 var semver_28 = semver.cmp;
3801 var semver_29 = semver.Comparator;
3802 var semver_30 = semver.Range;
3803 var semver_31 = semver.toComparators;
3804 var semver_32 = semver.satisfies;
3805 var semver_33 = semver.maxSatisfying;
3806 var semver_34 = semver.minSatisfying;
3807 var semver_35 = semver.minVersion;
3808 var semver_36 = semver.validRange;
3809 var semver_37 = semver.ltr;
3810 var semver_38 = semver.gtr;
3811 var semver_39 = semver.outside;
3812 var semver_40 = semver.prerelease;
3813 var semver_41 = semver.intersects;
3814 var semver_42 = semver.coerce;
3816 var arrayify = function arrayify(object, keyName) {
3817 return Object.keys(object).reduce(function (array, key) {
3818 return array.concat(Object.assign({
3824 var dedent_1 = createCommonjsModule(function (module) {
3826 function dedent(strings) {
3829 if (typeof strings === "string") {
3830 // dedent can be used as a plain function
3834 } // first, perform interpolation
3839 for (var i = 0; i < raw.length; i++) {
3840 result += raw[i]. // join lines when there is a suppressed newline
3841 replace(/\\\n[ \t]*/g, ""). // handle escaped backticks
3842 replace(/\\`/g, "`");
3844 if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) {
3845 result += arguments.length <= i + 1 ? undefined : arguments[i + 1];
3847 } // now strip indentation
3850 var lines = result.split("\n");
3852 lines.forEach(function (l) {
3853 var m = l.match(/^(\s+)\S+/);
3856 var indent = m[1].length;
3859 // this is the first indented line
3862 mindent = Math.min(mindent, indent);
3867 if (mindent !== null) {
3868 result = lines.map(function (l) {
3869 return l[0] === " " ? l.slice(mindent) : l;
3871 } // dedent eats leading and trailing whitespace too
3874 result = result.trim(); // handle escaped newlines at the end to ensure they don't get stripped too
3876 return result.replace(/\\n/g, "\n");
3880 module.exports = dedent;
3884 var CATEGORY_CONFIG = "Config";
3885 var CATEGORY_EDITOR = "Editor";
3886 var CATEGORY_FORMAT = "Format";
3887 var CATEGORY_OTHER = "Other";
3888 var CATEGORY_OUTPUT = "Output";
3889 var CATEGORY_GLOBAL = "Global";
3890 var CATEGORY_SPECIAL = "Special";
3892 * @typedef {Object} OptionInfo
3893 * @property {string} [since] - available since version
3894 * @property {string} category
3895 * @property {'int' | 'boolean' | 'choice' | 'path'} type
3896 * @property {boolean} [array] - indicate it's an array of the specified type
3897 * @property {OptionValueInfo} [default]
3898 * @property {OptionRangeInfo} [range] - for type int
3899 * @property {string} description
3900 * @property {string} [deprecated] - deprecated since version
3901 * @property {OptionRedirectInfo} [redirect] - redirect deprecated option
3902 * @property {(value: any) => boolean} [exception]
3903 * @property {OptionChoiceInfo[]} [choices] - for type choice
3904 * @property {string} [cliName]
3905 * @property {string} [cliCategory]
3906 * @property {string} [cliDescription]
3908 * @typedef {number | boolean | string} OptionValue
3909 * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo
3911 * @typedef {Object} OptionRedirectInfo
3912 * @property {string} option
3913 * @property {OptionValue} value
3915 * @typedef {Object} OptionRangeInfo
3916 * @property {number} start - recommended range start
3917 * @property {number} end - recommended range end
3918 * @property {number} step - recommended range step
3920 * @typedef {Object} OptionChoiceInfo
3921 * @property {boolean | string} value - boolean for the option that is originally boolean type
3922 * @property {string} description
3923 * @property {string} [since] - undefined if available since the first version of the option
3924 * @property {string} [deprecated] - deprecated since version
3925 * @property {OptionValueInfo} [redirect] - redirect deprecated value
3928 /** @type {{ [name: string]: OptionInfo }} */
3933 category: CATEGORY_SPECIAL,
3941 description: dedent_1`
3942 Print (to stderr) where a cursor at the given position would move to after formatting.
3943 This option cannot be used with --range-start and --range-end.
3945 cliCategory: CATEGORY_EDITOR
3949 category: CATEGORY_GLOBAL,
3952 description: "Which end of line characters to apply.",
3955 description: dedent_1`
3957 (mixed values within one file are normalised by looking at what's used after the first line)
3961 description: "Line Feed only (\\n), common on Linux and macOS as well as inside git repos"
3964 description: "Carriage Return + Line Feed characters (\\r\\n), common on Windows"
3967 description: "Carriage Return character only (\\r), used very rarely"
3972 category: CATEGORY_SPECIAL,
3974 description: "Specify the input filepath. This will be used to do parser inference.",
3975 cliName: "stdin-filepath",
3976 cliCategory: CATEGORY_OTHER,
3977 cliDescription: "Path to the file to pretend that stdin comes from."
3981 category: CATEGORY_SPECIAL,
3984 description: "Insert @format pragma into file's first docblock comment.",
3985 cliCategory: CATEGORY_OTHER
3989 category: CATEGORY_GLOBAL,
3998 description: "Which parser to use.",
3999 exception: function exception(value) {
4000 return typeof value === "string" || typeof value === "function";
4007 description: "JavaScript",
4008 deprecated: "1.16.0",
4013 description: "JavaScript"
4015 value: "babel-flow",
4019 value: "typescript",
4021 description: "TypeScript"
4029 description: "CSS/Less/SCSS",
4030 deprecated: "1.7.1",
4047 description: "JSON5"
4049 value: "json-stringify",
4051 description: "JSON.stringify"
4055 description: "GraphQL"
4059 description: "Markdown"
4075 description: "Handlebars"
4083 description: "Angular"
4087 description: "Lightning Web Components"
4097 category: CATEGORY_GLOBAL,
4098 description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.",
4099 exception: function exception(value) {
4100 return typeof value === "string" || typeof value === "object";
4103 cliCategory: CATEGORY_CONFIG
4112 category: CATEGORY_GLOBAL,
4113 description: dedent_1`
4114 Custom directory that contains prettier plugins in node_modules subdirectory.
4115 Overrides default behavior when plugins are searched relatively to the location of Prettier.
4116 Multiple values are accepted.
4118 exception: function exception(value) {
4119 return typeof value === "string" || typeof value === "object";
4121 cliName: "plugin-search-dir",
4122 cliCategory: CATEGORY_CONFIG
4126 category: CATEGORY_GLOBAL,
4129 description: "The line length where Prettier will try wrap.",
4138 category: CATEGORY_SPECIAL,
4146 description: dedent_1`
4147 Format code ending at a given character offset (exclusive).
4148 The range will extend forwards to the end of the selected statement.
4149 This option cannot be used with --cursor-offset.
4151 cliCategory: CATEGORY_EDITOR
4155 category: CATEGORY_SPECIAL,
4163 description: dedent_1`
4164 Format code starting at a given character offset.
4165 The range will extend backwards to the start of the first line containing the selected statement.
4166 This option cannot be used with --cursor-offset.
4168 cliCategory: CATEGORY_EDITOR
4172 category: CATEGORY_SPECIAL,
4175 description: dedent_1`
4176 Require either '@prettier' or '@format' to be present in the file's first docblock comment
4177 in order for it to be formatted.
4179 cliCategory: CATEGORY_OTHER
4183 category: CATEGORY_GLOBAL,
4185 description: "Number of spaces per indentation level.",
4194 category: CATEGORY_GLOBAL,
4203 deprecated: "0.0.10",
4204 description: "Use flow parser.",
4209 cliName: "flow-parser"
4213 category: CATEGORY_GLOBAL,
4216 description: "Indent with tabs instead of spaces."
4230 var require$$0 = getCjsExportFromNamespace(_package$1);
4232 var currentVersion = require$$0.version;
4233 var coreOptions$1 = coreOptions.options;
4235 function getSupportInfo(version, opts) {
4236 opts = Object.assign({
4238 showUnreleased: false,
4239 showDeprecated: false,
4244 // pre-release version is smaller than the normal version in semver,
4245 // we need to treat it as the normal one so as to test new features.
4246 version = currentVersion.split("-", 1)[0];
4249 var plugins = opts.plugins;
4250 var options = arrayify(Object.assign(plugins.reduce(function (currentOptions, plugin) {
4251 return Object.assign(currentOptions, plugin.options);
4252 }, {}), coreOptions$1), "name").sort(function (a, b) {
4253 return a.name === b.name ? 0 : a.name < b.name ? -1 : 1;
4254 }).filter(filterSince).filter(filterDeprecated).map(mapDeprecated).map(mapInternal).map(function (option) {
4255 var newOption = Object.assign({}, option);
4257 if (Array.isArray(newOption.default)) {
4258 newOption.default = newOption.default.length === 1 ? newOption.default[0].value : newOption.default.filter(filterSince).sort(function (info1, info2) {
4259 return semver.compare(info2.since, info1.since);
4263 if (Array.isArray(newOption.choices)) {
4264 newOption.choices = newOption.choices.filter(filterSince).filter(filterDeprecated).map(mapDeprecated);
4268 }).map(function (option) {
4269 var filteredPlugins = plugins.filter(function (plugin) {
4270 return plugin.defaultOptions && plugin.defaultOptions[option.name] !== undefined;
4272 var pluginDefaults = filteredPlugins.reduce(function (reduced, plugin) {
4273 reduced[plugin.name] = plugin.defaultOptions[option.name];
4276 return Object.assign(option, {
4280 var usePostCssParser = semver.lt(version, "1.7.1");
4281 var useBabylonParser = semver.lt(version, "1.16.0");
4282 var languages = plugins.reduce(function (all, plugin) {
4283 return all.concat(plugin.languages || []);
4284 }, []).filter(filterSince).map(function (language) {
4285 // Prevent breaking changes
4286 if (language.name === "Markdown") {
4287 return Object.assign({}, language, {
4288 parsers: ["markdown"]
4292 if (language.name === "TypeScript") {
4293 return Object.assign({}, language, {
4294 parsers: ["typescript"]
4296 } // "babylon" was renamed to "babel" in 1.16.0
4299 if (useBabylonParser && language.parsers.indexOf("babel") !== -1) {
4300 return Object.assign({}, language, {
4301 parsers: language.parsers.map(function (parser) {
4302 return parser === "babel" ? "babylon" : parser;
4307 if (usePostCssParser && (language.name === "CSS" || language.group === "CSS")) {
4308 return Object.assign({}, language, {
4309 parsers: ["postcss"]
4320 function filterSince(object) {
4321 return opts.showUnreleased || !("since" in object) || object.since && semver.gte(version, object.since);
4324 function filterDeprecated(object) {
4325 return opts.showDeprecated || !("deprecated" in object) || object.deprecated && semver.lt(version, object.deprecated);
4328 function mapDeprecated(object) {
4329 if (!object.deprecated || opts.showDeprecated) {
4333 var newObject = Object.assign({}, object);
4334 delete newObject.deprecated;
4335 delete newObject.redirect;
4339 function mapInternal(object) {
4340 if (opts.showInternal) {
4344 var newObject = Object.assign({}, object);
4345 delete newObject.cliName;
4346 delete newObject.cliCategory;
4347 delete newObject.cliDescription;
4356 /*! *****************************************************************************
4357 Copyright (c) Microsoft Corporation. All rights reserved.
4358 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4359 this file except in compliance with the License. You may obtain a copy of the
4360 License at http://www.apache.org/licenses/LICENSE-2.0
4362 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
4363 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
4364 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
4365 MERCHANTABLITY OR NON-INFRINGEMENT.
4367 See the Apache Version 2.0 License for specific language governing permissions
4368 and limitations under the License.
4369 ***************************************************************************** */
4371 /* global Reflect, Promise */
4372 var _extendStatics = function extendStatics(d, b) {
4373 _extendStatics = Object.setPrototypeOf || {
4375 } instanceof Array && function (d, b) {
4377 } || function (d, b) {
4379 if (b.hasOwnProperty(p)) d[p] = b[p];
4383 return _extendStatics(d, b);
4386 function __extends(d, b) {
4387 _extendStatics(d, b);
4390 this.constructor = d;
4393 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
4396 var _assign = function __assign() {
4397 _assign = Object.assign || function __assign(t) {
4398 for (var s, i = 1, n = arguments.length; i < n; i++) {
4402 if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
4409 return _assign.apply(this, arguments);
4411 function __rest(s, e) {
4415 if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
4418 if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
4419 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
4423 function __decorate(decorators, target, key, desc) {
4424 var c = arguments.length,
4425 r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
4427 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--) {
4428 if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
4430 return c > 3 && r && Object.defineProperty(target, key, r), r;
4432 function __param(paramIndex, decorator) {
4433 return function (target, key) {
4434 decorator(target, key, paramIndex);
4437 function __metadata(metadataKey, metadataValue) {
4438 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
4440 function __awaiter(thisArg, _arguments, P, generator) {
4441 return new (P || (P = Promise))(function (resolve, reject) {
4442 function fulfilled(value) {
4444 step(generator.next(value));
4450 function rejected(value) {
4452 step(generator["throw"](value));
4458 function step(result) {
4459 result.done ? resolve(result.value) : new P(function (resolve) {
4460 resolve(result.value);
4461 }).then(fulfilled, rejected);
4464 step((generator = generator.apply(thisArg, _arguments || [])).next());
4467 function __generator(thisArg, body) {
4470 sent: function sent() {
4471 if (t[0] & 1) throw t[1];
4485 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
4490 return function (v) {
4491 return step([n, v]);
4496 if (f) throw new TypeError("Generator is already executing.");
4500 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;
4501 if (y = 0, t) op = [op[0] & 2, t.value];
4530 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
4535 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
4540 if (op[0] === 6 && _.label < t[1]) {
4546 if (t && _.label < t[2]) {
4554 if (t[2]) _.ops.pop();
4561 op = body.call(thisArg, _);
4570 if (op[0] & 5) throw op[1];
4572 value: op[0] ? op[1] : void 0,
4577 function __exportStar(m, exports) {
4579 if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4582 function __values(o) {
4583 var m = typeof Symbol === "function" && o[Symbol.iterator],
4585 if (m) return m.call(o);
4587 next: function next() {
4588 if (o && i >= o.length) o = void 0;
4596 function __read(o, n) {
4597 var m = typeof Symbol === "function" && o[Symbol.iterator];
4605 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) {
4614 if (r && !r.done && (m = i["return"])) m.call(i);
4616 if (e) throw e.error;
4622 function __spread() {
4623 for (var ar = [], i = 0; i < arguments.length; i++) {
4624 ar = ar.concat(__read(arguments[i]));
4629 function __spreadArrays() {
4630 for (var s = 0, i = 0, il = arguments.length; i < il; i++) {
4631 s += arguments[i].length;
4634 for (var r = Array(s), k = 0, i = 0; i < il; i++) {
4635 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) {
4642 function __await(v) {
4643 return this instanceof __await ? (this.v = v, this) : new __await(v);
4645 function __asyncGenerator(thisArg, _arguments, generator) {
4646 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4647 var g = generator.apply(thisArg, _arguments || []),
4650 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
4655 if (g[n]) i[n] = function (v) {
4656 return new Promise(function (a, b) {
4657 q.push([n, v, a, b]) > 1 || resume(n, v);
4662 function resume(n, v) {
4671 r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
4674 function fulfill(value) {
4675 resume("next", value);
4678 function reject(value) {
4679 resume("throw", value);
4682 function settle(f, v) {
4683 if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
4686 function __asyncDelegator(o) {
4688 return i = {}, verb("next"), verb("throw", function (e) {
4690 }), verb("return"), i[Symbol.iterator] = function () {
4694 function verb(n, f) {
4695 i[n] = o[n] ? function (v) {
4697 value: __await(o[n](v)),
4698 done: n === "return"
4703 function __asyncValues(o) {
4704 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
4705 var m = o[Symbol.asyncIterator],
4707 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 () {
4712 i[n] = o[n] && function (v) {
4713 return new Promise(function (resolve, reject) {
4714 v = o[n](v), settle(resolve, reject, v.done, v.value);
4719 function settle(resolve, reject, d, v) {
4720 Promise.resolve(v).then(function (v) {
4728 function __makeTemplateObject(cooked, raw) {
4729 if (Object.defineProperty) {
4730 Object.defineProperty(cooked, "raw", {
4739 function __importStar(mod) {
4740 if (mod && mod.__esModule) return mod;
4742 if (mod != null) for (var k in mod) {
4743 if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
4745 result.default = mod;
4748 function __importDefault(mod) {
4749 return mod && mod.__esModule ? mod : {
4754 var tslib_es6 = /*#__PURE__*/Object.freeze({
4756 __extends: __extends,
4757 get __assign () { return _assign; },
4759 __decorate: __decorate,
4761 __metadata: __metadata,
4762 __awaiter: __awaiter,
4763 __generator: __generator,
4764 __exportStar: __exportStar,
4768 __spreadArrays: __spreadArrays,
4770 __asyncGenerator: __asyncGenerator,
4771 __asyncDelegator: __asyncDelegator,
4772 __asyncValues: __asyncValues,
4773 __makeTemplateObject: __makeTemplateObject,
4774 __importStar: __importStar,
4775 __importDefault: __importDefault
4778 var api = createCommonjsModule(function (module, exports) {
4780 Object.defineProperty(exports, "__esModule", {
4783 exports.apiDescriptor = {
4784 key: function key(_key) {
4785 return /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(_key) ? _key : JSON.stringify(_key);
4789 if (value === null || typeof value !== 'object') {
4790 return JSON.stringify(value);
4793 if (Array.isArray(value)) {
4794 return `[${value.map(function (subValue) {
4795 return exports.apiDescriptor.value(subValue);
4799 var keys = Object.keys(value);
4800 return keys.length === 0 ? '{}' : `{ ${keys.map(function (key) {
4801 return `${exports.apiDescriptor.key(key)}: ${exports.apiDescriptor.value(value[key])}`;
4805 pair: function pair(_ref) {
4808 return exports.apiDescriptor.value({
4815 var api_1 = api.apiDescriptor;
4817 var descriptors = createCommonjsModule(function (module, exports) {
4819 Object.defineProperty(exports, "__esModule", {
4823 tslib_es6.__exportStar(api, exports);
4825 unwrapExports(descriptors);
4827 var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
4829 var escapeStringRegexp = function escapeStringRegexp(str) {
4830 if (typeof str !== 'string') {
4831 throw new TypeError('Expected a string');
4834 return str.replace(matchOperatorsRe, '\\$&');
4838 "aliceblue": [240, 248, 255],
4839 "antiquewhite": [250, 235, 215],
4840 "aqua": [0, 255, 255],
4841 "aquamarine": [127, 255, 212],
4842 "azure": [240, 255, 255],
4843 "beige": [245, 245, 220],
4844 "bisque": [255, 228, 196],
4846 "blanchedalmond": [255, 235, 205],
4847 "blue": [0, 0, 255],
4848 "blueviolet": [138, 43, 226],
4849 "brown": [165, 42, 42],
4850 "burlywood": [222, 184, 135],
4851 "cadetblue": [95, 158, 160],
4852 "chartreuse": [127, 255, 0],
4853 "chocolate": [210, 105, 30],
4854 "coral": [255, 127, 80],
4855 "cornflowerblue": [100, 149, 237],
4856 "cornsilk": [255, 248, 220],
4857 "crimson": [220, 20, 60],
4858 "cyan": [0, 255, 255],
4859 "darkblue": [0, 0, 139],
4860 "darkcyan": [0, 139, 139],
4861 "darkgoldenrod": [184, 134, 11],
4862 "darkgray": [169, 169, 169],
4863 "darkgreen": [0, 100, 0],
4864 "darkgrey": [169, 169, 169],
4865 "darkkhaki": [189, 183, 107],
4866 "darkmagenta": [139, 0, 139],
4867 "darkolivegreen": [85, 107, 47],
4868 "darkorange": [255, 140, 0],
4869 "darkorchid": [153, 50, 204],
4870 "darkred": [139, 0, 0],
4871 "darksalmon": [233, 150, 122],
4872 "darkseagreen": [143, 188, 143],
4873 "darkslateblue": [72, 61, 139],
4874 "darkslategray": [47, 79, 79],
4875 "darkslategrey": [47, 79, 79],
4876 "darkturquoise": [0, 206, 209],
4877 "darkviolet": [148, 0, 211],
4878 "deeppink": [255, 20, 147],
4879 "deepskyblue": [0, 191, 255],
4880 "dimgray": [105, 105, 105],
4881 "dimgrey": [105, 105, 105],
4882 "dodgerblue": [30, 144, 255],
4883 "firebrick": [178, 34, 34],
4884 "floralwhite": [255, 250, 240],
4885 "forestgreen": [34, 139, 34],
4886 "fuchsia": [255, 0, 255],
4887 "gainsboro": [220, 220, 220],
4888 "ghostwhite": [248, 248, 255],
4889 "gold": [255, 215, 0],
4890 "goldenrod": [218, 165, 32],
4891 "gray": [128, 128, 128],
4892 "green": [0, 128, 0],
4893 "greenyellow": [173, 255, 47],
4894 "grey": [128, 128, 128],
4895 "honeydew": [240, 255, 240],
4896 "hotpink": [255, 105, 180],
4897 "indianred": [205, 92, 92],
4898 "indigo": [75, 0, 130],
4899 "ivory": [255, 255, 240],
4900 "khaki": [240, 230, 140],
4901 "lavender": [230, 230, 250],
4902 "lavenderblush": [255, 240, 245],
4903 "lawngreen": [124, 252, 0],
4904 "lemonchiffon": [255, 250, 205],
4905 "lightblue": [173, 216, 230],
4906 "lightcoral": [240, 128, 128],
4907 "lightcyan": [224, 255, 255],
4908 "lightgoldenrodyellow": [250, 250, 210],
4909 "lightgray": [211, 211, 211],
4910 "lightgreen": [144, 238, 144],
4911 "lightgrey": [211, 211, 211],
4912 "lightpink": [255, 182, 193],
4913 "lightsalmon": [255, 160, 122],
4914 "lightseagreen": [32, 178, 170],
4915 "lightskyblue": [135, 206, 250],
4916 "lightslategray": [119, 136, 153],
4917 "lightslategrey": [119, 136, 153],
4918 "lightsteelblue": [176, 196, 222],
4919 "lightyellow": [255, 255, 224],
4920 "lime": [0, 255, 0],
4921 "limegreen": [50, 205, 50],
4922 "linen": [250, 240, 230],
4923 "magenta": [255, 0, 255],
4924 "maroon": [128, 0, 0],
4925 "mediumaquamarine": [102, 205, 170],
4926 "mediumblue": [0, 0, 205],
4927 "mediumorchid": [186, 85, 211],
4928 "mediumpurple": [147, 112, 219],
4929 "mediumseagreen": [60, 179, 113],
4930 "mediumslateblue": [123, 104, 238],
4931 "mediumspringgreen": [0, 250, 154],
4932 "mediumturquoise": [72, 209, 204],
4933 "mediumvioletred": [199, 21, 133],
4934 "midnightblue": [25, 25, 112],
4935 "mintcream": [245, 255, 250],
4936 "mistyrose": [255, 228, 225],
4937 "moccasin": [255, 228, 181],
4938 "navajowhite": [255, 222, 173],
4939 "navy": [0, 0, 128],
4940 "oldlace": [253, 245, 230],
4941 "olive": [128, 128, 0],
4942 "olivedrab": [107, 142, 35],
4943 "orange": [255, 165, 0],
4944 "orangered": [255, 69, 0],
4945 "orchid": [218, 112, 214],
4946 "palegoldenrod": [238, 232, 170],
4947 "palegreen": [152, 251, 152],
4948 "paleturquoise": [175, 238, 238],
4949 "palevioletred": [219, 112, 147],
4950 "papayawhip": [255, 239, 213],
4951 "peachpuff": [255, 218, 185],
4952 "peru": [205, 133, 63],
4953 "pink": [255, 192, 203],
4954 "plum": [221, 160, 221],
4955 "powderblue": [176, 224, 230],
4956 "purple": [128, 0, 128],
4957 "rebeccapurple": [102, 51, 153],
4959 "rosybrown": [188, 143, 143],
4960 "royalblue": [65, 105, 225],
4961 "saddlebrown": [139, 69, 19],
4962 "salmon": [250, 128, 114],
4963 "sandybrown": [244, 164, 96],
4964 "seagreen": [46, 139, 87],
4965 "seashell": [255, 245, 238],
4966 "sienna": [160, 82, 45],
4967 "silver": [192, 192, 192],
4968 "skyblue": [135, 206, 235],
4969 "slateblue": [106, 90, 205],
4970 "slategray": [112, 128, 144],
4971 "slategrey": [112, 128, 144],
4972 "snow": [255, 250, 250],
4973 "springgreen": [0, 255, 127],
4974 "steelblue": [70, 130, 180],
4975 "tan": [210, 180, 140],
4976 "teal": [0, 128, 128],
4977 "thistle": [216, 191, 216],
4978 "tomato": [255, 99, 71],
4979 "turquoise": [64, 224, 208],
4980 "violet": [238, 130, 238],
4981 "wheat": [245, 222, 179],
4982 "white": [255, 255, 255],
4983 "whitesmoke": [245, 245, 245],
4984 "yellow": [255, 255, 0],
4985 "yellowgreen": [154, 205, 50]
4988 var conversions = createCommonjsModule(function (module) {
4990 // NOTE: conversions should only return primitive values (i.e. arrays, or
4991 // values that give correct `typeof` results).
4992 // do not use box values types (i.e. Number(), String(), etc.)
4993 var reverseKeywords = {};
4995 for (var key in colorName) {
4996 if (colorName.hasOwnProperty(key)) {
4997 reverseKeywords[colorName[key]] = key;
5001 var convert = module.exports = {
5052 labels: ['h', 'c', 'g']
5056 labels: ['r16', 'g16', 'b16']
5062 }; // hide .channels and .labels properties
5064 for (var model in convert) {
5065 if (convert.hasOwnProperty(model)) {
5066 if (!('channels' in convert[model])) {
5067 throw new Error('missing channels property: ' + model);
5070 if (!('labels' in convert[model])) {
5071 throw new Error('missing channel labels property: ' + model);
5074 if (convert[model].labels.length !== convert[model].channels) {
5075 throw new Error('channel and label counts mismatch: ' + model);
5078 var channels = convert[model].channels;
5079 var labels = convert[model].labels;
5080 delete convert[model].channels;
5081 delete convert[model].labels;
5082 Object.defineProperty(convert[model], 'channels', {
5085 Object.defineProperty(convert[model], 'labels', {
5091 convert.rgb.hsl = function (rgb) {
5092 var r = rgb[0] / 255;
5093 var g = rgb[1] / 255;
5094 var b = rgb[2] / 255;
5095 var min = Math.min(r, g, b);
5096 var max = Math.max(r, g, b);
5097 var delta = max - min;
5104 } else if (r === max) {
5105 h = (g - b) / delta;
5106 } else if (g === max) {
5107 h = 2 + (b - r) / delta;
5108 } else if (b === max) {
5109 h = 4 + (r - g) / delta;
5112 h = Math.min(h * 60, 360);
5118 l = (min + max) / 2;
5122 } else if (l <= 0.5) {
5123 s = delta / (max + min);
5125 s = delta / (2 - max - min);
5128 return [h, s * 100, l * 100];
5131 convert.rgb.hsv = function (rgb) {
5135 var min = Math.min(r, g, b);
5136 var max = Math.max(r, g, b);
5137 var delta = max - min;
5145 s = delta / max * 1000 / 10;
5150 } else if (r === max) {
5151 h = (g - b) / delta;
5152 } else if (g === max) {
5153 h = 2 + (b - r) / delta;
5154 } else if (b === max) {
5155 h = 4 + (r - g) / delta;
5158 h = Math.min(h * 60, 360);
5164 v = max / 255 * 1000 / 10;
5168 convert.rgb.hwb = function (rgb) {
5172 var h = convert.rgb.hsl(rgb)[0];
5173 var w = 1 / 255 * Math.min(r, Math.min(g, b));
5174 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
5175 return [h, w * 100, b * 100];
5178 convert.rgb.cmyk = function (rgb) {
5179 var r = rgb[0] / 255;
5180 var g = rgb[1] / 255;
5181 var b = rgb[2] / 255;
5186 k = Math.min(1 - r, 1 - g, 1 - b);
5187 c = (1 - r - k) / (1 - k) || 0;
5188 m = (1 - g - k) / (1 - k) || 0;
5189 y = (1 - b - k) / (1 - k) || 0;
5190 return [c * 100, m * 100, y * 100, k * 100];
5193 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
5197 function comparativeDistance(x, y) {
5198 return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
5201 convert.rgb.keyword = function (rgb) {
5202 var reversed = reverseKeywords[rgb];
5208 var currentClosestDistance = Infinity;
5209 var currentClosestKeyword;
5211 for (var keyword in colorName) {
5212 if (colorName.hasOwnProperty(keyword)) {
5213 var value = colorName[keyword]; // Compute comparative distance
5215 var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
5217 if (distance < currentClosestDistance) {
5218 currentClosestDistance = distance;
5219 currentClosestKeyword = keyword;
5224 return currentClosestKeyword;
5227 convert.keyword.rgb = function (keyword) {
5228 return colorName[keyword];
5231 convert.rgb.xyz = function (rgb) {
5232 var r = rgb[0] / 255;
5233 var g = rgb[1] / 255;
5234 var b = rgb[2] / 255; // assume sRGB
5236 r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
5237 g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
5238 b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
5239 var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
5240 var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
5241 var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
5242 return [x * 100, y * 100, z * 100];
5245 convert.rgb.lab = function (rgb) {
5246 var xyz = convert.rgb.xyz(rgb);
5256 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
5257 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
5258 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
5265 convert.hsl.rgb = function (hsl) {
5266 var h = hsl[0] / 360;
5267 var s = hsl[1] / 100;
5268 var l = hsl[2] / 100;
5277 return [val, val, val];
5289 for (var i = 0; i < 3; i++) {
5290 t3 = h + 1 / 3 * -(i - 1);
5301 val = t1 + (t2 - t1) * 6 * t3;
5302 } else if (2 * t3 < 1) {
5304 } else if (3 * t3 < 2) {
5305 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
5316 convert.hsl.hsv = function (hsl) {
5318 var s = hsl[1] / 100;
5319 var l = hsl[2] / 100;
5321 var lmin = Math.max(l, 0.01);
5325 s *= l <= 1 ? l : 2 - l;
5326 smin *= lmin <= 1 ? lmin : 2 - lmin;
5328 sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
5329 return [h, sv * 100, v * 100];
5332 convert.hsv.rgb = function (hsv) {
5333 var h = hsv[0] / 60;
5334 var s = hsv[1] / 100;
5335 var v = hsv[2] / 100;
5336 var hi = Math.floor(h) % 6;
5337 var f = h - Math.floor(h);
5338 var p = 255 * v * (1 - s);
5339 var q = 255 * v * (1 - s * f);
5340 var t = 255 * v * (1 - s * (1 - f));
5364 convert.hsv.hsl = function (hsv) {
5366 var s = hsv[1] / 100;
5367 var v = hsv[2] / 100;
5368 var vmin = Math.max(v, 0.01);
5373 lmin = (2 - s) * vmin;
5375 sl /= lmin <= 1 ? lmin : 2 - lmin;
5378 return [h, sl * 100, l * 100];
5379 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
5382 convert.hwb.rgb = function (hwb) {
5383 var h = hwb[0] / 360;
5384 var wh = hwb[1] / 100;
5385 var bl = hwb[2] / 100;
5386 var ratio = wh + bl;
5390 var n; // wh + bl cant be > 1
5397 i = Math.floor(6 * h);
5401 if ((i & 0x01) !== 0) {
5405 n = wh + f * (v - wh); // linear interpolation
5451 return [r * 255, g * 255, b * 255];
5454 convert.cmyk.rgb = function (cmyk) {
5455 var c = cmyk[0] / 100;
5456 var m = cmyk[1] / 100;
5457 var y = cmyk[2] / 100;
5458 var k = cmyk[3] / 100;
5462 r = 1 - Math.min(1, c * (1 - k) + k);
5463 g = 1 - Math.min(1, m * (1 - k) + k);
5464 b = 1 - Math.min(1, y * (1 - k) + k);
5465 return [r * 255, g * 255, b * 255];
5468 convert.xyz.rgb = function (xyz) {
5469 var x = xyz[0] / 100;
5470 var y = xyz[1] / 100;
5471 var z = xyz[2] / 100;
5475 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
5476 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
5477 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
5479 r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
5480 g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
5481 b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
5482 r = Math.min(Math.max(0, r), 1);
5483 g = Math.min(Math.max(0, g), 1);
5484 b = Math.min(Math.max(0, b), 1);
5485 return [r * 255, g * 255, b * 255];
5488 convert.xyz.lab = function (xyz) {
5498 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
5499 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
5500 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
5507 convert.lab.xyz = function (lab) {
5517 var y2 = Math.pow(y, 3);
5518 var x2 = Math.pow(x, 3);
5519 var z2 = Math.pow(z, 3);
5520 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
5521 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
5522 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
5529 convert.lab.lch = function (lab) {
5536 hr = Math.atan2(b, a);
5537 h = hr * 360 / 2 / Math.PI;
5543 c = Math.sqrt(a * a + b * b);
5547 convert.lch.lab = function (lch) {
5554 hr = h / 360 * 2 * Math.PI;
5555 a = c * Math.cos(hr);
5556 b = c * Math.sin(hr);
5560 convert.rgb.ansi16 = function (args) {
5564 var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
5566 value = Math.round(value / 50);
5572 var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
5581 convert.hsv.ansi16 = function (args) {
5582 // optimization here; we already know the value and don't need to get
5583 // it converted for us.
5584 return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
5587 convert.rgb.ansi256 = function (args) {
5590 var b = args[2]; // we use the extended greyscale palette here, with the exception of
5591 // black and white. normal palette only has 4 greyscale shades.
5593 if (r === g && g === b) {
5602 return Math.round((r - 8) / 247 * 24) + 232;
5605 var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
5609 convert.ansi16.rgb = function (args) {
5610 var color = args % 10; // handle greyscale
5612 if (color === 0 || color === 7) {
5617 color = color / 10.5 * 255;
5618 return [color, color, color];
5621 var mult = (~~(args > 50) + 1) * 0.5;
5622 var r = (color & 1) * mult * 255;
5623 var g = (color >> 1 & 1) * mult * 255;
5624 var b = (color >> 2 & 1) * mult * 255;
5628 convert.ansi256.rgb = function (args) {
5631 var c = (args - 232) * 10 + 8;
5637 var r = Math.floor(args / 36) / 5 * 255;
5638 var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
5639 var b = rem % 6 / 5 * 255;
5643 convert.rgb.hex = function (args) {
5644 var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
5645 var string = integer.toString(16).toUpperCase();
5646 return '000000'.substring(string.length) + string;
5649 convert.hex.rgb = function (args) {
5650 var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
5656 var colorString = match[0];
5658 if (match[0].length === 3) {
5659 colorString = colorString.split('').map(function (char) {
5664 var integer = parseInt(colorString, 16);
5665 var r = integer >> 16 & 0xFF;
5666 var g = integer >> 8 & 0xFF;
5667 var b = integer & 0xFF;
5671 convert.rgb.hcg = function (rgb) {
5672 var r = rgb[0] / 255;
5673 var g = rgb[1] / 255;
5674 var b = rgb[2] / 255;
5675 var max = Math.max(Math.max(r, g), b);
5676 var min = Math.min(Math.min(r, g), b);
5677 var chroma = max - min;
5682 grayscale = min / (1 - chroma);
5689 } else if (max === r) {
5690 hue = (g - b) / chroma % 6;
5691 } else if (max === g) {
5692 hue = 2 + (b - r) / chroma;
5694 hue = 4 + (r - g) / chroma + 4;
5699 return [hue * 360, chroma * 100, grayscale * 100];
5702 convert.hsl.hcg = function (hsl) {
5703 var s = hsl[1] / 100;
5704 var l = hsl[2] / 100;
5711 c = 2.0 * s * (1.0 - l);
5715 f = (l - 0.5 * c) / (1.0 - c);
5718 return [hsl[0], c * 100, f * 100];
5721 convert.hsv.hcg = function (hsv) {
5722 var s = hsv[1] / 100;
5723 var v = hsv[2] / 100;
5728 f = (v - c) / (1 - c);
5731 return [hsv[0], c * 100, f * 100];
5734 convert.hcg.rgb = function (hcg) {
5735 var h = hcg[0] / 360;
5736 var c = hcg[1] / 100;
5737 var g = hcg[2] / 100;
5740 return [g * 255, g * 255, g * 255];
5743 var pure = [0, 0, 0];
5749 switch (Math.floor(hi)) {
5787 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
5790 convert.hcg.hsv = function (hcg) {
5791 var c = hcg[1] / 100;
5792 var g = hcg[2] / 100;
5793 var v = c + g * (1.0 - c);
5800 return [hcg[0], f * 100, v * 100];
5803 convert.hcg.hsl = function (hcg) {
5804 var c = hcg[1] / 100;
5805 var g = hcg[2] / 100;
5806 var l = g * (1.0 - c) + 0.5 * c;
5809 if (l > 0.0 && l < 0.5) {
5811 } else if (l >= 0.5 && l < 1.0) {
5812 s = c / (2 * (1 - l));
5815 return [hcg[0], s * 100, l * 100];
5818 convert.hcg.hwb = function (hcg) {
5819 var c = hcg[1] / 100;
5820 var g = hcg[2] / 100;
5821 var v = c + g * (1.0 - c);
5822 return [hcg[0], (v - c) * 100, (1 - v) * 100];
5825 convert.hwb.hcg = function (hwb) {
5826 var w = hwb[1] / 100;
5827 var b = hwb[2] / 100;
5833 g = (v - c) / (1 - c);
5836 return [hwb[0], c * 100, g * 100];
5839 convert.apple.rgb = function (apple) {
5840 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
5843 convert.rgb.apple = function (rgb) {
5844 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
5847 convert.gray.rgb = function (args) {
5848 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
5851 convert.gray.hsl = convert.gray.hsv = function (args) {
5852 return [0, 0, args[0]];
5855 convert.gray.hwb = function (gray) {
5856 return [0, 100, gray[0]];
5859 convert.gray.cmyk = function (gray) {
5860 return [0, 0, 0, gray[0]];
5863 convert.gray.lab = function (gray) {
5864 return [gray[0], 0, 0];
5867 convert.gray.hex = function (gray) {
5868 var val = Math.round(gray[0] / 100 * 255) & 0xFF;
5869 var integer = (val << 16) + (val << 8) + val;
5870 var string = integer.toString(16).toUpperCase();
5871 return '000000'.substring(string.length) + string;
5874 convert.rgb.gray = function (rgb) {
5875 var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
5876 return [val / 255 * 100];
5879 var conversions_1 = conversions.rgb;
5880 var conversions_2 = conversions.hsl;
5881 var conversions_3 = conversions.hsv;
5882 var conversions_4 = conversions.hwb;
5883 var conversions_5 = conversions.cmyk;
5884 var conversions_6 = conversions.xyz;
5885 var conversions_7 = conversions.lab;
5886 var conversions_8 = conversions.lch;
5887 var conversions_9 = conversions.hex;
5888 var conversions_10 = conversions.keyword;
5889 var conversions_11 = conversions.ansi16;
5890 var conversions_12 = conversions.ansi256;
5891 var conversions_13 = conversions.hcg;
5892 var conversions_14 = conversions.apple;
5893 var conversions_15 = conversions.gray;
5896 this function routes a model to all other models.
5898 all functions that are routed have a property `.conversion` attached
5899 to the returned synthetic function. This property is an array
5900 of strings, each with the steps in between the 'from' and 'to'
5901 color models (inclusive).
5903 conversions that are not possible simply are not included.
5905 // https://jsperf.com/object-keys-vs-for-in-with-closure/3
5907 var models = Object.keys(conversions);
5909 function buildGraph() {
5912 for (var len = models.length, i = 0; i < len; i++) {
5913 graph[models[i]] = {
5914 // http://jsperf.com/1-vs-infinity
5915 // micro-opt, but this is simple.
5922 } // https://en.wikipedia.org/wiki/Breadth-first_search
5925 function deriveBFS(fromModel) {
5926 var graph = buildGraph();
5927 var queue = [fromModel]; // unshift -> queue -> pop
5929 graph[fromModel].distance = 0;
5931 while (queue.length) {
5932 var current = queue.pop();
5933 var adjacents = Object.keys(conversions[current]);
5935 for (var len = adjacents.length, i = 0; i < len; i++) {
5936 var adjacent = adjacents[i];
5937 var node = graph[adjacent];
5939 if (node.distance === -1) {
5940 node.distance = graph[current].distance + 1;
5941 node.parent = current;
5942 queue.unshift(adjacent);
5950 function link(from, to) {
5951 return function (args) {
5952 return to(from(args));
5956 function wrapConversion(toModel, graph) {
5957 var path = [graph[toModel].parent, toModel];
5958 var fn = conversions[graph[toModel].parent][toModel];
5959 var cur = graph[toModel].parent;
5961 while (graph[cur].parent) {
5962 path.unshift(graph[cur].parent);
5963 fn = link(conversions[graph[cur].parent][cur], fn);
5964 cur = graph[cur].parent;
5967 fn.conversion = path;
5971 var route = function route(fromModel) {
5972 var graph = deriveBFS(fromModel);
5973 var conversion = {};
5974 var models = Object.keys(graph);
5976 for (var len = models.length, i = 0; i < len; i++) {
5977 var toModel = models[i];
5978 var node = graph[toModel];
5980 if (node.parent === null) {
5981 // no possible conversion, or this node is the source model.
5985 conversion[toModel] = wrapConversion(toModel, graph);
5992 var models$1 = Object.keys(conversions);
5994 function wrapRaw(fn) {
5995 var wrappedFn = function wrappedFn(args) {
5996 if (args === undefined || args === null) {
6000 if (arguments.length > 1) {
6001 args = Array.prototype.slice.call(arguments);
6005 }; // preserve .conversion property if there is one
6008 if ('conversion' in fn) {
6009 wrappedFn.conversion = fn.conversion;
6015 function wrapRounded(fn) {
6016 var wrappedFn = function wrappedFn(args) {
6017 if (args === undefined || args === null) {
6021 if (arguments.length > 1) {
6022 args = Array.prototype.slice.call(arguments);
6025 var result = fn(args); // we're assuming the result is an array here.
6026 // see notice in conversions.js; don't use box types
6027 // in conversion functions.
6029 if (typeof result === 'object') {
6030 for (var len = result.length, i = 0; i < len; i++) {
6031 result[i] = Math.round(result[i]);
6036 }; // preserve .conversion property if there is one
6039 if ('conversion' in fn) {
6040 wrappedFn.conversion = fn.conversion;
6046 models$1.forEach(function (fromModel) {
6047 convert[fromModel] = {};
6048 Object.defineProperty(convert[fromModel], 'channels', {
6049 value: conversions[fromModel].channels
6051 Object.defineProperty(convert[fromModel], 'labels', {
6052 value: conversions[fromModel].labels
6054 var routes = route(fromModel);
6055 var routeModels = Object.keys(routes);
6056 routeModels.forEach(function (toModel) {
6057 var fn = routes[toModel];
6058 convert[fromModel][toModel] = wrapRounded(fn);
6059 convert[fromModel][toModel].raw = wrapRaw(fn);
6062 var colorConvert = convert;
6064 var ansiStyles = createCommonjsModule(function (module) {
6066 var wrapAnsi16 = function wrapAnsi16(fn, offset) {
6067 return function () {
6068 var code = fn.apply(colorConvert, arguments);
6069 return `\u001B[${code + offset}m`;
6073 var wrapAnsi256 = function wrapAnsi256(fn, offset) {
6074 return function () {
6075 var code = fn.apply(colorConvert, arguments);
6076 return `\u001B[${38 + offset};5;${code}m`;
6080 var wrapAnsi16m = function wrapAnsi16m(fn, offset) {
6081 return function () {
6082 var rgb = fn.apply(colorConvert, arguments);
6083 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
6087 function assembleStyles() {
6088 var codes = new Map();
6092 // 21 isn't widely supported and 22 does the same thing
6099 strikethrough: [9, 29]
6112 redBright: [91, 39],
6113 greenBright: [92, 39],
6114 yellowBright: [93, 39],
6115 blueBright: [94, 39],
6116 magentaBright: [95, 39],
6117 cyanBright: [96, 39],
6118 whiteBright: [97, 39]
6126 bgMagenta: [45, 49],
6130 bgBlackBright: [100, 49],
6131 bgRedBright: [101, 49],
6132 bgGreenBright: [102, 49],
6133 bgYellowBright: [103, 49],
6134 bgBlueBright: [104, 49],
6135 bgMagentaBright: [105, 49],
6136 bgCyanBright: [106, 49],
6137 bgWhiteBright: [107, 49]
6141 styles.color.grey = styles.color.gray;
6143 for (var _i = 0, _Object$keys = Object.keys(styles); _i < _Object$keys.length; _i++) {
6144 var groupName = _Object$keys[_i];
6145 var group = styles[groupName];
6147 for (var _i3 = 0, _Object$keys3 = Object.keys(group); _i3 < _Object$keys3.length; _i3++) {
6148 var styleName = _Object$keys3[_i3];
6149 var style = group[styleName];
6150 styles[styleName] = {
6151 open: `\u001B[${style[0]}m`,
6152 close: `\u001B[${style[1]}m`
6154 group[styleName] = styles[styleName];
6155 codes.set(style[0], style[1]);
6158 Object.defineProperty(styles, groupName, {
6162 Object.defineProperty(styles, 'codes', {
6168 var ansi2ansi = function ansi2ansi(n) {
6172 var rgb2rgb = function rgb2rgb(r, g, b) {
6176 styles.color.close = '\u001B[39m';
6177 styles.bgColor.close = '\u001B[49m';
6178 styles.color.ansi = {
6179 ansi: wrapAnsi16(ansi2ansi, 0)
6181 styles.color.ansi256 = {
6182 ansi256: wrapAnsi256(ansi2ansi, 0)
6184 styles.color.ansi16m = {
6185 rgb: wrapAnsi16m(rgb2rgb, 0)
6187 styles.bgColor.ansi = {
6188 ansi: wrapAnsi16(ansi2ansi, 10)
6190 styles.bgColor.ansi256 = {
6191 ansi256: wrapAnsi256(ansi2ansi, 10)
6193 styles.bgColor.ansi16m = {
6194 rgb: wrapAnsi16m(rgb2rgb, 10)
6197 for (var _i2 = 0, _Object$keys2 = Object.keys(colorConvert); _i2 < _Object$keys2.length; _i2++) {
6198 var key = _Object$keys2[_i2];
6200 if (typeof colorConvert[key] !== 'object') {
6204 var suite = colorConvert[key];
6206 if (key === 'ansi16') {
6210 if ('ansi16' in suite) {
6211 styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
6212 styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
6215 if ('ansi256' in suite) {
6216 styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
6217 styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
6220 if ('rgb' in suite) {
6221 styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
6222 styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
6227 } // Make the export immutable
6230 Object.defineProperty(module, 'exports', {
6236 var hasFlag = function hasFlag(flag, argv) {
6237 argv = argv || process.argv;
6238 var prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
6239 var pos = argv.indexOf(prefix + flag);
6240 var terminatorPos = argv.indexOf('--');
6241 return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
6244 var env = process.env;
6247 if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
6249 } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
6253 if ('FORCE_COLOR' in env) {
6254 forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0;
6257 function translateLevel(level) {
6270 function supportsColor(stream) {
6271 if (forceColor === false) {
6275 if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
6279 if (hasFlag('color=256')) {
6283 if (stream && !stream.isTTY && forceColor !== true) {
6287 var min = forceColor ? 1 : 0;
6289 if (process.platform === 'win32') {
6290 // Node.js 7.5.0 is the first version of Node.js to include a patch to
6291 // libuv that enables 256 color output on Windows. Anything earlier and it
6292 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
6293 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
6294 // release that supports 256 colors. Windows 10 build 14931 is the first release
6295 // that supports 16m/TrueColor.
6296 var osRelease = os$1.release().split('.');
6298 if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
6299 return Number(osRelease[2]) >= 14931 ? 3 : 2;
6306 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function (sign) {
6308 }) || env.CI_NAME === 'codeship') {
6315 if ('TEAMCITY_VERSION' in env) {
6316 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
6319 if (env.COLORTERM === 'truecolor') {
6323 if ('TERM_PROGRAM' in env) {
6324 var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
6326 switch (env.TERM_PROGRAM) {
6328 return version >= 3 ? 3 : 2;
6330 case 'Apple_Terminal':
6336 if (/-256(color)?$/i.test(env.TERM)) {
6340 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
6344 if ('COLORTERM' in env) {
6348 if (env.TERM === 'dumb') {
6355 function getSupportLevel(stream) {
6356 var level = supportsColor(stream);
6357 return translateLevel(level);
6360 var supportsColor_1 = {
6361 supportsColor: getSupportLevel,
6362 stdout: getSupportLevel(process.stdout),
6363 stderr: getSupportLevel(process.stderr)
6366 var TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
6367 var STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
6368 var STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
6369 var ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
6370 var ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
6372 function unescape(c) {
6373 if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
6374 return String.fromCharCode(parseInt(c.slice(1), 16));
6377 return ESCAPES.get(c) || c;
6380 function parseArguments(name, args) {
6382 var chunks = args.trim().split(/\s*,\s*/g);
6384 var _iteratorNormalCompletion = true;
6385 var _didIteratorError = false;
6386 var _iteratorError = undefined;
6389 for (var _iterator = chunks[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
6390 var chunk = _step.value;
6392 if (!isNaN(chunk)) {
6393 results.push(Number(chunk));
6394 } else if (matches = chunk.match(STRING_REGEX)) {
6395 results.push(matches[2].replace(ESCAPE_REGEX, function (m, escape, chr) {
6396 return escape ? unescape(escape) : chr;
6399 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
6403 _didIteratorError = true;
6404 _iteratorError = err;
6407 if (!_iteratorNormalCompletion && _iterator.return != null) {
6411 if (_didIteratorError) {
6412 throw _iteratorError;
6420 function parseStyle(style) {
6421 STYLE_REGEX.lastIndex = 0;
6425 while ((matches = STYLE_REGEX.exec(style)) !== null) {
6426 var name = matches[1];
6429 var args = parseArguments(name, matches[2]);
6430 results.push([name].concat(args));
6432 results.push([name]);
6439 function buildStyle(chalk, styles) {
6441 var _iteratorNormalCompletion2 = true;
6442 var _didIteratorError2 = false;
6443 var _iteratorError2 = undefined;
6446 for (var _iterator2 = styles[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
6447 var layer = _step2.value;
6448 var _iteratorNormalCompletion3 = true;
6449 var _didIteratorError3 = false;
6450 var _iteratorError3 = undefined;
6453 for (var _iterator3 = layer.styles[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
6454 var style = _step3.value;
6455 enabled[style[0]] = layer.inverse ? null : style.slice(1);
6458 _didIteratorError3 = true;
6459 _iteratorError3 = err;
6462 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
6463 _iterator3.return();
6466 if (_didIteratorError3) {
6467 throw _iteratorError3;
6473 _didIteratorError2 = true;
6474 _iteratorError2 = err;
6477 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
6478 _iterator2.return();
6481 if (_didIteratorError2) {
6482 throw _iteratorError2;
6487 var current = chalk;
6489 for (var _i = 0, _Object$keys = Object.keys(enabled); _i < _Object$keys.length; _i++) {
6490 var styleName = _Object$keys[_i];
6492 if (Array.isArray(enabled[styleName])) {
6493 if (!(styleName in current)) {
6494 throw new Error(`Unknown Chalk style: ${styleName}`);
6497 if (enabled[styleName].length > 0) {
6498 current = current[styleName].apply(current, enabled[styleName]);
6500 current = current[styleName];
6508 var templates = function templates(chalk, tmp) {
6511 var chunk = []; // eslint-disable-next-line max-params
6513 tmp.replace(TEMPLATE_REGEX, function (m, escapeChar, inverse, style, close, chr) {
6515 chunk.push(unescape(escapeChar));
6517 var str = chunk.join('');
6519 chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
6522 styles: parseStyle(style)
6525 if (styles.length === 0) {
6526 throw new Error('Found extraneous } in Chalk template literal');
6529 chunks.push(buildStyle(chalk, styles)(chunk.join('')));
6536 chunks.push(chunk.join(''));
6538 if (styles.length > 0) {
6539 var errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
6540 throw new Error(errMsg);
6543 return chunks.join('');
6546 var chalk = createCommonjsModule(function (module) {
6548 var stdoutColor = supportsColor_1.stdout;
6549 var isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
6551 var levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
6553 var skipModels = new Set(['gray']);
6554 var styles = Object.create(null);
6556 function applyOptions(obj, options) {
6557 options = options || {}; // Detect level if not set manually
6559 var scLevel = stdoutColor ? stdoutColor.level : 0;
6560 obj.level = options.level === undefined ? scLevel : options.level;
6561 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
6564 function Chalk(options) {
6565 // We check for this.template here since calling `chalk.constructor()`
6566 // by itself will have a `this` of a previously constructed chalk object
6567 if (!this || !(this instanceof Chalk) || this.template) {
6569 applyOptions(_chalk, options);
6571 _chalk.template = function () {
6572 var args = [].slice.call(arguments);
6573 return chalkTag.apply(null, [_chalk.template].concat(args));
6576 Object.setPrototypeOf(_chalk, Chalk.prototype);
6577 Object.setPrototypeOf(_chalk.template, _chalk);
6578 _chalk.template.constructor = Chalk;
6579 return _chalk.template;
6582 applyOptions(this, options);
6583 } // Use bright blue on Windows as the normal blue color is illegible
6586 if (isSimpleWindowsTerm) {
6587 ansiStyles.blue.open = '\u001B[94m';
6590 var _loop = function _loop() {
6591 var key = _Object$keys[_i];
6592 ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
6595 var codes = ansiStyles[key];
6596 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
6602 for (var _i = 0, _Object$keys = Object.keys(ansiStyles); _i < _Object$keys.length; _i++) {
6608 return build.call(this, this._styles || [], true, 'visible');
6612 ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
6614 var _loop2 = function _loop2() {
6615 var model = _Object$keys2[_i2];
6617 if (skipModels.has(model)) {
6623 var level = this.level;
6624 return function () {
6625 var open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
6628 close: ansiStyles.color.close,
6629 closeRe: ansiStyles.color.closeRe
6631 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
6638 for (var _i2 = 0, _Object$keys2 = Object.keys(ansiStyles.color.ansi); _i2 < _Object$keys2.length; _i2++) {
6639 var _ret = _loop2();
6641 if (_ret === "continue") continue;
6644 ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
6646 var _loop3 = function _loop3() {
6647 var model = _Object$keys3[_i3];
6649 if (skipModels.has(model)) {
6653 var bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
6656 var level = this.level;
6657 return function () {
6658 var open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
6661 close: ansiStyles.bgColor.close,
6662 closeRe: ansiStyles.bgColor.closeRe
6664 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
6671 for (var _i3 = 0, _Object$keys3 = Object.keys(ansiStyles.bgColor.ansi); _i3 < _Object$keys3.length; _i3++) {
6672 var _ret2 = _loop3();
6674 if (_ret2 === "continue") continue;
6677 var proto = Object.defineProperties(function () {}, styles);
6679 function build(_styles, _empty, key) {
6680 var builder = function builder() {
6681 return applyStyle.apply(builder, arguments);
6684 builder._styles = _styles;
6685 builder._empty = _empty;
6687 Object.defineProperty(builder, 'level', {
6699 Object.defineProperty(builder, 'enabled', {
6703 return self.enabled;
6707 self.enabled = enabled;
6710 }); // See below for fix regarding invisible grey/dim combination on Windows
6712 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
6713 // no way to create a function with a different prototype
6715 builder.__proto__ = proto; // eslint-disable-line no-proto
6720 function applyStyle() {
6721 // Support varags, but simply cast to string in case there's only one arg
6722 var args = arguments;
6723 var argsLen = args.length;
6724 var str = String(arguments[0]);
6726 if (argsLen === 0) {
6731 // Don't slice `arguments`, it prevents V8 optimizations
6732 for (var a = 1; a < argsLen; a++) {
6733 str += ' ' + args[a];
6737 if (!this.enabled || this.level <= 0 || !str) {
6738 return this._empty ? '' : str;
6739 } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
6740 // see https://github.com/chalk/chalk/issues/58
6741 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
6744 var originalDim = ansiStyles.dim.open;
6746 if (isSimpleWindowsTerm && this.hasGrey) {
6747 ansiStyles.dim.open = '';
6750 var _iteratorNormalCompletion = true;
6751 var _didIteratorError = false;
6752 var _iteratorError = undefined;
6755 for (var _iterator = this._styles.slice().reverse()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
6756 var code = _step.value;
6757 // Replace any instances already present with a re-opening code
6758 // otherwise only the part of the string until said closing code
6759 // will be colored, and the rest will simply be 'plain'.
6760 str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
6761 // after next line to fix a bleed issue on macOS
6762 // https://github.com/chalk/chalk/pull/92
6764 str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
6765 } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
6768 _didIteratorError = true;
6769 _iteratorError = err;
6772 if (!_iteratorNormalCompletion && _iterator.return != null) {
6776 if (_didIteratorError) {
6777 throw _iteratorError;
6782 ansiStyles.dim.open = originalDim;
6786 function chalkTag(chalk, strings) {
6787 if (!Array.isArray(strings)) {
6788 // If chalk() was called by itself or with a string,
6789 // return the string itself as a string.
6790 return [].slice.call(arguments, 1).join(' ');
6793 var args = [].slice.call(arguments, 2);
6794 var parts = [strings.raw[0]];
6796 for (var i = 1; i < strings.length; i++) {
6797 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
6798 parts.push(String(strings.raw[i]));
6801 return templates(chalk, parts.join(''));
6804 Object.defineProperties(Chalk.prototype, styles);
6805 module.exports = Chalk(); // eslint-disable-line new-cap
6807 module.exports.supportsColor = stdoutColor;
6808 module.exports.default = module.exports; // For TypeScript
6810 var chalk_1 = chalk.supportsColor;
6812 var common = createCommonjsModule(function (module, exports) {
6814 Object.defineProperty(exports, "__esModule", {
6818 exports.commonDeprecatedHandler = function (keyOrPair, redirectTo, _ref) {
6819 var descriptor = _ref.descriptor;
6820 var messages = [`${chalk.default.yellow(typeof keyOrPair === 'string' ? descriptor.key(keyOrPair) : descriptor.pair(keyOrPair))} is deprecated`];
6823 messages.push(`we now treat it as ${chalk.default.blue(typeof redirectTo === 'string' ? descriptor.key(redirectTo) : descriptor.pair(redirectTo))}`);
6826 return messages.join('; ') + '.';
6829 unwrapExports(common);
6830 var common_1 = common.commonDeprecatedHandler;
6832 var deprecated = createCommonjsModule(function (module, exports) {
6834 Object.defineProperty(exports, "__esModule", {
6838 tslib_es6.__exportStar(common, exports);
6840 unwrapExports(deprecated);
6842 var common$1 = createCommonjsModule(function (module, exports) {
6844 Object.defineProperty(exports, "__esModule", {
6848 exports.commonInvalidHandler = function (key, value, utils) {
6849 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(' ');
6852 unwrapExports(common$1);
6853 var common_1$1 = common$1.commonInvalidHandler;
6855 var invalid = createCommonjsModule(function (module, exports) {
6857 Object.defineProperty(exports, "__esModule", {
6861 tslib_es6.__exportStar(common$1, exports);
6863 unwrapExports(invalid);
6865 /* eslint-disable no-nested-ternary */
6868 var charCodeCache = [];
6870 var leven = function leven(a, b) {
6875 var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the
6876 // shortest & which one is the longest
6878 if (a.length > b.length) {
6883 var aLen = a.length;
6884 var bLen = b.length;
6892 } // Performing suffix trimming:
6893 // We can linearly drop suffix common to both strings since they
6894 // don't increase distance at all
6895 // Note: `~-` is the bitwise way to perform a `- 1` operation
6898 while (aLen > 0 && a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen)) {
6905 } // Performing prefix trimming
6906 // We can linearly drop prefix common to both strings since they
6907 // don't increase distance at all
6912 while (start < aLen && a.charCodeAt(start) === b.charCodeAt(start)) {
6931 charCodeCache[start + i] = a.charCodeAt(start + i);
6936 bCharCode = b.charCodeAt(start + j);
6940 for (i = 0; i < aLen; i++) {
6941 tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1;
6943 ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2;
6950 var leven_1 = createCommonjsModule(function (module, exports) {
6952 Object.defineProperty(exports, "__esModule", {
6956 exports.levenUnknownHandler = function (key, value, _ref) {
6957 var descriptor = _ref.descriptor,
6958 logger = _ref.logger,
6959 schemas = _ref.schemas;
6960 var messages = [`Ignored unknown option ${chalk.default.yellow(descriptor.pair({
6964 var suggestion = Object.keys(schemas).sort().find(function (knownKey) {
6965 return leven(key, knownKey) < 3;
6969 messages.push(`Did you mean ${chalk.default.blue(descriptor.key(suggestion))}?`);
6972 logger.warn(messages.join(' '));
6975 unwrapExports(leven_1);
6976 var leven_2 = leven_1.levenUnknownHandler;
6978 var unknown = createCommonjsModule(function (module, exports) {
6980 Object.defineProperty(exports, "__esModule", {
6984 tslib_es6.__exportStar(leven_1, exports);
6986 unwrapExports(unknown);
6988 var handlers = createCommonjsModule(function (module, exports) {
6990 Object.defineProperty(exports, "__esModule", {
6994 tslib_es6.__exportStar(deprecated, exports);
6996 tslib_es6.__exportStar(invalid, exports);
6998 tslib_es6.__exportStar(unknown, exports);
7000 unwrapExports(handlers);
7002 var schema = createCommonjsModule(function (module, exports) {
7004 Object.defineProperty(exports, "__esModule", {
7007 var HANDLER_KEYS = ['default', 'expected', 'validate', 'deprecated', 'forward', 'redirect', 'overlap', 'preprocess', 'postprocess'];
7009 function createSchema(SchemaConstructor, parameters) {
7010 var schema = new SchemaConstructor(parameters);
7011 var subSchema = Object.create(schema);
7012 var _iteratorNormalCompletion = true;
7013 var _didIteratorError = false;
7014 var _iteratorError = undefined;
7017 for (var _iterator = HANDLER_KEYS[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
7018 var handlerKey = _step.value;
7020 if (handlerKey in parameters) {
7021 subSchema[handlerKey] = normalizeHandler(parameters[handlerKey], schema, Schema.prototype[handlerKey].length);
7025 _didIteratorError = true;
7026 _iteratorError = err;
7029 if (!_iteratorNormalCompletion && _iterator.return != null) {
7033 if (_didIteratorError) {
7034 throw _iteratorError;
7042 exports.createSchema = createSchema;
7047 function Schema(parameters) {
7048 _classCallCheck(this, Schema);
7050 this.name = parameters.name;
7053 _createClass(Schema, [{
7055 value: function _default(_utils) {
7057 } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
7061 value: function expected(_utils) {
7063 } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
7067 value: function validate(_value, _utils) {
7072 value: function deprecated(_value, _utils) {
7077 value: function forward(_value, _utils) {
7082 value: function redirect(_value, _utils) {
7087 value: function overlap(currentValue, _newValue, _utils) {
7088 return currentValue;
7092 value: function preprocess(value, _utils) {
7097 value: function postprocess(value, _utils) {
7102 value: function create(parameters) {
7103 // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/5863
7104 return createSchema(this, parameters);
7111 exports.Schema = Schema;
7113 function normalizeHandler(handler, superSchema, handlerArgumentsLength) {
7114 return typeof handler === 'function' ? function () {
7115 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
7116 args[_key] = arguments[_key];
7119 return handler.apply(void 0, _toConsumableArray$1(args.slice(0, handlerArgumentsLength - 1)).concat([superSchema], _toConsumableArray$1(args.slice(handlerArgumentsLength - 1))));
7125 unwrapExports(schema);
7126 var schema_1 = schema.createSchema;
7127 var schema_2 = schema.Schema;
7129 var alias = createCommonjsModule(function (module, exports) {
7131 Object.defineProperty(exports, "__esModule", {
7137 function (_schema_1$Schema) {
7138 _inherits(AliasSchema, _schema_1$Schema);
7140 function AliasSchema(parameters) {
7143 _classCallCheck(this, AliasSchema);
7145 _this = _possibleConstructorReturn(this, _getPrototypeOf(AliasSchema).call(this, parameters));
7146 _this._sourceName = parameters.sourceName;
7150 _createClass(AliasSchema, [{
7152 value: function expected(utils) {
7153 return utils.schemas[this._sourceName].expected(utils);
7157 value: function validate(value, utils) {
7158 return utils.schemas[this._sourceName].validate(value, utils);
7162 value: function redirect(_value, _utils) {
7163 return this._sourceName;
7170 exports.AliasSchema = AliasSchema;
7172 unwrapExports(alias);
7173 var alias_1 = alias.AliasSchema;
7175 var any = createCommonjsModule(function (module, exports) {
7177 Object.defineProperty(exports, "__esModule", {
7183 function (_schema_1$Schema) {
7184 _inherits(AnySchema, _schema_1$Schema);
7186 function AnySchema() {
7187 _classCallCheck(this, AnySchema);
7189 return _possibleConstructorReturn(this, _getPrototypeOf(AnySchema).apply(this, arguments));
7192 _createClass(AnySchema, [{
7194 value: function expected() {
7199 value: function validate() {
7207 exports.AnySchema = AnySchema;
7210 var any_1 = any.AnySchema;
7212 var array = createCommonjsModule(function (module, exports) {
7214 Object.defineProperty(exports, "__esModule", {
7220 function (_schema_1$Schema) {
7221 _inherits(ArraySchema, _schema_1$Schema);
7223 function ArraySchema(_a) {
7226 _classCallCheck(this, ArraySchema);
7228 var valueSchema = _a.valueSchema,
7230 name = _a$name === void 0 ? valueSchema.name : _a$name,
7231 handlers = tslib_es6.__rest(_a, ["valueSchema", "name"]);
7233 _this = _possibleConstructorReturn(this, _getPrototypeOf(ArraySchema).call(this, Object.assign({}, handlers, {
7236 _this._valueSchema = valueSchema;
7240 _createClass(ArraySchema, [{
7242 value: function expected(utils) {
7243 return `an array of ${this._valueSchema.expected(utils)}`;
7247 value: function validate(value, utils) {
7248 if (!Array.isArray(value)) {
7252 var invalidValues = [];
7253 var _iteratorNormalCompletion = true;
7254 var _didIteratorError = false;
7255 var _iteratorError = undefined;
7258 for (var _iterator = value[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
7259 var subValue = _step.value;
7260 var subValidateResult = utils.normalizeValidateResult(this._valueSchema.validate(subValue, utils), subValue);
7262 if (subValidateResult !== true) {
7263 invalidValues.push(subValidateResult.value);
7267 _didIteratorError = true;
7268 _iteratorError = err;
7271 if (!_iteratorNormalCompletion && _iterator.return != null) {
7275 if (_didIteratorError) {
7276 throw _iteratorError;
7281 return invalidValues.length === 0 ? true : {
7282 value: invalidValues
7287 value: function deprecated(value, utils) {
7288 var deprecatedResult = [];
7289 var _iteratorNormalCompletion2 = true;
7290 var _didIteratorError2 = false;
7291 var _iteratorError2 = undefined;
7294 for (var _iterator2 = value[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
7295 var subValue = _step2.value;
7296 var subDeprecatedResult = utils.normalizeDeprecatedResult(this._valueSchema.deprecated(subValue, utils), subValue);
7298 if (subDeprecatedResult !== false) {
7299 deprecatedResult.push.apply(deprecatedResult, _toConsumableArray$1(subDeprecatedResult.map(function (_ref) {
7300 var deprecatedValue = _ref.value;
7302 value: [deprecatedValue]
7308 _didIteratorError2 = true;
7309 _iteratorError2 = err;
7312 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
7313 _iterator2.return();
7316 if (_didIteratorError2) {
7317 throw _iteratorError2;
7322 return deprecatedResult;
7326 value: function forward(value, utils) {
7327 var forwardResult = [];
7328 var _iteratorNormalCompletion3 = true;
7329 var _didIteratorError3 = false;
7330 var _iteratorError3 = undefined;
7333 for (var _iterator3 = value[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
7334 var subValue = _step3.value;
7335 var subForwardResult = utils.normalizeForwardResult(this._valueSchema.forward(subValue, utils), subValue);
7336 forwardResult.push.apply(forwardResult, _toConsumableArray$1(subForwardResult.map(wrapTransferResult)));
7339 _didIteratorError3 = true;
7340 _iteratorError3 = err;
7343 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
7344 _iterator3.return();
7347 if (_didIteratorError3) {
7348 throw _iteratorError3;
7353 return forwardResult;
7357 value: function redirect(value, utils) {
7360 var _iteratorNormalCompletion4 = true;
7361 var _didIteratorError4 = false;
7362 var _iteratorError4 = undefined;
7365 for (var _iterator4 = value[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
7366 var subValue = _step4.value;
7367 var subRedirectResult = utils.normalizeRedirectResult(this._valueSchema.redirect(subValue, utils), subValue);
7369 if ('remain' in subRedirectResult) {
7370 remain.push(subRedirectResult.remain);
7373 redirect.push.apply(redirect, _toConsumableArray$1(subRedirectResult.redirect.map(wrapTransferResult)));
7376 _didIteratorError4 = true;
7377 _iteratorError4 = err;
7380 if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
7381 _iterator4.return();
7384 if (_didIteratorError4) {
7385 throw _iteratorError4;
7390 return remain.length === 0 ? {
7399 value: function overlap(currentValue, newValue) {
7400 return currentValue.concat(newValue);
7407 exports.ArraySchema = ArraySchema;
7409 function wrapTransferResult(_ref2) {
7410 var from = _ref2.from,
7418 unwrapExports(array);
7419 var array_1 = array.ArraySchema;
7421 var boolean_1 = createCommonjsModule(function (module, exports) {
7423 Object.defineProperty(exports, "__esModule", {
7429 function (_schema_1$Schema) {
7430 _inherits(BooleanSchema, _schema_1$Schema);
7432 function BooleanSchema() {
7433 _classCallCheck(this, BooleanSchema);
7435 return _possibleConstructorReturn(this, _getPrototypeOf(BooleanSchema).apply(this, arguments));
7438 _createClass(BooleanSchema, [{
7440 value: function expected() {
7441 return 'true or false';
7445 value: function validate(value) {
7446 return typeof value === 'boolean';
7450 return BooleanSchema;
7453 exports.BooleanSchema = BooleanSchema;
7455 unwrapExports(boolean_1);
7456 var boolean_2 = boolean_1.BooleanSchema;
7458 var utils = createCommonjsModule(function (module, exports) {
7460 Object.defineProperty(exports, "__esModule", {
7464 function recordFromArray(array, mainKey) {
7465 var record = Object.create(null);
7466 var _iteratorNormalCompletion = true;
7467 var _didIteratorError = false;
7468 var _iteratorError = undefined;
7471 for (var _iterator = array[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
7472 var value = _step.value;
7473 var key = value[mainKey]; // istanbul ignore next
7476 throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`);
7480 record[key] = value;
7483 _didIteratorError = true;
7484 _iteratorError = err;
7487 if (!_iteratorNormalCompletion && _iterator.return != null) {
7491 if (_didIteratorError) {
7492 throw _iteratorError;
7500 exports.recordFromArray = recordFromArray;
7502 function mapFromArray(array, mainKey) {
7503 var map = new Map();
7504 var _iteratorNormalCompletion2 = true;
7505 var _didIteratorError2 = false;
7506 var _iteratorError2 = undefined;
7509 for (var _iterator2 = array[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
7510 var value = _step2.value;
7511 var key = value[mainKey]; // istanbul ignore next
7514 throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`);
7517 map.set(key, value);
7520 _didIteratorError2 = true;
7521 _iteratorError2 = err;
7524 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
7525 _iterator2.return();
7528 if (_didIteratorError2) {
7529 throw _iteratorError2;
7537 exports.mapFromArray = mapFromArray;
7539 function createAutoChecklist() {
7540 var map = Object.create(null);
7541 return function (id) {
7542 var idString = JSON.stringify(id);
7544 if (map[idString]) {
7548 map[idString] = true;
7553 exports.createAutoChecklist = createAutoChecklist;
7555 function partition(array, predicate) {
7557 var falseArray = [];
7558 var _iteratorNormalCompletion3 = true;
7559 var _didIteratorError3 = false;
7560 var _iteratorError3 = undefined;
7563 for (var _iterator3 = array[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
7564 var value = _step3.value;
7566 if (predicate(value)) {
7567 trueArray.push(value);
7569 falseArray.push(value);
7573 _didIteratorError3 = true;
7574 _iteratorError3 = err;
7577 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
7578 _iterator3.return();
7581 if (_didIteratorError3) {
7582 throw _iteratorError3;
7587 return [trueArray, falseArray];
7590 exports.partition = partition;
7592 function isInt(value) {
7593 return value === Math.floor(value);
7596 exports.isInt = isInt;
7598 function comparePrimitive(a, b) {
7603 var typeofA = typeof a;
7604 var typeofB = typeof b;
7605 var orders = ['undefined', 'object', 'boolean', 'number', 'string'];
7607 if (typeofA !== typeofB) {
7608 return orders.indexOf(typeofA) - orders.indexOf(typeofB);
7611 if (typeofA !== 'string') {
7612 return Number(a) - Number(b);
7615 return a.localeCompare(b);
7618 exports.comparePrimitive = comparePrimitive;
7620 function normalizeDefaultResult(result) {
7621 return result === undefined ? {} : result;
7624 exports.normalizeDefaultResult = normalizeDefaultResult;
7626 function normalizeValidateResult(result, value) {
7627 return result === true ? true : result === false ? {
7632 exports.normalizeValidateResult = normalizeValidateResult;
7634 function normalizeDeprecatedResult(result, value) {
7635 var doNotNormalizeTrue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
7636 return result === false ? false : result === true ? doNotNormalizeTrue ? true : [{
7638 }] : 'value' in result ? [result] : result.length === 0 ? false : result;
7641 exports.normalizeDeprecatedResult = normalizeDeprecatedResult;
7643 function normalizeTransferResult(result, value) {
7644 return typeof result === 'string' || 'key' in result ? {
7647 } : 'from' in result ? {
7656 exports.normalizeTransferResult = normalizeTransferResult;
7658 function normalizeForwardResult(result, value) {
7659 return result === undefined ? [] : Array.isArray(result) ? result.map(function (transferResult) {
7660 return normalizeTransferResult(transferResult, value);
7661 }) : [normalizeTransferResult(result, value)];
7664 exports.normalizeForwardResult = normalizeForwardResult;
7666 function normalizeRedirectResult(result, value) {
7667 var redirect = normalizeForwardResult(typeof result === 'object' && 'redirect' in result ? result.redirect : result, value);
7668 return redirect.length === 0 ? {
7671 } : typeof result === 'object' && 'remain' in result ? {
7672 remain: result.remain,
7679 exports.normalizeRedirectResult = normalizeRedirectResult;
7681 unwrapExports(utils);
7682 var utils_1 = utils.recordFromArray;
7683 var utils_2 = utils.mapFromArray;
7684 var utils_3 = utils.createAutoChecklist;
7685 var utils_4 = utils.partition;
7686 var utils_5 = utils.isInt;
7687 var utils_6 = utils.comparePrimitive;
7688 var utils_7 = utils.normalizeDefaultResult;
7689 var utils_8 = utils.normalizeValidateResult;
7690 var utils_9 = utils.normalizeDeprecatedResult;
7691 var utils_10 = utils.normalizeTransferResult;
7692 var utils_11 = utils.normalizeForwardResult;
7693 var utils_12 = utils.normalizeRedirectResult;
7695 var choice = createCommonjsModule(function (module, exports) {
7697 Object.defineProperty(exports, "__esModule", {
7703 function (_schema_1$Schema) {
7704 _inherits(ChoiceSchema, _schema_1$Schema);
7706 function ChoiceSchema(parameters) {
7709 _classCallCheck(this, ChoiceSchema);
7711 _this = _possibleConstructorReturn(this, _getPrototypeOf(ChoiceSchema).call(this, parameters));
7712 _this._choices = utils.mapFromArray(parameters.choices.map(function (choice) {
7713 return choice && typeof choice === 'object' ? choice : {
7720 _createClass(ChoiceSchema, [{
7722 value: function expected(_ref) {
7725 var descriptor = _ref.descriptor;
7726 var choiceValues = Array.from(this._choices.keys()).map(function (value) {
7727 return _this2._choices.get(value);
7728 }).filter(function (choiceInfo) {
7729 return !choiceInfo.deprecated;
7730 }).map(function (choiceInfo) {
7731 return choiceInfo.value;
7732 }).sort(utils.comparePrimitive).map(descriptor.value);
7733 var head = choiceValues.slice(0, -2);
7734 var tail = choiceValues.slice(-2);
7735 return head.concat(tail.join(' or ')).join(', ');
7739 value: function validate(value) {
7740 return this._choices.has(value);
7744 value: function deprecated(value) {
7745 var choiceInfo = this._choices.get(value);
7747 return choiceInfo && choiceInfo.deprecated ? {
7753 value: function forward(value) {
7754 var choiceInfo = this._choices.get(value);
7756 return choiceInfo ? choiceInfo.forward : undefined;
7760 value: function redirect(value) {
7761 var choiceInfo = this._choices.get(value);
7763 return choiceInfo ? choiceInfo.redirect : undefined;
7767 return ChoiceSchema;
7770 exports.ChoiceSchema = ChoiceSchema;
7772 unwrapExports(choice);
7773 var choice_1 = choice.ChoiceSchema;
7775 var number = createCommonjsModule(function (module, exports) {
7777 Object.defineProperty(exports, "__esModule", {
7783 function (_schema_1$Schema) {
7784 _inherits(NumberSchema, _schema_1$Schema);
7786 function NumberSchema() {
7787 _classCallCheck(this, NumberSchema);
7789 return _possibleConstructorReturn(this, _getPrototypeOf(NumberSchema).apply(this, arguments));
7792 _createClass(NumberSchema, [{
7794 value: function expected() {
7799 value: function validate(value, _utils) {
7800 return typeof value === 'number';
7804 return NumberSchema;
7807 exports.NumberSchema = NumberSchema;
7809 unwrapExports(number);
7810 var number_1 = number.NumberSchema;
7812 var integer = createCommonjsModule(function (module, exports) {
7814 Object.defineProperty(exports, "__esModule", {
7820 function (_number_1$NumberSchem) {
7821 _inherits(IntegerSchema, _number_1$NumberSchem);
7823 function IntegerSchema() {
7824 _classCallCheck(this, IntegerSchema);
7826 return _possibleConstructorReturn(this, _getPrototypeOf(IntegerSchema).apply(this, arguments));
7829 _createClass(IntegerSchema, [{
7831 value: function expected() {
7832 return 'an integer';
7836 value: function validate(value, utils$1) {
7837 return utils$1.normalizeValidateResult(_get(_getPrototypeOf(IntegerSchema.prototype), "validate", this).call(this, value, utils$1), value) === true && utils.isInt(value);
7841 return IntegerSchema;
7842 }(number.NumberSchema);
7844 exports.IntegerSchema = IntegerSchema;
7846 unwrapExports(integer);
7847 var integer_1 = integer.IntegerSchema;
7849 var string = createCommonjsModule(function (module, exports) {
7851 Object.defineProperty(exports, "__esModule", {
7857 function (_schema_1$Schema) {
7858 _inherits(StringSchema, _schema_1$Schema);
7860 function StringSchema() {
7861 _classCallCheck(this, StringSchema);
7863 return _possibleConstructorReturn(this, _getPrototypeOf(StringSchema).apply(this, arguments));
7866 _createClass(StringSchema, [{
7868 value: function expected() {
7873 value: function validate(value) {
7874 return typeof value === 'string';
7878 return StringSchema;
7881 exports.StringSchema = StringSchema;
7883 unwrapExports(string);
7884 var string_1 = string.StringSchema;
7886 var schemas = createCommonjsModule(function (module, exports) {
7888 Object.defineProperty(exports, "__esModule", {
7892 tslib_es6.__exportStar(alias, exports);
7894 tslib_es6.__exportStar(any, exports);
7896 tslib_es6.__exportStar(array, exports);
7898 tslib_es6.__exportStar(boolean_1, exports);
7900 tslib_es6.__exportStar(choice, exports);
7902 tslib_es6.__exportStar(integer, exports);
7904 tslib_es6.__exportStar(number, exports);
7906 tslib_es6.__exportStar(string, exports);
7908 unwrapExports(schemas);
7910 var defaults = createCommonjsModule(function (module, exports) {
7912 Object.defineProperty(exports, "__esModule", {
7915 exports.defaultDescriptor = api.apiDescriptor;
7916 exports.defaultUnknownHandler = leven_1.levenUnknownHandler;
7917 exports.defaultInvalidHandler = invalid.commonInvalidHandler;
7918 exports.defaultDeprecatedHandler = common.commonDeprecatedHandler;
7920 unwrapExports(defaults);
7921 var defaults_1 = defaults.defaultDescriptor;
7922 var defaults_2 = defaults.defaultUnknownHandler;
7923 var defaults_3 = defaults.defaultInvalidHandler;
7924 var defaults_4 = defaults.defaultDeprecatedHandler;
7926 var normalize = createCommonjsModule(function (module, exports) {
7928 Object.defineProperty(exports, "__esModule", {
7932 exports.normalize = function (options, schemas, opts) {
7933 return new Normalizer(schemas, opts).normalize(options);
7939 function Normalizer(schemas, opts) {
7940 _classCallCheck(this, Normalizer);
7942 // istanbul ignore next
7943 var _ref = opts || {},
7944 _ref$logger = _ref.logger,
7945 logger = _ref$logger === void 0 ? console : _ref$logger,
7946 _ref$descriptor = _ref.descriptor,
7947 descriptor = _ref$descriptor === void 0 ? defaults.defaultDescriptor : _ref$descriptor,
7948 _ref$unknown = _ref.unknown,
7949 unknown = _ref$unknown === void 0 ? defaults.defaultUnknownHandler : _ref$unknown,
7950 _ref$invalid = _ref.invalid,
7951 invalid = _ref$invalid === void 0 ? defaults.defaultInvalidHandler : _ref$invalid,
7952 _ref$deprecated = _ref.deprecated,
7953 deprecated = _ref$deprecated === void 0 ? defaults.defaultDeprecatedHandler : _ref$deprecated;
7958 /* istanbul ignore next */
7960 warn: function warn() {}
7962 schemas: utils.recordFromArray(schemas, 'name'),
7963 normalizeDefaultResult: utils.normalizeDefaultResult,
7964 normalizeDeprecatedResult: utils.normalizeDeprecatedResult,
7965 normalizeForwardResult: utils.normalizeForwardResult,
7966 normalizeRedirectResult: utils.normalizeRedirectResult,
7967 normalizeValidateResult: utils.normalizeValidateResult
7969 this._unknownHandler = unknown;
7970 this._invalidHandler = invalid;
7971 this._deprecatedHandler = deprecated;
7972 this.cleanHistory();
7975 _createClass(Normalizer, [{
7976 key: "cleanHistory",
7977 value: function cleanHistory() {
7978 this._hasDeprecationWarned = utils.createAutoChecklist();
7982 value: function normalize(options) {
7985 var normalized = {};
7986 var restOptionsArray = [options];
7988 var applyNormalization = function applyNormalization() {
7989 while (restOptionsArray.length !== 0) {
7990 var currentOptions = restOptionsArray.shift();
7992 var transferredOptionsArray = _this._applyNormalization(currentOptions, normalized);
7994 restOptionsArray.push.apply(restOptionsArray, _toConsumableArray$1(transferredOptionsArray));
7998 applyNormalization();
8000 for (var _i = 0, _Object$keys = Object.keys(this._utils.schemas); _i < _Object$keys.length; _i++) {
8001 var key = _Object$keys[_i];
8002 var schema = this._utils.schemas[key];
8004 if (!(key in normalized)) {
8005 var defaultResult = utils.normalizeDefaultResult(schema.default(this._utils));
8007 if ('value' in defaultResult) {
8008 restOptionsArray.push({
8009 [key]: defaultResult.value
8015 applyNormalization();
8017 for (var _i2 = 0, _Object$keys2 = Object.keys(this._utils.schemas); _i2 < _Object$keys2.length; _i2++) {
8018 var _key = _Object$keys2[_i2];
8019 var _schema = this._utils.schemas[_key];
8021 if (_key in normalized) {
8022 normalized[_key] = _schema.postprocess(normalized[_key], this._utils);
8029 key: "_applyNormalization",
8030 value: function _applyNormalization(options, normalized) {
8033 var transferredOptionsArray = [];
8035 var _utils_1$partition = utils.partition(Object.keys(options), function (key) {
8036 return key in _this2._utils.schemas;
8038 _utils_1$partition2 = _slicedToArray(_utils_1$partition, 2),
8039 knownOptionNames = _utils_1$partition2[0],
8040 unknownOptionNames = _utils_1$partition2[1];
8042 var _iteratorNormalCompletion = true;
8043 var _didIteratorError = false;
8044 var _iteratorError = undefined;
8047 var _loop = function _loop() {
8048 var key = _step.value;
8049 var schema = _this2._utils.schemas[key];
8050 var value = schema.preprocess(options[key], _this2._utils);
8051 var validateResult = utils.normalizeValidateResult(schema.validate(value, _this2._utils), value);
8053 if (validateResult !== true) {
8054 var invalidValue = validateResult.value;
8056 var errorMessageOrError = _this2._invalidHandler(key, invalidValue, _this2._utils);
8058 throw typeof errorMessageOrError === 'string' ? new Error(errorMessageOrError) :
8059 /* istanbul ignore next*/
8060 errorMessageOrError;
8063 var appendTransferredOptions = function appendTransferredOptions(_ref2) {
8064 var from = _ref2.from,
8066 transferredOptionsArray.push(typeof to === 'string' ? {
8073 var warnDeprecated = function warnDeprecated(_ref3) {
8074 var currentValue = _ref3.value,
8075 redirectTo = _ref3.redirectTo;
8076 var deprecatedResult = utils.normalizeDeprecatedResult(schema.deprecated(currentValue, _this2._utils), value,
8077 /* doNotNormalizeTrue */
8080 if (deprecatedResult === false) {
8084 if (deprecatedResult === true) {
8085 if (!_this2._hasDeprecationWarned(key)) {
8086 _this2._utils.logger.warn(_this2._deprecatedHandler(key, redirectTo, _this2._utils));
8089 var _iteratorNormalCompletion3 = true;
8090 var _didIteratorError3 = false;
8091 var _iteratorError3 = undefined;
8094 for (var _iterator3 = deprecatedResult[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
8095 var deprecatedValue = _step3.value.value;
8098 value: deprecatedValue
8101 if (!_this2._hasDeprecationWarned(pair)) {
8102 var redirectToPair = typeof redirectTo === 'string' ? {
8104 value: deprecatedValue
8107 _this2._utils.logger.warn(_this2._deprecatedHandler(pair, redirectToPair, _this2._utils));
8111 _didIteratorError3 = true;
8112 _iteratorError3 = err;
8115 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
8116 _iterator3.return();
8119 if (_didIteratorError3) {
8120 throw _iteratorError3;
8127 var forwardResult = utils.normalizeForwardResult(schema.forward(value, _this2._utils), value);
8128 forwardResult.forEach(appendTransferredOptions);
8129 var redirectResult = utils.normalizeRedirectResult(schema.redirect(value, _this2._utils), value);
8130 redirectResult.redirect.forEach(appendTransferredOptions);
8132 if ('remain' in redirectResult) {
8133 var remainingValue = redirectResult.remain;
8134 normalized[key] = key in normalized ? schema.overlap(normalized[key], remainingValue, _this2._utils) : remainingValue;
8136 value: remainingValue
8140 var _iteratorNormalCompletion4 = true;
8141 var _didIteratorError4 = false;
8142 var _iteratorError4 = undefined;
8145 for (var _iterator4 = redirectResult.redirect[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
8146 var _step4$value = _step4.value,
8147 from = _step4$value.from,
8148 to = _step4$value.to;
8155 _didIteratorError4 = true;
8156 _iteratorError4 = err;
8159 if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
8160 _iterator4.return();
8163 if (_didIteratorError4) {
8164 throw _iteratorError4;
8170 for (var _iterator = knownOptionNames[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
8174 _didIteratorError = true;
8175 _iteratorError = err;
8178 if (!_iteratorNormalCompletion && _iterator.return != null) {
8182 if (_didIteratorError) {
8183 throw _iteratorError;
8188 var _iteratorNormalCompletion2 = true;
8189 var _didIteratorError2 = false;
8190 var _iteratorError2 = undefined;
8193 for (var _iterator2 = unknownOptionNames[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
8194 var key = _step2.value;
8195 var value = options[key];
8197 var unknownResult = this._unknownHandler(key, value, this._utils);
8199 if (unknownResult) {
8200 for (var _i3 = 0, _Object$keys3 = Object.keys(unknownResult); _i3 < _Object$keys3.length; _i3++) {
8201 var unknownKey = _Object$keys3[_i3];
8202 var unknownOption = {
8203 [unknownKey]: unknownResult[unknownKey]
8206 if (unknownKey in this._utils.schemas) {
8207 transferredOptionsArray.push(unknownOption);
8209 Object.assign(normalized, unknownOption);
8215 _didIteratorError2 = true;
8216 _iteratorError2 = err;
8219 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
8220 _iterator2.return();
8223 if (_didIteratorError2) {
8224 throw _iteratorError2;
8229 return transferredOptionsArray;
8236 exports.Normalizer = Normalizer;
8238 unwrapExports(normalize);
8239 var normalize_1 = normalize.normalize;
8240 var normalize_2 = normalize.Normalizer;
8242 var lib = createCommonjsModule(function (module, exports) {
8244 Object.defineProperty(exports, "__esModule", {
8248 tslib_es6.__exportStar(descriptors, exports);
8250 tslib_es6.__exportStar(handlers, exports);
8252 tslib_es6.__exportStar(schemas, exports);
8254 tslib_es6.__exportStar(normalize, exports);
8256 tslib_es6.__exportStar(schema, exports);
8261 var charCodeCache$1 = [];
8263 var leven$1 = function leven(left, right) {
8264 if (left === right) {
8268 var swap = left; // Swapping the strings if `a` is longer than `b` so we know which one is the
8269 // shortest & which one is the longest
8271 if (left.length > right.length) {
8276 var leftLength = left.length;
8277 var rightLength = right.length; // Performing suffix trimming:
8278 // We can linearly drop suffix common to both strings since they
8279 // don't increase distance at all
8280 // Note: `~-` is the bitwise way to perform a `- 1` operation
8282 while (leftLength > 0 && left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength)) {
8285 } // Performing prefix trimming
8286 // We can linearly drop prefix common to both strings since they
8287 // don't increase distance at all
8292 while (start < leftLength && left.charCodeAt(start) === right.charCodeAt(start)) {
8296 leftLength -= start;
8297 rightLength -= start;
8299 if (leftLength === 0) {
8310 while (i < leftLength) {
8311 charCodeCache$1[i] = left.charCodeAt(start + i);
8315 while (j < rightLength) {
8316 bCharCode = right.charCodeAt(start + j);
8320 for (i = 0; i < leftLength; i++) {
8321 temp2 = bCharCode === charCodeCache$1[i] ? temp : temp + 1;
8322 temp = array$1[i]; // eslint-disable-next-line no-multi-assign
8324 result = array$1[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2;
8331 var leven_1$1 = leven$1; // TODO: Remove this for the next major release
8333 var default_1 = leven$1;
8334 leven_1$1.default = default_1;
8336 var cliDescriptor = {
8337 key: function key(_key) {
8338 return _key.length === 1 ? `-${_key}` : `--${_key}`;
8340 value: function value(_value) {
8341 return lib.apiDescriptor.value(_value);
8343 pair: function pair(_ref) {
8346 return value === false ? `--no-${key}` : value === true ? cliDescriptor.key(key) : value === "" ? `${cliDescriptor.key(key)} without an argument` : `${cliDescriptor.key(key)}=${value}`;
8352 function (_vnopts$ChoiceSchema) {
8353 _inherits(FlagSchema, _vnopts$ChoiceSchema);
8355 function FlagSchema(_ref2) {
8358 var name = _ref2.name,
8359 flags = _ref2.flags;
8361 _classCallCheck(this, FlagSchema);
8363 _this = _possibleConstructorReturn(this, _getPrototypeOf(FlagSchema).call(this, {
8367 _this._flags = flags.slice().sort();
8371 _createClass(FlagSchema, [{
8373 value: function preprocess(value, utils) {
8374 if (typeof value === "string" && value.length !== 0 && this._flags.indexOf(value) === -1) {
8375 var suggestion = this._flags.find(function (flag) {
8376 return leven_1$1(flag, value) < 3;
8380 utils.logger.warn([`Unknown flag ${chalk.yellow(utils.descriptor.value(value))},`, `did you mean ${chalk.blue(utils.descriptor.value(suggestion))}?`].join(" "));
8389 value: function expected() {
8395 }(lib.ChoiceSchema);
8397 var hasDeprecationWarned;
8399 function normalizeOptions(options, optionInfos) {
8400 var _ref3 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
8401 logger = _ref3.logger,
8402 _ref3$isCLI = _ref3.isCLI,
8403 isCLI = _ref3$isCLI === void 0 ? false : _ref3$isCLI,
8404 _ref3$passThrough = _ref3.passThrough,
8405 passThrough = _ref3$passThrough === void 0 ? false : _ref3$passThrough;
8407 var unknown = !passThrough ? lib.levenUnknownHandler : Array.isArray(passThrough) ? function (key, value) {
8408 return passThrough.indexOf(key) === -1 ? undefined : {
8411 } : function (key, value) {
8416 var descriptor = isCLI ? cliDescriptor : lib.apiDescriptor;
8417 var schemas = optionInfosToSchemas(optionInfos, {
8420 var normalizer = new lib.Normalizer(schemas, {
8425 var shouldSuppressDuplicateDeprecationWarnings = logger !== false;
8427 if (shouldSuppressDuplicateDeprecationWarnings && hasDeprecationWarned) {
8428 normalizer._hasDeprecationWarned = hasDeprecationWarned;
8431 var normalized = normalizer.normalize(options);
8433 if (shouldSuppressDuplicateDeprecationWarnings) {
8434 hasDeprecationWarned = normalizer._hasDeprecationWarned;
8440 function optionInfosToSchemas(optionInfos, _ref4) {
8441 var isCLI = _ref4.isCLI;
8445 schemas.push(lib.AnySchema.create({
8450 var _iteratorNormalCompletion = true;
8451 var _didIteratorError = false;
8452 var _iteratorError = undefined;
8455 for (var _iterator = optionInfos[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
8456 var optionInfo = _step.value;
8457 schemas.push(optionInfoToSchema(optionInfo, {
8462 if (optionInfo.alias && isCLI) {
8463 schemas.push(lib.AliasSchema.create({
8464 name: optionInfo.alias,
8465 sourceName: optionInfo.name
8470 _didIteratorError = true;
8471 _iteratorError = err;
8474 if (!_iteratorNormalCompletion && _iterator.return != null) {
8478 if (_didIteratorError) {
8479 throw _iteratorError;
8487 function optionInfoToSchema(optionInfo, _ref5) {
8488 var isCLI = _ref5.isCLI,
8489 optionInfos = _ref5.optionInfos;
8490 var SchemaConstructor;
8492 name: optionInfo.name
8496 switch (optionInfo.type) {
8498 SchemaConstructor = lib.IntegerSchema;
8501 parameters.preprocess = function (value) {
8502 return Number(value);
8509 SchemaConstructor = lib.StringSchema;
8513 SchemaConstructor = lib.ChoiceSchema;
8514 parameters.choices = optionInfo.choices.map(function (choiceInfo) {
8515 return typeof choiceInfo === "object" && choiceInfo.redirect ? Object.assign({}, choiceInfo, {
8518 key: optionInfo.name,
8519 value: choiceInfo.redirect
8527 SchemaConstructor = lib.BooleanSchema;
8531 SchemaConstructor = FlagSchema;
8532 parameters.flags = optionInfos.map(function (optionInfo) {
8533 return [].concat(optionInfo.alias || [], optionInfo.description ? optionInfo.name : [], optionInfo.oppositeDescription ? `no-${optionInfo.name}` : []);
8534 }).reduce(function (a, b) {
8540 SchemaConstructor = lib.StringSchema;
8544 throw new Error(`Unexpected type ${optionInfo.type}`);
8547 if (optionInfo.exception) {
8548 parameters.validate = function (value, schema, utils) {
8549 return optionInfo.exception(value) || schema.validate(value, utils);
8552 parameters.validate = function (value, schema, utils) {
8553 return value === undefined || schema.validate(value, utils);
8557 if (optionInfo.redirect) {
8558 handlers.redirect = function (value) {
8559 return !value ? undefined : {
8561 key: optionInfo.redirect.option,
8562 value: optionInfo.redirect.value
8568 if (optionInfo.deprecated) {
8569 handlers.deprecated = true;
8570 } // allow CLI overriding, e.g., prettier package.json --tab-width 1 --tab-width 2
8573 if (isCLI && !optionInfo.array) {
8574 var originalPreprocess = parameters.preprocess || function (x) {
8578 parameters.preprocess = function (value, schema, utils) {
8579 return schema.preprocess(originalPreprocess(Array.isArray(value) ? value[value.length - 1] : value), utils);
8583 return optionInfo.array ? lib.ArraySchema.create(Object.assign(isCLI ? {
8584 preprocess: function preprocess(v) {
8585 return [].concat(v);
8588 valueSchema: SchemaConstructor.create(parameters)
8589 })) : SchemaConstructor.create(Object.assign({}, parameters, handlers));
8592 function normalizeApiOptions(options, optionInfos, opts) {
8593 return normalizeOptions(options, optionInfos, opts);
8596 function normalizeCliOptions(options, optionInfos, opts) {
8597 return normalizeOptions(options, optionInfos, Object.assign({
8602 var optionsNormalizer = {
8603 normalizeApiOptions,
8607 var getLast = function getLast(arr) {
8608 return arr.length > 0 ? arr[arr.length - 1] : null;
8611 function locStart(node, opts) {
8612 opts = opts || {}; // Handle nodes with decorators. They should start at the first decorator
8614 if (!opts.ignoreDecorators && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0) {
8615 return locStart(node.declaration.decorators[0]);
8618 if (!opts.ignoreDecorators && node.decorators && node.decorators.length > 0) {
8619 return locStart(node.decorators[0]);
8622 if (node.__location) {
8623 return node.__location.startOffset;
8627 return node.range[0];
8630 if (typeof node.start === "number") {
8635 return node.loc.start;
8641 function locEnd(node) {
8642 var endNode = node.nodes && getLast(node.nodes);
8644 if (endNode && node.source && !node.source.end) {
8648 if (node.__location) {
8649 return node.__location.endOffset;
8652 var loc = node.range ? node.range[1] : typeof node.end === "number" ? node.end : null;
8654 if (node.typeAnnotation) {
8655 return Math.max(loc, locEnd(node.typeAnnotation));
8658 if (node.loc && !loc) {
8659 return node.loc.end;
8670 var jsTokens = createCommonjsModule(function (module, exports) {
8671 // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell
8672 // License: MIT. (See LICENSE.)
8673 Object.defineProperty(exports, "__esModule", {
8675 }); // This regex comes from regex.coffee, and is inserted here by generate-index.js
8676 // (run `npm run build`).
8678 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;
8680 exports.matchToToken = function (match) {
8686 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";
8690 unwrapExports(jsTokens);
8691 var jsTokens_1 = jsTokens.matchToToken;
8693 var ast = createCommonjsModule(function (module) {
8695 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
8697 Redistribution and use in source and binary forms, with or without
8698 modification, are permitted provided that the following conditions are met:
8700 * Redistributions of source code must retain the above copyright
8701 notice, this list of conditions and the following disclaimer.
8702 * Redistributions in binary form must reproduce the above copyright
8703 notice, this list of conditions and the following disclaimer in the
8704 documentation and/or other materials provided with the distribution.
8706 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
8707 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
8708 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
8709 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
8710 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
8711 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
8712 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
8713 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8714 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8715 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8719 function isExpression(node) {
8724 switch (node.type) {
8725 case 'ArrayExpression':
8726 case 'AssignmentExpression':
8727 case 'BinaryExpression':
8728 case 'CallExpression':
8729 case 'ConditionalExpression':
8730 case 'FunctionExpression':
8733 case 'LogicalExpression':
8734 case 'MemberExpression':
8735 case 'NewExpression':
8736 case 'ObjectExpression':
8737 case 'SequenceExpression':
8738 case 'ThisExpression':
8739 case 'UnaryExpression':
8740 case 'UpdateExpression':
8747 function isIterationStatement(node) {
8752 switch (node.type) {
8753 case 'DoWhileStatement':
8754 case 'ForInStatement':
8755 case 'ForStatement':
8756 case 'WhileStatement':
8763 function isStatement(node) {
8768 switch (node.type) {
8769 case 'BlockStatement':
8770 case 'BreakStatement':
8771 case 'ContinueStatement':
8772 case 'DebuggerStatement':
8773 case 'DoWhileStatement':
8774 case 'EmptyStatement':
8775 case 'ExpressionStatement':
8776 case 'ForInStatement':
8777 case 'ForStatement':
8779 case 'LabeledStatement':
8780 case 'ReturnStatement':
8781 case 'SwitchStatement':
8782 case 'ThrowStatement':
8783 case 'TryStatement':
8784 case 'VariableDeclaration':
8785 case 'WhileStatement':
8786 case 'WithStatement':
8793 function isSourceElement(node) {
8794 return isStatement(node) || node != null && node.type === 'FunctionDeclaration';
8797 function trailingStatement(node) {
8798 switch (node.type) {
8800 if (node.alternate != null) {
8801 return node.alternate;
8804 return node.consequent;
8806 case 'LabeledStatement':
8807 case 'ForStatement':
8808 case 'ForInStatement':
8809 case 'WhileStatement':
8810 case 'WithStatement':
8817 function isProblematicIfStatement(node) {
8820 if (node.type !== 'IfStatement') {
8824 if (node.alternate == null) {
8828 current = node.consequent;
8831 if (current.type === 'IfStatement') {
8832 if (current.alternate == null) {
8837 current = trailingStatement(current);
8844 isExpression: isExpression,
8845 isStatement: isStatement,
8846 isIterationStatement: isIterationStatement,
8847 isSourceElement: isSourceElement,
8848 isProblematicIfStatement: isProblematicIfStatement,
8849 trailingStatement: trailingStatement
8852 /* vim: set sw=4 ts=4 et tw=80 : */
8855 var ast_1 = ast.isExpression;
8856 var ast_2 = ast.isStatement;
8857 var ast_3 = ast.isIterationStatement;
8858 var ast_4 = ast.isSourceElement;
8859 var ast_5 = ast.isProblematicIfStatement;
8860 var ast_6 = ast.trailingStatement;
8862 var code = createCommonjsModule(function (module) {
8864 Copyright (C) 2013-2014 Yusuke Suzuki <utatane.tea@gmail.com>
8865 Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
8867 Redistribution and use in source and binary forms, with or without
8868 modification, are permitted provided that the following conditions are met:
8870 * Redistributions of source code must retain the above copyright
8871 notice, this list of conditions and the following disclaimer.
8872 * Redistributions in binary form must reproduce the above copyright
8873 notice, this list of conditions and the following disclaimer in the
8874 documentation and/or other materials provided with the distribution.
8876 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
8877 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
8878 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
8879 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
8880 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
8881 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
8882 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
8883 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
8884 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
8885 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
8889 var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`.
8892 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart:
8893 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]/,
8894 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart:
8895 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]/
8898 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart:
8899 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]/,
8900 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart:
8901 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]/
8904 function isDecimalDigit(ch) {
8905 return 0x30 <= ch && ch <= 0x39; // 0..9
8908 function isHexDigit(ch) {
8909 return 0x30 <= ch && ch <= 0x39 || // 0..9
8910 0x61 <= ch && ch <= 0x66 || // a..f
8911 0x41 <= ch && ch <= 0x46; // A..F
8914 function isOctalDigit(ch) {
8915 return ch >= 0x30 && ch <= 0x37; // 0..7
8916 } // 7.2 White Space
8919 NON_ASCII_WHITESPACES = [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF];
8921 function isWhiteSpace(ch) {
8922 return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
8923 } // 7.3 Line Terminators
8926 function isLineTerminator(ch) {
8927 return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;
8928 } // 7.6 Identifier Names and Identifiers
8931 function fromCodePoint(cp) {
8933 return String.fromCharCode(cp);
8936 var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800);
8937 var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00);
8941 IDENTIFIER_START = new Array(0x80);
8943 for (ch = 0; ch < 0x80; ++ch) {
8944 IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
8945 ch >= 0x41 && ch <= 0x5A || // A..Z
8946 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
8949 IDENTIFIER_PART = new Array(0x80);
8951 for (ch = 0; ch < 0x80; ++ch) {
8952 IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
8953 ch >= 0x41 && ch <= 0x5A || // A..Z
8954 ch >= 0x30 && ch <= 0x39 || // 0..9
8955 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
8958 function isIdentifierStartES5(ch) {
8959 return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
8962 function isIdentifierPartES5(ch) {
8963 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
8966 function isIdentifierStartES6(ch) {
8967 return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
8970 function isIdentifierPartES6(ch) {
8971 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
8975 isDecimalDigit: isDecimalDigit,
8976 isHexDigit: isHexDigit,
8977 isOctalDigit: isOctalDigit,
8978 isWhiteSpace: isWhiteSpace,
8979 isLineTerminator: isLineTerminator,
8980 isIdentifierStartES5: isIdentifierStartES5,
8981 isIdentifierPartES5: isIdentifierPartES5,
8982 isIdentifierStartES6: isIdentifierStartES6,
8983 isIdentifierPartES6: isIdentifierPartES6
8986 /* vim: set sw=4 ts=4 et tw=80 : */
8989 var code_1 = code.isDecimalDigit;
8990 var code_2 = code.isHexDigit;
8991 var code_3 = code.isOctalDigit;
8992 var code_4 = code.isWhiteSpace;
8993 var code_5 = code.isLineTerminator;
8994 var code_6 = code.isIdentifierStartES5;
8995 var code_7 = code.isIdentifierPartES5;
8996 var code_8 = code.isIdentifierStartES6;
8997 var code_9 = code.isIdentifierPartES6;
8999 var keyword = createCommonjsModule(function (module) {
9001 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
9003 Redistribution and use in source and binary forms, with or without
9004 modification, are permitted provided that the following conditions are met:
9006 * Redistributions of source code must retain the above copyright
9007 notice, this list of conditions and the following disclaimer.
9008 * Redistributions in binary form must reproduce the above copyright
9009 notice, this list of conditions and the following disclaimer in the
9010 documentation and/or other materials provided with the distribution.
9012 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
9013 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
9014 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
9015 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
9016 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
9017 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
9018 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
9019 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9020 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
9021 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9027 function isStrictModeReservedWordES6(id) {
9044 function isKeywordES5(id, strict) {
9045 // yield should not be treated as keyword under non-strict mode.
9046 if (!strict && id === 'yield') {
9050 return isKeywordES6(id, strict);
9053 function isKeywordES6(id, strict) {
9054 if (strict && isStrictModeReservedWordES6(id)) {
9058 switch (id.length) {
9060 return id === 'if' || id === 'in' || id === 'do';
9063 return id === 'var' || id === 'for' || id === 'new' || id === 'try';
9066 return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum';
9069 return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super';
9072 return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import';
9075 return id === 'default' || id === 'finally' || id === 'extends';
9078 return id === 'function' || id === 'continue' || id === 'debugger';
9081 return id === 'instanceof';
9088 function isReservedWordES5(id, strict) {
9089 return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict);
9092 function isReservedWordES6(id, strict) {
9093 return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict);
9096 function isRestrictedWord(id) {
9097 return id === 'eval' || id === 'arguments';
9100 function isIdentifierNameES5(id) {
9103 if (id.length === 0) {
9107 ch = id.charCodeAt(0);
9109 if (!code$1.isIdentifierStartES5(ch)) {
9113 for (i = 1, iz = id.length; i < iz; ++i) {
9114 ch = id.charCodeAt(i);
9116 if (!code$1.isIdentifierPartES5(ch)) {
9124 function decodeUtf16(lead, trail) {
9125 return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
9128 function isIdentifierNameES6(id) {
9129 var i, iz, ch, lowCh, check;
9131 if (id.length === 0) {
9135 check = code$1.isIdentifierStartES6;
9137 for (i = 0, iz = id.length; i < iz; ++i) {
9138 ch = id.charCodeAt(i);
9140 if (0xD800 <= ch && ch <= 0xDBFF) {
9147 lowCh = id.charCodeAt(i);
9149 if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) {
9153 ch = decodeUtf16(ch, lowCh);
9160 check = code$1.isIdentifierPartES6;
9166 function isIdentifierES5(id, strict) {
9167 return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
9170 function isIdentifierES6(id, strict) {
9171 return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
9175 isKeywordES5: isKeywordES5,
9176 isKeywordES6: isKeywordES6,
9177 isReservedWordES5: isReservedWordES5,
9178 isReservedWordES6: isReservedWordES6,
9179 isRestrictedWord: isRestrictedWord,
9180 isIdentifierNameES5: isIdentifierNameES5,
9181 isIdentifierNameES6: isIdentifierNameES6,
9182 isIdentifierES5: isIdentifierES5,
9183 isIdentifierES6: isIdentifierES6
9186 /* vim: set sw=4 ts=4 et tw=80 : */
9189 var keyword_1 = keyword.isKeywordES5;
9190 var keyword_2 = keyword.isKeywordES6;
9191 var keyword_3 = keyword.isReservedWordES5;
9192 var keyword_4 = keyword.isReservedWordES6;
9193 var keyword_5 = keyword.isRestrictedWord;
9194 var keyword_6 = keyword.isIdentifierNameES5;
9195 var keyword_7 = keyword.isIdentifierNameES6;
9196 var keyword_8 = keyword.isIdentifierES5;
9197 var keyword_9 = keyword.isIdentifierES6;
9199 var utils$1 = createCommonjsModule(function (module, exports) {
9201 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
9203 Redistribution and use in source and binary forms, with or without
9204 modification, are permitted provided that the following conditions are met:
9206 * Redistributions of source code must retain the above copyright
9207 notice, this list of conditions and the following disclaimer.
9208 * Redistributions in binary form must reproduce the above copyright
9209 notice, this list of conditions and the following disclaimer in the
9210 documentation and/or other materials provided with the distribution.
9212 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
9213 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
9214 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
9215 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
9216 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
9217 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
9218 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
9219 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
9220 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
9221 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
9226 exports.code = code;
9227 exports.keyword = keyword;
9229 /* vim: set sw=4 ts=4 et tw=80 : */
9232 var utils_1$1 = utils$1.ast;
9233 var utils_2$1 = utils$1.code;
9234 var utils_3$1 = utils$1.keyword;
9236 var lib$1 = createCommonjsModule(function (module, exports) {
9238 Object.defineProperty(exports, "__esModule", {
9241 exports.shouldHighlight = shouldHighlight;
9242 exports.getChalk = getChalk;
9243 exports.default = highlight;
9245 function _jsTokens() {
9246 var data = _interopRequireWildcard(jsTokens);
9248 _jsTokens = function _jsTokens() {
9255 function _esutils() {
9256 var data = _interopRequireDefault(utils$1);
9258 _esutils = function _esutils() {
9266 var data = _interopRequireDefault(chalk);
9268 _chalk = function _chalk() {
9275 function _interopRequireDefault(obj) {
9276 return obj && obj.__esModule ? obj : {
9281 function _interopRequireWildcard(obj) {
9282 if (obj && obj.__esModule) {
9288 for (var key in obj) {
9289 if (Object.prototype.hasOwnProperty.call(obj, key)) {
9290 var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
9292 if (desc.get || desc.set) {
9293 Object.defineProperty(newObj, key, desc);
9295 newObj[key] = obj[key];
9301 newObj.default = obj;
9306 function getDefs(chalk) {
9308 keyword: chalk.cyan,
9309 capitalized: chalk.yellow,
9310 jsx_tag: chalk.yellow,
9311 punctuator: chalk.yellow,
9312 number: chalk.magenta,
9313 string: chalk.green,
9314 regex: chalk.magenta,
9315 comment: chalk.grey,
9316 invalid: chalk.white.bgRed.bold
9320 var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
9321 var JSX_TAG = /^[a-z][\w-]*$/i;
9322 var BRACKET = /^[()[\]{}]$/;
9324 function getTokenType(match) {
9325 var _match$slice = match.slice(-2),
9326 _match$slice2 = _slicedToArray(_match$slice, 2),
9327 offset = _match$slice2[0],
9328 text = _match$slice2[1];
9330 var token = (0, _jsTokens().matchToToken)(match);
9332 if (token.type === "name") {
9333 if (_esutils().default.keyword.isReservedWordES6(token.value)) {
9337 if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
9341 if (token.value[0] !== token.value[0].toLowerCase()) {
9342 return "capitalized";
9346 if (token.type === "punctuator" && BRACKET.test(token.value)) {
9350 if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
9351 return "punctuator";
9357 function highlightTokens(defs, text) {
9358 return text.replace(_jsTokens().default, function () {
9359 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
9360 args[_key] = arguments[_key];
9363 var type = getTokenType(args);
9364 var colorize = defs[type];
9367 return args[0].split(NEWLINE).map(function (str) {
9368 return colorize(str);
9376 function shouldHighlight(options) {
9377 return _chalk().default.supportsColor || options.forceColor;
9380 function getChalk(options) {
9381 var chalk = _chalk().default;
9383 if (options.forceColor) {
9384 chalk = new (_chalk().default.constructor)({
9393 function highlight(code) {
9394 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
9396 if (shouldHighlight(options)) {
9397 var chalk = getChalk(options);
9398 var defs = getDefs(chalk);
9399 return highlightTokens(defs, code);
9405 unwrapExports(lib$1);
9406 var lib_1 = lib$1.shouldHighlight;
9407 var lib_2 = lib$1.getChalk;
9409 var lib$2 = createCommonjsModule(function (module, exports) {
9411 Object.defineProperty(exports, "__esModule", {
9414 exports.codeFrameColumns = codeFrameColumns;
9415 exports.default = _default;
9417 function _highlight() {
9418 var data = _interopRequireWildcard(lib$1);
9420 _highlight = function _highlight() {
9427 function _interopRequireWildcard(obj) {
9428 if (obj && obj.__esModule) {
9434 for (var key in obj) {
9435 if (Object.prototype.hasOwnProperty.call(obj, key)) {
9436 var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};
9438 if (desc.get || desc.set) {
9439 Object.defineProperty(newObj, key, desc);
9441 newObj[key] = obj[key];
9447 newObj.default = obj;
9452 var deprecationWarningShown = false;
9454 function getDefs(chalk) {
9457 marker: chalk.red.bold,
9458 message: chalk.red.bold
9462 var NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
9464 function getMarkerLines(loc, source, opts) {
9465 var startLoc = Object.assign({
9469 var endLoc = Object.assign({}, startLoc, loc.end);
9471 var _ref = opts || {},
9472 _ref$linesAbove = _ref.linesAbove,
9473 linesAbove = _ref$linesAbove === void 0 ? 2 : _ref$linesAbove,
9474 _ref$linesBelow = _ref.linesBelow,
9475 linesBelow = _ref$linesBelow === void 0 ? 3 : _ref$linesBelow;
9477 var startLine = startLoc.line;
9478 var startColumn = startLoc.column;
9479 var endLine = endLoc.line;
9480 var endColumn = endLoc.column;
9481 var start = Math.max(startLine - (linesAbove + 1), 0);
9482 var end = Math.min(source.length, endLine + linesBelow);
9484 if (startLine === -1) {
9488 if (endLine === -1) {
9489 end = source.length;
9492 var lineDiff = endLine - startLine;
9493 var markerLines = {};
9496 for (var i = 0; i <= lineDiff; i++) {
9497 var lineNumber = i + startLine;
9500 markerLines[lineNumber] = true;
9501 } else if (i === 0) {
9502 var sourceLength = source[lineNumber - 1].length;
9503 markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
9504 } else if (i === lineDiff) {
9505 markerLines[lineNumber] = [0, endColumn];
9507 var _sourceLength = source[lineNumber - i].length;
9508 markerLines[lineNumber] = [0, _sourceLength];
9512 if (startColumn === endColumn) {
9514 markerLines[startLine] = [startColumn, 0];
9516 markerLines[startLine] = true;
9519 markerLines[startLine] = [startColumn, endColumn - startColumn];
9530 function codeFrameColumns(rawLines, loc) {
9531 var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
9532 var highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight().shouldHighlight)(opts);
9533 var chalk = (0, _highlight().getChalk)(opts);
9534 var defs = getDefs(chalk);
9536 var maybeHighlight = function maybeHighlight(chalkFn, string) {
9537 return highlighted ? chalkFn(string) : string;
9540 var lines = rawLines.split(NEWLINE);
9542 var _getMarkerLines = getMarkerLines(loc, lines, opts),
9543 start = _getMarkerLines.start,
9544 end = _getMarkerLines.end,
9545 markerLines = _getMarkerLines.markerLines;
9547 var hasColumns = loc.start && typeof loc.start.column === "number";
9548 var numberMaxWidth = String(end).length;
9549 var highlightedLines = highlighted ? (0, _highlight().default)(rawLines, opts) : rawLines;
9550 var frame = highlightedLines.split(NEWLINE).slice(start, end).map(function (line, index) {
9551 var number = start + 1 + index;
9552 var paddedNumber = ` ${number}`.slice(-numberMaxWidth);
9553 var gutter = ` ${paddedNumber} | `;
9554 var hasMarker = markerLines[number];
9555 var lastMarkerLine = !markerLines[number + 1];
9558 var markerLine = "";
9560 if (Array.isArray(hasMarker)) {
9561 var markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
9562 var numberOfMarkers = hasMarker[1] || 1;
9563 markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
9565 if (lastMarkerLine && opts.message) {
9566 markerLine += " " + maybeHighlight(defs.message, opts.message);
9570 return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
9572 return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;
9576 if (opts.message && !hasColumns) {
9577 frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
9581 return chalk.reset(frame);
9587 function _default(rawLines, lineNumber, colNumber) {
9588 var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
9590 if (!deprecationWarningShown) {
9591 deprecationWarningShown = true;
9592 var message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
9594 if (process.emitWarning) {
9595 process.emitWarning(message, "DeprecationWarning");
9597 var deprecationError = new Error(message);
9598 deprecationError.name = "DeprecationWarning";
9599 console.warn(new Error(message));
9603 colNumber = Math.max(colNumber, 0);
9610 return codeFrameColumns(rawLines, location, opts);
9613 unwrapExports(lib$2);
9614 var lib_1$1 = lib$2.codeFrameColumns;
9616 var ConfigError$1 = errors.ConfigError;
9617 var locStart$1 = loc.locStart,
9618 locEnd$1 = loc.locEnd; // Use defineProperties()/getOwnPropertyDescriptor() to prevent
9619 // triggering the parsers getters.
9621 var ownNames = Object.getOwnPropertyNames;
9622 var ownDescriptor = Object.getOwnPropertyDescriptor;
9624 function getParsers(options) {
9626 var _iteratorNormalCompletion = true;
9627 var _didIteratorError = false;
9628 var _iteratorError = undefined;
9631 for (var _iterator = options.plugins[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
9632 var plugin = _step.value;
9634 if (!plugin.parsers) {
9638 var _iteratorNormalCompletion2 = true;
9639 var _didIteratorError2 = false;
9640 var _iteratorError2 = undefined;
9643 for (var _iterator2 = ownNames(plugin.parsers)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
9644 var name = _step2.value;
9645 Object.defineProperty(parsers, name, ownDescriptor(plugin.parsers, name));
9648 _didIteratorError2 = true;
9649 _iteratorError2 = err;
9652 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
9653 _iterator2.return();
9656 if (_didIteratorError2) {
9657 throw _iteratorError2;
9663 _didIteratorError = true;
9664 _iteratorError = err;
9667 if (!_iteratorNormalCompletion && _iterator.return != null) {
9671 if (_didIteratorError) {
9672 throw _iteratorError;
9680 function resolveParser(opts, parsers) {
9681 parsers = parsers || getParsers(opts);
9683 if (typeof opts.parser === "function") {
9684 // Custom parser API always works with JavaScript.
9687 astFormat: "estree",
9688 locStart: locStart$1,
9693 if (typeof opts.parser === "string") {
9694 if (Object.prototype.hasOwnProperty.call(parsers, opts.parser)) {
9695 return parsers[opts.parser];
9697 /* istanbul ignore next */
9703 parse: require(path$2.resolve(process.cwd(), opts.parser)),
9704 astFormat: "estree",
9705 locStart: locStart$1,
9709 /* istanbul ignore next */
9710 throw new ConfigError$1(`Couldn't resolve parser "${opts.parser}"`);
9716 function parse(text, opts) {
9717 var parsers = getParsers(opts); // Create a new object {parserName: parseFn}. Uses defineProperty() to only call
9718 // the parsers getters when actually calling the parser `parse` function.
9720 var parsersForCustomParserApi = Object.keys(parsers).reduce(function (object, parserName) {
9721 return Object.defineProperty(object, parserName, {
9725 return parsers[parserName].parse;
9730 var parser = resolveParser(opts, parsers);
9733 if (parser.preprocess) {
9734 text = parser.preprocess(text, opts);
9739 ast: parser.parse(text, parsersForCustomParserApi, opts)
9742 var loc = error.loc;
9745 var codeFrame = lib$2;
9746 error.codeFrame = codeFrame.codeFrameColumns(text, loc, {
9749 error.message += "\n" + error.codeFrame;
9752 /* istanbul ignore next */
9764 var UndefinedParserError$1 = errors.UndefinedParserError;
9765 var getSupportInfo$1 = support.getSupportInfo;
9766 var resolveParser$1 = parser.resolveParser;
9767 var hiddenDefaults = {
9768 astFormat: "estree",
9770 originalText: undefined,
9773 }; // Copy options and fill in default values.
9775 function normalize$1(options, opts) {
9777 var rawOptions = Object.assign({}, options);
9778 var supportOptions = getSupportInfo$1(null, {
9779 plugins: options.plugins,
9780 showUnreleased: true,
9781 showDeprecated: true
9783 var defaults = supportOptions.reduce(function (reduced, optionInfo) {
9784 return optionInfo.default !== undefined ? Object.assign(reduced, {
9785 [optionInfo.name]: optionInfo.default
9787 }, Object.assign({}, hiddenDefaults));
9789 if (!rawOptions.parser) {
9790 if (!rawOptions.filepath) {
9791 var logger = opts.logger || console;
9792 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.");
9793 rawOptions.parser = "babel";
9795 rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins);
9797 if (!rawOptions.parser) {
9798 throw new UndefinedParserError$1(`No parser could be inferred for file: ${rawOptions.filepath}`);
9803 var parser = resolveParser$1(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(function (x) {
9804 return x.name === "parser";
9809 rawOptions.astFormat = parser.astFormat;
9810 rawOptions.locEnd = parser.locEnd;
9811 rawOptions.locStart = parser.locStart;
9812 var plugin = getPlugin(rawOptions);
9813 rawOptions.printer = plugin.printers[rawOptions.astFormat];
9814 var pluginDefaults = supportOptions.filter(function (optionInfo) {
9815 return optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name] !== undefined;
9816 }).reduce(function (reduced, optionInfo) {
9817 return Object.assign(reduced, {
9818 [optionInfo.name]: optionInfo.pluginDefaults[plugin.name]
9821 var mixedDefaults = Object.assign({}, defaults, pluginDefaults);
9822 Object.keys(mixedDefaults).forEach(function (k) {
9823 if (rawOptions[k] == null) {
9824 rawOptions[k] = mixedDefaults[k];
9828 if (rawOptions.parser === "json") {
9829 rawOptions.trailingComma = "none";
9832 return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({
9833 passThrough: Object.keys(hiddenDefaults)
9837 function getPlugin(options) {
9838 var astFormat = options.astFormat;
9841 throw new Error("getPlugin() requires astFormat to be set");
9844 var printerPlugin = options.plugins.find(function (plugin) {
9845 return plugin.printers && plugin.printers[astFormat];
9848 if (!printerPlugin) {
9849 throw new Error(`Couldn't find plugin for AST format "${astFormat}"`);
9852 return printerPlugin;
9855 function getInterpreter(filepath) {
9856 if (typeof filepath !== "string") {
9863 fd = fs$1.openSync(filepath, "r");
9869 var liner = new readlines(fd);
9870 var firstLine = liner.next().toString("utf8"); // #!/bin/env node, #!/usr/bin/env node
9872 var m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/);
9876 } // #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node
9879 var m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/);
9887 // There are some weird cases where paths are missing, causing Jest
9888 // failures. It's unclear what these correspond to in the real world.
9892 // There are some weird cases where paths are missing, causing Jest
9893 // failures. It's unclear what these correspond to in the real world.
9895 } catch (err) {// nop
9900 function inferParser(filepath, plugins) {
9901 var filepathParts = normalizePath(filepath).split("/");
9902 var filename = filepathParts[filepathParts.length - 1].toLowerCase(); // If the file has no extension, we can try to infer the language from the
9903 // interpreter in the shebang line, if any; but since this requires FS access,
9906 var language = getSupportInfo$1(null, {
9908 }).languages.find(function (language) {
9909 return language.since !== null && (language.extensions && language.extensions.some(function (extension) {
9910 return filename.endsWith(extension);
9911 }) || language.filenames && language.filenames.find(function (name) {
9912 return name.toLowerCase() === filename;
9913 }) || filename.indexOf(".") === -1 && language.interpreters && language.interpreters.indexOf(getInterpreter(filepath)) !== -1);
9915 return language && language.parsers[0];
9919 normalize: normalize$1,
9924 function massageAST(ast, options, parent) {
9925 if (Array.isArray(ast)) {
9926 return ast.map(function (e) {
9927 return massageAST(e, options, parent);
9928 }).filter(function (e) {
9933 if (!ast || typeof ast !== "object") {
9939 for (var _i = 0, _Object$keys = Object.keys(ast); _i < _Object$keys.length; _i++) {
9940 var key = _Object$keys[_i];
9942 if (typeof ast[key] !== "function") {
9943 newObj[key] = massageAST(ast[key], options, ast);
9947 if (options.printer.massageAstNode) {
9948 var result = options.printer.massageAstNode(ast, newObj, parent);
9950 if (result === null) {
9962 var massageAst = massageAST;
9965 * @param {Doc[]} parts
9970 function concat(parts) {
9971 // access the internals of a document directly.
9972 // if(parts.length === 1) {
9973 // // If it's a single document, no need to concat it.
9984 * @param {Doc} contents
9989 function indent(contents) {
9998 * @param {Doc} contents
10003 function align(n, contents) {
10012 * @param {Doc} contents
10013 * @param {object} [opts] - TBD ???
10018 function group(contents, opts) {
10024 contents: contents,
10025 break: !!opts.shouldBreak,
10026 expandedStates: opts.expandedStates
10030 * @param {Doc} contents
10035 function dedentToRoot(contents) {
10036 return align(-Infinity, contents);
10039 * @param {Doc} contents
10044 function markAsRoot(contents) {
10045 // @ts-ignore - TBD ???:
10051 * @param {Doc} contents
10056 function dedent(contents) {
10057 return align(-1, contents);
10060 * @param {Doc[]} states
10061 * @param {object} [opts] - TBD ???
10066 function conditionalGroup(states, opts) {
10067 return group(states[0], Object.assign(opts || {}, {
10068 expandedStates: states
10072 * @param {Doc[]} parts
10077 function fill(parts) {
10085 * @param {Doc} [breakContents]
10086 * @param {Doc} [flatContents]
10087 * @param {object} [opts] - TBD ???
10092 function ifBreak(breakContents, flatContents, opts) {
10099 groupId: opts.groupId
10103 * @param {Doc} contents
10108 function lineSuffix(contents) {
10111 type: "line-suffix",
10116 var lineSuffixBoundary = {
10117 type: "line-suffix-boundary"
10119 var breakParent = {
10120 type: "break-parent"
10132 var hardline = concat([{
10136 var literalline = concat([{
10143 placeholder: Symbol("cursor")
10147 * @param {Doc[]} arr
10151 function join(sep, arr) {
10154 for (var i = 0; i < arr.length; i++) {
10162 return concat(res);
10166 * @param {number} size
10167 * @param {number} tabWidth
10171 function addAlignmentToDoc(doc, size, tabWidth) {
10175 // Use indent to add tabs for all the levels of tabs we need
10176 for (var i = 0; i < Math.floor(size / tabWidth); ++i) {
10177 aligned = indent(aligned);
10178 } // Use align for all the spaces that are needed
10181 aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current
10182 // indentation, so we use -Infinity to reset the indentation to 0
10184 aligned = align(-Infinity, aligned);
10190 var docBuilders = {
10201 lineSuffixBoundary,
10214 var ansiRegex = function ansiRegex(options) {
10215 options = Object.assign({
10218 var pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|');
10219 return new RegExp(pattern, options.onlyFirst ? undefined : 'g');
10222 var stripAnsi = function stripAnsi(string) {
10223 return typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
10226 var stripAnsi_1 = stripAnsi;
10227 var default_1$1 = stripAnsi;
10228 stripAnsi_1.default = default_1$1;
10230 /* eslint-disable yoda */
10232 var isFullwidthCodePoint = function isFullwidthCodePoint(codePoint) {
10233 if (Number.isNaN(codePoint)) {
10235 } // Code points are derived from:
10236 // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
10239 if (codePoint >= 0x1100 && (codePoint <= 0x115F || // Hangul Jamo
10240 codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET
10241 codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET
10242 // CJK Radicals Supplement .. Enclosed CJK Letters and Months
10243 0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
10244 0x3250 <= codePoint && codePoint <= 0x4DBF || // CJK Unified Ideographs .. Yi Radicals
10245 0x4E00 <= codePoint && codePoint <= 0xA4C6 || // Hangul Jamo Extended-A
10246 0xA960 <= codePoint && codePoint <= 0xA97C || // Hangul Syllables
10247 0xAC00 <= codePoint && codePoint <= 0xD7A3 || // CJK Compatibility Ideographs
10248 0xF900 <= codePoint && codePoint <= 0xFAFF || // Vertical Forms
10249 0xFE10 <= codePoint && codePoint <= 0xFE19 || // CJK Compatibility Forms .. Small Form Variants
10250 0xFE30 <= codePoint && codePoint <= 0xFE6B || // Halfwidth and Fullwidth Forms
10251 0xFF01 <= codePoint && codePoint <= 0xFF60 || 0xFFE0 <= codePoint && codePoint <= 0xFFE6 || // Kana Supplement
10252 0x1B000 <= codePoint && codePoint <= 0x1B001 || // Enclosed Ideographic Supplement
10253 0x1F200 <= codePoint && codePoint <= 0x1F251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
10254 0x20000 <= codePoint && codePoint <= 0x3FFFD)) {
10261 var isFullwidthCodePoint_1 = isFullwidthCodePoint;
10262 var default_1$2 = isFullwidthCodePoint;
10263 isFullwidthCodePoint_1.default = default_1$2;
10265 var emojiRegex = function emojiRegex() {
10266 // https://mths.be/emoji
10267 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;
10270 var stringWidth = function stringWidth(string) {
10271 string = string.replace(emojiRegex(), ' ');
10273 if (typeof string !== 'string' || string.length === 0) {
10277 string = stripAnsi_1(string);
10280 for (var i = 0; i < string.length; i++) {
10281 var code = string.codePointAt(i); // Ignore control characters
10283 if (code <= 0x1F || code >= 0x7F && code <= 0x9F) {
10285 } // Ignore combining characters
10288 if (code >= 0x300 && code <= 0x36F) {
10293 if (code > 0xFFFF) {
10297 width += isFullwidthCodePoint_1(code) ? 2 : 1;
10303 var stringWidth_1 = stringWidth; // TODO: remove this in the next major version
10305 var default_1$3 = stringWidth;
10306 stringWidth_1.default = default_1$3;
10308 var notAsciiRegex = /[^\x20-\x7F]/;
10310 function isExportDeclaration(node) {
10312 switch (node.type) {
10313 case "ExportDefaultDeclaration":
10314 case "ExportDefaultSpecifier":
10315 case "DeclareExportDeclaration":
10316 case "ExportNamedDeclaration":
10317 case "ExportAllDeclaration":
10325 function getParentExportDeclaration(path) {
10326 var parentNode = path.getParentNode();
10328 if (path.getName() === "declaration" && isExportDeclaration(parentNode)) {
10335 function getPenultimate(arr) {
10336 if (arr.length > 1) {
10337 return arr[arr.length - 2];
10343 * @typedef {{backwards?: boolean}} SkipOptions
10347 * @param {string | RegExp} chars
10348 * @returns {(text: string, index: number | false, opts?: SkipOptions) => number | false}
10352 function skip(chars) {
10353 return function (text, index, opts) {
10354 var backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having
10355 // to check for failures (did someone say monads?).
10357 if (index === false) {
10361 var length = text.length;
10362 var cursor = index;
10364 while (cursor >= 0 && cursor < length) {
10365 var c = text.charAt(cursor);
10367 if (chars instanceof RegExp) {
10368 if (!chars.test(c)) {
10371 } else if (chars.indexOf(c) === -1) {
10375 backwards ? cursor-- : cursor++;
10378 if (cursor === -1 || cursor === length) {
10379 // If we reached the beginning or end of the file, return the
10380 // out-of-bounds cursor. It's up to the caller to handle this
10381 // correctly. We don't want to indicate `false` though if it
10382 // actually skipped valid characters.
10390 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
10394 var skipWhitespace = skip(/\s/);
10396 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
10399 var skipSpaces = skip(" \t");
10401 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
10404 var skipToLineEnd = skip(",; \t");
10406 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
10409 var skipEverythingButNewLine = skip(/[^\r\n]/);
10411 * @param {string} text
10412 * @param {number | false} index
10413 * @returns {number | false}
10416 function skipInlineComment(text, index) {
10417 if (index === false) {
10421 if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") {
10422 for (var i = index + 2; i < text.length; ++i) {
10423 if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") {
10432 * @param {string} text
10433 * @param {number | false} index
10434 * @returns {number | false}
10438 function skipTrailingComment(text, index) {
10439 if (index === false) {
10443 if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") {
10444 return skipEverythingButNewLine(text, index);
10448 } // This one doesn't use the above helper function because it wants to
10449 // test \r\n in order and `skip` doesn't support ordering and we only
10450 // want to skip one newline. It's simple to implement.
10453 * @param {string} text
10454 * @param {number | false} index
10455 * @param {SkipOptions=} opts
10456 * @returns {number | false}
10460 function skipNewline(text, index, opts) {
10461 var backwards = opts && opts.backwards;
10463 if (index === false) {
10467 var atIndex = text.charAt(index);
10470 if (text.charAt(index - 1) === "\r" && atIndex === "\n") {
10474 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
10478 if (atIndex === "\r" && text.charAt(index + 1) === "\n") {
10482 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
10490 * @param {string} text
10491 * @param {number} index
10492 * @param {SkipOptions=} opts
10493 * @returns {boolean}
10497 function hasNewline(text, index, opts) {
10499 var idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
10500 var idx2 = skipNewline(text, idx, opts);
10501 return idx !== idx2;
10504 * @param {string} text
10505 * @param {number} start
10506 * @param {number} end
10507 * @returns {boolean}
10511 function hasNewlineInRange(text, start, end) {
10512 for (var i = start; i < end; ++i) {
10513 if (text.charAt(i) === "\n") {
10519 } // Note: this function doesn't ignore leading comments unlike isNextLineEmpty
10523 * @param {string} text
10525 * @param {(node: N) => number} locStart
10529 function isPreviousLineEmpty(text, node, locStart) {
10530 /** @type {number | false} */
10531 var idx = locStart(node) - 1;
10532 idx = skipSpaces(text, idx, {
10535 idx = skipNewline(text, idx, {
10538 idx = skipSpaces(text, idx, {
10541 var idx2 = skipNewline(text, idx, {
10544 return idx !== idx2;
10547 * @param {string} text
10548 * @param {number} index
10549 * @returns {boolean}
10553 function isNextLineEmptyAfterIndex(text, index) {
10554 /** @type {number | false} */
10556 /** @type {number | false} */
10560 while (idx !== oldIdx) {
10561 // We need to skip all the potential trailing inline comments
10563 idx = skipToLineEnd(text, idx);
10564 idx = skipInlineComment(text, idx);
10565 idx = skipSpaces(text, idx);
10568 idx = skipTrailingComment(text, idx);
10569 idx = skipNewline(text, idx);
10570 return idx !== false && hasNewline(text, idx);
10574 * @param {string} text
10576 * @param {(node: N) => number} locEnd
10577 * @returns {boolean}
10581 function isNextLineEmpty(text, node, locEnd) {
10582 return isNextLineEmptyAfterIndex(text, locEnd(node));
10585 * @param {string} text
10586 * @param {number} idx
10587 * @returns {number | false}
10591 function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) {
10592 /** @type {number | false} */
10594 /** @type {number | false} */
10598 while (nextIdx !== oldIdx) {
10600 nextIdx = skipSpaces(text, nextIdx);
10601 nextIdx = skipInlineComment(text, nextIdx);
10602 nextIdx = skipTrailingComment(text, nextIdx);
10603 nextIdx = skipNewline(text, nextIdx);
10610 * @param {string} text
10612 * @param {(node: N) => number} locEnd
10613 * @returns {number | false}
10617 function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) {
10618 return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node));
10622 * @param {string} text
10624 * @param {(node: N) => number} locEnd
10625 * @returns {string}
10629 function getNextNonSpaceNonCommentCharacter(text, node, locEnd) {
10630 return text.charAt( // @ts-ignore => TBD: can return false, should we define a fallback?
10631 getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd));
10634 * @param {string} text
10635 * @param {number} index
10636 * @param {SkipOptions=} opts
10637 * @returns {boolean}
10641 function hasSpaces(text, index, opts) {
10643 var idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
10644 return idx !== index;
10647 * @param {{range?: [number, number], start?: number}} node
10648 * @param {number} index
10652 function setLocStart(node, index) {
10654 node.range[0] = index;
10656 node.start = index;
10660 * @param {{range?: [number, number], end?: number}} node
10661 * @param {number} index
10665 function setLocEnd(node, index) {
10667 node.range[1] = index;
10673 var PRECEDENCE = {};
10674 [["|>"], ["??"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach(function (tier, i) {
10675 tier.forEach(function (op) {
10676 PRECEDENCE[op] = i;
10680 function getPrecedence(op) {
10681 return PRECEDENCE[op];
10684 var equalityOperators = {
10690 var multiplicativeOperators = {
10695 var bitshiftOperators = {
10701 function shouldFlatten(parentOp, nodeOp) {
10702 if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) {
10704 } // ** is right-associative
10705 // x ** y ** z --> x ** (y ** z)
10708 if (parentOp === "**") {
10710 } // x == y == z --> (x == y) == z
10713 if (equalityOperators[parentOp] && equalityOperators[nodeOp]) {
10715 } // x * y % z --> (x * y) % z
10718 if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) {
10720 } // x * y / z --> (x * y) / z
10721 // x / y * z --> (x / y) * z
10724 if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) {
10726 } // x << y << z --> (x << y) << z
10729 if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) {
10736 function isBitwiseOperator(operator) {
10737 return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&";
10738 } // Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr
10739 // holds) `function`, `class`, or `do {}`. Will be overzealous if there's
10740 // already necessary grouping parentheses.
10743 function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) {
10744 node = getLeftMost(node);
10746 switch (node.type) {
10747 case "FunctionExpression":
10748 case "ClassExpression":
10749 case "DoExpression":
10750 return forbidFunctionClassAndDoExpr;
10752 case "ObjectExpression":
10755 case "MemberExpression":
10756 case "OptionalMemberExpression":
10757 return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
10759 case "TaggedTemplateExpression":
10760 if (node.tag.type === "FunctionExpression") {
10761 // IIFEs are always already parenthesized
10765 return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr);
10767 case "CallExpression":
10768 case "OptionalCallExpression":
10769 if (node.callee.type === "FunctionExpression") {
10770 // IIFEs are always already parenthesized
10774 return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr);
10776 case "ConditionalExpression":
10777 return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr);
10779 case "UpdateExpression":
10780 return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr);
10782 case "BindExpression":
10783 return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
10785 case "SequenceExpression":
10786 return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr);
10788 case "TSAsExpression":
10789 return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr);
10796 function getLeftMost(node) {
10798 return getLeftMost(node.left);
10804 * @param {string} value
10805 * @param {number} tabWidth
10806 * @param {number=} startIndex
10807 * @returns {number}
10811 function getAlignmentSize(value, tabWidth, startIndex) {
10812 startIndex = startIndex || 0;
10815 for (var i = startIndex; i < value.length; ++i) {
10816 if (value[i] === "\t") {
10817 // Tabs behave in a way that they are aligned to the nearest
10818 // multiple of tabWidth:
10819 // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4
10820 // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ...
10821 size = size + tabWidth - size % tabWidth;
10830 * @param {string} value
10831 * @param {number} tabWidth
10832 * @returns {number}
10836 function getIndentSize(value, tabWidth) {
10837 var lastNewlineIndex = value.lastIndexOf("\n");
10839 if (lastNewlineIndex === -1) {
10843 return getAlignmentSize( // All the leading whitespaces
10844 value.slice(lastNewlineIndex + 1).match(/^[ \t]*/)[0], tabWidth);
10847 * @typedef {'"' | "'"} Quote
10852 * @param {string} raw
10853 * @param {Quote} preferredQuote
10858 function getPreferredQuote(raw, preferredQuote) {
10859 // `rawContent` is the string exactly like it appeared in the input source
10860 // code, without its enclosing quotes.
10861 var rawContent = raw.slice(1, -1);
10862 /** @type {{ quote: '"', regex: RegExp }} */
10868 /** @type {{ quote: "'", regex: RegExp }} */
10874 var preferred = preferredQuote === "'" ? single : double;
10875 var alternate = preferred === single ? double : single;
10876 var result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing
10877 // the string, we might want to enclose with the alternate quote instead, to
10878 // minimize the number of escaped quotes.
10880 if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) {
10881 var numPreferredQuotes = (rawContent.match(preferred.regex) || []).length;
10882 var numAlternateQuotes = (rawContent.match(alternate.regex) || []).length;
10883 result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote;
10889 function printString(raw, options, isDirectiveLiteral) {
10890 // `rawContent` is the string exactly like it appeared in the input source
10891 // code, without its enclosing quotes.
10892 var rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap
10893 // the quotes on a DirectiveLiteral.
10895 var canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'");
10896 /** @type {Quote} */
10898 var enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't
10899 // change the escape sequences they use.
10900 // See https://github.com/prettier/prettier/issues/1555
10901 // and https://tc39.github.io/ecma262/#directive-prologue
10903 if (isDirectiveLiteral) {
10904 if (canChangeDirectiveQuotes) {
10905 return enclosingQuote + rawContent + enclosingQuote;
10909 } // It might sound unnecessary to use `makeString` even if the string already
10910 // is enclosed with `enclosingQuote`, but it isn't. The string could contain
10911 // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes
10912 // sure that we consistently output the minimum amount of escaped quotes.
10915 return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.embeddedInHtml));
10918 * @param {string} rawContent
10919 * @param {Quote} enclosingQuote
10920 * @param {boolean=} unescapeUnnecessaryEscapes
10921 * @returns {string}
10925 function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) {
10926 var otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double).
10928 var regex = /\\([\s\S])|(['"])/g; // Escape and unescape single and double quotes as needed to be able to
10929 // enclose `rawContent` with `enclosingQuote`.
10931 var newContent = rawContent.replace(regex, function (match, escaped, quote) {
10932 // If we matched an escape, and the escaped character is a quote of the
10933 // other type than we intend to enclose the string with, there's no need for
10934 // it to be escaped, so return it _without_ the backslash.
10935 if (escaped === otherQuote) {
10937 } // If we matched an unescaped quote and it is of the _same_ type as we
10938 // intend to enclose the string with, it must be escaped, so return it with
10942 if (quote === enclosingQuote) {
10943 return "\\" + quote;
10948 } // Unescape any unnecessarily escaped character.
10949 // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27
10952 return unescapeUnnecessaryEscapes && /^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(escaped) ? escaped : "\\" + escaped;
10954 return enclosingQuote + newContent + enclosingQuote;
10957 function printNumber(rawNumber) {
10958 return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation.
10959 .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0).
10960 .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit.
10961 .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes.
10962 .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot.
10963 .replace(/\.(?=e|$)/, "");
10966 * @param {string} str
10967 * @param {string} target
10968 * @returns {number}
10972 function getMaxContinuousCount(str, target) {
10973 var results = str.match(new RegExp(`(${escapeStringRegexp(target)})+`, "g"));
10975 if (results === null) {
10979 return results.reduce(function (maxCount, result) {
10980 return Math.max(maxCount, result.length / target.length);
10984 function getMinNotPresentContinuousCount(str, target) {
10985 var matches = str.match(new RegExp(`(${escapeStringRegexp(target)})+`, "g"));
10987 if (matches === null) {
10991 var countPresent = new Map();
10993 var _iteratorNormalCompletion = true;
10994 var _didIteratorError = false;
10995 var _iteratorError = undefined;
10998 for (var _iterator = matches[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
10999 var match = _step.value;
11000 var count = match.length / target.length;
11001 countPresent.set(count, true);
11008 _didIteratorError = true;
11009 _iteratorError = err;
11012 if (!_iteratorNormalCompletion && _iterator.return != null) {
11013 _iterator.return();
11016 if (_didIteratorError) {
11017 throw _iteratorError;
11022 for (var i = 1; i < max; i++) {
11023 if (!countPresent.get(i)) {
11031 * @param {string} text
11032 * @returns {number}
11036 function getStringWidth(text) {
11039 } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width`
11042 if (!notAsciiRegex.test(text)) {
11043 return text.length;
11046 return stringWidth_1(text);
11049 function hasIgnoreComment(path) {
11050 var node = path.getValue();
11051 return hasNodeIgnoreComment(node);
11054 function hasNodeIgnoreComment(node) {
11055 return node && node.comments && node.comments.length > 0 && node.comments.some(function (comment) {
11056 return comment.value.trim() === "prettier-ignore";
11060 function matchAncestorTypes(path, types, index) {
11061 index = index || 0;
11062 types = types.slice();
11064 while (types.length) {
11065 var parent = path.getParentNode(index);
11066 var type = types.shift();
11068 if (!parent || parent.type !== type) {
11078 function addCommentHelper(node, comment) {
11079 var comments = node.comments || (node.comments = []);
11080 comments.push(comment);
11081 comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment
11082 // We already "print" it via the raw text, we don't need to re-print it as a
11085 if (node.type === "JSXText") {
11086 comment.printed = true;
11090 function addLeadingComment(node, comment) {
11091 comment.leading = true;
11092 comment.trailing = false;
11093 addCommentHelper(node, comment);
11096 function addDanglingComment(node, comment) {
11097 comment.leading = false;
11098 comment.trailing = false;
11099 addCommentHelper(node, comment);
11102 function addTrailingComment(node, comment) {
11103 comment.leading = false;
11104 comment.trailing = true;
11105 addCommentHelper(node, comment);
11108 function isWithinParentArrayProperty(path, propertyName) {
11109 var node = path.getValue();
11110 var parent = path.getParentNode();
11112 if (parent == null) {
11116 if (!Array.isArray(parent[propertyName])) {
11120 var key = path.getName();
11121 return parent[propertyName][key] === node;
11124 function replaceEndOfLineWith(text, replacement) {
11126 var _iteratorNormalCompletion2 = true;
11127 var _didIteratorError2 = false;
11128 var _iteratorError2 = undefined;
11131 for (var _iterator2 = text.split("\n")[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
11132 var part = _step2.value;
11134 if (parts.length !== 0) {
11135 parts.push(replacement);
11141 _didIteratorError2 = true;
11142 _iteratorError2 = err;
11145 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
11146 _iterator2.return();
11149 if (_didIteratorError2) {
11150 throw _iteratorError2;
11159 replaceEndOfLineWith,
11161 getMaxContinuousCount,
11162 getMinNotPresentContinuousCount,
11166 isExportDeclaration,
11167 getParentExportDeclaration,
11170 getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
11171 getNextNonSpaceNonCommentCharacterIndex,
11172 getNextNonSpaceNonCommentCharacter,
11177 skipEverythingButNewLine,
11179 skipTrailingComment,
11181 isNextLineEmptyAfterIndex,
11183 isPreviousLineEmpty,
11189 startsWithNoLookaheadToken,
11196 hasNodeIgnoreComment,
11198 matchAncestorTypes,
11200 addDanglingComment,
11201 addTrailingComment,
11202 isWithinParentArrayProperty
11205 function guessEndOfLine(text) {
11206 var index = text.indexOf("\r");
11209 return text.charAt(index + 1) === "\n" ? "crlf" : "cr";
11215 function convertEndOfLineToChars(value) {
11230 convertEndOfLineToChars
11233 var getStringWidth$1 = util.getStringWidth;
11234 var convertEndOfLineToChars$1 = endOfLine.convertEndOfLineToChars;
11235 var concat$1 = docBuilders.concat,
11236 fill$1 = docBuilders.fill,
11237 cursor$1 = docBuilders.cursor;
11238 /** @type {Record<symbol, typeof MODE_BREAK | typeof MODE_FLAT>} */
11241 var MODE_BREAK = 1;
11244 function rootIndent() {
11252 function makeIndent(ind, options) {
11253 return generateInd(ind, {
11258 function makeAlign(ind, n, options) {
11259 return n === -Infinity ? ind.root || rootIndent() : n < 0 ? generateInd(ind, {
11261 }, options) : !n ? ind : n.type === "root" ? Object.assign({}, ind, {
11263 }) : typeof n === "string" ? generateInd(ind, {
11264 type: "stringAlign",
11266 }, options) : generateInd(ind, {
11267 type: "numberAlign",
11272 function generateInd(ind, newPart, options) {
11273 var queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart);
11277 var lastSpaces = 0;
11278 var _iteratorNormalCompletion = true;
11279 var _didIteratorError = false;
11280 var _iteratorError = undefined;
11283 for (var _iterator = queue[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
11284 var part = _step.value;
11286 switch (part.type) {
11290 if (options.useTabs) {
11293 addSpaces(options.tabWidth);
11298 case "stringAlign":
11301 length += part.n.length;
11304 case "numberAlign":
11306 lastSpaces += part.n;
11309 /* istanbul ignore next */
11312 throw new Error(`Unexpected type '${part.type}'`);
11316 _didIteratorError = true;
11317 _iteratorError = err;
11320 if (!_iteratorNormalCompletion && _iterator.return != null) {
11321 _iterator.return();
11324 if (_didIteratorError) {
11325 throw _iteratorError;
11331 return Object.assign({}, ind, {
11337 function addTabs(count) {
11338 value += "\t".repeat(count);
11339 length += options.tabWidth * count;
11342 function addSpaces(count) {
11343 value += " ".repeat(count);
11348 if (options.useTabs) {
11355 function flushTabs() {
11356 if (lastTabs > 0) {
11363 function flushSpaces() {
11364 if (lastSpaces > 0) {
11365 addSpaces(lastSpaces);
11371 function resetLast() {
11377 function trim$1(out) {
11378 if (out.length === 0) {
11382 var trimCount = 0; // Trim whitespace at the end of line
11384 while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[ \t]*$/)) {
11385 trimCount += out.pop().length;
11388 if (out.length && typeof out[out.length - 1] === "string") {
11389 var trimmed = out[out.length - 1].replace(/[ \t]*$/, "");
11390 trimCount += out[out.length - 1].length - trimmed.length;
11391 out[out.length - 1] = trimmed;
11397 function fits(next, restCommands, width, options, mustBeFlat) {
11398 var restIdx = restCommands.length;
11399 var cmds = [next]; // `out` is only used for width counting because `trim` requires to look
11400 // backwards for space characters.
11404 while (width >= 0) {
11405 if (cmds.length === 0) {
11406 if (restIdx === 0) {
11410 cmds.push(restCommands[restIdx - 1]);
11415 var x = cmds.pop();
11420 if (typeof doc === "string") {
11422 width -= getStringWidth$1(doc);
11424 switch (doc.type) {
11426 for (var i = doc.parts.length - 1; i >= 0; i--) {
11427 cmds.push([ind, mode, doc.parts[i]]);
11433 cmds.push([makeIndent(ind, options), mode, doc.contents]);
11437 cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
11441 width += trim$1(out);
11445 if (mustBeFlat && doc.break) {
11449 cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]);
11452 groupModeMap[doc.id] = cmds[cmds.length - 1][1];
11458 for (var _i = doc.parts.length - 1; _i >= 0; _i--) {
11459 cmds.push([ind, mode, doc.parts[_i]]);
11466 var groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
11468 if (groupMode === MODE_BREAK) {
11469 if (doc.breakContents) {
11470 cmds.push([ind, mode, doc.breakContents]);
11474 if (groupMode === MODE_FLAT) {
11475 if (doc.flatContents) {
11476 cmds.push([ind, mode, doc.flatContents]);
11510 function printDocToString(doc, options) {
11512 var width = options.printWidth;
11513 var newLine = convertEndOfLineToChars$1(options.endOfLine);
11514 var pos = 0; // cmds is basically a stack. We've turned a recursive call into a
11515 // while loop which is much faster. The while loop below adds new
11516 // cmds to the array instead of recursively calling `print`.
11518 var cmds = [[rootIndent(), MODE_BREAK, doc]];
11520 var shouldRemeasure = false;
11521 var lineSuffix = [];
11523 while (cmds.length !== 0) {
11524 var x = cmds.pop();
11529 if (typeof _doc === "string") {
11531 pos += getStringWidth$1(_doc);
11533 switch (_doc.type) {
11535 out.push(cursor$1.placeholder);
11539 for (var i = _doc.parts.length - 1; i >= 0; i--) {
11540 cmds.push([ind, mode, _doc.parts[i]]);
11546 cmds.push([makeIndent(ind, options), mode, _doc.contents]);
11550 cmds.push([makeAlign(ind, _doc.n, options), mode, _doc.contents]);
11554 pos -= trim$1(out);
11560 if (!shouldRemeasure) {
11561 cmds.push([ind, _doc.break ? MODE_BREAK : MODE_FLAT, _doc.contents]);
11569 shouldRemeasure = false;
11570 var next = [ind, MODE_FLAT, _doc.contents];
11571 var rem = width - pos;
11573 if (!_doc.break && fits(next, cmds, rem, options)) {
11576 // Expanded states are a rare case where a document
11577 // can manually provide multiple representations of
11578 // itself. It provides an array of documents
11579 // going from the least expanded (most flattened)
11580 // representation first to the most expanded. If a
11581 // group has these, we need to manually go through
11582 // these states and find the first one that fits.
11583 if (_doc.expandedStates) {
11584 var mostExpanded = _doc.expandedStates[_doc.expandedStates.length - 1];
11587 cmds.push([ind, MODE_BREAK, mostExpanded]);
11590 for (var _i2 = 1; _i2 < _doc.expandedStates.length + 1; _i2++) {
11591 if (_i2 >= _doc.expandedStates.length) {
11592 cmds.push([ind, MODE_BREAK, mostExpanded]);
11595 var state = _doc.expandedStates[_i2];
11596 var cmd = [ind, MODE_FLAT, state];
11598 if (fits(cmd, cmds, rem, options)) {
11606 cmds.push([ind, MODE_BREAK, _doc.contents]);
11615 groupModeMap[_doc.id] = cmds[cmds.length - 1][1];
11619 // Fills each line with as much code as possible before moving to a new
11620 // line with the same indentation.
11622 // Expects doc.parts to be an array of alternating content and
11623 // whitespace. The whitespace contains the linebreaks.
11626 // ["I", line, "love", line, "monkeys"]
11628 // [{ type: group, ... }, softline, { type: group, ... }]
11630 // It uses this parts structure to handle three main layout cases:
11631 // * The first two content items fit on the same line without
11633 // -> output the first content item and the whitespace "flat".
11634 // * Only the first content item fits on the line without breaking
11635 // -> output the first content item "flat" and the whitespace with
11637 // * Neither content item fits on the line without breaking
11638 // -> output the first content item and the whitespace with "break".
11642 var _rem = width - pos;
11644 var parts = _doc.parts;
11646 if (parts.length === 0) {
11650 var content = parts[0];
11651 var contentFlatCmd = [ind, MODE_FLAT, content];
11652 var contentBreakCmd = [ind, MODE_BREAK, content];
11653 var contentFits = fits(contentFlatCmd, [], _rem, options, true);
11655 if (parts.length === 1) {
11657 cmds.push(contentFlatCmd);
11659 cmds.push(contentBreakCmd);
11665 var whitespace = parts[1];
11666 var whitespaceFlatCmd = [ind, MODE_FLAT, whitespace];
11667 var whitespaceBreakCmd = [ind, MODE_BREAK, whitespace];
11669 if (parts.length === 2) {
11671 cmds.push(whitespaceFlatCmd);
11672 cmds.push(contentFlatCmd);
11674 cmds.push(whitespaceBreakCmd);
11675 cmds.push(contentBreakCmd);
11679 } // At this point we've handled the first pair (context, separator)
11680 // and will create a new fill doc for the rest of the content.
11681 // Ideally we wouldn't mutate the array here but coping all the
11682 // elements to a new array would make this algorithm quadratic,
11683 // which is unusable for large arrays (e.g. large texts in JSX).
11686 parts.splice(0, 2);
11687 var remainingCmd = [ind, mode, fill$1(parts)];
11688 var secondContent = parts[0];
11689 var firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$1([content, whitespace, secondContent])];
11690 var firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], _rem, options, true);
11692 if (firstAndSecondContentFits) {
11693 cmds.push(remainingCmd);
11694 cmds.push(whitespaceFlatCmd);
11695 cmds.push(contentFlatCmd);
11696 } else if (contentFits) {
11697 cmds.push(remainingCmd);
11698 cmds.push(whitespaceBreakCmd);
11699 cmds.push(contentFlatCmd);
11701 cmds.push(remainingCmd);
11702 cmds.push(whitespaceBreakCmd);
11703 cmds.push(contentBreakCmd);
11711 var groupMode = _doc.groupId ? groupModeMap[_doc.groupId] : mode;
11713 if (groupMode === MODE_BREAK) {
11714 if (_doc.breakContents) {
11715 cmds.push([ind, mode, _doc.breakContents]);
11719 if (groupMode === MODE_FLAT) {
11720 if (_doc.flatContents) {
11721 cmds.push([ind, mode, _doc.flatContents]);
11728 case "line-suffix":
11729 lineSuffix.push([ind, mode, _doc.contents]);
11732 case "line-suffix-boundary":
11733 if (lineSuffix.length > 0) {
11734 cmds.push([ind, mode, {
11753 // This line was forced into the output even if we
11754 // were in flattened mode, so we need to tell the next
11755 // group that no matter what, it needs to remeasure
11756 // because the previous measurement didn't accurately
11757 // capture the entire expression (this is necessary
11758 // for nested groups)
11759 shouldRemeasure = true;
11765 if (lineSuffix.length) {
11766 cmds.push([ind, mode, _doc]);
11767 [].push.apply(cmds, lineSuffix.reverse());
11772 if (_doc.literal) {
11774 out.push(newLine, ind.root.value);
11775 pos = ind.root.length;
11781 pos -= trim$1(out);
11782 out.push(newLine + ind.value);
11794 var cursorPlaceholderIndex = out.indexOf(cursor$1.placeholder);
11796 if (cursorPlaceholderIndex !== -1) {
11797 var otherCursorPlaceholderIndex = out.indexOf(cursor$1.placeholder, cursorPlaceholderIndex + 1);
11798 var beforeCursor = out.slice(0, cursorPlaceholderIndex).join("");
11799 var aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join("");
11800 var afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join("");
11802 formatted: beforeCursor + aroundCursor + afterCursor,
11803 cursorNodeStart: beforeCursor.length,
11804 cursorNodeText: aroundCursor
11809 formatted: out.join("")
11817 var traverseDocOnExitStackMarker = {};
11819 function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) {
11820 var docsStack = [doc];
11822 while (docsStack.length !== 0) {
11823 var _doc = docsStack.pop();
11825 if (_doc === traverseDocOnExitStackMarker) {
11826 onExit(docsStack.pop());
11830 var shouldRecurse = true;
11833 if (onEnter(_doc) === false) {
11834 shouldRecurse = false;
11839 docsStack.push(_doc);
11840 docsStack.push(traverseDocOnExitStackMarker);
11843 if (shouldRecurse) {
11844 // When there are multiple parts to process,
11845 // the parts need to be pushed onto the stack in reverse order,
11846 // so that they are processed in the original order
11847 // when the stack is popped.
11848 if (_doc.type === "concat" || _doc.type === "fill") {
11849 for (var ic = _doc.parts.length, i = ic - 1; i >= 0; --i) {
11850 docsStack.push(_doc.parts[i]);
11852 } else if (_doc.type === "if-break") {
11853 if (_doc.flatContents) {
11854 docsStack.push(_doc.flatContents);
11857 if (_doc.breakContents) {
11858 docsStack.push(_doc.breakContents);
11860 } else if (_doc.type === "group" && _doc.expandedStates) {
11861 if (shouldTraverseConditionalGroups) {
11862 for (var _ic = _doc.expandedStates.length, _i = _ic - 1; _i >= 0; --_i) {
11863 docsStack.push(_doc.expandedStates[_i]);
11866 docsStack.push(_doc.contents);
11868 } else if (_doc.contents) {
11869 docsStack.push(_doc.contents);
11875 function mapDoc(doc, cb) {
11876 if (doc.type === "concat" || doc.type === "fill") {
11877 var parts = doc.parts.map(function (part) {
11878 return mapDoc(part, cb);
11880 return cb(Object.assign({}, doc, {
11883 } else if (doc.type === "if-break") {
11884 var breakContents = doc.breakContents && mapDoc(doc.breakContents, cb);
11885 var flatContents = doc.flatContents && mapDoc(doc.flatContents, cb);
11886 return cb(Object.assign({}, doc, {
11890 } else if (doc.contents) {
11891 var contents = mapDoc(doc.contents, cb);
11892 return cb(Object.assign({}, doc, {
11900 function findInDoc(doc, fn, defaultValue) {
11901 var result = defaultValue;
11902 var hasStopped = false;
11904 function findInDocOnEnterFn(doc) {
11905 var maybeResult = fn(doc);
11907 if (maybeResult !== undefined) {
11909 result = maybeResult;
11917 traverseDoc(doc, findInDocOnEnterFn);
11921 function isEmpty(n) {
11922 return typeof n === "string" && n.length === 0;
11925 function isLineNextFn(doc) {
11926 if (typeof doc === "string") {
11930 if (doc.type === "line") {
11935 function isLineNext(doc) {
11936 return findInDoc(doc, isLineNextFn, false);
11939 function willBreakFn(doc) {
11940 if (doc.type === "group" && doc.break) {
11944 if (doc.type === "line" && doc.hard) {
11948 if (doc.type === "break-parent") {
11953 function willBreak(doc) {
11954 return findInDoc(doc, willBreakFn, false);
11957 function breakParentGroup(groupStack) {
11958 if (groupStack.length > 0) {
11959 var parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because
11960 // the user is expected to manually handle what breaks.
11962 if (!parentGroup.expandedStates) {
11963 parentGroup.break = true;
11970 function propagateBreaks(doc) {
11971 var alreadyVisitedSet = new Set();
11972 var groupStack = [];
11974 function propagateBreaksOnEnterFn(doc) {
11975 if (doc.type === "break-parent") {
11976 breakParentGroup(groupStack);
11979 if (doc.type === "group") {
11980 groupStack.push(doc);
11982 if (alreadyVisitedSet.has(doc)) {
11986 alreadyVisitedSet.add(doc);
11990 function propagateBreaksOnExitFn(doc) {
11991 if (doc.type === "group") {
11992 var group = groupStack.pop();
11995 breakParentGroup(groupStack);
12000 traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn,
12001 /* shouldTraverseConditionalGroups */
12005 function removeLinesFn(doc) {
12006 // Force this doc into flat mode by statically converting all
12007 // lines into spaces (or soft lines into nothing). Hard lines
12008 // should still output because there's too great of a chance
12009 // of breaking existing assumptions otherwise.
12010 if (doc.type === "line" && !doc.hard) {
12011 return doc.soft ? "" : " ";
12012 } else if (doc.type === "if-break") {
12013 return doc.flatContents || "";
12019 function removeLines(doc) {
12020 return mapDoc(doc, removeLinesFn);
12023 function stripTrailingHardline(doc) {
12024 // HACK remove ending hardline, original PR: #1984
12025 if (doc.type === "concat" && doc.parts.length !== 0) {
12026 var lastPart = doc.parts[doc.parts.length - 1];
12028 if (lastPart.type === "concat") {
12029 if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") {
12032 parts: doc.parts.slice(0, -1)
12038 parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart))
12055 stripTrailingHardline
12058 function flattenDoc(doc) {
12059 if (doc.type === "concat") {
12062 for (var i = 0; i < doc.parts.length; ++i) {
12063 var doc2 = doc.parts[i];
12065 if (typeof doc2 !== "string" && doc2.type === "concat") {
12066 [].push.apply(res, flattenDoc(doc2).parts);
12068 var flattened = flattenDoc(doc2);
12070 if (flattened !== "") {
12071 res.push(flattened);
12076 return Object.assign({}, doc, {
12079 } else if (doc.type === "if-break") {
12080 return Object.assign({}, doc, {
12081 breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null,
12082 flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null
12084 } else if (doc.type === "group") {
12085 return Object.assign({}, doc, {
12086 contents: flattenDoc(doc.contents),
12087 expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates
12089 } else if (doc.contents) {
12090 return Object.assign({}, doc, {
12091 contents: flattenDoc(doc.contents)
12098 function printDoc(doc) {
12099 if (typeof doc === "string") {
12100 return JSON.stringify(doc);
12103 if (doc.type === "line") {
12105 return "literalline";
12119 if (doc.type === "break-parent") {
12120 return "breakParent";
12123 if (doc.type === "trim") {
12127 if (doc.type === "concat") {
12128 return "[" + doc.parts.map(printDoc).join(", ") + "]";
12131 if (doc.type === "indent") {
12132 return "indent(" + printDoc(doc.contents) + ")";
12135 if (doc.type === "align") {
12136 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) + ")";
12139 if (doc.type === "if-break") {
12140 return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")";
12143 if (doc.type === "group") {
12144 if (doc.expandedStates) {
12145 return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])";
12148 return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")";
12151 if (doc.type === "fill") {
12152 return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")";
12155 if (doc.type === "line-suffix") {
12156 return "lineSuffix(" + printDoc(doc.contents) + ")";
12159 if (doc.type === "line-suffix-boundary") {
12160 return "lineSuffixBoundary";
12163 throw new Error("Unknown doc type " + doc.type);
12167 printDocToDebug: function printDocToDebug(doc) {
12168 return printDoc(flattenDoc(doc));
12173 builders: docBuilders,
12174 printer: docPrinter,
12179 var mapDoc$1 = doc.utils.mapDoc;
12181 function isNextLineEmpty$1(text, node, options) {
12182 return util.isNextLineEmpty(text, node, options.locEnd);
12185 function isPreviousLineEmpty$1(text, node, options) {
12186 return util.isPreviousLineEmpty(text, node, options.locStart);
12189 function getNextNonSpaceNonCommentCharacterIndex$1(text, node, options) {
12190 return util.getNextNonSpaceNonCommentCharacterIndex(text, node, options.locEnd);
12194 getMaxContinuousCount: util.getMaxContinuousCount,
12195 getStringWidth: util.getStringWidth,
12196 getAlignmentSize: util.getAlignmentSize,
12197 getIndentSize: util.getIndentSize,
12199 skipWhitespace: util.skipWhitespace,
12200 skipSpaces: util.skipSpaces,
12201 skipNewline: util.skipNewline,
12202 skipToLineEnd: util.skipToLineEnd,
12203 skipEverythingButNewLine: util.skipEverythingButNewLine,
12204 skipInlineComment: util.skipInlineComment,
12205 skipTrailingComment: util.skipTrailingComment,
12206 hasNewline: util.hasNewline,
12207 hasNewlineInRange: util.hasNewlineInRange,
12208 hasSpaces: util.hasSpaces,
12209 isNextLineEmpty: isNextLineEmpty$1,
12210 isNextLineEmptyAfterIndex: util.isNextLineEmptyAfterIndex,
12211 isPreviousLineEmpty: isPreviousLineEmpty$1,
12212 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1,
12214 // TODO: remove in 2.0, we already exposed it in docUtils
12215 makeString: util.makeString,
12216 addLeadingComment: util.addLeadingComment,
12217 addDanglingComment: util.addDanglingComment,
12218 addTrailingComment: util.addTrailingComment
12221 var _require$$0$builders = doc.builders,
12222 concat$2 = _require$$0$builders.concat,
12223 hardline$1 = _require$$0$builders.hardline,
12224 breakParent$1 = _require$$0$builders.breakParent,
12225 indent$1 = _require$$0$builders.indent,
12226 lineSuffix$1 = _require$$0$builders.lineSuffix,
12227 join$1 = _require$$0$builders.join,
12228 cursor$2 = _require$$0$builders.cursor;
12229 var hasNewline$1 = util.hasNewline,
12230 skipNewline$1 = util.skipNewline,
12231 isPreviousLineEmpty$2 = util.isPreviousLineEmpty;
12232 var addLeadingComment$1 = utilShared.addLeadingComment,
12233 addDanglingComment$1 = utilShared.addDanglingComment,
12234 addTrailingComment$1 = utilShared.addTrailingComment;
12235 var childNodesCacheKey = Symbol("child-nodes");
12237 function getSortedChildNodes(node, options, resultArray) {
12242 var printer = options.printer,
12243 locStart = options.locStart,
12244 locEnd = options.locEnd;
12247 if (node && printer.canAttachComment && printer.canAttachComment(node)) {
12248 // This reverse insertion sort almost always takes constant
12249 // time because we almost always (maybe always?) append the
12250 // nodes in order anyway.
12253 for (i = resultArray.length - 1; i >= 0; --i) {
12254 if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) {
12259 resultArray.splice(i + 1, 0, node);
12262 } else if (node[childNodesCacheKey]) {
12263 return node[childNodesCacheKey];
12268 if (printer.getCommentChildNodes) {
12269 childNodes = printer.getCommentChildNodes(node);
12270 } else if (node && typeof node === "object") {
12271 childNodes = Object.keys(node).filter(function (n) {
12272 return n !== "enclosingNode" && n !== "precedingNode" && n !== "followingNode";
12273 }).map(function (n) {
12282 if (!resultArray) {
12283 Object.defineProperty(node, childNodesCacheKey, {
12284 value: resultArray = [],
12289 childNodes.forEach(function (childNode) {
12290 getSortedChildNodes(childNode, options, resultArray);
12292 return resultArray;
12293 } // As efficiently as possible, decorate the comment object with
12294 // .precedingNode, .enclosingNode, and/or .followingNode properties, at
12295 // least one of which is guaranteed to be defined.
12298 function decorateComment(node, comment, options) {
12299 var locStart = options.locStart,
12300 locEnd = options.locEnd;
12301 var childNodes = getSortedChildNodes(node, options);
12303 var followingNode; // Time to dust off the old binary search robes and wizard hat.
12306 var right = childNodes.length;
12308 while (left < right) {
12309 var middle = left + right >> 1;
12310 var child = childNodes[middle];
12312 if (locStart(child) - locStart(comment) <= 0 && locEnd(comment) - locEnd(child) <= 0) {
12313 // The comment is completely contained by this child node.
12314 comment.enclosingNode = child;
12315 decorateComment(child, comment, options);
12316 return; // Abandon the binary search at this level.
12319 if (locEnd(child) - locStart(comment) <= 0) {
12320 // This child node falls completely before the comment.
12321 // Because we will never consider this node or any nodes
12322 // before it again, this node must be the closest preceding
12323 // node we have encountered so far.
12324 precedingNode = child;
12329 if (locEnd(comment) - locStart(child) <= 0) {
12330 // This child node falls completely after the comment.
12331 // Because we will never consider this node or any nodes after
12332 // it again, this node must be the closest following node we
12333 // have encountered so far.
12334 followingNode = child;
12338 /* istanbul ignore next */
12341 throw new Error("Comment location overlaps with node location");
12342 } // We don't want comments inside of different expressions inside of the same
12343 // template literal to move to another expression.
12346 if (comment.enclosingNode && comment.enclosingNode.type === "TemplateLiteral") {
12347 var quasis = comment.enclosingNode.quasis;
12348 var commentIndex = findExpressionIndexForComment(quasis, comment, options);
12350 if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) {
12351 precedingNode = null;
12354 if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) {
12355 followingNode = null;
12359 if (precedingNode) {
12360 comment.precedingNode = precedingNode;
12363 if (followingNode) {
12364 comment.followingNode = followingNode;
12368 function attach(comments, ast, text, options) {
12369 if (!Array.isArray(comments)) {
12373 var tiesToBreak = [];
12374 var locStart = options.locStart,
12375 locEnd = options.locEnd;
12376 comments.forEach(function (comment, i) {
12377 if (options.parser === "json" || options.parser === "json5" || options.parser === "__js_expression" || options.parser === "__vue_expression") {
12378 if (locStart(comment) - locStart(ast) <= 0) {
12379 addLeadingComment$1(ast, comment);
12383 if (locEnd(comment) - locEnd(ast) >= 0) {
12384 addTrailingComment$1(ast, comment);
12389 decorateComment(ast, comment, options);
12390 var precedingNode = comment.precedingNode,
12391 enclosingNode = comment.enclosingNode,
12392 followingNode = comment.followingNode;
12393 var pluginHandleOwnLineComment = options.printer.handleComments && options.printer.handleComments.ownLine ? options.printer.handleComments.ownLine : function () {
12396 var pluginHandleEndOfLineComment = options.printer.handleComments && options.printer.handleComments.endOfLine ? options.printer.handleComments.endOfLine : function () {
12399 var pluginHandleRemainingComment = options.printer.handleComments && options.printer.handleComments.remaining ? options.printer.handleComments.remaining : function () {
12402 var isLastComment = comments.length - 1 === i;
12404 if (hasNewline$1(text, locStart(comment), {
12407 // If a comment exists on its own line, prefer a leading comment.
12408 // We also need to check if it's the first line of the file.
12409 if (pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)) ; else if (followingNode) {
12410 // Always a leading comment.
12411 addLeadingComment$1(followingNode, comment);
12412 } else if (precedingNode) {
12413 addTrailingComment$1(precedingNode, comment);
12414 } else if (enclosingNode) {
12415 addDanglingComment$1(enclosingNode, comment);
12417 // There are no nodes, let's attach it to the root of the ast
12419 /* istanbul ignore next */
12420 addDanglingComment$1(ast, comment);
12422 } else if (hasNewline$1(text, locEnd(comment))) {
12423 if (pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode) {
12424 // There is content before this comment on the same line, but
12425 // none after it, so prefer a trailing comment of the previous node.
12426 addTrailingComment$1(precedingNode, comment);
12427 } else if (followingNode) {
12428 addLeadingComment$1(followingNode, comment);
12429 } else if (enclosingNode) {
12430 addDanglingComment$1(enclosingNode, comment);
12432 // There are no nodes, let's attach it to the root of the ast
12434 /* istanbul ignore next */
12435 addDanglingComment$1(ast, comment);
12438 if (pluginHandleRemainingComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode && followingNode) {
12439 // Otherwise, text exists both before and after the comment on
12440 // the same line. If there is both a preceding and following
12441 // node, use a tie-breaking algorithm to determine if it should
12442 // be attached to the next or previous node. In the last case,
12443 // simply attach the right node;
12444 var tieCount = tiesToBreak.length;
12446 if (tieCount > 0) {
12447 var lastTie = tiesToBreak[tieCount - 1];
12449 if (lastTie.followingNode !== comment.followingNode) {
12450 breakTies(tiesToBreak, text, options);
12454 tiesToBreak.push(comment);
12455 } else if (precedingNode) {
12456 addTrailingComment$1(precedingNode, comment);
12457 } else if (followingNode) {
12458 addLeadingComment$1(followingNode, comment);
12459 } else if (enclosingNode) {
12460 addDanglingComment$1(enclosingNode, comment);
12462 // There are no nodes, let's attach it to the root of the ast
12464 /* istanbul ignore next */
12465 addDanglingComment$1(ast, comment);
12469 breakTies(tiesToBreak, text, options);
12470 comments.forEach(function (comment) {
12471 // These node references were useful for breaking ties, but we
12472 // don't need them anymore, and they create cycles in the AST that
12473 // may lead to infinite recursion if we don't delete them here.
12474 delete comment.precedingNode;
12475 delete comment.enclosingNode;
12476 delete comment.followingNode;
12480 function breakTies(tiesToBreak, text, options) {
12481 var tieCount = tiesToBreak.length;
12483 if (tieCount === 0) {
12487 var _tiesToBreak$ = tiesToBreak[0],
12488 precedingNode = _tiesToBreak$.precedingNode,
12489 followingNode = _tiesToBreak$.followingNode;
12490 var gapEndPos = options.locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps
12491 // between the tied comments. In order to qualify as leading, a
12492 // comment must be separated from followingNode by an unbroken series of
12493 // gaps (or other comments). Gaps should only contain whitespace or open
12496 var indexOfFirstLeadingComment;
12498 for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) {
12499 var comment = tiesToBreak[indexOfFirstLeadingComment - 1];
12500 assert$1.strictEqual(comment.precedingNode, precedingNode);
12501 assert$1.strictEqual(comment.followingNode, followingNode);
12502 var gap = text.slice(options.locEnd(comment), gapEndPos);
12504 if (/^[\s(]*$/.test(gap)) {
12505 gapEndPos = options.locStart(comment);
12507 // The gap string contained something other than whitespace or open
12513 tiesToBreak.forEach(function (comment, i) {
12514 if (i < indexOfFirstLeadingComment) {
12515 addTrailingComment$1(precedingNode, comment);
12517 addLeadingComment$1(followingNode, comment);
12520 tiesToBreak.length = 0;
12523 function printComment(commentPath, options) {
12524 var comment = commentPath.getValue();
12525 comment.printed = true;
12526 return options.printer.printComment(commentPath, options);
12529 function findExpressionIndexForComment(quasis, comment, options) {
12530 var startPos = options.locStart(comment) - 1;
12532 for (var i = 1; i < quasis.length; ++i) {
12533 if (startPos < getQuasiRange(quasis[i]).start) {
12536 } // We haven't found it, it probably means that some of the locations are off.
12537 // Let's just return the first one.
12539 /* istanbul ignore next */
12545 function getQuasiRange(expr) {
12546 if (expr.start !== undefined) {
12556 start: expr.range[0],
12561 function printLeadingComment(commentPath, print, options) {
12562 var comment = commentPath.getValue();
12563 var contents = printComment(commentPath, options);
12569 var isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // Leading block comments should see if they need to stay on the
12570 // same line or not.
12573 return concat$2([contents, hasNewline$1(options.originalText, options.locEnd(comment)) ? hardline$1 : " "]);
12576 return concat$2([contents, hardline$1]);
12579 function printTrailingComment(commentPath, print, options) {
12580 var comment = commentPath.getValue();
12581 var contents = printComment(commentPath, options);
12587 var isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // We don't want the line to break
12588 // when the parentParentNode is a ClassDeclaration/-Expression
12589 // And the parentNode is in the superClass property
12591 var parentNode = commentPath.getNode(1);
12592 var parentParentNode = commentPath.getNode(2);
12593 var isParentSuperClass = parentParentNode && (parentParentNode.type === "ClassDeclaration" || parentParentNode.type === "ClassExpression") && parentParentNode.superClass === parentNode;
12595 if (hasNewline$1(options.originalText, options.locStart(comment), {
12598 // This allows comments at the end of nested structures:
12604 // Those kinds of comments are almost always leading comments, but
12605 // here it doesn't go "outside" the block and turns it into a
12606 // trailing comment for `2`. We can simulate the above by checking
12607 // if this a comment on its own line; normal trailing comments are
12608 // always at the end of another expression.
12609 var isLineBeforeEmpty = isPreviousLineEmpty$2(options.originalText, comment, options.locStart);
12610 return lineSuffix$1(concat$2([hardline$1, isLineBeforeEmpty ? hardline$1 : "", contents]));
12611 } else if (isBlock || isParentSuperClass) {
12612 // Trailing block comments never need a newline
12613 return concat$2([" ", contents]);
12616 return concat$2([lineSuffix$1(concat$2([" ", contents])), !isBlock ? breakParent$1 : ""]);
12619 function printDanglingComments(path, options, sameIndent, filter) {
12621 var node = path.getValue();
12623 if (!node || !node.comments) {
12627 path.each(function (commentPath) {
12628 var comment = commentPath.getValue();
12630 if (comment && !comment.leading && !comment.trailing && (!filter || filter(comment))) {
12631 parts.push(printComment(commentPath, options));
12635 if (parts.length === 0) {
12640 return join$1(hardline$1, parts);
12643 return indent$1(concat$2([hardline$1, join$1(hardline$1, parts)]));
12646 function prependCursorPlaceholder(path, options, printed) {
12647 if (path.getNode() === options.cursorNode && path.getValue()) {
12648 return concat$2([cursor$2, printed, cursor$2]);
12654 function printComments(path, print, options, needsSemi) {
12655 var value = path.getValue();
12656 var printed = print(path);
12657 var comments = value && value.comments;
12659 if (!comments || comments.length === 0) {
12660 return prependCursorPlaceholder(path, options, printed);
12663 var leadingParts = [];
12664 var trailingParts = [needsSemi ? ";" : "", printed];
12665 path.each(function (commentPath) {
12666 var comment = commentPath.getValue();
12667 var leading = comment.leading,
12668 trailing = comment.trailing;
12671 var contents = printLeadingComment(commentPath, print, options);
12677 leadingParts.push(contents);
12678 var text = options.originalText;
12679 var index = skipNewline$1(text, options.locEnd(comment));
12681 if (index !== false && hasNewline$1(text, index)) {
12682 leadingParts.push(hardline$1);
12684 } else if (trailing) {
12685 trailingParts.push(printTrailingComment(commentPath, print, options));
12688 return prependCursorPlaceholder(path, options, concat$2(leadingParts.concat(trailingParts)));
12694 printDanglingComments,
12695 getSortedChildNodes
12698 function FastPath(value) {
12699 assert$1.ok(this instanceof FastPath);
12700 this.stack = [value];
12701 } // The name of the current property is always the penultimate element of
12702 // this.stack, and always a String.
12705 FastPath.prototype.getName = function getName() {
12706 var s = this.stack;
12707 var len = s.length;
12711 } // Since the name is always a string, null is a safe sentinel value to
12712 // return if we do not know the name of the (root) value.
12714 /* istanbul ignore next */
12718 }; // The value of the current property is always the final element of
12722 FastPath.prototype.getValue = function getValue() {
12723 var s = this.stack;
12724 return s[s.length - 1];
12727 function getNodeHelper(path, count) {
12728 var stackIndex = getNodeStackIndexHelper(path.stack, count);
12729 return stackIndex === -1 ? null : path.stack[stackIndex];
12732 function getNodeStackIndexHelper(stack, count) {
12733 for (var i = stack.length - 1; i >= 0; i -= 2) {
12734 var value = stack[i];
12736 if (value && !Array.isArray(value) && --count < 0) {
12744 FastPath.prototype.getNode = function getNode(count) {
12745 return getNodeHelper(this, ~~count);
12748 FastPath.prototype.getParentNode = function getParentNode(count) {
12749 return getNodeHelper(this, ~~count + 1);
12750 }; // Temporarily push properties named by string arguments given after the
12751 // callback function onto this.stack, then call the callback with a
12752 // reference to this (modified) FastPath object. Note that the stack will
12753 // be restored to its original state after the callback is finished, so it
12754 // is probably a mistake to retain a reference to the path.
12757 FastPath.prototype.call = function call(callback
12758 /*, name1, name2, ... */
12760 var s = this.stack;
12761 var origLen = s.length;
12762 var value = s[origLen - 1];
12763 var argc = arguments.length;
12765 for (var i = 1; i < argc; ++i) {
12766 var name = arguments[i];
12767 value = value[name];
12768 s.push(name, value);
12771 var result = callback(this);
12772 s.length = origLen;
12776 FastPath.prototype.callParent = function callParent(callback, count) {
12777 var stackIndex = getNodeStackIndexHelper(this.stack, ~~count + 1);
12778 var parentValues = this.stack.splice(stackIndex + 1);
12779 var result = callback(this);
12780 Array.prototype.push.apply(this.stack, parentValues);
12782 }; // Similar to FastPath.prototype.call, except that the value obtained by
12783 // accessing this.getValue()[name1][name2]... should be array-like. The
12784 // callback will be called with a reference to this path object for each
12785 // element of the array.
12788 FastPath.prototype.each = function each(callback
12789 /*, name1, name2, ... */
12791 var s = this.stack;
12792 var origLen = s.length;
12793 var value = s[origLen - 1];
12794 var argc = arguments.length;
12796 for (var i = 1; i < argc; ++i) {
12797 var name = arguments[i];
12798 value = value[name];
12799 s.push(name, value);
12802 for (var _i = 0; _i < value.length; ++_i) {
12804 s.push(_i, value[_i]); // If the callback needs to know the value of i, call
12805 // path.getName(), assuming path is the parameter name.
12812 s.length = origLen;
12813 }; // Similar to FastPath.prototype.each, except that the results of the
12814 // callback function invocations are stored in an array and returned at
12815 // the end of the iteration.
12818 FastPath.prototype.map = function map(callback
12819 /*, name1, name2, ... */
12821 var s = this.stack;
12822 var origLen = s.length;
12823 var value = s[origLen - 1];
12824 var argc = arguments.length;
12826 for (var i = 1; i < argc; ++i) {
12827 var name = arguments[i];
12828 value = value[name];
12829 s.push(name, value);
12832 var result = new Array(value.length);
12834 for (var _i2 = 0; _i2 < value.length; ++_i2) {
12835 if (_i2 in value) {
12836 s.push(_i2, value[_i2]);
12837 result[_i2] = callback(this, _i2);
12842 s.length = origLen;
12846 var fastPath = FastPath;
12848 var normalize$2 = options$1.normalize;
12850 function printSubtree(path, print, options, printAstToDoc) {
12851 if (options.printer.embed) {
12852 return options.printer.embed(path, print, function (text, partialNextOptions) {
12853 return textToDoc(text, partialNextOptions, options, printAstToDoc);
12858 function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc) {
12859 var nextOptions = normalize$2(Object.assign({}, parentOptions, partialNextOptions, {
12860 parentParser: parentOptions.parser,
12861 embeddedInHtml: !!(parentOptions.embeddedInHtml || parentOptions.parser === "html" || parentOptions.parser === "vue" || parentOptions.parser === "angular" || parentOptions.parser === "lwc"),
12866 var result = parser.parse(text, nextOptions);
12867 var ast = result.ast;
12868 text = result.text;
12869 var astComments = ast.comments;
12870 delete ast.comments;
12871 comments.attach(astComments, ast, text, nextOptions);
12872 return printAstToDoc(ast, nextOptions);
12875 var multiparser = {
12880 var docBuilders$1 = doc$1.builders;
12881 var concat$3 = docBuilders$1.concat;
12882 var hardline$2 = docBuilders$1.hardline;
12883 var addAlignmentToDoc$1 = docBuilders$1.addAlignmentToDoc;
12884 var docUtils$1 = doc$1.utils;
12886 * Takes an abstract syntax tree (AST) and recursively converts it to a
12887 * document (series of printing primitives).
12889 * This is done by descending down the AST recursively. The recursion
12890 * involves two functions that call each other:
12892 * 1. printGenerically(), which is defined as an inner function here.
12893 * It basically takes care of node caching.
12894 * 2. callPluginPrintFunction(), which checks for some options, and
12895 * ultimately calls the print() function provided by the plugin.
12897 * The plugin function will call printGenerically() again for child nodes
12898 * of the current node, which will do its housekeeping, then call the
12899 * plugin function again, and so on.
12901 * All the while, these functions pass a "path" variable around, which
12902 * is a stack-like data structure (FastPath) that maintains the current
12903 * state of the recursion. It is called "path", because it represents
12904 * the path to the current node through the Abstract Syntax Tree.
12907 function printAstToDoc(ast, options) {
12908 var alignmentSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
12909 var printer = options.printer;
12911 if (printer.preprocess) {
12912 ast = printer.preprocess(ast, options);
12915 var cache = new Map();
12917 function printGenerically(path, args) {
12918 var node = path.getValue();
12919 var shouldCache = node && typeof node === "object" && args === undefined;
12921 if (shouldCache && cache.has(node)) {
12922 return cache.get(node);
12923 } // We let JSXElement print its comments itself because it adds () around
12924 // UnionTypeAnnotation has to align the child without the comments
12929 if (printer.willPrintOwnComments && printer.willPrintOwnComments(path, options)) {
12930 res = callPluginPrintFunction(path, options, printGenerically, args);
12932 // printComments will call the plugin print function and check for
12933 // comments to print
12934 res = comments.printComments(path, function (p) {
12935 return callPluginPrintFunction(p, options, printGenerically, args);
12936 }, options, args && args.needsSemi);
12940 cache.set(node, res);
12946 var doc = printGenerically(new fastPath(ast));
12948 if (alignmentSize > 0) {
12949 // Add a hardline to make the indents take effect
12950 // It should be removed in index.js format()
12951 doc = addAlignmentToDoc$1(concat$3([hardline$2, doc]), alignmentSize, options.tabWidth);
12954 docUtils$1.propagateBreaks(doc);
12958 function callPluginPrintFunction(path, options, printPath, args) {
12959 assert$1.ok(path instanceof fastPath);
12960 var node = path.getValue();
12961 var printer = options.printer; // Escape hatch
12963 if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path)) {
12964 return options.originalText.slice(options.locStart(node), options.locEnd(node));
12969 // Potentially switch to a different parser
12970 var sub = multiparser.printSubtree(path, printPath, options, printAstToDoc);
12976 /* istanbul ignore if */
12977 if (process.env.PRETTIER_DEBUG) {
12979 } // Continue with current parser
12984 return printer.print(path, options, printPath, args);
12987 var astToDoc = printAstToDoc;
12989 function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) {
12990 var resultStartNode = startNodeAndParents.node;
12991 var resultEndNode = endNodeAndParents.node;
12993 if (resultStartNode === resultEndNode) {
12995 startNode: resultStartNode,
12996 endNode: resultEndNode
13000 var _iteratorNormalCompletion = true;
13001 var _didIteratorError = false;
13002 var _iteratorError = undefined;
13005 for (var _iterator = endNodeAndParents.parentNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
13006 var endParent = _step.value;
13008 if (endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node)) {
13009 resultEndNode = endParent;
13015 _didIteratorError = true;
13016 _iteratorError = err;
13019 if (!_iteratorNormalCompletion && _iterator.return != null) {
13020 _iterator.return();
13023 if (_didIteratorError) {
13024 throw _iteratorError;
13029 var _iteratorNormalCompletion2 = true;
13030 var _didIteratorError2 = false;
13031 var _iteratorError2 = undefined;
13034 for (var _iterator2 = startNodeAndParents.parentNodes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
13035 var startParent = _step2.value;
13037 if (startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node)) {
13038 resultStartNode = startParent;
13044 _didIteratorError2 = true;
13045 _iteratorError2 = err;
13048 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
13049 _iterator2.return();
13052 if (_didIteratorError2) {
13053 throw _iteratorError2;
13059 startNode: resultStartNode,
13060 endNode: resultEndNode
13064 function findNodeAtOffset(node, offset, options, predicate, parentNodes) {
13065 predicate = predicate || function () {
13069 parentNodes = parentNodes || [];
13070 var start = options.locStart(node, options.locStart);
13071 var end = options.locEnd(node, options.locEnd);
13073 if (start <= offset && offset <= end) {
13074 var _iteratorNormalCompletion3 = true;
13075 var _didIteratorError3 = false;
13076 var _iteratorError3 = undefined;
13079 for (var _iterator3 = comments.getSortedChildNodes(node, options)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
13080 var childNode = _step3.value;
13081 var childResult = findNodeAtOffset(childNode, offset, options, predicate, [node].concat(parentNodes));
13084 return childResult;
13088 _didIteratorError3 = true;
13089 _iteratorError3 = err;
13092 if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
13093 _iterator3.return();
13096 if (_didIteratorError3) {
13097 throw _iteratorError3;
13102 if (predicate(node)) {
13105 parentNodes: parentNodes
13109 } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5
13112 function isSourceElement(opts, node) {
13113 if (node == null) {
13115 } // JS and JS like to avoid repetitions
13118 var jsSourceElements = ["FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015
13119 "ImportDeclaration", // Module
13120 "ExportDefaultDeclaration", // Module
13121 "ExportNamedDeclaration", // Module
13122 "ExportAllDeclaration", // Module
13123 "TypeAlias", // Flow
13124 "InterfaceDeclaration", // Flow, TypeScript
13125 "TypeAliasDeclaration", // TypeScript
13126 "ExportAssignment", // TypeScript
13127 "ExportDeclaration" // TypeScript
13129 var jsonSourceElements = ["ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"];
13130 var graphqlSourceElements = ["OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition"];
13132 switch (opts.parser) {
13136 return jsSourceElements.indexOf(node.type) > -1;
13139 return jsonSourceElements.indexOf(node.type) > -1;
13142 return graphqlSourceElements.indexOf(node.kind) > -1;
13145 return node.tag !== "root";
13151 function calculateRange(text, opts, ast) {
13152 // Contract the range so that it has non-whitespace characters at its endpoints.
13153 // This ensures we can format a range that doesn't end on a node.
13154 var rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd);
13155 var startNonWhitespace = Math.max(opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart);
13156 var endNonWhitespace;
13158 for (endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace) {
13159 if (text[endNonWhitespace - 1].match(/\S/)) {
13164 var startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace, opts, function (node) {
13165 return isSourceElement(opts, node);
13167 var endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace, opts, function (node) {
13168 return isSourceElement(opts, node);
13171 if (!startNodeAndParents || !endNodeAndParents) {
13178 var siblingAncestors = findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts);
13179 var startNode = siblingAncestors.startNode,
13180 endNode = siblingAncestors.endNode;
13181 var rangeStart = Math.min(opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart));
13182 var rangeEnd = Math.max(opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd));
13184 rangeStart: rangeStart,
13194 var normalizeOptions$1 = options$1.normalize;
13195 var guessEndOfLine$1 = endOfLine.guessEndOfLine,
13196 convertEndOfLineToChars$2 = endOfLine.convertEndOfLineToChars;
13197 var mapDoc$2 = doc.utils.mapDoc,
13198 printDocToString$1 = doc.printer.printDocToString,
13199 printDocToDebug = doc.debug.printDocToDebug;
13200 var UTF8BOM = 0xfeff;
13201 var CURSOR = Symbol("cursor");
13202 var PLACEHOLDERS = {
13203 cursorOffset: "<<<PRETTIER_CURSOR>>>",
13204 rangeStart: "<<<PRETTIER_RANGE_START>>>",
13205 rangeEnd: "<<<PRETTIER_RANGE_END>>>"
13208 function ensureAllCommentsPrinted(astComments) {
13209 if (!astComments) {
13213 for (var i = 0; i < astComments.length; ++i) {
13214 if (astComments[i].value.trim() === "prettier-ignore") {
13215 // If there's a prettier-ignore, we're not printing that sub-tree so we
13216 // don't know if the comments was printed or not.
13221 astComments.forEach(function (comment) {
13222 if (!comment.printed) {
13223 throw new Error('Comment "' + comment.value.trim() + '" was not printed. Please report this error!');
13226 delete comment.printed;
13230 function attachComments(text, ast, opts) {
13231 var astComments = ast.comments;
13234 delete ast.comments;
13235 comments.attach(astComments, ast, text, opts);
13239 opts.originalText = opts.parser === "yaml" ? text : text.trimRight();
13240 return astComments;
13243 function coreFormat(text, opts, addAlignmentSize) {
13244 if (!text || !text.trim().length) {
13251 addAlignmentSize = addAlignmentSize || 0;
13252 var parsed = parser.parse(text, opts);
13253 var ast = parsed.ast;
13254 text = parsed.text;
13256 if (opts.cursorOffset >= 0) {
13257 var nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts);
13259 if (nodeResult && nodeResult.node) {
13260 opts.cursorNode = nodeResult.node;
13264 var astComments = attachComments(text, ast, opts);
13265 var doc = astToDoc(ast, opts, addAlignmentSize);
13266 var eol = convertEndOfLineToChars$2(opts.endOfLine);
13267 var result = printDocToString$1(opts.endOfLine === "lf" ? doc : mapDoc$2(doc, function (currentDoc) {
13268 return typeof currentDoc === "string" && currentDoc.indexOf("\n") !== -1 ? currentDoc.replace(/\n/g, eol) : currentDoc;
13270 ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline
13272 if (addAlignmentSize > 0) {
13273 var trimmed = result.formatted.trim();
13275 if (result.cursorNodeStart !== undefined) {
13276 result.cursorNodeStart -= result.formatted.indexOf(trimmed);
13279 result.formatted = trimmed + convertEndOfLineToChars$2(opts.endOfLine);
13282 if (opts.cursorOffset >= 0) {
13283 var oldCursorNodeStart;
13284 var oldCursorNodeText;
13285 var cursorOffsetRelativeToOldCursorNode;
13286 var newCursorNodeStart;
13287 var newCursorNodeText;
13289 if (opts.cursorNode && result.cursorNodeText) {
13290 oldCursorNodeStart = opts.locStart(opts.cursorNode);
13291 oldCursorNodeText = text.slice(oldCursorNodeStart, opts.locEnd(opts.cursorNode));
13292 cursorOffsetRelativeToOldCursorNode = opts.cursorOffset - oldCursorNodeStart;
13293 newCursorNodeStart = result.cursorNodeStart;
13294 newCursorNodeText = result.cursorNodeText;
13296 oldCursorNodeStart = 0;
13297 oldCursorNodeText = text;
13298 cursorOffsetRelativeToOldCursorNode = opts.cursorOffset;
13299 newCursorNodeStart = 0;
13300 newCursorNodeText = result.formatted;
13303 if (oldCursorNodeText === newCursorNodeText) {
13305 formatted: result.formatted,
13306 cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode
13308 } // diff old and new cursor node texts, with a special cursor
13309 // symbol inserted to find out where it moves to
13312 var oldCursorNodeCharArray = oldCursorNodeText.split("");
13313 oldCursorNodeCharArray.splice(cursorOffsetRelativeToOldCursorNode, 0, CURSOR);
13314 var newCursorNodeCharArray = newCursorNodeText.split("");
13315 var cursorNodeDiff = index_es6.diffArrays(oldCursorNodeCharArray, newCursorNodeCharArray);
13316 var cursorOffset = newCursorNodeStart;
13317 var _iteratorNormalCompletion = true;
13318 var _didIteratorError = false;
13319 var _iteratorError = undefined;
13322 for (var _iterator = cursorNodeDiff[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
13323 var entry = _step.value;
13325 if (entry.removed) {
13326 if (entry.value.indexOf(CURSOR) > -1) {
13330 cursorOffset += entry.count;
13334 _didIteratorError = true;
13335 _iteratorError = err;
13338 if (!_iteratorNormalCompletion && _iterator.return != null) {
13339 _iterator.return();
13342 if (_didIteratorError) {
13343 throw _iteratorError;
13349 formatted: result.formatted,
13355 formatted: result.formatted
13359 function formatRange(text, opts) {
13360 var parsed = parser.parse(text, opts);
13361 var ast = parsed.ast;
13362 text = parsed.text;
13363 var range = rangeUtil.calculateRange(text, opts, ast);
13364 var rangeStart = range.rangeStart;
13365 var rangeEnd = range.rangeEnd;
13366 var rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line.
13367 // This is so we can detect indentation correctly and restore it.
13368 // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0
13370 var rangeStart2 = Math.min(rangeStart, text.lastIndexOf("\n", rangeStart) + 1);
13371 var indentString = text.slice(rangeStart2, rangeStart);
13372 var alignmentSize = util.getAlignmentSize(indentString, opts.tabWidth);
13373 var rangeResult = coreFormat(rangeString, Object.assign({}, opts, {
13375 rangeEnd: Infinity,
13376 // track the cursor offset only if it's within our range
13377 cursorOffset: opts.cursorOffset >= rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart : -1
13378 }), alignmentSize); // Since the range contracts to avoid trailing whitespace,
13379 // we need to remove the newline that was inserted by the `format` call.
13381 var rangeTrimmed = rangeResult.formatted.trimRight();
13382 var rangeLeft = text.slice(0, rangeStart);
13383 var rangeRight = text.slice(rangeEnd);
13384 var cursorOffset = opts.cursorOffset;
13386 if (opts.cursorOffset >= rangeEnd) {
13387 // handle the case where the cursor was past the end of the range
13388 cursorOffset = opts.cursorOffset - rangeEnd + (rangeStart + rangeTrimmed.length);
13389 } else if (rangeResult.cursorOffset !== undefined) {
13390 // handle the case where the cursor was in the range
13391 cursorOffset = rangeResult.cursorOffset + rangeStart;
13392 } // keep the cursor as it was if it was before the start of the range
13397 if (opts.endOfLine === "lf") {
13398 formatted = rangeLeft + rangeTrimmed + rangeRight;
13400 var eol = convertEndOfLineToChars$2(opts.endOfLine);
13402 if (cursorOffset >= 0) {
13403 var parts = [rangeLeft, rangeTrimmed, rangeRight];
13405 var partOffset = cursorOffset;
13407 while (partIndex < parts.length) {
13408 var part = parts[partIndex];
13410 if (partOffset < part.length) {
13411 parts[partIndex] = parts[partIndex].slice(0, partOffset) + PLACEHOLDERS.cursorOffset + parts[partIndex].slice(partOffset);
13416 partOffset -= part.length;
13419 var newRangeLeft = parts[0],
13420 newRangeTrimmed = parts[1],
13421 newRangeRight = parts[2];
13422 formatted = (newRangeLeft.replace(/\n/g, eol) + newRangeTrimmed + newRangeRight.replace(/\n/g, eol)).replace(PLACEHOLDERS.cursorOffset, function (_, index) {
13423 cursorOffset = index;
13427 formatted = rangeLeft.replace(/\n/g, eol) + rangeTrimmed + rangeRight.replace(/\n/g, eol);
13437 function format(text, opts) {
13438 var selectedParser = parser.resolveParser(opts);
13439 var hasPragma = !selectedParser.hasPragma || selectedParser.hasPragma(text);
13441 if (opts.requirePragma && !hasPragma) {
13447 if (opts.endOfLine === "auto") {
13448 opts.endOfLine = guessEndOfLine$1(text);
13451 var hasCursor = opts.cursorOffset >= 0;
13452 var hasRangeStart = opts.rangeStart > 0;
13453 var hasRangeEnd = opts.rangeEnd < text.length; // get rid of CR/CRLF parsing
13455 if (text.indexOf("\r") !== -1) {
13456 var offsetKeys = [hasCursor && "cursorOffset", hasRangeStart && "rangeStart", hasRangeEnd && "rangeEnd"].filter(Boolean).sort(function (aKey, bKey) {
13457 return opts[aKey] - opts[bKey];
13460 for (var i = offsetKeys.length - 1; i >= 0; i--) {
13461 var key = offsetKeys[i];
13462 text = text.slice(0, opts[key]) + PLACEHOLDERS[key] + text.slice(opts[key]);
13465 text = text.replace(/\r\n?/g, "\n");
13467 var _loop = function _loop(_i) {
13468 var key = offsetKeys[_i];
13469 text = text.replace(PLACEHOLDERS[key], function (_, index) {
13475 for (var _i = 0; _i < offsetKeys.length; _i++) {
13480 var hasUnicodeBOM = text.charCodeAt(0) === UTF8BOM;
13482 if (hasUnicodeBOM) {
13483 text = text.substring(1);
13486 opts.cursorOffset++;
13489 if (hasRangeStart) {
13499 opts.cursorOffset = -1;
13502 if (opts.rangeStart < 0) {
13503 opts.rangeStart = 0;
13506 if (opts.rangeEnd > text.length) {
13507 opts.rangeEnd = text.length;
13510 var result = hasRangeStart || hasRangeEnd ? formatRange(text, opts) : coreFormat(opts.insertPragma && opts.printer.insertPragma && !hasPragma ? opts.printer.insertPragma(text) : text, opts);
13512 if (hasUnicodeBOM) {
13513 result.formatted = String.fromCharCode(UTF8BOM) + result.formatted;
13516 result.cursorOffset++;
13524 formatWithCursor(text, opts) {
13525 opts = normalizeOptions$1(opts);
13526 return format(text, opts);
13529 parse(text, opts, massage) {
13530 opts = normalizeOptions$1(opts);
13532 if (text.indexOf("\r") !== -1) {
13533 text = text.replace(/\r\n?/g, "\n");
13536 var parsed = parser.parse(text, opts);
13539 parsed.ast = massageAst(parsed.ast, opts);
13545 formatAST(ast, opts) {
13546 opts = normalizeOptions$1(opts);
13547 var doc = astToDoc(ast, opts);
13548 return printDocToString$1(doc, opts);
13551 // Doesn't handle shebang for now
13552 formatDoc(doc, opts) {
13553 var debug = printDocToDebug(doc);
13554 opts = normalizeOptions$1(Object.assign({}, opts, {
13557 return format(debug, opts).formatted;
13560 printToDoc(text, opts) {
13561 opts = normalizeOptions$1(opts);
13562 var parsed = parser.parse(text, opts);
13563 var ast = parsed.ast;
13564 text = parsed.text;
13565 attachComments(text, ast, opts);
13566 return astToDoc(ast, opts);
13569 printDocToString(doc, opts) {
13570 return printDocToString$1(doc, normalizeOptions$1(opts));
13575 // A simple implementation of make-array
13576 function make_array(subject) {
13577 return Array.isArray(subject) ? subject : [subject];
13580 var REGEX_BLANK_LINE = /^\s+$/;
13581 var REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
13582 var REGEX_LEADING_EXCAPED_HASH = /^\\#/;
13584 var KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore')
13585 /* istanbul ignore next */
13588 var define = function define(object, key, value) {
13589 return Object.defineProperty(object, key, {
13594 var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression
13595 // The cases are complicated, see test cases for details
13597 var sanitizeRange = function sanitizeRange(range) {
13598 return range.replace(REGEX_REGEXP_RANGE, function (match, from, to) {
13599 return from.charCodeAt(0) <= to.charCodeAt(0) ? match // Invalid range (out of order) which is ok for gitignore rules but
13600 // fatal for JavaScript regular expression, so eliminate it.
13603 }; // > If the pattern ends with a slash,
13604 // > it is removed for the purpose of the following description,
13605 // > but it would only find a match with a directory.
13606 // > In other words, foo/ will match a directory foo and paths underneath it,
13607 // > but will not match a regular file or a symbolic link foo
13608 // > (this is consistent with the way how pathspec works in general in Git).
13609 // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
13610 // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
13611 // you could use option `mark: true` with `glob`
13612 // '`foo/`' should not continue with the '`..`'
13615 var DEFAULT_REPLACER_PREFIX = [// > Trailing spaces are ignored unless they are quoted with backslash ("\")
13619 /\\?\s+$/, function (match) {
13620 return match.indexOf('\\') === 0 ? ' ' : '';
13621 }], // replace (\ ) with ' '
13622 [/\\\s/g, function () {
13624 }], // Escape metacharacters
13625 // which is written down by users but means special for regular expressions.
13626 // > There are 12 characters with special meanings:
13627 // > - the backslash \,
13628 // > - the caret ^,
13629 // > - the dollar sign $,
13630 // > - the period or dot .,
13631 // > - the vertical bar or pipe symbol |,
13632 // > - the question mark ?,
13633 // > - the asterisk or star *,
13634 // > - the plus sign +,
13635 // > - the opening parenthesis (,
13636 // > - the closing parenthesis ),
13637 // > - and the opening square bracket [,
13638 // > - the opening curly brace {,
13639 // > These special characters are often called "metacharacters".
13640 [/[\\^$.|*+(){]/g, function (match) {
13641 return `\\${match}`;
13642 }], [// > [abc] matches any character inside the brackets
13643 // > (in this case a, b, or c);
13644 /\[([^\]/]*)($|\])/g, function (match, p1, p2) {
13645 return p2 === ']' ? `[${sanitizeRange(p1)}]` : `\\${match}`;
13646 }], [// > a question mark (?) matches a single character
13647 /(?!\\)\?/g, function () {
13649 }], // leading slash
13650 [// > A leading slash matches the beginning of the pathname.
13651 // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
13652 // A leading slash matches the beginning of the pathname
13653 /^\//, function () {
13655 }], // replace special metacharacter slash after the leading slash
13656 [/\//g, function () {
13658 }], [// > A leading "**" followed by a slash means match in all directories.
13659 // > For example, "**/foo" matches file or directory "foo" anywhere,
13660 // > the same as pattern "foo".
13661 // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
13662 // > under directory "foo".
13663 // Notice that the '*'s have been replaced as '\\*'
13664 /^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo'
13666 return '^(?:.*\\/)?';
13668 var DEFAULT_REPLACER_SUFFIX = [// starting
13669 [// there will be no leading '/'
13670 // (which has been replaced by section "leading slash")
13671 // If starts with '**', adding a '^' to the regular expression also works
13672 /^(?=[^^])/, function startingReplacer() {
13673 return !/\/(?!$)/.test(this) // > If the pattern does not contain a slash /,
13674 // > Git treats it as a shell glob pattern
13675 // Actually, if there is only a trailing slash,
13676 // git also treats it as a shell glob pattern
13677 ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for
13678 // > consumption by fnmatch(3)
13680 }], // two globstars
13681 [// Use lookahead assertions so that we could match more than one `'/**'`
13682 /\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories
13683 // should not use '*', or it will be replaced by the next replacer
13684 // Check if it is not the last `'/**'`
13685 function (match, index, str) {
13686 return index + 6 < str.length // case: /**/
13687 // > A slash followed by two consecutive asterisks then a slash matches
13688 // > zero or more directories.
13689 // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
13691 ? '(?:\\/[^\\/]+)*' // case: /**
13692 // > A trailing `"/**"` matches everything inside.
13693 // #21: everything inside but it should not include the current folder
13695 }], // intermediate wildcards
13696 [// Never replace escaped '*'
13697 // ignore rule '\*' will match the path '*'
13699 // 'abc.*' -> skip this rule
13700 /(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js'
13701 // '*.js' doesn't match 'abc'
13702 function (match, p1) {
13703 return `${p1}[^\\/]*`;
13704 }], // trailing wildcard
13705 [/(\^|\\\/)?\\\*$/, function (match, p1) {
13706 var prefix = p1 // '\^':
13707 // '/*' does not match ''
13708 // '/*' does not match everything
13710 // 'abc/*' does not match 'abc/'
13711 ? `${p1}[^/]+` // 'a*' matches 'a'
13712 // 'a*' matches 'aa'
13714 return `${prefix}(?=$|\\/$)`;
13716 /\\\\\\/g, function () {
13719 var POSITIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [// 'f'
13731 [// 'js' will not match 'js.'
13732 // 'ab' will not match 'abc'
13733 /(?:[^*/])$/, // 'js*' will not match 'a.js'
13734 // 'js/' will not match 'a.js'
13735 // 'js' will match 'a.js' and 'a.js/'
13737 return `${match}(?=$|\\/)`;
13738 }]], DEFAULT_REPLACER_SUFFIX);
13739 var NEGATIVE_REPLACERS = [].concat(DEFAULT_REPLACER_PREFIX, [// #24, #38
13740 // The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore)
13741 // A negative pattern without a trailing wildcard should not
13742 // re-include the things inside that directory.
13744 // ['node_modules/*', '!node_modules']
13745 // should ignore `node_modules/a.js`
13746 [/(?:[^*])$/, function (match) {
13747 return `${match}(?=$|\\/$)`;
13748 }]], DEFAULT_REPLACER_SUFFIX); // A simple cache, because an ignore rule only has only one certain meaning
13750 var cache = Object.create(null); // @param {pattern}
13752 var make_regex = function make_regex(pattern, negative, ignorecase) {
13753 var r = cache[pattern];
13759 var replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS;
13760 var source = replacers.reduce(function (prev, current) {
13761 return prev.replace(current[0], current[1].bind(pattern));
13763 return cache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source);
13764 }; // > A blank line matches no files, so it can serve as a separator for readability.
13767 var checkPattern = function checkPattern(pattern) {
13768 return pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment.
13769 && pattern.indexOf('#') !== 0;
13772 var createRule = function createRule(pattern, ignorecase) {
13773 var origin = pattern;
13774 var negative = false; // > An optional prefix "!" which negates the pattern;
13776 if (pattern.indexOf('!') === 0) {
13778 pattern = pattern.substr(1);
13781 pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that
13782 // > begin with a literal "!", for example, `"\!important!.txt"`.
13783 .replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that
13784 // > begin with a hash.
13785 .replace(REGEX_LEADING_EXCAPED_HASH, '#');
13786 var regex = make_regex(pattern, negative, ignorecase);
13798 function IgnoreBase() {
13799 var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
13800 _ref$ignorecase = _ref.ignorecase,
13801 ignorecase = _ref$ignorecase === void 0 ? true : _ref$ignorecase;
13803 _classCallCheck(this, IgnoreBase);
13806 this._ignorecase = ignorecase;
13807 define(this, KEY_IGNORE, true);
13812 _createClass(IgnoreBase, [{
13814 value: function _initCache() {
13815 this._cache = Object.create(null);
13816 } // @param {Array.<string>|string|Ignore} pattern
13820 value: function add(pattern) {
13821 this._added = false;
13823 if (typeof pattern === 'string') {
13824 pattern = pattern.split(/\r?\n/g);
13827 make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore,
13828 // making the behavior changed.
13839 value: function addPattern(pattern) {
13840 return this.add(pattern);
13843 key: "_addPattern",
13844 value: function _addPattern(pattern) {
13846 if (pattern && pattern[KEY_IGNORE]) {
13847 this._rules = this._rules.concat(pattern._rules);
13848 this._added = true;
13852 if (checkPattern(pattern)) {
13853 var rule = createRule(pattern, this._ignorecase);
13854 this._added = true;
13856 this._rules.push(rule);
13861 value: function filter(paths) {
13864 return make_array(paths).filter(function (path) {
13865 return _this._filter(path);
13869 key: "createFilter",
13870 value: function createFilter() {
13873 return function (path) {
13874 return _this2._filter(path);
13879 value: function ignores(path) {
13880 return !this._filter(path);
13881 } // @returns `Boolean` true if the `path` is NOT ignored
13885 value: function _filter(path, slices) {
13890 if (path in this._cache) {
13891 return this._cache[path];
13896 // ['path', 'to', 'a.js']
13897 slices = path.split(SLASH);
13901 return this._cache[path] = slices.length // > It is not possible to re-include a file if a parent directory of
13902 // > that file is excluded.
13903 // If the path contains a parent directory, check the parent first
13904 ? this._filter(slices.join(SLASH) + SLASH, slices) && this._test(path) // Or only test the path
13905 : this._test(path);
13906 } // @returns {Boolean} true if a file is NOT ignored
13910 value: function _test(path) {
13911 // Explicitly define variable type by setting matched to `0`
13914 this._rules.forEach(function (rule) {
13915 // if matched = true, then we only test negative rules
13916 // if matched = false, then we test non-negative rules
13917 if (!(matched ^ rule.negative)) {
13918 matched = rule.negative ^ rule.regex.test(path);
13928 // --------------------------------------------------------------
13930 /* istanbul ignore if */
13933 if ( // Detect `process` so that it can run in browsers.
13934 typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) {
13935 var filter = IgnoreBase.prototype._filter;
13936 /* eslint no-control-regex: "off" */
13938 var make_posix = function make_posix(str) {
13939 return /^\\\\\?\\/.test(str) || /[^\x00-\x80]+/.test(str) ? str : str.replace(/\\/g, '/');
13942 IgnoreBase.prototype._filter = function filterWin32(path, slices) {
13943 path = make_posix(path);
13944 return filter.call(this, path, slices);
13948 var ignore = function ignore(options) {
13949 return new IgnoreBase(options);
13953 * @param {string} filename
13954 * @returns {Promise<null | string>}
13958 function getFileContentOrNull(filename) {
13959 return new Promise(function (resolve, reject) {
13960 fs$1.readFile(filename, "utf8", function (error, data) {
13961 if (error && error.code !== "ENOENT") {
13962 reject(createError(filename, error));
13964 resolve(error ? null : data);
13970 * @param {string} filename
13971 * @returns {null | string}
13975 getFileContentOrNull.sync = function (filename) {
13977 return fs$1.readFileSync(filename, "utf8");
13979 if (error && error.code === "ENOENT") {
13983 throw createError(filename, error);
13987 function createError(filename, error) {
13988 return new Error(`Unable to read ${filename}: ${error.message}`);
13991 var getFileContentOrNull_1 = getFileContentOrNull;
13994 * @param {undefined | string} ignorePath
13995 * @param {undefined | boolean} withNodeModules
13999 function createIgnorer(ignorePath, withNodeModules) {
14000 return (!ignorePath ? Promise.resolve(null) : getFileContentOrNull_1(path$2.resolve(ignorePath))).then(function (ignoreContent) {
14001 return _createIgnorer(ignoreContent, withNodeModules);
14005 * @param {undefined | string} ignorePath
14006 * @param {undefined | boolean} withNodeModules
14010 createIgnorer.sync = function (ignorePath, withNodeModules) {
14011 var ignoreContent = !ignorePath ? null : getFileContentOrNull_1.sync(path$2.resolve(ignorePath));
14012 return _createIgnorer(ignoreContent, withNodeModules);
14015 * @param {null | string} ignoreContent
14016 * @param {undefined | boolean} withNodeModules
14020 function _createIgnorer(ignoreContent, withNodeModules) {
14021 var ignorer = ignore().add(ignoreContent || "");
14023 if (!withNodeModules) {
14024 ignorer.add("node_modules");
14030 var createIgnorer_1 = createIgnorer;
14032 var thirdParty = require("./third-party");
14034 var concatMap = function concatMap(xs, fn) {
14037 for (var i = 0; i < xs.length; i++) {
14038 var x = fn(xs[i], i);
14039 if (isArray(x)) res.push.apply(res, x);else res.push(x);
14045 var isArray = Array.isArray || function (xs) {
14046 return Object.prototype.toString.call(xs) === '[object Array]';
14049 var balancedMatch = balanced;
14051 function balanced(a, b, str) {
14052 if (a instanceof RegExp) a = maybeMatch(a, str);
14053 if (b instanceof RegExp) b = maybeMatch(b, str);
14054 var r = range(a, b, str);
14058 pre: str.slice(0, r[0]),
14059 body: str.slice(r[0] + a.length, r[1]),
14060 post: str.slice(r[1] + b.length)
14064 function maybeMatch(reg, str) {
14065 var m = str.match(reg);
14066 return m ? m[0] : null;
14069 balanced.range = range;
14071 function range(a, b, str) {
14072 var begs, beg, left, right, result;
14073 var ai = str.indexOf(a);
14074 var bi = str.indexOf(b, ai + 1);
14077 if (ai >= 0 && bi > 0) {
14081 while (i >= 0 && !result) {
14084 ai = str.indexOf(a, i + 1);
14085 } else if (begs.length == 1) {
14086 result = [begs.pop(), bi];
14095 bi = str.indexOf(b, i + 1);
14098 i = ai < bi && ai >= 0 ? ai : bi;
14102 result = [left, right];
14109 var braceExpansion = expandTop;
14110 var escSlash = '\0SLASH' + Math.random() + '\0';
14111 var escOpen = '\0OPEN' + Math.random() + '\0';
14112 var escClose = '\0CLOSE' + Math.random() + '\0';
14113 var escComma = '\0COMMA' + Math.random() + '\0';
14114 var escPeriod = '\0PERIOD' + Math.random() + '\0';
14116 function numeric(str) {
14117 return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
14120 function escapeBraces(str) {
14121 return str.split('\\\\').join(escSlash).split('\\{').join(escOpen).split('\\}').join(escClose).split('\\,').join(escComma).split('\\.').join(escPeriod);
14124 function unescapeBraces(str) {
14125 return str.split(escSlash).join('\\').split(escOpen).join('{').split(escClose).join('}').split(escComma).join(',').split(escPeriod).join('.');
14126 } // Basically just str.split(","), but handling cases
14127 // where we have nested braced sections, which should be
14128 // treated as individual members, like {a,{b,c},d}
14131 function parseCommaParts(str) {
14132 if (!str) return [''];
14134 var m = balancedMatch('{', '}', str);
14135 if (!m) return str.split(',');
14139 var p = pre.split(',');
14140 p[p.length - 1] += '{' + body + '}';
14141 var postParts = parseCommaParts(post);
14144 p[p.length - 1] += postParts.shift();
14145 p.push.apply(p, postParts);
14148 parts.push.apply(parts, p);
14152 function expandTop(str) {
14153 if (!str) return []; // I don't know why Bash 4.3 does this, but it does.
14154 // Anything starting with {} will have the first two bytes preserved
14155 // but *only* at the top level, so {},a}b will not expand to anything,
14156 // but a{},b}c will be expanded to [a}c,abc].
14157 // One could argue that this is a bug in Bash, but since the goal of
14158 // this module is to match Bash's rules, we escape a leading {}
14160 if (str.substr(0, 2) === '{}') {
14161 str = '\\{\\}' + str.substr(2);
14164 return expand(escapeBraces(str), true).map(unescapeBraces);
14167 function embrace(str) {
14168 return '{' + str + '}';
14171 function isPadded(el) {
14172 return /^-?0\d/.test(el);
14175 function lte(i, y) {
14179 function gte(i, y) {
14183 function expand(str, isTop) {
14184 var expansions = [];
14185 var m = balancedMatch('{', '}', str);
14186 if (!m || /\$$/.test(m.pre)) return [str];
14187 var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
14188 var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
14189 var isSequence = isNumericSequence || isAlphaSequence;
14190 var isOptions = m.body.indexOf(',') >= 0;
14192 if (!isSequence && !isOptions) {
14194 if (m.post.match(/,.*\}/)) {
14195 str = m.pre + '{' + m.body + escClose + m.post;
14196 return expand(str);
14205 n = m.body.split(/\.\./);
14207 n = parseCommaParts(m.body);
14209 if (n.length === 1) {
14210 // x{{a,b}}y ==> x{a}y x{b}y
14211 n = expand(n[0], false).map(embrace);
14213 if (n.length === 1) {
14214 var post = m.post.length ? expand(m.post, false) : [''];
14215 return post.map(function (p) {
14216 return m.pre + n[0] + p;
14220 } // at this point, n is the parts, and we know it's not a comma set
14221 // with a single entry.
14222 // no need to expand pre, since it is guaranteed to be free of brace-sets
14226 var post = m.post.length ? expand(m.post, false) : [''];
14230 var x = numeric(n[0]);
14231 var y = numeric(n[1]);
14232 var width = Math.max(n[0].length, n[1].length);
14233 var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
14235 var reverse = y < x;
14242 var pad = n.some(isPadded);
14245 for (var i = x; test(i, y); i += incr) {
14248 if (isAlphaSequence) {
14249 c = String.fromCharCode(i);
14250 if (c === '\\') c = '';
14255 var need = width - c.length;
14258 var z = new Array(need + 1).join('0');
14259 if (i < 0) c = '-' + z + c.slice(1);else c = z + c;
14267 N = concatMap(n, function (el) {
14268 return expand(el, false);
14272 for (var j = 0; j < N.length; j++) {
14273 for (var k = 0; k < post.length; k++) {
14274 var expansion = pre + N[j] + post[k];
14275 if (!isTop || isSequence || expansion) expansions.push(expansion);
14282 var minimatch_1 = minimatch;
14283 minimatch.Minimatch = Minimatch;
14292 var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
14314 }; // any single thing other than /
14315 // don't need to escape / when using new RegExp()
14317 var qmark = '[^/]'; // * => any number of characters
14319 var star = qmark + '*?'; // ** when dots are allowed. Anything goes, except .. and .
14320 // not (^ or / followed by one or two dots followed by $ or /),
14321 // followed by anything, any number of times.
14323 var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; // not a ^ or / followed by a dot,
14324 // followed by anything, any number of times.
14326 var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; // characters that need to be escaped in RegExp.
14328 var reSpecials = charSet('().*{}+?[]^$\\!'); // "abc" -> { a:true, b:true, c:true }
14330 function charSet(s) {
14331 return s.split('').reduce(function (set, c) {
14335 } // normalizes slashes.
14338 var slashSplit = /\/+/;
14339 minimatch.filter = filter$1;
14341 function filter$1(pattern, options) {
14342 options = options || {};
14343 return function (p, i, list) {
14344 return minimatch(p, pattern, options);
14348 function ext(a, b) {
14352 Object.keys(b).forEach(function (k) {
14355 Object.keys(a).forEach(function (k) {
14361 minimatch.defaults = function (def) {
14362 if (!def || !Object.keys(def).length) return minimatch;
14363 var orig = minimatch;
14365 var m = function minimatch(p, pattern, options) {
14366 return orig.minimatch(p, pattern, ext(def, options));
14369 m.Minimatch = function Minimatch(pattern, options) {
14370 return new orig.Minimatch(pattern, ext(def, options));
14376 Minimatch.defaults = function (def) {
14377 if (!def || !Object.keys(def).length) return Minimatch;
14378 return minimatch.defaults(def).Minimatch;
14381 function minimatch(p, pattern, options) {
14382 if (typeof pattern !== 'string') {
14383 throw new TypeError('glob pattern string required');
14386 if (!options) options = {}; // shortcut: comments match nothing.
14388 if (!options.nocomment && pattern.charAt(0) === '#') {
14390 } // "" only matches ""
14393 if (pattern.trim() === '') return p === '';
14394 return new Minimatch(pattern, options).match(p);
14397 function Minimatch(pattern, options) {
14398 if (!(this instanceof Minimatch)) {
14399 return new Minimatch(pattern, options);
14402 if (typeof pattern !== 'string') {
14403 throw new TypeError('glob pattern string required');
14406 if (!options) options = {};
14407 pattern = pattern.trim(); // windows support: need to use /, not \
14409 if (path.sep !== '/') {
14410 pattern = pattern.split(path.sep).join('/');
14413 this.options = options;
14415 this.pattern = pattern;
14416 this.regexp = null;
14417 this.negate = false;
14418 this.comment = false;
14419 this.empty = false; // make the set of regexps etc.
14424 Minimatch.prototype.debug = function () {};
14426 Minimatch.prototype.make = make;
14429 // don't do it more than once.
14430 if (this._made) return;
14431 var pattern = this.pattern;
14432 var options = this.options; // empty patterns and comments match nothing.
14434 if (!options.nocomment && pattern.charAt(0) === '#') {
14435 this.comment = true;
14442 } // step 1: figure out negation, etc.
14445 this.parseNegate(); // step 2: expand braces
14447 var set = this.globSet = this.braceExpand();
14448 if (options.debug) this.debug = console.error;
14449 this.debug(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion
14450 // matching patterns.
14451 // These will be regexps, except in the case of "**", which is
14452 // set to the GLOBSTAR object for globstar behavior,
14453 // and will not contain any / characters
14455 set = this.globParts = set.map(function (s) {
14456 return s.split(slashSplit);
14458 this.debug(this.pattern, set); // glob --> regexps
14460 set = set.map(function (s, si, set) {
14461 return s.map(this.parse, this);
14463 this.debug(this.pattern, set); // filter out everything that didn't compile properly.
14465 set = set.filter(function (s) {
14466 return s.indexOf(false) === -1;
14468 this.debug(this.pattern, set);
14472 Minimatch.prototype.parseNegate = parseNegate;
14474 function parseNegate() {
14475 var pattern = this.pattern;
14476 var negate = false;
14477 var options = this.options;
14478 var negateOffset = 0;
14479 if (options.nonegate) return;
14481 for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === '!'; i++) {
14486 if (negateOffset) this.pattern = pattern.substr(negateOffset);
14487 this.negate = negate;
14488 } // Brace expansion:
14489 // a{b,c}d -> abd acd
14490 // a{b,}c -> abc ac
14491 // a{0..3}d -> a0d a1d a2d a3d
14492 // a{b,c{d,e}f}g -> abg acdfg acefg
14493 // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
14495 // Invalid sets are not expanded.
14496 // a{2..}b -> a{2..}b
14500 minimatch.braceExpand = function (pattern, options) {
14501 return braceExpand(pattern, options);
14504 Minimatch.prototype.braceExpand = braceExpand;
14506 function braceExpand(pattern, options) {
14508 if (this instanceof Minimatch) {
14509 options = this.options;
14515 pattern = typeof pattern === 'undefined' ? this.pattern : pattern;
14517 if (typeof pattern === 'undefined') {
14518 throw new TypeError('undefined pattern');
14521 if (options.nobrace || !pattern.match(/\{.*\}/)) {
14522 // shortcut. no need to expand.
14526 return braceExpansion(pattern);
14527 } // parse a component of the expanded set.
14528 // At this point, no pattern may contain "/" in it
14529 // so we're going to return a 2d array, where each entry is the full
14530 // pattern, split on '/', and then turned into a regular expression.
14531 // A regexp is made at the end which joins each array with an
14532 // escaped /, and another full one which joins each regexp with |.
14534 // Following the lead of Bash 4.1, note that "**" only has special meaning
14535 // when it is the *only* thing in a path portion. Otherwise, any series
14536 // of * is equivalent to a single *. Globstar behavior is enabled by
14537 // default, and can be disabled by setting options.noglobstar.
14540 Minimatch.prototype.parse = parse$1;
14543 function parse$1(pattern, isSub) {
14544 if (pattern.length > 1024 * 64) {
14545 throw new TypeError('pattern is too long');
14548 var options = this.options; // shortcuts
14550 if (!options.noglobstar && pattern === '**') return GLOBSTAR;
14551 if (pattern === '') return '';
14553 var hasMagic = !!options.nocase;
14554 var escaping = false; // ? => one single character
14556 var patternListStack = [];
14557 var negativeLists = [];
14559 var inClass = false;
14560 var reClassStart = -1;
14561 var classStart = -1; // . and .. never match anything that doesn't start with .,
14562 // even when options.dot is set.
14564 var patternStart = pattern.charAt(0) === '.' ? '' // anything
14565 // not (start or / followed by . or .. followed by / or end)
14566 : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)';
14569 function clearStateChar() {
14571 // we had some state-tracking character
14572 // that wasn't consumed by this pass.
14573 switch (stateChar) {
14585 re += '\\' + stateChar;
14589 self.debug('clearStateChar %j %j', stateChar, re);
14594 for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
14595 this.debug('%s\t%s %s %j', pattern, i, re, c); // skip over any that are escaped.
14597 if (escaping && reSpecials[c]) {
14605 // completely not allowed, even escaped.
14606 // Should already be path-split by now.
14613 // the various stateChar values
14614 // for the "extglob" stuff.
14621 this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); // all of those are literals inside a class, except that
14622 // the glob [!a] means [^a] in regexp
14625 this.debug(' in class');
14626 if (c === '!' && i === classStart + 1) c = '^';
14629 } // if we already have a stateChar, then it means
14630 // that there was something like ** or +? in there.
14631 // Handle the stateChar, then proceed with this one.
14634 self.debug('call clearStateChar %j', stateChar);
14636 stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
14637 // just clear the statechar *now*, rather than even diving into
14638 // the patternList stuff.
14640 if (options.noext) clearStateChar();
14654 patternListStack.push({
14657 reStart: re.length,
14658 open: plTypes[stateChar].open,
14659 close: plTypes[stateChar].close
14660 }); // negation is (?:(?!js)[^/]*)
14662 re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
14663 this.debug('plType %j %j', stateChar, re);
14668 if (inClass || !patternListStack.length) {
14675 var pl = patternListStack.pop(); // negation is (?:(?!js)[^/]*)
14676 // The others are (?:<pattern>)<type>
14680 if (pl.type === '!') {
14681 negativeLists.push(pl);
14684 pl.reEnd = re.length;
14688 if (inClass || !patternListStack.length || escaping) {
14697 // these are mostly the same in regexp and glob
14700 // swallow any state-tracking char before the [
14710 reClassStart = re.length;
14715 // a right bracket shall lose its special
14716 // meaning and represent itself in
14717 // a bracket expression if it occurs
14718 // first in the list. -- POSIX.2 2.8.3.2
14719 if (i === classStart + 1 || !inClass) {
14723 } // handle the case where we left a class open.
14724 // "[z-a]" is valid, equivalent to "\[z-a\]"
14728 // split where the last [ was, make sure we don't have
14729 // an invalid re. if so, re-walk the contents of the
14730 // would-be class to re-translate any characters that
14731 // were passed through as-is
14732 // TODO: It would probably be faster to determine this
14733 // without a try/catch and a new RegExp, but it's tricky
14734 // to do safely. For now, this is safe and works.
14735 var cs = pattern.substring(classStart + 1, i);
14738 RegExp('[' + cs + ']');
14740 // not a valid class!
14741 var sp = this.parse(cs, SUBPARSE);
14742 re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
14743 hasMagic = hasMagic || sp[1];
14747 } // finish up the class.
14756 // swallow any state char that wasn't consumed
14762 } else if (reSpecials[c] && !(c === '^' && inClass)) {
14770 // handle the case where we left a class open.
14771 // "[abc" is valid, equivalent to "\[abc"
14775 // split where the last [ was, and escape it
14776 // this is a huge pita. We now have to re-walk
14777 // the contents of the would-be class to re-translate
14778 // any characters that were passed through as-is
14779 cs = pattern.substr(classStart + 1);
14780 sp = this.parse(cs, SUBPARSE);
14781 re = re.substr(0, reClassStart) + '\\[' + sp[0];
14782 hasMagic = hasMagic || sp[1];
14783 } // handle the case where we had a +( thing at the *end*
14785 // each pattern list stack adds 3 chars, and we need to go through
14786 // and escape any | chars that were passed through as-is for the regexp.
14787 // Go through and escape them, taking care not to double-escape any
14788 // | chars that were already escaped.
14791 for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
14792 var tail = re.slice(pl.reStart + pl.open.length);
14793 this.debug('setting tail', re, pl); // maybe some even number of \, then maybe 1 \, followed by a |
14795 tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
14797 // the | isn't already escaped, so escape it.
14799 } // need to escape all those slashes *again*, without escaping the
14800 // one that we need for escaping the | character. As it works out,
14801 // escaping an even number of slashes can be done by simply repeating
14802 // it exactly after itself. That's why this trick works.
14804 // I am sorry that you have to see this.
14807 return $1 + $1 + $2 + '|';
14809 this.debug('tail=%j\n %s', tail, tail, pl, re);
14810 var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type;
14812 re = re.slice(0, pl.reStart) + t + '\\(' + tail;
14813 } // handle trailing things that only matter at the very end.
14821 } // only need to apply the nodot start if the re starts with
14822 // something that could conceivably capture a dot
14825 var addPatternStart = false;
14827 switch (re.charAt(0)) {
14831 addPatternStart = true;
14832 } // Hack to work around lack of negative lookbehind in JS
14833 // A pattern like: *.!(x).!(y|z) needs to ensure that a name
14834 // like 'a.xyz.yz' doesn't match. So, the first negative
14835 // lookahead, has to look ALL the way ahead, to the end of
14839 for (var n = negativeLists.length - 1; n > -1; n--) {
14840 var nl = negativeLists[n];
14841 var nlBefore = re.slice(0, nl.reStart);
14842 var nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
14843 var nlLast = re.slice(nl.reEnd - 8, nl.reEnd);
14844 var nlAfter = re.slice(nl.reEnd);
14845 nlLast += nlAfter; // Handle nested stuff like *(*.js|!(*.json)), where open parens
14846 // mean that we should *not* include the ) in the bit that is considered
14847 // "after" the negated section.
14849 var openParensBefore = nlBefore.split('(').length - 1;
14850 var cleanAfter = nlAfter;
14852 for (i = 0; i < openParensBefore; i++) {
14853 cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
14856 nlAfter = cleanAfter;
14859 if (nlAfter === '' && isSub !== SUBPARSE) {
14863 var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast;
14865 } // if the re is not "" at this point, then we need to make sure
14866 // it doesn't match against an empty path part.
14867 // Otherwise a/* will match a/, which it should not.
14870 if (re !== '' && hasMagic) {
14874 if (addPatternStart) {
14875 re = patternStart + re;
14876 } // parsing just a piece of a larger pattern.
14879 if (isSub === SUBPARSE) {
14880 return [re, hasMagic];
14881 } // skip the regexp for non-magical patterns
14882 // unescape anything in it, though, so that it'll be
14883 // an exact match against a file etc.
14887 return globUnescape(pattern);
14890 var flags = options.nocase ? 'i' : '';
14893 var regExp = new RegExp('^' + re + '$', flags);
14895 // If it was an invalid regular expression, then it can't match
14896 // anything. This trick looks for a character after the end of
14897 // the string, which is of course impossible, except in multi-line
14898 // mode, but it's not a /m regex.
14899 return new RegExp('$.');
14902 regExp._glob = pattern;
14907 minimatch.makeRe = function (pattern, options) {
14908 return new Minimatch(pattern, options || {}).makeRe();
14911 Minimatch.prototype.makeRe = makeRe;
14913 function makeRe() {
14914 if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
14915 // pattern strings, or "**".
14917 // It's better to use .match(). This function shouldn't
14918 // be used, really, but it's pretty convenient sometimes,
14919 // when you just want to work with a regex.
14921 var set = this.set;
14924 this.regexp = false;
14925 return this.regexp;
14928 var options = this.options;
14929 var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot;
14930 var flags = options.nocase ? 'i' : '';
14931 var re = set.map(function (pattern) {
14932 return pattern.map(function (p) {
14933 return p === GLOBSTAR ? twoStar : typeof p === 'string' ? regExpEscape(p) : p._src;
14935 }).join('|'); // must match entire pattern
14936 // ending in a * or ** will make it less strict.
14938 re = '^(?:' + re + ')$'; // can match anything, as long as it's not this.
14940 if (this.negate) re = '^(?!' + re + ').*$';
14943 this.regexp = new RegExp(re, flags);
14945 this.regexp = false;
14948 return this.regexp;
14951 minimatch.match = function (list, pattern, options) {
14952 options = options || {};
14953 var mm = new Minimatch(pattern, options);
14954 list = list.filter(function (f) {
14955 return mm.match(f);
14958 if (mm.options.nonull && !list.length) {
14959 list.push(pattern);
14965 Minimatch.prototype.match = match;
14967 function match(f, partial) {
14968 this.debug('match', f, this.pattern); // short-circuit in the case of busted things.
14971 if (this.comment) return false;
14972 if (this.empty) return f === '';
14973 if (f === '/' && partial) return true;
14974 var options = this.options; // windows: need to use /, not \
14976 if (path.sep !== '/') {
14977 f = f.split(path.sep).join('/');
14978 } // treat the test path as a set of pathparts.
14981 f = f.split(slashSplit);
14982 this.debug(this.pattern, 'split', f); // just ONE of the pattern sets in this.set needs to match
14983 // in order for it to be valid. If negating, then just one
14984 // match means that we have failed.
14985 // Either way, return on the first hit.
14987 var set = this.set;
14988 this.debug(this.pattern, 'set', set); // Find the basename of the path by looking for the last non-empty segment
14993 for (i = f.length - 1; i >= 0; i--) {
14995 if (filename) break;
14998 for (i = 0; i < set.length; i++) {
14999 var pattern = set[i];
15002 if (options.matchBase && pattern.length === 1) {
15006 var hit = this.matchOne(file, pattern, partial);
15009 if (options.flipNegate) return true;
15010 return !this.negate;
15012 } // didn't get any hits. this is success if it's a negative
15013 // pattern, failure otherwise.
15016 if (options.flipNegate) return false;
15017 return this.negate;
15018 } // set partial to true to test if, for example,
15019 // "/a/b" matches the start of "/*/b/*/d"
15020 // Partial means, if you run out of file before you run
15021 // out of pattern, then that's fine, as long as all
15022 // the parts match.
15025 Minimatch.prototype.matchOne = function (file, pattern, partial) {
15026 var options = this.options;
15027 this.debug('matchOne', {
15032 this.debug('matchOne', file.length, pattern.length);
15034 for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
15035 this.debug('matchOne loop');
15036 var p = pattern[pi];
15038 this.debug(pattern, p, f); // should be impossible.
15039 // some invalid regexp stuff in the set.
15041 if (p === false) return false;
15043 if (p === GLOBSTAR) {
15044 this.debug('GLOBSTAR', [pattern, p, f]); // "**"
15045 // a/**/b/**/c would match the following:
15050 // To do this, take the rest of the pattern after
15051 // the **, and see if it would match the file remainder.
15052 // If so, return success.
15053 // If not, the ** "swallows" a segment, and try again.
15054 // This is recursively awful.
15056 // a/**/b/**/c matching a/b/x/y/z/c
15059 // - matchOne(b/x/y/z/c, b/**/c)
15062 // - matchOne(x/y/z/c, c) -> no
15063 // - matchOne(y/z/c, c) -> no
15064 // - matchOne(z/c, c) -> no
15065 // - matchOne(c, c) yes, hit
15071 this.debug('** at the end'); // a ** at the end will just swallow the rest.
15072 // We have found a match.
15073 // however, it will not swallow /.x, unless
15074 // options.dot is set.
15075 // . and .. are *never* matched by **, for explosively
15076 // exponential reasons.
15078 for (; fi < fl; fi++) {
15079 if (file[fi] === '.' || file[fi] === '..' || !options.dot && file[fi].charAt(0) === '.') return false;
15083 } // ok, let's see if we can swallow whatever we can.
15087 var swallowee = file[fr];
15088 this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); // XXX remove this slice. Just pass the start index.
15090 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
15091 this.debug('globstar found match!', fr, fl, swallowee); // found a match.
15095 // can't swallow "." or ".." ever.
15096 // can only swallow ".foo" when explicitly asked.
15097 if (swallowee === '.' || swallowee === '..' || !options.dot && swallowee.charAt(0) === '.') {
15098 this.debug('dot detected!', file, fr, pattern, pr);
15100 } // ** swallows a segment, and continue.
15103 this.debug('globstar swallow a segment, and continue');
15106 } // no match was found.
15107 // However, in partial mode, we can't say this is necessarily over.
15108 // If there's more *pattern* left, then
15113 this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
15114 if (fr === fl) return true;
15118 } // something other than **
15119 // non-magic patterns just have to match exactly
15120 // patterns with magic have been turned into regexps.
15125 if (typeof p === 'string') {
15126 if (options.nocase) {
15127 hit = f.toLowerCase() === p.toLowerCase();
15132 this.debug('string match', p, f, hit);
15135 this.debug('pattern match', p, f, hit);
15138 if (!hit) return false;
15139 } // Note: ending in / means that we'll get a final ""
15140 // at the end of the pattern. This can only match a
15141 // corresponding "" at the end of the file.
15142 // If the file ends in /, then it can only match a
15143 // a pattern that ends in /, unless the pattern just
15144 // doesn't have any more for it. But, a/b/ should *not*
15145 // match "a/b/*", even though "" matches against the
15146 // [^/]*? pattern, except in partial mode, where it might
15147 // simply not be reached yet.
15148 // However, a/b/ should still satisfy a/*
15149 // now either we fell off the end of the pattern, or we're done.
15152 if (fi === fl && pi === pl) {
15153 // ran out of pattern and filename at the same time.
15156 } else if (fi === fl) {
15157 // ran out of file, but still had pattern left.
15158 // this is ok if we're doing the match as part of
15159 // a glob fs traversal.
15161 } else if (pi === pl) {
15162 // ran out of pattern, still have file left.
15163 // this is only acceptable if we're on the very last
15164 // empty segment of a file with a trailing slash.
15165 // a/* should match a/b/
15166 var emptyFileEnd = fi === fl - 1 && file[fi] === '';
15167 return emptyFileEnd;
15168 } // should be unreachable.
15171 throw new Error('wtf?');
15172 }; // replace stuff like \* with *
15175 function globUnescape(s) {
15176 return s.replace(/\\(.)/g, '$1');
15179 function regExpEscape(s) {
15180 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
15184 var async_hooks = ">= 8";
15185 var buffer_ieee754 = "< 0.9.7";
15187 var child_process = true;
15188 var cluster = true;
15189 var console$1 = true;
15190 var constants = true;
15192 var _debug_agent = ">= 1 && < 8";
15193 var _debugger = "< 8";
15198 var freelist = "< 6";
15200 var _http_agent = ">= 0.11.1";
15201 var _http_client = ">= 0.11.1";
15202 var _http_common = ">= 0.11.1";
15203 var _http_incoming = ">= 0.11.1";
15204 var _http_outgoing = ">= 0.11.1";
15205 var _http_server = ">= 0.11.1";
15207 var http2 = ">= 8.8";
15209 var inspector = ">= 8.0.0";
15210 var _linklist = "< 8";
15211 var module$1 = true;
15215 var perf_hooks = ">= 8.5";
15216 var process$1 = ">= 1";
15217 var punycode = true;
15218 var querystring = true;
15219 var readline = true;
15221 var smalloc = ">= 0.11.5 && < 3";
15222 var _stream_duplex = ">= 0.9.4";
15223 var _stream_transform = ">= 0.9.4";
15224 var _stream_wrap = ">= 1.4.1";
15225 var _stream_passthrough = ">= 0.9.4";
15226 var _stream_readable = ">= 0.9.4";
15227 var _stream_writable = ">= 0.9.4";
15229 var string_decoder = true;
15232 var _tls_common = ">= 0.11.13";
15233 var _tls_legacy = ">= 0.11.3 && < 10";
15234 var _tls_wrap = ">= 0.11.3";
15236 var trace_events = ">= 10";
15242 var worker_threads = ">= 11.7";
15246 async_hooks: async_hooks,
15247 buffer_ieee754: buffer_ieee754,
15249 child_process: child_process,
15251 console: console$1,
15252 constants: constants,
15254 _debug_agent: _debug_agent,
15255 _debugger: _debugger,
15260 freelist: freelist,
15262 "fs/promises": ">= 10 && < 10.1",
15263 _http_agent: _http_agent,
15264 _http_client: _http_client,
15265 _http_common: _http_common,
15266 _http_incoming: _http_incoming,
15267 _http_outgoing: _http_outgoing,
15268 _http_server: _http_server,
15272 inspector: inspector,
15273 _linklist: _linklist,
15276 "node-inspect/lib/_inspect": ">= 7.6.0 && < 12",
15277 "node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12",
15278 "node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12",
15281 perf_hooks: perf_hooks,
15282 process: process$1,
15283 punycode: punycode,
15284 querystring: querystring,
15285 readline: readline,
15288 _stream_duplex: _stream_duplex,
15289 _stream_transform: _stream_transform,
15290 _stream_wrap: _stream_wrap,
15291 _stream_passthrough: _stream_passthrough,
15292 _stream_readable: _stream_readable,
15293 _stream_writable: _stream_writable,
15295 string_decoder: string_decoder,
15298 _tls_common: _tls_common,
15299 _tls_legacy: _tls_legacy,
15300 _tls_wrap: _tls_wrap,
15302 trace_events: trace_events,
15306 "v8/tools/arguments": ">= 10 && < 12",
15307 "v8/tools/codemap": [
15311 "v8/tools/consarray": [
15315 "v8/tools/csvparser": [
15319 "v8/tools/logreader": [
15323 "v8/tools/profile_view": [
15327 "v8/tools/splaytree": [
15333 worker_threads: worker_threads,
15337 var core$2 = /*#__PURE__*/Object.freeze({
15340 async_hooks: async_hooks,
15341 buffer_ieee754: buffer_ieee754,
15343 child_process: child_process,
15345 console: console$1,
15346 constants: constants,
15348 _debug_agent: _debug_agent,
15349 _debugger: _debugger,
15354 freelist: freelist,
15356 _http_agent: _http_agent,
15357 _http_client: _http_client,
15358 _http_common: _http_common,
15359 _http_incoming: _http_incoming,
15360 _http_outgoing: _http_outgoing,
15361 _http_server: _http_server,
15365 inspector: inspector,
15366 _linklist: _linklist,
15371 perf_hooks: perf_hooks,
15372 process: process$1,
15373 punycode: punycode,
15374 querystring: querystring,
15375 readline: readline,
15378 _stream_duplex: _stream_duplex,
15379 _stream_transform: _stream_transform,
15380 _stream_wrap: _stream_wrap,
15381 _stream_passthrough: _stream_passthrough,
15382 _stream_readable: _stream_readable,
15383 _stream_writable: _stream_writable,
15385 string_decoder: string_decoder,
15388 _tls_common: _tls_common,
15389 _tls_legacy: _tls_legacy,
15390 _tls_wrap: _tls_wrap,
15392 trace_events: trace_events,
15398 worker_threads: worker_threads,
15403 var data = getCjsExportFromNamespace(core$2);
15405 var current = process.versions && process.versions.node && process.versions.node.split('.') || [];
15407 function specifierIncluded(specifier) {
15408 var parts = specifier.split(' ');
15409 var op = parts.length > 1 ? parts[0] : '=';
15410 var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.');
15412 for (var i = 0; i < 3; ++i) {
15413 var cur = Number(current[i] || 0);
15414 var ver = Number(versionParts[i] || 0);
15417 continue; // eslint-disable-line no-restricted-syntax, no-continue
15422 } else if (op === '>=') {
15429 return op === '>=';
15432 function matchesRange(range) {
15433 var specifiers = range.split(/ ?&& ?/);
15435 if (specifiers.length === 0) {
15439 for (var i = 0; i < specifiers.length; ++i) {
15440 if (!specifierIncluded(specifiers[i])) {
15448 function versionIncluded(specifierValue) {
15449 if (typeof specifierValue === 'boolean') {
15450 return specifierValue;
15453 if (specifierValue && typeof specifierValue === 'object') {
15454 for (var i = 0; i < specifierValue.length; ++i) {
15455 if (matchesRange(specifierValue[i])) {
15463 return matchesRange(specifierValue);
15468 for (var mod in data) {
15469 // eslint-disable-line no-restricted-syntax
15470 if (Object.prototype.hasOwnProperty.call(data, mod)) {
15471 core$3[mod] = versionIncluded(data[mod]);
15475 var core_1 = core$3;
15477 var caller = function caller() {
15478 // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
15479 var origPrepareStackTrace = Error.prepareStackTrace;
15481 Error.prepareStackTrace = function (_, stack) {
15485 var stack = new Error().stack;
15486 Error.prepareStackTrace = origPrepareStackTrace;
15487 return stack[2].getFileName();
15490 var pathParse = createCommonjsModule(function (module) {
15492 var isWindows = process.platform === 'win32'; // Regex to split a windows path into three parts: [*, device, slash,
15493 // tail] windows-only
15495 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; // Regex to split the tail part of the above into [*, dir, basename, ext]
15497 var splitTailRe = /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
15498 var win32 = {}; // Function to split a filename into [root, dir, basename, ext]
15500 function win32SplitPath(filename) {
15501 // Separate device+slash from tail
15502 var result = splitDeviceRe.exec(filename),
15503 device = (result[1] || '') + (result[2] || ''),
15504 tail = result[3] || ''; // Split the tail into dir, basename and extension
15506 var result2 = splitTailRe.exec(tail),
15508 basename = result2[2],
15510 return [device, dir, basename, ext];
15513 win32.parse = function (pathString) {
15514 if (typeof pathString !== 'string') {
15515 throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
15518 var allParts = win32SplitPath(pathString);
15520 if (!allParts || allParts.length !== 4) {
15521 throw new TypeError("Invalid path '" + pathString + "'");
15526 dir: allParts[0] + allParts[1].slice(0, -1),
15529 name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
15531 }; // Split a filename into [root, dir, basename, ext], unix version
15532 // 'root' is just a slash, or nothing.
15535 var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
15538 function posixSplitPath(filename) {
15539 return splitPathRe.exec(filename).slice(1);
15542 posix.parse = function (pathString) {
15543 if (typeof pathString !== 'string') {
15544 throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString);
15547 var allParts = posixSplitPath(pathString);
15549 if (!allParts || allParts.length !== 4) {
15550 throw new TypeError("Invalid path '" + pathString + "'");
15553 allParts[1] = allParts[1] || '';
15554 allParts[2] = allParts[2] || '';
15555 allParts[3] = allParts[3] || '';
15558 dir: allParts[0] + allParts[1].slice(0, -1),
15561 name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
15565 if (isWindows) module.exports = win32.parse;else
15567 module.exports = posix.parse;
15568 module.exports.posix = posix.parse;
15569 module.exports.win32 = win32.parse;
15571 var pathParse_1 = pathParse.posix;
15572 var pathParse_2 = pathParse.win32;
15574 var parse$2 = path$2.parse || pathParse;
15576 var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) {
15579 if (/^([A-Za-z]:)/.test(absoluteStart)) {
15581 } else if (/^\\\\/.test(absoluteStart)) {
15585 var paths = [absoluteStart];
15586 var parsed = parse$2(absoluteStart);
15588 while (parsed.dir !== paths[paths.length - 1]) {
15589 paths.push(parsed.dir);
15590 parsed = parse$2(parsed.dir);
15593 return paths.reduce(function (dirs, aPath) {
15594 return dirs.concat(modules.map(function (moduleDir) {
15595 return path$2.resolve(prefix, aPath, moduleDir);
15600 var nodeModulesPaths = function nodeModulesPaths(start, opts, request) {
15601 var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ['node_modules'];
15603 if (opts && typeof opts.paths === 'function') {
15604 return opts.paths(request, start, function () {
15605 return getNodeModulesDirs(start, modules);
15609 var dirs = getNodeModulesDirs(start, modules);
15610 return opts && opts.paths ? dirs.concat(opts.paths) : dirs;
15613 var normalizeOptions$2 = function normalizeOptions(x, opts) {
15615 * This file is purposefully a passthrough. It's expected that third-party
15616 * environments will override it at runtime in order to inject special logic
15617 * into `resolve` (by manipulating the options). One such example is the PnP
15618 * code path in Yarn.
15623 var defaultIsFile = function isFile(file, cb) {
15624 fs$1.stat(file, function (err, stat) {
15626 return cb(null, stat.isFile() || stat.isFIFO());
15629 if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
15634 var defaultIsDir = function isDirectory(dir, cb) {
15635 fs$1.stat(dir, function (err, stat) {
15637 return cb(null, stat.isDirectory());
15640 if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false);
15645 var maybeUnwrapSymlink = function maybeUnwrapSymlink(x, opts, cb) {
15646 if (opts && opts.preserveSymlinks === false) {
15647 fs$1.realpath(x, function (realPathErr, realPath) {
15648 if (realPathErr && realPathErr.code !== 'ENOENT') cb(realPathErr);else cb(null, realPathErr ? x : realPath);
15655 var async = function resolve(x, options, callback) {
15657 var opts = options;
15659 if (typeof options === 'function') {
15664 if (typeof x !== 'string') {
15665 var err = new TypeError('Path must be a string.');
15666 return process.nextTick(function () {
15671 opts = normalizeOptions$2(x, opts);
15672 var isFile = opts.isFile || defaultIsFile;
15673 var isDirectory = opts.isDirectory || defaultIsDir;
15674 var readFile = opts.readFile || fs$1.readFile;
15675 var extensions = opts.extensions || ['.js'];
15676 var basedir = opts.basedir || path$2.dirname(caller());
15677 var parent = opts.filename || basedir;
15678 opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
15680 var absoluteStart = path$2.resolve(basedir);
15681 maybeUnwrapSymlink(absoluteStart, opts, function (err, realStart) {
15682 if (err) cb(err);else init(realStart);
15686 function init(basedir) {
15687 if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
15688 res = path$2.resolve(basedir, x);
15689 if (x === '..' || x.slice(-1) === '/') res += '/';
15691 if (/\/$/.test(x) && res === basedir) {
15692 loadAsDirectory(res, opts.package, onfile);
15693 } else loadAsFile(res, opts.package, onfile);
15694 } else loadNodeModules(x, basedir, function (err, n, pkg) {
15695 if (err) cb(err);else if (core_1[x]) return cb(null, x);else if (n) {
15696 return maybeUnwrapSymlink(n, opts, function (err, realN) {
15700 cb(null, realN, pkg);
15704 var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
15705 moduleError.code = 'MODULE_NOT_FOUND';
15711 function onfile(err, m, pkg) {
15712 if (err) cb(err);else if (m) cb(null, m, pkg);else loadAsDirectory(res, function (err, d, pkg) {
15713 if (err) cb(err);else if (d) {
15714 maybeUnwrapSymlink(d, opts, function (err, realD) {
15718 cb(null, realD, pkg);
15722 var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'");
15723 moduleError.code = 'MODULE_NOT_FOUND';
15729 function loadAsFile(x, thePackage, callback) {
15730 var loadAsFilePackage = thePackage;
15733 if (typeof loadAsFilePackage === 'function') {
15734 cb = loadAsFilePackage;
15735 loadAsFilePackage = undefined;
15738 var exts = [''].concat(extensions);
15739 load(exts, x, loadAsFilePackage);
15741 function load(exts, x, loadPackage) {
15742 if (exts.length === 0) return cb(null, undefined, loadPackage);
15743 var file = x + exts[0];
15744 var pkg = loadPackage;
15745 if (pkg) onpkg(null, pkg);else loadpkg(path$2.dirname(file), onpkg);
15747 function onpkg(err, pkg_, dir) {
15749 if (err) return cb(err);
15751 if (dir && pkg && opts.pathFilter) {
15752 var rfile = path$2.relative(dir, file);
15753 var rel = rfile.slice(0, rfile.length - exts[0].length);
15754 var r = opts.pathFilter(pkg, x, rel);
15755 if (r) return load([''].concat(extensions.slice()), path$2.resolve(dir, r), pkg);
15758 isFile(file, onex);
15761 function onex(err, ex) {
15762 if (err) return cb(err);
15763 if (ex) return cb(null, file, pkg);
15764 load(exts.slice(1), x, pkg);
15769 function loadpkg(dir, cb) {
15770 if (dir === '' || dir === '/') return cb(null);
15772 if (process.platform === 'win32' && /^\w:[/\\]*$/.test(dir)) {
15776 if (/[/\\]node_modules[/\\]*$/.test(dir)) return cb(null);
15777 var pkgfile = path$2.join(dir, 'package.json');
15778 isFile(pkgfile, function (err, ex) {
15779 // on err, ex is false
15780 if (!ex) return loadpkg(path$2.dirname(dir), cb);
15781 readFile(pkgfile, function (err, body) {
15785 var pkg = JSON.parse(body);
15786 } catch (jsonErr) {}
15788 if (pkg && opts.packageFilter) {
15789 pkg = opts.packageFilter(pkg, pkgfile);
15792 cb(null, pkg, dir);
15797 function loadAsDirectory(x, loadAsDirectoryPackage, callback) {
15799 var fpkg = loadAsDirectoryPackage;
15801 if (typeof fpkg === 'function') {
15803 fpkg = opts.package;
15806 var pkgfile = path$2.join(x, 'package.json');
15807 isFile(pkgfile, function (err, ex) {
15808 if (err) return cb(err);
15809 if (!ex) return loadAsFile(path$2.join(x, 'index'), fpkg, cb);
15810 readFile(pkgfile, function (err, body) {
15811 if (err) return cb(err);
15814 var pkg = JSON.parse(body);
15815 } catch (jsonErr) {}
15817 if (opts.packageFilter) {
15818 pkg = opts.packageFilter(pkg, pkgfile);
15822 if (typeof pkg.main !== 'string') {
15823 var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
15824 mainError.code = 'INVALID_PACKAGE_MAIN';
15825 return cb(mainError);
15828 if (pkg.main === '.' || pkg.main === './') {
15829 pkg.main = 'index';
15832 loadAsFile(path$2.resolve(x, pkg.main), pkg, function (err, m, pkg) {
15833 if (err) return cb(err);
15834 if (m) return cb(null, m, pkg);
15835 if (!pkg) return loadAsFile(path$2.join(x, 'index'), pkg, cb);
15836 var dir = path$2.resolve(x, pkg.main);
15837 loadAsDirectory(dir, pkg, function (err, n, pkg) {
15838 if (err) return cb(err);
15839 if (n) return cb(null, n, pkg);
15840 loadAsFile(path$2.join(x, 'index'), pkg, cb);
15846 loadAsFile(path$2.join(x, '/index'), pkg, cb);
15851 function processDirs(cb, dirs) {
15852 if (dirs.length === 0) return cb(null, undefined);
15854 isDirectory(dir, isdir);
15856 function isdir(err, isdir) {
15857 if (err) return cb(err);
15858 if (!isdir) return processDirs(cb, dirs.slice(1));
15859 var file = path$2.join(dir, x);
15860 loadAsFile(file, opts.package, onfile);
15863 function onfile(err, m, pkg) {
15864 if (err) return cb(err);
15865 if (m) return cb(null, m, pkg);
15866 loadAsDirectory(path$2.join(dir, x), opts.package, ondir);
15869 function ondir(err, n, pkg) {
15870 if (err) return cb(err);
15871 if (n) return cb(null, n, pkg);
15872 processDirs(cb, dirs.slice(1));
15876 function loadNodeModules(x, start, cb) {
15877 processDirs(cb, nodeModulesPaths(start, opts, x));
15881 var defaultIsFile$1 = function isFile(file) {
15883 var stat = fs$1.statSync(file);
15885 if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
15889 return stat.isFile() || stat.isFIFO();
15892 var defaultIsDir$1 = function isDirectory(dir) {
15894 var stat = fs$1.statSync(dir);
15896 if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
15900 return stat.isDirectory();
15903 var maybeUnwrapSymlink$1 = function maybeUnwrapSymlink(x, opts) {
15904 if (opts && opts.preserveSymlinks === false) {
15906 return fs$1.realpathSync(x);
15907 } catch (realPathErr) {
15908 if (realPathErr.code !== 'ENOENT') {
15917 var sync = function sync(x, options) {
15918 if (typeof x !== 'string') {
15919 throw new TypeError('Path must be a string.');
15922 var opts = normalizeOptions$2(x, options);
15923 var isFile = opts.isFile || defaultIsFile$1;
15924 var readFileSync = opts.readFileSync || fs$1.readFileSync;
15925 var isDirectory = opts.isDirectory || defaultIsDir$1;
15926 var extensions = opts.extensions || ['.js'];
15927 var basedir = opts.basedir || path$2.dirname(caller());
15928 var parent = opts.filename || basedir;
15929 opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory
15931 var absoluteStart = maybeUnwrapSymlink$1(path$2.resolve(basedir), opts);
15933 if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) {
15934 var res = path$2.resolve(absoluteStart, x);
15935 if (x === '..' || x.slice(-1) === '/') res += '/';
15936 var m = loadAsFileSync(res) || loadAsDirectorySync(res);
15937 if (m) return maybeUnwrapSymlink$1(m, opts);
15938 } else if (core_1[x]) {
15941 var n = loadNodeModulesSync(x, absoluteStart);
15942 if (n) return maybeUnwrapSymlink$1(n, opts);
15945 if (core_1[x]) return x;
15946 var err = new Error("Cannot find module '" + x + "' from '" + parent + "'");
15947 err.code = 'MODULE_NOT_FOUND';
15950 function loadAsFileSync(x) {
15951 var pkg = loadpkg(path$2.dirname(x));
15953 if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) {
15954 var rfile = path$2.relative(pkg.dir, x);
15955 var r = opts.pathFilter(pkg.pkg, x, rfile);
15958 x = path$2.resolve(pkg.dir, r); // eslint-disable-line no-param-reassign
15966 for (var i = 0; i < extensions.length; i++) {
15967 var file = x + extensions[i];
15969 if (isFile(file)) {
15975 function loadpkg(dir) {
15976 if (dir === '' || dir === '/') return;
15978 if (process.platform === 'win32' && /^\w:[/\\]*$/.test(dir)) {
15982 if (/[/\\]node_modules[/\\]*$/.test(dir)) return;
15983 var pkgfile = path$2.join(dir, 'package.json');
15985 if (!isFile(pkgfile)) {
15986 return loadpkg(path$2.dirname(dir));
15989 var body = readFileSync(pkgfile);
15992 var pkg = JSON.parse(body);
15993 } catch (jsonErr) {}
15995 if (pkg && opts.packageFilter) {
15996 pkg = opts.packageFilter(pkg, dir);
16005 function loadAsDirectorySync(x) {
16006 var pkgfile = path$2.join(x, '/package.json');
16008 if (isFile(pkgfile)) {
16010 var body = readFileSync(pkgfile, 'UTF8');
16011 var pkg = JSON.parse(body);
16014 if (opts.packageFilter) {
16015 pkg = opts.packageFilter(pkg, x);
16019 if (typeof pkg.main !== 'string') {
16020 var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string');
16021 mainError.code = 'INVALID_PACKAGE_MAIN';
16025 if (pkg.main === '.' || pkg.main === './') {
16026 pkg.main = 'index';
16030 var m = loadAsFileSync(path$2.resolve(x, pkg.main));
16032 var n = loadAsDirectorySync(path$2.resolve(x, pkg.main));
16038 return loadAsFileSync(path$2.join(x, '/index'));
16041 function loadNodeModulesSync(x, start) {
16042 var dirs = nodeModulesPaths(start, opts, x);
16044 for (var i = 0; i < dirs.length; i++) {
16047 if (isDirectory(dir)) {
16048 var m = loadAsFileSync(path$2.join(dir, '/', x));
16050 var n = loadAsDirectorySync(path$2.join(dir, '/', x));
16057 var resolve = createCommonjsModule(function (module, exports) {
16058 async.core = core_1;
16060 async.isCore = function isCore(x) {
16065 module.exports = async;
16068 var mimicFn = function mimicFn(to, from) {
16069 var _iteratorNormalCompletion = true;
16070 var _didIteratorError = false;
16071 var _iteratorError = undefined;
16074 for (var _iterator = Reflect.ownKeys(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
16075 var prop = _step.value;
16076 Object.defineProperty(to, prop, Object.getOwnPropertyDescriptor(from, prop));
16079 _didIteratorError = true;
16080 _iteratorError = err;
16083 if (!_iteratorNormalCompletion && _iterator.return != null) {
16084 _iterator.return();
16087 if (_didIteratorError) {
16088 throw _iteratorError;
16096 var mimicFn_1 = mimicFn; // TODO: Remove this for the next major release
16098 var default_1$4 = mimicFn;
16099 mimicFn_1.default = default_1$4;
16101 var isPromise = function isPromise(input) {
16102 return input instanceof Promise || input !== null && typeof input === 'object' && typeof input.then === 'function' && typeof input.catch === 'function';
16105 var pIsPromise = isPromise; // TODO: Remove this for the next major release
16107 var default_1$5 = isPromise;
16108 pIsPromise.default = default_1$5;
16110 var pDefer = function pDefer() {
16112 ret.promise = new Promise(function (resolve, reject) {
16113 ret.resolve = resolve;
16114 ret.reject = reject;
16119 var dist = createCommonjsModule(function (module, exports) {
16121 var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
16122 return new (P || (P = Promise))(function (resolve, reject) {
16123 function fulfilled(value) {
16125 step(generator.next(value));
16131 function rejected(value) {
16133 step(generator["throw"](value));
16139 function step(result) {
16140 result.done ? resolve(result.value) : new P(function (resolve) {
16141 resolve(result.value);
16142 }).then(fulfilled, rejected);
16145 step((generator = generator.apply(thisArg, _arguments || [])).next());
16149 var __importDefault = this && this.__importDefault || function (mod) {
16150 return mod && mod.__esModule ? mod : {
16155 Object.defineProperty(exports, "__esModule", {
16159 var p_defer_1 = __importDefault(pDefer);
16161 function mapAgeCleaner(map) {
16164 var property = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'maxAge';
16166 var processingTimer;
16167 var processingDeferred;
16169 var cleanup = function cleanup() {
16170 return __awaiter(_this, void 0, void 0,
16172 regeneratorRuntime.mark(function _callee2() {
16175 var setupTimer, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, entry;
16177 return regeneratorRuntime.wrap(function _callee2$(_context2) {
16179 switch (_context2.prev = _context2.next) {
16181 if (!(processingKey !== undefined)) {
16182 _context2.next = 2;
16186 return _context2.abrupt("return");
16189 setupTimer = function setupTimer(item) {
16190 return __awaiter(_this2, void 0, void 0,
16192 regeneratorRuntime.mark(function _callee() {
16194 return regeneratorRuntime.wrap(function _callee$(_context) {
16196 switch (_context.prev = _context.next) {
16198 processingDeferred = p_defer_1.default();
16199 delay = item[1][property] - Date.now();
16201 if (!(delay <= 0)) {
16206 // Remove the item immediately if the delay is equal to or below 0
16207 map.delete(item[0]);
16208 processingDeferred.resolve();
16209 return _context.abrupt("return");
16212 // Keep track of the current processed key
16213 processingKey = item[0];
16214 processingTimer = setTimeout(function () {
16215 // Remove the item when the timeout fires
16216 map.delete(item[0]);
16218 if (processingDeferred) {
16219 processingDeferred.resolve();
16221 }, delay); // tslint:disable-next-line:strict-type-predicates
16223 if (typeof processingTimer.unref === 'function') {
16224 // Don't hold up the process from exiting
16225 processingTimer.unref();
16228 return _context.abrupt("return", processingDeferred.promise);
16232 return _context.stop();
16239 _context2.prev = 3;
16240 _iteratorNormalCompletion = true;
16241 _didIteratorError = false;
16242 _iteratorError = undefined;
16243 _context2.prev = 7;
16244 _iterator = map[Symbol.iterator]();
16247 if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
16248 _context2.next = 16;
16252 entry = _step.value;
16253 _context2.next = 13;
16254 return setupTimer(entry);
16257 _iteratorNormalCompletion = true;
16258 _context2.next = 9;
16262 _context2.next = 22;
16266 _context2.prev = 18;
16267 _context2.t0 = _context2["catch"](7);
16268 _didIteratorError = true;
16269 _iteratorError = _context2.t0;
16272 _context2.prev = 22;
16273 _context2.prev = 23;
16275 if (!_iteratorNormalCompletion && _iterator.return != null) {
16276 _iterator.return();
16280 _context2.prev = 25;
16282 if (!_didIteratorError) {
16283 _context2.next = 28;
16287 throw _iteratorError;
16290 return _context2.finish(25);
16293 return _context2.finish(22);
16296 _context2.next = 34;
16300 _context2.prev = 32;
16301 _context2.t1 = _context2["catch"](3);
16304 processingKey = undefined;
16308 return _context2.stop();
16311 }, _callee2, null, [[3, 32], [7, 18, 22, 30], [23,, 25, 29]]);
16315 var reset = function reset() {
16316 processingKey = undefined;
16318 if (processingTimer !== undefined) {
16319 clearTimeout(processingTimer);
16320 processingTimer = undefined;
16323 if (processingDeferred !== undefined) {
16324 // tslint:disable-line:early-exit
16325 processingDeferred.reject(undefined);
16326 processingDeferred = undefined;
16330 var originalSet = map.set.bind(map);
16332 map.set = function (key, value) {
16333 if (map.has(key)) {
16334 // If the key already exist, remove it so we can add it back at the end of the map.
16336 } // Call the original `map.set`
16339 var result = originalSet(key, value); // If we are already processing a key and the key added is the current processed key, stop processing it
16341 if (processingKey && processingKey === key) {
16343 } // Always run the cleanup method in case it wasn't started yet
16346 cleanup(); // tslint:disable-line:no-floating-promises
16351 cleanup(); // tslint:disable-line:no-floating-promises
16356 exports.default = mapAgeCleaner; // Add support for CJS
16358 module.exports = mapAgeCleaner;
16359 module.exports.default = mapAgeCleaner;
16361 unwrapExports(dist);
16363 var cacheStore = new WeakMap();
16365 var defaultCacheKey = function defaultCacheKey() {
16366 for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) {
16367 arguments_[_key] = arguments[_key];
16370 if (arguments_.length === 0) {
16371 return '__defaultKey';
16374 if (arguments_.length === 1) {
16375 var firstArgument = arguments_[0];
16376 var isObject = typeof firstArgument === 'object' && firstArgument !== null;
16377 var isPrimitive = !isObject;
16380 return firstArgument;
16384 return JSON.stringify(arguments_);
16387 var mem = function mem(fn) {
16388 var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
16389 _ref$cacheKey = _ref.cacheKey,
16390 cacheKey = _ref$cacheKey === void 0 ? defaultCacheKey : _ref$cacheKey,
16391 _ref$cache = _ref.cache,
16392 cache = _ref$cache === void 0 ? new Map() : _ref$cache,
16393 _ref$cachePromiseReje = _ref.cachePromiseRejection,
16394 cachePromiseRejection = _ref$cachePromiseReje === void 0 ? true : _ref$cachePromiseReje,
16395 maxAge = _ref.maxAge;
16397 if (typeof maxAge === 'number') {
16401 var memoized = function memoized() {
16402 for (var _len2 = arguments.length, arguments_ = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
16403 arguments_[_key2] = arguments[_key2];
16406 var key = cacheKey.apply(void 0, arguments_);
16408 if (cache.has(key)) {
16409 return cache.get(key).data;
16412 var cacheItem = fn.apply(this, arguments_);
16415 maxAge: maxAge ? Date.now() + maxAge : Infinity
16418 if (pIsPromise(cacheItem) && cachePromiseRejection === false) {
16419 cacheItem.catch(function () {
16420 return cache.delete(key);
16428 // The below call will throw in some host environments
16429 // See https://github.com/sindresorhus/mimic-fn/issues/10
16430 mimicFn_1(memoized, fn);
16433 cacheStore.set(memoized, cache);
16439 var clear = function clear(fn) {
16440 var cache = cacheStore.get(fn);
16442 if (cache && typeof cache.clear === 'function') {
16446 mem_1.clear = clear;
16448 var semver$1 = createCommonjsModule(function (module, exports) {
16449 exports = module.exports = SemVer; // The debug function is excluded entirely from the minified version.
16456 if (typeof process === 'object' &&
16460 process.env.NODE_DEBUG &&
16462 /\bsemver\b/i.test(process.env.NODE_DEBUG))
16464 debug = function debug() {
16466 var args = Array.prototype.slice.call(arguments, 0);
16469 args.unshift('SEMVER');
16472 console.log.apply(console, args);
16478 debug = function debug() {}; // Note: this is the semver.org version of the spec that it implements
16479 // Not necessarily the package version of this code.
16481 exports.SEMVER_SPEC_VERSION = '2.0.0';
16482 var MAX_LENGTH = 256;
16483 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // Max safe segment length for coercion.
16485 var MAX_SAFE_COMPONENT_LENGTH = 16; // The actual regexps go on exports.re
16487 var re = exports.re = [];
16488 var src = exports.src = [];
16489 var R = 0; // The following Regular Expressions can be used for tokenizing,
16490 // validating, and parsing SemVer version strings.
16491 // ## Numeric Identifier
16492 // A single `0`, or a non-zero digit followed by zero or more digits.
16494 var NUMERICIDENTIFIER = R++;
16495 src[NUMERICIDENTIFIER] = '0|[1-9]\\d*';
16496 var NUMERICIDENTIFIERLOOSE = R++;
16497 src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier
16498 // Zero or more digits, followed by a letter or hyphen, and then zero or
16499 // more letters, digits, or hyphens.
16501 var NONNUMERICIDENTIFIER = R++;
16502 src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version
16503 // Three dot-separated numeric identifiers.
16505 var MAINVERSION = R++;
16506 src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')';
16507 var MAINVERSIONLOOSE = R++;
16508 src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier
16509 // A numeric identifier, or a non-numeric identifier.
16511 var PRERELEASEIDENTIFIER = R++;
16512 src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')';
16513 var PRERELEASEIDENTIFIERLOOSE = R++;
16514 src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version
16515 // Hyphen, followed by one or more dot-separated pre-release version
16518 var PRERELEASE = R++;
16519 src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))';
16520 var PRERELEASELOOSE = R++;
16521 src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier
16522 // Any combination of digits, letters, or hyphens.
16524 var BUILDIDENTIFIER = R++;
16525 src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata
16526 // Plus sign, followed by one or more period-separated build metadata
16530 src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; // ## Full Version String
16531 // A main version, followed optionally by a pre-release version and
16533 // Note that the only major, minor, patch, and pre-release sections of
16534 // the version string are capturing groups. The build metadata is not a
16535 // capturing group, because it should not ever be used in version
16539 var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?';
16540 src[FULL] = '^' + FULLPLAIN + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
16541 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
16542 // common in the npm registry.
16544 var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?';
16546 src[LOOSE] = '^' + LOOSEPLAIN + '$';
16548 src[GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x".
16549 // Note that "x.x" is a valid xRange identifer, meaning "any version"
16550 // Only the first item is strictly required.
16552 var XRANGEIDENTIFIERLOOSE = R++;
16553 src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*';
16554 var XRANGEIDENTIFIER = R++;
16555 src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*';
16556 var XRANGEPLAIN = R++;
16557 src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?';
16558 var XRANGEPLAINLOOSE = R++;
16559 src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?';
16561 src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$';
16562 var XRANGELOOSE = R++;
16563 src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; // Coercion.
16564 // Extract anything that could conceivably be a part of a valid semver
16567 src[COERCE] = '(?:^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])'; // Tilde ranges.
16568 // Meaning is "reasonably at or greater than"
16570 var LONETILDE = R++;
16571 src[LONETILDE] = '(?:~>?)';
16572 var TILDETRIM = R++;
16573 src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+';
16574 re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g');
16575 var tildeTrimReplace = '$1~';
16577 src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$';
16578 var TILDELOOSE = R++;
16579 src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; // Caret ranges.
16580 // Meaning is "at least and backwards compatible with"
16582 var LONECARET = R++;
16583 src[LONECARET] = '(?:\\^)';
16584 var CARETTRIM = R++;
16585 src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+';
16586 re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g');
16587 var caretTrimReplace = '$1^';
16589 src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$';
16590 var CARETLOOSE = R++;
16591 src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version"
16593 var COMPARATORLOOSE = R++;
16594 src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$';
16595 var COMPARATOR = R++;
16596 src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing
16597 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
16599 var COMPARATORTRIM = R++;
16600 src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; // this one has to use the /g flag
16602 re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g');
16603 var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
16604 // Note that these all use the loose form, because they'll be
16605 // checked against either the strict or loose comparator form
16608 var HYPHENRANGE = R++;
16609 src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$';
16610 var HYPHENRANGELOOSE = R++;
16611 src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all.
16614 src[STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects.
16615 // All are flag-free, unless they were created above with a flag.
16617 for (var i = 0; i < R; i++) {
16619 if (!re[i]) re[i] = new RegExp(src[i]);
16622 exports.parse = parse;
16624 function parse(version, options) {
16625 if (!options || typeof options !== 'object') options = {
16627 includePrerelease: false
16629 if (version instanceof SemVer) return version;
16630 if (typeof version !== 'string') return null;
16631 if (version.length > MAX_LENGTH) return null;
16632 var r = options.loose ? re[LOOSE] : re[FULL];
16633 if (!r.test(version)) return null;
16636 return new SemVer(version, options);
16642 exports.valid = valid;
16644 function valid(version, options) {
16645 var v = parse(version, options);
16646 return v ? v.version : null;
16649 exports.clean = clean;
16651 function clean(version, options) {
16652 var s = parse(version.trim().replace(/^[=v]+/, ''), options);
16653 return s ? s.version : null;
16656 exports.SemVer = SemVer;
16658 function SemVer(version, options) {
16659 if (!options || typeof options !== 'object') options = {
16661 includePrerelease: false
16664 if (version instanceof SemVer) {
16665 if (version.loose === options.loose) return version;else version = version.version;
16666 } else if (typeof version !== 'string') {
16667 throw new TypeError('Invalid Version: ' + version);
16670 if (version.length > MAX_LENGTH) throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters');
16671 if (!(this instanceof SemVer)) return new SemVer(version, options);
16672 debug('SemVer', version, options);
16673 this.options = options;
16674 this.loose = !!options.loose;
16675 var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]);
16676 if (!m) throw new TypeError('Invalid Version: ' + version);
16677 this.raw = version; // these are actually numbers
16679 this.major = +m[1];
16680 this.minor = +m[2];
16681 this.patch = +m[3];
16682 if (this.major > MAX_SAFE_INTEGER || this.major < 0) throw new TypeError('Invalid major version');
16683 if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) throw new TypeError('Invalid minor version');
16684 if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) throw new TypeError('Invalid patch version'); // numberify any prerelease numeric ids
16686 if (!m[4]) this.prerelease = [];else this.prerelease = m[4].split('.').map(function (id) {
16687 if (/^[0-9]+$/.test(id)) {
16689 if (num >= 0 && num < MAX_SAFE_INTEGER) return num;
16694 this.build = m[5] ? m[5].split('.') : [];
16698 SemVer.prototype.format = function () {
16699 this.version = this.major + '.' + this.minor + '.' + this.patch;
16700 if (this.prerelease.length) this.version += '-' + this.prerelease.join('.');
16701 return this.version;
16704 SemVer.prototype.toString = function () {
16705 return this.version;
16708 SemVer.prototype.compare = function (other) {
16709 debug('SemVer.compare', this.version, this.options, other);
16710 if (!(other instanceof SemVer)) other = new SemVer(other, this.options);
16711 return this.compareMain(other) || this.comparePre(other);
16714 SemVer.prototype.compareMain = function (other) {
16715 if (!(other instanceof SemVer)) other = new SemVer(other, this.options);
16716 return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
16719 SemVer.prototype.comparePre = function (other) {
16720 if (!(other instanceof SemVer)) other = new SemVer(other, this.options); // NOT having a prerelease is > having one
16722 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;
16726 var a = this.prerelease[i];
16727 var b = other.prerelease[i];
16728 debug('prerelease compare', i, a, b);
16729 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);
16731 }; // preminor will bump the version up to the next minor release, and immediately
16732 // down to pre-release. premajor and prepatch work the same way.
16735 SemVer.prototype.inc = function (release, identifier) {
16738 this.prerelease.length = 0;
16742 this.inc('pre', identifier);
16746 this.prerelease.length = 0;
16749 this.inc('pre', identifier);
16753 // If this is already a prerelease, it will bump to the next version
16754 // drop any prereleases that might already exist, since they are not
16755 // relevant at this point.
16756 this.prerelease.length = 0;
16757 this.inc('patch', identifier);
16758 this.inc('pre', identifier);
16760 // If the input is a non-prerelease version, this acts the same as
16764 if (this.prerelease.length === 0) this.inc('patch', identifier);
16765 this.inc('pre', identifier);
16769 // If this is a pre-major version, bump up to the same major version.
16770 // Otherwise increment major.
16771 // 1.0.0-5 bumps to 1.0.0
16772 // 1.1.0 bumps to 2.0.0
16773 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) this.major++;
16776 this.prerelease = [];
16780 // If this is a pre-minor version, bump up to the same minor version.
16781 // Otherwise increment minor.
16782 // 1.2.0-5 bumps to 1.2.0
16783 // 1.2.1 bumps to 1.3.0
16784 if (this.patch !== 0 || this.prerelease.length === 0) this.minor++;
16786 this.prerelease = [];
16790 // If this is not a pre-release version, it will increment the patch.
16791 // If it is a pre-release it will bump up to the same patch version.
16792 // 1.2.0-5 patches to 1.2.0
16793 // 1.2.0 patches to 1.2.1
16794 if (this.prerelease.length === 0) this.patch++;
16795 this.prerelease = [];
16797 // This probably shouldn't be used publicly.
16798 // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction.
16801 if (this.prerelease.length === 0) this.prerelease = [0];else {
16802 var i = this.prerelease.length;
16805 if (typeof this.prerelease[i] === 'number') {
16806 this.prerelease[i]++;
16811 if (i === -1) // didn't increment anything
16812 this.prerelease.push(0);
16816 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
16817 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
16818 if (this.prerelease[0] === identifier) {
16819 if (isNaN(this.prerelease[1])) this.prerelease = [identifier, 0];
16820 } else this.prerelease = [identifier, 0];
16826 throw new Error('invalid increment argument: ' + release);
16830 this.raw = this.version;
16836 function inc(version, release, loose, identifier) {
16837 if (typeof loose === 'string') {
16838 identifier = loose;
16843 return new SemVer(version, loose).inc(release, identifier).version;
16849 exports.diff = diff;
16851 function diff(version1, version2) {
16852 if (eq(version1, version2)) {
16855 var v1 = parse(version1);
16856 var v2 = parse(version2);
16858 if (v1.prerelease.length || v2.prerelease.length) {
16859 for (var key in v1) {
16860 if (key === 'major' || key === 'minor' || key === 'patch') {
16861 if (v1[key] !== v2[key]) {
16862 return 'pre' + key;
16867 return 'prerelease';
16870 for (var key in v1) {
16871 if (key === 'major' || key === 'minor' || key === 'patch') {
16872 if (v1[key] !== v2[key]) {
16880 exports.compareIdentifiers = compareIdentifiers;
16881 var numeric = /^[0-9]+$/;
16883 function compareIdentifiers(a, b) {
16884 var anum = numeric.test(a);
16885 var bnum = numeric.test(b);
16887 if (anum && bnum) {
16892 return anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : a > b ? 1 : 0;
16895 exports.rcompareIdentifiers = rcompareIdentifiers;
16897 function rcompareIdentifiers(a, b) {
16898 return compareIdentifiers(b, a);
16901 exports.major = major;
16903 function major(a, loose) {
16904 return new SemVer(a, loose).major;
16907 exports.minor = minor;
16909 function minor(a, loose) {
16910 return new SemVer(a, loose).minor;
16913 exports.patch = patch;
16915 function patch(a, loose) {
16916 return new SemVer(a, loose).patch;
16919 exports.compare = compare;
16921 function compare(a, b, loose) {
16922 return new SemVer(a, loose).compare(new SemVer(b, loose));
16925 exports.compareLoose = compareLoose;
16927 function compareLoose(a, b) {
16928 return compare(a, b, true);
16931 exports.rcompare = rcompare;
16933 function rcompare(a, b, loose) {
16934 return compare(b, a, loose);
16937 exports.sort = sort;
16939 function sort(list, loose) {
16940 return list.sort(function (a, b) {
16941 return exports.compare(a, b, loose);
16945 exports.rsort = rsort;
16947 function rsort(list, loose) {
16948 return list.sort(function (a, b) {
16949 return exports.rcompare(a, b, loose);
16955 function gt(a, b, loose) {
16956 return compare(a, b, loose) > 0;
16961 function lt(a, b, loose) {
16962 return compare(a, b, loose) < 0;
16967 function eq(a, b, loose) {
16968 return compare(a, b, loose) === 0;
16973 function neq(a, b, loose) {
16974 return compare(a, b, loose) !== 0;
16979 function gte(a, b, loose) {
16980 return compare(a, b, loose) >= 0;
16985 function lte(a, b, loose) {
16986 return compare(a, b, loose) <= 0;
16991 function cmp(a, op, b, loose) {
16996 if (typeof a === 'object') a = a.version;
16997 if (typeof b === 'object') b = b.version;
17002 if (typeof a === 'object') a = a.version;
17003 if (typeof b === 'object') b = b.version;
17010 ret = eq(a, b, loose);
17014 ret = neq(a, b, loose);
17018 ret = gt(a, b, loose);
17022 ret = gte(a, b, loose);
17026 ret = lt(a, b, loose);
17030 ret = lte(a, b, loose);
17034 throw new TypeError('Invalid operator: ' + op);
17040 exports.Comparator = Comparator;
17042 function Comparator(comp, options) {
17043 if (!options || typeof options !== 'object') options = {
17045 includePrerelease: false
17048 if (comp instanceof Comparator) {
17049 if (comp.loose === !!options.loose) return comp;else comp = comp.value;
17052 if (!(this instanceof Comparator)) return new Comparator(comp, options);
17053 debug('comparator', comp, options);
17054 this.options = options;
17055 this.loose = !!options.loose;
17057 if (this.semver === ANY) this.value = '';else this.value = this.operator + this.semver.version;
17058 debug('comp', this);
17063 Comparator.prototype.parse = function (comp) {
17064 var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
17065 var m = comp.match(r);
17066 if (!m) throw new TypeError('Invalid comparator: ' + comp);
17067 this.operator = m[1];
17068 if (this.operator === '=') this.operator = ''; // if it literally is just '>' or '' then allow anything.
17070 if (!m[2]) this.semver = ANY;else this.semver = new SemVer(m[2], this.options.loose);
17073 Comparator.prototype.toString = function () {
17077 Comparator.prototype.test = function (version) {
17078 debug('Comparator.test', version, this.options.loose);
17079 if (this.semver === ANY) return true;
17080 if (typeof version === 'string') version = new SemVer(version, this.options);
17081 return cmp(version, this.operator, this.semver, this.options);
17084 Comparator.prototype.intersects = function (comp, options) {
17085 if (!(comp instanceof Comparator)) {
17086 throw new TypeError('a Comparator is required');
17089 if (!options || typeof options !== 'object') options = {
17091 includePrerelease: false
17095 if (this.operator === '') {
17096 rangeTmp = new Range(comp.value, options);
17097 return satisfies(this.value, rangeTmp, options);
17098 } else if (comp.operator === '') {
17099 rangeTmp = new Range(this.value, options);
17100 return satisfies(comp.semver, rangeTmp, options);
17103 var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>');
17104 var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<');
17105 var sameSemVer = this.semver.version === comp.semver.version;
17106 var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=');
17107 var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<');
17108 var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>');
17109 return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
17112 exports.Range = Range;
17114 function Range(range, options) {
17115 if (!options || typeof options !== 'object') options = {
17117 includePrerelease: false
17120 if (range instanceof Range) {
17121 if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
17124 return new Range(range.raw, options);
17128 if (range instanceof Comparator) {
17129 return new Range(range.value, options);
17132 if (!(this instanceof Range)) return new Range(range, options);
17133 this.options = options;
17134 this.loose = !!options.loose;
17135 this.includePrerelease = !!options.includePrerelease; // First, split based on boolean or ||
17138 this.set = range.split(/\s*\|\|\s*/).map(function (range) {
17139 return this.parseRange(range.trim());
17140 }, this).filter(function (c) {
17141 // throw out any that are not relevant for whatever reason
17145 if (!this.set.length) {
17146 throw new TypeError('Invalid SemVer Range: ' + range);
17152 Range.prototype.format = function () {
17153 this.range = this.set.map(function (comps) {
17154 return comps.join(' ').trim();
17155 }).join('||').trim();
17159 Range.prototype.toString = function () {
17163 Range.prototype.parseRange = function (range) {
17164 var loose = this.options.loose;
17165 range = range.trim(); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
17167 var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE];
17168 range = range.replace(hr, hyphenReplace);
17169 debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
17171 range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace);
17172 debug('comparator trim', range, re[COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3`
17174 range = range.replace(re[TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3`
17176 range = range.replace(re[CARETTRIM], caretTrimReplace); // normalize spaces
17178 range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and
17179 // ready to be split into comparators.
17181 var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR];
17182 var set = range.split(' ').map(function (comp) {
17183 return parseComparator(comp, this.options);
17184 }, this).join(' ').split(/\s+/);
17186 if (this.options.loose) {
17187 // in loose mode, throw out any that are not valid comparators
17188 set = set.filter(function (comp) {
17189 return !!comp.match(compRe);
17193 set = set.map(function (comp) {
17194 return new Comparator(comp, this.options);
17199 Range.prototype.intersects = function (range, options) {
17200 if (!(range instanceof Range)) {
17201 throw new TypeError('a Range is required');
17204 return this.set.some(function (thisComparators) {
17205 return thisComparators.every(function (thisComparator) {
17206 return range.set.some(function (rangeComparators) {
17207 return rangeComparators.every(function (rangeComparator) {
17208 return thisComparator.intersects(rangeComparator, options);
17213 }; // Mostly just for testing and legacy API reasons
17216 exports.toComparators = toComparators;
17218 function toComparators(range, options) {
17219 return new Range(range, options).set.map(function (comp) {
17220 return comp.map(function (c) {
17222 }).join(' ').trim().split(' ');
17224 } // comprised of xranges, tildes, stars, and gtlt's at this point.
17225 // already replaced the hyphen ranges
17226 // turn into a set of JUST comparators.
17229 function parseComparator(comp, options) {
17230 debug('comp', comp, options);
17231 comp = replaceCarets(comp, options);
17232 debug('caret', comp);
17233 comp = replaceTildes(comp, options);
17234 debug('tildes', comp);
17235 comp = replaceXRanges(comp, options);
17236 debug('xrange', comp);
17237 comp = replaceStars(comp, options);
17238 debug('stars', comp);
17243 return !id || id.toLowerCase() === 'x' || id === '*';
17244 } // ~, ~> --> * (any, kinda silly)
17245 // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0
17246 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0
17247 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0
17248 // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0
17249 // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0
17252 function replaceTildes(comp, options) {
17253 return comp.trim().split(/\s+/).map(function (comp) {
17254 return replaceTilde(comp, options);
17258 function replaceTilde(comp, options) {
17259 if (!options || typeof options !== 'object') options = {
17261 includePrerelease: false
17263 var r = options.loose ? re[TILDELOOSE] : re[TILDE];
17264 return comp.replace(r, function (_, M, m, p, pr) {
17265 debug('tilde', comp, _, M, m, p, pr);
17267 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
17268 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';else if (pr) {
17269 debug('replaceTilde pr', pr);
17270 if (pr.charAt(0) !== '-') pr = '-' + pr;
17271 ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0';
17272 } else // ~1.2.3 == >=1.2.3 <1.3.0
17273 ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
17274 debug('tilde return', ret);
17277 } // ^ --> * (any, kinda silly)
17278 // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0
17279 // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0
17280 // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0
17281 // ^1.2.3 --> >=1.2.3 <2.0.0
17282 // ^1.2.0 --> >=1.2.0 <2.0.0
17285 function replaceCarets(comp, options) {
17286 return comp.trim().split(/\s+/).map(function (comp) {
17287 return replaceCaret(comp, options);
17291 function replaceCaret(comp, options) {
17292 debug('caret', comp, options);
17293 if (!options || typeof options !== 'object') options = {
17295 includePrerelease: false
17297 var r = options.loose ? re[CARETLOOSE] : re[CARET];
17298 return comp.replace(r, function (_, M, m, p, pr) {
17299 debug('caret', comp, _, M, m, p, pr);
17301 if (isX(M)) ret = '';else if (isX(m)) ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';else if (isX(p)) {
17302 if (M === '0') ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';else ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0';
17304 debug('replaceCaret pr', pr);
17305 if (pr.charAt(0) !== '-') pr = '-' + pr;
17308 if (m === '0') ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + m + '.' + (+p + 1);else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + M + '.' + (+m + 1) + '.0';
17309 } else ret = '>=' + M + '.' + m + '.' + p + pr + ' <' + (+M + 1) + '.0.0';
17314 if (m === '0') ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1);else ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0';
17315 } else ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0';
17317 debug('caret return', ret);
17322 function replaceXRanges(comp, options) {
17323 debug('replaceXRanges', comp, options);
17324 return comp.split(/\s+/).map(function (comp) {
17325 return replaceXRange(comp, options);
17329 function replaceXRange(comp, options) {
17330 comp = comp.trim();
17331 if (!options || typeof options !== 'object') options = {
17333 includePrerelease: false
17335 var r = options.loose ? re[XRANGELOOSE] : re[XRANGE];
17336 return comp.replace(r, function (ret, gtlt, M, m, p, pr) {
17337 debug('xRange', comp, ret, gtlt, M, m, p, pr);
17339 var xm = xM || isX(m);
17340 var xp = xm || isX(p);
17342 if (gtlt === '=' && anyX) gtlt = '';
17345 if (gtlt === '>' || gtlt === '<') {
17346 // nothing is allowed
17349 // nothing is forbidden
17352 } else if (gtlt && anyX) {
17353 // replace X with 0
17357 if (gtlt === '>') {
17360 // >1.2.3 => >= 1.2.4
17371 } else if (gtlt === '<=') {
17372 // <=0.7.x is actually <0.8.0, since any 0.7.x should
17373 // pass. Similarly, <=7.x is actually <8.0.0, etc.
17375 if (xm) M = +M + 1;else m = +m + 1;
17378 ret = gtlt + M + '.' + m + '.' + p;
17380 ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0';
17382 ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0';
17385 debug('xRange return', ret);
17388 } // Because * is AND-ed with everything else in the comparator,
17389 // and '' means "any version", just remove the *s entirely.
17392 function replaceStars(comp, options) {
17393 debug('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets!
17395 return comp.trim().replace(re[STAR], '');
17396 } // This function is passed to string.replace(re[HYPHENRANGE])
17397 // M, m, patch, prerelease, build
17398 // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
17399 // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do
17400 // 1.2 - 3.4 => >=1.2.0 <3.5.0
17403 function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) {
17404 if (isX(fM)) from = '';else if (isX(fm)) from = '>=' + fM + '.0.0';else if (isX(fp)) from = '>=' + fM + '.' + fm + '.0';else from = '>=' + from;
17405 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;
17406 return (from + ' ' + to).trim();
17407 } // if ANY of the sets match ALL of its comparators, then pass
17410 Range.prototype.test = function (version) {
17411 if (!version) return false;
17412 if (typeof version === 'string') version = new SemVer(version, this.options);
17414 for (var i = 0; i < this.set.length; i++) {
17415 if (testSet(this.set[i], version, this.options)) return true;
17421 function testSet(set, version, options) {
17422 for (var i = 0; i < set.length; i++) {
17423 if (!set[i].test(version)) return false;
17426 if (!options) options = {};
17428 if (version.prerelease.length && !options.includePrerelease) {
17429 // Find the set of versions that are allowed to have prereleases
17430 // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
17431 // That should allow `1.2.3-pr.2` to pass.
17432 // However, `1.2.4-alpha.notready` should NOT be allowed,
17433 // even though it's within the range set by the comparators.
17434 for (var i = 0; i < set.length; i++) {
17435 debug(set[i].semver);
17436 if (set[i].semver === ANY) continue;
17438 if (set[i].semver.prerelease.length > 0) {
17439 var allowed = set[i].semver;
17440 if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) return true;
17442 } // Version has a -pre, but it's not one of the ones we like.
17451 exports.satisfies = satisfies;
17453 function satisfies(version, range, options) {
17455 range = new Range(range, options);
17460 return range.test(version);
17463 exports.maxSatisfying = maxSatisfying;
17465 function maxSatisfying(versions, range, options) {
17470 var rangeObj = new Range(range, options);
17475 versions.forEach(function (v) {
17476 if (rangeObj.test(v)) {
17477 // satisfies(v, range, options)
17478 if (!max || maxSV.compare(v) === -1) {
17479 // compare(max, v, true)
17481 maxSV = new SemVer(max, options);
17488 exports.minSatisfying = minSatisfying;
17490 function minSatisfying(versions, range, options) {
17495 var rangeObj = new Range(range, options);
17500 versions.forEach(function (v) {
17501 if (rangeObj.test(v)) {
17502 // satisfies(v, range, options)
17503 if (!min || minSV.compare(v) === 1) {
17504 // compare(min, v, true)
17506 minSV = new SemVer(min, options);
17513 exports.validRange = validRange;
17515 function validRange(range, options) {
17517 // Return '*' instead of '' so that truthiness works.
17518 // This will throw if it's invalid anyway
17519 return new Range(range, options).range || '*';
17523 } // Determine if version is less than all the versions possible in the range
17528 function ltr(version, range, options) {
17529 return outside(version, range, '<', options);
17530 } // Determine if version is greater than all the versions possible in the range.
17535 function gtr(version, range, options) {
17536 return outside(version, range, '>', options);
17539 exports.outside = outside;
17541 function outside(version, range, hilo, options) {
17542 version = new SemVer(version, options);
17543 range = new Range(range, options);
17544 var gtfn, ltefn, ltfn, comp, ecomp;
17564 throw new TypeError('Must provide a hilo val of "<" or ">"');
17565 } // If it satisifes the range it is not outside
17568 if (satisfies(version, range, options)) {
17570 } // From now on, variable terms are as if we're in "gtr" mode.
17571 // but note that everything is flipped for the "ltr" function.
17574 for (var i = 0; i < range.set.length; ++i) {
17575 var comparators = range.set[i];
17578 comparators.forEach(function (comparator) {
17579 if (comparator.semver === ANY) {
17580 comparator = new Comparator('>=0.0.0');
17583 high = high || comparator;
17584 low = low || comparator;
17586 if (gtfn(comparator.semver, high.semver, options)) {
17588 } else if (ltfn(comparator.semver, low.semver, options)) {
17591 }); // If the edge version comparator has a operator then our version
17592 // isn't outside it
17594 if (high.operator === comp || high.operator === ecomp) {
17596 } // If the lowest version comparator has an operator and our version
17597 // is less than it then it isn't higher than the range
17600 if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
17602 } else if (low.operator === ecomp && ltfn(version, low.semver)) {
17610 exports.prerelease = prerelease;
17612 function prerelease(version, options) {
17613 var parsed = parse(version, options);
17614 return parsed && parsed.prerelease.length ? parsed.prerelease : null;
17617 exports.intersects = intersects;
17619 function intersects(r1, r2, options) {
17620 r1 = new Range(r1, options);
17621 r2 = new Range(r2, options);
17622 return r1.intersects(r2);
17625 exports.coerce = coerce;
17627 function coerce(version) {
17628 if (version instanceof SemVer) return version;
17629 if (typeof version !== 'string') return null;
17630 var match = version.match(re[COERCE]);
17631 if (match == null) return null;
17632 return parse((match[1] || '0') + '.' + (match[2] || '0') + '.' + (match[3] || '0'));
17635 var semver_1$1 = semver$1.SEMVER_SPEC_VERSION;
17636 var semver_2$1 = semver$1.re;
17637 var semver_3$1 = semver$1.src;
17638 var semver_4$1 = semver$1.parse;
17639 var semver_5$1 = semver$1.valid;
17640 var semver_6$1 = semver$1.clean;
17641 var semver_7$1 = semver$1.SemVer;
17642 var semver_8$1 = semver$1.inc;
17643 var semver_9$1 = semver$1.diff;
17644 var semver_10$1 = semver$1.compareIdentifiers;
17645 var semver_11$1 = semver$1.rcompareIdentifiers;
17646 var semver_12$1 = semver$1.major;
17647 var semver_13$1 = semver$1.minor;
17648 var semver_14$1 = semver$1.patch;
17649 var semver_15$1 = semver$1.compare;
17650 var semver_16$1 = semver$1.compareLoose;
17651 var semver_17$1 = semver$1.rcompare;
17652 var semver_18$1 = semver$1.sort;
17653 var semver_19$1 = semver$1.rsort;
17654 var semver_20$1 = semver$1.gt;
17655 var semver_21$1 = semver$1.lt;
17656 var semver_22$1 = semver$1.eq;
17657 var semver_23$1 = semver$1.neq;
17658 var semver_24$1 = semver$1.gte;
17659 var semver_25$1 = semver$1.lte;
17660 var semver_26$1 = semver$1.cmp;
17661 var semver_27$1 = semver$1.Comparator;
17662 var semver_28$1 = semver$1.Range;
17663 var semver_29$1 = semver$1.toComparators;
17664 var semver_30$1 = semver$1.satisfies;
17665 var semver_31$1 = semver$1.maxSatisfying;
17666 var semver_32$1 = semver$1.minSatisfying;
17667 var semver_33$1 = semver$1.validRange;
17668 var semver_34$1 = semver$1.ltr;
17669 var semver_35$1 = semver$1.gtr;
17670 var semver_36$1 = semver$1.outside;
17671 var semver_37$1 = semver$1.prerelease;
17672 var semver_38$1 = semver$1.intersects;
17673 var semver_39$1 = semver$1.coerce;
17675 var hasOwnProperty = Object.prototype.hasOwnProperty;
17676 var pseudomap = PseudoMap;
17678 function PseudoMap(set) {
17679 if (!(this instanceof PseudoMap)) // whyyyyyyy
17680 throw new TypeError("Constructor PseudoMap requires 'new'");
17684 if (set instanceof PseudoMap || typeof Map === 'function' && set instanceof Map) set.forEach(function (value, key) {
17685 this.set(key, value);
17686 }, this);else if (Array.isArray(set)) set.forEach(function (kv) {
17687 this.set(kv[0], kv[1]);
17688 }, this);else throw new TypeError('invalid argument');
17692 PseudoMap.prototype.forEach = function (fn, thisp) {
17693 thisp = thisp || this;
17694 Object.keys(this._data).forEach(function (k) {
17695 if (k !== 'size') fn.call(thisp, this._data[k].value, this._data[k].key);
17699 PseudoMap.prototype.has = function (k) {
17700 return !!find(this._data, k);
17703 PseudoMap.prototype.get = function (k) {
17704 var res = find(this._data, k);
17705 return res && res.value;
17708 PseudoMap.prototype.set = function (k, v) {
17709 set(this._data, k, v);
17712 PseudoMap.prototype.delete = function (k) {
17713 var res = find(this._data, k);
17716 delete this._data[res._index];
17721 PseudoMap.prototype.clear = function () {
17722 var data = Object.create(null);
17724 Object.defineProperty(this, '_data', {
17727 configurable: true,
17732 Object.defineProperty(PseudoMap.prototype, 'size', {
17733 get: function get() {
17734 return this._data.size;
17736 set: function set(n) {},
17741 PseudoMap.prototype.values = PseudoMap.prototype.keys = PseudoMap.prototype.entries = function () {
17742 throw new Error('iterators are not implemented in this version');
17743 }; // Either identical, or both NaN
17746 function same(a, b) {
17747 return a === b || a !== a && b !== b;
17750 function Entry(k, v, i) {
17756 function find(data, k) {
17757 for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) {
17758 if (same(data[key].key, k)) return data[key];
17762 function set(data, k, v) {
17763 for (var i = 0, s = '_' + k, key = s; hasOwnProperty.call(data, key); key = s + i++) {
17764 if (same(data[key].key, k)) {
17765 data[key].value = v;
17771 data[key] = new Entry(k, v, key);
17774 var map = createCommonjsModule(function (module) {
17775 if (process.env.npm_package_name === 'pseudomap' && process.env.npm_lifecycle_script === 'test') process.env.TEST_PSEUDOMAP = 'true';
17777 if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) {
17778 module.exports = Map;
17780 module.exports = pseudomap;
17784 var yallist = Yallist;
17785 Yallist.Node = Node;
17786 Yallist.create = Yallist;
17788 function Yallist(list) {
17791 if (!(self instanceof Yallist)) {
17792 self = new Yallist();
17799 if (list && typeof list.forEach === 'function') {
17800 list.forEach(function (item) {
17803 } else if (arguments.length > 0) {
17804 for (var i = 0, l = arguments.length; i < l; i++) {
17805 self.push(arguments[i]);
17812 Yallist.prototype.removeNode = function (node) {
17813 if (node.list !== this) {
17814 throw new Error('removing node which does not belong to this list');
17817 var next = node.next;
17818 var prev = node.prev;
17828 if (node === this.head) {
17832 if (node === this.tail) {
17836 node.list.length--;
17842 Yallist.prototype.unshiftNode = function (node) {
17843 if (node === this.head) {
17848 node.list.removeNode(node);
17851 var head = this.head;
17868 Yallist.prototype.pushNode = function (node) {
17869 if (node === this.tail) {
17874 node.list.removeNode(node);
17877 var tail = this.tail;
17894 Yallist.prototype.push = function () {
17895 for (var i = 0, l = arguments.length; i < l; i++) {
17896 push(this, arguments[i]);
17899 return this.length;
17902 Yallist.prototype.unshift = function () {
17903 for (var i = 0, l = arguments.length; i < l; i++) {
17904 unshift(this, arguments[i]);
17907 return this.length;
17910 Yallist.prototype.pop = function () {
17915 var res = this.tail.value;
17916 this.tail = this.tail.prev;
17919 this.tail.next = null;
17928 Yallist.prototype.shift = function () {
17933 var res = this.head.value;
17934 this.head = this.head.next;
17937 this.head.prev = null;
17946 Yallist.prototype.forEach = function (fn, thisp) {
17947 thisp = thisp || this;
17949 for (var walker = this.head, i = 0; walker !== null; i++) {
17950 fn.call(thisp, walker.value, i, this);
17951 walker = walker.next;
17955 Yallist.prototype.forEachReverse = function (fn, thisp) {
17956 thisp = thisp || this;
17958 for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
17959 fn.call(thisp, walker.value, i, this);
17960 walker = walker.prev;
17964 Yallist.prototype.get = function (n) {
17965 for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
17966 // abort out of the list early if we hit a cycle
17967 walker = walker.next;
17970 if (i === n && walker !== null) {
17971 return walker.value;
17975 Yallist.prototype.getReverse = function (n) {
17976 for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
17977 // abort out of the list early if we hit a cycle
17978 walker = walker.prev;
17981 if (i === n && walker !== null) {
17982 return walker.value;
17986 Yallist.prototype.map = function (fn, thisp) {
17987 thisp = thisp || this;
17988 var res = new Yallist();
17990 for (var walker = this.head; walker !== null;) {
17991 res.push(fn.call(thisp, walker.value, this));
17992 walker = walker.next;
17998 Yallist.prototype.mapReverse = function (fn, thisp) {
17999 thisp = thisp || this;
18000 var res = new Yallist();
18002 for (var walker = this.tail; walker !== null;) {
18003 res.push(fn.call(thisp, walker.value, this));
18004 walker = walker.prev;
18010 Yallist.prototype.reduce = function (fn, initial) {
18012 var walker = this.head;
18014 if (arguments.length > 1) {
18016 } else if (this.head) {
18017 walker = this.head.next;
18018 acc = this.head.value;
18020 throw new TypeError('Reduce of empty list with no initial value');
18023 for (var i = 0; walker !== null; i++) {
18024 acc = fn(acc, walker.value, i);
18025 walker = walker.next;
18031 Yallist.prototype.reduceReverse = function (fn, initial) {
18033 var walker = this.tail;
18035 if (arguments.length > 1) {
18037 } else if (this.tail) {
18038 walker = this.tail.prev;
18039 acc = this.tail.value;
18041 throw new TypeError('Reduce of empty list with no initial value');
18044 for (var i = this.length - 1; walker !== null; i--) {
18045 acc = fn(acc, walker.value, i);
18046 walker = walker.prev;
18052 Yallist.prototype.toArray = function () {
18053 var arr = new Array(this.length);
18055 for (var i = 0, walker = this.head; walker !== null; i++) {
18056 arr[i] = walker.value;
18057 walker = walker.next;
18063 Yallist.prototype.toArrayReverse = function () {
18064 var arr = new Array(this.length);
18066 for (var i = 0, walker = this.tail; walker !== null; i++) {
18067 arr[i] = walker.value;
18068 walker = walker.prev;
18074 Yallist.prototype.slice = function (from, to) {
18075 to = to || this.length;
18084 from += this.length;
18087 var ret = new Yallist();
18089 if (to < from || to < 0) {
18097 if (to > this.length) {
18101 for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
18102 walker = walker.next;
18105 for (; walker !== null && i < to; i++, walker = walker.next) {
18106 ret.push(walker.value);
18112 Yallist.prototype.sliceReverse = function (from, to) {
18113 to = to || this.length;
18122 from += this.length;
18125 var ret = new Yallist();
18127 if (to < from || to < 0) {
18135 if (to > this.length) {
18139 for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
18140 walker = walker.prev;
18143 for (; walker !== null && i > from; i--, walker = walker.prev) {
18144 ret.push(walker.value);
18150 Yallist.prototype.reverse = function () {
18151 var head = this.head;
18152 var tail = this.tail;
18154 for (var walker = head; walker !== null; walker = walker.prev) {
18155 var p = walker.prev;
18156 walker.prev = walker.next;
18165 function push(self, item) {
18166 self.tail = new Node(item, self.tail, null, self);
18169 self.head = self.tail;
18175 function unshift(self, item) {
18176 self.head = new Node(item, null, self.head, self);
18179 self.tail = self.head;
18185 function Node(value, prev, next, list) {
18186 if (!(this instanceof Node)) {
18187 return new Node(value, prev, next, list);
18191 this.value = value;
18208 var lruCache = LRUCache; // This will be a proper iterable 'Map' in engines that support it,
18209 // or a fakey-fake PseudoMap in older versions.
18210 // A linked list to keep track of recently-used-ness
18211 // use symbols if possible, otherwise just _props
18213 var hasSymbol = typeof Symbol === 'function' && process.env._nodeLRUCacheForceNoSymbol !== '1';
18217 makeSymbol = function makeSymbol(key) {
18218 return Symbol(key);
18221 makeSymbol = function makeSymbol(key) {
18226 var MAX = makeSymbol('max');
18227 var LENGTH = makeSymbol('length');
18228 var LENGTH_CALCULATOR = makeSymbol('lengthCalculator');
18229 var ALLOW_STALE = makeSymbol('allowStale');
18230 var MAX_AGE = makeSymbol('maxAge');
18231 var DISPOSE = makeSymbol('dispose');
18232 var NO_DISPOSE_ON_SET = makeSymbol('noDisposeOnSet');
18233 var LRU_LIST = makeSymbol('lruList');
18234 var CACHE = makeSymbol('cache');
18236 function naiveLength() {
18238 } // lruList is a yallist where the head is the youngest
18239 // item, and the tail is the oldest. the list contains the Hit
18240 // objects as the entries.
18241 // Each Hit object has a reference to its Yallist.Node. This
18244 // cache is a Map (or PseudoMap) that matches the keys to
18245 // the Yallist.Node object.
18248 function LRUCache(options) {
18249 if (!(this instanceof LRUCache)) {
18250 return new LRUCache(options);
18253 if (typeof options === 'number') {
18263 var max = this[MAX] = options.max; // Kind of weird to have a default max of Infinity, but oh well.
18265 if (!max || !(typeof max === 'number') || max <= 0) {
18266 this[MAX] = Infinity;
18269 var lc = options.length || naiveLength;
18271 if (typeof lc !== 'function') {
18275 this[LENGTH_CALCULATOR] = lc;
18276 this[ALLOW_STALE] = options.stale || false;
18277 this[MAX_AGE] = options.maxAge || 0;
18278 this[DISPOSE] = options.dispose;
18279 this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
18281 } // resize the cache when the max changes.
18284 Object.defineProperty(LRUCache.prototype, 'max', {
18285 set: function set(mL) {
18286 if (!mL || !(typeof mL === 'number') || mL <= 0) {
18293 get: function get() {
18298 Object.defineProperty(LRUCache.prototype, 'allowStale', {
18299 set: function set(allowStale) {
18300 this[ALLOW_STALE] = !!allowStale;
18302 get: function get() {
18303 return this[ALLOW_STALE];
18307 Object.defineProperty(LRUCache.prototype, 'maxAge', {
18308 set: function set(mA) {
18309 if (!mA || !(typeof mA === 'number') || mA < 0) {
18313 this[MAX_AGE] = mA;
18316 get: function get() {
18317 return this[MAX_AGE];
18320 }); // resize the cache when the lengthCalculator changes.
18322 Object.defineProperty(LRUCache.prototype, 'lengthCalculator', {
18323 set: function set(lC) {
18324 if (typeof lC !== 'function') {
18328 if (lC !== this[LENGTH_CALCULATOR]) {
18329 this[LENGTH_CALCULATOR] = lC;
18331 this[LRU_LIST].forEach(function (hit) {
18332 hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
18333 this[LENGTH] += hit.length;
18339 get: function get() {
18340 return this[LENGTH_CALCULATOR];
18344 Object.defineProperty(LRUCache.prototype, 'length', {
18345 get: function get() {
18346 return this[LENGTH];
18350 Object.defineProperty(LRUCache.prototype, 'itemCount', {
18351 get: function get() {
18352 return this[LRU_LIST].length;
18357 LRUCache.prototype.rforEach = function (fn, thisp) {
18358 thisp = thisp || this;
18360 for (var walker = this[LRU_LIST].tail; walker !== null;) {
18361 var prev = walker.prev;
18362 forEachStep(this, fn, walker, thisp);
18367 function forEachStep(self, fn, node, thisp) {
18368 var hit = node.value;
18370 if (isStale(self, hit)) {
18373 if (!self[ALLOW_STALE]) {
18379 fn.call(thisp, hit.value, hit.key, self);
18383 LRUCache.prototype.forEach = function (fn, thisp) {
18384 thisp = thisp || this;
18386 for (var walker = this[LRU_LIST].head; walker !== null;) {
18387 var next = walker.next;
18388 forEachStep(this, fn, walker, thisp);
18393 LRUCache.prototype.keys = function () {
18394 return this[LRU_LIST].toArray().map(function (k) {
18399 LRUCache.prototype.values = function () {
18400 return this[LRU_LIST].toArray().map(function (k) {
18405 LRUCache.prototype.reset = function () {
18406 if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) {
18407 this[LRU_LIST].forEach(function (hit) {
18408 this[DISPOSE](hit.key, hit.value);
18412 this[CACHE] = new map(); // hash of items by key
18414 this[LRU_LIST] = new yallist(); // list of items in order of use recency
18416 this[LENGTH] = 0; // length of items in the list
18419 LRUCache.prototype.dump = function () {
18420 return this[LRU_LIST].map(function (hit) {
18421 if (!isStale(this, hit)) {
18425 e: hit.now + (hit.maxAge || 0)
18428 }, this).toArray().filter(function (h) {
18433 LRUCache.prototype.dumpLru = function () {
18434 return this[LRU_LIST];
18436 /* istanbul ignore next */
18439 LRUCache.prototype.inspect = function (n, opts) {
18440 var str = 'LRUCache {';
18441 var extras = false;
18442 var as = this[ALLOW_STALE];
18445 str += '\n allowStale: true';
18449 var max = this[MAX];
18451 if (max && max !== Infinity) {
18456 str += '\n max: ' + util$2.inspect(max, opts);
18460 var maxAge = this[MAX_AGE];
18467 str += '\n maxAge: ' + util$2.inspect(maxAge, opts);
18471 var lc = this[LENGTH_CALCULATOR];
18473 if (lc && lc !== naiveLength) {
18478 str += '\n length: ' + util$2.inspect(this[LENGTH], opts);
18482 var didFirst = false;
18483 this[LRU_LIST].forEach(function (item) {
18495 var key = util$2.inspect(item.key).split('\n').join('\n ');
18500 if (item.maxAge !== maxAge) {
18501 val.maxAge = item.maxAge;
18504 if (lc !== naiveLength) {
18505 val.length = item.length;
18508 if (isStale(this, item)) {
18512 val = util$2.inspect(val, opts).split('\n').join('\n ');
18513 str += key + ' => ' + val;
18516 if (didFirst || extras) {
18524 LRUCache.prototype.set = function (key, value, maxAge) {
18525 maxAge = maxAge || this[MAX_AGE];
18526 var now = maxAge ? Date.now() : 0;
18527 var len = this[LENGTH_CALCULATOR](value, key);
18529 if (this[CACHE].has(key)) {
18530 if (len > this[MAX]) {
18531 del(this, this[CACHE].get(key));
18535 var node = this[CACHE].get(key);
18536 var item = node.value; // dispose of the old one before overwriting
18537 // split out into 2 ifs for better coverage tracking
18539 if (this[DISPOSE]) {
18540 if (!this[NO_DISPOSE_ON_SET]) {
18541 this[DISPOSE](key, item.value);
18546 item.maxAge = maxAge;
18547 item.value = value;
18548 this[LENGTH] += len - item.length;
18555 var hit = new Entry$1(key, value, len, now, maxAge); // oversized objects fall out of cache automatically.
18557 if (hit.length > this[MAX]) {
18558 if (this[DISPOSE]) {
18559 this[DISPOSE](key, value);
18565 this[LENGTH] += hit.length;
18566 this[LRU_LIST].unshift(hit);
18567 this[CACHE].set(key, this[LRU_LIST].head);
18572 LRUCache.prototype.has = function (key) {
18573 if (!this[CACHE].has(key)) return false;
18574 var hit = this[CACHE].get(key).value;
18576 if (isStale(this, hit)) {
18583 LRUCache.prototype.get = function (key) {
18584 return get(this, key, true);
18587 LRUCache.prototype.peek = function (key) {
18588 return get(this, key, false);
18591 LRUCache.prototype.pop = function () {
18592 var node = this[LRU_LIST].tail;
18593 if (!node) return null;
18598 LRUCache.prototype.del = function (key) {
18599 del(this, this[CACHE].get(key));
18602 LRUCache.prototype.load = function (arr) {
18605 var now = Date.now(); // A previous serialized cache has the most recent items first
18607 for (var l = arr.length - 1; l >= 0; l--) {
18609 var expiresAt = hit.e || 0;
18611 if (expiresAt === 0) {
18612 // the item was created without expiration in a non aged cache
18613 this.set(hit.k, hit.v);
18615 var maxAge = expiresAt - now; // dont add already expired items
18618 this.set(hit.k, hit.v, maxAge);
18624 LRUCache.prototype.prune = function () {
18626 this[CACHE].forEach(function (value, key) {
18627 get(self, key, false);
18631 function get(self, key, doUse) {
18632 var node = self[CACHE].get(key);
18635 var hit = node.value;
18637 if (isStale(self, hit)) {
18639 if (!self[ALLOW_STALE]) hit = undefined;
18642 self[LRU_LIST].unshiftNode(node);
18646 if (hit) hit = hit.value;
18652 function isStale(self, hit) {
18653 if (!hit || !hit.maxAge && !self[MAX_AGE]) {
18658 var diff = Date.now() - hit.now;
18661 stale = diff > hit.maxAge;
18663 stale = self[MAX_AGE] && diff > self[MAX_AGE];
18669 function trim$2(self) {
18670 if (self[LENGTH] > self[MAX]) {
18671 for (var walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) {
18672 // We know that we're about to delete this one, and also
18673 // what the next least recently used key will be, so just
18674 // go ahead and set it now.
18675 var prev = walker.prev;
18682 function del(self, node) {
18684 var hit = node.value;
18686 if (self[DISPOSE]) {
18687 self[DISPOSE](hit.key, hit.value);
18690 self[LENGTH] -= hit.length;
18691 self[CACHE].delete(hit.key);
18692 self[LRU_LIST].removeNode(node);
18694 } // classy, since V8 prefers predictable objects.
18697 function Entry$1(key, value, length, now, maxAge) {
18699 this.value = value;
18700 this.length = length;
18702 this.maxAge = maxAge || 0;
18705 var sigmund_1 = sigmund;
18707 function sigmund(subject, maxSessions) {
18708 maxSessions = maxSessions || 10;
18713 function psychoAnalyze(subject, session) {
18714 if (session > maxSessions) return;
18716 if (typeof subject === 'function' || typeof subject === 'undefined') {
18720 if (typeof subject !== 'object' || !subject || subject instanceof RE) {
18721 analysis += subject;
18725 if (notes.indexOf(subject) !== -1 || session === maxSessions) return;
18726 notes.push(subject);
18728 Object.keys(subject).forEach(function (issue, _, __) {
18729 // pseudo-private values. skip those.
18730 if (issue.charAt(0) === '_') return;
18731 var to = typeof subject[issue];
18732 if (to === 'function' || to === 'undefined') return;
18734 psychoAnalyze(subject[issue], session + 1);
18738 psychoAnalyze(subject, 0);
18740 } // vim: set softtabstop=4 shiftwidth=4:
18742 var fnmatch = createCommonjsModule(function (module, exports) {
18743 // Based on minimatch.js by isaacs <https://npmjs.org/package/minimatch>
18744 var platform = typeof process === "object" ? process.platform : "win32";
18745 if (module) module.exports = minimatch;else exports.minimatch = minimatch;
18746 minimatch.Minimatch = Minimatch;
18747 var cache = minimatch.cache = new lruCache({
18750 GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {};
18751 var qmark = "[^/]" // * => any number of characters
18753 star = qmark + "*?" // ** when dots are allowed. Anything goes, except .. and .
18754 // not (^ or / followed by one or two dots followed by $ or /),
18755 // followed by anything, any number of times.
18757 twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" // not a ^ or / followed by a dot,
18758 // followed by anything, any number of times.
18760 twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" // characters that need to be escaped in RegExp.
18762 reSpecials = charSet("().*{}+?[]^$\\!"); // "abc" -> { a:true, b:true, c:true }
18764 function charSet(s) {
18765 return s.split("").reduce(function (set, c) {
18769 } // normalizes slashes.
18772 var slashSplit = /\/+/;
18773 minimatch.monkeyPatch = monkeyPatch;
18775 function monkeyPatch() {
18776 var desc = Object.getOwnPropertyDescriptor(String.prototype, "match");
18777 var orig = desc.value;
18779 desc.value = function (p) {
18780 if (p instanceof Minimatch) return p.match(this);
18781 return orig.call(this, p);
18784 Object.defineProperty(String.prototype, desc);
18787 minimatch.filter = filter;
18789 function filter(pattern, options) {
18790 options = options || {};
18791 return function (p, i, list) {
18792 return minimatch(p, pattern, options);
18796 function ext(a, b) {
18800 Object.keys(b).forEach(function (k) {
18803 Object.keys(a).forEach(function (k) {
18809 minimatch.defaults = function (def) {
18810 if (!def || !Object.keys(def).length) return minimatch;
18811 var orig = minimatch;
18813 var m = function minimatch(p, pattern, options) {
18814 return orig.minimatch(p, pattern, ext(def, options));
18817 m.Minimatch = function Minimatch(pattern, options) {
18818 return new orig.Minimatch(pattern, ext(def, options));
18824 Minimatch.defaults = function (def) {
18825 if (!def || !Object.keys(def).length) return Minimatch;
18826 return minimatch.defaults(def).Minimatch;
18829 function minimatch(p, pattern, options) {
18830 if (typeof pattern !== "string") {
18831 throw new TypeError("glob pattern string required");
18834 if (!options) options = {}; // shortcut: comments match nothing.
18836 if (!options.nocomment && pattern.charAt(0) === "#") {
18838 } // "" only matches ""
18841 if (pattern.trim() === "") return p === "";
18842 return new Minimatch(pattern, options).match(p);
18845 function Minimatch(pattern, options) {
18846 if (!(this instanceof Minimatch)) {
18847 return new Minimatch(pattern, options, cache);
18850 if (typeof pattern !== "string") {
18851 throw new TypeError("glob pattern string required");
18854 if (!options) options = {}; // windows: need to use /, not \
18855 // On other platforms, \ is a valid (albeit bad) filename char.
18857 if (platform === "win32") {
18858 pattern = pattern.split("\\").join("/");
18860 // these things aren't particularly big, but walking down the string
18861 // and turning it into a regexp can get pretty costly.
18864 var cacheKey = pattern + "\n" + sigmund_1(options);
18865 var cached = minimatch.cache.get(cacheKey);
18866 if (cached) return cached;
18867 minimatch.cache.set(cacheKey, this);
18868 this.options = options;
18870 this.pattern = pattern;
18871 this.regexp = null;
18872 this.negate = false;
18873 this.comment = false;
18874 this.empty = false; // make the set of regexps etc.
18879 Minimatch.prototype.make = make;
18882 // don't do it more than once.
18883 if (this._made) return;
18884 var pattern = this.pattern;
18885 var options = this.options; // empty patterns and comments match nothing.
18887 if (!options.nocomment && pattern.charAt(0) === "#") {
18888 this.comment = true;
18895 } // step 1: figure out negation, etc.
18898 this.parseNegate(); // step 2: expand braces
18900 var set = this.globSet = this.braceExpand();
18901 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
18902 // matching patterns.
18903 // These will be regexps, except in the case of "**", which is
18904 // set to the GLOBSTAR object for globstar behavior,
18905 // and will not contain any / characters
18907 set = this.globParts = set.map(function (s) {
18908 return s.split(slashSplit);
18910 if (options.debug) console.error(this.pattern, set); // glob --> regexps
18912 set = set.map(function (s, si, set) {
18913 return s.map(this.parse, this);
18915 if (options.debug) console.error(this.pattern, set); // filter out everything that didn't compile properly.
18917 set = set.filter(function (s) {
18918 return -1 === s.indexOf(false);
18920 if (options.debug) console.error(this.pattern, set);
18924 Minimatch.prototype.parseNegate = parseNegate;
18926 function parseNegate() {
18927 var pattern = this.pattern,
18929 options = this.options,
18931 if (options.nonegate) return;
18933 for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) {
18938 if (negateOffset) this.pattern = pattern.substr(negateOffset);
18939 this.negate = negate;
18940 } // Brace expansion:
18941 // a{b,c}d -> abd acd
18942 // a{b,}c -> abc ac
18943 // a{0..3}d -> a0d a1d a2d a3d
18944 // a{b,c{d,e}f}g -> abg acdfg acefg
18945 // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
18947 // Invalid sets are not expanded.
18948 // a{2..}b -> a{2..}b
18952 minimatch.braceExpand = function (pattern, options) {
18953 return new Minimatch(pattern, options).braceExpand();
18956 Minimatch.prototype.braceExpand = braceExpand;
18958 function braceExpand(pattern, options) {
18959 options = options || this.options;
18960 pattern = typeof pattern === "undefined" ? this.pattern : pattern;
18962 if (typeof pattern === "undefined") {
18963 throw new Error("undefined pattern");
18966 if (options.nobrace || !pattern.match(/\{.*\}/)) {
18967 // shortcut. no need to expand.
18971 var escaping = false; // examples and comments refer to this crazy pattern:
18972 // a{b,c{d,e},{f,g}h}x{y,z}
18984 // everything before the first \{ is just a prefix.
18985 // So, we pluck that off, and work with the rest,
18986 // and then prepend it to everything we find.
18988 if (pattern.charAt(0) !== "{") {
18989 // console.error(pattern)
18992 for (var i = 0, l = pattern.length; i < l; i++) {
18993 var c = pattern.charAt(i); // console.error(i, c)
18996 escaping = !escaping;
18997 } else if (c === "{" && !escaping) {
18998 prefix = pattern.substr(0, i);
19001 } // actually no sets, all { were escaped.
19004 if (prefix === null) {
19005 // console.error("no sets")
19009 var tail = braceExpand(pattern.substr(i), options);
19010 return tail.map(function (t) {
19013 } // now we have something like:
19014 // {b,c{d,e},{f,g}h}x{y,z}
19015 // walk through the set, expanding each part, until
19016 // the set ends. then, we'll expand the suffix.
19017 // If the set only has a single member, then'll put the {} back
19018 // first, handle numeric sets, since they're easier
19021 var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/);
19024 // console.error("numset", numset[1], numset[2])
19025 var suf = braceExpand(pattern.substr(numset[0].length), options),
19026 start = +numset[1],
19028 inc = start > end ? -1 : 1,
19031 for (var i = start; i != end + inc; i += inc) {
19032 // append all the suffixes
19033 for (var ii = 0, ll = suf.length; ii < ll; ii++) {
19034 set.push(i + suf[ii]);
19039 } // ok, walk through the set
19040 // We hope, somewhat optimistically, that there
19041 // will be a } at the end.
19042 // If the closing brace isn't found, then the pattern is
19043 // interpreted as braceExpand("\\" + pattern) so that
19044 // the leading \{ will be interpreted literally.
19047 var i = 1 // skip the \{
19054 function addMember() {
19057 } // console.error("Entering for")
19060 FOR: for (i = 1, l = pattern.length; i < l; i++) {
19061 var c = pattern.charAt(i); // console.error("", i, c)
19065 member += "\\" + c;
19078 depth--; // if this closes the actual set, then we're done
19081 addMember(); // pluck off the close-brace
19107 // now we've either finished the set, and the suffix is
19108 // pattern.substr(i), or we have *not* closed the set,
19109 // and need to escape the leading brace
19113 // console.error("didn't close", pattern)
19114 return braceExpand("\\" + pattern, options);
19115 } // x{y,z} -> ["xy", "xz"]
19116 // console.error("set", set)
19117 // console.error("suffix", pattern.substr(i))
19120 var suf = braceExpand(pattern.substr(i), options); // ["b", "c{d,e}","{f,g}h"] ->
19121 // [["b"], ["cd", "ce"], ["fh", "gh"]]
19123 var addBraces = set.length === 1; // console.error("set pre-expanded", set)
19125 set = set.map(function (p) {
19126 return braceExpand(p, options);
19127 }); // console.error("set expanded", set)
19128 // [["b"], ["cd", "ce"], ["fh", "gh"]] ->
19129 // ["b", "cd", "ce", "fh", "gh"]
19131 set = set.reduce(function (l, r) {
19132 return l.concat(r);
19136 set = set.map(function (s) {
19137 return "{" + s + "}";
19139 } // now attach the suffixes.
19144 for (var i = 0, l = set.length; i < l; i++) {
19145 for (var ii = 0, ll = suf.length; ii < ll; ii++) {
19146 ret.push(set[i] + suf[ii]);
19151 } // parse a component of the expanded set.
19152 // At this point, no pattern may contain "/" in it
19153 // so we're going to return a 2d array, where each entry is the full
19154 // pattern, split on '/', and then turned into a regular expression.
19155 // A regexp is made at the end which joins each array with an
19156 // escaped /, and another full one which joins each regexp with |.
19158 // Following the lead of Bash 4.1, note that "**" only has special meaning
19159 // when it is the *only* thing in a path portion. Otherwise, any series
19160 // of * is equivalent to a single *. Globstar behavior is enabled by
19161 // default, and can be disabled by setting options.noglobstar.
19164 Minimatch.prototype.parse = parse;
19167 function parse(pattern, isSub) {
19168 var options = this.options; // shortcuts
19170 if (!options.noglobstar && pattern === "**") return GLOBSTAR;
19171 if (pattern === "") return "";
19173 hasMagic = !!options.nocase,
19174 escaping = false // ? => one single character
19176 patternListStack = [],
19181 classStart = -1 // . and .. never match anything that doesn't start with .,
19182 // even when options.dot is set.
19184 patternStart = pattern.charAt(0) === "." ? "" // anything
19185 // not (start or / followed by . or .. followed by / or end)
19186 : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" : "(?!\\.)";
19188 function clearStateChar() {
19190 // we had some state-tracking character
19191 // that wasn't consumed by this pass.
19192 switch (stateChar) {
19204 re += "\\" + stateChar;
19212 for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) {
19213 if (options.debug) {
19214 console.error("%s\t%s %s %j", pattern, i, re, c);
19215 } // skip over any that are escaped.
19218 if (escaping && reSpecials[c]) {
19226 // completely not allowed, even escaped.
19227 // Should already be path-split by now.
19234 // the various stateChar values
19235 // for the "extglob" stuff.
19242 if (options.debug) {
19243 console.error("%s\t%s %s %j <-- stateChar", pattern, i, re, c);
19244 } // all of those are literals inside a class, except that
19245 // the glob [!a] means [^a] in regexp
19249 if (c === "!" && i === classStart + 1) c = "^";
19252 } // if we already have a stateChar, then it means
19253 // that there was something like ** or +? in there.
19254 // Handle the stateChar, then proceed with this one.
19258 stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing.
19259 // just clear the statechar *now*, rather than even diving into
19260 // the patternList stuff.
19262 if (options.noext) clearStateChar();
19276 plType = stateChar;
19277 patternListStack.push({
19281 }); // negation is (?:(?!js)[^/]*)
19283 re += stateChar === "!" ? "(?:(?!" : "(?:";
19288 if (inClass || !patternListStack.length) {
19295 plType = patternListStack.pop().type; // negation is (?:(?!js)[^/]*)
19296 // The others are (?:<pattern>)<type>
19307 // the default anyway
19313 if (inClass || !patternListStack.length || escaping) {
19321 // these are mostly the same in regexp and glob
19324 // swallow any state-tracking char before the [
19334 reClassStart = re.length;
19339 // a right bracket shall lose its special
19340 // meaning and represent itself in
19341 // a bracket expression if it occurs
19342 // first in the list. -- POSIX.2 2.8.3.2
19343 if (i === classStart + 1 || !inClass) {
19347 } // finish up the class.
19356 // swallow any state char that wasn't consumed
19362 } else if (reSpecials[c] && !(c === "^" && inClass)) {
19370 // handle the case where we left a class open.
19371 // "[abc" is valid, equivalent to "\[abc"
19375 // split where the last [ was, and escape it
19376 // this is a huge pita. We now have to re-walk
19377 // the contents of the would-be class to re-translate
19378 // any characters that were passed through as-is
19379 var cs = pattern.substr(classStart + 1),
19380 sp = this.parse(cs, SUBPARSE);
19381 re = re.substr(0, reClassStart) + "\\[" + sp[0];
19382 hasMagic = hasMagic || sp[1];
19383 } // handle the case where we had a +( thing at the *end*
19385 // each pattern list stack adds 3 chars, and we need to go through
19386 // and escape any | chars that were passed through as-is for the regexp.
19387 // Go through and escape them, taking care not to double-escape any
19388 // | chars that were already escaped.
19393 while (pl = patternListStack.pop()) {
19394 var tail = re.slice(pl.reStart + 3); // maybe some even number of \, then maybe 1 \, followed by a |
19396 tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {
19398 // the | isn't already escaped, so escape it.
19400 } // need to escape all those slashes *again*, without escaping the
19401 // one that we need for escaping the | character. As it works out,
19402 // escaping an even number of slashes can be done by simply repeating
19403 // it exactly after itself. That's why this trick works.
19405 // I am sorry that you have to see this.
19408 return $1 + $1 + $2 + "|";
19409 }); // console.error("tail=%j\n %s", tail, tail)
19411 var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type;
19413 re = re.slice(0, pl.reStart) + t + "\\(" + tail;
19414 } // handle trailing things that only matter at the very end.
19422 } // only need to apply the nodot start if the re starts with
19423 // something that could conceivably capture a dot
19426 var addPatternStart = false;
19428 switch (re.charAt(0)) {
19432 addPatternStart = true;
19433 } // if the re is not "" at this point, then we need to make sure
19434 // it doesn't match against an empty path part.
19435 // Otherwise a/* will match a/, which it should not.
19438 if (re !== "" && hasMagic) re = "(?=.)" + re;
19439 if (addPatternStart) re = patternStart + re; // parsing just a piece of a larger pattern.
19441 if (isSub === SUBPARSE) {
19442 return [re, hasMagic];
19443 } // skip the regexp for non-magical patterns
19444 // unescape anything in it, though, so that it'll be
19445 // an exact match against a file etc.
19449 return globUnescape(pattern);
19452 var flags = options.nocase ? "i" : "",
19453 regExp = new RegExp("^" + re + "$", flags);
19454 regExp._glob = pattern;
19459 minimatch.makeRe = function (pattern, options) {
19460 return new Minimatch(pattern, options || {}).makeRe();
19463 Minimatch.prototype.makeRe = makeRe;
19465 function makeRe() {
19466 if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial
19467 // pattern strings, or "**".
19469 // It's better to use .match(). This function shouldn't
19470 // be used, really, but it's pretty convenient sometimes,
19471 // when you just want to work with a regex.
19473 var set = this.set;
19474 if (!set.length) return this.regexp = false;
19475 var options = this.options;
19476 var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot,
19477 flags = options.nocase ? "i" : "";
19478 var re = set.map(function (pattern) {
19479 return pattern.map(function (p) {
19480 return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src;
19482 }).join("|"); // must match entire pattern
19483 // ending in a * or ** will make it less strict.
19485 re = "^(?:" + re + ")$"; // can match anything, as long as it's not this.
19487 if (this.negate) re = "^(?!" + re + ").*$";
19490 return this.regexp = new RegExp(re, flags);
19492 return this.regexp = false;
19496 minimatch.match = function (list, pattern, options) {
19497 var mm = new Minimatch(pattern, options);
19498 list = list.filter(function (f) {
19499 return mm.match(f);
19502 if (options.nonull && !list.length) {
19503 list.push(pattern);
19509 Minimatch.prototype.match = match;
19511 function match(f, partial) {
19512 // console.error("match", f, this.pattern)
19513 // short-circuit in the case of busted things.
19515 if (this.comment) return false;
19516 if (this.empty) return f === "";
19517 if (f === "/" && partial) return true;
19518 var options = this.options; // windows: need to use /, not \
19519 // On other platforms, \ is a valid (albeit bad) filename char.
19521 if (platform === "win32") {
19522 f = f.split("\\").join("/");
19523 } // treat the test path as a set of pathparts.
19526 f = f.split(slashSplit);
19528 if (options.debug) {
19529 console.error(this.pattern, "split", f);
19530 } // just ONE of the pattern sets in this.set needs to match
19531 // in order for it to be valid. If negating, then just one
19532 // match means that we have failed.
19533 // Either way, return on the first hit.
19536 var set = this.set; // console.error(this.pattern, "set", set)
19538 for (var i = 0, l = set.length; i < l; i++) {
19539 var pattern = set[i];
19540 var hit = this.matchOne(f, pattern, partial);
19543 if (options.flipNegate) return true;
19544 return !this.negate;
19546 } // didn't get any hits. this is success if it's a negative
19547 // pattern, failure otherwise.
19550 if (options.flipNegate) return false;
19551 return this.negate;
19552 } // set partial to true to test if, for example,
19553 // "/a/b" matches the start of "/*/b/*/d"
19554 // Partial means, if you run out of file before you run
19555 // out of pattern, then that's fine, as long as all
19556 // the parts match.
19559 Minimatch.prototype.matchOne = function (file, pattern, partial) {
19560 var options = this.options;
19562 if (options.debug) {
19563 console.error("matchOne", {
19570 if (options.matchBase && pattern.length === 1) {
19571 file = path$2.basename(file.join("/")).split("/");
19574 if (options.debug) {
19575 console.error("matchOne", file.length, pattern.length);
19578 for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
19579 if (options.debug) {
19580 console.error("matchOne loop");
19583 var p = pattern[pi],
19586 if (options.debug) {
19587 console.error(pattern, p, f);
19588 } // should be impossible.
19589 // some invalid regexp stuff in the set.
19592 if (p === false) return false;
19594 if (p === GLOBSTAR) {
19595 if (options.debug) console.error('GLOBSTAR', [pattern, p, f]); // "**"
19596 // a/**/b/**/c would match the following:
19601 // To do this, take the rest of the pattern after
19602 // the **, and see if it would match the file remainder.
19603 // If so, return success.
19604 // If not, the ** "swallows" a segment, and try again.
19605 // This is recursively awful.
19607 // a/**/b/**/c matching a/b/x/y/z/c
19610 // - matchOne(b/x/y/z/c, b/**/c)
19613 // - matchOne(x/y/z/c, c) -> no
19614 // - matchOne(y/z/c, c) -> no
19615 // - matchOne(z/c, c) -> no
19616 // - matchOne(c, c) yes, hit
19622 if (options.debug) console.error('** at the end'); // a ** at the end will just swallow the rest.
19623 // We have found a match.
19624 // however, it will not swallow /.x, unless
19625 // options.dot is set.
19626 // . and .. are *never* matched by **, for explosively
19627 // exponential reasons.
19629 for (; fi < fl; fi++) {
19630 if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false;
19634 } // ok, let's see if we can swallow whatever we can.
19637 WHILE: while (fr < fl) {
19638 var swallowee = file[fr];
19640 if (options.debug) {
19641 console.error('\nglobstar while', file, fr, pattern, pr, swallowee);
19642 } // XXX remove this slice. Just pass the start index.
19645 if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
19646 if (options.debug) console.error('globstar found match!', fr, fl, swallowee); // found a match.
19650 // can't swallow "." or ".." ever.
19651 // can only swallow ".foo" when explicitly asked.
19652 if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") {
19653 if (options.debug) console.error("dot detected!", file, fr, pattern, pr);
19655 } // ** swallows a segment, and continue.
19658 if (options.debug) console.error('globstar swallow a segment, and continue');
19661 } // no match was found.
19662 // However, in partial mode, we can't say this is necessarily over.
19663 // If there's more *pattern* left, then
19668 // console.error("\n>>> no match, partial?", file, fr, pattern, pr)
19669 if (fr === fl) return true;
19673 } // something other than **
19674 // non-magic patterns just have to match exactly
19675 // patterns with magic have been turned into regexps.
19680 if (typeof p === "string") {
19681 if (options.nocase) {
19682 hit = f.toLowerCase() === p.toLowerCase();
19687 if (options.debug) {
19688 console.error("string match", p, f, hit);
19693 if (options.debug) {
19694 console.error("pattern match", p, f, hit);
19698 if (!hit) return false;
19699 } // Note: ending in / means that we'll get a final ""
19700 // at the end of the pattern. This can only match a
19701 // corresponding "" at the end of the file.
19702 // If the file ends in /, then it can only match a
19703 // a pattern that ends in /, unless the pattern just
19704 // doesn't have any more for it. But, a/b/ should *not*
19705 // match "a/b/*", even though "" matches against the
19706 // [^/]*? pattern, except in partial mode, where it might
19707 // simply not be reached yet.
19708 // However, a/b/ should still satisfy a/*
19709 // now either we fell off the end of the pattern, or we're done.
19712 if (fi === fl && pi === pl) {
19713 // ran out of pattern and filename at the same time.
19716 } else if (fi === fl) {
19717 // ran out of file, but still had pattern left.
19718 // this is ok if we're doing the match as part of
19719 // a glob fs traversal.
19721 } else if (pi === pl) {
19722 // ran out of pattern, still have file left.
19723 // this is only acceptable if we're on the very last
19724 // empty segment of a file with a trailing slash.
19725 // a/* should match a/b/
19726 var emptyFileEnd = fi === fl - 1 && file[fi] === "";
19727 return emptyFileEnd;
19728 } // should be unreachable.
19731 throw new Error("wtf?");
19732 }; // replace stuff like \* with *
19735 function globUnescape(s) {
19736 return s.replace(/\\(.)/g, "$1");
19739 function regExpEscape(s) {
19740 return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
19743 var fnmatch_1 = fnmatch.minimatch;
19745 var ini = createCommonjsModule(function (module, exports) {
19747 var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
19748 return new (P || (P = Promise))(function (resolve, reject) {
19749 function fulfilled(value) {
19751 step(generator.next(value));
19757 function rejected(value) {
19759 step(generator["throw"](value));
19765 function step(result) {
19766 result.done ? resolve(result.value) : new P(function (resolve) {
19767 resolve(result.value);
19768 }).then(fulfilled, rejected);
19771 step((generator = generator.apply(thisArg, _arguments || [])).next());
19775 var __generator = this && this.__generator || function (thisArg, body) {
19778 sent: function sent() {
19779 if (t[0] & 1) throw t[1];
19793 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
19798 return function (v) {
19799 return step([n, v]);
19803 function step(op) {
19804 if (f) throw new TypeError("Generator is already executing.");
19808 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;
19809 if (y = 0, t) op = [op[0] & 2, t.value];
19838 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
19843 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
19848 if (op[0] === 6 && _.label < t[1]) {
19854 if (t && _.label < t[2]) {
19862 if (t[2]) _.ops.pop();
19869 op = body.call(thisArg, _);
19878 if (op[0] & 5) throw op[1];
19880 value: op[0] ? op[1] : void 0,
19886 var __importStar = this && this.__importStar || function (mod) {
19887 if (mod && mod.__esModule) return mod;
19889 if (mod != null) for (var k in mod) {
19890 if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
19892 result["default"] = mod;
19896 Object.defineProperty(exports, "__esModule", {
19900 var fs = __importStar(fs$1);
19902 * define the possible values:
19903 * section: [section]
19905 * comment: ;this is a comment
19910 section: /^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$/,
19911 param: /^\s*([\w\.\-\_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$/,
19912 comment: /^\s*[#;].*$/
19915 * Parses an .ini file
19916 * @param file The location of the .ini file
19919 function parse(file) {
19920 return __awaiter(this, void 0, void 0, function () {
19921 return __generator(this, function (_a) {
19924 , new Promise(function (resolve, reject) {
19925 fs.readFile(file, 'utf8', function (err, data) {
19931 resolve(parseString(data));
19938 exports.parse = parse;
19940 function parseSync(file) {
19941 return parseString(fs.readFileSync(file, 'utf8'));
19944 exports.parseSync = parseSync;
19946 function parseString(data) {
19947 var sectionBody = {};
19948 var sectionName = null;
19949 var value = [[sectionName, sectionBody]];
19950 var lines = data.split(/\r\n|\r|\n/);
19951 lines.forEach(function (line) {
19954 if (regex.comment.test(line)) {
19958 if (regex.param.test(line)) {
19959 match = line.match(regex.param);
19960 sectionBody[match[1]] = match[2];
19961 } else if (regex.section.test(line)) {
19962 match = line.match(regex.section);
19963 sectionName = match[1];
19965 value.push([sectionName, sectionBody]);
19971 exports.parseString = parseString;
19973 unwrapExports(ini);
19974 var ini_1 = ini.parse;
19975 var ini_2 = ini.parseSync;
19976 var ini_3 = ini.parseString;
19978 var name$1 = "editorconfig";
19979 var version$1 = "0.15.3";
19980 var description$1 = "EditorConfig File Locator and Interpreter for Node.js";
19985 var main$1 = "src/index.js";
19986 var contributors = [
19987 "Hong Xu (topbug.net)",
19988 "Jed Mao (https://github.com/jedmao/)",
19989 "Trey Hunner (http://treyhunner.com)"
19991 var directories = {
19996 clean: "rimraf dist",
19997 prebuild: "npm run clean",
19999 pretest: "npm run lint && npm run build && npm run copy && cmake .",
20001 "pretest:ci": "npm run pretest",
20002 "test:ci": "ctest -VV --output-on-failure .",
20003 lint: "npm run eclint && npm run tslint",
20004 eclint: "eclint check --indent_size ignore \"src/**\"",
20005 tslint: "tslint --project tsconfig.json --exclude package.json",
20006 copy: "cpy .npmignore LICENSE README.md CHANGELOG.md dist && cpy bin/* dist/bin && cpy src/lib/fnmatch*.* dist/src/lib",
20007 prepub: "npm run lint && npm run build && npm run copy",
20008 pub: "npm publish ./dist"
20010 var repository$1 = {
20012 url: "git://github.com/editorconfig/editorconfig-core-js.git"
20014 var bugs = "https://github.com/editorconfig/editorconfig-core-js/issues";
20015 var author$1 = "EditorConfig Team";
20016 var license$1 = "MIT";
20017 var dependencies$1 = {
20018 commander: "^2.19.0",
20019 "lru-cache": "^4.1.5",
20023 var devDependencies$1 = {
20024 "@types/mocha": "^5.2.6",
20025 "@types/node": "^10.12.29",
20026 "@types/semver": "^5.5.0",
20027 "cpy-cli": "^2.0.0",
20033 typescript: "^3.3.3333"
20037 version: version$1,
20038 description: description$1,
20039 keywords: keywords,
20041 contributors: contributors,
20042 directories: directories,
20043 scripts: scripts$1,
20044 repository: repository$1,
20047 license: license$1,
20048 dependencies: dependencies$1,
20049 devDependencies: devDependencies$1
20052 var _package$3 = /*#__PURE__*/Object.freeze({
20055 version: version$1,
20056 description: description$1,
20057 keywords: keywords,
20059 contributors: contributors,
20060 directories: directories,
20061 scripts: scripts$1,
20062 repository: repository$1,
20065 license: license$1,
20066 dependencies: dependencies$1,
20067 devDependencies: devDependencies$1,
20068 'default': _package$2
20071 var require$$4 = getCjsExportFromNamespace(_package$3);
20073 var src = createCommonjsModule(function (module, exports) {
20075 var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) {
20076 return new (P || (P = Promise))(function (resolve, reject) {
20077 function fulfilled(value) {
20079 step(generator.next(value));
20085 function rejected(value) {
20087 step(generator["throw"](value));
20093 function step(result) {
20094 result.done ? resolve(result.value) : new P(function (resolve) {
20095 resolve(result.value);
20096 }).then(fulfilled, rejected);
20099 step((generator = generator.apply(thisArg, _arguments || [])).next());
20103 var __generator = this && this.__generator || function (thisArg, body) {
20106 sent: function sent() {
20107 if (t[0] & 1) throw t[1];
20121 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
20126 return function (v) {
20127 return step([n, v]);
20131 function step(op) {
20132 if (f) throw new TypeError("Generator is already executing.");
20136 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;
20137 if (y = 0, t) op = [op[0] & 2, t.value];
20166 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
20171 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
20176 if (op[0] === 6 && _.label < t[1]) {
20182 if (t && _.label < t[2]) {
20190 if (t[2]) _.ops.pop();
20197 op = body.call(thisArg, _);
20206 if (op[0] & 5) throw op[1];
20208 value: op[0] ? op[1] : void 0,
20214 var __importStar = this && this.__importStar || function (mod) {
20215 if (mod && mod.__esModule) return mod;
20217 if (mod != null) for (var k in mod) {
20218 if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
20220 result["default"] = mod;
20224 var __importDefault = this && this.__importDefault || function (mod) {
20225 return mod && mod.__esModule ? mod : {
20230 Object.defineProperty(exports, "__esModule", {
20234 var fs = __importStar(fs$1);
20236 var path = __importStar(path$2);
20238 var semver = __importStar(semver$1);
20240 var fnmatch_1 = __importDefault(fnmatch);
20242 exports.parseString = ini.parseString;
20244 var package_json_1 = __importDefault(require$$4);
20248 indent_style: true,
20250 insert_final_newline: true,
20251 trim_trailing_whitespace: true,
20255 function fnmatch$1(filepath, glob) {
20256 var matchOptions = {
20261 glob = glob.replace(/\*\*/g, '{*,**/**/**}');
20262 return fnmatch_1.default(filepath, glob, matchOptions);
20265 function getConfigFileNames(filepath, options) {
20269 filepath = path.dirname(filepath);
20270 paths.push(path.join(filepath, options.config));
20271 } while (filepath !== options.root);
20276 function processMatches(matches, version) {
20277 // Set indent_size to 'tab' if indent_size is unspecified and
20278 // indent_style is set to 'tab'.
20279 if ('indent_style' in matches && matches.indent_style === 'tab' && !('indent_size' in matches) && semver.gte(version, '0.10.0')) {
20280 matches.indent_size = 'tab';
20281 } // Set tab_width to indent_size if indent_size is specified and
20282 // tab_width is unspecified
20285 if ('indent_size' in matches && !('tab_width' in matches) && matches.indent_size !== 'tab') {
20286 matches.tab_width = matches.indent_size;
20287 } // Set indent_size to tab_width if indent_size is 'tab'
20290 if ('indent_size' in matches && 'tab_width' in matches && matches.indent_size === 'tab') {
20291 matches.indent_size = matches.tab_width;
20297 function processOptions(options, filepath) {
20298 if (options === void 0) {
20303 config: options.config || '.editorconfig',
20304 version: options.version || package_json_1.default.version,
20305 root: path.resolve(options.root || path.parse(filepath).root)
20309 function buildFullGlob(pathPrefix, glob) {
20310 switch (glob.indexOf('/')) {
20312 glob = '**/' + glob;
20316 glob = glob.substring(1);
20320 return path.join(pathPrefix, glob);
20323 function extendProps(props, options) {
20324 if (props === void 0) {
20328 if (options === void 0) {
20332 for (var key in options) {
20333 if (options.hasOwnProperty(key)) {
20334 var value = options[key];
20335 var key2 = key.toLowerCase();
20336 var value2 = value;
20338 if (knownProps[key2]) {
20339 value2 = value.toLowerCase();
20343 value2 = JSON.parse(value);
20346 if (typeof value === 'undefined' || value === null) {
20347 // null and undefined are values specific to JSON (no special meaning
20348 // in editorconfig) & should just be returned as regular strings.
20349 value2 = String(value);
20352 props[key2] = value2;
20359 function parseFromConfigs(configs, filepath, options) {
20360 return processMatches(configs.reverse().reduce(function (matches, file) {
20361 var pathPrefix = path.dirname(file.name);
20362 file.contents.forEach(function (section) {
20363 var glob = section[0];
20364 var options2 = section[1];
20370 var fullGlob = buildFullGlob(pathPrefix, glob);
20372 if (!fnmatch$1(filepath, fullGlob)) {
20376 matches = extendProps(matches, options2);
20379 }, {}), options.version);
20382 function getConfigsForFiles(files) {
20385 for (var i in files) {
20386 if (files.hasOwnProperty(i)) {
20387 var file = files[i];
20388 var contents = ini.parseString(file.contents);
20394 if ((contents[0][1].root || '').toLowerCase() === 'true') {
20403 function readConfigFiles(filepaths) {
20404 return __awaiter(this, void 0, void 0, function () {
20405 return __generator(this, function (_a) {
20408 , Promise.all(filepaths.map(function (name) {
20409 return new Promise(function (resolve) {
20410 fs.readFile(name, 'utf8', function (err, data) {
20413 contents: err ? '' : data
20422 function readConfigFilesSync(filepaths) {
20425 filepaths.forEach(function (filepath) {
20427 file = fs.readFileSync(filepath, 'utf8');
20440 function opts(filepath, options) {
20441 if (options === void 0) {
20445 var resolvedFilePath = path.resolve(filepath);
20446 return [resolvedFilePath, processOptions(options, resolvedFilePath)];
20449 function parseFromFiles(filepath, files, options) {
20450 if (options === void 0) {
20454 return __awaiter(this, void 0, void 0, function () {
20455 var _a, resolvedFilePath, processedOptions;
20457 return __generator(this, function (_b) {
20458 _a = opts(filepath, options), resolvedFilePath = _a[0], processedOptions = _a[1];
20461 , files.then(getConfigsForFiles).then(function (configs) {
20462 return parseFromConfigs(configs, resolvedFilePath, processedOptions);
20468 exports.parseFromFiles = parseFromFiles;
20470 function parseFromFilesSync(filepath, files, options) {
20471 if (options === void 0) {
20475 var _a = opts(filepath, options),
20476 resolvedFilePath = _a[0],
20477 processedOptions = _a[1];
20479 return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
20482 exports.parseFromFilesSync = parseFromFilesSync;
20484 function parse(_filepath, _options) {
20485 if (_options === void 0) {
20489 return __awaiter(this, void 0, void 0, function () {
20490 var _a, resolvedFilePath, processedOptions, filepaths;
20492 return __generator(this, function (_b) {
20493 _a = opts(_filepath, _options), resolvedFilePath = _a[0], processedOptions = _a[1];
20494 filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
20497 , readConfigFiles(filepaths).then(getConfigsForFiles).then(function (configs) {
20498 return parseFromConfigs(configs, resolvedFilePath, processedOptions);
20504 exports.parse = parse;
20506 function parseSync(_filepath, _options) {
20507 if (_options === void 0) {
20511 var _a = opts(_filepath, _options),
20512 resolvedFilePath = _a[0],
20513 processedOptions = _a[1];
20515 var filepaths = getConfigFileNames(resolvedFilePath, processedOptions);
20516 var files = readConfigFilesSync(filepaths);
20517 return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions);
20520 exports.parseSync = parseSync;
20522 unwrapExports(src);
20523 var src_1 = src.parseString;
20524 var src_2 = src.parseFromFiles;
20525 var src_3 = src.parseFromFilesSync;
20526 var src_4 = src.parse;
20527 var src_5 = src.parseSync;
20529 var editorconfigToPrettier = editorConfigToPrettier;
20531 function removeUnset(editorConfig) {
20533 var keys = Object.keys(editorConfig);
20535 for (var i = 0; i < keys.length; i++) {
20538 if (editorConfig[key] === "unset") {
20542 result[key] = editorConfig[key];
20548 function editorConfigToPrettier(editorConfig) {
20549 if (!editorConfig) {
20553 editorConfig = removeUnset(editorConfig);
20555 if (Object.keys(editorConfig).length === 0) {
20561 if (editorConfig.indent_style) {
20562 result.useTabs = editorConfig.indent_style === "tab";
20565 if (editorConfig.indent_size === "tab") {
20566 result.useTabs = true;
20569 if (result.useTabs && editorConfig.tab_width) {
20570 result.tabWidth = editorConfig.tab_width;
20571 } else if (editorConfig.indent_style === "space" && editorConfig.indent_size && editorConfig.indent_size !== "tab") {
20572 result.tabWidth = editorConfig.indent_size;
20573 } else if (editorConfig.tab_width !== undefined) {
20574 result.tabWidth = editorConfig.tab_width;
20577 if (editorConfig.max_line_length && editorConfig.max_line_length !== "off") {
20578 result.printWidth = editorConfig.max_line_length;
20581 if (editorConfig.quote_type === "single") {
20582 result.singleQuote = true;
20583 } else if (editorConfig.quote_type === "double") {
20584 result.singleQuote = false;
20587 if (["cr", "crlf", "lf"].indexOf(editorConfig.end_of_line) !== -1) {
20588 result.endOfLine = editorConfig.end_of_line;
20594 function markerExists(files, markers) {
20595 return markers.some(function (marker) {
20596 return files.some(function (file) {
20597 return file === marker;
20602 function traverseFolder(directory, levels, markers) {
20603 var files = fs$1.readdirSync(directory);
20605 if (levels === 0) {
20607 } else if (markerExists(files, markers)) {
20610 return traverseFolder(path$2.resolve(directory, '..'), levels - 1, markers);
20614 var findProjectRoot = function findRoot(dir, opts) {
20615 if (!dir) throw new Error("Directory not defined");
20617 var levels = opts.maxDepth || findRoot.MAX_DEPTH;
20618 var markers = opts.markers || findRoot.MARKERS;
20619 return traverseFolder(dir, levels, markers);
20623 var MARKERS = ['.git', '.hg'];
20624 findProjectRoot.MAX_DEPTH = MAX_DEPTH;
20625 findProjectRoot.MARKERS = MARKERS;
20627 var maybeParse = function maybeParse(filePath, config, parse) {
20628 // findProjectRoot will throw an error if we pass a nonexistent directory to
20629 // it, which is possible, for example, when the path is given via
20630 // --stdin-filepath. So, first, traverse up until we find an existing
20632 var dirPath = path$2.dirname(path$2.resolve(filePath));
20633 var fsRoot = path$2.parse(dirPath).root;
20635 while (dirPath !== fsRoot && !fs$1.existsSync(dirPath)) {
20636 dirPath = path$2.dirname(dirPath);
20639 var root = findProjectRoot(dirPath);
20640 return filePath && parse(filePath, {
20645 var editorconfigAsyncNoCache = function editorconfigAsyncNoCache(filePath, config) {
20646 return Promise.resolve(maybeParse(filePath, config, src.parse)).then(editorconfigToPrettier);
20649 var editorconfigAsyncWithCache = mem_1(editorconfigAsyncNoCache);
20651 var editorconfigSyncNoCache = function editorconfigSyncNoCache(filePath, config) {
20652 return editorconfigToPrettier(maybeParse(filePath, config, src.parseSync));
20655 var editorconfigSyncWithCache = mem_1(editorconfigSyncNoCache);
20657 function getLoadFunction(opts) {
20658 if (!opts.editorconfig) {
20659 return function () {
20665 return opts.cache ? editorconfigSyncWithCache : editorconfigSyncNoCache;
20668 return opts.cache ? editorconfigAsyncWithCache : editorconfigAsyncNoCache;
20671 function clearCache() {
20672 mem_1.clear(editorconfigSyncWithCache);
20673 mem_1.clear(editorconfigAsyncWithCache);
20676 var resolveConfigEditorconfig = {
20681 var ParserEND = 0x110000;
20685 function (_Error) {
20686 _inherits(ParserError, _Error);
20688 /* istanbul ignore next */
20689 function ParserError(msg, filename, linenumber) {
20692 _classCallCheck(this, ParserError);
20694 _this = _possibleConstructorReturn(this, _getPrototypeOf(ParserError).call(this, '[ParserError] ' + msg, filename, linenumber));
20695 _this.name = 'ParserError';
20696 _this.code = 'ParserError';
20697 if (Error.captureStackTrace) Error.captureStackTrace(_assertThisInitialized(_this), ParserError);
20701 return ParserError;
20702 }(_wrapNativeSuper(Error));
20704 var State = function State(parser) {
20705 _classCallCheck(this, State);
20707 this.parser = parser;
20709 this.returned = null;
20710 this.result = null;
20711 this.resultTable = null;
20712 this.resultArr = null;
20718 function Parser() {
20719 _classCallCheck(this, Parser);
20725 this.ctx = this.obj;
20730 this.state = new State(this.parseStart);
20733 _createClass(Parser, [{
20735 value: function parse(str) {
20736 /* istanbul ignore next */
20737 if (str.length === 0 || str.length == null) return;
20738 this._buf = String(str);
20743 while (getNext === false || this.nextChar()) {
20744 getNext = this.runOne();
20751 value: function nextChar() {
20752 if (this.char === 0x0A) {
20758 this.char = this._buf.codePointAt(this.ii);
20761 return this.haveBuffer();
20765 value: function haveBuffer() {
20766 return this.ii < this._buf.length;
20770 value: function runOne() {
20771 return this.state.parser.call(this, this.state.returned);
20775 value: function finish() {
20776 this.char = ParserEND;
20780 last = this.state.parser;
20782 } while (this.state.parser !== last);
20791 value: function next(fn) {
20792 /* istanbul ignore next */
20793 if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn));
20794 this.state.parser = fn;
20798 value: function goto(fn) {
20800 return this.runOne();
20804 value: function call(fn, returnWith) {
20805 if (returnWith) this.next(returnWith);
20806 this.stack.push(this.state);
20807 this.state = new State(fn);
20811 value: function callNow(fn, returnWith) {
20812 this.call(fn, returnWith);
20813 return this.runOne();
20817 value: function _return(value) {
20818 /* istanbul ignore next */
20819 if (this.stack.length === 0) throw this.error(new ParserError('Stack underflow'));
20820 if (value === undefined) value = this.state.buf;
20821 this.state = this.stack.pop();
20822 this.state.returned = value;
20826 value: function returnNow(value) {
20827 this.return(value);
20828 return this.runOne();
20832 value: function consume() {
20833 /* istanbul ignore next */
20834 if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer'));
20835 this.state.buf += this._buf[this.ii];
20839 value: function error(err) {
20840 err.line = this.line;
20841 err.col = this.col;
20842 err.pos = this.pos;
20845 /* istanbul ignore next */
20849 value: function parseStart() {
20850 throw new ParserError('Must declare a parseStart method');
20857 Parser.END = ParserEND;
20858 Parser.Error = ParserError;
20859 var parser$1 = Parser;
20861 var createDatetime = function createDatetime(value) {
20862 var date = new Date(value);
20863 /* istanbul ignore if */
20866 throw new TypeError('Invalid Datetime');
20872 var formatNum = function formatNum(d, num) {
20875 while (num.length < d) {
20882 var FloatingDateTime =
20885 _inherits(FloatingDateTime, _Date);
20887 function FloatingDateTime(value) {
20890 _classCallCheck(this, FloatingDateTime);
20892 _this = _possibleConstructorReturn(this, _getPrototypeOf(FloatingDateTime).call(this, value + 'Z'));
20893 _this.isFloating = true;
20897 _createClass(FloatingDateTime, [{
20898 key: "toISOString",
20899 value: function toISOString() {
20900 var date = `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`;
20901 var time = `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`;
20902 return `${date}T${time}`;
20906 return FloatingDateTime;
20907 }(_wrapNativeSuper(Date));
20909 var createDatetimeFloat = function createDatetimeFloat(value) {
20910 var date = new FloatingDateTime(value);
20911 /* istanbul ignore if */
20914 throw new TypeError('Invalid Datetime');
20920 var DateTime = global.Date;
20924 function (_DateTime) {
20925 _inherits(Date, _DateTime);
20927 function Date(value) {
20930 _classCallCheck(this, Date);
20932 _this = _possibleConstructorReturn(this, _getPrototypeOf(Date).call(this, value));
20933 _this.isDate = true;
20937 _createClass(Date, [{
20938 key: "toISOString",
20939 value: function toISOString() {
20940 return `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`;
20947 var createDate = function createDate(value) {
20948 var date = new Date$1(value);
20949 /* istanbul ignore if */
20952 throw new TypeError('Invalid Datetime');
20961 _inherits(Time, _Date);
20963 function Time(value) {
20966 _classCallCheck(this, Time);
20968 _this = _possibleConstructorReturn(this, _getPrototypeOf(Time).call(this, `0000-01-01T${value}Z`));
20969 _this.isTime = true;
20973 _createClass(Time, [{
20974 key: "toISOString",
20975 value: function toISOString() {
20976 return `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`;
20981 }(_wrapNativeSuper(Date));
20983 var createTime = function createTime(value) {
20984 var date = new Time(value);
20985 /* istanbul ignore if */
20988 throw new TypeError('Invalid Datetime');
20994 /* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */
20997 var tomlParser = makeParserClass(parser$1);
20998 var makeParserClass_1 = makeParserClass;
21002 function (_Error) {
21003 _inherits(TomlError, _Error);
21005 function TomlError(msg) {
21008 _classCallCheck(this, TomlError);
21010 _this = _possibleConstructorReturn(this, _getPrototypeOf(TomlError).call(this, msg));
21011 _this.name = 'TomlError';
21012 /* istanbul ignore next */
21014 if (Error.captureStackTrace) Error.captureStackTrace(_assertThisInitialized(_this), TomlError);
21015 _this.fromTOML = true;
21016 _this.wrapped = null;
21021 }(_wrapNativeSuper(Error));
21023 TomlError.wrap = function (err) {
21024 var terr = new TomlError(err.message);
21025 terr.code = err.code;
21026 terr.wrapped = err;
21030 var TomlError_1 = TomlError;
21034 var CTRL_CHAR_BOUNDARY = 0x1F; // the last non-character in the latin1 region of unicode, except DEL
21036 var CHAR_SP = 0x20;
21037 var CHAR_QUOT = 0x22;
21038 var CHAR_NUM = 0x23;
21039 var CHAR_APOS = 0x27;
21040 var CHAR_PLUS = 0x2B;
21041 var CHAR_COMMA = 0x2C;
21042 var CHAR_HYPHEN = 0x2D;
21043 var CHAR_PERIOD = 0x2E;
21048 var CHAR_COLON = 0x3A;
21049 var CHAR_EQUALS = 0x3D;
21056 var CHAR_LOWBAR = 0x5F;
21071 var CHAR_LCUB = 0x7B;
21072 var CHAR_RCUB = 0x7D;
21073 var CHAR_LSQB = 0x5B;
21074 var CHAR_BSOL = 0x5C;
21075 var CHAR_RSQB = 0x5D;
21076 var CHAR_DEL = 0x7F;
21077 var SURROGATE_FIRST = 0xD800;
21078 var SURROGATE_LAST = 0xDFFF;
21080 [CHAR_b]: '\u0008',
21081 [CHAR_t]: '\u0009',
21082 [CHAR_n]: '\u000A',
21083 [CHAR_f]: '\u000C',
21084 [CHAR_r]: '\u000D',
21085 [CHAR_QUOT]: '\u0022',
21086 [CHAR_BSOL]: '\u005C'
21089 function isDigit(cp) {
21090 return cp >= CHAR_0 && cp <= CHAR_9;
21093 function isHexit(cp) {
21094 return cp >= CHAR_A && cp <= CHAR_F || cp >= CHAR_a && cp <= CHAR_f || cp >= CHAR_0 && cp <= CHAR_9;
21097 function isBit(cp) {
21098 return cp === CHAR_1 || cp === CHAR_0;
21101 function isOctit(cp) {
21102 return cp >= CHAR_0 && cp <= CHAR_7;
21105 function isAlphaNumQuoteHyphen(cp) {
21106 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;
21109 function isAlphaNumHyphen(cp) {
21110 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;
21113 var _type = Symbol('type');
21115 var _declared = Symbol('declared');
21117 var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
21118 var defineProperty = Object.defineProperty;
21120 configurable: true,
21126 function hasKey(obj, key) {
21127 if (hasOwnProperty$1.call(obj, key)) return true;
21128 if (key === '__proto__') defineProperty(obj, '__proto__', descriptor);
21132 var INLINE_TABLE = Symbol('inline-table');
21134 function InlineTable() {
21135 return Object.defineProperties({}, {
21137 value: INLINE_TABLE
21142 function isInlineTable(obj) {
21143 if (obj === null || typeof obj !== 'object') return false;
21144 return obj[_type] === INLINE_TABLE;
21147 var TABLE = Symbol('table');
21150 return Object.defineProperties({}, {
21161 function isTable(obj) {
21162 if (obj === null || typeof obj !== 'object') return false;
21163 return obj[_type] === TABLE;
21166 var _contentType = Symbol('content-type');
21168 var INLINE_LIST = Symbol('inline-list');
21170 function InlineList(type) {
21171 return Object.defineProperties([], {
21181 function isInlineList(obj) {
21182 if (obj === null || typeof obj !== 'object') return false;
21183 return obj[_type] === INLINE_LIST;
21186 var LIST = Symbol('list');
21189 return Object.defineProperties([], {
21196 function isList(obj) {
21197 if (obj === null || typeof obj !== 'object') return false;
21198 return obj[_type] === LIST;
21199 } // in an eval, to let bundlers not slurp in a util proxy
21205 var utilInspect = util$2.inspect;
21206 _custom = utilInspect.custom;
21208 /* eval require not available in transpiled bundle */
21210 /* istanbul ignore next */
21213 var _inspect = _custom || 'inspect';
21218 function BoxedBigInt(value) {
21219 _classCallCheck(this, BoxedBigInt);
21222 this.value = global.BigInt.asIntN(64, value);
21224 /* istanbul ignore next */
21228 Object.defineProperty(this, _type, {
21233 _createClass(BoxedBigInt, [{
21235 value: function isNaN() {
21236 return this.value === null;
21238 /* istanbul ignore next */
21242 value: function toString() {
21243 return String(this.value);
21245 /* istanbul ignore next */
21249 value: function value() {
21250 return `[BigInt: ${this.toString()}]}`;
21254 value: function valueOf() {
21259 return BoxedBigInt;
21262 var INTEGER = Symbol('integer');
21264 function Integer(_value) {
21265 var num = Number(_value); // -0 is a float thing, not an int thing
21267 if (Object.is(num, -0)) num = 0;
21268 /* istanbul ignore else */
21270 if (global.BigInt && !Number.isSafeInteger(num)) {
21271 return new BoxedBigInt(_value);
21273 /* istanbul ignore next */
21274 return Object.defineProperties(new Number(num), {
21276 value: function value() {
21277 return isNaN(this);
21284 value: function value() {
21285 return `[Integer: ${_value}]`;
21292 function isInteger(obj) {
21293 if (obj === null || typeof obj !== 'object') return false;
21294 return obj[_type] === INTEGER;
21297 var FLOAT = Symbol('float');
21299 function Float(_value2) {
21300 /* istanbul ignore next */
21301 return Object.defineProperties(new Number(_value2), {
21306 value: function value() {
21307 return `[Float: ${_value2}]`;
21313 function isFloat(obj) {
21314 if (obj === null || typeof obj !== 'object') return false;
21315 return obj[_type] === FLOAT;
21318 function tomlType(value) {
21319 var type = typeof value;
21321 if (type === 'object') {
21322 /* istanbul ignore if */
21323 if (value === null) return 'null';
21324 if (value instanceof Date) return 'datetime';
21325 /* istanbul ignore else */
21327 if (_type in value) {
21328 switch (value[_type]) {
21330 return 'inline-table';
21333 return 'inline-list';
21335 /* istanbul ignore next */
21340 /* istanbul ignore next */
21357 function makeParserClass(Parser) {
21360 function (_Parser) {
21361 _inherits(TOMLParser, _Parser);
21363 function TOMLParser() {
21366 _classCallCheck(this, TOMLParser);
21368 _this2 = _possibleConstructorReturn(this, _getPrototypeOf(TOMLParser).call(this));
21369 _this2.ctx = _this2.obj = Table();
21375 _createClass(TOMLParser, [{
21376 key: "atEndOfWord",
21377 value: function atEndOfWord() {
21378 return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine();
21381 key: "atEndOfLine",
21382 value: function atEndOfLine() {
21383 return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M;
21387 value: function parseStart() {
21388 if (this.char === Parser.END) {
21390 } else if (this.char === CHAR_LSQB) {
21391 return this.call(this.parseTableOrList);
21392 } else if (this.char === CHAR_NUM) {
21393 return this.call(this.parseComment);
21394 } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
21396 } else if (isAlphaNumQuoteHyphen(this.char)) {
21397 return this.callNow(this.parseAssignStatement);
21399 throw this.error(new TomlError(`Unknown character "${this.char}"`));
21401 } // HELPER, this strips any whitespace and comments to the end of the line
21402 // then RETURNS. Last state in a production.
21405 key: "parseWhitespaceToEOL",
21406 value: function parseWhitespaceToEOL() {
21407 if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
21409 } else if (this.char === CHAR_NUM) {
21410 return this.goto(this.parseComment);
21411 } else if (this.char === Parser.END || this.char === CTRL_J) {
21412 return this.return();
21414 throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line'));
21417 /* ASSIGNMENT: key = value */
21420 key: "parseAssignStatement",
21421 value: function parseAssignStatement() {
21422 return this.callNow(this.parseAssign, this.recordAssignStatement);
21425 key: "recordAssignStatement",
21426 value: function recordAssignStatement(kv) {
21427 var target = this.ctx;
21428 var finalKey = kv.key.pop();
21429 var _iteratorNormalCompletion = true;
21430 var _didIteratorError = false;
21431 var _iteratorError = undefined;
21434 for (var _iterator = kv.key[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
21435 var kw = _step.value;
21437 if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
21438 throw this.error(new TomlError("Can't redefine existing key"));
21441 target = target[kw] = target[kw] || Table();
21444 _didIteratorError = true;
21445 _iteratorError = err;
21448 if (!_iteratorNormalCompletion && _iterator.return != null) {
21449 _iterator.return();
21452 if (_didIteratorError) {
21453 throw _iteratorError;
21458 if (hasKey(target, finalKey)) {
21459 throw this.error(new TomlError("Can't redefine existing key"));
21460 } // unbox our numbers
21463 if (isInteger(kv.value) || isFloat(kv.value)) {
21464 target[finalKey] = kv.value.valueOf();
21466 target[finalKey] = kv.value;
21469 return this.goto(this.parseWhitespaceToEOL);
21471 /* ASSSIGNMENT expression, key = value possibly inside an inline table */
21474 key: "parseAssign",
21475 value: function parseAssign() {
21476 return this.callNow(this.parseKeyword, this.recordAssignKeyword);
21479 key: "recordAssignKeyword",
21480 value: function recordAssignKeyword(key) {
21481 if (this.state.resultTable) {
21482 this.state.resultTable.push(key);
21484 this.state.resultTable = [key];
21487 return this.goto(this.parseAssignKeywordPreDot);
21490 key: "parseAssignKeywordPreDot",
21491 value: function parseAssignKeywordPreDot() {
21492 if (this.char === CHAR_PERIOD) {
21493 return this.next(this.parseAssignKeywordPostDot);
21494 } else if (this.char !== CHAR_SP && this.char !== CTRL_I) {
21495 return this.goto(this.parseAssignEqual);
21499 key: "parseAssignKeywordPostDot",
21500 value: function parseAssignKeywordPostDot() {
21501 if (this.char !== CHAR_SP && this.char !== CTRL_I) {
21502 return this.callNow(this.parseKeyword, this.recordAssignKeyword);
21506 key: "parseAssignEqual",
21507 value: function parseAssignEqual() {
21508 if (this.char === CHAR_EQUALS) {
21509 return this.next(this.parseAssignPreValue);
21511 throw this.error(new TomlError('Invalid character, expected "="'));
21515 key: "parseAssignPreValue",
21516 value: function parseAssignPreValue() {
21517 if (this.char === CHAR_SP || this.char === CTRL_I) {
21520 return this.callNow(this.parseValue, this.recordAssignValue);
21524 key: "recordAssignValue",
21525 value: function recordAssignValue(value) {
21526 return this.returnNow({
21527 key: this.state.resultTable,
21531 /* COMMENTS: #...eol */
21534 key: "parseComment",
21535 value: function parseComment() {
21537 if (this.char === Parser.END || this.char === CTRL_J) {
21538 return this.return();
21540 } while (this.nextChar());
21542 /* TABLES AND LISTS, [foo] and [[foo]] */
21545 key: "parseTableOrList",
21546 value: function parseTableOrList() {
21547 if (this.char === CHAR_LSQB) {
21548 this.next(this.parseList);
21550 return this.goto(this.parseTable);
21553 /* TABLE [foo.bar.baz] */
21557 value: function parseTable() {
21558 this.ctx = this.obj;
21559 return this.goto(this.parseTableNext);
21562 key: "parseTableNext",
21563 value: function parseTableNext() {
21564 if (this.char === CHAR_SP || this.char === CTRL_I) {
21567 return this.callNow(this.parseKeyword, this.parseTableMore);
21571 key: "parseTableMore",
21572 value: function parseTableMore(keyword) {
21573 if (this.char === CHAR_SP || this.char === CTRL_I) {
21575 } else if (this.char === CHAR_RSQB) {
21576 if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) {
21577 throw this.error(new TomlError("Can't redefine existing key"));
21579 this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table();
21580 this.ctx[_declared] = true;
21583 return this.next(this.parseWhitespaceToEOL);
21584 } else if (this.char === CHAR_PERIOD) {
21585 if (!hasKey(this.ctx, keyword)) {
21586 this.ctx = this.ctx[keyword] = Table();
21587 } else if (isTable(this.ctx[keyword])) {
21588 this.ctx = this.ctx[keyword];
21589 } else if (isList(this.ctx[keyword])) {
21590 this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
21592 throw this.error(new TomlError("Can't redefine existing key"));
21595 return this.next(this.parseTableNext);
21597 throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
21600 /* LIST [[a.b.c]] */
21604 value: function parseList() {
21605 this.ctx = this.obj;
21606 return this.goto(this.parseListNext);
21609 key: "parseListNext",
21610 value: function parseListNext() {
21611 if (this.char === CHAR_SP || this.char === CTRL_I) {
21614 return this.callNow(this.parseKeyword, this.parseListMore);
21618 key: "parseListMore",
21619 value: function parseListMore(keyword) {
21620 if (this.char === CHAR_SP || this.char === CTRL_I) {
21622 } else if (this.char === CHAR_RSQB) {
21623 if (!hasKey(this.ctx, keyword)) {
21624 this.ctx[keyword] = List();
21627 if (isInlineList(this.ctx[keyword])) {
21628 throw this.error(new TomlError("Can't extend an inline array"));
21629 } else if (isList(this.ctx[keyword])) {
21630 var next = Table();
21631 this.ctx[keyword].push(next);
21634 throw this.error(new TomlError("Can't redefine an existing key"));
21637 return this.next(this.parseListEnd);
21638 } else if (this.char === CHAR_PERIOD) {
21639 if (!hasKey(this.ctx, keyword)) {
21640 this.ctx = this.ctx[keyword] = Table();
21641 } else if (isInlineList(this.ctx[keyword])) {
21642 throw this.error(new TomlError("Can't extend an inline array"));
21643 } else if (isInlineTable(this.ctx[keyword])) {
21644 throw this.error(new TomlError("Can't extend an inline table"));
21645 } else if (isList(this.ctx[keyword])) {
21646 this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1];
21647 } else if (isTable(this.ctx[keyword])) {
21648 this.ctx = this.ctx[keyword];
21650 throw this.error(new TomlError("Can't redefine an existing key"));
21653 return this.next(this.parseListNext);
21655 throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
21659 key: "parseListEnd",
21660 value: function parseListEnd(keyword) {
21661 if (this.char === CHAR_RSQB) {
21662 return this.next(this.parseWhitespaceToEOL);
21664 throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]'));
21667 /* VALUE string, number, boolean, inline list, inline object */
21671 value: function parseValue() {
21672 if (this.char === Parser.END) {
21673 throw this.error(new TomlError('Key without value'));
21674 } else if (this.char === CHAR_QUOT) {
21675 return this.next(this.parseDoubleString);
21678 if (this.char === CHAR_APOS) {
21679 return this.next(this.parseSingleString);
21680 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
21681 return this.goto(this.parseNumberSign);
21682 } else if (this.char === CHAR_i) {
21683 return this.next(this.parseInf);
21684 } else if (this.char === CHAR_n) {
21685 return this.next(this.parseNan);
21686 } else if (isDigit(this.char)) {
21687 return this.goto(this.parseNumberOrDateTime);
21688 } else if (this.char === CHAR_t || this.char === CHAR_f) {
21689 return this.goto(this.parseBoolean);
21690 } else if (this.char === CHAR_LSQB) {
21691 return this.call(this.parseInlineList, this.recordValue);
21692 } else if (this.char === CHAR_LCUB) {
21693 return this.call(this.parseInlineTable, this.recordValue);
21695 throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table'));
21699 key: "recordValue",
21700 value: function recordValue(value) {
21701 return this.returnNow(value);
21705 value: function parseInf() {
21706 if (this.char === CHAR_n) {
21707 return this.next(this.parseInf2);
21709 throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
21714 value: function parseInf2() {
21715 if (this.char === CHAR_f) {
21716 if (this.state.buf === '-') {
21717 return this.return(-Infinity);
21719 return this.return(Infinity);
21722 throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"'));
21727 value: function parseNan() {
21728 if (this.char === CHAR_a) {
21729 return this.next(this.parseNan2);
21731 throw this.error(new TomlError('Unexpected character, expected "nan"'));
21736 value: function parseNan2() {
21737 if (this.char === CHAR_n) {
21738 return this.return(NaN);
21740 throw this.error(new TomlError('Unexpected character, expected "nan"'));
21743 /* KEYS, barewords or basic, literal, or dotted */
21746 key: "parseKeyword",
21747 value: function parseKeyword() {
21748 if (this.char === CHAR_QUOT) {
21749 return this.next(this.parseBasicString);
21750 } else if (this.char === CHAR_APOS) {
21751 return this.next(this.parseLiteralString);
21753 return this.goto(this.parseBareKey);
21756 /* KEYS: barewords */
21759 key: "parseBareKey",
21760 value: function parseBareKey() {
21762 if (this.char === Parser.END) {
21763 throw this.error(new TomlError('Key ended without value'));
21764 } else if (isAlphaNumHyphen(this.char)) {
21766 } else if (this.state.buf.length === 0) {
21767 throw this.error(new TomlError('Empty bare keys are not allowed'));
21769 return this.returnNow();
21771 } while (this.nextChar());
21773 /* STRINGS, single quoted (literal) */
21776 key: "parseSingleString",
21777 value: function parseSingleString() {
21778 if (this.char === CHAR_APOS) {
21779 return this.next(this.parseLiteralMultiStringMaybe);
21781 return this.goto(this.parseLiteralString);
21785 key: "parseLiteralString",
21786 value: function parseLiteralString() {
21788 if (this.char === CHAR_APOS) {
21789 return this.return();
21790 } else if (this.atEndOfLine()) {
21791 throw this.error(new TomlError('Unterminated string'));
21792 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
21793 throw this.errorControlCharInString();
21797 } while (this.nextChar());
21800 key: "parseLiteralMultiStringMaybe",
21801 value: function parseLiteralMultiStringMaybe() {
21802 if (this.char === CHAR_APOS) {
21803 return this.next(this.parseLiteralMultiString);
21805 return this.returnNow();
21809 key: "parseLiteralMultiString",
21810 value: function parseLiteralMultiString() {
21811 if (this.char === CTRL_M) {
21813 } else if (this.char === CTRL_J) {
21814 return this.next(this.parseLiteralMultiStringContent);
21816 return this.goto(this.parseLiteralMultiStringContent);
21820 key: "parseLiteralMultiStringContent",
21821 value: function parseLiteralMultiStringContent() {
21823 if (this.char === CHAR_APOS) {
21824 return this.next(this.parseLiteralMultiEnd);
21825 } else if (this.char === Parser.END) {
21826 throw this.error(new TomlError('Unterminated multi-line string'));
21827 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
21828 throw this.errorControlCharInString();
21832 } while (this.nextChar());
21835 key: "parseLiteralMultiEnd",
21836 value: function parseLiteralMultiEnd() {
21837 if (this.char === CHAR_APOS) {
21838 return this.next(this.parseLiteralMultiEnd2);
21840 this.state.buf += "'";
21841 return this.goto(this.parseLiteralMultiStringContent);
21845 key: "parseLiteralMultiEnd2",
21846 value: function parseLiteralMultiEnd2() {
21847 if (this.char === CHAR_APOS) {
21848 return this.return();
21850 this.state.buf += "''";
21851 return this.goto(this.parseLiteralMultiStringContent);
21854 /* STRINGS double quoted */
21857 key: "parseDoubleString",
21858 value: function parseDoubleString() {
21859 if (this.char === CHAR_QUOT) {
21860 return this.next(this.parseMultiStringMaybe);
21862 return this.goto(this.parseBasicString);
21866 key: "parseBasicString",
21867 value: function parseBasicString() {
21869 if (this.char === CHAR_BSOL) {
21870 return this.call(this.parseEscape, this.recordEscapeReplacement);
21871 } else if (this.char === CHAR_QUOT) {
21872 return this.return();
21873 } else if (this.atEndOfLine()) {
21874 throw this.error(new TomlError('Unterminated string'));
21875 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) {
21876 throw this.errorControlCharInString();
21880 } while (this.nextChar());
21883 key: "recordEscapeReplacement",
21884 value: function recordEscapeReplacement(replacement) {
21885 this.state.buf += replacement;
21886 return this.goto(this.parseBasicString);
21889 key: "parseMultiStringMaybe",
21890 value: function parseMultiStringMaybe() {
21891 if (this.char === CHAR_QUOT) {
21892 return this.next(this.parseMultiString);
21894 return this.returnNow();
21898 key: "parseMultiString",
21899 value: function parseMultiString() {
21900 if (this.char === CTRL_M) {
21902 } else if (this.char === CTRL_J) {
21903 return this.next(this.parseMultiStringContent);
21905 return this.goto(this.parseMultiStringContent);
21909 key: "parseMultiStringContent",
21910 value: function parseMultiStringContent() {
21912 if (this.char === CHAR_BSOL) {
21913 return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement);
21914 } else if (this.char === CHAR_QUOT) {
21915 return this.next(this.parseMultiEnd);
21916 } else if (this.char === Parser.END) {
21917 throw this.error(new TomlError('Unterminated multi-line string'));
21918 } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) {
21919 throw this.errorControlCharInString();
21923 } while (this.nextChar());
21926 key: "errorControlCharInString",
21927 value: function errorControlCharInString() {
21928 var displayCode = '\\u00';
21930 if (this.char < 16) {
21931 displayCode += '0';
21934 displayCode += this.char.toString(16);
21935 return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`));
21938 key: "recordMultiEscapeReplacement",
21939 value: function recordMultiEscapeReplacement(replacement) {
21940 this.state.buf += replacement;
21941 return this.goto(this.parseMultiStringContent);
21944 key: "parseMultiEnd",
21945 value: function parseMultiEnd() {
21946 if (this.char === CHAR_QUOT) {
21947 return this.next(this.parseMultiEnd2);
21949 this.state.buf += '"';
21950 return this.goto(this.parseMultiStringContent);
21954 key: "parseMultiEnd2",
21955 value: function parseMultiEnd2() {
21956 if (this.char === CHAR_QUOT) {
21957 return this.return();
21959 this.state.buf += '""';
21960 return this.goto(this.parseMultiStringContent);
21964 key: "parseMultiEscape",
21965 value: function parseMultiEscape() {
21966 if (this.char === CTRL_M || this.char === CTRL_J) {
21967 return this.next(this.parseMultiTrim);
21968 } else if (this.char === CHAR_SP || this.char === CTRL_I) {
21969 return this.next(this.parsePreMultiTrim);
21971 return this.goto(this.parseEscape);
21975 key: "parsePreMultiTrim",
21976 value: function parsePreMultiTrim() {
21977 if (this.char === CHAR_SP || this.char === CTRL_I) {
21979 } else if (this.char === CTRL_M || this.char === CTRL_J) {
21980 return this.next(this.parseMultiTrim);
21982 throw this.error(new TomlError("Can't escape whitespace"));
21986 key: "parseMultiTrim",
21987 value: function parseMultiTrim() {
21988 // explicitly whitespace here, END should follow the same path as chars
21989 if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) {
21992 return this.returnNow();
21996 key: "parseEscape",
21997 value: function parseEscape() {
21998 if (this.char in escapes) {
21999 return this.return(escapes[this.char]);
22000 } else if (this.char === CHAR_u) {
22001 return this.call(this.parseSmallUnicode, this.parseUnicodeReturn);
22002 } else if (this.char === CHAR_U) {
22003 return this.call(this.parseLargeUnicode, this.parseUnicodeReturn);
22005 throw this.error(new TomlError('Unknown escape character: ' + this.char));
22009 key: "parseUnicodeReturn",
22010 value: function parseUnicodeReturn(char) {
22012 var codePoint = parseInt(char, 16);
22014 if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) {
22015 throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved'));
22018 return this.returnNow(String.fromCodePoint(codePoint));
22020 throw this.error(TomlError.wrap(err));
22024 key: "parseSmallUnicode",
22025 value: function parseSmallUnicode() {
22026 if (!isHexit(this.char)) {
22027 throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'));
22030 if (this.state.buf.length >= 4) return this.return();
22034 key: "parseLargeUnicode",
22035 value: function parseLargeUnicode() {
22036 if (!isHexit(this.char)) {
22037 throw this.error(new TomlError('Invalid character in unicode sequence, expected hex'));
22040 if (this.state.buf.length >= 8) return this.return();
22046 key: "parseNumberSign",
22047 value: function parseNumberSign() {
22049 return this.next(this.parseMaybeSignedInfOrNan);
22052 key: "parseMaybeSignedInfOrNan",
22053 value: function parseMaybeSignedInfOrNan() {
22054 if (this.char === CHAR_i) {
22055 return this.next(this.parseInf);
22056 } else if (this.char === CHAR_n) {
22057 return this.next(this.parseNan);
22059 return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart);
22063 key: "parseNumberIntegerStart",
22064 value: function parseNumberIntegerStart() {
22065 if (this.char === CHAR_0) {
22067 return this.next(this.parseNumberIntegerExponentOrDecimal);
22069 return this.goto(this.parseNumberInteger);
22073 key: "parseNumberIntegerExponentOrDecimal",
22074 value: function parseNumberIntegerExponentOrDecimal() {
22075 if (this.char === CHAR_PERIOD) {
22077 return this.call(this.parseNoUnder, this.parseNumberFloat);
22078 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22080 return this.next(this.parseNumberExponentSign);
22082 return this.returnNow(Integer(this.state.buf));
22086 key: "parseNumberInteger",
22087 value: function parseNumberInteger() {
22088 if (isDigit(this.char)) {
22090 } else if (this.char === CHAR_LOWBAR) {
22091 return this.call(this.parseNoUnder);
22092 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22094 return this.next(this.parseNumberExponentSign);
22095 } else if (this.char === CHAR_PERIOD) {
22097 return this.call(this.parseNoUnder, this.parseNumberFloat);
22099 var result = Integer(this.state.buf);
22100 /* istanbul ignore if */
22102 if (result.isNaN()) {
22103 throw this.error(new TomlError('Invalid number'));
22105 return this.returnNow(result);
22110 key: "parseNoUnder",
22111 value: function parseNoUnder() {
22112 if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) {
22113 throw this.error(new TomlError('Unexpected character, expected digit'));
22114 } else if (this.atEndOfWord()) {
22115 throw this.error(new TomlError('Incomplete number'));
22118 return this.returnNow();
22121 key: "parseNumberFloat",
22122 value: function parseNumberFloat() {
22123 if (this.char === CHAR_LOWBAR) {
22124 return this.call(this.parseNoUnder, this.parseNumberFloat);
22125 } else if (isDigit(this.char)) {
22127 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22129 return this.next(this.parseNumberExponentSign);
22131 return this.returnNow(Float(this.state.buf));
22135 key: "parseNumberExponentSign",
22136 value: function parseNumberExponentSign() {
22137 if (isDigit(this.char)) {
22138 return this.goto(this.parseNumberExponent);
22139 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
22141 this.call(this.parseNoUnder, this.parseNumberExponent);
22143 throw this.error(new TomlError('Unexpected character, expected -, + or digit'));
22147 key: "parseNumberExponent",
22148 value: function parseNumberExponent() {
22149 if (isDigit(this.char)) {
22151 } else if (this.char === CHAR_LOWBAR) {
22152 return this.call(this.parseNoUnder);
22154 return this.returnNow(Float(this.state.buf));
22157 /* NUMBERS or DATETIMES */
22160 key: "parseNumberOrDateTime",
22161 value: function parseNumberOrDateTime() {
22162 if (this.char === CHAR_0) {
22164 return this.next(this.parseNumberBaseOrDateTime);
22166 return this.goto(this.parseNumberOrDateTimeOnly);
22170 key: "parseNumberOrDateTimeOnly",
22171 value: function parseNumberOrDateTimeOnly() {
22172 // note, if two zeros are in a row then it MUST be a date
22173 if (this.char === CHAR_LOWBAR) {
22174 return this.call(this.parseNoUnder, this.parseNumberInteger);
22175 } else if (isDigit(this.char)) {
22177 if (this.state.buf.length > 4) this.next(this.parseNumberInteger);
22178 } else if (this.char === CHAR_E || this.char === CHAR_e) {
22180 return this.next(this.parseNumberExponentSign);
22181 } else if (this.char === CHAR_PERIOD) {
22183 return this.call(this.parseNoUnder, this.parseNumberFloat);
22184 } else if (this.char === CHAR_HYPHEN) {
22185 return this.goto(this.parseDateTime);
22186 } else if (this.char === CHAR_COLON) {
22187 return this.goto(this.parseOnlyTimeHour);
22189 return this.returnNow(Integer(this.state.buf));
22193 key: "parseDateTimeOnly",
22194 value: function parseDateTimeOnly() {
22195 if (this.state.buf.length < 4) {
22196 if (isDigit(this.char)) {
22197 return this.consume();
22198 } else if (this.char === CHAR_COLON) {
22199 return this.goto(this.parseOnlyTimeHour);
22201 throw this.error(new TomlError('Expected digit while parsing year part of a date'));
22204 if (this.char === CHAR_HYPHEN) {
22205 return this.goto(this.parseDateTime);
22207 throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date'));
22212 key: "parseNumberBaseOrDateTime",
22213 value: function parseNumberBaseOrDateTime() {
22214 if (this.char === CHAR_b) {
22216 return this.call(this.parseNoUnder, this.parseIntegerBin);
22217 } else if (this.char === CHAR_o) {
22219 return this.call(this.parseNoUnder, this.parseIntegerOct);
22220 } else if (this.char === CHAR_x) {
22222 return this.call(this.parseNoUnder, this.parseIntegerHex);
22223 } else if (this.char === CHAR_PERIOD) {
22224 return this.goto(this.parseNumberInteger);
22225 } else if (isDigit(this.char)) {
22226 return this.goto(this.parseDateTimeOnly);
22228 return this.returnNow(Integer(this.state.buf));
22232 key: "parseIntegerHex",
22233 value: function parseIntegerHex() {
22234 if (isHexit(this.char)) {
22236 } else if (this.char === CHAR_LOWBAR) {
22237 return this.call(this.parseNoUnder);
22239 var result = Integer(this.state.buf);
22240 /* istanbul ignore if */
22242 if (result.isNaN()) {
22243 throw this.error(new TomlError('Invalid number'));
22245 return this.returnNow(result);
22250 key: "parseIntegerOct",
22251 value: function parseIntegerOct() {
22252 if (isOctit(this.char)) {
22254 } else if (this.char === CHAR_LOWBAR) {
22255 return this.call(this.parseNoUnder);
22257 var result = Integer(this.state.buf);
22258 /* istanbul ignore if */
22260 if (result.isNaN()) {
22261 throw this.error(new TomlError('Invalid number'));
22263 return this.returnNow(result);
22268 key: "parseIntegerBin",
22269 value: function parseIntegerBin() {
22270 if (isBit(this.char)) {
22272 } else if (this.char === CHAR_LOWBAR) {
22273 return this.call(this.parseNoUnder);
22275 var result = Integer(this.state.buf);
22276 /* istanbul ignore if */
22278 if (result.isNaN()) {
22279 throw this.error(new TomlError('Invalid number'));
22281 return this.returnNow(result);
22288 key: "parseDateTime",
22289 value: function parseDateTime() {
22290 // we enter here having just consumed the year and about to consume the hyphen
22291 if (this.state.buf.length < 4) {
22292 throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters'));
22295 this.state.result = this.state.buf;
22296 this.state.buf = '';
22297 return this.next(this.parseDateMonth);
22300 key: "parseDateMonth",
22301 value: function parseDateMonth() {
22302 if (this.char === CHAR_HYPHEN) {
22303 if (this.state.buf.length < 2) {
22304 throw this.error(new TomlError('Months less than 10 must be zero padded to two characters'));
22307 this.state.result += '-' + this.state.buf;
22308 this.state.buf = '';
22309 return this.next(this.parseDateDay);
22310 } else if (isDigit(this.char)) {
22313 throw this.error(new TomlError('Incomplete datetime'));
22317 key: "parseDateDay",
22318 value: function parseDateDay() {
22319 if (this.char === CHAR_T || this.char === CHAR_SP) {
22320 if (this.state.buf.length < 2) {
22321 throw this.error(new TomlError('Days less than 10 must be zero padded to two characters'));
22324 this.state.result += '-' + this.state.buf;
22325 this.state.buf = '';
22326 return this.next(this.parseStartTimeHour);
22327 } else if (this.atEndOfWord()) {
22328 return this.return(createDate(this.state.result + '-' + this.state.buf));
22329 } else if (isDigit(this.char)) {
22332 throw this.error(new TomlError('Incomplete datetime'));
22336 key: "parseStartTimeHour",
22337 value: function parseStartTimeHour() {
22338 if (this.atEndOfWord()) {
22339 return this.returnNow(createDate(this.state.result));
22341 return this.goto(this.parseTimeHour);
22345 key: "parseTimeHour",
22346 value: function parseTimeHour() {
22347 if (this.char === CHAR_COLON) {
22348 if (this.state.buf.length < 2) {
22349 throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'));
22352 this.state.result += 'T' + this.state.buf;
22353 this.state.buf = '';
22354 return this.next(this.parseTimeMin);
22355 } else if (isDigit(this.char)) {
22358 throw this.error(new TomlError('Incomplete datetime'));
22362 key: "parseTimeMin",
22363 value: function parseTimeMin() {
22364 if (this.state.buf.length < 2 && isDigit(this.char)) {
22366 } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
22367 this.state.result += ':' + this.state.buf;
22368 this.state.buf = '';
22369 return this.next(this.parseTimeSec);
22371 throw this.error(new TomlError('Incomplete datetime'));
22375 key: "parseTimeSec",
22376 value: function parseTimeSec() {
22377 if (isDigit(this.char)) {
22380 if (this.state.buf.length === 2) {
22381 this.state.result += ':' + this.state.buf;
22382 this.state.buf = '';
22383 return this.next(this.parseTimeZoneOrFraction);
22386 throw this.error(new TomlError('Incomplete datetime'));
22390 key: "parseOnlyTimeHour",
22391 value: function parseOnlyTimeHour() {
22392 /* istanbul ignore else */
22393 if (this.char === CHAR_COLON) {
22394 if (this.state.buf.length < 2) {
22395 throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters'));
22398 this.state.result = this.state.buf;
22399 this.state.buf = '';
22400 return this.next(this.parseOnlyTimeMin);
22402 throw this.error(new TomlError('Incomplete time'));
22406 key: "parseOnlyTimeMin",
22407 value: function parseOnlyTimeMin() {
22408 if (this.state.buf.length < 2 && isDigit(this.char)) {
22410 } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) {
22411 this.state.result += ':' + this.state.buf;
22412 this.state.buf = '';
22413 return this.next(this.parseOnlyTimeSec);
22415 throw this.error(new TomlError('Incomplete time'));
22419 key: "parseOnlyTimeSec",
22420 value: function parseOnlyTimeSec() {
22421 if (isDigit(this.char)) {
22424 if (this.state.buf.length === 2) {
22425 return this.next(this.parseOnlyTimeFractionMaybe);
22428 throw this.error(new TomlError('Incomplete time'));
22432 key: "parseOnlyTimeFractionMaybe",
22433 value: function parseOnlyTimeFractionMaybe() {
22434 this.state.result += ':' + this.state.buf;
22436 if (this.char === CHAR_PERIOD) {
22437 this.state.buf = '';
22438 this.next(this.parseOnlyTimeFraction);
22440 return this.return(createTime(this.state.result));
22444 key: "parseOnlyTimeFraction",
22445 value: function parseOnlyTimeFraction() {
22446 if (isDigit(this.char)) {
22448 } else if (this.atEndOfWord()) {
22449 if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds'));
22450 return this.returnNow(createTime(this.state.result + '.' + this.state.buf));
22452 throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
22456 key: "parseTimeZoneOrFraction",
22457 value: function parseTimeZoneOrFraction() {
22458 if (this.char === CHAR_PERIOD) {
22460 this.next(this.parseDateTimeFraction);
22461 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
22463 this.next(this.parseTimeZoneHour);
22464 } else if (this.char === CHAR_Z) {
22466 return this.return(createDatetime(this.state.result + this.state.buf));
22467 } else if (this.atEndOfWord()) {
22468 return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf));
22470 throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
22474 key: "parseDateTimeFraction",
22475 value: function parseDateTimeFraction() {
22476 if (isDigit(this.char)) {
22478 } else if (this.state.buf.length === 1) {
22479 throw this.error(new TomlError('Expected digit in milliseconds'));
22480 } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) {
22482 this.next(this.parseTimeZoneHour);
22483 } else if (this.char === CHAR_Z) {
22485 return this.return(createDatetime(this.state.result + this.state.buf));
22486 } else if (this.atEndOfWord()) {
22487 return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf));
22489 throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z'));
22493 key: "parseTimeZoneHour",
22494 value: function parseTimeZoneHour() {
22495 if (isDigit(this.char)) {
22496 this.consume(); // FIXME: No more regexps
22498 if (/\d\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep);
22500 throw this.error(new TomlError('Unexpected character in datetime, expected digit'));
22504 key: "parseTimeZoneSep",
22505 value: function parseTimeZoneSep() {
22506 if (this.char === CHAR_COLON) {
22508 this.next(this.parseTimeZoneMin);
22510 throw this.error(new TomlError('Unexpected character in datetime, expected colon'));
22514 key: "parseTimeZoneMin",
22515 value: function parseTimeZoneMin() {
22516 if (isDigit(this.char)) {
22518 if (/\d\d$/.test(this.state.buf)) return this.return(createDatetime(this.state.result + this.state.buf));
22520 throw this.error(new TomlError('Unexpected character in datetime, expected digit'));
22526 key: "parseBoolean",
22527 value: function parseBoolean() {
22528 /* istanbul ignore else */
22529 if (this.char === CHAR_t) {
22531 return this.next(this.parseTrue_r);
22532 } else if (this.char === CHAR_f) {
22534 return this.next(this.parseFalse_a);
22538 key: "parseTrue_r",
22539 value: function parseTrue_r() {
22540 if (this.char === CHAR_r) {
22542 return this.next(this.parseTrue_u);
22544 throw this.error(new TomlError('Invalid boolean, expected true or false'));
22548 key: "parseTrue_u",
22549 value: function parseTrue_u() {
22550 if (this.char === CHAR_u) {
22552 return this.next(this.parseTrue_e);
22554 throw this.error(new TomlError('Invalid boolean, expected true or false'));
22558 key: "parseTrue_e",
22559 value: function parseTrue_e() {
22560 if (this.char === CHAR_e) {
22561 return this.return(true);
22563 throw this.error(new TomlError('Invalid boolean, expected true or false'));
22567 key: "parseFalse_a",
22568 value: function parseFalse_a() {
22569 if (this.char === CHAR_a) {
22571 return this.next(this.parseFalse_l);
22573 throw this.error(new TomlError('Invalid boolean, expected true or false'));
22577 key: "parseFalse_l",
22578 value: function parseFalse_l() {
22579 if (this.char === CHAR_l) {
22581 return this.next(this.parseFalse_s);
22583 throw this.error(new TomlError('Invalid boolean, expected true or false'));
22587 key: "parseFalse_s",
22588 value: function parseFalse_s() {
22589 if (this.char === CHAR_s) {
22591 return this.next(this.parseFalse_e);
22593 throw this.error(new TomlError('Invalid boolean, expected true or false'));
22597 key: "parseFalse_e",
22598 value: function parseFalse_e() {
22599 if (this.char === CHAR_e) {
22600 return this.return(false);
22602 throw this.error(new TomlError('Invalid boolean, expected true or false'));
22608 key: "parseInlineList",
22609 value: function parseInlineList() {
22610 if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
22612 } else if (this.char === Parser.END) {
22613 throw this.error(new TomlError('Unterminated inline array'));
22614 } else if (this.char === CHAR_NUM) {
22615 return this.call(this.parseComment);
22616 } else if (this.char === CHAR_RSQB) {
22617 return this.return(this.state.resultArr || InlineList());
22619 return this.callNow(this.parseValue, this.recordInlineListValue);
22623 key: "recordInlineListValue",
22624 value: function recordInlineListValue(value) {
22625 if (this.state.resultArr) {
22626 var listType = this.state.resultArr[_contentType];
22627 var valueType = tomlType(value);
22629 if (listType !== valueType) {
22630 throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`));
22633 this.state.resultArr = InlineList(tomlType(value));
22636 if (isFloat(value) || isInteger(value)) {
22637 // unbox now that we've verified they're ok
22638 this.state.resultArr.push(value.valueOf());
22640 this.state.resultArr.push(value);
22643 return this.goto(this.parseInlineListNext);
22646 key: "parseInlineListNext",
22647 value: function parseInlineListNext() {
22648 if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) {
22650 } else if (this.char === CHAR_NUM) {
22651 return this.call(this.parseComment);
22652 } else if (this.char === CHAR_COMMA) {
22653 return this.next(this.parseInlineList);
22654 } else if (this.char === CHAR_RSQB) {
22655 return this.goto(this.parseInlineList);
22657 throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'));
22663 key: "parseInlineTable",
22664 value: function parseInlineTable() {
22665 if (this.char === CHAR_SP || this.char === CTRL_I) {
22667 } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
22668 throw this.error(new TomlError('Unterminated inline array'));
22669 } else if (this.char === CHAR_RCUB) {
22670 return this.return(this.state.resultTable || InlineTable());
22672 if (!this.state.resultTable) this.state.resultTable = InlineTable();
22673 return this.callNow(this.parseAssign, this.recordInlineTableValue);
22677 key: "recordInlineTableValue",
22678 value: function recordInlineTableValue(kv) {
22679 var target = this.state.resultTable;
22680 var finalKey = kv.key.pop();
22681 var _iteratorNormalCompletion2 = true;
22682 var _didIteratorError2 = false;
22683 var _iteratorError2 = undefined;
22686 for (var _iterator2 = kv.key[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
22687 var kw = _step2.value;
22689 if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) {
22690 throw this.error(new TomlError("Can't redefine existing key"));
22693 target = target[kw] = target[kw] || Table();
22696 _didIteratorError2 = true;
22697 _iteratorError2 = err;
22700 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
22701 _iterator2.return();
22704 if (_didIteratorError2) {
22705 throw _iteratorError2;
22710 if (hasKey(target, finalKey)) {
22711 throw this.error(new TomlError("Can't redefine existing key"));
22714 if (isInteger(kv.value) || isFloat(kv.value)) {
22715 target[finalKey] = kv.value.valueOf();
22717 target[finalKey] = kv.value;
22720 return this.goto(this.parseInlineTableNext);
22723 key: "parseInlineTableNext",
22724 value: function parseInlineTableNext() {
22725 if (this.char === CHAR_SP || this.char === CTRL_I) {
22727 } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) {
22728 throw this.error(new TomlError('Unterminated inline array'));
22729 } else if (this.char === CHAR_COMMA) {
22730 return this.next(this.parseInlineTable);
22731 } else if (this.char === CHAR_RCUB) {
22732 return this.goto(this.parseInlineTable);
22734 throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])'));
22744 tomlParser.makeParserClass = makeParserClass_1;
22745 tomlParser.TomlError = TomlError_1;
22747 var parsePrettyError = prettyError;
22749 function prettyError(err, buf) {
22750 /* istanbul ignore if */
22751 if (err.pos == null || err.line == null) return err;
22752 var msg = err.message;
22753 msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\n`;
22754 /* istanbul ignore else */
22756 if (buf && buf.split) {
22757 var lines = buf.split(/\n/);
22758 var lineNumWidth = String(Math.min(lines.length, err.line + 3)).length;
22759 var linePadding = ' ';
22761 while (linePadding.length < lineNumWidth) {
22762 linePadding += ' ';
22765 for (var ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {
22766 var lineNum = String(ii + 1);
22767 if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum;
22769 if (err.line === ii) {
22770 msg += lineNum + '> ' + lines[ii] + '\n';
22771 msg += linePadding + ' ';
22773 for (var hh = 0; hh < err.col; ++hh) {
22779 msg += lineNum + ': ' + lines[ii] + '\n';
22784 err.message = msg + '\n';
22788 var parseString_1 = parseString;
22790 function parseString(str) {
22791 if (global.Buffer && global.Buffer.isBuffer(str)) {
22792 str = str.toString('utf8');
22795 var parser = new tomlParser();
22799 return parser.finish();
22801 throw parsePrettyError(err, str);
22805 var loadToml = function loadToml(filePath, content) {
22807 return parseString_1(content);
22809 error.message = `TOML Error in ${filePath}:\n${error.message}`;
22814 var getExplorerMemoized = mem_1(function (opts) {
22815 var explorer = thirdParty.cosmiconfig("prettier", {
22817 transform: function transform(result) {
22818 if (result && result.config) {
22819 if (typeof result.config === "string") {
22820 var modulePath = resolve.sync(result.config, {
22821 basedir: path$2.dirname(result.filepath)
22823 result.config = require(modulePath);
22826 if (typeof result.config !== "object") {
22827 throw new Error(`Config is only allowed to be an object, ` + `but received ${typeof result.config} in "${result.filepath}"`);
22830 delete result.config.$schema;
22835 searchPlaces: ["package.json", ".prettierrc", ".prettierrc.json", ".prettierrc.yaml", ".prettierrc.yml", ".prettierrc.js", "prettier.config.js", ".prettierrc.toml"],
22841 var _load = opts.sync ? explorer.loadSync : explorer.load;
22843 var search = opts.sync ? explorer.searchSync : explorer.search;
22845 // cosmiconfig v4 interface
22846 load: function load(searchPath, configPath) {
22847 return configPath ? _load(configPath) : search(searchPath);
22851 /** @param {{ cache: boolean, sync: boolean }} opts */
22853 function getLoadFunction$1(opts) {
22854 // Normalize opts before passing to a memoized function
22855 opts = Object.assign({
22859 return getExplorerMemoized(opts).load;
22862 function _resolveConfig(filePath, opts, sync) {
22863 opts = Object.assign({
22867 cache: !!opts.useCache,
22869 editorconfig: !!opts.editorconfig
22871 var load = getLoadFunction$1(loadOpts);
22872 var loadEditorConfig = resolveConfigEditorconfig.getLoadFunction(loadOpts);
22873 var arr = [load, loadEditorConfig].map(function (l) {
22874 return l(filePath, opts.config);
22877 var unwrapAndMerge = function unwrapAndMerge(arr) {
22878 var result = arr[0];
22879 var editorConfigured = arr[1];
22880 var merged = Object.assign({}, editorConfigured, mergeOverrides(Object.assign({}, result), filePath));
22881 ["plugins", "pluginSearchDirs"].forEach(function (optionName) {
22882 if (Array.isArray(merged[optionName])) {
22883 merged[optionName] = merged[optionName].map(function (value) {
22884 return typeof value === "string" && value.startsWith(".") // relative path
22885 ? path$2.resolve(path$2.dirname(result.filepath), value) : value;
22890 if (!result && !editorConfigured) {
22897 if (loadOpts.sync) {
22898 return unwrapAndMerge(arr);
22901 return Promise.all(arr).then(unwrapAndMerge);
22904 var resolveConfig = function resolveConfig(filePath, opts) {
22905 return _resolveConfig(filePath, opts, false);
22908 resolveConfig.sync = function (filePath, opts) {
22909 return _resolveConfig(filePath, opts, true);
22912 function clearCache$1() {
22913 mem_1.clear(getExplorerMemoized);
22914 resolveConfigEditorconfig.clearCache();
22917 function resolveConfigFile(filePath) {
22918 var load = getLoadFunction$1({
22921 return load(filePath).then(function (result) {
22922 return result ? result.filepath : null;
22926 resolveConfigFile.sync = function (filePath) {
22927 var load = getLoadFunction$1({
22930 var result = load(filePath);
22931 return result ? result.filepath : null;
22934 function mergeOverrides(configResult, filePath) {
22935 var options = Object.assign({}, configResult.config);
22937 if (filePath && options.overrides) {
22938 var relativeFilePath = path$2.relative(path$2.dirname(configResult.filepath), filePath);
22939 var _iteratorNormalCompletion = true;
22940 var _didIteratorError = false;
22941 var _iteratorError = undefined;
22944 for (var _iterator = options.overrides[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
22945 var override = _step.value;
22947 if (pathMatchesGlobs(relativeFilePath, override.files, override.excludeFiles)) {
22948 Object.assign(options, override.options);
22952 _didIteratorError = true;
22953 _iteratorError = err;
22956 if (!_iteratorNormalCompletion && _iterator.return != null) {
22957 _iterator.return();
22960 if (_didIteratorError) {
22961 throw _iteratorError;
22967 delete options.overrides;
22969 } // Based on eslint: https://github.com/eslint/eslint/blob/master/lib/config/config-ops.js
22972 function pathMatchesGlobs(filePath, patterns, excludedPatterns) {
22973 var patternList = [].concat(patterns);
22974 var excludedPatternList = [].concat(excludedPatterns || []);
22979 return patternList.some(function (pattern) {
22980 return minimatch_1(filePath, pattern, opts);
22981 }) && !excludedPatternList.some(function (excludedPattern) {
22982 return minimatch_1(filePath, excludedPattern, opts);
22986 var resolveConfig_1 = {
22989 clearCache: clearCache$1
22993 * @typedef {{ ignorePath?: string, withNodeModules?: boolean, plugins: object }} FileInfoOptions
22994 * @typedef {{ ignored: boolean, inferredParser: string | null }} FileInfoResult
22998 * @param {string} filePath
22999 * @param {FileInfoOptions} opts
23000 * @returns {Promise<FileInfoResult>}
23002 * Please note that prettier.getFileInfo() expects opts.plugins to be an array of paths,
23003 * not an object. A transformation from this array to an object is automatically done
23004 * internally by the method wrapper. See withPlugins() in index.js.
23008 function getFileInfo(filePath, opts) {
23009 if (typeof filePath !== "string") {
23010 return Promise.reject(new TypeError(`expect \`filePath\` to be a string, got \`${typeof filePath}\``));
23013 return createIgnorer_1(opts.ignorePath, opts.withNodeModules).then(function (ignorer) {
23014 return _getFileInfo({
23016 filePath: normalizeFilePath(filePath, opts.ignorePath),
23017 plugins: opts.plugins,
23018 resolveConfig: opts.resolveConfig,
23024 * @param {string} filePath
23025 * @param {FileInfoOptions} opts
23026 * @returns {FileInfoResult}
23030 getFileInfo.sync = function (filePath, opts) {
23031 if (typeof filePath !== "string") {
23032 throw new TypeError(`expect \`filePath\` to be a string, got \`${typeof filePath}\``);
23035 var ignorer = createIgnorer_1.sync(opts.ignorePath, opts.withNodeModules);
23036 return _getFileInfo({
23038 filePath: normalizeFilePath(filePath, opts.ignorePath),
23039 plugins: opts.plugins,
23040 resolveConfig: opts.resolveConfig,
23045 function _getFileInfo(_ref) {
23046 var ignorer = _ref.ignorer,
23047 filePath = _ref.filePath,
23048 plugins = _ref.plugins,
23049 _ref$resolveConfig = _ref.resolveConfig,
23050 resolveConfig = _ref$resolveConfig === void 0 ? false : _ref$resolveConfig,
23051 _ref$sync = _ref.sync,
23052 sync = _ref$sync === void 0 ? false : _ref$sync;
23054 ignored: ignorer.ignores(filePath),
23055 inferredParser: options$1.inferParser(filePath, plugins) || null
23058 if (!fileInfo.inferredParser && resolveConfig) {
23060 return resolveConfig_1.resolveConfig(filePath).then(function (resolvedConfig) {
23061 if (resolvedConfig && resolvedConfig.parser) {
23062 fileInfo.inferredParser = resolvedConfig.parser;
23069 var resolvedConfig = resolveConfig_1.resolveConfig.sync(filePath);
23071 if (resolvedConfig && resolvedConfig.parser) {
23072 fileInfo.inferredParser = resolvedConfig.parser;
23079 function normalizeFilePath(filePath, ignorePath) {
23080 return ignorePath ? path$2.relative(path$2.dirname(ignorePath), filePath) : filePath;
23083 var getFileInfo_1 = getFileInfo;
23085 var lodash_uniqby = createCommonjsModule(function (module, exports) {
23087 * lodash (Custom Build) <https://lodash.com/>
23088 * Build: `lodash modularize exports="npm" -o ./`
23089 * Copyright jQuery Foundation and other contributors <https://jquery.org/>
23090 * Released under MIT license <https://lodash.com/license>
23091 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
23092 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
23095 /** Used as the size to enable large array optimizations. */
23096 var LARGE_ARRAY_SIZE = 200;
23097 /** Used as the `TypeError` message for "Functions" methods. */
23099 var FUNC_ERROR_TEXT = 'Expected a function';
23100 /** Used to stand-in for `undefined` hash values. */
23102 var HASH_UNDEFINED = '__lodash_hash_undefined__';
23103 /** Used to compose bitmasks for comparison styles. */
23105 var UNORDERED_COMPARE_FLAG = 1,
23106 PARTIAL_COMPARE_FLAG = 2;
23107 /** Used as references for various `Number` constants. */
23109 var INFINITY = 1 / 0,
23110 MAX_SAFE_INTEGER = 9007199254740991;
23111 /** `Object#toString` result references. */
23113 var argsTag = '[object Arguments]',
23114 arrayTag = '[object Array]',
23115 boolTag = '[object Boolean]',
23116 dateTag = '[object Date]',
23117 errorTag = '[object Error]',
23118 funcTag = '[object Function]',
23119 genTag = '[object GeneratorFunction]',
23120 mapTag = '[object Map]',
23121 numberTag = '[object Number]',
23122 objectTag = '[object Object]',
23123 promiseTag = '[object Promise]',
23124 regexpTag = '[object RegExp]',
23125 setTag = '[object Set]',
23126 stringTag = '[object String]',
23127 symbolTag = '[object Symbol]',
23128 weakMapTag = '[object WeakMap]';
23129 var arrayBufferTag = '[object ArrayBuffer]',
23130 dataViewTag = '[object DataView]',
23131 float32Tag = '[object Float32Array]',
23132 float64Tag = '[object Float64Array]',
23133 int8Tag = '[object Int8Array]',
23134 int16Tag = '[object Int16Array]',
23135 int32Tag = '[object Int32Array]',
23136 uint8Tag = '[object Uint8Array]',
23137 uint8ClampedTag = '[object Uint8ClampedArray]',
23138 uint16Tag = '[object Uint16Array]',
23139 uint32Tag = '[object Uint32Array]';
23140 /** Used to match property names within property paths. */
23142 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
23143 reIsPlainProp = /^\w*$/,
23144 reLeadingDot = /^\./,
23145 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
23147 * Used to match `RegExp`
23148 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
23151 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
23152 /** Used to match backslashes in property paths. */
23154 var reEscapeChar = /\\(\\)?/g;
23155 /** Used to detect host constructors (Safari). */
23157 var reIsHostCtor = /^\[object .+?Constructor\]$/;
23158 /** Used to detect unsigned integer values. */
23160 var reIsUint = /^(?:0|[1-9]\d*)$/;
23161 /** Used to identify `toStringTag` values of typed arrays. */
23163 var typedArrayTags = {};
23164 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
23165 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;
23166 /** Detect free variable `global` from Node.js. */
23168 var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
23169 /** Detect free variable `self`. */
23171 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
23172 /** Used as a reference to the global object. */
23174 var root = freeGlobal || freeSelf || Function('return this')();
23175 /** Detect free variable `exports`. */
23177 var freeExports = exports && !exports.nodeType && exports;
23178 /** Detect free variable `module`. */
23180 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
23181 /** Detect the popular CommonJS extension `module.exports`. */
23183 var moduleExports = freeModule && freeModule.exports === freeExports;
23184 /** Detect free variable `process` from Node.js. */
23186 var freeProcess = moduleExports && freeGlobal.process;
23187 /** Used to access faster Node.js helpers. */
23189 var nodeUtil = function () {
23191 return freeProcess && freeProcess.binding('util');
23194 /* Node.js helper references. */
23197 var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
23199 * A specialized version of `_.includes` for arrays without support for
23200 * specifying an index to search from.
23203 * @param {Array} [array] The array to inspect.
23204 * @param {*} target The value to search for.
23205 * @returns {boolean} Returns `true` if `target` is found, else `false`.
23208 function arrayIncludes(array, value) {
23209 var length = array ? array.length : 0;
23210 return !!length && baseIndexOf(array, value, 0) > -1;
23213 * This function is like `arrayIncludes` except that it accepts a comparator.
23216 * @param {Array} [array] The array to inspect.
23217 * @param {*} target The value to search for.
23218 * @param {Function} comparator The comparator invoked per element.
23219 * @returns {boolean} Returns `true` if `target` is found, else `false`.
23223 function arrayIncludesWith(array, value, comparator) {
23225 length = array ? array.length : 0;
23227 while (++index < length) {
23228 if (comparator(value, array[index])) {
23236 * A specialized version of `_.some` for arrays without support for iteratee
23240 * @param {Array} [array] The array to iterate over.
23241 * @param {Function} predicate The function invoked per iteration.
23242 * @returns {boolean} Returns `true` if any element passes the predicate check,
23247 function arraySome(array, predicate) {
23249 length = array ? array.length : 0;
23251 while (++index < length) {
23252 if (predicate(array[index], index, array)) {
23260 * The base implementation of `_.findIndex` and `_.findLastIndex` without
23261 * support for iteratee shorthands.
23264 * @param {Array} array The array to inspect.
23265 * @param {Function} predicate The function invoked per iteration.
23266 * @param {number} fromIndex The index to search from.
23267 * @param {boolean} [fromRight] Specify iterating from right to left.
23268 * @returns {number} Returns the index of the matched value, else `-1`.
23272 function baseFindIndex(array, predicate, fromIndex, fromRight) {
23273 var length = array.length,
23274 index = fromIndex + (fromRight ? 1 : -1);
23276 while (fromRight ? index-- : ++index < length) {
23277 if (predicate(array[index], index, array)) {
23285 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
23288 * @param {Array} array The array to inspect.
23289 * @param {*} value The value to search for.
23290 * @param {number} fromIndex The index to search from.
23291 * @returns {number} Returns the index of the matched value, else `-1`.
23295 function baseIndexOf(array, value, fromIndex) {
23296 if (value !== value) {
23297 return baseFindIndex(array, baseIsNaN, fromIndex);
23300 var index = fromIndex - 1,
23301 length = array.length;
23303 while (++index < length) {
23304 if (array[index] === value) {
23312 * The base implementation of `_.isNaN` without support for number objects.
23315 * @param {*} value The value to check.
23316 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
23320 function baseIsNaN(value) {
23321 return value !== value;
23324 * The base implementation of `_.property` without support for deep paths.
23327 * @param {string} key The key of the property to get.
23328 * @returns {Function} Returns the new accessor function.
23332 function baseProperty(key) {
23333 return function (object) {
23334 return object == null ? undefined : object[key];
23338 * The base implementation of `_.times` without support for iteratee shorthands
23339 * or max array length checks.
23342 * @param {number} n The number of times to invoke `iteratee`.
23343 * @param {Function} iteratee The function invoked per iteration.
23344 * @returns {Array} Returns the array of results.
23348 function baseTimes(n, iteratee) {
23352 while (++index < n) {
23353 result[index] = iteratee(index);
23359 * The base implementation of `_.unary` without support for storing metadata.
23362 * @param {Function} func The function to cap arguments for.
23363 * @returns {Function} Returns the new capped function.
23367 function baseUnary(func) {
23368 return function (value) {
23369 return func(value);
23373 * Checks if a cache value for `key` exists.
23376 * @param {Object} cache The cache to query.
23377 * @param {string} key The key of the entry to check.
23378 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
23382 function cacheHas(cache, key) {
23383 return cache.has(key);
23386 * Gets the value at `key` of `object`.
23389 * @param {Object} [object] The object to query.
23390 * @param {string} key The key of the property to get.
23391 * @returns {*} Returns the property value.
23395 function getValue(object, key) {
23396 return object == null ? undefined : object[key];
23399 * Checks if `value` is a host object in IE < 9.
23402 * @param {*} value The value to check.
23403 * @returns {boolean} Returns `true` if `value` is a host object, else `false`.
23407 function isHostObject(value) {
23408 // Many host objects are `Object` objects that can coerce to strings
23409 // despite having improperly defined `toString` methods.
23410 var result = false;
23412 if (value != null && typeof value.toString != 'function') {
23414 result = !!(value + '');
23421 * Converts `map` to its key-value pairs.
23424 * @param {Object} map The map to convert.
23425 * @returns {Array} Returns the key-value pairs.
23429 function mapToArray(map) {
23431 result = Array(map.size);
23432 map.forEach(function (value, key) {
23433 result[++index] = [key, value];
23438 * Creates a unary function that invokes `func` with its argument transformed.
23441 * @param {Function} func The function to wrap.
23442 * @param {Function} transform The argument transform.
23443 * @returns {Function} Returns the new function.
23447 function overArg(func, transform) {
23448 return function (arg) {
23449 return func(transform(arg));
23453 * Converts `set` to an array of its values.
23456 * @param {Object} set The set to convert.
23457 * @returns {Array} Returns the values.
23461 function setToArray(set) {
23463 result = Array(set.size);
23464 set.forEach(function (value) {
23465 result[++index] = value;
23469 /** Used for built-in method references. */
23472 var arrayProto = Array.prototype,
23473 funcProto = Function.prototype,
23474 objectProto = Object.prototype;
23475 /** Used to detect overreaching core-js shims. */
23477 var coreJsData = root['__core-js_shared__'];
23478 /** Used to detect methods masquerading as native. */
23480 var maskSrcKey = function () {
23481 var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
23482 return uid ? 'Symbol(src)_1.' + uid : '';
23484 /** Used to resolve the decompiled source of functions. */
23487 var funcToString = funcProto.toString;
23488 /** Used to check objects for own properties. */
23490 var hasOwnProperty = objectProto.hasOwnProperty;
23492 * Used to resolve the
23493 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
23497 var objectToString = objectProto.toString;
23498 /** Used to detect if a method is native. */
23500 var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
23501 /** Built-in value references. */
23503 var Symbol = root.Symbol,
23504 Uint8Array = root.Uint8Array,
23505 propertyIsEnumerable = objectProto.propertyIsEnumerable,
23506 splice = arrayProto.splice;
23507 /* Built-in method references for those with the same name as other `lodash` methods. */
23509 var nativeKeys = overArg(Object.keys, Object);
23510 /* Built-in method references that are verified to be native. */
23512 var DataView = getNative(root, 'DataView'),
23513 Map = getNative(root, 'Map'),
23514 Promise = getNative(root, 'Promise'),
23515 Set = getNative(root, 'Set'),
23516 WeakMap = getNative(root, 'WeakMap'),
23517 nativeCreate = getNative(Object, 'create');
23518 /** Used to detect maps, sets, and weakmaps. */
23520 var dataViewCtorString = toSource(DataView),
23521 mapCtorString = toSource(Map),
23522 promiseCtorString = toSource(Promise),
23523 setCtorString = toSource(Set),
23524 weakMapCtorString = toSource(WeakMap);
23525 /** Used to convert symbols to primitives and strings. */
23527 var symbolProto = Symbol ? Symbol.prototype : undefined,
23528 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
23529 symbolToString = symbolProto ? symbolProto.toString : undefined;
23531 * Creates a hash object.
23535 * @param {Array} [entries] The key-value pairs to cache.
23538 function Hash(entries) {
23540 length = entries ? entries.length : 0;
23543 while (++index < length) {
23544 var entry = entries[index];
23545 this.set(entry[0], entry[1]);
23549 * Removes all key-value entries from the hash.
23557 function hashClear() {
23558 this.__data__ = nativeCreate ? nativeCreate(null) : {};
23561 * Removes `key` and its value from the hash.
23566 * @param {Object} hash The hash to modify.
23567 * @param {string} key The key of the value to remove.
23568 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
23572 function hashDelete(key) {
23573 return this.has(key) && delete this.__data__[key];
23576 * Gets the hash value for `key`.
23581 * @param {string} key The key of the value to get.
23582 * @returns {*} Returns the entry value.
23586 function hashGet(key) {
23587 var data = this.__data__;
23589 if (nativeCreate) {
23590 var result = data[key];
23591 return result === HASH_UNDEFINED ? undefined : result;
23594 return hasOwnProperty.call(data, key) ? data[key] : undefined;
23597 * Checks if a hash value for `key` exists.
23602 * @param {string} key The key of the entry to check.
23603 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
23607 function hashHas(key) {
23608 var data = this.__data__;
23609 return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
23612 * Sets the hash `key` to `value`.
23617 * @param {string} key The key of the value to set.
23618 * @param {*} value The value to set.
23619 * @returns {Object} Returns the hash instance.
23623 function hashSet(key, value) {
23624 var data = this.__data__;
23625 data[key] = nativeCreate && value === undefined ? HASH_UNDEFINED : value;
23627 } // Add methods to `Hash`.
23630 Hash.prototype.clear = hashClear;
23631 Hash.prototype['delete'] = hashDelete;
23632 Hash.prototype.get = hashGet;
23633 Hash.prototype.has = hashHas;
23634 Hash.prototype.set = hashSet;
23636 * Creates an list cache object.
23640 * @param {Array} [entries] The key-value pairs to cache.
23643 function ListCache(entries) {
23645 length = entries ? entries.length : 0;
23648 while (++index < length) {
23649 var entry = entries[index];
23650 this.set(entry[0], entry[1]);
23654 * Removes all key-value entries from the list cache.
23658 * @memberOf ListCache
23662 function listCacheClear() {
23663 this.__data__ = [];
23666 * Removes `key` and its value from the list cache.
23670 * @memberOf ListCache
23671 * @param {string} key The key of the value to remove.
23672 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
23676 function listCacheDelete(key) {
23677 var data = this.__data__,
23678 index = assocIndexOf(data, key);
23684 var lastIndex = data.length - 1;
23686 if (index == lastIndex) {
23689 splice.call(data, index, 1);
23695 * Gets the list cache value for `key`.
23699 * @memberOf ListCache
23700 * @param {string} key The key of the value to get.
23701 * @returns {*} Returns the entry value.
23705 function listCacheGet(key) {
23706 var data = this.__data__,
23707 index = assocIndexOf(data, key);
23708 return index < 0 ? undefined : data[index][1];
23711 * Checks if a list cache value for `key` exists.
23715 * @memberOf ListCache
23716 * @param {string} key The key of the entry to check.
23717 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
23721 function listCacheHas(key) {
23722 return assocIndexOf(this.__data__, key) > -1;
23725 * Sets the list cache `key` to `value`.
23729 * @memberOf ListCache
23730 * @param {string} key The key of the value to set.
23731 * @param {*} value The value to set.
23732 * @returns {Object} Returns the list cache instance.
23736 function listCacheSet(key, value) {
23737 var data = this.__data__,
23738 index = assocIndexOf(data, key);
23741 data.push([key, value]);
23743 data[index][1] = value;
23747 } // Add methods to `ListCache`.
23750 ListCache.prototype.clear = listCacheClear;
23751 ListCache.prototype['delete'] = listCacheDelete;
23752 ListCache.prototype.get = listCacheGet;
23753 ListCache.prototype.has = listCacheHas;
23754 ListCache.prototype.set = listCacheSet;
23756 * Creates a map cache object to store key-value pairs.
23760 * @param {Array} [entries] The key-value pairs to cache.
23763 function MapCache(entries) {
23765 length = entries ? entries.length : 0;
23768 while (++index < length) {
23769 var entry = entries[index];
23770 this.set(entry[0], entry[1]);
23774 * Removes all key-value entries from the map.
23778 * @memberOf MapCache
23782 function mapCacheClear() {
23784 'hash': new Hash(),
23785 'map': new (Map || ListCache)(),
23786 'string': new Hash()
23790 * Removes `key` and its value from the map.
23794 * @memberOf MapCache
23795 * @param {string} key The key of the value to remove.
23796 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
23800 function mapCacheDelete(key) {
23801 return getMapData(this, key)['delete'](key);
23804 * Gets the map value for `key`.
23808 * @memberOf MapCache
23809 * @param {string} key The key of the value to get.
23810 * @returns {*} Returns the entry value.
23814 function mapCacheGet(key) {
23815 return getMapData(this, key).get(key);
23818 * Checks if a map value for `key` exists.
23822 * @memberOf MapCache
23823 * @param {string} key The key of the entry to check.
23824 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
23828 function mapCacheHas(key) {
23829 return getMapData(this, key).has(key);
23832 * Sets the map `key` to `value`.
23836 * @memberOf MapCache
23837 * @param {string} key The key of the value to set.
23838 * @param {*} value The value to set.
23839 * @returns {Object} Returns the map cache instance.
23843 function mapCacheSet(key, value) {
23844 getMapData(this, key).set(key, value);
23846 } // Add methods to `MapCache`.
23849 MapCache.prototype.clear = mapCacheClear;
23850 MapCache.prototype['delete'] = mapCacheDelete;
23851 MapCache.prototype.get = mapCacheGet;
23852 MapCache.prototype.has = mapCacheHas;
23853 MapCache.prototype.set = mapCacheSet;
23856 * Creates an array cache object to store unique values.
23860 * @param {Array} [values] The values to cache.
23863 function SetCache(values) {
23865 length = values ? values.length : 0;
23866 this.__data__ = new MapCache();
23868 while (++index < length) {
23869 this.add(values[index]);
23873 * Adds `value` to the array cache.
23877 * @memberOf SetCache
23879 * @param {*} value The value to cache.
23880 * @returns {Object} Returns the cache instance.
23884 function setCacheAdd(value) {
23885 this.__data__.set(value, HASH_UNDEFINED);
23890 * Checks if `value` is in the array cache.
23894 * @memberOf SetCache
23895 * @param {*} value The value to search for.
23896 * @returns {number} Returns `true` if `value` is found, else `false`.
23900 function setCacheHas(value) {
23901 return this.__data__.has(value);
23902 } // Add methods to `SetCache`.
23905 SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
23906 SetCache.prototype.has = setCacheHas;
23908 * Creates a stack cache object to store key-value pairs.
23912 * @param {Array} [entries] The key-value pairs to cache.
23915 function Stack(entries) {
23916 this.__data__ = new ListCache(entries);
23919 * Removes all key-value entries from the stack.
23927 function stackClear() {
23928 this.__data__ = new ListCache();
23931 * Removes `key` and its value from the stack.
23936 * @param {string} key The key of the value to remove.
23937 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
23941 function stackDelete(key) {
23942 return this.__data__['delete'](key);
23945 * Gets the stack value for `key`.
23950 * @param {string} key The key of the value to get.
23951 * @returns {*} Returns the entry value.
23955 function stackGet(key) {
23956 return this.__data__.get(key);
23959 * Checks if a stack value for `key` exists.
23964 * @param {string} key The key of the entry to check.
23965 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
23969 function stackHas(key) {
23970 return this.__data__.has(key);
23973 * Sets the stack `key` to `value`.
23978 * @param {string} key The key of the value to set.
23979 * @param {*} value The value to set.
23980 * @returns {Object} Returns the stack cache instance.
23984 function stackSet(key, value) {
23985 var cache = this.__data__;
23987 if (cache instanceof ListCache) {
23988 var pairs = cache.__data__;
23990 if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
23991 pairs.push([key, value]);
23995 cache = this.__data__ = new MapCache(pairs);
23998 cache.set(key, value);
24000 } // Add methods to `Stack`.
24003 Stack.prototype.clear = stackClear;
24004 Stack.prototype['delete'] = stackDelete;
24005 Stack.prototype.get = stackGet;
24006 Stack.prototype.has = stackHas;
24007 Stack.prototype.set = stackSet;
24009 * Creates an array of the enumerable property names of the array-like `value`.
24012 * @param {*} value The value to query.
24013 * @param {boolean} inherited Specify returning inherited property names.
24014 * @returns {Array} Returns the array of property names.
24017 function arrayLikeKeys(value, inherited) {
24018 // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
24019 // Safari 9 makes `arguments.length` enumerable in strict mode.
24020 var result = isArray(value) || isArguments(value) ? baseTimes(value.length, String) : [];
24021 var length = result.length,
24022 skipIndexes = !!length;
24024 for (var key in value) {
24025 if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == 'length' || isIndex(key, length)))) {
24033 * Gets the index at which the `key` is found in `array` of key-value pairs.
24036 * @param {Array} array The array to inspect.
24037 * @param {*} key The key to search for.
24038 * @returns {number} Returns the index of the matched value, else `-1`.
24042 function assocIndexOf(array, key) {
24043 var length = array.length;
24046 if (eq(array[length][0], key)) {
24054 * The base implementation of `_.get` without support for default values.
24057 * @param {Object} object The object to query.
24058 * @param {Array|string} path The path of the property to get.
24059 * @returns {*} Returns the resolved value.
24063 function baseGet(object, path) {
24064 path = isKey(path, object) ? [path] : castPath(path);
24066 length = path.length;
24068 while (object != null && index < length) {
24069 object = object[toKey(path[index++])];
24072 return index && index == length ? object : undefined;
24075 * The base implementation of `getTag`.
24078 * @param {*} value The value to query.
24079 * @returns {string} Returns the `toStringTag`.
24083 function baseGetTag(value) {
24084 return objectToString.call(value);
24087 * The base implementation of `_.hasIn` without support for deep paths.
24090 * @param {Object} [object] The object to query.
24091 * @param {Array|string} key The key to check.
24092 * @returns {boolean} Returns `true` if `key` exists, else `false`.
24096 function baseHasIn(object, key) {
24097 return object != null && key in Object(object);
24100 * The base implementation of `_.isEqual` which supports partial comparisons
24101 * and tracks traversed objects.
24104 * @param {*} value The value to compare.
24105 * @param {*} other The other value to compare.
24106 * @param {Function} [customizer] The function to customize comparisons.
24107 * @param {boolean} [bitmask] The bitmask of comparison flags.
24108 * The bitmask may be composed of the following flags:
24109 * 1 - Unordered comparison
24110 * 2 - Partial comparison
24111 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
24112 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
24116 function baseIsEqual(value, other, customizer, bitmask, stack) {
24117 if (value === other) {
24121 if (value == null || other == null || !isObject(value) && !isObjectLike(other)) {
24122 return value !== value && other !== other;
24125 return baseIsEqualDeep(value, other, baseIsEqual, customizer, bitmask, stack);
24128 * A specialized version of `baseIsEqual` for arrays and objects which performs
24129 * deep comparisons and tracks traversed objects enabling objects with circular
24130 * references to be compared.
24133 * @param {Object} object The object to compare.
24134 * @param {Object} other The other object to compare.
24135 * @param {Function} equalFunc The function to determine equivalents of values.
24136 * @param {Function} [customizer] The function to customize comparisons.
24137 * @param {number} [bitmask] The bitmask of comparison flags. See `baseIsEqual`
24138 * for more details.
24139 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
24140 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
24144 function baseIsEqualDeep(object, other, equalFunc, customizer, bitmask, stack) {
24145 var objIsArr = isArray(object),
24146 othIsArr = isArray(other),
24151 objTag = getTag(object);
24152 objTag = objTag == argsTag ? objectTag : objTag;
24156 othTag = getTag(other);
24157 othTag = othTag == argsTag ? objectTag : othTag;
24160 var objIsObj = objTag == objectTag && !isHostObject(object),
24161 othIsObj = othTag == objectTag && !isHostObject(other),
24162 isSameTag = objTag == othTag;
24164 if (isSameTag && !objIsObj) {
24165 stack || (stack = new Stack());
24166 return objIsArr || isTypedArray(object) ? equalArrays(object, other, equalFunc, customizer, bitmask, stack) : equalByTag(object, other, objTag, equalFunc, customizer, bitmask, stack);
24169 if (!(bitmask & PARTIAL_COMPARE_FLAG)) {
24170 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
24171 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
24173 if (objIsWrapped || othIsWrapped) {
24174 var objUnwrapped = objIsWrapped ? object.value() : object,
24175 othUnwrapped = othIsWrapped ? other.value() : other;
24176 stack || (stack = new Stack());
24177 return equalFunc(objUnwrapped, othUnwrapped, customizer, bitmask, stack);
24185 stack || (stack = new Stack());
24186 return equalObjects(object, other, equalFunc, customizer, bitmask, stack);
24189 * The base implementation of `_.isMatch` without support for iteratee shorthands.
24192 * @param {Object} object The object to inspect.
24193 * @param {Object} source The object of property values to match.
24194 * @param {Array} matchData The property names, values, and compare flags to match.
24195 * @param {Function} [customizer] The function to customize comparisons.
24196 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
24200 function baseIsMatch(object, source, matchData, customizer) {
24201 var index = matchData.length,
24203 noCustomizer = !customizer;
24205 if (object == null) {
24209 object = Object(object);
24212 var data = matchData[index];
24214 if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
24219 while (++index < length) {
24220 data = matchData[index];
24222 objValue = object[key],
24223 srcValue = data[1];
24225 if (noCustomizer && data[2]) {
24226 if (objValue === undefined && !(key in object)) {
24230 var stack = new Stack();
24233 var result = customizer(objValue, srcValue, key, object, source, stack);
24236 if (!(result === undefined ? baseIsEqual(srcValue, objValue, customizer, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG, stack) : result)) {
24245 * The base implementation of `_.isNative` without bad shim checks.
24248 * @param {*} value The value to check.
24249 * @returns {boolean} Returns `true` if `value` is a native function,
24254 function baseIsNative(value) {
24255 if (!isObject(value) || isMasked(value)) {
24259 var pattern = isFunction(value) || isHostObject(value) ? reIsNative : reIsHostCtor;
24260 return pattern.test(toSource(value));
24263 * The base implementation of `_.isTypedArray` without Node.js optimizations.
24266 * @param {*} value The value to check.
24267 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
24271 function baseIsTypedArray(value) {
24272 return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objectToString.call(value)];
24275 * The base implementation of `_.iteratee`.
24278 * @param {*} [value=_.identity] The value to convert to an iteratee.
24279 * @returns {Function} Returns the iteratee.
24283 function baseIteratee(value) {
24284 // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
24285 // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
24286 if (typeof value == 'function') {
24290 if (value == null) {
24294 if (typeof value == 'object') {
24295 return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value);
24298 return property(value);
24301 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
24304 * @param {Object} object The object to query.
24305 * @returns {Array} Returns the array of property names.
24309 function baseKeys(object) {
24310 if (!isPrototype(object)) {
24311 return nativeKeys(object);
24316 for (var key in Object(object)) {
24317 if (hasOwnProperty.call(object, key) && key != 'constructor') {
24325 * The base implementation of `_.matches` which doesn't clone `source`.
24328 * @param {Object} source The object of property values to match.
24329 * @returns {Function} Returns the new spec function.
24333 function baseMatches(source) {
24334 var matchData = getMatchData(source);
24336 if (matchData.length == 1 && matchData[0][2]) {
24337 return matchesStrictComparable(matchData[0][0], matchData[0][1]);
24340 return function (object) {
24341 return object === source || baseIsMatch(object, source, matchData);
24345 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
24348 * @param {string} path The path of the property to get.
24349 * @param {*} srcValue The value to match.
24350 * @returns {Function} Returns the new spec function.
24354 function baseMatchesProperty(path, srcValue) {
24355 if (isKey(path) && isStrictComparable(srcValue)) {
24356 return matchesStrictComparable(toKey(path), srcValue);
24359 return function (object) {
24360 var objValue = get(object, path);
24361 return objValue === undefined && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, undefined, UNORDERED_COMPARE_FLAG | PARTIAL_COMPARE_FLAG);
24365 * A specialized version of `baseProperty` which supports deep paths.
24368 * @param {Array|string} path The path of the property to get.
24369 * @returns {Function} Returns the new accessor function.
24373 function basePropertyDeep(path) {
24374 return function (object) {
24375 return baseGet(object, path);
24379 * The base implementation of `_.toString` which doesn't convert nullish
24380 * values to empty strings.
24383 * @param {*} value The value to process.
24384 * @returns {string} Returns the string.
24388 function baseToString(value) {
24389 // Exit early for strings to avoid a performance hit in some environments.
24390 if (typeof value == 'string') {
24394 if (isSymbol(value)) {
24395 return symbolToString ? symbolToString.call(value) : '';
24398 var result = value + '';
24399 return result == '0' && 1 / value == -INFINITY ? '-0' : result;
24402 * The base implementation of `_.uniqBy` without support for iteratee shorthands.
24405 * @param {Array} array The array to inspect.
24406 * @param {Function} [iteratee] The iteratee invoked per element.
24407 * @param {Function} [comparator] The comparator invoked per element.
24408 * @returns {Array} Returns the new duplicate free array.
24412 function baseUniq(array, iteratee, comparator) {
24414 includes = arrayIncludes,
24415 length = array.length,
24422 includes = arrayIncludesWith;
24423 } else if (length >= LARGE_ARRAY_SIZE) {
24424 var set = iteratee ? null : createSet(array);
24427 return setToArray(set);
24431 includes = cacheHas;
24432 seen = new SetCache();
24434 seen = iteratee ? [] : result;
24437 outer: while (++index < length) {
24438 var value = array[index],
24439 computed = iteratee ? iteratee(value) : value;
24440 value = comparator || value !== 0 ? value : 0;
24442 if (isCommon && computed === computed) {
24443 var seenIndex = seen.length;
24445 while (seenIndex--) {
24446 if (seen[seenIndex] === computed) {
24452 seen.push(computed);
24455 result.push(value);
24456 } else if (!includes(seen, computed, comparator)) {
24457 if (seen !== result) {
24458 seen.push(computed);
24461 result.push(value);
24468 * Casts `value` to a path array if it's not one.
24471 * @param {*} value The value to inspect.
24472 * @returns {Array} Returns the cast property path array.
24476 function castPath(value) {
24477 return isArray(value) ? value : stringToPath(value);
24480 * Creates a set object of `values`.
24483 * @param {Array} values The values to add to the set.
24484 * @returns {Object} Returns the new set.
24488 var createSet = !(Set && 1 / setToArray(new Set([, -0]))[1] == INFINITY) ? noop : function (values) {
24489 return new Set(values);
24492 * A specialized version of `baseIsEqualDeep` for arrays with support for
24493 * partial deep comparisons.
24496 * @param {Array} array The array to compare.
24497 * @param {Array} other The other array to compare.
24498 * @param {Function} equalFunc The function to determine equivalents of values.
24499 * @param {Function} customizer The function to customize comparisons.
24500 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
24501 * for more details.
24502 * @param {Object} stack Tracks traversed `array` and `other` objects.
24503 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
24506 function equalArrays(array, other, equalFunc, customizer, bitmask, stack) {
24507 var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
24508 arrLength = array.length,
24509 othLength = other.length;
24511 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
24513 } // Assume cyclic values are equal.
24516 var stacked = stack.get(array);
24518 if (stacked && stack.get(other)) {
24519 return stacked == other;
24524 seen = bitmask & UNORDERED_COMPARE_FLAG ? new SetCache() : undefined;
24525 stack.set(array, other);
24526 stack.set(other, array); // Ignore non-index properties.
24528 while (++index < arrLength) {
24529 var arrValue = array[index],
24530 othValue = other[index];
24533 var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
24536 if (compared !== undefined) {
24543 } // Recursively compare arrays (susceptible to call stack limits).
24547 if (!arraySome(other, function (othValue, othIndex) {
24548 if (!seen.has(othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
24549 return seen.add(othIndex);
24555 } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, customizer, bitmask, stack))) {
24561 stack['delete'](array);
24562 stack['delete'](other);
24566 * A specialized version of `baseIsEqualDeep` for comparing objects of
24567 * the same `toStringTag`.
24569 * **Note:** This function only supports comparing values with tags of
24570 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
24573 * @param {Object} object The object to compare.
24574 * @param {Object} other The other object to compare.
24575 * @param {string} tag The `toStringTag` of the objects to compare.
24576 * @param {Function} equalFunc The function to determine equivalents of values.
24577 * @param {Function} customizer The function to customize comparisons.
24578 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
24579 * for more details.
24580 * @param {Object} stack Tracks traversed `object` and `other` objects.
24581 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
24585 function equalByTag(object, other, tag, equalFunc, customizer, bitmask, stack) {
24588 if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
24592 object = object.buffer;
24593 other = other.buffer;
24595 case arrayBufferTag:
24596 if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
24605 // Coerce booleans to `1` or `0` and dates to milliseconds.
24606 // Invalid dates are coerced to `NaN`.
24607 return eq(+object, +other);
24610 return object.name == other.name && object.message == other.message;
24614 // Coerce regexes to strings and treat strings, primitives and objects,
24615 // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
24616 // for more details.
24617 return object == other + '';
24620 var convert = mapToArray;
24623 var isPartial = bitmask & PARTIAL_COMPARE_FLAG;
24624 convert || (convert = setToArray);
24626 if (object.size != other.size && !isPartial) {
24628 } // Assume cyclic values are equal.
24631 var stacked = stack.get(object);
24634 return stacked == other;
24637 bitmask |= UNORDERED_COMPARE_FLAG; // Recursively compare objects (susceptible to call stack limits).
24639 stack.set(object, other);
24640 var result = equalArrays(convert(object), convert(other), equalFunc, customizer, bitmask, stack);
24641 stack['delete'](object);
24645 if (symbolValueOf) {
24646 return symbolValueOf.call(object) == symbolValueOf.call(other);
24654 * A specialized version of `baseIsEqualDeep` for objects with support for
24655 * partial deep comparisons.
24658 * @param {Object} object The object to compare.
24659 * @param {Object} other The other object to compare.
24660 * @param {Function} equalFunc The function to determine equivalents of values.
24661 * @param {Function} customizer The function to customize comparisons.
24662 * @param {number} bitmask The bitmask of comparison flags. See `baseIsEqual`
24663 * for more details.
24664 * @param {Object} stack Tracks traversed `object` and `other` objects.
24665 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
24669 function equalObjects(object, other, equalFunc, customizer, bitmask, stack) {
24670 var isPartial = bitmask & PARTIAL_COMPARE_FLAG,
24671 objProps = keys(object),
24672 objLength = objProps.length,
24673 othProps = keys(other),
24674 othLength = othProps.length;
24676 if (objLength != othLength && !isPartial) {
24680 var index = objLength;
24683 var key = objProps[index];
24685 if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
24688 } // Assume cyclic values are equal.
24691 var stacked = stack.get(object);
24693 if (stacked && stack.get(other)) {
24694 return stacked == other;
24698 stack.set(object, other);
24699 stack.set(other, object);
24700 var skipCtor = isPartial;
24702 while (++index < objLength) {
24703 key = objProps[index];
24704 var objValue = object[key],
24705 othValue = other[key];
24708 var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
24709 } // Recursively compare objects (susceptible to call stack limits).
24712 if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, customizer, bitmask, stack) : compared)) {
24717 skipCtor || (skipCtor = key == 'constructor');
24720 if (result && !skipCtor) {
24721 var objCtor = object.constructor,
24722 othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal.
24724 if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
24729 stack['delete'](object);
24730 stack['delete'](other);
24734 * Gets the data for `map`.
24737 * @param {Object} map The map to query.
24738 * @param {string} key The reference key.
24739 * @returns {*} Returns the map data.
24743 function getMapData(map, key) {
24744 var data = map.__data__;
24745 return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
24748 * Gets the property names, values, and compare flags of `object`.
24751 * @param {Object} object The object to query.
24752 * @returns {Array} Returns the match data of `object`.
24756 function getMatchData(object) {
24757 var result = keys(object),
24758 length = result.length;
24761 var key = result[length],
24762 value = object[key];
24763 result[length] = [key, value, isStrictComparable(value)];
24769 * Gets the native function at `key` of `object`.
24772 * @param {Object} object The object to query.
24773 * @param {string} key The key of the method to get.
24774 * @returns {*} Returns the function if it's native, else `undefined`.
24778 function getNative(object, key) {
24779 var value = getValue(object, key);
24780 return baseIsNative(value) ? value : undefined;
24783 * Gets the `toStringTag` of `value`.
24786 * @param {*} value The value to query.
24787 * @returns {string} Returns the `toStringTag`.
24791 var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11,
24792 // for data views in Edge < 14, and promises in Node.js.
24794 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) {
24795 getTag = function getTag(value) {
24796 var result = objectToString.call(value),
24797 Ctor = result == objectTag ? value.constructor : undefined,
24798 ctorString = Ctor ? toSource(Ctor) : undefined;
24801 switch (ctorString) {
24802 case dataViewCtorString:
24803 return dataViewTag;
24805 case mapCtorString:
24808 case promiseCtorString:
24811 case setCtorString:
24814 case weakMapCtorString:
24823 * Checks if `path` exists on `object`.
24826 * @param {Object} object The object to query.
24827 * @param {Array|string} path The path to check.
24828 * @param {Function} hasFunc The function to check properties.
24829 * @returns {boolean} Returns `true` if `path` exists, else `false`.
24833 function hasPath(object, path, hasFunc) {
24834 path = isKey(path, object) ? [path] : castPath(path);
24837 length = path.length;
24839 while (++index < length) {
24840 var key = toKey(path[index]);
24842 if (!(result = object != null && hasFunc(object, key))) {
24846 object = object[key];
24853 var length = object ? object.length : 0;
24854 return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object));
24857 * Checks if `value` is a valid array-like index.
24860 * @param {*} value The value to check.
24861 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
24862 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
24866 function isIndex(value, length) {
24867 length = length == null ? MAX_SAFE_INTEGER : length;
24868 return !!length && (typeof value == 'number' || reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
24871 * Checks if `value` is a property name and not a property path.
24874 * @param {*} value The value to check.
24875 * @param {Object} [object] The object to query keys on.
24876 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
24880 function isKey(value, object) {
24881 if (isArray(value)) {
24885 var type = typeof value;
24887 if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) {
24891 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
24894 * Checks if `value` is suitable for use as unique object key.
24897 * @param {*} value The value to check.
24898 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
24902 function isKeyable(value) {
24903 var type = typeof value;
24904 return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
24907 * Checks if `func` has its source masked.
24910 * @param {Function} func The function to check.
24911 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
24915 function isMasked(func) {
24916 return !!maskSrcKey && maskSrcKey in func;
24919 * Checks if `value` is likely a prototype object.
24922 * @param {*} value The value to check.
24923 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
24927 function isPrototype(value) {
24928 var Ctor = value && value.constructor,
24929 proto = typeof Ctor == 'function' && Ctor.prototype || objectProto;
24930 return value === proto;
24933 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
24936 * @param {*} value The value to check.
24937 * @returns {boolean} Returns `true` if `value` if suitable for strict
24938 * equality comparisons, else `false`.
24942 function isStrictComparable(value) {
24943 return value === value && !isObject(value);
24946 * A specialized version of `matchesProperty` for source values suitable
24947 * for strict equality comparisons, i.e. `===`.
24950 * @param {string} key The key of the property to get.
24951 * @param {*} srcValue The value to match.
24952 * @returns {Function} Returns the new spec function.
24956 function matchesStrictComparable(key, srcValue) {
24957 return function (object) {
24958 if (object == null) {
24962 return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
24966 * Converts `string` to a property path array.
24969 * @param {string} string The string to convert.
24970 * @returns {Array} Returns the property path array.
24974 var stringToPath = memoize(function (string) {
24975 string = toString(string);
24978 if (reLeadingDot.test(string)) {
24982 string.replace(rePropName, function (match, number, quote, string) {
24983 result.push(quote ? string.replace(reEscapeChar, '$1') : number || match);
24988 * Converts `value` to a string key if it's not a string or symbol.
24991 * @param {*} value The value to inspect.
24992 * @returns {string|symbol} Returns the key.
24995 function toKey(value) {
24996 if (typeof value == 'string' || isSymbol(value)) {
25000 var result = value + '';
25001 return result == '0' && 1 / value == -INFINITY ? '-0' : result;
25004 * Converts `func` to its source code.
25007 * @param {Function} func The function to process.
25008 * @returns {string} Returns the source code.
25012 function toSource(func) {
25013 if (func != null) {
25015 return funcToString.call(func);
25026 * This method is like `_.uniq` except that it accepts `iteratee` which is
25027 * invoked for each element in `array` to generate the criterion by which
25028 * uniqueness is computed. The iteratee is invoked with one argument: (value).
25034 * @param {Array} array The array to inspect.
25035 * @param {Function} [iteratee=_.identity]
25036 * The iteratee invoked per element.
25037 * @returns {Array} Returns the new duplicate free array.
25040 * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
25043 * // The `_.property` iteratee shorthand.
25044 * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
25045 * // => [{ 'x': 1 }, { 'x': 2 }]
25049 function uniqBy(array, iteratee) {
25050 return array && array.length ? baseUniq(array, baseIteratee(iteratee)) : [];
25053 * Creates a function that memoizes the result of `func`. If `resolver` is
25054 * provided, it determines the cache key for storing the result based on the
25055 * arguments provided to the memoized function. By default, the first argument
25056 * provided to the memoized function is used as the map cache key. The `func`
25057 * is invoked with the `this` binding of the memoized function.
25059 * **Note:** The cache is exposed as the `cache` property on the memoized
25060 * function. Its creation may be customized by replacing the `_.memoize.Cache`
25061 * constructor with one whose instances implement the
25062 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
25063 * method interface of `delete`, `get`, `has`, and `set`.
25068 * @category Function
25069 * @param {Function} func The function to have its output memoized.
25070 * @param {Function} [resolver] The function to resolve the cache key.
25071 * @returns {Function} Returns the new memoized function.
25074 * var object = { 'a': 1, 'b': 2 };
25075 * var other = { 'c': 3, 'd': 4 };
25077 * var values = _.memoize(_.values);
25088 * // Modify the result cache.
25089 * values.cache.set(object, ['a', 'b']);
25093 * // Replace `_.memoize.Cache`.
25094 * _.memoize.Cache = WeakMap;
25098 function memoize(func, resolver) {
25099 if (typeof func != 'function' || resolver && typeof resolver != 'function') {
25100 throw new TypeError(FUNC_ERROR_TEXT);
25103 var memoized = function memoized() {
25104 var args = arguments,
25105 key = resolver ? resolver.apply(this, args) : args[0],
25106 cache = memoized.cache;
25108 if (cache.has(key)) {
25109 return cache.get(key);
25112 var result = func.apply(this, args);
25113 memoized.cache = cache.set(key, result);
25117 memoized.cache = new (memoize.Cache || MapCache)();
25119 } // Assign cache to `_.memoize`.
25122 memoize.Cache = MapCache;
25125 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
25126 * comparison between two values to determine if they are equivalent.
25132 * @param {*} value The value to compare.
25133 * @param {*} other The other value to compare.
25134 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
25137 * var object = { 'a': 1 };
25138 * var other = { 'a': 1 };
25140 * _.eq(object, object);
25143 * _.eq(object, other);
25149 * _.eq('a', Object('a'));
25156 function eq(value, other) {
25157 return value === other || value !== value && other !== other;
25160 * Checks if `value` is likely an `arguments` object.
25166 * @param {*} value The value to check.
25167 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
25171 * _.isArguments(function() { return arguments; }());
25174 * _.isArguments([1, 2, 3]);
25179 function isArguments(value) {
25180 // Safari 8.1 makes `arguments.callee` enumerable in strict mode.
25181 return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
25184 * Checks if `value` is classified as an `Array` object.
25190 * @param {*} value The value to check.
25191 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
25194 * _.isArray([1, 2, 3]);
25197 * _.isArray(document.body.children);
25200 * _.isArray('abc');
25203 * _.isArray(_.noop);
25208 var isArray = Array.isArray;
25210 * Checks if `value` is array-like. A value is considered array-like if it's
25211 * not a function and has a `value.length` that's an integer greater than or
25212 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
25218 * @param {*} value The value to check.
25219 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
25222 * _.isArrayLike([1, 2, 3]);
25225 * _.isArrayLike(document.body.children);
25228 * _.isArrayLike('abc');
25231 * _.isArrayLike(_.noop);
25235 function isArrayLike(value) {
25236 return value != null && isLength(value.length) && !isFunction(value);
25239 * This method is like `_.isArrayLike` except that it also checks if `value`
25246 * @param {*} value The value to check.
25247 * @returns {boolean} Returns `true` if `value` is an array-like object,
25251 * _.isArrayLikeObject([1, 2, 3]);
25254 * _.isArrayLikeObject(document.body.children);
25257 * _.isArrayLikeObject('abc');
25260 * _.isArrayLikeObject(_.noop);
25265 function isArrayLikeObject(value) {
25266 return isObjectLike(value) && isArrayLike(value);
25269 * Checks if `value` is classified as a `Function` object.
25275 * @param {*} value The value to check.
25276 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
25282 * _.isFunction(/abc/);
25287 function isFunction(value) {
25288 // The use of `Object#toString` avoids issues with the `typeof` operator
25289 // in Safari 8-9 which returns 'object' for typed array and other constructors.
25290 var tag = isObject(value) ? objectToString.call(value) : '';
25291 return tag == funcTag || tag == genTag;
25294 * Checks if `value` is a valid array-like length.
25296 * **Note:** This method is loosely based on
25297 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
25303 * @param {*} value The value to check.
25304 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
25310 * _.isLength(Number.MIN_VALUE);
25313 * _.isLength(Infinity);
25321 function isLength(value) {
25322 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
25325 * Checks if `value` is the
25326 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
25327 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
25333 * @param {*} value The value to check.
25334 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
25340 * _.isObject([1, 2, 3]);
25343 * _.isObject(_.noop);
25346 * _.isObject(null);
25351 function isObject(value) {
25352 var type = typeof value;
25353 return !!value && (type == 'object' || type == 'function');
25356 * Checks if `value` is object-like. A value is object-like if it's not `null`
25357 * and has a `typeof` result of "object".
25363 * @param {*} value The value to check.
25364 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
25367 * _.isObjectLike({});
25370 * _.isObjectLike([1, 2, 3]);
25373 * _.isObjectLike(_.noop);
25376 * _.isObjectLike(null);
25381 function isObjectLike(value) {
25382 return !!value && typeof value == 'object';
25385 * Checks if `value` is classified as a `Symbol` primitive or object.
25391 * @param {*} value The value to check.
25392 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
25395 * _.isSymbol(Symbol.iterator);
25398 * _.isSymbol('abc');
25403 function isSymbol(value) {
25404 return typeof value == 'symbol' || isObjectLike(value) && objectToString.call(value) == symbolTag;
25407 * Checks if `value` is classified as a typed array.
25413 * @param {*} value The value to check.
25414 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
25417 * _.isTypedArray(new Uint8Array);
25420 * _.isTypedArray([]);
25425 var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
25427 * Converts `value` to a string. An empty string is returned for `null`
25428 * and `undefined` values. The sign of `-0` is preserved.
25434 * @param {*} value The value to process.
25435 * @returns {string} Returns the string.
25438 * _.toString(null);
25444 * _.toString([1, 2, 3]);
25448 function toString(value) {
25449 return value == null ? '' : baseToString(value);
25452 * Gets the value at `path` of `object`. If the resolved value is
25453 * `undefined`, the `defaultValue` is returned in its place.
25459 * @param {Object} object The object to query.
25460 * @param {Array|string} path The path of the property to get.
25461 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
25462 * @returns {*} Returns the resolved value.
25465 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
25467 * _.get(object, 'a[0].b.c');
25470 * _.get(object, ['a', '0', 'b', 'c']);
25473 * _.get(object, 'a.b.c', 'default');
25478 function get(object, path, defaultValue) {
25479 var result = object == null ? undefined : baseGet(object, path);
25480 return result === undefined ? defaultValue : result;
25483 * Checks if `path` is a direct or inherited property of `object`.
25489 * @param {Object} object The object to query.
25490 * @param {Array|string} path The path to check.
25491 * @returns {boolean} Returns `true` if `path` exists, else `false`.
25494 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
25496 * _.hasIn(object, 'a');
25499 * _.hasIn(object, 'a.b');
25502 * _.hasIn(object, ['a', 'b']);
25505 * _.hasIn(object, 'b');
25510 function hasIn(object, path) {
25511 return object != null && hasPath(object, path, baseHasIn);
25514 * Creates an array of the own enumerable property names of `object`.
25516 * **Note:** Non-object values are coerced to objects. See the
25517 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
25518 * for more details.
25524 * @param {Object} object The object to query.
25525 * @returns {Array} Returns the array of property names.
25533 * Foo.prototype.c = 3;
25536 * // => ['a', 'b'] (iteration order is not guaranteed)
25543 function keys(object) {
25544 return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
25547 * This method returns the first argument it receives.
25553 * @param {*} value Any value.
25554 * @returns {*} Returns `value`.
25557 * var object = { 'a': 1 };
25559 * console.log(_.identity(object) === object);
25564 function identity(value) {
25568 * This method returns `undefined`.
25576 * _.times(2, _.noop);
25577 * // => [undefined, undefined]
25581 function noop() {} // No operation performed.
25584 * Creates a function that returns the value at `path` of a given object.
25590 * @param {Array|string} path The path of the property to get.
25591 * @returns {Function} Returns the new accessor function.
25595 * { 'a': { 'b': 2 } },
25596 * { 'a': { 'b': 1 } }
25599 * _.map(objects, _.property('a.b'));
25602 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
25607 function property(path) {
25608 return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
25611 module.exports = uniqBy;
25614 var PENDING = 'pending';
25615 var SETTLED = 'settled';
25616 var FULFILLED = 'fulfilled';
25617 var REJECTED = 'rejected';
25619 var NOOP = function NOOP() {};
25621 var isNode = typeof global !== 'undefined' && typeof global.process !== 'undefined' && typeof global.process.emit === 'function';
25622 var asyncSetTimer = typeof setImmediate === 'undefined' ? setTimeout : setImmediate;
25623 var asyncQueue = [];
25626 function asyncFlush() {
25627 // run promise callbacks
25628 for (var i = 0; i < asyncQueue.length; i++) {
25629 asyncQueue[i][0](asyncQueue[i][1]);
25630 } // reset async asyncQueue
25634 asyncTimer = false;
25637 function asyncCall(callback, arg) {
25638 asyncQueue.push([callback, arg]);
25642 asyncSetTimer(asyncFlush, 0);
25646 function invokeResolver(resolver, promise) {
25647 function resolvePromise(value) {
25648 resolve$1(promise, value);
25651 function rejectPromise(reason) {
25652 reject(promise, reason);
25656 resolver(resolvePromise, rejectPromise);
25662 function invokeCallback(subscriber) {
25663 var owner = subscriber.owner;
25664 var settled = owner._state;
25665 var value = owner._data;
25666 var callback = subscriber[settled];
25667 var promise = subscriber.then;
25669 if (typeof callback === 'function') {
25670 settled = FULFILLED;
25673 value = callback(value);
25675 reject(promise, e);
25679 if (!handleThenable(promise, value)) {
25680 if (settled === FULFILLED) {
25681 resolve$1(promise, value);
25684 if (settled === REJECTED) {
25685 reject(promise, value);
25690 function handleThenable(promise, value) {
25694 if (promise === value) {
25695 throw new TypeError('A promises callback cannot return that same promise.');
25698 if (value && (typeof value === 'function' || typeof value === 'object')) {
25699 // then should be retrieved only once
25700 var then = value.then;
25702 if (typeof then === 'function') {
25703 then.call(value, function (val) {
25707 if (value === val) {
25708 fulfill(promise, val);
25710 resolve$1(promise, val);
25713 }, function (reason) {
25716 reject(promise, reason);
25724 reject(promise, e);
25733 function resolve$1(promise, value) {
25734 if (promise === value || !handleThenable(promise, value)) {
25735 fulfill(promise, value);
25739 function fulfill(promise, value) {
25740 if (promise._state === PENDING) {
25741 promise._state = SETTLED;
25742 promise._data = value;
25743 asyncCall(publishFulfillment, promise);
25747 function reject(promise, reason) {
25748 if (promise._state === PENDING) {
25749 promise._state = SETTLED;
25750 promise._data = reason;
25751 asyncCall(publishRejection, promise);
25755 function publish(promise) {
25756 promise._then = promise._then.forEach(invokeCallback);
25759 function publishFulfillment(promise) {
25760 promise._state = FULFILLED;
25764 function publishRejection(promise) {
25765 promise._state = REJECTED;
25768 if (!promise._handled && isNode) {
25769 global.process.emit('unhandledRejection', promise._data, promise);
25773 function notifyRejectionHandled(promise) {
25774 global.process.emit('rejectionHandled', promise);
25781 function Promise$1(resolver) {
25782 if (typeof resolver !== 'function') {
25783 throw new TypeError('Promise resolver ' + resolver + ' is not a function');
25786 if (this instanceof Promise$1 === false) {
25787 throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.');
25791 invokeResolver(resolver, this);
25794 Promise$1.prototype = {
25795 constructor: Promise$1,
25800 then: function then(onFulfillment, onRejection) {
25803 then: new this.constructor(NOOP),
25804 fulfilled: onFulfillment,
25805 rejected: onRejection
25808 if ((onRejection || onFulfillment) && !this._handled) {
25809 this._handled = true;
25811 if (this._state === REJECTED && isNode) {
25812 asyncCall(notifyRejectionHandled, this);
25816 if (this._state === FULFILLED || this._state === REJECTED) {
25817 // already resolved, call callback async
25818 asyncCall(invokeCallback, subscriber);
25821 this._then.push(subscriber);
25824 return subscriber.then;
25826 catch: function _catch(onRejection) {
25827 return this.then(null, onRejection);
25831 Promise$1.all = function (promises) {
25832 if (!Array.isArray(promises)) {
25833 throw new TypeError('You must pass an array to Promise.all().');
25836 return new Promise$1(function (resolve, reject) {
25840 function resolver(index) {
25842 return function (value) {
25843 results[index] = value;
25845 if (! --remaining) {
25851 for (var i = 0, promise; i < promises.length; i++) {
25852 promise = promises[i];
25854 if (promise && typeof promise.then === 'function') {
25855 promise.then(resolver(i), reject);
25857 results[i] = promise;
25867 Promise$1.race = function (promises) {
25868 if (!Array.isArray(promises)) {
25869 throw new TypeError('You must pass an array to Promise.race().');
25872 return new Promise$1(function (resolve, reject) {
25873 for (var i = 0, promise; i < promises.length; i++) {
25874 promise = promises[i];
25876 if (promise && typeof promise.then === 'function') {
25877 promise.then(resolve, reject);
25885 Promise$1.resolve = function (value) {
25886 if (value && typeof value === 'object' && value.constructor === Promise$1) {
25890 return new Promise$1(function (resolve) {
25895 Promise$1.reject = function (reason) {
25896 return new Promise$1(function (resolve, reject) {
25901 var pinkie = Promise$1;
25903 var pinkiePromise = typeof Promise === 'function' ? Promise : pinkie;
25905 var arrayUniq = createCommonjsModule(function (module) {
25906 // 1 - no Set type is defined
25908 function uniqNoSet(arr) {
25911 for (var i = 0; i < arr.length; i++) {
25912 if (ret.indexOf(arr[i]) === -1) {
25918 } // 2 - a simple Set type is defined
25921 function uniqSet(arr) {
25922 var seen = new Set();
25923 return arr.filter(function (el) {
25924 if (!seen.has(el)) {
25931 } // 3 - a standard Set type is defined and it has a forEach method
25934 function uniqSetWithForEach(arr) {
25936 new Set(arr).forEach(function (el) {
25940 } // V8 currently has a broken implementation
25941 // https://github.com/joyent/node/issues/8449
25944 function doesForEachActuallyWork() {
25946 new Set([true]).forEach(function (el) {
25949 return ret === true;
25952 if ('Set' in global) {
25953 if (typeof Set.prototype.forEach === 'function' && doesForEachActuallyWork()) {
25954 module.exports = uniqSetWithForEach;
25956 module.exports = uniqSet;
25959 module.exports = uniqNoSet;
25963 var arrayUnion = function arrayUnion() {
25964 return arrayUniq([].concat.apply([], arguments));
25972 /* eslint-disable no-unused-vars */
25974 var getOwnPropertySymbols = Object.getOwnPropertySymbols;
25975 var hasOwnProperty$2 = Object.prototype.hasOwnProperty;
25976 var propIsEnumerable = Object.prototype.propertyIsEnumerable;
25978 function toObject(val) {
25979 if (val === null || val === undefined) {
25980 throw new TypeError('Object.assign cannot be called with null or undefined');
25983 return Object(val);
25986 function shouldUseNative() {
25988 if (!Object.assign) {
25990 } // Detect buggy property enumeration order in older V8 versions.
25991 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
25994 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
25998 if (Object.getOwnPropertyNames(test1)[0] === '5') {
26000 } // https://bugs.chromium.org/p/v8/issues/detail?id=3056
26005 for (var i = 0; i < 10; i++) {
26006 test2['_' + String.fromCharCode(i)] = i;
26009 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
26013 if (order2.join('') !== '0123456789') {
26015 } // https://bugs.chromium.org/p/v8/issues/detail?id=3056
26019 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
26020 test3[letter] = letter;
26023 if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') {
26029 // We don't expect any of the above to throw, but better to be safe.
26034 var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
26036 var to = toObject(target);
26039 for (var s = 1; s < arguments.length; s++) {
26040 from = Object(arguments[s]);
26042 for (var key in from) {
26043 if (hasOwnProperty$2.call(from, key)) {
26044 to[key] = from[key];
26048 if (getOwnPropertySymbols) {
26049 symbols = getOwnPropertySymbols(from);
26051 for (var i = 0; i < symbols.length; i++) {
26052 if (propIsEnumerable.call(from, symbols[i])) {
26053 to[symbols[i]] = from[symbols[i]];
26063 // Permission is hereby granted, free of charge, to any person obtaining a
26064 // copy of this software and associated documentation files (the
26065 // "Software"), to deal in the Software without restriction, including
26066 // without limitation the rights to use, copy, modify, merge, publish,
26067 // distribute, sublicense, and/or sell copies of the Software, and to permit
26068 // persons to whom the Software is furnished to do so, subject to the
26069 // following conditions:
26071 // The above copyright notice and this permission notice shall be included
26072 // in all copies or substantial portions of the Software.
26074 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
26075 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26076 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
26077 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
26078 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
26079 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
26080 // USE OR OTHER DEALINGS IN THE SOFTWARE.
26082 var isWindows = process.platform === 'win32'; // JavaScript implementation of realpath, ported from node pre-v6
26084 var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
26086 function rethrow() {
26087 // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and
26088 // is fairly slow to generate.
26092 var backtrace = new Error();
26093 callback = debugCallback;
26094 } else callback = missingCallback;
26098 function debugCallback(err) {
26100 backtrace.message = err.message;
26102 missingCallback(err);
26106 function missingCallback(err) {
26108 if (process.throwDeprecation) throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs
26109 else if (!process.noDeprecation) {
26110 var msg = 'fs: missing callback ' + (err.stack || err.message);
26111 if (process.traceDeprecation) console.trace(msg);else console.error(msg);
26117 function maybeCallback(cb) {
26118 return typeof cb === 'function' ? cb : rethrow();
26121 var normalize$3 = path$2.normalize; // Regexp that finds the next partion of a (partial) path
26122 // result is [base_with_slash, base], e.g. ['somedir/', 'somedir']
26125 var nextPartRe = /(.*?)(?:[\/\\]+|$)/g;
26127 var nextPartRe = /(.*?)(?:[\/]+|$)/g;
26128 } // Regex to find the device root, including trailing slash. E.g. 'c:\\'.
26132 var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/;
26134 var splitRootRe = /^[\/]*/;
26137 var realpathSync = function realpathSync(p, cache) {
26138 // make p is absolute
26139 p = path$2.resolve(p);
26141 if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
26147 knownHard = {}; // current character position in p
26149 var pos; // the partial path so far, including a trailing slash if any
26151 var current; // the partial path without a trailing slash (except when pointing at a root)
26153 var base; // the partial path scanned in the previous round, with slash
26160 var m = splitRootRe.exec(p);
26164 previous = ''; // On windows, check that the root exists. On unix there is no need.
26166 if (isWindows && !knownHard[base]) {
26167 fs$1.lstatSync(base);
26168 knownHard[base] = true;
26170 } // walk down the path, swapping out linked pathparts for their real
26172 // NB: p.length changes.
26175 while (pos < p.length) {
26176 // find the next part
26177 nextPartRe.lastIndex = pos;
26178 var result = nextPartRe.exec(p);
26179 previous = current;
26180 current += result[0];
26181 base = previous + result[1];
26182 pos = nextPartRe.lastIndex; // continue if not a symlink
26184 if (knownHard[base] || cache && cache[base] === base) {
26190 if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
26191 // some known symbolic link. no need to stat again.
26192 resolvedLink = cache[base];
26194 var stat = fs$1.lstatSync(base);
26196 if (!stat.isSymbolicLink()) {
26197 knownHard[base] = true;
26198 if (cache) cache[base] = base;
26200 } // read the link if it wasn't read before
26201 // dev/ino always return 0 on windows, so skip the check.
26204 var linkTarget = null;
26207 var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
26209 if (seenLinks.hasOwnProperty(id)) {
26210 linkTarget = seenLinks[id];
26214 if (linkTarget === null) {
26215 fs$1.statSync(base);
26216 linkTarget = fs$1.readlinkSync(base);
26219 resolvedLink = path$2.resolve(previous, linkTarget); // track this, if given a cache.
26221 if (cache) cache[base] = resolvedLink;
26222 if (!isWindows) seenLinks[id] = linkTarget;
26223 } // resolve the link, then start over
26226 p = path$2.resolve(resolvedLink, p.slice(pos));
26230 if (cache) cache[original] = p;
26234 var realpath = function realpath(p, cache, cb) {
26235 if (typeof cb !== 'function') {
26236 cb = maybeCallback(cache);
26238 } // make p is absolute
26241 p = path$2.resolve(p);
26243 if (cache && Object.prototype.hasOwnProperty.call(cache, p)) {
26244 return process.nextTick(cb.bind(null, null, cache[p]));
26249 knownHard = {}; // current character position in p
26251 var pos; // the partial path so far, including a trailing slash if any
26253 var current; // the partial path without a trailing slash (except when pointing at a root)
26255 var base; // the partial path scanned in the previous round, with slash
26262 var m = splitRootRe.exec(p);
26266 previous = ''; // On windows, check that the root exists. On unix there is no need.
26268 if (isWindows && !knownHard[base]) {
26269 fs$1.lstat(base, function (err) {
26270 if (err) return cb(err);
26271 knownHard[base] = true;
26275 process.nextTick(LOOP);
26277 } // walk down the path, swapping out linked pathparts for their real
26282 // stop if scanned past end of path
26283 if (pos >= p.length) {
26284 if (cache) cache[original] = p;
26285 return cb(null, p);
26286 } // find the next part
26289 nextPartRe.lastIndex = pos;
26290 var result = nextPartRe.exec(p);
26291 previous = current;
26292 current += result[0];
26293 base = previous + result[1];
26294 pos = nextPartRe.lastIndex; // continue if not a symlink
26296 if (knownHard[base] || cache && cache[base] === base) {
26297 return process.nextTick(LOOP);
26300 if (cache && Object.prototype.hasOwnProperty.call(cache, base)) {
26301 // known symbolic link. no need to stat again.
26302 return gotResolvedLink(cache[base]);
26305 return fs$1.lstat(base, gotStat);
26308 function gotStat(err, stat) {
26309 if (err) return cb(err); // if not a symlink, skip to the next path part
26311 if (!stat.isSymbolicLink()) {
26312 knownHard[base] = true;
26313 if (cache) cache[base] = base;
26314 return process.nextTick(LOOP);
26315 } // stat & read the link if not read before
26316 // call gotTarget as soon as the link target is known
26317 // dev/ino always return 0 on windows, so skip the check.
26321 var id = stat.dev.toString(32) + ':' + stat.ino.toString(32);
26323 if (seenLinks.hasOwnProperty(id)) {
26324 return gotTarget(null, seenLinks[id], base);
26328 fs$1.stat(base, function (err) {
26329 if (err) return cb(err);
26330 fs$1.readlink(base, function (err, target) {
26331 if (!isWindows) seenLinks[id] = target;
26332 gotTarget(err, target);
26337 function gotTarget(err, target, base) {
26338 if (err) return cb(err);
26339 var resolvedLink = path$2.resolve(previous, target);
26340 if (cache) cache[base] = resolvedLink;
26341 gotResolvedLink(resolvedLink);
26344 function gotResolvedLink(resolvedLink) {
26345 // resolve the link, then start over
26346 p = path$2.resolve(resolvedLink, p.slice(pos));
26352 realpathSync: realpathSync,
26356 var fs_realpath = realpath$1;
26357 realpath$1.realpath = realpath$1;
26358 realpath$1.sync = realpathSync$1;
26359 realpath$1.realpathSync = realpathSync$1;
26360 realpath$1.monkeypatch = monkeypatch;
26361 realpath$1.unmonkeypatch = unmonkeypatch;
26362 var origRealpath = fs$1.realpath;
26363 var origRealpathSync = fs$1.realpathSync;
26364 var version$2 = process.version;
26365 var ok = /^v[0-5]\./.test(version$2);
26367 function newError(er) {
26368 return er && er.syscall === 'realpath' && (er.code === 'ELOOP' || er.code === 'ENOMEM' || er.code === 'ENAMETOOLONG');
26371 function realpath$1(p, cache, cb) {
26373 return origRealpath(p, cache, cb);
26376 if (typeof cache === 'function') {
26381 origRealpath(p, cache, function (er, result) {
26382 if (newError(er)) {
26383 old.realpath(p, cache, cb);
26390 function realpathSync$1(p, cache) {
26392 return origRealpathSync(p, cache);
26396 return origRealpathSync(p, cache);
26398 if (newError(er)) {
26399 return old.realpathSync(p, cache);
26406 function monkeypatch() {
26407 fs$1.realpath = realpath$1;
26408 fs$1.realpathSync = realpathSync$1;
26411 function unmonkeypatch() {
26412 fs$1.realpath = origRealpath;
26413 fs$1.realpathSync = origRealpathSync;
26416 var inherits_browser = createCommonjsModule(function (module) {
26417 if (typeof Object.create === 'function') {
26418 // implementation from standard node.js 'util' module
26419 module.exports = function inherits(ctor, superCtor) {
26421 ctor.super_ = superCtor;
26422 ctor.prototype = Object.create(superCtor.prototype, {
26433 // old school shim for old browsers
26434 module.exports = function inherits(ctor, superCtor) {
26436 ctor.super_ = superCtor;
26438 var TempCtor = function TempCtor() {};
26440 TempCtor.prototype = superCtor.prototype;
26441 ctor.prototype = new TempCtor();
26442 ctor.prototype.constructor = ctor;
26448 var inherits = createCommonjsModule(function (module) {
26451 /* istanbul ignore next */
26453 if (typeof util.inherits !== 'function') throw '';
26454 module.exports = util.inherits;
26456 /* istanbul ignore next */
26457 module.exports = inherits_browser;
26461 function posix(path) {
26462 return path.charAt(0) === '/';
26465 function win32(path) {
26466 // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56
26467 var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/;
26468 var result = splitDeviceRe.exec(path);
26469 var device = result[1] || '';
26470 var isUnc = Boolean(device && device.charAt(1) !== ':'); // UNC paths are always absolute
26472 return Boolean(result[2] || isUnc);
26475 var pathIsAbsolute = process.platform === 'win32' ? win32 : posix;
26476 var posix_1 = posix;
26477 var win32_1 = win32;
26478 pathIsAbsolute.posix = posix_1;
26479 pathIsAbsolute.win32 = win32_1;
26481 var alphasort_1 = alphasort;
26482 var alphasorti_1 = alphasorti;
26483 var setopts_1 = setopts;
26484 var ownProp_1 = ownProp;
26485 var makeAbs_1 = makeAbs;
26486 var finish_1 = finish;
26488 var isIgnored_1 = isIgnored;
26489 var childrenIgnored_1 = childrenIgnored;
26491 function ownProp(obj, field) {
26492 return Object.prototype.hasOwnProperty.call(obj, field);
26495 var Minimatch$1 = minimatch_1.Minimatch;
26497 function alphasorti(a, b) {
26498 return a.toLowerCase().localeCompare(b.toLowerCase());
26501 function alphasort(a, b) {
26502 return a.localeCompare(b);
26505 function setupIgnores(self, options) {
26506 self.ignore = options.ignore || [];
26507 if (!Array.isArray(self.ignore)) self.ignore = [self.ignore];
26509 if (self.ignore.length) {
26510 self.ignore = self.ignore.map(ignoreMap);
26512 } // ignore patterns are always in dot:true mode.
26515 function ignoreMap(pattern) {
26516 var gmatcher = null;
26518 if (pattern.slice(-3) === '/**') {
26519 var gpattern = pattern.replace(/(\/\*\*)+$/, '');
26520 gmatcher = new Minimatch$1(gpattern, {
26526 matcher: new Minimatch$1(pattern, {
26533 function setopts(self, pattern, options) {
26534 if (!options) options = {}; // base-matching: just use globstar for that.
26536 if (options.matchBase && -1 === pattern.indexOf("/")) {
26537 if (options.noglobstar) {
26538 throw new Error("base matching requires globstar");
26541 pattern = "**/" + pattern;
26544 self.silent = !!options.silent;
26545 self.pattern = pattern;
26546 self.strict = options.strict !== false;
26547 self.realpath = !!options.realpath;
26548 self.realpathCache = options.realpathCache || Object.create(null);
26549 self.follow = !!options.follow;
26550 self.dot = !!options.dot;
26551 self.mark = !!options.mark;
26552 self.nodir = !!options.nodir;
26553 if (self.nodir) self.mark = true;
26554 self.sync = !!options.sync;
26555 self.nounique = !!options.nounique;
26556 self.nonull = !!options.nonull;
26557 self.nosort = !!options.nosort;
26558 self.nocase = !!options.nocase;
26559 self.stat = !!options.stat;
26560 self.noprocess = !!options.noprocess;
26561 self.absolute = !!options.absolute;
26562 self.maxLength = options.maxLength || Infinity;
26563 self.cache = options.cache || Object.create(null);
26564 self.statCache = options.statCache || Object.create(null);
26565 self.symlinks = options.symlinks || Object.create(null);
26566 setupIgnores(self, options);
26567 self.changedCwd = false;
26568 var cwd = process.cwd();
26569 if (!ownProp(options, "cwd")) self.cwd = cwd;else {
26570 self.cwd = path$2.resolve(options.cwd);
26571 self.changedCwd = self.cwd !== cwd;
26573 self.root = options.root || path$2.resolve(self.cwd, "/");
26574 self.root = path$2.resolve(self.root);
26575 if (process.platform === "win32") self.root = self.root.replace(/\\/g, "/"); // TODO: is an absolute `cwd` supposed to be resolved against `root`?
26576 // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
26578 self.cwdAbs = pathIsAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd);
26579 if (process.platform === "win32") self.cwdAbs = self.cwdAbs.replace(/\\/g, "/");
26580 self.nomount = !!options.nomount; // disable comments and negation in Minimatch.
26581 // Note that they are not supported in Glob itself anyway.
26583 options.nonegate = true;
26584 options.nocomment = true;
26585 self.minimatch = new Minimatch$1(pattern, options);
26586 self.options = self.minimatch.options;
26589 function finish(self) {
26590 var nou = self.nounique;
26591 var all = nou ? [] : Object.create(null);
26593 for (var i = 0, l = self.matches.length; i < l; i++) {
26594 var matches = self.matches[i];
26596 if (!matches || Object.keys(matches).length === 0) {
26598 // do like the shell, and spit out the literal glob
26599 var literal = self.minimatch.globSet[i];
26600 if (nou) all.push(literal);else all[literal] = true;
26604 var m = Object.keys(matches);
26605 if (nou) all.push.apply(all, m);else m.forEach(function (m) {
26611 if (!nou) all = Object.keys(all);
26612 if (!self.nosort) all = all.sort(self.nocase ? alphasorti : alphasort); // at *some* point we statted all of these
26615 for (var i = 0; i < all.length; i++) {
26616 all[i] = self._mark(all[i]);
26620 all = all.filter(function (e) {
26621 var notDir = !/\/$/.test(e);
26622 var c = self.cache[e] || self.cache[makeAbs(self, e)];
26623 if (notDir && c) notDir = c !== 'DIR' && !Array.isArray(c);
26629 if (self.ignore.length) all = all.filter(function (m) {
26630 return !isIgnored(self, m);
26635 function mark(self, p) {
26636 var abs = makeAbs(self, p);
26637 var c = self.cache[abs];
26641 var isDir = c === 'DIR' || Array.isArray(c);
26642 var slash = p.slice(-1) === '/';
26643 if (isDir && !slash) m += '/';else if (!isDir && slash) m = m.slice(0, -1);
26646 var mabs = makeAbs(self, m);
26647 self.statCache[mabs] = self.statCache[abs];
26648 self.cache[mabs] = self.cache[abs];
26653 } // lotta situps...
26656 function makeAbs(self, f) {
26659 if (f.charAt(0) === '/') {
26660 abs = path$2.join(self.root, f);
26661 } else if (pathIsAbsolute(f) || f === '') {
26663 } else if (self.changedCwd) {
26664 abs = path$2.resolve(self.cwd, f);
26666 abs = path$2.resolve(f);
26669 if (process.platform === 'win32') abs = abs.replace(/\\/g, '/');
26671 } // Return true, if pattern ends with globstar '**', for the accompanying parent directory.
26672 // Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
26675 function isIgnored(self, path) {
26676 if (!self.ignore.length) return false;
26677 return self.ignore.some(function (item) {
26678 return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path));
26682 function childrenIgnored(self, path) {
26683 if (!self.ignore.length) return false;
26684 return self.ignore.some(function (item) {
26685 return !!(item.gmatcher && item.gmatcher.match(path));
26690 alphasort: alphasort_1,
26691 alphasorti: alphasorti_1,
26692 setopts: setopts_1,
26693 ownProp: ownProp_1,
26694 makeAbs: makeAbs_1,
26697 isIgnored: isIgnored_1,
26698 childrenIgnored: childrenIgnored_1
26701 var sync$1 = globSync;
26702 globSync.GlobSync = GlobSync;
26703 var setopts$1 = common$2.setopts;
26704 var ownProp$1 = common$2.ownProp;
26705 var childrenIgnored$1 = common$2.childrenIgnored;
26706 var isIgnored$1 = common$2.isIgnored;
26708 function globSync(pattern, options) {
26709 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');
26710 return new GlobSync(pattern, options).found;
26713 function GlobSync(pattern, options) {
26714 if (!pattern) throw new Error('must provide pattern');
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 if (!(this instanceof GlobSync)) return new GlobSync(pattern, options);
26717 setopts$1(this, pattern, options);
26718 if (this.noprocess) return this;
26719 var n = this.minimatch.set.length;
26720 this.matches = new Array(n);
26722 for (var i = 0; i < n; i++) {
26723 this._process(this.minimatch.set[i], i, false);
26729 GlobSync.prototype._finish = function () {
26730 assert$1(this instanceof GlobSync);
26732 if (this.realpath) {
26734 this.matches.forEach(function (matchset, index) {
26735 var set = self.matches[index] = Object.create(null);
26737 for (var p in matchset) {
26739 p = self._makeAbs(p);
26740 var real = fs_realpath.realpathSync(p, self.realpathCache);
26743 if (er.syscall === 'stat') set[self._makeAbs(p)] = true;else throw er;
26749 common$2.finish(this);
26752 GlobSync.prototype._process = function (pattern, index, inGlobStar) {
26753 assert$1(this instanceof GlobSync); // Get the first [n] parts of pattern that are all strings.
26757 while (typeof pattern[n] === 'string') {
26759 } // now n is the index of the first one that is *not* a string.
26760 // See if there's anything else
26766 // if not, then this is rather simple
26767 case pattern.length:
26768 this._processSimple(pattern.join('/'), index);
26773 // pattern *starts* with some non-trivial item.
26774 // going to readdir(cwd), but not include the prefix in matches.
26779 // pattern has some string bits in the front.
26780 // whatever it starts with, whether that's 'absolute' like /foo/bar,
26781 // or 'relative' like '../baz'
26782 prefix = pattern.slice(0, n).join('/');
26786 var remain = pattern.slice(n); // get the list of entries.
26789 if (prefix === null) read = '.';else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
26790 if (!prefix || !pathIsAbsolute(prefix)) prefix = '/' + prefix;
26792 } else read = prefix;
26794 var abs = this._makeAbs(read); //if ignored, skip processing
26797 if (childrenIgnored$1(this, read)) return;
26798 var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
26799 if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar);else this._processReaddir(prefix, read, abs, remain, index, inGlobStar);
26802 GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
26803 var entries = this._readdir(abs, inGlobStar); // if the abs isn't a dir, then nothing can match!
26806 if (!entries) return; // It will only match dot entries if it starts with a dot, or if
26807 // dot is set. Stuff like @(.foo|.bar) isn't allowed.
26809 var pn = remain[0];
26810 var negate = !!this.minimatch.negate;
26811 var rawGlob = pn._glob;
26812 var dotOk = this.dot || rawGlob.charAt(0) === '.';
26813 var matchedEntries = [];
26815 for (var i = 0; i < entries.length; i++) {
26816 var e = entries[i];
26818 if (e.charAt(0) !== '.' || dotOk) {
26821 if (negate && !prefix) {
26827 if (m) matchedEntries.push(e);
26831 var len = matchedEntries.length; // If there are no matched entries, then nothing matches.
26833 if (len === 0) return; // if this is the last remaining pattern bit, then no need for
26834 // an additional stat *unless* the user has specified mark or
26835 // stat explicitly. We know they exist, since readdir returned
26838 if (remain.length === 1 && !this.mark && !this.stat) {
26839 if (!this.matches[index]) this.matches[index] = Object.create(null);
26841 for (var i = 0; i < len; i++) {
26842 var e = matchedEntries[i];
26845 if (prefix.slice(-1) !== '/') e = prefix + '/' + e;else e = prefix + e;
26848 if (e.charAt(0) === '/' && !this.nomount) {
26849 e = path$2.join(this.root, e);
26852 this._emitMatch(index, e);
26853 } // This was the last one, and no stats were needed
26857 } // now test all matched entries as stand-ins for that part
26863 for (var i = 0; i < len; i++) {
26864 var e = matchedEntries[i];
26866 if (prefix) newPattern = [prefix, e];else newPattern = [e];
26868 this._process(newPattern.concat(remain), index, inGlobStar);
26872 GlobSync.prototype._emitMatch = function (index, e) {
26873 if (isIgnored$1(this, e)) return;
26875 var abs = this._makeAbs(e);
26877 if (this.mark) e = this._mark(e);
26879 if (this.absolute) {
26883 if (this.matches[index][e]) return;
26886 var c = this.cache[abs];
26887 if (c === 'DIR' || Array.isArray(c)) return;
26890 this.matches[index][e] = true;
26891 if (this.stat) this._stat(e);
26894 GlobSync.prototype._readdirInGlobStar = function (abs) {
26895 // follow all symlinked directories forever
26896 // just proceed as if this is a non-globstar situation
26897 if (this.follow) return this._readdir(abs, false);
26902 lstat = fs$1.lstatSync(abs);
26904 if (er.code === 'ENOENT') {
26905 // lstat failed, doesn't exist
26910 var isSym = lstat && lstat.isSymbolicLink();
26911 this.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file.
26912 // don't bother doing a readdir in that case.
26914 if (!isSym && lstat && !lstat.isDirectory()) this.cache[abs] = 'FILE';else entries = this._readdir(abs, false);
26918 GlobSync.prototype._readdir = function (abs, inGlobStar) {
26919 if (inGlobStar && !ownProp$1(this.symlinks, abs)) return this._readdirInGlobStar(abs);
26921 if (ownProp$1(this.cache, abs)) {
26922 var c = this.cache[abs];
26923 if (!c || c === 'FILE') return null;
26924 if (Array.isArray(c)) return c;
26928 return this._readdirEntries(abs, fs$1.readdirSync(abs));
26930 this._readdirError(abs, er);
26936 GlobSync.prototype._readdirEntries = function (abs, entries) {
26937 // if we haven't asked to stat everything, then just
26938 // assume that everything in there exists, so we can avoid
26939 // having to stat it a second time.
26940 if (!this.mark && !this.stat) {
26941 for (var i = 0; i < entries.length; i++) {
26942 var e = entries[i];
26943 if (abs === '/') e = abs + e;else e = abs + '/' + e;
26944 this.cache[e] = true;
26948 this.cache[abs] = entries; // mark and cache dir-ness
26953 GlobSync.prototype._readdirError = function (f, er) {
26954 // handle errors, and cache the information
26956 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
26959 // totally normal. means it *does* exist.
26960 var abs = this._makeAbs(f);
26962 this.cache[abs] = 'FILE';
26964 if (abs === this.cwdAbs) {
26965 var error = new Error(er.code + ' invalid cwd ' + this.cwd);
26966 error.path = this.cwd;
26967 error.code = er.code;
26973 case 'ENOENT': // not terribly unusual
26976 case 'ENAMETOOLONG':
26978 this.cache[this._makeAbs(f)] = false;
26982 // some unusual error. Treat as failure.
26983 this.cache[this._makeAbs(f)] = false;
26984 if (this.strict) throw er;
26985 if (!this.silent) console.error('glob error', er);
26990 GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
26991 var entries = this._readdir(abs, inGlobStar); // no entries means not a dir, so it can never have matches
26992 // foo.txt/** doesn't match foo.txt
26995 if (!entries) return; // test without the globstar, and with every child both below
26996 // and replacing the globstar.
26998 var remainWithoutGlobStar = remain.slice(1);
26999 var gspref = prefix ? [prefix] : [];
27000 var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state
27002 this._process(noGlobStar, index, false);
27004 var len = entries.length;
27005 var isSym = this.symlinks[abs]; // If it's a symlink, and we're in a globstar, then stop
27007 if (isSym && inGlobStar) return;
27009 for (var i = 0; i < len; i++) {
27010 var e = entries[i];
27011 if (e.charAt(0) === '.' && !this.dot) continue; // these two cases enter the inGlobStar state
27013 var instead = gspref.concat(entries[i], remainWithoutGlobStar);
27015 this._process(instead, index, true);
27017 var below = gspref.concat(entries[i], remain);
27019 this._process(below, index, true);
27023 GlobSync.prototype._processSimple = function (prefix, index) {
27024 // XXX review this. Shouldn't it be doing the mounting etc
27025 // before doing stat? kinda weird?
27026 var exists = this._stat(prefix);
27028 if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results
27030 if (!exists) return;
27032 if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
27033 var trail = /[\/\\]$/.test(prefix);
27035 if (prefix.charAt(0) === '/') {
27036 prefix = path$2.join(this.root, prefix);
27038 prefix = path$2.resolve(this.root, prefix);
27039 if (trail) prefix += '/';
27043 if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match
27045 this._emitMatch(index, prefix);
27046 }; // Returns either 'DIR', 'FILE', or false
27049 GlobSync.prototype._stat = function (f) {
27050 var abs = this._makeAbs(f);
27052 var needDir = f.slice(-1) === '/';
27053 if (f.length > this.maxLength) return false;
27055 if (!this.stat && ownProp$1(this.cache, abs)) {
27056 var c = this.cache[abs];
27057 if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it
27059 if (!needDir || c === 'DIR') return c;
27060 if (needDir && c === 'FILE') return false; // otherwise we have to stat, because maybe c=true
27061 // if we know it exists, but not what it is.
27063 var stat = this.statCache[abs];
27069 lstat = fs$1.lstatSync(abs);
27071 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
27072 this.statCache[abs] = false;
27077 if (lstat && lstat.isSymbolicLink()) {
27079 stat = fs$1.statSync(abs);
27088 this.statCache[abs] = stat;
27090 if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE';
27091 this.cache[abs] = this.cache[abs] || c;
27092 if (needDir && c === 'FILE') return false;
27096 GlobSync.prototype._mark = function (p) {
27097 return common$2.mark(this, p);
27100 GlobSync.prototype._makeAbs = function (f) {
27101 return common$2.makeAbs(this, f);
27104 // Returns a wrapper function that returns a wrapped callback
27105 // The wrapper function should do some stuff, and return a
27106 // presumably different callback function.
27107 // This makes sure that own properties are retained, so that
27108 // decorations and such are not lost along the way.
27109 var wrappy_1 = wrappy;
27111 function wrappy(fn, cb) {
27112 if (fn && cb) return wrappy(fn)(cb);
27113 if (typeof fn !== 'function') throw new TypeError('need wrapper function');
27114 Object.keys(fn).forEach(function (k) {
27115 wrapper[k] = fn[k];
27119 function wrapper() {
27120 var args = new Array(arguments.length);
27122 for (var i = 0; i < args.length; i++) {
27123 args[i] = arguments[i];
27126 var ret = fn.apply(this, args);
27127 var cb = args[args.length - 1];
27129 if (typeof ret === 'function' && ret !== cb) {
27130 Object.keys(cb).forEach(function (k) {
27139 var once_1 = wrappy_1(once);
27140 var strict = wrappy_1(onceStrict);
27141 once.proto = once(function () {
27142 Object.defineProperty(Function.prototype, 'once', {
27143 value: function value() {
27148 Object.defineProperty(Function.prototype, 'onceStrict', {
27149 value: function value() {
27150 return onceStrict(this);
27156 function once(fn) {
27157 var f = function f() {
27158 if (f.called) return f.value;
27160 return f.value = fn.apply(this, arguments);
27167 function onceStrict(fn) {
27168 var f = function f() {
27169 if (f.called) throw new Error(f.onceError);
27171 return f.value = fn.apply(this, arguments);
27174 var name = fn.name || 'Function wrapped with `once`';
27175 f.onceError = name + " shouldn't be called more than once";
27179 once_1.strict = strict;
27181 var reqs = Object.create(null);
27182 var inflight_1 = wrappy_1(inflight);
27184 function inflight(key, cb) {
27186 reqs[key].push(cb);
27190 return makeres(key);
27194 function makeres(key) {
27195 return once_1(function RES() {
27196 var cbs = reqs[key];
27197 var len = cbs.length;
27198 var args = slice(arguments); // XXX It's somewhat ambiguous whether a new callback added in this
27199 // pass should be queued for later execution if something in the
27200 // list of callbacks throws, or if it should just be discarded.
27201 // However, it's such an edge case that it hardly matters, and either
27202 // choice is likely as surprising as the other.
27203 // As it happens, we do go ahead and schedule it for later execution.
27206 for (var i = 0; i < len; i++) {
27207 cbs[i].apply(null, args);
27210 if (cbs.length > len) {
27211 // added more in the interim.
27212 // de-zalgo, just in case, but don't call again.
27213 cbs.splice(0, len);
27214 process.nextTick(function () {
27215 RES.apply(null, args);
27224 function slice(args) {
27225 var length = args.length;
27228 for (var i = 0; i < length; i++) {
27229 array[i] = args[i];
27236 // 1. Get the minimatch set
27237 // 2. For each pattern in the set, PROCESS(pattern, false)
27238 // 3. Store matches per-set, then uniq them
27240 // PROCESS(pattern, inGlobStar)
27241 // Get the first [n] items from pattern that are all strings
27242 // Join these together. This is PREFIX.
27243 // If there is no more remaining, then stat(PREFIX) and
27244 // add to matches if it succeeds. END.
27246 // If inGlobStar and PREFIX is symlink and points to dir
27247 // set ENTRIES = []
27248 // else readdir(PREFIX) as ENTRIES
27252 // If pattern[n] is GLOBSTAR
27253 // // handle the case where the globstar match is empty
27254 // // by pruning it out, and testing the resulting pattern
27255 // PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
27256 // // handle other cases.
27257 // for ENTRY in ENTRIES (not dotfiles)
27258 // // attach globstar + tail onto the entry
27259 // // Mark that this entry is a globstar match
27260 // PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
27262 // else // not globstar
27263 // for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
27264 // Test ENTRY against pattern[n]
27265 // If fails, continue
27266 // If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
27269 // Cache all stats and readdirs results to minimize syscall. Since all
27270 // we ever care about is existence and directory-ness, we can just keep
27271 // `true` for files, and [children,...] for directories, or `false` for
27272 // things that don't exist.
27275 var EE = events$1.EventEmitter;
27276 var setopts$2 = common$2.setopts;
27277 var ownProp$2 = common$2.ownProp;
27278 var childrenIgnored$2 = common$2.childrenIgnored;
27279 var isIgnored$2 = common$2.isIgnored;
27281 function glob(pattern, options, cb) {
27282 if (typeof options === 'function') cb = options, options = {};
27283 if (!options) options = {};
27285 if (options.sync) {
27286 if (cb) throw new TypeError('callback provided to sync glob');
27287 return sync$1(pattern, options);
27290 return new Glob(pattern, options, cb);
27293 glob.sync = sync$1;
27294 var GlobSync$1 = glob.GlobSync = sync$1.GlobSync; // old api surface
27298 function extend(origin, add) {
27299 if (add === null || typeof add !== 'object') {
27303 var keys = Object.keys(add);
27304 var i = keys.length;
27307 origin[keys[i]] = add[keys[i]];
27313 glob.hasMagic = function (pattern, options_) {
27314 var options = extend({}, options_);
27315 options.noprocess = true;
27316 var g = new Glob(pattern, options);
27317 var set = g.minimatch.set;
27318 if (!pattern) return false;
27319 if (set.length > 1) return true;
27321 for (var j = 0; j < set[0].length; j++) {
27322 if (typeof set[0][j] !== 'string') return true;
27329 inherits(Glob, EE);
27331 function Glob(pattern, options, cb) {
27332 if (typeof options === 'function') {
27337 if (options && options.sync) {
27338 if (cb) throw new TypeError('callback provided to sync glob');
27339 return new GlobSync$1(pattern, options);
27342 if (!(this instanceof Glob)) return new Glob(pattern, options, cb);
27343 setopts$2(this, pattern, options);
27344 this._didRealPath = false; // process each pattern in the minimatch set
27346 var n = this.minimatch.set.length; // The matches are stored as {<filename>: true,...} so that
27347 // duplicates are automagically pruned.
27348 // Later, we do an Object.keys() on these.
27349 // Keep them as a list so we can fill in when nonull is set.
27351 this.matches = new Array(n);
27353 if (typeof cb === 'function') {
27355 this.on('error', cb);
27356 this.on('end', function (matches) {
27362 this._processing = 0;
27363 this._emitQueue = [];
27364 this._processQueue = [];
27365 this.paused = false;
27366 if (this.noprocess) return this;
27367 if (n === 0) return done();
27370 for (var i = 0; i < n; i++) {
27371 this._process(this.minimatch.set[i], i, false, done);
27377 --self._processing;
27379 if (self._processing <= 0) {
27381 process.nextTick(function () {
27391 Glob.prototype._finish = function () {
27392 assert$1(this instanceof Glob);
27393 if (this.aborted) return;
27394 if (this.realpath && !this._didRealpath) return this._realpath();
27395 common$2.finish(this);
27396 this.emit('end', this.found);
27399 Glob.prototype._realpath = function () {
27400 if (this._didRealpath) return;
27401 this._didRealpath = true;
27402 var n = this.matches.length;
27403 if (n === 0) return this._finish();
27406 for (var i = 0; i < this.matches.length; i++) {
27407 this._realpathSet(i, next);
27411 if (--n === 0) self._finish();
27415 Glob.prototype._realpathSet = function (index, cb) {
27416 var matchset = this.matches[index];
27417 if (!matchset) return cb();
27418 var found = Object.keys(matchset);
27420 var n = found.length;
27421 if (n === 0) return cb();
27422 var set = this.matches[index] = Object.create(null);
27423 found.forEach(function (p, i) {
27424 // If there's a problem with the stat, then it means that
27425 // one or more of the links in the realpath couldn't be
27426 // resolved. just return the abs value in that case.
27427 p = self._makeAbs(p);
27428 fs_realpath.realpath(p, self.realpathCache, function (er, real) {
27429 if (!er) set[real] = true;else if (er.syscall === 'stat') set[p] = true;else self.emit('error', er); // srsly wtf right here
27432 self.matches[index] = set;
27439 Glob.prototype._mark = function (p) {
27440 return common$2.mark(this, p);
27443 Glob.prototype._makeAbs = function (f) {
27444 return common$2.makeAbs(this, f);
27447 Glob.prototype.abort = function () {
27448 this.aborted = true;
27449 this.emit('abort');
27452 Glob.prototype.pause = function () {
27453 if (!this.paused) {
27454 this.paused = true;
27455 this.emit('pause');
27459 Glob.prototype.resume = function () {
27461 this.emit('resume');
27462 this.paused = false;
27464 if (this._emitQueue.length) {
27465 var eq = this._emitQueue.slice(0);
27467 this._emitQueue.length = 0;
27469 for (var i = 0; i < eq.length; i++) {
27472 this._emitMatch(e[0], e[1]);
27476 if (this._processQueue.length) {
27477 var pq = this._processQueue.slice(0);
27479 this._processQueue.length = 0;
27481 for (var i = 0; i < pq.length; i++) {
27483 this._processing--;
27485 this._process(p[0], p[1], p[2], p[3]);
27491 Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
27492 assert$1(this instanceof Glob);
27493 assert$1(typeof cb === 'function');
27494 if (this.aborted) return;
27495 this._processing++;
27498 this._processQueue.push([pattern, index, inGlobStar, cb]);
27501 } //console.error('PROCESS %d', this._processing, pattern)
27502 // Get the first [n] parts of pattern that are all strings.
27507 while (typeof pattern[n] === 'string') {
27509 } // now n is the index of the first one that is *not* a string.
27510 // see if there's anything else
27516 // if not, then this is rather simple
27517 case pattern.length:
27518 this._processSimple(pattern.join('/'), index, cb);
27523 // pattern *starts* with some non-trivial item.
27524 // going to readdir(cwd), but not include the prefix in matches.
27529 // pattern has some string bits in the front.
27530 // whatever it starts with, whether that's 'absolute' like /foo/bar,
27531 // or 'relative' like '../baz'
27532 prefix = pattern.slice(0, n).join('/');
27536 var remain = pattern.slice(n); // get the list of entries.
27539 if (prefix === null) read = '.';else if (pathIsAbsolute(prefix) || pathIsAbsolute(pattern.join('/'))) {
27540 if (!prefix || !pathIsAbsolute(prefix)) prefix = '/' + prefix;
27542 } else read = prefix;
27544 var abs = this._makeAbs(read); //if ignored, skip _processing
27547 if (childrenIgnored$2(this, read)) return cb();
27548 var isGlobStar = remain[0] === minimatch_1.GLOBSTAR;
27549 if (isGlobStar) this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb);else this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb);
27552 Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
27555 this._readdir(abs, inGlobStar, function (er, entries) {
27556 return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
27560 Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
27561 // if the abs isn't a dir, then nothing can match!
27562 if (!entries) return cb(); // It will only match dot entries if it starts with a dot, or if
27563 // dot is set. Stuff like @(.foo|.bar) isn't allowed.
27565 var pn = remain[0];
27566 var negate = !!this.minimatch.negate;
27567 var rawGlob = pn._glob;
27568 var dotOk = this.dot || rawGlob.charAt(0) === '.';
27569 var matchedEntries = [];
27571 for (var i = 0; i < entries.length; i++) {
27572 var e = entries[i];
27574 if (e.charAt(0) !== '.' || dotOk) {
27577 if (negate && !prefix) {
27583 if (m) matchedEntries.push(e);
27585 } //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
27588 var len = matchedEntries.length; // If there are no matched entries, then nothing matches.
27590 if (len === 0) return cb(); // if this is the last remaining pattern bit, then no need for
27591 // an additional stat *unless* the user has specified mark or
27592 // stat explicitly. We know they exist, since readdir returned
27595 if (remain.length === 1 && !this.mark && !this.stat) {
27596 if (!this.matches[index]) this.matches[index] = Object.create(null);
27598 for (var i = 0; i < len; i++) {
27599 var e = matchedEntries[i];
27602 if (prefix !== '/') e = prefix + '/' + e;else e = prefix + e;
27605 if (e.charAt(0) === '/' && !this.nomount) {
27606 e = path$2.join(this.root, e);
27609 this._emitMatch(index, e);
27610 } // This was the last one, and no stats were needed
27614 } // now test all matched entries as stand-ins for that part
27620 for (var i = 0; i < len; i++) {
27621 var e = matchedEntries[i];
27624 if (prefix !== '/') e = prefix + '/' + e;else e = prefix + e;
27627 this._process([e].concat(remain), index, inGlobStar, cb);
27633 Glob.prototype._emitMatch = function (index, e) {
27634 if (this.aborted) return;
27635 if (isIgnored$2(this, e)) return;
27638 this._emitQueue.push([index, e]);
27643 var abs = pathIsAbsolute(e) ? e : this._makeAbs(e);
27644 if (this.mark) e = this._mark(e);
27645 if (this.absolute) e = abs;
27646 if (this.matches[index][e]) return;
27649 var c = this.cache[abs];
27650 if (c === 'DIR' || Array.isArray(c)) return;
27653 this.matches[index][e] = true;
27654 var st = this.statCache[abs];
27655 if (st) this.emit('stat', e, st);
27656 this.emit('match', e);
27659 Glob.prototype._readdirInGlobStar = function (abs, cb) {
27660 if (this.aborted) return; // follow all symlinked directories forever
27661 // just proceed as if this is a non-globstar situation
27663 if (this.follow) return this._readdir(abs, false, cb);
27664 var lstatkey = 'lstat\0' + abs;
27666 var lstatcb = inflight_1(lstatkey, lstatcb_);
27667 if (lstatcb) fs$1.lstat(abs, lstatcb);
27669 function lstatcb_(er, lstat) {
27670 if (er && er.code === 'ENOENT') return cb();
27671 var isSym = lstat && lstat.isSymbolicLink();
27672 self.symlinks[abs] = isSym; // If it's not a symlink or a dir, then it's definitely a regular file.
27673 // don't bother doing a readdir in that case.
27675 if (!isSym && lstat && !lstat.isDirectory()) {
27676 self.cache[abs] = 'FILE';
27678 } else self._readdir(abs, false, cb);
27682 Glob.prototype._readdir = function (abs, inGlobStar, cb) {
27683 if (this.aborted) return;
27684 cb = inflight_1('readdir\0' + abs + '\0' + inGlobStar, cb);
27685 if (!cb) return; //console.error('RD %j %j', +inGlobStar, abs)
27687 if (inGlobStar && !ownProp$2(this.symlinks, abs)) return this._readdirInGlobStar(abs, cb);
27689 if (ownProp$2(this.cache, abs)) {
27690 var c = this.cache[abs];
27691 if (!c || c === 'FILE') return cb();
27692 if (Array.isArray(c)) return cb(null, c);
27694 fs$1.readdir(abs, readdirCb(this, abs, cb));
27697 function readdirCb(self, abs, cb) {
27698 return function (er, entries) {
27699 if (er) self._readdirError(abs, er, cb);else self._readdirEntries(abs, entries, cb);
27703 Glob.prototype._readdirEntries = function (abs, entries, cb) {
27704 if (this.aborted) return; // if we haven't asked to stat everything, then just
27705 // assume that everything in there exists, so we can avoid
27706 // having to stat it a second time.
27708 if (!this.mark && !this.stat) {
27709 for (var i = 0; i < entries.length; i++) {
27710 var e = entries[i];
27711 if (abs === '/') e = abs + e;else e = abs + '/' + e;
27712 this.cache[e] = true;
27716 this.cache[abs] = entries;
27717 return cb(null, entries);
27720 Glob.prototype._readdirError = function (f, er, cb) {
27721 if (this.aborted) return; // handle errors, and cache the information
27724 case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
27727 // totally normal. means it *does* exist.
27728 var abs = this._makeAbs(f);
27730 this.cache[abs] = 'FILE';
27732 if (abs === this.cwdAbs) {
27733 var error = new Error(er.code + ' invalid cwd ' + this.cwd);
27734 error.path = this.cwd;
27735 error.code = er.code;
27736 this.emit('error', error);
27742 case 'ENOENT': // not terribly unusual
27745 case 'ENAMETOOLONG':
27747 this.cache[this._makeAbs(f)] = false;
27751 // some unusual error. Treat as failure.
27752 this.cache[this._makeAbs(f)] = false;
27755 this.emit('error', er); // If the error is handled, then we abort
27756 // if not, we threw out of here
27761 if (!this.silent) console.error('glob error', er);
27768 Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
27771 this._readdir(abs, inGlobStar, function (er, entries) {
27772 self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb);
27776 Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
27777 //console.error('pgs2', prefix, remain[0], entries)
27778 // no entries means not a dir, so it can never have matches
27779 // foo.txt/** doesn't match foo.txt
27780 if (!entries) return cb(); // test without the globstar, and with every child both below
27781 // and replacing the globstar.
27783 var remainWithoutGlobStar = remain.slice(1);
27784 var gspref = prefix ? [prefix] : [];
27785 var noGlobStar = gspref.concat(remainWithoutGlobStar); // the noGlobStar pattern exits the inGlobStar state
27787 this._process(noGlobStar, index, false, cb);
27789 var isSym = this.symlinks[abs];
27790 var len = entries.length; // If it's a symlink, and we're in a globstar, then stop
27792 if (isSym && inGlobStar) return cb();
27794 for (var i = 0; i < len; i++) {
27795 var e = entries[i];
27796 if (e.charAt(0) === '.' && !this.dot) continue; // these two cases enter the inGlobStar state
27798 var instead = gspref.concat(entries[i], remainWithoutGlobStar);
27800 this._process(instead, index, true, cb);
27802 var below = gspref.concat(entries[i], remain);
27804 this._process(below, index, true, cb);
27810 Glob.prototype._processSimple = function (prefix, index, cb) {
27811 // XXX review this. Shouldn't it be doing the mounting etc
27812 // before doing stat? kinda weird?
27815 this._stat(prefix, function (er, exists) {
27816 self._processSimple2(prefix, index, er, exists, cb);
27820 Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
27821 //console.error('ps2', prefix, exists)
27822 if (!this.matches[index]) this.matches[index] = Object.create(null); // If it doesn't exist, then just mark the lack of results
27824 if (!exists) return cb();
27826 if (prefix && pathIsAbsolute(prefix) && !this.nomount) {
27827 var trail = /[\/\\]$/.test(prefix);
27829 if (prefix.charAt(0) === '/') {
27830 prefix = path$2.join(this.root, prefix);
27832 prefix = path$2.resolve(this.root, prefix);
27833 if (trail) prefix += '/';
27837 if (process.platform === 'win32') prefix = prefix.replace(/\\/g, '/'); // Mark this as a match
27839 this._emitMatch(index, prefix);
27842 }; // Returns either 'DIR', 'FILE', or false
27845 Glob.prototype._stat = function (f, cb) {
27846 var abs = this._makeAbs(f);
27848 var needDir = f.slice(-1) === '/';
27849 if (f.length > this.maxLength) return cb();
27851 if (!this.stat && ownProp$2(this.cache, abs)) {
27852 var c = this.cache[abs];
27853 if (Array.isArray(c)) c = 'DIR'; // It exists, but maybe not how we need it
27855 if (!needDir || c === 'DIR') return cb(null, c);
27856 if (needDir && c === 'FILE') return cb(); // otherwise we have to stat, because maybe c=true
27857 // if we know it exists, but not what it is.
27859 var stat = this.statCache[abs];
27861 if (stat !== undefined) {
27862 if (stat === false) return cb(null, stat);else {
27863 var type = stat.isDirectory() ? 'DIR' : 'FILE';
27864 if (needDir && type === 'FILE') return cb();else return cb(null, type, stat);
27869 var statcb = inflight_1('stat\0' + abs, lstatcb_);
27870 if (statcb) fs$1.lstat(abs, statcb);
27872 function lstatcb_(er, lstat) {
27873 if (lstat && lstat.isSymbolicLink()) {
27874 // If it's a symlink, then treat it as the target, unless
27875 // the target does not exist, then treat it as a file.
27876 return fs$1.stat(abs, function (er, stat) {
27877 if (er) self._stat2(f, abs, null, lstat, cb);else self._stat2(f, abs, er, stat, cb);
27880 self._stat2(f, abs, er, lstat, cb);
27885 Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
27886 if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
27887 this.statCache[abs] = false;
27891 var needDir = f.slice(-1) === '/';
27892 this.statCache[abs] = stat;
27893 if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) return cb(null, false, stat);
27895 if (stat) c = stat.isDirectory() ? 'DIR' : 'FILE';
27896 this.cache[abs] = this.cache[abs] || c;
27897 if (needDir && c === 'FILE') return cb();
27898 return cb(null, c, stat);
27901 var pify_1 = createCommonjsModule(function (module) {
27903 var processFn = function processFn(fn, P, opts) {
27904 return function () {
27906 var args = new Array(arguments.length);
27908 for (var i = 0; i < arguments.length; i++) {
27909 args[i] = arguments[i];
27912 return new P(function (resolve, reject) {
27913 args.push(function (err, result) {
27916 } else if (opts.multiArgs) {
27917 var results = new Array(arguments.length - 1);
27919 for (var i = 1; i < arguments.length; i++) {
27920 results[i - 1] = arguments[i];
27928 fn.apply(that, args);
27933 var pify = module.exports = function (obj, P, opts) {
27934 if (typeof P !== 'function') {
27940 opts.exclude = opts.exclude || [/.+Sync$/];
27942 var filter = function filter(key) {
27943 var match = function match(pattern) {
27944 return typeof pattern === 'string' ? key === pattern : pattern.test(key);
27947 return opts.include ? opts.include.some(match) : !opts.exclude.some(match);
27950 var ret = typeof obj === 'function' ? function () {
27951 if (opts.excludeMain) {
27952 return obj.apply(this, arguments);
27955 return processFn(obj, P, opts).apply(this, arguments);
27957 return Object.keys(obj).reduce(function (ret, key) {
27959 ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x;
27967 var globP = pify_1(glob_1, pinkiePromise).bind(glob_1);
27969 function isNegative(pattern) {
27970 return pattern[0] === '!';
27973 function isString(value) {
27974 return typeof value === 'string';
27977 function assertPatternsInput(patterns) {
27978 if (!patterns.every(isString)) {
27979 throw new TypeError('patterns must be a string or an array of strings');
27983 function generateGlobTasks(patterns, opts) {
27984 patterns = [].concat(patterns);
27985 assertPatternsInput(patterns);
27986 var globTasks = [];
27987 opts = objectAssign({
27988 cache: Object.create(null),
27989 statCache: Object.create(null),
27990 realpathCache: Object.create(null),
27991 symlinks: Object.create(null),
27994 patterns.forEach(function (pattern, i) {
27995 if (isNegative(pattern)) {
27999 var ignore = patterns.slice(i).filter(isNegative).map(function (pattern) {
28000 return pattern.slice(1);
28004 opts: objectAssign({}, opts, {
28005 ignore: opts.ignore.concat(ignore)
28012 var globby = function globby(patterns, opts) {
28016 globTasks = generateGlobTasks(patterns, opts);
28018 return pinkiePromise.reject(err);
28021 return pinkiePromise.all(globTasks.map(function (task) {
28022 return globP(task.pattern, task.opts);
28023 })).then(function (paths) {
28024 return arrayUnion.apply(null, paths);
28028 var sync$2 = function sync(patterns, opts) {
28029 var globTasks = generateGlobTasks(patterns, opts);
28030 return globTasks.reduce(function (matches, task) {
28031 return arrayUnion(matches, glob_1.sync(task.pattern, task.opts));
28035 var generateGlobTasks_1 = generateGlobTasks;
28037 var hasMagic = function hasMagic(patterns, opts) {
28038 return [].concat(patterns).some(function (pattern) {
28039 return glob_1.hasMagic(pattern, opts);
28042 globby.sync = sync$2;
28043 globby.generateGlobTasks = generateGlobTasks_1;
28044 globby.hasMagic = hasMagic;
28046 var addLeadingComment$2 = utilShared.addLeadingComment,
28047 addTrailingComment$2 = utilShared.addTrailingComment,
28048 addDanglingComment$2 = utilShared.addDanglingComment;
28050 function handleOwnLineComment(comment, text, options, ast, isLastComment) {
28051 var precedingNode = comment.precedingNode,
28052 enclosingNode = comment.enclosingNode,
28053 followingNode = comment.followingNode;
28055 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)) {
28062 function handleEndOfLineComment(comment, text, options, ast, isLastComment) {
28063 var precedingNode = comment.precedingNode,
28064 enclosingNode = comment.enclosingNode,
28065 followingNode = comment.followingNode;
28067 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)) {
28074 function handleRemainingComment(comment, text, options, ast, isLastComment) {
28075 var precedingNode = comment.precedingNode,
28076 enclosingNode = comment.enclosingNode,
28077 followingNode = comment.followingNode;
28079 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)) {
28086 function addBlockStatementFirstComment(node, comment) {
28087 var body = node.body.filter(function (n) {
28088 return n.type !== "EmptyStatement";
28091 if (body.length === 0) {
28092 addDanglingComment$2(node, comment);
28094 addLeadingComment$2(body[0], comment);
28098 function addBlockOrNotComment(node, comment) {
28099 if (node.type === "BlockStatement") {
28100 addBlockStatementFirstComment(node, comment);
28102 addLeadingComment$2(node, comment);
28104 } // There are often comments before the else clause of if statements like
28110 // They are being attached as leading comments of the BlockExpression which
28111 // is not well printed. What we want is to instead move the comment inside
28112 // of the block and make it leadingComment of the first element of the block
28113 // or dangling comment of the block if there is nothing inside
28122 function handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
28123 if (!enclosingNode || enclosingNode.type !== "IfStatement" || !followingNode) {
28125 } // We unfortunately have no way using the AST or location of nodes to know
28126 // if the comment is positioned before the condition parenthesis:
28127 // if (a /* comment */) {}
28128 // The only workaround I found is to look at the next character to see if
28132 var nextCharacter = util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd);
28134 if (nextCharacter === ")") {
28135 addTrailingComment$2(precedingNode, comment);
28137 } // Comments before `else`:
28138 // - treat as trailing comments of the consequent, if it's a BlockStatement
28139 // - treat as a dangling comment otherwise
28142 if (precedingNode === enclosingNode.consequent && followingNode === enclosingNode.alternate) {
28143 if (precedingNode.type === "BlockStatement") {
28144 addTrailingComment$2(precedingNode, comment);
28146 addDanglingComment$2(enclosingNode, comment);
28152 if (followingNode.type === "BlockStatement") {
28153 addBlockStatementFirstComment(followingNode, comment);
28157 if (followingNode.type === "IfStatement") {
28158 addBlockOrNotComment(followingNode.consequent, comment);
28160 } // For comments positioned after the condition parenthesis in an if statement
28161 // before the consequent without brackets on, such as
28162 // if (a) /* comment */ true,
28163 // we look at the next character to see if the following node
28164 // is the consequent for the if statement
28167 if (enclosingNode.consequent === followingNode) {
28168 addLeadingComment$2(followingNode, comment);
28175 function handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
28176 if (!enclosingNode || enclosingNode.type !== "WhileStatement" || !followingNode) {
28178 } // We unfortunately have no way using the AST or location of nodes to know
28179 // if the comment is positioned before the condition parenthesis:
28180 // while (a /* comment */) {}
28181 // The only workaround I found is to look at the next character to see if
28185 var nextCharacter = util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd);
28187 if (nextCharacter === ")") {
28188 addTrailingComment$2(precedingNode, comment);
28192 if (followingNode.type === "BlockStatement") {
28193 addBlockStatementFirstComment(followingNode, comment);
28198 } // Same as IfStatement but for TryStatement
28201 function handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) {
28202 if (!enclosingNode || enclosingNode.type !== "TryStatement" && enclosingNode.type !== "CatchClause" || !followingNode) {
28206 if (enclosingNode.type === "CatchClause" && precedingNode) {
28207 addTrailingComment$2(precedingNode, comment);
28211 if (followingNode.type === "BlockStatement") {
28212 addBlockStatementFirstComment(followingNode, comment);
28216 if (followingNode.type === "TryStatement") {
28217 addBlockOrNotComment(followingNode.finalizer, comment);
28221 if (followingNode.type === "CatchClause") {
28222 addBlockOrNotComment(followingNode.body, comment);
28229 function handleMemberExpressionComments(enclosingNode, followingNode, comment) {
28230 if (enclosingNode && (enclosingNode.type === "MemberExpression" || enclosingNode.type === "OptionalMemberExpression") && followingNode && followingNode.type === "Identifier") {
28231 addLeadingComment$2(enclosingNode, comment);
28238 function handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) {
28239 var isSameLineAsPrecedingNode = precedingNode && !util.hasNewlineInRange(text, options.locEnd(precedingNode), options.locStart(comment));
28241 if ((!precedingNode || !isSameLineAsPrecedingNode) && enclosingNode && enclosingNode.type === "ConditionalExpression" && followingNode) {
28242 addLeadingComment$2(followingNode, comment);
28249 function handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) {
28250 if (enclosingNode && (enclosingNode.type === "ObjectProperty" || enclosingNode.type === "Property") && enclosingNode.shorthand && enclosingNode.key === precedingNode && enclosingNode.value.type === "AssignmentPattern") {
28251 addTrailingComment$2(enclosingNode.value.left, comment);
28258 function handleClassComments(enclosingNode, precedingNode, followingNode, comment) {
28259 if (enclosingNode && (enclosingNode.type === "ClassDeclaration" || enclosingNode.type === "ClassExpression") && enclosingNode.decorators && enclosingNode.decorators.length > 0 && !(followingNode && followingNode.type === "Decorator")) {
28260 if (!enclosingNode.decorators || enclosingNode.decorators.length === 0) {
28261 addLeadingComment$2(enclosingNode, comment);
28263 addTrailingComment$2(enclosingNode.decorators[enclosingNode.decorators.length - 1], comment);
28272 function handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) {
28273 // This is only needed for estree parsers (flow, typescript) to attach
28274 // after a method name:
28275 // obj = { fn /*comment*/() {} };
28276 if (enclosingNode && precedingNode && (enclosingNode.type === "Property" || enclosingNode.type === "MethodDefinition") && precedingNode.type === "Identifier" && enclosingNode.key === precedingNode && // special Property case: { key: /*comment*/(value) };
28277 // comment should be attached to value instead of key
28278 util.getNextNonSpaceNonCommentCharacter(text, precedingNode, options.locEnd) !== ":") {
28279 addTrailingComment$2(precedingNode, comment);
28281 } // Print comments between decorators and class methods as a trailing comment
28282 // on the decorator node instead of the method node
28285 if (precedingNode && enclosingNode && precedingNode.type === "Decorator" && (enclosingNode.type === "ClassMethod" || enclosingNode.type === "ClassProperty" || enclosingNode.type === "TSAbstractClassProperty" || enclosingNode.type === "TSAbstractMethodDefinition" || enclosingNode.type === "MethodDefinition")) {
28286 addTrailingComment$2(precedingNode, comment);
28293 function handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) {
28294 if (util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== "(") {
28298 if (precedingNode && enclosingNode && (enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ClassMethod" || enclosingNode.type === "MethodDefinition" || enclosingNode.type === "ObjectMethod")) {
28299 addTrailingComment$2(precedingNode, comment);
28306 function handleCommentAfterArrowParams(text, enclosingNode, comment, options) {
28307 if (!(enclosingNode && enclosingNode.type === "ArrowFunctionExpression")) {
28311 var index = utilShared.getNextNonSpaceNonCommentCharacterIndex(text, comment, options);
28313 if (text.substr(index, 2) === "=>") {
28314 addDanglingComment$2(enclosingNode, comment);
28321 function handleCommentInEmptyParens(text, enclosingNode, comment, options) {
28322 if (util.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== ")") {
28324 } // Only add dangling comments to fix the case when no params are present,
28325 // i.e. a function without any argument.
28328 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)) {
28329 addDanglingComment$2(enclosingNode, comment);
28333 if (enclosingNode && enclosingNode.type === "MethodDefinition" && enclosingNode.value.params.length === 0) {
28334 addDanglingComment$2(enclosingNode.value, comment);
28341 function handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
28342 // Type definitions functions
28343 if (precedingNode && precedingNode.type === "FunctionTypeParam" && enclosingNode && enclosingNode.type === "FunctionTypeAnnotation" && followingNode && followingNode.type !== "FunctionTypeParam") {
28344 addTrailingComment$2(precedingNode, comment);
28346 } // Real functions
28349 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) === ")") {
28350 addTrailingComment$2(precedingNode, comment);
28354 if (enclosingNode && enclosingNode.type === "FunctionDeclaration" && followingNode && followingNode.type === "BlockStatement") {
28355 var functionParamRightParenIndex = function () {
28356 if (enclosingNode.params.length !== 0) {
28357 return util.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(util.getLast(enclosingNode.params)));
28360 var functionParamLeftParenIndex = util.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(enclosingNode.id));
28361 return util.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, functionParamLeftParenIndex + 1);
28364 if (options.locStart(comment) > functionParamRightParenIndex) {
28365 addBlockStatementFirstComment(followingNode, comment);
28373 function handleImportSpecifierComments(enclosingNode, comment) {
28374 if (enclosingNode && enclosingNode.type === "ImportSpecifier") {
28375 addLeadingComment$2(enclosingNode, comment);
28382 function handleLabeledStatementComments(enclosingNode, comment) {
28383 if (enclosingNode && enclosingNode.type === "LabeledStatement") {
28384 addLeadingComment$2(enclosingNode, comment);
28391 function handleBreakAndContinueStatementComments(enclosingNode, comment) {
28392 if (enclosingNode && (enclosingNode.type === "ContinueStatement" || enclosingNode.type === "BreakStatement") && !enclosingNode.label) {
28393 addTrailingComment$2(enclosingNode, comment);
28400 function handleCallExpressionComments(precedingNode, enclosingNode, comment) {
28401 if (enclosingNode && (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression") && precedingNode && enclosingNode.callee === precedingNode && enclosingNode.arguments.length > 0) {
28402 addLeadingComment$2(enclosingNode.arguments[0], comment);
28409 function handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) {
28410 if (enclosingNode && (enclosingNode.type === "UnionTypeAnnotation" || enclosingNode.type === "TSUnionType")) {
28411 addTrailingComment$2(precedingNode, comment);
28418 function handlePropertyComments(enclosingNode, comment) {
28419 if (enclosingNode && (enclosingNode.type === "Property" || enclosingNode.type === "ObjectProperty")) {
28420 addLeadingComment$2(enclosingNode, comment);
28427 function handleOnlyComments(enclosingNode, ast, comment, isLastComment) {
28428 // With Flow the enclosingNode is undefined so use the AST instead.
28429 if (ast && ast.body && ast.body.length === 0) {
28430 if (isLastComment) {
28431 addDanglingComment$2(ast, comment);
28433 addLeadingComment$2(ast, comment);
28437 } else if (enclosingNode && enclosingNode.type === "Program" && enclosingNode.body.length === 0 && enclosingNode.directives && enclosingNode.directives.length === 0) {
28438 if (isLastComment) {
28439 addDanglingComment$2(enclosingNode, comment);
28441 addLeadingComment$2(enclosingNode, comment);
28450 function handleForComments(enclosingNode, precedingNode, comment) {
28451 if (enclosingNode && (enclosingNode.type === "ForInStatement" || enclosingNode.type === "ForOfStatement")) {
28452 addLeadingComment$2(enclosingNode, comment);
28459 function handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) {
28460 if (precedingNode && precedingNode.type === "ImportSpecifier" && enclosingNode && enclosingNode.type === "ImportDeclaration" && util.hasNewline(text, options.locEnd(comment))) {
28461 addTrailingComment$2(precedingNode, comment);
28468 function handleAssignmentPatternComments(enclosingNode, comment) {
28469 if (enclosingNode && enclosingNode.type === "AssignmentPattern") {
28470 addLeadingComment$2(enclosingNode, comment);
28477 function handleTypeAliasComments(enclosingNode, followingNode, comment) {
28478 if (enclosingNode && enclosingNode.type === "TypeAlias") {
28479 addLeadingComment$2(enclosingNode, comment);
28486 function handleVariableDeclaratorComments(enclosingNode, followingNode, comment) {
28487 if (enclosingNode && (enclosingNode.type === "VariableDeclarator" || enclosingNode.type === "AssignmentExpression") && followingNode && (followingNode.type === "ObjectExpression" || followingNode.type === "ArrayExpression" || followingNode.type === "TemplateLiteral" || followingNode.type === "TaggedTemplateExpression")) {
28488 addLeadingComment$2(followingNode, comment);
28495 function handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) {
28496 if (!enclosingNode || enclosingNode.type !== "TSMappedType") {
28500 if (followingNode && followingNode.type === "TSTypeParameter" && followingNode.name) {
28501 addLeadingComment$2(followingNode.name, comment);
28505 if (precedingNode && precedingNode.type === "TSTypeParameter" && precedingNode.constraint) {
28506 addTrailingComment$2(precedingNode.constraint, comment);
28513 function isBlockComment(comment) {
28514 return comment.type === "Block" || comment.type === "CommentBlock";
28517 function hasLeadingComment(node) {
28518 var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {
28522 if (node.leadingComments) {
28523 return node.leadingComments.some(fn);
28526 if (node.comments) {
28527 return node.comments.some(function (comment) {
28528 return comment.leading && fn(comment);
28536 handleOwnLineComment,
28537 handleEndOfLineComment,
28538 handleRemainingComment,
28543 var isBlockComment$1 = comments$1.isBlockComment,
28544 hasLeadingComment$1 = comments$1.hasLeadingComment;
28545 var _require$$1$builders = doc.builders,
28546 indent$2 = _require$$1$builders.indent,
28547 join$2 = _require$$1$builders.join,
28548 hardline$3 = _require$$1$builders.hardline,
28549 softline$1 = _require$$1$builders.softline,
28550 literalline$1 = _require$$1$builders.literalline,
28551 concat$4 = _require$$1$builders.concat,
28552 group$1 = _require$$1$builders.group,
28553 dedentToRoot$1 = _require$$1$builders.dedentToRoot,
28554 _require$$1$utils = doc.utils,
28555 mapDoc$3 = _require$$1$utils.mapDoc,
28556 stripTrailingHardline$1 = _require$$1$utils.stripTrailingHardline;
28558 function embed(path, print, textToDoc, options) {
28559 var node = path.getValue();
28560 var parent = path.getParentNode();
28561 var parentParent = path.getParentNode(1);
28563 switch (node.type) {
28564 case "TemplateLiteral":
28566 var isCss = [isStyledJsx, isStyledComponents, isCssProp, isAngularComponentStyles].some(function (isIt) {
28571 // Get full template literal with expressions replaced by placeholders
28572 var rawQuasis = node.quasis.map(function (q) {
28573 return q.value.raw;
28575 var placeholderID = 0;
28576 var text = rawQuasis.reduce(function (prevVal, currVal, idx) {
28577 return idx == 0 ? currVal : prevVal + "@prettier-placeholder-" + placeholderID++ + "-id" + currVal;
28579 var doc = textToDoc(text, {
28582 return transformCssDoc(doc, path, print);
28585 * react-relay and graphql-tag
28587 * graphql.experimental`...`
28590 * This intentionally excludes Relay Classic tags, as Prettier does not
28591 * support Relay Classic formatting.
28595 if (isGraphQL(path)) {
28596 var expressionDocs = node.expressions ? path.map(print, "expressions") : [];
28597 var numQuasis = node.quasis.length;
28599 if (numQuasis === 1 && node.quasis[0].value.raw.trim() === "") {
28605 for (var i = 0; i < numQuasis; i++) {
28606 var templateElement = node.quasis[i];
28607 var isFirst = i === 0;
28608 var isLast = i === numQuasis - 1;
28609 var _text = templateElement.value.cooked; // Bail out if any of the quasis have an invalid escape sequence
28610 // (which would make the `cooked` value be `null` or `undefined`)
28612 if (typeof _text !== "string") {
28616 var lines = _text.split("\n");
28618 var numLines = lines.length;
28619 var expressionDoc = expressionDocs[i];
28620 var startsWithBlankLine = numLines > 2 && lines[0].trim() === "" && lines[1].trim() === "";
28621 var endsWithBlankLine = numLines > 2 && lines[numLines - 1].trim() === "" && lines[numLines - 2].trim() === "";
28622 var commentsAndWhitespaceOnly = lines.every(function (line) {
28623 return /^\s*(?:#[^\r\n]*)?$/.test(line);
28624 }); // Bail out if an interpolation occurs within a comment.
28626 if (!isLast && /#[^\r\n]*$/.test(lines[numLines - 1])) {
28632 if (commentsAndWhitespaceOnly) {
28633 _doc = printGraphqlComments(lines);
28635 _doc = stripTrailingHardline$1(textToDoc(_text, {
28641 _doc = escapeTemplateCharacters(_doc, false);
28643 if (!isFirst && startsWithBlankLine) {
28649 if (!isLast && endsWithBlankLine) {
28652 } else if (!isFirst && !isLast && startsWithBlankLine) {
28656 if (expressionDoc) {
28657 parts.push(concat$4(["${", expressionDoc, "}"]));
28661 return concat$4(["`", indent$2(concat$4([hardline$3, join$2(hardline$3, parts)])), hardline$3, "`"]);
28664 var htmlParser = isHtml(path) ? "html" : isAngularComponentTemplate(path) ? "angular" : undefined;
28667 return printHtmlTemplateLiteral(path, print, textToDoc, htmlParser, options.embeddedInHtml);
28673 case "TemplateElement":
28679 if (parentParent && parentParent.type === "TaggedTemplateExpression" && parent.quasis.length === 1 && parentParent.tag.type === "Identifier" && (parentParent.tag.name === "md" || parentParent.tag.name === "markdown")) {
28680 var _text2 = parent.quasis[0].value.raw.replace(/((?:\\\\)*)\\`/g, function (_, backslashes) {
28681 return "\\".repeat(backslashes.length / 2) + "`";
28684 var indentation = getIndentation(_text2);
28685 var hasIndent = indentation !== "";
28686 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]);
28693 function printMarkdown(text) {
28694 var doc = textToDoc(text, {
28695 parser: "markdown",
28696 __inJsTemplate: true
28698 return stripTrailingHardline$1(escapeTemplateCharacters(doc, true));
28702 function getIndentation(str) {
28703 var firstMatchedIndent = str.match(/^([^\S\n]*)\S/m);
28704 return firstMatchedIndent === null ? "" : firstMatchedIndent[1];
28707 function uncook(cookedValue) {
28708 return cookedValue.replace(/([\\`]|\$\{)/g, "\\$1");
28711 function escapeTemplateCharacters(doc, raw) {
28712 return mapDoc$3(doc, function (currentDoc) {
28713 if (!currentDoc.parts) {
28718 currentDoc.parts.forEach(function (part) {
28719 if (typeof part === "string") {
28720 parts.push(raw ? part.replace(/(\\*)`/g, "$1$1\\`") : uncook(part));
28725 return Object.assign({}, currentDoc, {
28731 function transformCssDoc(quasisDoc, path, print) {
28732 var parentNode = path.getValue();
28733 var isEmpty = parentNode.quasis.length === 1 && !parentNode.quasis[0].value.raw.trim();
28739 var expressionDocs = parentNode.expressions ? path.map(print, "expressions") : [];
28740 var newDoc = replacePlaceholders(quasisDoc, expressionDocs);
28741 /* istanbul ignore if */
28744 throw new Error("Couldn't insert all the expressions");
28747 return concat$4(["`", indent$2(concat$4([hardline$3, stripTrailingHardline$1(newDoc)])), softline$1, "`"]);
28748 } // Search all the placeholders in the quasisDoc tree
28749 // and replace them with the expression docs one by one
28750 // returns a new doc with all the placeholders replaced,
28751 // or null if it couldn't replace any expression
28754 function replacePlaceholders(quasisDoc, expressionDocs) {
28755 if (!expressionDocs || !expressionDocs.length) {
28759 var expressions = expressionDocs.slice();
28760 var replaceCounter = 0;
28761 var newDoc = mapDoc$3(quasisDoc, function (doc) {
28762 if (!doc || !doc.parts || !doc.parts.length) {
28766 var parts = doc.parts;
28767 var atIndex = parts.indexOf("@");
28768 var placeholderIndex = atIndex + 1;
28770 if (atIndex > -1 && typeof parts[placeholderIndex] === "string" && parts[placeholderIndex].startsWith("prettier-placeholder")) {
28771 // If placeholder is split, join it
28772 var at = parts[atIndex];
28773 var placeholder = parts[placeholderIndex];
28774 var rest = parts.slice(placeholderIndex + 1);
28775 parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest);
28778 var atPlaceholderIndex = parts.findIndex(function (part) {
28779 return typeof part === "string" && part.startsWith("@prettier-placeholder");
28782 if (atPlaceholderIndex > -1) {
28783 var _placeholder = parts[atPlaceholderIndex];
28785 var _rest = parts.slice(atPlaceholderIndex + 1);
28787 var placeholderMatch = _placeholder.match(/@prettier-placeholder-(.+)-id([\s\S]*)/);
28789 var placeholderID = placeholderMatch[1]; // When the expression has a suffix appended, like:
28790 // animation: linear ${time}s ease-out;
28792 var suffix = placeholderMatch[2];
28793 var expression = expressions[placeholderID];
28795 parts = parts.slice(0, atPlaceholderIndex).concat(["${", expression, "}" + suffix]).concat(_rest);
28798 return Object.assign({}, doc, {
28802 return expressions.length === replaceCounter ? newDoc : null;
28805 function printGraphqlComments(lines) {
28807 var seenComment = false;
28808 lines.map(function (textLine) {
28809 return textLine.trim();
28810 }).forEach(function (textLine, i, array) {
28811 // Lines are either whitespace only, or a comment (with potential whitespace
28812 // around it). Drop whitespace-only lines.
28813 if (textLine === "") {
28817 if (array[i - 1] === "" && seenComment) {
28818 // If a non-first comment is preceded by a blank (whitespace only) line,
28819 // add in a blank line.
28820 parts.push(concat$4([hardline$3, textLine]));
28822 parts.push(textLine);
28825 seenComment = true;
28826 }); // If `lines` was whitespace only, return `null`.
28828 return parts.length === 0 ? null : join$2(hardline$3, parts);
28831 * Template literal in these contexts:
28832 * <style jsx>{`div{color:red}`}</style>
28839 function isStyledJsx(path) {
28840 var node = path.getValue();
28841 var parent = path.getParentNode();
28842 var parentParent = path.getParentNode(1);
28843 return parentParent && node.quasis && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXElement" && parentParent.openingElement.name.name === "style" && parentParent.openingElement.attributes.some(function (attribute) {
28844 return attribute.name.name === "jsx";
28845 }) || 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");
28848 * Angular Components can have:
28849 * - Inline HTML template
28850 * - Inline CSS styles
28852 * ...which are both within template literals somewhere
28853 * inside of the Component decorator factory.
28857 * template: `<div>...</div>`,
28858 * styles: [`h1 { color: blue; }`]
28863 function isAngularComponentStyles(path) {
28864 return isPathMatch(path, [function (node) {
28865 return node.type === "TemplateLiteral";
28866 }, function (node, name) {
28867 return node.type === "ArrayExpression" && name === "elements";
28868 }, function (node, name) {
28869 return node.type === "Property" && node.key.type === "Identifier" && node.key.name === "styles" && name === "value";
28870 }].concat(getAngularComponentObjectExpressionPredicates()));
28873 function isAngularComponentTemplate(path) {
28874 return isPathMatch(path, [function (node) {
28875 return node.type === "TemplateLiteral";
28876 }, function (node, name) {
28877 return node.type === "Property" && node.key.type === "Identifier" && node.key.name === "template" && name === "value";
28878 }].concat(getAngularComponentObjectExpressionPredicates()));
28881 function getAngularComponentObjectExpressionPredicates() {
28882 return [function (node, name) {
28883 return node.type === "ObjectExpression" && name === "properties";
28884 }, function (node, name) {
28885 return node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "Component" && name === "arguments";
28886 }, function (node, name) {
28887 return node.type === "Decorator" && name === "expression";
28891 * styled-components template literals
28895 function isStyledComponents(path) {
28896 var parent = path.getParentNode();
28898 if (!parent || parent.type !== "TaggedTemplateExpression") {
28902 var tag = parent.tag;
28904 switch (tag.type) {
28905 case "MemberExpression":
28906 return (// styled.foo``
28907 isStyledIdentifier(tag.object) || // Component.extend``
28908 isStyledExtend(tag)
28911 case "CallExpression":
28912 return (// styled(Component)``
28913 isStyledIdentifier(tag.callee) || tag.callee.type === "MemberExpression" && (tag.callee.object.type === "MemberExpression" && ( // styled.foo.attrs({})``
28914 isStyledIdentifier(tag.callee.object.object) || // Component.extend.attrs({})``
28915 isStyledExtend(tag.callee.object)) || // styled(Component).attrs({})``
28916 tag.callee.object.type === "CallExpression" && isStyledIdentifier(tag.callee.object.callee))
28921 return tag.name === "css";
28928 * JSX element with CSS prop
28932 function isCssProp(path) {
28933 var parent = path.getParentNode();
28934 var parentParent = path.getParentNode(1);
28935 return parentParent && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" && parentParent.name.type === "JSXIdentifier" && parentParent.name.name === "css";
28938 function isStyledIdentifier(node) {
28939 return node.type === "Identifier" && node.name === "styled";
28942 function isStyledExtend(node) {
28943 return /^[A-Z]/.test(node.object.name) && node.property.name === "extend";
28946 * react-relay and graphql-tag
28948 * graphql.experimental`...`
28950 * GraphQL comment block
28952 * This intentionally excludes Relay Classic tags, as Prettier does not
28953 * support Relay Classic formatting.
28957 function isGraphQL(path) {
28958 var node = path.getValue();
28959 var parent = path.getParentNode();
28960 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");
28963 function hasLanguageComment(node, languageName) {
28964 // This checks for a leading comment that is exactly `/* GraphQL */`
28965 // In order to be in line with other implementations of this comment tag
28966 // we will not trim the comment value and we will expect exactly one space on
28967 // either side of the GraphQL string
28968 // Also see ./clean.js
28969 return hasLeadingComment$1(node, function (comment) {
28970 return isBlockComment$1(comment) && comment.value === ` ${languageName} `;
28974 function isPathMatch(path, predicateStack) {
28975 var stack = path.stack.slice();
28977 var node = stack.pop();
28978 var _iteratorNormalCompletion = true;
28979 var _didIteratorError = false;
28980 var _iteratorError = undefined;
28983 for (var _iterator = predicateStack[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
28984 var predicate = _step.value;
28986 if (node === undefined) {
28988 } // skip index/array
28991 if (typeof name === "number") {
28992 name = stack.pop();
28993 node = stack.pop();
28996 if (!predicate(node, name)) {
29000 name = stack.pop();
29001 node = stack.pop();
29004 _didIteratorError = true;
29005 _iteratorError = err;
29008 if (!_iteratorNormalCompletion && _iterator.return != null) {
29009 _iterator.return();
29012 if (_didIteratorError) {
29013 throw _iteratorError;
29022 * - HTML comment block
29026 function isHtml(path) {
29027 var node = path.getValue();
29028 return hasLanguageComment(node, "HTML") || isPathMatch(path, [function (node) {
29029 return node.type === "TemplateLiteral";
29030 }, function (node, name) {
29031 return node.type === "TaggedTemplateExpression" && node.tag.type === "Identifier" && node.tag.name === "html" && name === "quasi";
29033 } // The counter is needed to distinguish nested embeds.
29036 var htmlTemplateLiteralCounter = 0;
29038 function printHtmlTemplateLiteral(path, print, textToDoc, parser, escapeClosingScriptTag) {
29039 var node = path.getValue();
29040 var counter = htmlTemplateLiteralCounter;
29041 htmlTemplateLiteralCounter = htmlTemplateLiteralCounter + 1 >>> 0;
29043 var composePlaceholder = function composePlaceholder(index) {
29044 return `PRETTIER_HTML_PLACEHOLDER_${index}_${counter}_IN_JS`;
29047 var text = node.quasis.map(function (quasi, index, quasis) {
29048 return index === quasis.length - 1 ? quasi.value.cooked : quasi.value.cooked + composePlaceholder(index);
29050 var expressionDocs = path.map(print, "expressions");
29052 if (expressionDocs.length === 0 && text.trim().length === 0) {
29056 var placeholderRegex = RegExp(composePlaceholder("(\\d+)"), "g");
29057 var contentDoc = mapDoc$3(stripTrailingHardline$1(textToDoc(text, {
29059 })), function (doc) {
29060 if (typeof doc !== "string") {
29065 var components = doc.split(placeholderRegex);
29067 for (var i = 0; i < components.length; i++) {
29068 var component = components[i];
29072 component = uncook(component);
29074 if (escapeClosingScriptTag) {
29075 component = component.replace(/<\/(script)\b/gi, "<\\/$1");
29078 parts.push(component);
29084 var placeholderIndex = +component;
29085 parts.push(concat$4(["${", group$1(expressionDocs[placeholderIndex]), "}"]));
29088 return concat$4(parts);
29090 return group$1(concat$4(["`", indent$2(concat$4([hardline$3, group$1(contentDoc)])), softline$1, "`"]));
29093 var embed_1 = embed;
29095 function clean(ast, newObj, parent) {
29096 ["range", "raw", "comments", "leadingComments", "trailingComments", "extra", "start", "end", "flags", "errors"].forEach(function (name) {
29097 delete newObj[name];
29100 if (ast.type === "BigIntLiteral") {
29101 newObj.value = newObj.value.toLowerCase();
29102 } // We remove extra `;` and add them when needed
29105 if (ast.type === "EmptyStatement") {
29107 } // We move text around, including whitespaces and add {" "}
29110 if (ast.type === "JSXText") {
29114 if (ast.type === "JSXExpressionContainer" && ast.expression.type === "Literal" && ast.expression.value === " ") {
29116 } // We remove unneeded parens around same-operator LogicalExpressions
29119 if (isUnbalancedLogicalTree(newObj)) {
29120 return rebalanceLogicalTree(newObj);
29121 } // (TypeScript) Ignore `static` in `constructor(static p) {}`
29122 // and `export` in `constructor(export p) {}`
29125 if (ast.type === "TSParameterProperty" && ast.accessibility === null && !ast.readonly) {
29127 type: "Identifier",
29128 name: ast.parameter.name,
29129 typeAnnotation: newObj.parameter.typeAnnotation,
29130 decorators: newObj.decorators
29132 } // (TypeScript) ignore empty `specifiers` array
29135 if (ast.type === "TSNamespaceExportDeclaration" && ast.specifiers && ast.specifiers.length === 0) {
29136 delete newObj.specifiers;
29137 } // We convert <div></div> to <div />
29140 if (ast.type === "JSXOpeningElement") {
29141 delete newObj.selfClosing;
29144 if (ast.type === "JSXElement") {
29145 delete newObj.closingElement;
29146 } // We change {'key': value} into {key: value}
29149 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")) {
29153 if (ast.type === "OptionalMemberExpression" && ast.optional === false) {
29154 newObj.type = "MemberExpression";
29155 delete newObj.optional;
29156 } // Remove raw and cooked values from TemplateElement when it's CSS
29160 if (ast.type === "JSXElement" && ast.openingElement.name.name === "style" && ast.openingElement.attributes.some(function (attr) {
29161 return attr.name.name === "jsx";
29163 var templateLiterals = newObj.children.filter(function (child) {
29164 return child.type === "JSXExpressionContainer" && child.expression.type === "TemplateLiteral";
29165 }).map(function (container) {
29166 return container.expression;
29168 var quasis = templateLiterals.reduce(function (quasis, templateLiteral) {
29169 return quasis.concat(templateLiteral.quasis);
29171 quasis.forEach(function (q) {
29172 return delete q.value;
29174 } // CSS template literals in css prop
29177 if (ast.type === "JSXAttribute" && ast.name.name === "css" && ast.value.type === "JSXExpressionContainer" && ast.value.expression.type === "TemplateLiteral") {
29178 newObj.value.expression.quasis.forEach(function (q) {
29179 return delete q.value;
29181 } // Angular Components: Inline HTML template and Inline CSS styles
29184 var expression = ast.expression || ast.callee;
29186 if (ast.type === "Decorator" && expression.type === "CallExpression" && expression.callee.name === "Component" && expression.arguments.length === 1) {
29187 var astProps = ast.expression.arguments[0].properties;
29188 newObj.expression.arguments[0].properties.forEach(function (prop, index) {
29189 var templateLiteral = null;
29191 switch (astProps[index].key.name) {
29193 if (prop.value.type === "ArrayExpression") {
29194 templateLiteral = prop.value.elements[0];
29200 if (prop.value.type === "TemplateLiteral") {
29201 templateLiteral = prop.value;
29207 if (templateLiteral) {
29208 templateLiteral.quasis.forEach(function (q) {
29209 return delete q.value;
29213 } // styled-components, graphql, markdown
29216 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")) {
29217 newObj.quasi.quasis.forEach(function (quasi) {
29218 return delete quasi.value;
29222 if (ast.type === "TemplateLiteral") {
29223 // This checks for a leading comment that is exactly `/* GraphQL */`
29224 // In order to be in line with other implementations of this comment tag
29225 // we will not trim the comment value and we will expect exactly one space on
29226 // either side of the GraphQL string
29227 // Also see ./embed.js
29228 var hasLanguageComment = ast.leadingComments && ast.leadingComments.some(function (comment) {
29229 return comment.type === "CommentBlock" && ["GraphQL", "HTML"].some(function (languageName) {
29230 return comment.value === ` ${languageName} `;
29234 if (hasLanguageComment || parent.type === "CallExpression" && parent.callee.name === "graphql") {
29235 newObj.quasis.forEach(function (quasi) {
29236 return delete quasi.value;
29242 function isUnbalancedLogicalTree(newObj) {
29243 return newObj.type === "LogicalExpression" && newObj.right.type === "LogicalExpression" && newObj.operator === newObj.right.operator;
29246 function rebalanceLogicalTree(newObj) {
29247 if (isUnbalancedLogicalTree(newObj)) {
29248 return rebalanceLogicalTree({
29249 type: "LogicalExpression",
29250 operator: newObj.operator,
29251 left: rebalanceLogicalTree({
29252 type: "LogicalExpression",
29253 operator: newObj.operator,
29255 right: newObj.right.left,
29258 right: newObj.right.right,
29266 var clean_1 = clean;
29268 var detectNewline = createCommonjsModule(function (module) {
29270 module.exports = function (str) {
29271 if (typeof str !== 'string') {
29272 throw new TypeError('Expected a string');
29275 var newlines = str.match(/(?:\r?\n)/g) || [];
29277 if (newlines.length === 0) {
29281 var crlf = newlines.filter(function (el) {
29282 return el === '\r\n';
29284 var lf = newlines.length - crlf;
29285 return crlf > lf ? '\r\n' : '\n';
29288 module.exports.graceful = function (str) {
29289 return module.exports(str) || '\n';
29292 var detectNewline_1 = detectNewline.graceful;
29294 var build = createCommonjsModule(function (module, exports) {
29296 Object.defineProperty(exports, '__esModule', {
29299 exports.extract = extract;
29300 exports.strip = strip;
29301 exports.parse = parse;
29302 exports.parseWithComments = parseWithComments;
29303 exports.print = print;
29308 _os = function _os() {
29315 function _detectNewline() {
29316 var data = _interopRequireDefault(detectNewline);
29318 _detectNewline = function _detectNewline() {
29325 function _interopRequireDefault(obj) {
29326 return obj && obj.__esModule ? obj : {
29331 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
29333 * This source code is licensed under the MIT license found in the
29334 * LICENSE file in the root directory of this source tree.
29338 var commentEndRe = /\*\/$/;
29339 var commentStartRe = /^\/\*\*/;
29340 var docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/;
29341 var lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g;
29342 var ltrimNewlineRe = /^(\r?\n)+/;
29343 var multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
29344 var propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
29345 var stringStartRe = /(\r?\n|^) *\* ?/g;
29347 function extract(contents) {
29348 var match = contents.match(docblockRe);
29349 return match ? match[0].trimLeft() : '';
29352 function strip(contents) {
29353 var match = contents.match(docblockRe);
29354 return match && match[0] ? contents.substring(match[0].length) : contents;
29357 function parse(docblock) {
29358 return parseWithComments(docblock).pragmas;
29361 function parseWithComments(docblock) {
29362 var line = (0, _detectNewline().default)(docblock) || _os().EOL;
29364 docblock = docblock.replace(commentStartRe, '').replace(commentEndRe, '').replace(stringStartRe, '$1'); // Normalize multi-line directives
29368 while (prev !== docblock) {
29370 docblock = docblock.replace(multilineRe, `${line}$1 $2${line}`);
29373 docblock = docblock.replace(ltrimNewlineRe, '').trimRight();
29374 var result = Object.create(null);
29375 var comments = docblock.replace(propertyRe, '').replace(ltrimNewlineRe, '').trimRight();
29378 while (match = propertyRe.exec(docblock)) {
29379 // strip linecomments from pragmas
29380 var nextPragma = match[2].replace(lineCommentRe, '');
29382 if (typeof result[match[1]] === 'string' || Array.isArray(result[match[1]])) {
29383 result[match[1]] = [].concat(result[match[1]], nextPragma);
29385 result[match[1]] = nextPragma;
29395 function print(_ref) {
29396 var _ref$comments = _ref.comments,
29397 comments = _ref$comments === void 0 ? '' : _ref$comments,
29398 _ref$pragmas = _ref.pragmas,
29399 pragmas = _ref$pragmas === void 0 ? {} : _ref$pragmas;
29401 var line = (0, _detectNewline().default)(comments) || _os().EOL;
29406 var keys = Object.keys(pragmas);
29407 var printedObject = keys.map(function (key) {
29408 return printKeyValues(key, pragmas[key]);
29409 }).reduce(function (arr, next) {
29410 return arr.concat(next);
29411 }, []).map(function (keyValue) {
29412 return start + ' ' + keyValue + line;
29416 if (keys.length === 0) {
29420 if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) {
29421 var value = pragmas[keys[0]];
29422 return `${head} ${printKeyValues(keys[0], value)[0]}${tail}`;
29426 var printedComments = comments.split(line).map(function (textLine) {
29427 return `${start} ${textLine}`;
29428 }).join(line) + line;
29429 return head + line + (comments ? printedComments : '') + (comments && keys.length ? start + line : '') + printedObject + tail;
29432 function printKeyValues(key, valueOrArray) {
29433 return [].concat(valueOrArray).map(function (value) {
29434 return `@${key} ${value}`.trim();
29438 unwrapExports(build);
29439 var build_1 = build.extract;
29440 var build_2 = build.strip;
29441 var build_3 = build.parse;
29442 var build_4 = build.parseWithComments;
29443 var build_5 = build.print;
29445 function hasPragma(text) {
29446 var pragmas = Object.keys(build.parse(build.extract(text)));
29447 return pragmas.indexOf("prettier") !== -1 || pragmas.indexOf("format") !== -1;
29450 function insertPragma(text) {
29451 var parsedDocblock = build.parseWithComments(build.extract(text));
29452 var pragmas = Object.assign({
29454 }, parsedDocblock.pragmas);
29455 var newDocblock = build.print({
29457 comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines
29459 }).replace(/(\r\n|\r)/g, "\n"); // normalise newlines (mitigate use of os.EOL by jest-docblock)
29461 var strippedText = build.strip(text);
29462 var separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n";
29463 return newDocblock + separatingNewlines + strippedText;
29471 var getLast$1 = util.getLast,
29472 hasNewline$2 = util.hasNewline,
29473 hasNewlineInRange$1 = util.hasNewlineInRange,
29474 hasIgnoreComment$1 = util.hasIgnoreComment,
29475 hasNodeIgnoreComment$1 = util.hasNodeIgnoreComment,
29476 skipWhitespace$1 = util.skipWhitespace;
29477 var isIdentifierName = utils$1.keyword.isIdentifierNameES5; // We match any whitespace except line terminators because
29478 // Flow annotation comments cannot be split across lines. For example:
29481 // : any */).foo = 5;
29483 // is not picked up by Flow (see https://github.com/facebook/flow/issues/7050), so
29484 // removing the newline would create a type annotation that the user did not intend
29487 var NON_LINE_TERMINATING_WHITE_SPACE = "(?:(?=.)\\s)";
29488 var FLOW_SHORTHAND_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*:`);
29489 var FLOW_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*::`);
29491 function hasFlowShorthandAnnotationComment(node) {
29492 // https://flow.org/en/docs/types/comments/
29493 // Syntax example: const r = new (window.Request /*: Class<Request> */)("");
29494 return node.extra && node.extra.parenthesized && node.trailingComments && node.trailingComments[0].value.match(FLOW_SHORTHAND_ANNOTATION);
29497 function hasFlowAnnotationComment(comments) {
29498 return comments && comments[0].value.match(FLOW_ANNOTATION);
29501 function hasNode(node, fn) {
29502 if (!node || typeof node !== "object") {
29506 if (Array.isArray(node)) {
29507 return node.some(function (value) {
29508 return hasNode(value, fn);
29512 var result = fn(node);
29513 return typeof result === "boolean" ? result : Object.keys(node).some(function (key) {
29514 return hasNode(node[key], fn);
29518 function hasNakedLeftSide(node) {
29519 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";
29522 function getLeftSide(node) {
29523 if (node.expressions) {
29524 return node.expressions[0];
29527 return node.left || node.test || node.callee || node.object || node.tag || node.argument || node.expression;
29530 function getLeftSidePathName(path, node) {
29531 if (node.expressions) {
29532 return ["expressions", 0];
29555 if (node.argument) {
29556 return ["argument"];
29559 if (node.expression) {
29560 return ["expression"];
29563 throw new Error("Unexpected node has no left side", node);
29566 function isLiteral(node) {
29567 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";
29570 function isNumericLiteral(node) {
29571 return node.type === "NumericLiteral" || node.type === "Literal" && typeof node.value === "number";
29574 function isStringLiteral(node) {
29575 return node.type === "StringLiteral" || node.type === "Literal" && typeof node.value === "string";
29578 function isObjectType(n) {
29579 return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral";
29582 function isFunctionOrArrowExpression(node) {
29583 return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
29586 function isFunctionOrArrowExpressionWithBody(node) {
29587 return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement";
29590 function isTemplateLiteral(node) {
29591 return node.type === "TemplateLiteral";
29592 } // `inject` is used in AngularJS 1.x, `async` in Angular 2+
29593 // example: https://docs.angularjs.org/guide/unit-testing#using-beforeall-
29596 function isAngularTestWrapper(node) {
29597 return (node.type === "CallExpression" || node.type === "OptionalCallExpression") && node.callee.type === "Identifier" && (node.callee.name === "async" || node.callee.name === "inject" || node.callee.name === "fakeAsync");
29600 function isJSXNode(node) {
29601 return node.type === "JSXElement" || node.type === "JSXFragment";
29604 function isTheOnlyJSXElementInMarkdown(options, path) {
29605 if (options.parentParser !== "markdown" && options.parentParser !== "mdx") {
29609 var node = path.getNode();
29611 if (!node.expression || !isJSXNode(node.expression)) {
29615 var parent = path.getParentNode();
29616 return parent.type === "Program" && parent.body.length == 1;
29617 } // Detect an expression node representing `{" "}`
29620 function isJSXWhitespaceExpression(node) {
29621 return node.type === "JSXExpressionContainer" && isLiteral(node.expression) && node.expression.value === " " && !node.expression.comments;
29624 function isMemberExpressionChain(node) {
29625 if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") {
29629 if (node.object.type === "Identifier") {
29633 return isMemberExpressionChain(node.object);
29636 function isGetterOrSetter(node) {
29637 return node.kind === "get" || node.kind === "set";
29640 function sameLocStart(nodeA, nodeB, options) {
29641 return options.locStart(nodeA) === options.locStart(nodeB);
29642 } // TODO: This is a bad hack and we need a better way to distinguish between
29643 // arrow functions and otherwise
29646 function isFunctionNotation(node, options) {
29647 return isGetterOrSetter(node) || sameLocStart(node, node.value, options);
29648 } // Hack to differentiate between the following two which have the same ast
29649 // type T = { method: () => void };
29650 // type T = { method(): void };
29653 function isObjectTypePropertyAFunction(node, options) {
29654 return (node.type === "ObjectTypeProperty" || node.type === "ObjectTypeInternalSlot") && node.value.type === "FunctionTypeAnnotation" && !node.static && !isFunctionNotation(node, options);
29655 } // Hack to differentiate between the following two which have the same ast
29656 // declare function f(a): void;
29657 // var f: (a) => void;
29660 function isTypeAnnotationAFunction(node, options) {
29661 return (node.type === "TypeAnnotation" || node.type === "TSTypeAnnotation") && node.typeAnnotation.type === "FunctionTypeAnnotation" && !node.static && !sameLocStart(node, node.typeAnnotation, options);
29664 function isBinaryish(node) {
29665 return node.type === "BinaryExpression" || node.type === "LogicalExpression" || node.type === "NGPipeExpression";
29668 function isMemberish(node) {
29669 return node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "BindExpression" && node.object;
29672 function isSimpleFlowType(node) {
29673 var flowTypeAnnotations = ["AnyTypeAnnotation", "NullLiteralTypeAnnotation", "GenericTypeAnnotation", "ThisTypeAnnotation", "NumberTypeAnnotation", "VoidTypeAnnotation", "EmptyTypeAnnotation", "MixedTypeAnnotation", "BooleanTypeAnnotation", "BooleanLiteralTypeAnnotation", "StringTypeAnnotation"];
29674 return node && flowTypeAnnotations.indexOf(node.type) !== -1 && !(node.type === "GenericTypeAnnotation" && node.typeParameters);
29677 var unitTestRe = /^(skip|[fx]?(it|describe|test))$/;
29679 function isSkipOrOnlyBlock(node) {
29680 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");
29683 function isUnitTestSetUp(n) {
29684 var unitTestSetUpRe = /^(before|after)(Each|All)$/;
29685 return n.callee.type === "Identifier" && unitTestSetUpRe.test(n.callee.name) && n.arguments.length === 1;
29686 } // eg; `describe("some string", (done) => {})`
29689 function isTestCall(n, parent) {
29690 if (n.type !== "CallExpression") {
29694 if (n.arguments.length === 1) {
29695 if (isAngularTestWrapper(n) && parent && isTestCall(parent)) {
29696 return isFunctionOrArrowExpression(n.arguments[0]);
29699 if (isUnitTestSetUp(n)) {
29700 return isAngularTestWrapper(n.arguments[0]);
29702 } else if (n.arguments.length === 2 || n.arguments.length === 3) {
29703 if ((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name) || isSkipOrOnlyBlock(n)) && (isTemplateLiteral(n.arguments[0]) || isStringLiteral(n.arguments[0]))) {
29704 // it("name", () => { ... }, 2500)
29705 if (n.arguments[2] && !isNumericLiteral(n.arguments[2])) {
29709 return (n.arguments.length === 2 ? isFunctionOrArrowExpression(n.arguments[1]) : isFunctionOrArrowExpressionWithBody(n.arguments[1]) && n.arguments[1].params.length <= 1) || isAngularTestWrapper(n.arguments[1]);
29716 function hasLeadingComment$2(node) {
29717 return node.comments && node.comments.some(function (comment) {
29718 return comment.leading;
29722 function hasTrailingComment(node) {
29723 return node.comments && node.comments.some(function (comment) {
29724 return comment.trailing;
29728 function isCallOrOptionalCallExpression(node) {
29729 return node.type === "CallExpression" || node.type === "OptionalCallExpression";
29732 function hasDanglingComments(node) {
29733 return node.comments && node.comments.some(function (comment) {
29734 return !comment.leading && !comment.trailing;
29737 /** identify if an angular expression seems to have side effects */
29740 function hasNgSideEffect(path) {
29741 return hasNode(path.getValue(), function (node) {
29742 switch (node.type) {
29746 case "CallExpression":
29747 case "OptionalCallExpression":
29748 case "AssignmentExpression":
29754 function isNgForOf(node, index, parentNode) {
29755 return node.type === "NGMicrosyntaxKeyedExpression" && node.key.name === "of" && index === 1 && parentNode.body[0].type === "NGMicrosyntaxLet" && parentNode.body[0].value === null;
29757 /** @param node {import("estree").TemplateLiteral} */
29760 function isSimpleTemplateLiteral(node) {
29761 if (node.expressions.length === 0) {
29765 return node.expressions.every(function (expr) {
29766 // Disallow comments since printDocToString can't print them here
29767 if (expr.comments) {
29769 } // Allow `x` and `this`
29772 if (expr.type === "Identifier" || expr.type === "ThisExpression") {
29774 } // Allow `a.b.c`, `a.b[c]`, and `this.x.y`
29777 if (expr.type === "MemberExpression" || expr.type === "OptionalMemberExpression") {
29780 while (head.type === "MemberExpression" || head.type === "OptionalMemberExpression") {
29781 if (head.property.type !== "Identifier" && head.property.type !== "Literal" && head.property.type !== "StringLiteral" && head.property.type !== "NumericLiteral") {
29785 head = head.object;
29787 if (head.comments) {
29792 if (head.type === "Identifier" || head.type === "ThisExpression") {
29803 function getFlowVariance(path) {
29804 if (!path.variance) {
29806 } // Babel 7.0 currently uses variance node type, and flow should
29807 // follow suit soon:
29808 // https://github.com/babel/babel/issues/4722
29811 var variance = path.variance.kind || path.variance;
29813 switch (variance) {
29821 /* istanbul ignore next */
29826 function classPropMayCauseASIProblems(path) {
29827 var node = path.getNode();
29829 if (node.type !== "ClassProperty") {
29833 var name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today
29834 // so isn't properly tested yet.
29836 if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) {
29841 function classChildNeedsASIProtection(node) {
29846 if (node.static || node.accessibility // TypeScript
29851 if (!node.computed) {
29852 var name = node.key && node.key.name;
29854 if (name === "in" || name === "instanceof") {
29859 switch (node.type) {
29860 case "ClassProperty":
29861 case "TSAbstractClassProperty":
29862 return node.computed;
29864 case "MethodDefinition": // Flow
29866 case "TSAbstractMethodDefinition": // TypeScript
29868 case "ClassMethod":
29869 case "ClassPrivateMethod":
29872 var isAsync = node.value ? node.value.async : node.async;
29873 var isGenerator = node.value ? node.value.generator : node.generator;
29875 if (isAsync || node.kind === "get" || node.kind === "set") {
29879 if (node.computed || isGenerator) {
29886 case "TSIndexSignature":
29890 /* istanbul ignore next */
29895 function getTypeScriptMappedTypeModifier(tokenNode, keyword) {
29896 if (tokenNode === "+") {
29897 return "+" + keyword;
29898 } else if (tokenNode === "-") {
29899 return "-" + keyword;
29905 function hasNewlineBetweenOrAfterDecorators(node, options) {
29906 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)));
29907 } // Only space, newline, carriage return, and tab are treated as whitespace
29911 var jsxWhitespaceChars = " \n\r\t";
29912 var matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)");
29913 var containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]"); // Meaningful if it contains non-whitespace characters,
29914 // or it contains whitespace without a new line.
29916 function isMeaningfulJSXText(node) {
29917 return isLiteral(node) && (containsNonJsxWhitespaceRegex.test(rawText(node)) || !/\n/.test(rawText(node)));
29920 function hasJsxIgnoreComment(path) {
29921 var node = path.getValue();
29922 var parent = path.getParentNode();
29924 if (!parent || !node || !isJSXNode(node) || !isJSXNode(parent)) {
29926 } // Lookup the previous sibling, ignoring any empty JSXText elements
29929 var index = parent.children.indexOf(node);
29930 var prevSibling = null;
29932 for (var i = index; i > 0; i--) {
29933 var candidate = parent.children[i - 1];
29935 if (candidate.type === "JSXText" && !isMeaningfulJSXText(candidate)) {
29939 prevSibling = candidate;
29943 return prevSibling && prevSibling.type === "JSXExpressionContainer" && prevSibling.expression.type === "JSXEmptyExpression" && prevSibling.expression.comments && prevSibling.expression.comments.find(function (comment) {
29944 return comment.value.trim() === "prettier-ignore";
29948 function isEmptyJSXElement(node) {
29949 if (node.children.length === 0) {
29953 if (node.children.length > 1) {
29955 } // if there is one text child and does not contain any meaningful text
29956 // we can treat the element as empty.
29959 var child = node.children[0];
29960 return isLiteral(child) && !isMeaningfulJSXText(child);
29963 function hasPrettierIgnore(path) {
29964 return hasIgnoreComment$1(path) || hasJsxIgnoreComment(path);
29967 function isLastStatement(path) {
29968 var parent = path.getParentNode();
29974 var node = path.getValue();
29975 var body = (parent.body || parent.consequent).filter(function (stmt) {
29976 return stmt.type !== "EmptyStatement";
29978 return body && body[body.length - 1] === node;
29981 function isFlowAnnotationComment(text, typeAnnotation, options) {
29982 var start = options.locStart(typeAnnotation);
29983 var end = skipWhitespace$1(text, options.locEnd(typeAnnotation));
29984 return text.substr(start, 2) === "/*" && text.substr(end, 2) === "*/";
29987 function hasLeadingOwnLineComment(text, node, options) {
29988 if (isJSXNode(node)) {
29989 return hasNodeIgnoreComment$1(node);
29992 var res = node.comments && node.comments.some(function (comment) {
29993 return comment.leading && hasNewline$2(text, options.locEnd(comment));
29996 } // This recurses the return argument, looking for the first token
29997 // (the leftmost leaf node) and, if it (or its parents) has any
29998 // leadingComments, returns true (so it can be wrapped in parens).
30001 function returnArgumentHasLeadingComment(options, argument) {
30002 if (hasLeadingOwnLineComment(options.originalText, argument, options)) {
30006 if (hasNakedLeftSide(argument)) {
30007 var leftMost = argument;
30010 while (newLeftMost = getLeftSide(leftMost)) {
30011 leftMost = newLeftMost;
30013 if (hasLeadingOwnLineComment(options.originalText, leftMost, options)) {
30022 function isStringPropSafeToCoerceToIdentifier(node, options) {
30023 return isStringLiteral(node.key) && isIdentifierName(node.key.value) && options.parser !== "json" && !(options.parser === "typescript" && node.type === "ClassProperty");
30026 function isJestEachTemplateLiteral(node, parentNode) {
30028 * describe.each`table`(name, fn)
30029 * describe.only.each`table`(name, fn)
30030 * describe.skip.each`table`(name, fn)
30031 * test.each`table`(name, fn)
30032 * test.only.each`table`(name, fn)
30033 * test.skip.each`table`(name, fn)
30035 * Ref: https://github.com/facebook/jest/pull/6102
30037 var jestEachTriggerRegex = /^[xf]?(describe|it|test)$/;
30038 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));
30041 function templateLiteralHasNewLines(template) {
30042 return template.quasis.some(function (quasi) {
30043 return quasi.value.raw.includes("\n");
30047 function isTemplateOnItsOwnLine(n, text, options) {
30048 return (n.type === "TemplateLiteral" && templateLiteralHasNewLines(n) || n.type === "TaggedTemplateExpression" && templateLiteralHasNewLines(n.quasi)) && !hasNewline$2(text, options.locStart(n), {
30053 function needsHardlineAfterDanglingComment(node) {
30054 if (!node.comments) {
30058 var lastDanglingComment = getLast$1(node.comments.filter(function (comment) {
30059 return !comment.leading && !comment.trailing;
30061 return lastDanglingComment && !comments$1.isBlockComment(lastDanglingComment);
30062 } // If we have nested conditional expressions, we want to print them in JSX mode
30063 // if there's at least one JSXElement somewhere in the tree.
30065 // A conditional expression chain like this should be printed in normal mode,
30066 // because there aren't JSXElements anywhere in it:
30068 // isA ? "A" : isB ? "B" : isC ? "C" : "Unknown";
30070 // But a conditional expression chain like this should be printed in JSX mode,
30071 // because there is a JSXElement in the last ConditionalExpression:
30073 // isA ? "A" : isB ? "B" : isC ? "C" : <span className="warning">Unknown</span>;
30075 // This type of ConditionalExpression chain is structured like this in the AST:
30077 // ConditionalExpression {
30079 // consequent: ...,
30080 // alternate: ConditionalExpression {
30082 // consequent: ...,
30083 // alternate: ConditionalExpression {
30085 // consequent: ...,
30091 // We want to traverse over that shape and convert it into a flat structure so
30092 // that we can find if there's a JSXElement somewhere inside.
30095 function getConditionalChainContents(node) {
30096 // Given this code:
30098 // // Using a ConditionalExpression as the consequent is uncommon, but should
30100 // A ? B : C ? D : E ? F ? G : H : I
30102 // which has this AST:
30104 // ConditionalExpression {
30105 // test: Identifier(A),
30106 // consequent: Identifier(B),
30107 // alternate: ConditionalExpression {
30108 // test: Identifier(C),
30109 // consequent: Identifier(D),
30110 // alternate: ConditionalExpression {
30111 // test: Identifier(E),
30112 // consequent: ConditionalExpression {
30113 // test: Identifier(F),
30114 // consequent: Identifier(G),
30115 // alternate: Identifier(H),
30117 // alternate: Identifier(I),
30122 // we should return this Array:
30136 // This loses the information about whether each node was the test,
30137 // consequent, or alternate, but we don't care about that here- we are only
30138 // flattening this structure to find if there's any JSXElements inside.
30139 var nonConditionalExpressions = [];
30141 function recurse(node) {
30142 if (node.type === "ConditionalExpression") {
30143 recurse(node.test);
30144 recurse(node.consequent);
30145 recurse(node.alternate);
30147 nonConditionalExpressions.push(node);
30152 return nonConditionalExpressions;
30155 function conditionalExpressionChainContainsJSX(node) {
30156 return Boolean(getConditionalChainContents(node).find(isJSXNode));
30157 } // Logic to check for args with multiple anonymous functions. For instance,
30158 // the following call should be split on multiple lines for readability:
30159 // source.pipe(map((x) => x + x), filter((x) => x % 2 === 0))
30162 function isFunctionCompositionArgs(args) {
30163 if (args.length <= 1) {
30168 var _iteratorNormalCompletion = true;
30169 var _didIteratorError = false;
30170 var _iteratorError = undefined;
30173 for (var _iterator = args[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
30174 var arg = _step.value;
30176 if (isFunctionOrArrowExpression(arg)) {
30182 } else if (isCallOrOptionalCallExpression(arg)) {
30183 var _iteratorNormalCompletion2 = true;
30184 var _didIteratorError2 = false;
30185 var _iteratorError2 = undefined;
30188 for (var _iterator2 = arg.arguments[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
30189 var childArg = _step2.value;
30191 if (isFunctionOrArrowExpression(childArg)) {
30196 _didIteratorError2 = true;
30197 _iteratorError2 = err;
30200 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
30201 _iterator2.return();
30204 if (_didIteratorError2) {
30205 throw _iteratorError2;
30212 _didIteratorError = true;
30213 _iteratorError = err;
30216 if (!_iteratorNormalCompletion && _iterator.return != null) {
30217 _iterator.return();
30220 if (_didIteratorError) {
30221 throw _iteratorError;
30227 } // Logic to determine if a call is a “long curried function call”.
30228 // See https://github.com/prettier/prettier/issues/1420.
30230 // `connect(a, b, c)(d)`
30231 // In the above call expression, the second call is the parent node and the
30232 // first call is the current node.
30235 function isLongCurriedCallExpression(path) {
30236 var node = path.getValue();
30237 var parent = path.getParentNode();
30238 return isCallOrOptionalCallExpression(node) && isCallOrOptionalCallExpression(parent) && parent.callee === node && node.arguments.length > parent.arguments.length && parent.arguments.length > 0;
30241 function rawText(node) {
30242 return node.extra ? node.extra.raw : node.raw;
30245 function identity(x) {
30249 function isTSXFile(options) {
30250 return options.filepath && /\.tsx$/i.test(options.filepath);
30254 classChildNeedsASIProtection,
30255 classPropMayCauseASIProblems,
30256 conditionalExpressionChainContainsJSX,
30258 getLeftSidePathName,
30259 getTypeScriptMappedTypeModifier,
30260 hasDanglingComments,
30261 hasFlowAnnotationComment,
30262 hasFlowShorthandAnnotationComment,
30263 hasLeadingComment: hasLeadingComment$2,
30264 hasLeadingOwnLineComment,
30266 hasNewlineBetweenOrAfterDecorators,
30270 hasTrailingComment,
30273 isCallOrOptionalCallExpression,
30275 isFlowAnnotationComment,
30276 isFunctionCompositionArgs,
30277 isFunctionNotation,
30278 isFunctionOrArrowExpression,
30280 isJestEachTemplateLiteral,
30282 isJSXWhitespaceExpression,
30285 isLongCurriedCallExpression,
30286 isMeaningfulJSXText,
30287 isMemberExpressionChain,
30292 isObjectTypePropertyAFunction,
30294 isSimpleTemplateLiteral,
30296 isStringPropSafeToCoerceToIdentifier,
30297 isTemplateOnItsOwnLine,
30299 isTheOnlyJSXElementInMarkdown,
30301 isTypeAnnotationAFunction,
30302 matchJsxWhitespaceRegex,
30303 needsHardlineAfterDanglingComment,
30305 returnArgumentHasLeadingComment
30308 var getLeftSidePathName$1 = utils$2.getLeftSidePathName,
30309 hasFlowShorthandAnnotationComment$1 = utils$2.hasFlowShorthandAnnotationComment,
30310 hasNakedLeftSide$1 = utils$2.hasNakedLeftSide,
30311 hasNode$1 = utils$2.hasNode;
30313 function hasClosureCompilerTypeCastComment(text, path) {
30314 // https://github.com/google/closure-compiler/wiki/Annotating-Types#type-casts
30315 // Syntax example: var x = /** @type {string} */ (fruit);
30316 var n = path.getValue();
30317 return isParenthesized(n) && (hasTypeCastComment(n) || hasAncestorTypeCastComment(0)); // for sub-item: /** @type {array} */ (numberOrString).map(x => x);
30319 function hasAncestorTypeCastComment(index) {
30320 var ancestor = path.getParentNode(index);
30321 return ancestor && !isParenthesized(ancestor) ? hasTypeCastComment(ancestor) || hasAncestorTypeCastComment(index + 1) : false;
30324 function hasTypeCastComment(node) {
30325 return node.comments && node.comments.some(function (comment) {
30326 return comment.leading && comments$1.isBlockComment(comment) && isTypeCastComment(comment.value);
30330 function isParenthesized(node) {
30331 // Closure typecast comments only really make sense when _not_ using
30332 // typescript or flow parsers, so we take advantage of the babel parser's
30333 // parenthesized expressions.
30334 return node.extra && node.extra.parenthesized;
30337 function isTypeCastComment(comment) {
30338 var cleaned = comment.trim().split("\n").map(function (line) {
30339 return line.replace(/^[\s*]+/, "");
30340 }).join(" ").trim();
30342 if (!/^@type\s*\{[^]+\}$/.test(cleaned)) {
30346 var isCompletelyClosed = false;
30347 var unpairedBracketCount = 0;
30348 var _iteratorNormalCompletion = true;
30349 var _didIteratorError = false;
30350 var _iteratorError = undefined;
30353 for (var _iterator = cleaned[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
30354 var char = _step.value;
30356 if (char === "{") {
30357 if (isCompletelyClosed) {
30361 unpairedBracketCount++;
30362 } else if (char === "}") {
30363 if (unpairedBracketCount === 0) {
30367 unpairedBracketCount--;
30369 if (unpairedBracketCount === 0) {
30370 isCompletelyClosed = true;
30375 _didIteratorError = true;
30376 _iteratorError = err;
30379 if (!_iteratorNormalCompletion && _iterator.return != null) {
30380 _iterator.return();
30383 if (_didIteratorError) {
30384 throw _iteratorError;
30389 return unpairedBracketCount === 0;
30393 function needsParens(path, options) {
30394 var parent = path.getParentNode();
30400 var name = path.getName();
30401 var node = path.getNode(); // If the value of this path is some child of a Node and not a Node
30402 // itself, then it doesn't need parentheses. Only Node objects (in
30403 // fact, only Expression nodes) need parentheses.
30405 if (path.getValue() !== node) {
30407 } // to avoid unexpected `}}` in HTML interpolations
30410 if (options.__isInHtmlInterpolation && !options.bracketSpacing && endsWithRightBracket(node) && isFollowedByRightBracket(path)) {
30412 } // Only statements don't need parentheses.
30415 if (isStatement(node)) {
30417 } // Closure compiler requires that type casted expressions to be surrounded by
30421 if (hasClosureCompilerTypeCastComment(options.originalText, path)) {
30425 if ( // Preserve parens if we have a Flow annotation comment, unless we're using the Flow
30426 // parser. The Flow parser turns Flow comments into type annotation nodes in its
30427 // AST, which we handle separately.
30428 options.parser !== "flow" && hasFlowShorthandAnnotationComment$1(path.getValue())) {
30430 } // Identifiers never need parentheses.
30433 if (node.type === "Identifier") {
30434 // ...unless those identifiers are embed placeholders. They might be substituted by complex
30435 // expressions, so the parens around them should not be dropped. Example (JS-in-HTML-in-JS):
30436 // let tpl = html`<script> f((${expr}) / 2); </script>`;
30437 // If the inner JS formatter removes the parens, the expression might change its meaning:
30438 // f((a + b) / 2) vs f(a + b / 2)
30439 if (node.extra && node.extra.parenthesized && /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(node.name)) {
30446 if (parent.type === "ParenthesizedExpression") {
30448 } // Add parens around the extends clause of a class. It is needed for almost
30449 // all expressions.
30452 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")) {
30454 } // `export default function` or `export default class` can't be followed by
30455 // anything after. So an expression like `export default (function(){}).toString()`
30456 // needs to be followed by a parentheses
30459 if (parent.type === "ExportDefaultDeclaration") {
30460 return shouldWrapFunctionForExportDefault(path, options);
30463 if (parent.type === "Decorator" && parent.expression === node) {
30464 var hasCallExpression = false;
30465 var hasMemberExpression = false;
30466 var current = node;
30469 switch (current.type) {
30470 case "MemberExpression":
30471 hasMemberExpression = true;
30472 current = current.object;
30475 case "CallExpression":
30478 hasMemberExpression ||
30480 hasCallExpression) {
30484 hasCallExpression = true;
30485 current = current.callee;
30499 if (parent.type === "ArrowFunctionExpression" && parent.body === node && node.type !== "SequenceExpression" && // these have parens added anyway
30500 util.startsWithNoLookaheadToken(node,
30501 /* forbidFunctionClassAndDoExpr */
30502 false) || parent.type === "ExpressionStatement" && util.startsWithNoLookaheadToken(node,
30503 /* forbidFunctionClassAndDoExpr */
30508 switch (node.type) {
30509 case "SpreadElement":
30510 case "SpreadProperty":
30511 return parent.type === "MemberExpression" && name === "object" && parent.object === node;
30513 case "UpdateExpression":
30514 if (parent.type === "UnaryExpression") {
30515 return node.prefix && (node.operator === "++" && parent.operator === "+" || node.operator === "--" && parent.operator === "-");
30518 // else fallthrough
30520 case "UnaryExpression":
30521 switch (parent.type) {
30522 case "UnaryExpression":
30523 return node.operator === parent.operator && (node.operator === "+" || node.operator === "-");
30525 case "BindExpression":
30528 case "MemberExpression":
30529 case "OptionalMemberExpression":
30530 return name === "object";
30532 case "TaggedTemplateExpression":
30535 case "NewExpression":
30536 case "CallExpression":
30537 case "OptionalCallExpression":
30538 return name === "callee";
30540 case "BinaryExpression":
30541 return parent.operator === "**" && name === "left";
30543 case "TSNonNullExpression":
30550 case "BinaryExpression":
30552 if (parent.type === "UpdateExpression") {
30556 var isLeftOfAForStatement = function isLeftOfAForStatement(node) {
30560 var _parent = path.getParentNode(i++);
30566 if (_parent.type === "ForStatement" && _parent.init === node) {
30576 if (node.operator === "in" && isLeftOfAForStatement(node)) {
30582 case "TSTypeAssertion":
30583 case "TSAsExpression":
30584 case "LogicalExpression":
30585 switch (parent.type) {
30586 case "ConditionalExpression":
30587 return node.type === "TSAsExpression";
30589 case "CallExpression":
30590 case "NewExpression":
30591 case "OptionalCallExpression":
30592 return name === "callee";
30594 case "ClassExpression":
30595 case "ClassDeclaration":
30596 return name === "superClass" && parent.superClass === node;
30598 case "TSTypeAssertion":
30599 case "TaggedTemplateExpression":
30600 case "UnaryExpression":
30601 case "JSXSpreadAttribute":
30602 case "SpreadElement":
30603 case "SpreadProperty":
30604 case "BindExpression":
30605 case "AwaitExpression":
30606 case "TSAsExpression":
30607 case "TSNonNullExpression":
30608 case "UpdateExpression":
30611 case "MemberExpression":
30612 case "OptionalMemberExpression":
30613 return name === "object";
30615 case "AssignmentExpression":
30616 return parent.left === node && (node.type === "TSTypeAssertion" || node.type === "TSAsExpression");
30618 case "LogicalExpression":
30619 if (node.type === "LogicalExpression") {
30620 return parent.operator !== node.operator;
30623 // else fallthrough
30625 case "BinaryExpression":
30627 if (!node.operator && node.type !== "TSTypeAssertion") {
30631 var po = parent.operator;
30632 var pp = util.getPrecedence(po);
30633 var no = node.operator;
30634 var np = util.getPrecedence(no);
30640 if (pp === np && name === "right") {
30641 assert$1.strictEqual(parent.right, node);
30645 if (pp === np && !util.shouldFlatten(po, no)) {
30649 if (pp < np && no === "%") {
30650 return po === "+" || po === "-";
30651 } // Add parenthesis when working with bitwise operators
30652 // It's not strictly needed but helps with code understanding
30655 if (util.isBitwiseOperator(po)) {
30666 case "SequenceExpression":
30667 switch (parent.type) {
30668 case "ReturnStatement":
30671 case "ForStatement":
30672 // Although parentheses wouldn't hurt around sequence
30673 // expressions in the head of for loops, traditional style
30674 // dictates that e.g. i++, j++ should not be wrapped with
30678 case "ExpressionStatement":
30679 return name !== "expression";
30681 case "ArrowFunctionExpression":
30682 // We do need parentheses, but SequenceExpressions are handled
30683 // specially when printing bodies of arrow functions.
30684 return name !== "body";
30687 // Otherwise err on the side of overparenthesization, adding
30688 // explicit exceptions above if this proves overzealous.
30692 case "YieldExpression":
30693 if (parent.type === "UnaryExpression" || parent.type === "AwaitExpression" || parent.type === "TSAsExpression" || parent.type === "TSNonNullExpression") {
30697 // else fallthrough
30699 case "AwaitExpression":
30700 switch (parent.type) {
30701 case "TaggedTemplateExpression":
30702 case "UnaryExpression":
30703 case "BinaryExpression":
30704 case "LogicalExpression":
30705 case "SpreadElement":
30706 case "SpreadProperty":
30707 case "TSAsExpression":
30708 case "TSNonNullExpression":
30709 case "BindExpression":
30712 case "MemberExpression":
30713 case "OptionalMemberExpression":
30714 return name === "object";
30716 case "NewExpression":
30717 case "CallExpression":
30718 case "OptionalCallExpression":
30719 return name === "callee";
30721 case "ConditionalExpression":
30722 return parent.test === node;
30728 case "TSConditionalType":
30729 if (parent.type === "TSConditionalType" && node === parent.extendsType) {
30735 case "TSFunctionType":
30736 case "TSConstructorType":
30737 if (parent.type === "TSConditionalType" && node === parent.checkType) {
30743 case "TSUnionType":
30744 case "TSIntersectionType":
30745 if (parent.type === "TSUnionType" || parent.type === "TSIntersectionType") {
30751 case "TSTypeOperator":
30752 case "TSInferType":
30753 return parent.type === "TSArrayType" || parent.type === "TSOptionalType" || parent.type === "TSRestType" || parent.type === "TSIndexedAccessType" && node === parent.objectType || parent.type === "TSTypeOperator";
30755 case "ArrayTypeAnnotation":
30756 return parent.type === "NullableTypeAnnotation";
30758 case "IntersectionTypeAnnotation":
30759 case "UnionTypeAnnotation":
30760 return parent.type === "ArrayTypeAnnotation" || parent.type === "NullableTypeAnnotation" || parent.type === "IntersectionTypeAnnotation" || parent.type === "UnionTypeAnnotation";
30762 case "NullableTypeAnnotation":
30763 return parent.type === "ArrayTypeAnnotation";
30765 case "FunctionTypeAnnotation":
30767 var ancestor = parent.type === "NullableTypeAnnotation" ? path.getParentNode(1) : parent;
30768 return ancestor.type === "UnionTypeAnnotation" || ancestor.type === "IntersectionTypeAnnotation" || ancestor.type === "ArrayTypeAnnotation" || // We should check ancestor's parent to know whether the parentheses
30769 // are really needed, but since ??T doesn't make sense this check
30770 // will almost never be true.
30771 ancestor.type === "NullableTypeAnnotation";
30774 case "StringLiteral":
30775 case "NumericLiteral":
30777 if (typeof node.value === "string" && parent.type === "ExpressionStatement" && ( // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2
30778 // See corresponding workaround in printer.js case: "Literal"
30779 options.parser !== "typescript" && !parent.directive || options.parser === "typescript" && options.originalText.substr(options.locStart(node) - 1, 1) === "(")) {
30780 // To avoid becoming a directive
30781 var grandParent = path.getParentNode(1);
30782 return grandParent.type === "Program" || grandParent.type === "BlockStatement";
30785 return parent.type === "MemberExpression" && typeof node.value === "number" && name === "object" && parent.object === node;
30787 case "AssignmentExpression":
30789 var _grandParent = path.getParentNode(1);
30791 if (parent.type === "ArrowFunctionExpression" && parent.body === node) {
30793 } else if (parent.type === "ClassProperty" && parent.key === node && parent.computed) {
30795 } else if (parent.type === "TSPropertySignature" && parent.name === node) {
30797 } else if (parent.type === "ForStatement" && (parent.init === node || parent.update === node)) {
30799 } else if (parent.type === "ExpressionStatement") {
30800 return node.left.type === "ObjectPattern";
30801 } else if (parent.type === "TSPropertySignature" && parent.key === node) {
30803 } else if (parent.type === "AssignmentExpression") {
30805 } else if (parent.type === "SequenceExpression" && _grandParent && _grandParent.type === "ForStatement" && (_grandParent.init === parent || _grandParent.update === parent)) {
30807 } else if (parent.type === "Property" && parent.value === node) {
30809 } else if (parent.type === "NGChainedExpression") {
30816 case "ConditionalExpression":
30817 switch (parent.type) {
30818 case "TaggedTemplateExpression":
30819 case "UnaryExpression":
30820 case "SpreadElement":
30821 case "SpreadProperty":
30822 case "BinaryExpression":
30823 case "LogicalExpression":
30824 case "NGPipeExpression":
30825 case "ExportDefaultDeclaration":
30826 case "AwaitExpression":
30827 case "JSXSpreadAttribute":
30828 case "TSTypeAssertion":
30829 case "TypeCastExpression":
30830 case "TSAsExpression":
30831 case "TSNonNullExpression":
30834 case "NewExpression":
30835 case "CallExpression":
30836 case "OptionalCallExpression":
30837 return name === "callee";
30839 case "ConditionalExpression":
30840 return name === "test" && parent.test === node;
30842 case "MemberExpression":
30843 case "OptionalMemberExpression":
30844 return name === "object";
30850 case "FunctionExpression":
30851 switch (parent.type) {
30852 case "NewExpression":
30853 case "CallExpression":
30854 case "OptionalCallExpression":
30855 // Not always necessary, but it's clearer to the reader if IIFEs are wrapped in parentheses.
30856 // Is necessary if it is `expression` of `ExpressionStatement`.
30857 return name === "callee";
30859 case "TaggedTemplateExpression":
30861 // This is basically a kind of IIFE.
30867 case "ArrowFunctionExpression":
30868 switch (parent.type) {
30869 case "NewExpression":
30870 case "CallExpression":
30871 case "OptionalCallExpression":
30872 return name === "callee";
30874 case "MemberExpression":
30875 case "OptionalMemberExpression":
30876 return name === "object";
30878 case "TSAsExpression":
30879 case "BindExpression":
30880 case "TaggedTemplateExpression":
30881 case "UnaryExpression":
30882 case "LogicalExpression":
30883 case "BinaryExpression":
30884 case "AwaitExpression":
30885 case "TSTypeAssertion":
30888 case "ConditionalExpression":
30889 return name === "test";
30895 case "ClassExpression":
30896 switch (parent.type) {
30897 case "NewExpression":
30898 return name === "callee" && parent.callee === node;
30904 case "OptionalMemberExpression":
30905 case "OptionalCallExpression":
30906 if ((parent.type === "MemberExpression" && name === "object" || parent.type === "CallExpression" && name === "callee") && // workaround for https://github.com/facebook/flow/issues/8159
30907 !(options.parser === "flow" && parent.range[0] === node.range[0])) {
30913 case "CallExpression":
30914 case "MemberExpression":
30915 case "TaggedTemplateExpression":
30916 case "TSNonNullExpression":
30917 if ((parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee") {
30921 switch (object.type) {
30922 case "CallExpression":
30923 case "OptionalCallExpression":
30926 case "MemberExpression":
30927 case "OptionalMemberExpression":
30928 case "BindExpression":
30929 object = object.object;
30931 // tagged templates are basically member expressions from a grammar perspective
30932 // see https://tc39.github.io/ecma262/#prod-MemberExpression
30934 case "TaggedTemplateExpression":
30935 object = object.tag;
30938 case "TSNonNullExpression":
30939 object = object.expression;
30950 case "BindExpression":
30951 return (parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && name === "object";
30953 case "NGPipeExpression":
30954 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") {
30960 case "JSXFragment":
30962 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";
30964 case "TypeAnnotation":
30965 return name === "returnType" && parent.type === "ArrowFunctionExpression" && includesFunctionTypeInObjectType(node);
30971 function isStatement(node) {
30972 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";
30975 function includesFunctionTypeInObjectType(node) {
30976 return hasNode$1(node, function (n1) {
30977 return n1.type === "ObjectTypeAnnotation" && hasNode$1(n1, function (n2) {
30978 return n2.type === "FunctionTypeAnnotation" || undefined;
30983 function endsWithRightBracket(node) {
30984 switch (node.type) {
30985 case "ObjectExpression":
30993 function isFollowedByRightBracket(path) {
30994 var node = path.getValue();
30995 var parent = path.getParentNode();
30996 var name = path.getName();
30998 switch (parent.type) {
30999 case "NGPipeExpression":
31000 if (typeof name === "number" && parent.arguments[name] === node && parent.arguments.length - 1 === name) {
31001 return path.callParent(isFollowedByRightBracket);
31006 case "ObjectProperty":
31007 if (name === "value") {
31008 var parentParent = path.getParentNode(1);
31009 return parentParent.properties[parentParent.properties.length - 1] === parent;
31014 case "BinaryExpression":
31015 case "LogicalExpression":
31016 if (name === "right") {
31017 return path.callParent(isFollowedByRightBracket);
31022 case "ConditionalExpression":
31023 if (name === "alternate") {
31024 return path.callParent(isFollowedByRightBracket);
31029 case "UnaryExpression":
31030 if (parent.prefix) {
31031 return path.callParent(isFollowedByRightBracket);
31040 function shouldWrapFunctionForExportDefault(path, options) {
31041 var node = path.getValue();
31042 var parent = path.getParentNode();
31044 if (node.type === "FunctionExpression" || node.type === "ClassExpression") {
31045 return parent.type === "ExportDefaultDeclaration" || // in some cases the function is already wrapped
31046 // (e.g. `export default (function() {})();`)
31047 // in this case we don't need to add extra parens
31048 !needsParens(path, options);
31051 if (!hasNakedLeftSide$1(node) || parent.type !== "ExportDefaultDeclaration" && needsParens(path, options)) {
31055 return path.call.apply(path, [function (childPath) {
31056 return shouldWrapFunctionForExportDefault(childPath, options);
31057 }].concat(getLeftSidePathName$1(path, node)));
31060 var needsParens_1 = needsParens;
31062 var _require$$0$builders$1 = doc.builders,
31063 concat$5 = _require$$0$builders$1.concat,
31064 join$3 = _require$$0$builders$1.join,
31065 line$1 = _require$$0$builders$1.line;
31067 function printHtmlBinding(path, options, print) {
31068 var node = path.getValue();
31070 if (options.__onHtmlBindingRoot && path.getName() === null) {
31071 options.__onHtmlBindingRoot(node);
31074 if (node.type !== "File") {
31078 if (options.__isVueForBindingLeft) {
31079 return path.call(function (functionDeclarationPath) {
31080 var _functionDeclarationP = functionDeclarationPath.getValue(),
31081 params = _functionDeclarationP.params;
31083 return concat$5([params.length > 1 ? "(" : "", join$3(concat$5([",", line$1]), functionDeclarationPath.map(print, "params")), params.length > 1 ? ")" : ""]);
31084 }, "program", "body", 0);
31087 if (options.__isVueSlotScope) {
31088 return path.call(function (functionDeclarationPath) {
31089 return join$3(concat$5([",", line$1]), functionDeclarationPath.map(print, "params"));
31090 }, "program", "body", 0);
31092 } // based on https://github.com/prettier/prettier/blob/master/src/language-html/syntax-vue.js isVueEventBindingExpression()
31095 function isVueEventBindingExpression(node) {
31096 switch (node.type) {
31097 case "MemberExpression":
31098 switch (node.property.type) {
31100 case "NumericLiteral":
31101 case "StringLiteral":
31102 return isVueEventBindingExpression(node.object);
31115 var htmlBinding = {
31116 isVueEventBindingExpression,
31120 function preprocess(ast, options) {
31121 switch (options.parser) {
31124 case "json-stringify":
31125 case "__js_expression":
31126 case "__vue_expression":
31127 return Object.assign({}, ast, {
31128 type: options.parser.startsWith("__") ? "JsExpressionRoot" : "JsonRoot",
31138 var preprocess_1 = preprocess;
31140 var getParentExportDeclaration$1 = util.getParentExportDeclaration,
31141 isExportDeclaration$1 = util.isExportDeclaration,
31142 shouldFlatten$1 = util.shouldFlatten,
31143 getNextNonSpaceNonCommentCharacter$1 = util.getNextNonSpaceNonCommentCharacter,
31144 hasNewline$3 = util.hasNewline,
31145 hasNewlineInRange$2 = util.hasNewlineInRange,
31146 getLast$2 = util.getLast,
31147 getStringWidth$2 = util.getStringWidth,
31148 printString$1 = util.printString,
31149 printNumber$1 = util.printNumber,
31150 hasIgnoreComment$2 = util.hasIgnoreComment,
31151 hasNodeIgnoreComment$2 = util.hasNodeIgnoreComment,
31152 getPenultimate$1 = util.getPenultimate,
31153 startsWithNoLookaheadToken$1 = util.startsWithNoLookaheadToken,
31154 getIndentSize$1 = util.getIndentSize,
31155 matchAncestorTypes$1 = util.matchAncestorTypes,
31156 getPreferredQuote$1 = util.getPreferredQuote;
31157 var isNextLineEmpty$2 = utilShared.isNextLineEmpty,
31158 isNextLineEmptyAfterIndex$1 = utilShared.isNextLineEmptyAfterIndex,
31159 getNextNonSpaceNonCommentCharacterIndex$2 = utilShared.getNextNonSpaceNonCommentCharacterIndex;
31160 var insertPragma$1 = pragma.insertPragma;
31161 var printHtmlBinding$1 = htmlBinding.printHtmlBinding,
31162 isVueEventBindingExpression$1 = htmlBinding.isVueEventBindingExpression;
31163 var classChildNeedsASIProtection$1 = utils$2.classChildNeedsASIProtection,
31164 classPropMayCauseASIProblems$1 = utils$2.classPropMayCauseASIProblems,
31165 conditionalExpressionChainContainsJSX$1 = utils$2.conditionalExpressionChainContainsJSX,
31166 getFlowVariance$1 = utils$2.getFlowVariance,
31167 getLeftSidePathName$2 = utils$2.getLeftSidePathName,
31168 getTypeScriptMappedTypeModifier$1 = utils$2.getTypeScriptMappedTypeModifier,
31169 hasDanglingComments$1 = utils$2.hasDanglingComments,
31170 hasFlowAnnotationComment$1 = utils$2.hasFlowAnnotationComment,
31171 hasFlowShorthandAnnotationComment$2 = utils$2.hasFlowShorthandAnnotationComment,
31172 hasLeadingComment$3 = utils$2.hasLeadingComment,
31173 hasLeadingOwnLineComment$1 = utils$2.hasLeadingOwnLineComment,
31174 hasNakedLeftSide$2 = utils$2.hasNakedLeftSide,
31175 hasNewlineBetweenOrAfterDecorators$1 = utils$2.hasNewlineBetweenOrAfterDecorators,
31176 hasNgSideEffect$1 = utils$2.hasNgSideEffect,
31177 hasPrettierIgnore$1 = utils$2.hasPrettierIgnore,
31178 hasTrailingComment$1 = utils$2.hasTrailingComment,
31179 identity$1 = utils$2.identity,
31180 isBinaryish$1 = utils$2.isBinaryish,
31181 isCallOrOptionalCallExpression$1 = utils$2.isCallOrOptionalCallExpression,
31182 isEmptyJSXElement$1 = utils$2.isEmptyJSXElement,
31183 isFlowAnnotationComment$1 = utils$2.isFlowAnnotationComment,
31184 isFunctionCompositionArgs$1 = utils$2.isFunctionCompositionArgs,
31185 isFunctionNotation$1 = utils$2.isFunctionNotation,
31186 isFunctionOrArrowExpression$1 = utils$2.isFunctionOrArrowExpression,
31187 isGetterOrSetter$1 = utils$2.isGetterOrSetter,
31188 isJestEachTemplateLiteral$1 = utils$2.isJestEachTemplateLiteral,
31189 isJSXNode$1 = utils$2.isJSXNode,
31190 isJSXWhitespaceExpression$1 = utils$2.isJSXWhitespaceExpression,
31191 isLastStatement$1 = utils$2.isLastStatement,
31192 isLiteral$1 = utils$2.isLiteral,
31193 isLongCurriedCallExpression$1 = utils$2.isLongCurriedCallExpression,
31194 isMeaningfulJSXText$1 = utils$2.isMeaningfulJSXText,
31195 isMemberExpressionChain$1 = utils$2.isMemberExpressionChain,
31196 isMemberish$1 = utils$2.isMemberish,
31197 isNgForOf$1 = utils$2.isNgForOf,
31198 isNumericLiteral$1 = utils$2.isNumericLiteral,
31199 isObjectType$1 = utils$2.isObjectType,
31200 isObjectTypePropertyAFunction$1 = utils$2.isObjectTypePropertyAFunction,
31201 isSimpleFlowType$1 = utils$2.isSimpleFlowType,
31202 isSimpleTemplateLiteral$1 = utils$2.isSimpleTemplateLiteral,
31203 isStringLiteral$1 = utils$2.isStringLiteral,
31204 isStringPropSafeToCoerceToIdentifier$1 = utils$2.isStringPropSafeToCoerceToIdentifier,
31205 isTemplateOnItsOwnLine$1 = utils$2.isTemplateOnItsOwnLine,
31206 isTestCall$1 = utils$2.isTestCall,
31207 isTheOnlyJSXElementInMarkdown$1 = utils$2.isTheOnlyJSXElementInMarkdown,
31208 isTSXFile$1 = utils$2.isTSXFile,
31209 isTypeAnnotationAFunction$1 = utils$2.isTypeAnnotationAFunction,
31210 matchJsxWhitespaceRegex$1 = utils$2.matchJsxWhitespaceRegex,
31211 needsHardlineAfterDanglingComment$1 = utils$2.needsHardlineAfterDanglingComment,
31212 rawText$1 = utils$2.rawText,
31213 returnArgumentHasLeadingComment$1 = utils$2.returnArgumentHasLeadingComment;
31214 var needsQuoteProps = new WeakMap();
31215 var _require$$5$builders = doc.builders,
31216 concat$6 = _require$$5$builders.concat,
31217 join$4 = _require$$5$builders.join,
31218 line$2 = _require$$5$builders.line,
31219 hardline$4 = _require$$5$builders.hardline,
31220 softline$2 = _require$$5$builders.softline,
31221 literalline$2 = _require$$5$builders.literalline,
31222 group$2 = _require$$5$builders.group,
31223 indent$3 = _require$$5$builders.indent,
31224 align$1 = _require$$5$builders.align,
31225 conditionalGroup$1 = _require$$5$builders.conditionalGroup,
31226 fill$2 = _require$$5$builders.fill,
31227 ifBreak$1 = _require$$5$builders.ifBreak,
31228 breakParent$2 = _require$$5$builders.breakParent,
31229 lineSuffixBoundary$1 = _require$$5$builders.lineSuffixBoundary,
31230 addAlignmentToDoc$2 = _require$$5$builders.addAlignmentToDoc,
31231 dedent$1 = _require$$5$builders.dedent,
31232 _require$$5$utils = doc.utils,
31233 willBreak$1 = _require$$5$utils.willBreak,
31234 isLineNext$1 = _require$$5$utils.isLineNext,
31235 isEmpty$1 = _require$$5$utils.isEmpty,
31236 removeLines$1 = _require$$5$utils.removeLines,
31237 printDocToString$2 = doc.printer.printDocToString;
31240 function shouldPrintComma(options, level) {
31241 level = level || "es5";
31243 switch (options.trailingComma) {
31245 if (level === "all") {
31252 if (level === "es5") {
31264 function genericPrint(path, options, printPath, args) {
31265 var node = path.getValue();
31266 var needsParens = false;
31267 var linesWithoutParens = printPathNoParens(path, options, printPath, args);
31269 if (!node || isEmpty$1(linesWithoutParens)) {
31270 return linesWithoutParens;
31273 var parentExportDecl = getParentExportDeclaration$1(path);
31274 var decorators = [];
31276 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
31277 // was written before the export, the export will be responsible
31278 // for printing the decorators.
31279 !(parentExportDecl && options.locStart(parentExportDecl, {
31280 ignoreDecorators: true
31281 }) > options.locStart(node.decorators[0]))) {
31282 var shouldBreak = node.type === "ClassExpression" || node.type === "ClassDeclaration" || hasNewlineBetweenOrAfterDecorators$1(node, options);
31283 var separator = shouldBreak ? hardline$4 : line$2;
31284 path.each(function (decoratorPath) {
31285 var decorator = decoratorPath.getValue();
31287 if (decorator.expression) {
31288 decorator = decorator.expression;
31290 decorator = decorator.callee;
31293 decorators.push(printPath(decoratorPath), separator);
31296 if (parentExportDecl) {
31297 decorators.unshift(hardline$4);
31299 } 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,
31300 // otherwise they are printed by the node.declaration
31301 options.locStart(node, {
31302 ignoreDecorators: true
31303 }) > options.locStart(node.declaration.decorators[0])) {
31304 // Export declarations are responsible for printing any decorators
31305 // that logically apply to node.declaration.
31306 path.each(function (decoratorPath) {
31307 var decorator = decoratorPath.getValue();
31308 var prefix = decorator.type === "Decorator" ? "" : "@";
31309 decorators.push(prefix, printPath(decoratorPath), hardline$4);
31310 }, "declaration", "decorators");
31312 // Nodes with decorators can't have parentheses, so we can avoid
31313 // computing pathNeedsParens() except in this case.
31314 needsParens = needsParens_1(path, options);
31320 parts.unshift("(");
31323 parts.push(linesWithoutParens);
31326 var _node = path.getValue();
31328 if (hasFlowShorthandAnnotationComment$2(_node)) {
31330 parts.push(_node.trailingComments[0].value.trimLeft());
31332 _node.trailingComments[0].printed = true;
31338 if (decorators.length > 0) {
31339 return group$2(concat$6(decorators.concat(parts)));
31342 return concat$6(parts);
31345 function printDecorators(path, options, print) {
31346 var node = path.getValue();
31347 return group$2(concat$6([join$4(line$2, path.map(print, "decorators")), hasNewlineBetweenOrAfterDecorators$1(node, options) ? hardline$4 : line$2]));
31350 * The following is the shared logic for
31351 * ternary operators, namely ConditionalExpression
31352 * and TSConditionalType
31353 * @typedef {Object} OperatorOptions
31354 * @property {() => Array<string | Doc>} beforeParts - Parts to print before the `?`.
31355 * @property {(breakClosingParen: boolean) => Array<string | Doc>} afterParts - Parts to print after the conditional expression.
31356 * @property {boolean} shouldCheckJsx - Whether to check for and print in JSX mode.
31357 * @property {string} conditionalNodeType - The type of the conditional expression node, ie "ConditionalExpression" or "TSConditionalType".
31358 * @property {string} consequentNodePropertyName - The property at which the consequent node can be found on the main node, eg "consequent".
31359 * @property {string} alternateNodePropertyName - The property at which the alternate node can be found on the main node, eg "alternate".
31360 * @property {string} testNodePropertyName - The property at which the test node can be found on the main node, eg "test".
31361 * @property {boolean} breakNested - Whether to break all nested ternaries when one breaks.
31362 * @param {FastPath} path - The path to the ConditionalExpression/TSConditionalType node.
31363 * @param {Options} options - Prettier options
31364 * @param {Function} print - Print function to call recursively
31365 * @param {OperatorOptions} operatorOptions
31370 function printTernaryOperator(path, options, print, operatorOptions) {
31371 var node = path.getValue();
31372 var testNode = node[operatorOptions.testNodePropertyName];
31373 var consequentNode = node[operatorOptions.consequentNodePropertyName];
31374 var alternateNode = node[operatorOptions.alternateNodePropertyName];
31375 var parts = []; // We print a ConditionalExpression in either "JSX mode" or "normal mode".
31376 // See tests/jsx/conditional-expression.js for more info.
31378 var jsxMode = false;
31379 var parent = path.getParentNode();
31380 var forceNoIndent = parent.type === operatorOptions.conditionalNodeType; // Find the outermost non-ConditionalExpression parent, and the outermost
31381 // ConditionalExpression parent. We'll use these to determine if we should
31382 // print in JSX mode.
31385 var previousParent;
31389 previousParent = currentParent || node;
31390 currentParent = path.getParentNode(i);
31392 } while (currentParent && currentParent.type === operatorOptions.conditionalNodeType);
31394 var firstNonConditionalParent = currentParent || parent;
31395 var lastConditionalParent = previousParent;
31397 if (operatorOptions.shouldCheckJsx && (isJSXNode$1(testNode) || isJSXNode$1(consequentNode) || isJSXNode$1(alternateNode) || conditionalExpressionChainContainsJSX$1(lastConditionalParent))) {
31399 forceNoIndent = true; // Even though they don't need parens, we wrap (almost) everything in
31400 // parens when using ?: within JSX, because the parens are analogous to
31401 // curly braces in an if statement.
31403 var wrap = function wrap(doc) {
31404 return concat$6([ifBreak$1("(", ""), indent$3(concat$6([softline$2, doc])), softline$2, ifBreak$1(")", "")]);
31405 }; // The only things we don't wrap are:
31406 // * Nested conditional expressions in alternates
31410 var isNull = function isNull(node) {
31411 return node.type === "NullLiteral" || node.type === "Literal" && node.value === null;
31414 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)));
31417 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))]);
31418 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));
31419 } // We want a whole chain of ConditionalExpressions to all
31420 // break if any of them break. That means we should only group around the
31421 // outer-most ConditionalExpression.
31424 var maybeGroup = function maybeGroup(doc) {
31425 return operatorOptions.breakNested ? parent === firstNonConditionalParent ? group$2(doc) : doc : group$2(doc);
31426 }; // Break the closing paren to keep the chain right after it:
31433 var breakClosingParen = !jsxMode && (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression" || parent.type === "NGPipeExpression" && parent.left === node && operatorOptions.breakNested) && !parent.computed;
31434 return maybeGroup(concat$6([].concat(function (testDoc) {
31446 parent.type === operatorOptions.conditionalNodeType && parent[operatorOptions.alternateNodePropertyName] === node ? align$1(2, testDoc) : testDoc
31448 }(concat$6(operatorOptions.beforeParts())), forceNoIndent ? concat$6(parts) : indent$3(concat$6(parts)), operatorOptions.afterParts(breakClosingParen))));
31451 function printPathNoParens(path, options, print, args) {
31452 var n = path.getValue();
31453 var semi = options.semi ? ";" : "";
31459 if (typeof n === "string") {
31463 var htmlBinding = printHtmlBinding$1(path, options, print);
31466 return htmlBinding;
31472 case "JsExpressionRoot":
31473 return path.call(print, "node");
31476 return concat$6([path.call(print, "node"), hardline$4]);
31479 // Print @babel/parser's InterpreterDirective here so that
31480 // leading comments on the `Program` node get printed after the hashbang.
31481 if (n.program && n.program.interpreter) {
31482 parts.push(path.call(function (programPath) {
31483 return programPath.call(print, "interpreter");
31487 parts.push(path.call(print, "program"));
31488 return concat$6(parts);
31492 if (n.directives) {
31493 path.each(function (childPath) {
31494 parts.push(print(childPath), semi, hardline$4);
31496 if (isNextLineEmpty$2(options.originalText, childPath.getValue(), options)) {
31497 parts.push(hardline$4);
31502 parts.push(path.call(function (bodyPath) {
31503 return printStatementSequence(bodyPath, options, print);
31505 parts.push(comments.printDanglingComments(path, options,
31507 true)); // Only force a trailing newline if there were any contents.
31509 if (n.body.length || n.comments) {
31510 parts.push(hardline$4);
31513 return concat$6(parts);
31514 // Babel extension.
31516 case "EmptyStatement":
31519 case "ExpressionStatement":
31520 // Detect Flow-parsed directives
31522 return concat$6([nodeStr(n.expression, options, true), semi]);
31525 if (options.parser === "__vue_event_binding") {
31526 var parent = path.getParentNode();
31528 if (parent.type === "Program" && parent.body.length === 1 && parent.body[0] === n) {
31529 return concat$6([path.call(print, "expression"), isVueEventBindingExpression$1(n.expression) ? ";" : ""]);
31531 } // Do not append semicolon after the only JSX element in a program
31534 return concat$6([path.call(print, "expression"), isTheOnlyJSXElementInMarkdown$1(options, path) ? "" : semi]);
31535 // Babel extension.
31537 case "ParenthesizedExpression":
31538 return concat$6(["(", path.call(print, "expression"), ")"]);
31540 case "AssignmentExpression":
31541 return printAssignment(n.left, path.call(print, "left"), concat$6([" ", n.operator]), n.right, path.call(print, "right"), options);
31543 case "BinaryExpression":
31544 case "LogicalExpression":
31545 case "NGPipeExpression":
31547 var _parent = path.getParentNode();
31549 var parentParent = path.getParentNode(1);
31550 var isInsideParenthesis = n !== _parent.body && (_parent.type === "IfStatement" || _parent.type === "WhileStatement" || _parent.type === "SwitchStatement" || _parent.type === "DoWhileStatement");
31552 var _parts = printBinaryishExpressions(path, print, options,
31554 false, isInsideParenthesis); // if (
31555 // this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft
31558 // looks super weird, we want to break the children if the parent breaks
31561 // this.hasPlugin("dynamicImports") &&
31562 // this.lookahead().type === tt.parenLeft
31566 if (isInsideParenthesis) {
31567 return concat$6(_parts);
31568 } // Break between the parens in
31569 // unaries or in a member or specific call expression, i.e.
31578 if ((_parent.type === "CallExpression" || _parent.type === "OptionalCallExpression") && _parent.callee === n || _parent.type === "UnaryExpression" || (_parent.type === "MemberExpression" || _parent.type === "OptionalMemberExpression") && !_parent.computed) {
31579 return group$2(concat$6([indent$3(concat$6([softline$2, concat$6(_parts)])), softline$2]));
31580 } // Avoid indenting sub-expressions in some cases where the first sub-expression is already
31581 // indented accordingly. We should indent sub-expressions where the first case isn't indented.
31584 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";
31585 var shouldIndentIfInlining = _parent.type === "AssignmentExpression" || _parent.type === "VariableDeclarator" || _parent.type === "ClassProperty" || _parent.type === "TSAbstractClassProperty" || _parent.type === "ClassPrivateProperty" || _parent.type === "ObjectProperty" || _parent.type === "Property";
31586 var samePrecedenceSubExpression = isBinaryish$1(n.left) && shouldFlatten$1(n.operator, n.left.operator);
31588 if (shouldNotIndent || shouldInlineLogicalExpression(n) && !samePrecedenceSubExpression || !shouldInlineLogicalExpression(n) && shouldIndentIfInlining) {
31589 return group$2(concat$6(_parts));
31592 if (_parts.length === 0) {
31594 } // If the right part is a JSX node, we include it in a separate group to
31595 // prevent it breaking the whole chain, so we can print the expression like:
31604 var hasJSX = isJSXNode$1(n.right);
31605 var rest = concat$6(hasJSX ? _parts.slice(1, -1) : _parts.slice(1));
31606 var groupId = Symbol("logicalChain-" + ++uid);
31607 var chain = group$2(concat$6([// Don't include the initial expression in the indentation
31608 // level. The first item is guaranteed to be the first
31609 // left-most expression.
31610 _parts.length > 0 ? _parts[0] : "", indent$3(rest)]), {
31618 var jsxPart = getLast$2(_parts);
31619 return group$2(concat$6([chain, ifBreak$1(indent$3(jsxPart), jsxPart, {
31624 case "AssignmentPattern":
31625 return concat$6([path.call(print, "left"), " = ", path.call(print, "right")]);
31627 case "TSTypeAssertion":
31629 var shouldBreakAfterCast = !(n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression");
31630 var castGroup = group$2(concat$6(["<", indent$3(concat$6([softline$2, path.call(print, "typeAnnotation")])), softline$2, ">"]));
31631 var exprContents = concat$6([ifBreak$1("("), indent$3(concat$6([softline$2, path.call(print, "expression")])), softline$2, ifBreak$1(")")]);
31633 if (shouldBreakAfterCast) {
31634 return conditionalGroup$1([concat$6([castGroup, path.call(print, "expression")]), concat$6([castGroup, group$2(exprContents, {
31636 })]), concat$6([castGroup, path.call(print, "expression")])]);
31639 return group$2(concat$6([castGroup, path.call(print, "expression")]));
31642 case "OptionalMemberExpression":
31643 case "MemberExpression":
31645 var _parent2 = path.getParentNode();
31647 var firstNonMemberParent;
31651 firstNonMemberParent = path.getParentNode(i);
31653 } while (firstNonMemberParent && (firstNonMemberParent.type === "MemberExpression" || firstNonMemberParent.type === "OptionalMemberExpression" || firstNonMemberParent.type === "TSNonNullExpression"));
31655 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";
31656 return concat$6([path.call(print, "object"), shouldInline ? printMemberLookup(path, options, print) : group$2(indent$3(concat$6([softline$2, printMemberLookup(path, options, print)])))]);
31659 case "MetaProperty":
31660 return concat$6([path.call(print, "meta"), ".", path.call(print, "property")]);
31662 case "BindExpression":
31664 parts.push(path.call(print, "object"));
31667 parts.push(group$2(indent$3(concat$6([softline$2, printBindExpressionCallee(path, options, print)]))));
31668 return concat$6(parts);
31672 return concat$6([n.name, printOptionalToken(path), printTypeAnnotation(path, options, print)]);
31675 case "V8IntrinsicIdentifier":
31676 return concat$6(["%", n.name]);
31678 case "SpreadElement":
31679 case "SpreadElementPattern":
31680 case "RestProperty":
31681 case "SpreadProperty":
31682 case "SpreadPropertyPattern":
31683 case "RestElement":
31684 case "ObjectTypeSpreadProperty":
31685 return concat$6(["...", path.call(print, "argument"), printTypeAnnotation(path, options, print)]);
31687 case "FunctionDeclaration":
31688 case "FunctionExpression":
31689 parts.push(printFunctionDeclaration(path, print, options));
31695 return concat$6(parts);
31697 case "ArrowFunctionExpression":
31700 parts.push("async ");
31703 if (shouldPrintParamsWithoutParens(path, options)) {
31704 parts.push(path.call(print, "params", 0));
31706 parts.push(group$2(concat$6([printFunctionParams(path, print, options,
31708 args && (args.expandLastArg || args.expandFirstArg),
31709 /* printTypeParams */
31710 true), printReturnType(path, print, options)])));
31713 var dangling = comments.printDanglingComments(path, options,
31715 true, function (comment) {
31716 var nextCharacter = getNextNonSpaceNonCommentCharacterIndex$2(options.originalText, comment, options);
31717 return options.originalText.substr(nextCharacter, 2) === "=>";
31721 parts.push(" ", dangling);
31725 var body = path.call(function (bodyPath) {
31726 return print(bodyPath, args);
31727 }, "body"); // We want to always keep these types of nodes on the same line
31730 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")) {
31731 return group$2(concat$6([concat$6(parts), " ", body]));
31732 } // We handle sequence expressions as the body of arrows specially,
31733 // so that the required parentheses end up on their own lines.
31736 if (n.body.type === "SequenceExpression") {
31737 return group$2(concat$6([concat$6(parts), group$2(concat$6([" (", indent$3(concat$6([softline$2, body])), softline$2, ")"]))]));
31738 } // if the arrow function is expanded as last argument, we are adding a
31739 // level of indentation and need to add a softline to align the closing )
31740 // with the opening (, or if it's inside a JSXExpression (e.g. an attribute)
31741 // we should align the expression's closing } with the line with the opening {.
31744 var shouldAddSoftLine = (args && args.expandLastArg || path.getParentNode().type === "JSXExpressionContainer") && !(n.comments && n.comments.length);
31745 var printTrailingComma = args && args.expandLastArg && shouldPrintComma(options, "all"); // In order to avoid confusion between
31749 var shouldAddParens = n.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken$1(n.body,
31750 /* forbidFunctionAndClass */
31752 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]) : ""]))]));
31755 case "YieldExpression":
31756 parts.push("yield");
31763 parts.push(" ", path.call(print, "argument"));
31766 return concat$6(parts);
31768 case "AwaitExpression":
31770 parts.push("await ", path.call(print, "argument"));
31772 var _parent3 = path.getParentNode();
31774 if ((_parent3.type === "CallExpression" || _parent3.type === "OptionalCallExpression") && _parent3.callee === n || (_parent3.type === "MemberExpression" || _parent3.type === "OptionalMemberExpression") && _parent3.object === n) {
31775 return group$2(concat$6([indent$3(concat$6([softline$2, concat$6(parts)])), softline$2]));
31778 return concat$6(parts);
31781 case "ImportSpecifier":
31782 if (n.importKind) {
31783 parts.push(path.call(print, "importKind"), " ");
31786 parts.push(path.call(print, "imported"));
31788 if (n.local && n.local.name !== n.imported.name) {
31789 parts.push(" as ", path.call(print, "local"));
31792 return concat$6(parts);
31794 case "ExportSpecifier":
31795 parts.push(path.call(print, "local"));
31797 if (n.exported && n.exported.name !== n.local.name) {
31798 parts.push(" as ", path.call(print, "exported"));
31801 return concat$6(parts);
31803 case "ImportNamespaceSpecifier":
31804 parts.push("* as ");
31805 parts.push(path.call(print, "local"));
31806 return concat$6(parts);
31808 case "ImportDefaultSpecifier":
31809 return path.call(print, "local");
31811 case "TSExportAssignment":
31812 return concat$6(["export = ", path.call(print, "expression"), semi]);
31814 case "ExportDefaultDeclaration":
31815 case "ExportNamedDeclaration":
31816 return printExportDeclaration(path, options, print);
31818 case "ExportAllDeclaration":
31819 parts.push("export ");
31821 if (n.exportKind === "type") {
31822 parts.push("type ");
31825 parts.push("* from ", path.call(print, "source"), semi);
31826 return concat$6(parts);
31828 case "ExportNamespaceSpecifier":
31829 case "ExportDefaultSpecifier":
31830 return path.call(print, "exported");
31832 case "ImportDeclaration":
31834 parts.push("import ");
31836 if (n.importKind && n.importKind !== "value") {
31837 parts.push(n.importKind + " ");
31840 var standalones = [];
31843 if (n.specifiers && n.specifiers.length > 0) {
31844 path.each(function (specifierPath) {
31845 var value = specifierPath.getValue();
31847 if (value.type === "ImportDefaultSpecifier" || value.type === "ImportNamespaceSpecifier") {
31848 standalones.push(print(specifierPath));
31850 grouped.push(print(specifierPath));
31854 if (standalones.length > 0) {
31855 parts.push(join$4(", ", standalones));
31858 if (standalones.length > 0 && grouped.length > 0) {
31862 if (grouped.length === 1 && standalones.length === 0 && n.specifiers && !n.specifiers.some(function (node) {
31863 return node.comments;
31865 parts.push(concat$6(["{", options.bracketSpacing ? " " : "", concat$6(grouped), options.bracketSpacing ? " " : "", "}"]));
31866 } else if (grouped.length >= 1) {
31867 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, "}"])));
31870 parts.push(" from ");
31871 } else if (n.importKind && n.importKind === "type" || // import {} from 'x'
31872 /{\s*}/.test(options.originalText.slice(options.locStart(n), options.locStart(n.source)))) {
31873 parts.push("{} from ");
31876 parts.push(path.call(print, "source"), semi);
31877 return concat$6(parts);
31883 case "TSModuleBlock":
31884 case "BlockStatement":
31886 var naked = path.call(function (bodyPath) {
31887 return printStatementSequence(bodyPath, options, print);
31889 var hasContent = n.body.find(function (node) {
31890 return node.type !== "EmptyStatement";
31892 var hasDirectives = n.directives && n.directives.length > 0;
31894 var _parent4 = path.getParentNode();
31896 var _parentParent = path.getParentNode(1);
31898 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")) {
31902 parts.push("{"); // Babel 6
31904 if (hasDirectives) {
31905 path.each(function (childPath) {
31906 parts.push(indent$3(concat$6([hardline$4, print(childPath), semi])));
31908 if (isNextLineEmpty$2(options.originalText, childPath.getValue(), options)) {
31909 parts.push(hardline$4);
31915 parts.push(indent$3(concat$6([hardline$4, naked])));
31918 parts.push(comments.printDanglingComments(path, options));
31919 parts.push(hardline$4, "}");
31920 return concat$6(parts);
31923 case "ReturnStatement":
31924 parts.push("return");
31927 if (returnArgumentHasLeadingComment$1(options, n.argument)) {
31928 parts.push(concat$6([" (", indent$3(concat$6([hardline$4, path.call(print, "argument")])), hardline$4, ")"]));
31929 } else if (n.argument.type === "LogicalExpression" || n.argument.type === "BinaryExpression" || n.argument.type === "SequenceExpression") {
31930 parts.push(group$2(concat$6([ifBreak$1(" (", " "), indent$3(concat$6([softline$2, path.call(print, "argument")])), softline$2, ifBreak$1(")")])));
31932 parts.push(" ", path.call(print, "argument"));
31936 if (hasDanglingComments$1(n)) {
31937 parts.push(" ", comments.printDanglingComments(path, options,
31943 return concat$6(parts);
31945 case "NewExpression":
31946 case "OptionalCallExpression":
31947 case "CallExpression":
31949 var isNew = n.type === "NewExpression";
31950 var optional = printOptionalToken(path);
31952 if ( // We want to keep CommonJS- and AMD-style require calls, and AMD-style
31953 // define calls, as a unit.
31954 // e.g. `define(["some/lib", (lib) => {`
31955 !isNew && n.callee.type === "Identifier" && (n.callee.name === "require" || n.callee.name === "define") || // Template literals as single arguments
31956 n.arguments.length === 1 && isTemplateOnItsOwnLine$1(n.arguments[0], options.originalText, options) || // Keep test declarations on a single line
31957 // e.g. `it('long name', () => {`
31958 !isNew && isTestCall$1(n, path.getParentNode())) {
31959 return concat$6([isNew ? "new " : "", path.call(print, "callee"), optional, printFunctionTypeParameters(path, options, print), concat$6(["(", join$4(", ", path.map(print, "arguments")), ")"])]);
31960 } // Inline Flow annotation comments following Identifiers in Call nodes need to
31961 // stay with the Identifier. For example:
31963 // foo /*:: <SomeGeneric> */(bar);
31965 // Here, we ensure that such comments stay between the Identifier and the Callee.
31968 var isIdentifierWithFlowAnnotation = n.callee.type === "Identifier" && hasFlowAnnotationComment$1(n.callee.trailingComments);
31970 if (isIdentifierWithFlowAnnotation) {
31971 n.callee.trailingComments[0].printed = true;
31972 } // We detect calls on member lookups and possibly print them in a
31973 // special chain format. See `printMemberChain` for more info.
31976 if (!isNew && isMemberish$1(n.callee)) {
31977 return printMemberChain(path, options, print);
31980 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.
31981 // See `isLongCurriedCallExpression` for more info.
31983 if (isCallOrOptionalCallExpression$1(n.callee)) {
31984 return group$2(contents);
31990 case "TSInterfaceDeclaration":
31992 parts.push("declare ");
31995 parts.push(n.abstract ? "abstract " : "", printTypeScriptModifiers(path, options, print), "interface ", path.call(print, "id"), n.typeParameters ? path.call(print, "typeParameters") : "", " ");
31997 if (n.extends && n.extends.length) {
31998 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"))), " "]))));
32001 parts.push(path.call(print, "body"));
32002 return concat$6(parts);
32004 case "ObjectTypeInternalSlot":
32005 return concat$6([n.static ? "static " : "", "[[", path.call(print, "id"), "]]", printOptionalToken(path), n.method ? "" : ": ", path.call(print, "value")]);
32007 case "ObjectExpression":
32008 case "ObjectPattern":
32009 case "ObjectTypeAnnotation":
32010 case "TSInterfaceBody":
32011 case "TSTypeLiteral":
32013 var propertiesField;
32015 if (n.type === "TSTypeLiteral") {
32016 propertiesField = "members";
32017 } else if (n.type === "TSInterfaceBody") {
32018 propertiesField = "body";
32020 propertiesField = "properties";
32023 var isTypeAnnotation = n.type === "ObjectTypeAnnotation";
32026 if (isTypeAnnotation) {
32027 fields.push("indexers", "callProperties", "internalSlots");
32030 fields.push(propertiesField);
32031 var firstProperty = fields.map(function (field) {
32032 return n[field][0];
32033 }).sort(function (a, b) {
32034 return options.locStart(a) - options.locStart(b);
32037 var _parent5 = path.getParentNode(0);
32039 var isFlowInterfaceLikeBody = isTypeAnnotation && _parent5 && (_parent5.type === "InterfaceDeclaration" || _parent5.type === "DeclareInterface" || _parent5.type === "DeclareClass") && path.getName() === "body";
32040 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) {
32041 return property.value && (property.value.type === "ObjectPattern" || property.value.type === "ArrayPattern");
32042 }) || n.type !== "ObjectPattern" && firstProperty && hasNewlineInRange$2(options.originalText, options.locStart(n), options.locStart(firstProperty));
32043 var separator = isFlowInterfaceLikeBody ? ";" : n.type === "TSInterfaceBody" || n.type === "TSTypeLiteral" ? ifBreak$1(semi, ";") : ",";
32044 var leftBrace = n.exact ? "{|" : "{";
32045 var rightBrace = n.exact ? "|}" : "}"; // Unfortunately, things are grouped together in the ast can be
32046 // interleaved in the source code. So we need to reorder them before
32049 var propsAndLoc = [];
32050 fields.forEach(function (field) {
32051 path.each(function (childPath) {
32052 var node = childPath.getValue();
32055 printed: print(childPath),
32056 loc: options.locStart(node)
32060 var separatorParts = [];
32061 var props = propsAndLoc.sort(function (a, b) {
32062 return a.loc - b.loc;
32063 }).map(function (prop) {
32064 var result = concat$6(separatorParts.concat(group$2(prop.printed)));
32065 separatorParts = [separator, line$2];
32067 if ((prop.node.type === "TSPropertySignature" || prop.node.type === "TSMethodSignature" || prop.node.type === "TSConstructSignatureDeclaration") && hasNodeIgnoreComment$2(prop.node)) {
32068 separatorParts.shift();
32071 if (isNextLineEmpty$2(options.originalText, prop.node, options)) {
32072 separatorParts.push(hardline$4);
32079 props.push(concat$6(separatorParts.concat(group$2("..."))));
32082 var lastElem = getLast$2(n[propertiesField]);
32083 var canHaveTrailingSeparator = !(lastElem && (lastElem.type === "RestProperty" || lastElem.type === "RestElement" || hasNodeIgnoreComment$2(lastElem) || n.inexact));
32086 if (props.length === 0) {
32087 if (!hasDanglingComments$1(n)) {
32088 return concat$6([leftBrace, rightBrace, printTypeAnnotation(path, options, print)]);
32091 content = group$2(concat$6([leftBrace, comments.printDanglingComments(path, options), softline$2, rightBrace, printOptionalToken(path), printTypeAnnotation(path, options, print)]));
32093 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)]);
32094 } // If we inline the object as first argument of the parent, we don't want
32095 // to create another group so that the object breaks before the return
32099 var parentParentParent = path.getParentNode(2);
32101 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) {
32105 return group$2(content, {
32111 case "ObjectProperty": // Non-standard AST node type.
32114 if (n.method || n.kind === "get" || n.kind === "set") {
32115 return printMethod(path, options, print);
32119 parts.push(path.call(print, "value"));
32121 parts.push(printAssignment(n.key, printPropertyKey(path, options, print), ":", n.value, path.call(print, "value"), options));
32124 return concat$6(parts);
32127 case "ClassMethod":
32128 case "ClassPrivateMethod":
32129 case "MethodDefinition":
32130 case "TSAbstractMethodDefinition":
32131 if (n.decorators && n.decorators.length !== 0) {
32132 parts.push(printDecorators(path, options, print));
32135 if (n.accessibility) {
32136 parts.push(n.accessibility + " ");
32140 parts.push("static ");
32143 if (n.type === "TSAbstractMethodDefinition") {
32144 parts.push("abstract ");
32147 parts.push(printMethod(path, options, print));
32148 return concat$6(parts);
32150 case "ObjectMethod":
32151 return printMethod(path, options, print);
32154 return concat$6(["@", path.call(print, "expression"), path.call(print, "callee")]);
32156 case "ArrayExpression":
32157 case "ArrayPattern":
32158 if (n.elements.length === 0) {
32159 if (!hasDanglingComments$1(n)) {
32162 parts.push(group$2(concat$6(["[", comments.printDanglingComments(path, options), softline$2, "]"])));
32165 var _lastElem = getLast$2(n.elements);
32167 var canHaveTrailingComma = !(_lastElem && _lastElem.type === "RestElement"); // JavaScript allows you to have empty elements in an array which
32168 // changes its length based on the number of commas. The algorithm
32169 // is that if the last argument is null, we need to force insert
32170 // a comma to ensure JavaScript recognizes it.
32171 // [,].length === 1
32172 // [1,].length === 1
32173 // [1,,].length === 2
32175 // Note that getLast returns null if the array is empty, but
32176 // we already check for an empty array just above so we are safe
32178 var needsForcedTrailingComma = canHaveTrailingComma && _lastElem === null;
32180 var _shouldBreak = n.elements.length > 1 && n.elements.every(function (element, i, elements) {
32181 var elementType = element && element.type;
32183 if (elementType !== "ArrayExpression" && elementType !== "ObjectExpression") {
32187 var nextElement = elements[i + 1];
32189 if (nextElement && elementType !== nextElement.type) {
32193 var itemsKey = elementType === "ArrayExpression" ? "elements" : "properties";
32194 return element[itemsKey] && element[itemsKey].length > 1;
32197 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,
32199 true), softline$2, "]"]), {
32200 shouldBreak: _shouldBreak
32204 parts.push(printOptionalToken(path), printTypeAnnotation(path, options, print));
32205 return concat$6(parts);
32207 case "SequenceExpression":
32209 var _parent6 = path.getParentNode(0);
32211 if (_parent6.type === "ExpressionStatement" || _parent6.type === "ForStatement") {
32212 // For ExpressionStatements and for-loop heads, which are among
32213 // the few places a SequenceExpression appears unparenthesized, we want
32214 // to indent expressions after the first.
32216 path.each(function (p) {
32217 if (p.getName() === 0) {
32218 _parts2.push(print(p));
32220 _parts2.push(",", indent$3(concat$6([line$2, print(p)])));
32223 return group$2(concat$6(_parts2));
32226 return group$2(concat$6([join$4(concat$6([",", line$2]), path.map(print, "expressions"))]));
32229 case "ThisExpression":
32235 case "NullLiteral":
32236 // Babel 6 Literal split
32239 case "RegExpLiteral":
32240 // Babel 6 Literal split
32241 return printRegex(n);
32243 case "NumericLiteral":
32244 // Babel 6 Literal split
32245 return printNumber$1(n.extra.raw);
32247 case "BigIntLiteral":
32248 // babel: n.extra.raw, typescript: n.raw, flow: n.bigint
32249 return (n.bigint || (n.extra ? n.extra.raw : n.raw)).toLowerCase();
32251 case "BooleanLiteral": // Babel 6 Literal split
32253 case "StringLiteral": // Babel 6 Literal split
32258 return printRegex(n.regex);
32261 if (typeof n.value === "number") {
32262 return printNumber$1(n.raw);
32265 if (typeof n.value !== "string") {
32266 return "" + n.value;
32267 } // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2
32268 // See corresponding workaround in needs-parens.js
32271 var grandParent = path.getParentNode(1);
32272 var isTypeScriptDirective = options.parser === "typescript" && typeof n.value === "string" && grandParent && (grandParent.type === "Program" || grandParent.type === "BlockStatement");
32273 return nodeStr(n, options, isTypeScriptDirective);
32277 return path.call(print, "value");
32280 case "DirectiveLiteral":
32281 return nodeStr(n, options);
32283 case "UnaryExpression":
32284 parts.push(n.operator);
32286 if (/[a-z]$/.test(n.operator)) {
32290 if (n.argument.comments && n.argument.comments.length > 0) {
32291 parts.push(group$2(concat$6(["(", indent$3(concat$6([softline$2, path.call(print, "argument")])), softline$2, ")"])));
32293 parts.push(path.call(print, "argument"));
32296 return concat$6(parts);
32298 case "UpdateExpression":
32299 parts.push(path.call(print, "argument"), n.operator);
32305 return concat$6(parts);
32307 case "ConditionalExpression":
32308 return printTernaryOperator(path, options, print, {
32309 beforeParts: function beforeParts() {
32310 return [path.call(print, "test")];
32312 afterParts: function afterParts(breakClosingParen) {
32313 return [breakClosingParen ? softline$2 : ""];
32315 shouldCheckJsx: true,
32316 conditionalNodeType: "ConditionalExpression",
32317 consequentNodePropertyName: "consequent",
32318 alternateNodePropertyName: "alternate",
32319 testNodePropertyName: "test",
32323 case "VariableDeclaration":
32325 var printed = path.map(function (childPath) {
32326 return print(childPath);
32327 }, "declarations"); // We generally want to terminate all variable declarations with a
32328 // semicolon, except when they in the () part of for loops.
32330 var parentNode = path.getParentNode();
32331 var isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement" || parentNode.type === "ForAwaitStatement";
32332 var hasValue = n.declarations.some(function (decl) {
32337 if (printed.length === 1 && !n.declarations[0].comments) {
32338 firstVariable = printed[0];
32339 } else if (printed.length > 0) {
32340 // Indent first var to comply with eslint one-var rule
32341 firstVariable = indent$3(printed[0]);
32344 parts = [n.declare ? "declare " : "", n.kind, firstVariable ? concat$6([" ", firstVariable]) : "", indent$3(concat$6(printed.slice(1).map(function (p) {
32345 return concat$6([",", hasValue && !isParentForLoop ? hardline$4 : line$2, p]);
32348 if (!(isParentForLoop && parentNode.body !== n)) {
32352 return group$2(concat$6(parts));
32355 case "TSTypeAliasDeclaration":
32358 parts.push("declare ");
32361 var _printed = printAssignmentRight(n.id, n.typeAnnotation, n.typeAnnotation && path.call(print, "typeAnnotation"), options);
32363 parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", _printed, semi);
32364 return group$2(concat$6(parts));
32367 case "VariableDeclarator":
32368 return printAssignment(n.id, path.call(print, "id"), " =", n.init, n.init && path.call(print, "init"), options);
32370 case "WithStatement":
32371 return group$2(concat$6(["with (", path.call(print, "object"), ")", adjustClause(n.body, path.call(print, "body"))]));
32373 case "IfStatement":
32375 var con = adjustClause(n.consequent, path.call(print, "consequent"));
32376 var opening = group$2(concat$6(["if (", group$2(concat$6([indent$3(concat$6([softline$2, path.call(print, "test")])), softline$2])), ")", con]));
32377 parts.push(opening);
32380 var commentOnOwnLine = hasTrailingComment$1(n.consequent) && n.consequent.comments.some(function (comment) {
32381 return comment.trailing && !comments$1.isBlockComment(comment);
32382 }) || needsHardlineAfterDanglingComment$1(n);
32383 var elseOnSameLine = n.consequent.type === "BlockStatement" && !commentOnOwnLine;
32384 parts.push(elseOnSameLine ? " " : hardline$4);
32386 if (hasDanglingComments$1(n)) {
32387 parts.push(comments.printDanglingComments(path, options, true), commentOnOwnLine ? hardline$4 : " ");
32390 parts.push("else", group$2(adjustClause(n.alternate, path.call(print, "alternate"), n.alternate.type === "IfStatement")));
32393 return concat$6(parts);
32396 case "ForStatement":
32398 var _body = adjustClause(n.body, path.call(print, "body")); // We want to keep dangling comments above the loop to stay consistent.
32399 // Any comment positioned between the for statement and the parentheses
32400 // is going to be printed before the statement.
32403 var _dangling = comments.printDanglingComments(path, options,
32407 var printedComments = _dangling ? concat$6([_dangling, softline$2]) : "";
32409 if (!n.init && !n.test && !n.update) {
32410 return concat$6([printedComments, group$2(concat$6(["for (;;)", _body]))]);
32413 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]))]);
32416 case "WhileStatement":
32417 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"))]));
32419 case "ForInStatement":
32420 // Note: esprima can't actually parse "for each (".
32421 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"))]));
32423 case "ForOfStatement":
32424 case "ForAwaitStatement":
32426 // Babel 7 removed ForAwaitStatement in favor of ForOfStatement
32427 // with `"await": true`:
32428 // https://github.com/estree/estree/pull/138
32429 var isAwait = n.type === "ForAwaitStatement" || n.await;
32430 return group$2(concat$6(["for", isAwait ? " await" : "", " (", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))]));
32433 case "DoWhileStatement":
32435 var clause = adjustClause(n.body, path.call(print, "body"));
32436 var doBody = group$2(concat$6(["do", clause]));
32439 if (n.body.type === "BlockStatement") {
32442 parts.push(hardline$4);
32445 parts.push("while (");
32446 parts.push(group$2(concat$6([indent$3(concat$6([softline$2, path.call(print, "test")])), softline$2])), ")", semi);
32447 return concat$6(parts);
32450 case "DoExpression":
32451 return concat$6(["do ", path.call(print, "body")]);
32453 case "BreakStatement":
32454 parts.push("break");
32457 parts.push(" ", path.call(print, "label"));
32461 return concat$6(parts);
32463 case "ContinueStatement":
32464 parts.push("continue");
32467 parts.push(" ", path.call(print, "label"));
32471 return concat$6(parts);
32473 case "LabeledStatement":
32474 if (n.body.type === "EmptyStatement") {
32475 return concat$6([path.call(print, "label"), ":;"]);
32478 return concat$6([path.call(print, "label"), ": ", path.call(print, "body")]);
32480 case "TryStatement":
32481 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")]) : ""]);
32483 case "CatchClause":
32485 var hasComments = n.param.comments && n.param.comments.some(function (comment) {
32486 return !comments$1.isBlockComment(comment) || comment.leading && hasNewline$3(options.originalText, options.locEnd(comment)) || comment.trailing && hasNewline$3(options.originalText, options.locStart(comment), {
32490 var param = path.call(print, "param");
32491 return concat$6(["catch ", hasComments ? concat$6(["(", indent$3(concat$6([softline$2, param])), softline$2, ") "]) : concat$6(["(", param, ") "]), path.call(print, "body")]);
32494 return concat$6(["catch ", path.call(print, "body")]);
32496 case "ThrowStatement":
32497 return concat$6(["throw ", path.call(print, "argument"), semi]);
32498 // Note: ignoring n.lexical because it has no printing consequences.
32500 case "SwitchStatement":
32501 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) {
32502 var caseNode = casePath.getValue();
32503 return concat$6([casePath.call(print), n.cases.indexOf(caseNode) !== n.cases.length - 1 && isNextLineEmpty$2(options.originalText, caseNode, options) ? hardline$4 : ""]);
32504 }, "cases"))])) : "", hardline$4, "}"]);
32509 parts.push("case ", path.call(print, "test"), ":");
32511 parts.push("default:");
32514 var consequent = n.consequent.filter(function (node) {
32515 return node.type !== "EmptyStatement";
32518 if (consequent.length > 0) {
32519 var cons = path.call(function (consequentPath) {
32520 return printStatementSequence(consequentPath, options, print);
32522 parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? concat$6([" ", cons]) : indent$3(concat$6([hardline$4, cons])));
32525 return concat$6(parts);
32527 // JSX extensions below.
32529 case "DebuggerStatement":
32530 return concat$6(["debugger", semi]);
32532 case "JSXAttribute":
32533 parts.push(path.call(print, "name"));
32538 if (isStringLiteral$1(n.value)) {
32539 var raw = rawText$1(n.value); // Unescape all quotes so we get an accurate preferred quote
32541 var final = raw.replace(/'/g, "'").replace(/"/g, '"');
32542 var quote = getPreferredQuote$1(final, options.jsxSingleQuote ? "'" : '"');
32544 var _escape = quote === "'" ? "'" : """;
32546 final = final.slice(1, -1).replace(new RegExp(quote, "g"), _escape);
32547 res = concat$6([quote, final, quote]);
32549 res = path.call(print, "value");
32552 parts.push("=", res);
32555 return concat$6(parts);
32557 case "JSXIdentifier":
32558 return "" + n.name;
32560 case "JSXNamespacedName":
32561 return join$4(":", [path.call(print, "namespace"), path.call(print, "name")]);
32563 case "JSXMemberExpression":
32564 return join$4(".", [path.call(print, "object"), path.call(print, "property")]);
32566 case "TSQualifiedName":
32567 return join$4(".", [path.call(print, "left"), path.call(print, "right")]);
32569 case "JSXSpreadAttribute":
32570 case "JSXSpreadChild":
32572 return concat$6(["{", path.call(function (p) {
32573 var printed = concat$6(["...", print(p)]);
32574 var n = p.getValue();
32576 if (!n.comments || !n.comments.length) {
32580 return concat$6([indent$3(concat$6([softline$2, comments.printComments(p, function () {
32582 }, options)])), softline$2]);
32583 }, n.type === "JSXSpreadAttribute" ? "argument" : "expression"), "}"]);
32586 case "JSXExpressionContainer":
32588 var _parent7 = path.getParentNode(0);
32590 var preventInline = _parent7.type === "JSXAttribute" && n.expression.comments && n.expression.comments.length > 0;
32592 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)));
32594 if (_shouldInline) {
32595 return group$2(concat$6(["{", path.call(print, "expression"), lineSuffixBoundary$1, "}"]));
32598 return group$2(concat$6(["{", indent$3(concat$6([softline$2, path.call(print, "expression")])), softline$2, lineSuffixBoundary$1, "}"]));
32601 case "JSXFragment":
32604 var elem = comments.printComments(path, function () {
32605 return printJSXElement(path, options, print);
32607 return maybeWrapJSXElementInParens(path, elem, options);
32610 case "JSXOpeningElement":
32612 var _n = path.getValue();
32614 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
32616 if (_n.selfClosing && !_n.attributes.length && !nameHasComments) {
32617 return concat$6(["<", path.call(print, "name"), path.call(print, "typeParameters"), " />"]);
32618 } // don't break up opening elements with a single long text attribute
32621 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:
32630 !nameHasComments && (!_n.attributes[0].comments || !_n.attributes[0].comments.length)) {
32631 return group$2(concat$6(["<", path.call(print, "name"), path.call(print, "typeParameters"), " ", concat$6(path.map(print, "attributes")), _n.selfClosing ? " />" : ">"]));
32634 var lastAttrHasTrailingComments = _n.attributes.length && hasTrailingComment$1(getLast$2(_n.attributes));
32635 var bracketSameLine = // Simple tags (no attributes and no comment in tag name) should be
32636 // kept unbroken regardless of `jsxBracketSameLine`
32637 !_n.attributes.length && !nameHasComments || options.jsxBracketSameLine && ( // We should print the bracket in a new line for the following cases:
32644 !nameHasComments || _n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a
32645 // string literal with newlines
32647 var _shouldBreak2 = _n.attributes && _n.attributes.some(function (attr) {
32648 return attr.value && isStringLiteral$1(attr.value) && attr.value.value.includes("\n");
32651 return group$2(concat$6(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$6([indent$3(concat$6(path.map(function (attr) {
32652 return concat$6([line$2, print(attr)]);
32653 }, "attributes"))), _n.selfClosing ? line$2 : bracketSameLine ? ">" : softline$2]), _n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), {
32654 shouldBreak: _shouldBreak2
32658 case "JSXClosingElement":
32659 return concat$6(["</", path.call(print, "name"), ">"]);
32661 case "JSXOpeningFragment":
32662 case "JSXClosingFragment":
32664 var hasComment = n.comments && n.comments.length;
32665 var hasOwnLineComment = hasComment && !n.comments.every(comments$1.isBlockComment);
32666 var isOpeningFragment = n.type === "JSXOpeningFragment";
32667 return concat$6([isOpeningFragment ? "<" : "</", indent$3(concat$6([hasOwnLineComment ? hardline$4 : hasComment && !isOpeningFragment ? " " : "", comments.printDanglingComments(path, options, true)])), hasOwnLineComment ? hardline$4 : "", ">"]);
32671 /* istanbul ignore next */
32672 throw new Error("JSXTest should be handled by JSXElement");
32674 case "JSXEmptyExpression":
32676 var requiresHardline = n.comments && !n.comments.every(comments$1.isBlockComment);
32677 return concat$6([comments.printDanglingComments(path, options,
32679 !requiresHardline), requiresHardline ? hardline$4 : ""]);
32683 if (!n.comments && n.body.length === 0) {
32687 return concat$6(["{", n.body.length > 0 ? indent$3(concat$6([hardline$4, path.call(function (bodyPath) {
32688 return printStatementSequence(bodyPath, options, print);
32689 }, "body")])) : comments.printDanglingComments(path, options), hardline$4, "}"]);
32691 case "ClassProperty":
32692 case "TSAbstractClassProperty":
32693 case "ClassPrivateProperty":
32695 if (n.decorators && n.decorators.length !== 0) {
32696 parts.push(printDecorators(path, options, print));
32699 if (n.accessibility) {
32700 parts.push(n.accessibility + " ");
32704 parts.push("declare ");
32708 parts.push("static ");
32711 if (n.type === "TSAbstractClassProperty") {
32712 parts.push("abstract ");
32716 parts.push("readonly ");
32719 var variance = getFlowVariance$1(n);
32722 parts.push(variance);
32725 parts.push(printPropertyKey(path, options, print), printOptionalToken(path), printTypeAnnotation(path, options, print));
32728 parts.push(" =", printAssignmentRight(n.key, n.value, path.call(print, "value"), options));
32732 return group$2(concat$6(parts));
32735 case "ClassDeclaration":
32736 case "ClassExpression":
32738 parts.push("declare ");
32741 parts.push(concat$6(printClass(path, options, print)));
32742 return concat$6(parts);
32744 case "TSInterfaceHeritage":
32745 parts.push(path.call(print, "expression"));
32747 if (n.typeParameters) {
32748 parts.push(path.call(print, "typeParameters"));
32751 return concat$6(parts);
32753 case "TemplateElement":
32754 return join$4(literalline$2, n.value.raw.split(/\r?\n/g));
32756 case "TemplateLiteral":
32758 var expressions = path.map(print, "expressions");
32760 var _parentNode = path.getParentNode();
32762 if (isJestEachTemplateLiteral$1(n, _parentNode)) {
32763 var _printed2 = printJestEachTemplateLiteral(n, expressions, options);
32770 var isSimple = isSimpleTemplateLiteral$1(n);
32773 expressions = expressions.map(function (doc) {
32774 return printDocToString$2(doc, Object.assign({}, options, {
32775 printWidth: Infinity
32780 parts.push(lineSuffixBoundary$1, "`");
32781 path.each(function (childPath) {
32782 var i = childPath.getName();
32783 parts.push(print(childPath));
32785 if (i < expressions.length) {
32786 // For a template literal of the following form:
32793 // the expression is on its own line (there is a \n in the previous
32794 // quasi literal), therefore we want to indent the JavaScript
32795 // expression inside at the beginning of ${ instead of the beginning
32797 var tabWidth = options.tabWidth;
32798 var quasi = childPath.getValue();
32799 var indentSize = getIndentSize$1(quasi.value.raw, tabWidth);
32800 var _printed3 = expressions[i];
32803 // Breaks at the template element boundaries (${ and }) are preferred to breaking
32804 // in the middle of a MemberExpression
32805 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") {
32806 _printed3 = concat$6([indent$3(concat$6([softline$2, _printed3])), softline$2]);
32810 var aligned = indentSize === 0 && quasi.value.raw.endsWith("\n") ? align$1(-Infinity, _printed3) : addAlignmentToDoc$2(_printed3, indentSize, tabWidth);
32811 parts.push(group$2(concat$6(["${", aligned, lineSuffixBoundary$1, "}"])));
32815 return concat$6(parts);
32817 // These types are unprintable because they serve as abstract
32818 // supertypes for other (printable) types.
32820 case "TaggedTemplateExpression":
32821 return concat$6([path.call(print, "tag"), path.call(print, "typeParameters"), path.call(print, "quasi")]);
32825 case "SourceLocation":
32831 case "Declaration":
32833 case "NamedSpecifier":
32835 case "MemberTypeAnnotation": // Flow
32838 /* istanbul ignore next */
32839 throw new Error("unprintable type: " + JSON.stringify(n.type));
32840 // Type Annotations for Facebook Flow, typically stripped out or
32841 // transformed away before printing.
32843 case "TypeAnnotation":
32844 case "TSTypeAnnotation":
32845 if (n.typeAnnotation) {
32846 return path.call(print, "typeAnnotation");
32848 /* istanbul ignore next */
32853 case "TSTupleType":
32854 case "TupleTypeAnnotation":
32856 var typesField = n.type === "TSTupleType" ? "elementTypes" : "types";
32857 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,
32859 true), softline$2, "]"]));
32862 case "ExistsTypeAnnotation":
32865 case "EmptyTypeAnnotation":
32868 case "AnyTypeAnnotation":
32871 case "MixedTypeAnnotation":
32874 case "ArrayTypeAnnotation":
32875 return concat$6([path.call(print, "elementType"), "[]"]);
32877 case "BooleanTypeAnnotation":
32880 case "BooleanLiteralTypeAnnotation":
32881 return "" + n.value;
32883 case "DeclareClass":
32884 return printFlowDeclaration(path, printClass(path, options, print));
32886 case "TSDeclareFunction":
32887 // For TypeScript the TSDeclareFunction node shares the AST
32888 // structure with FunctionDeclaration
32889 return concat$6([n.declare ? "declare " : "", printFunctionDeclaration(path, print, options), semi]);
32891 case "DeclareFunction":
32892 return printFlowDeclaration(path, ["function ", path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), semi]);
32894 case "DeclareModule":
32895 return printFlowDeclaration(path, ["module ", path.call(print, "id"), " ", path.call(print, "body")]);
32897 case "DeclareModuleExports":
32898 return printFlowDeclaration(path, ["module.exports", ": ", path.call(print, "typeAnnotation"), semi]);
32900 case "DeclareVariable":
32901 return printFlowDeclaration(path, ["var ", path.call(print, "id"), semi]);
32903 case "DeclareExportAllDeclaration":
32904 return concat$6(["declare export * from ", path.call(print, "source")]);
32906 case "DeclareExportDeclaration":
32907 return concat$6(["declare ", printExportDeclaration(path, options, print)]);
32909 case "DeclareOpaqueType":
32912 parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters"));
32915 parts.push(": ", path.call(print, "supertype"));
32919 parts.push(" = ", path.call(print, "impltype"));
32924 if (n.type === "DeclareOpaqueType") {
32925 return printFlowDeclaration(path, parts);
32928 return concat$6(parts);
32931 case "EnumDeclaration":
32932 return concat$6(["enum ", path.call(print, "id"), " ", path.call(print, "body")]);
32934 case "EnumBooleanBody":
32935 case "EnumNumberBody":
32936 case "EnumStringBody":
32937 case "EnumSymbolBody":
32939 if (n.type === "EnumSymbolBody" || n.explicitType) {
32943 case "EnumBooleanBody":
32947 case "EnumNumberBody":
32951 case "EnumStringBody":
32955 case "EnumSymbolBody":
32960 parts.push("of ", type, " ");
32963 if (n.members.length === 0) {
32964 parts.push(group$2(concat$6(["{", comments.printDanglingComments(path, options), softline$2, "}"])));
32966 parts.push(group$2(concat$6(["{", indent$3(concat$6([hardline$4, printArrayItems(path, options, "members", print), shouldPrintComma(options) ? "," : ""])), comments.printDanglingComments(path, options,
32968 true), hardline$4, "}"])));
32971 return concat$6(parts);
32974 case "EnumBooleanMember":
32975 case "EnumNumberMember":
32976 case "EnumStringMember":
32977 return concat$6([path.call(print, "id"), " = ", typeof n.init === "object" ? path.call(print, "init") : String(n.init)]);
32979 case "EnumDefaultedMember":
32980 return path.call(print, "id");
32982 case "FunctionTypeAnnotation":
32983 case "TSFunctionType":
32985 // FunctionTypeAnnotation is ambiguous:
32986 // declare function foo(a: B): void; OR
32987 // var A: (a: B) => void;
32988 var _parent8 = path.getParentNode(0);
32990 var _parentParent2 = path.getParentNode(1);
32992 var _parentParentParent = path.getParentNode(2);
32994 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");
32995 var needsColon = isArrowFunctionTypeAnnotation && (_parent8.type === "TypeAnnotation" || _parent8.type === "TSTypeAnnotation"); // Sadly we can't put it inside of FastPath::needsColon because we are
32996 // printing ":" as part of the expression and it would put parenthesis
32999 var needsParens = needsColon && isArrowFunctionTypeAnnotation && (_parent8.type === "TypeAnnotation" || _parent8.type === "TSTypeAnnotation") && _parentParent2.type === "ArrowFunctionExpression";
33001 if (isObjectTypePropertyAFunction$1(_parent8, options)) {
33002 isArrowFunctionTypeAnnotation = true;
33010 parts.push(printFunctionParams(path, print, options,
33013 /* printTypeParams */
33014 true)); // The returnType is not wrapped in a TypeAnnotation, so the colon
33015 // needs to be added separately.
33017 if (n.returnType || n.predicate || n.typeAnnotation) {
33018 parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType"), path.call(print, "predicate"), path.call(print, "typeAnnotation"));
33025 return group$2(concat$6(parts));
33029 return concat$6(["...", path.call(print, "typeAnnotation")]);
33031 case "TSOptionalType":
33032 return concat$6([path.call(print, "typeAnnotation"), "?"]);
33034 case "FunctionTypeParam":
33035 return concat$6([path.call(print, "name"), printOptionalToken(path), n.name ? ": " : "", path.call(print, "typeAnnotation")]);
33037 case "GenericTypeAnnotation":
33038 return concat$6([path.call(print, "id"), path.call(print, "typeParameters")]);
33040 case "DeclareInterface":
33041 case "InterfaceDeclaration":
33042 case "InterfaceTypeAnnotation":
33044 if (n.type === "DeclareInterface" || n.declare) {
33045 parts.push("declare ");
33048 parts.push("interface");
33050 if (n.type === "DeclareInterface" || n.type === "InterfaceDeclaration") {
33051 parts.push(" ", path.call(print, "id"), path.call(print, "typeParameters"));
33054 if (n["extends"].length > 0) {
33055 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")))]))));
33058 parts.push(" ", path.call(print, "body"));
33059 return group$2(concat$6(parts));
33062 case "ClassImplements":
33063 case "InterfaceExtends":
33064 return concat$6([path.call(print, "id"), path.call(print, "typeParameters")]);
33066 case "TSClassImplements":
33067 return concat$6([path.call(print, "expression"), path.call(print, "typeParameters")]);
33069 case "TSIntersectionType":
33070 case "IntersectionTypeAnnotation":
33072 var types = path.map(print, "types");
33074 var wasIndented = false;
33076 for (var _i = 0; _i < types.length; ++_i) {
33078 result.push(types[_i]);
33079 } else if (isObjectType$1(n.types[_i - 1]) && isObjectType$1(n.types[_i])) {
33080 // If both are objects, don't indent
33081 result.push(concat$6([" & ", wasIndented ? indent$3(types[_i]) : types[_i]]));
33082 } else if (!isObjectType$1(n.types[_i - 1]) && !isObjectType$1(n.types[_i])) {
33083 // If no object is involved, go to the next line if it breaks
33084 result.push(indent$3(concat$6([" &", line$2, types[_i]])));
33086 // If you go from object to non-object or vis-versa, then inline it
33088 wasIndented = true;
33091 result.push(" & ", _i > 1 ? indent$3(types[_i]) : types[_i]);
33095 return group$2(concat$6(result));
33098 case "TSUnionType":
33099 case "UnionTypeAnnotation":
33101 // single-line variation
33103 // multi-line variation
33107 var _parent9 = path.getParentNode(); // If there's a leading comment, the parent is doing the indentation
33110 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)); // {
33113 // should be inlined and not be printed in the multi-line variant
33115 var shouldHug = shouldHugType(n); // We want to align the children but without its comment, so it looks like
33120 var _printed4 = path.map(function (typePath) {
33121 var printedType = typePath.call(print);
33124 printedType = align$1(2, printedType);
33127 return comments.printComments(typePath, function () {
33128 return printedType;
33133 return join$4(" | ", _printed4);
33136 var shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment$1(options.originalText, n, options);
33137 var code = concat$6([ifBreak$1(concat$6([shouldAddStartLine ? line$2 : "", "| "])), join$4(concat$6([line$2, "| "]), _printed4)]);
33139 if (needsParens_1(path, options)) {
33140 return group$2(concat$6([indent$3(code), softline$2]));
33143 if (_parent9.type === "TupleTypeAnnotation" && _parent9.types.length > 1 || _parent9.type === "TSTupleType" && _parent9.elementTypes.length > 1) {
33144 return group$2(concat$6([indent$3(concat$6([ifBreak$1(concat$6(["(", softline$2])), code])), softline$2, ifBreak$1(")")]));
33147 return group$2(shouldIndent ? indent$3(code) : code);
33150 case "NullableTypeAnnotation":
33151 return concat$6(["?", path.call(print, "typeAnnotation")]);
33153 case "TSNullKeyword":
33154 case "NullLiteralTypeAnnotation":
33157 case "ThisTypeAnnotation":
33160 case "NumberTypeAnnotation":
33163 case "ObjectTypeCallProperty":
33165 parts.push("static ");
33168 parts.push(path.call(print, "value"));
33169 return concat$6(parts);
33171 case "ObjectTypeIndexer":
33173 var _variance = getFlowVariance$1(n);
33175 return concat$6([_variance || "", "[", path.call(print, "id"), n.id ? ": " : "", path.call(print, "key"), "]: ", path.call(print, "value")]);
33178 case "ObjectTypeProperty":
33180 var _variance2 = getFlowVariance$1(n);
33185 modifier = "proto ";
33186 } else if (n.static) {
33187 modifier = "static ";
33190 return concat$6([modifier, isGetterOrSetter$1(n) ? n.kind + " " : "", _variance2 || "", printPropertyKey(path, options, print), printOptionalToken(path), isFunctionNotation$1(n, options) ? "" : ": ", path.call(print, "value")]);
33193 case "QualifiedTypeIdentifier":
33194 return concat$6([path.call(print, "qualification"), ".", path.call(print, "id")]);
33196 case "StringLiteralTypeAnnotation":
33197 return nodeStr(n, options);
33199 case "NumberLiteralTypeAnnotation":
33200 assert$1.strictEqual(typeof n.value, "number");
33202 if (n.extra != null) {
33203 return printNumber$1(n.extra.raw);
33206 return printNumber$1(n.raw);
33208 case "StringTypeAnnotation":
33211 case "DeclareTypeAlias":
33214 if (n.type === "DeclareTypeAlias" || n.declare) {
33215 parts.push("declare ");
33218 var _printed5 = printAssignmentRight(n.id, n.right, path.call(print, "right"), options);
33220 parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", _printed5, semi);
33221 return group$2(concat$6(parts));
33224 case "TypeCastExpression":
33226 var value = path.getValue(); // Flow supports a comment syntax for specifying type annotations: https://flow.org/en/docs/types/comments/.
33227 // Unfortunately, its parser doesn't differentiate between comment annotations and regular
33228 // annotations when producing an AST. So to preserve parentheses around type casts that use
33229 // the comment syntax, we need to hackily read the source itself to see if the code contains
33230 // a type annotation comment.
33232 // Note that we're able to use the normal whitespace regex here because the Flow parser has
33233 // already deemed this AST node to be a type cast. Only the Babel parser needs the
33234 // non-line-break whitespace regex, which is why hasFlowShorthandAnnotationComment() is
33235 // implemented differently.
33237 var commentSyntax = value && value.typeAnnotation && value.typeAnnotation.range && options.originalText.substring(value.typeAnnotation.range[0]).match(/^\/\*\s*:/);
33238 return concat$6(["(", path.call(print, "expression"), commentSyntax ? " /*" : "", ": ", path.call(print, "typeAnnotation"), commentSyntax ? " */" : "", ")"]);
33241 case "TypeParameterDeclaration":
33242 case "TypeParameterInstantiation":
33244 var _value = path.getValue();
33246 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
33247 // because we know for sure that this is a type definition.
33249 var _commentSyntax = commentStart >= 0 && options.originalText.substring(commentStart).match(/^\/\*\s*::/);
33251 if (_commentSyntax) {
33252 return concat$6(["/*:: ", printTypeParameters(path, options, print, "params"), " */"]);
33255 return printTypeParameters(path, options, print, "params");
33258 case "TSTypeParameterDeclaration":
33259 case "TSTypeParameterInstantiation":
33260 return printTypeParameters(path, options, print, "params");
33262 case "TSTypeParameter":
33263 case "TypeParameter":
33265 var _parent10 = path.getParentNode();
33267 if (_parent10.type === "TSMappedType") {
33268 parts.push("[", path.call(print, "name"));
33270 if (n.constraint) {
33271 parts.push(" in ", path.call(print, "constraint"));
33275 return concat$6(parts);
33278 var _variance3 = getFlowVariance$1(n);
33281 parts.push(_variance3);
33284 parts.push(path.call(print, "name"));
33288 parts.push(path.call(print, "bound"));
33291 if (n.constraint) {
33292 parts.push(" extends ", path.call(print, "constraint"));
33295 if (n["default"]) {
33296 parts.push(" = ", path.call(print, "default"));
33297 } // Keep comma if the file extension is .tsx and
33298 // has one type parameter that isn't extend with any types.
33299 // Because, otherwise formatted result will be invalid as tsx.
33302 var _grandParent = path.getNode(2);
33304 if (_parent10.params && _parent10.params.length === 1 && isTSXFile$1(options) && !n.constraint && _grandParent.type === "ArrowFunctionExpression") {
33308 return concat$6(parts);
33311 case "TypeofTypeAnnotation":
33312 return concat$6(["typeof ", path.call(print, "argument")]);
33314 case "VoidTypeAnnotation":
33317 case "InferredPredicate":
33319 // Unhandled types below. If encountered, nodes of these types should
33320 // be either left alone or desugared into AST types that are fully
33321 // supported by the pretty-printer.
33323 case "DeclaredPredicate":
33324 return concat$6(["%checks(", path.call(print, "value"), ")"]);
33326 case "TSAbstractKeyword":
33329 case "TSAnyKeyword":
33332 case "TSAsyncKeyword":
33335 case "TSBooleanKeyword":
33338 case "TSBigIntKeyword":
33341 case "TSConstKeyword":
33344 case "TSDeclareKeyword":
33347 case "TSExportKeyword":
33350 case "TSNeverKeyword":
33353 case "TSNumberKeyword":
33356 case "TSObjectKeyword":
33359 case "TSProtectedKeyword":
33360 return "protected";
33362 case "TSPrivateKeyword":
33365 case "TSPublicKeyword":
33368 case "TSReadonlyKeyword":
33371 case "TSSymbolKeyword":
33374 case "TSStaticKeyword":
33377 case "TSStringKeyword":
33380 case "TSUndefinedKeyword":
33381 return "undefined";
33383 case "TSUnknownKeyword":
33386 case "TSVoidKeyword":
33389 case "TSAsExpression":
33390 return concat$6([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]);
33392 case "TSArrayType":
33393 return concat$6([path.call(print, "elementType"), "[]"]);
33395 case "TSPropertySignature":
33398 parts.push("export ");
33401 if (n.accessibility) {
33402 parts.push(n.accessibility + " ");
33406 parts.push("static ");
33410 parts.push("readonly ");
33413 parts.push(printPropertyKey(path, options, print), printOptionalToken(path));
33415 if (n.typeAnnotation) {
33417 parts.push(path.call(print, "typeAnnotation"));
33418 } // This isn't valid semantically, but it's in the AST so we can print it.
33421 if (n.initializer) {
33422 parts.push(" = ", path.call(print, "initializer"));
33425 return concat$6(parts);
33428 case "TSParameterProperty":
33429 if (n.accessibility) {
33430 parts.push(n.accessibility + " ");
33434 parts.push("export ");
33438 parts.push("static ");
33442 parts.push("readonly ");
33445 parts.push(path.call(print, "parameter"));
33446 return concat$6(parts);
33448 case "TSTypeReference":
33449 return concat$6([path.call(print, "typeName"), printTypeParameters(path, options, print, "typeParameters")]);
33451 case "TSTypeQuery":
33452 return concat$6(["typeof ", path.call(print, "exprName")]);
33454 case "TSIndexSignature":
33456 var _parent11 = path.getParentNode();
33458 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 : ""]);
33461 case "TSTypePredicate":
33462 return concat$6([n.asserts ? "asserts " : "", path.call(print, "parameterName"), n.typeAnnotation ? concat$6([" is ", path.call(print, "typeAnnotation")]) : ""]);
33464 case "TSNonNullExpression":
33465 return concat$6([path.call(print, "expression"), "!"]);
33470 case "TSImportType":
33471 return concat$6([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, "parameter"), ")", !n.qualifier ? "" : concat$6([".", path.call(print, "qualifier")]), printTypeParameters(path, options, print, "typeParameters")]);
33473 case "TSLiteralType":
33474 return path.call(print, "literal");
33476 case "TSIndexedAccessType":
33477 return concat$6([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]);
33479 case "TSConstructSignatureDeclaration":
33480 case "TSCallSignatureDeclaration":
33481 case "TSConstructorType":
33483 if (n.type !== "TSCallSignatureDeclaration") {
33484 parts.push("new ");
33487 parts.push(group$2(printFunctionParams(path, print, options,
33490 /* printTypeParams */
33493 if (n.returnType) {
33494 var isType = n.type === "TSConstructorType";
33495 parts.push(isType ? " => " : ": ", path.call(print, "returnType"));
33498 return concat$6(parts);
33501 case "TSTypeOperator":
33502 return concat$6([n.operator, " ", path.call(print, "typeAnnotation")]);
33504 case "TSMappedType":
33506 var _shouldBreak3 = hasNewlineInRange$2(options.originalText, options.locStart(n), options.locEnd(n));
33508 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,
33510 true), options.bracketSpacing ? line$2 : softline$2, "}"]), {
33511 shouldBreak: _shouldBreak3
33515 case "TSMethodSignature":
33516 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,
33519 /* printTypeParams */
33522 if (n.returnType) {
33523 parts.push(": ", path.call(print, "returnType"));
33526 return group$2(concat$6(parts));
33528 case "TSNamespaceExportDeclaration":
33529 parts.push("export as namespace ", path.call(print, "id"));
33531 if (options.semi) {
33535 return group$2(concat$6(parts));
33537 case "TSEnumDeclaration":
33539 parts.push("declare ");
33543 parts.push(printTypeScriptModifiers(path, options, print));
33547 parts.push("const ");
33550 parts.push("enum ", path.call(print, "id"), " ");
33552 if (n.members.length === 0) {
33553 parts.push(group$2(concat$6(["{", comments.printDanglingComments(path, options), softline$2, "}"])));
33555 parts.push(group$2(concat$6(["{", indent$3(concat$6([hardline$4, printArrayItems(path, options, "members", print), shouldPrintComma(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options,
33557 true), hardline$4, "}"])));
33560 return concat$6(parts);
33562 case "TSEnumMember":
33563 parts.push(path.call(print, "id"));
33565 if (n.initializer) {
33566 parts.push(" = ", path.call(print, "initializer"));
33569 return concat$6(parts);
33571 case "TSImportEqualsDeclaration":
33573 parts.push("export ");
33576 parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference"));
33578 if (options.semi) {
33582 return group$2(concat$6(parts));
33584 case "TSExternalModuleReference":
33585 return concat$6(["require(", path.call(print, "expression"), ")"]);
33587 case "TSModuleDeclaration":
33589 var _parent12 = path.getParentNode();
33591 var isExternalModule = isLiteral$1(n.id);
33592 var parentIsDeclaration = _parent12.type === "TSModuleDeclaration";
33593 var bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration";
33595 if (parentIsDeclaration) {
33599 parts.push("declare ");
33602 parts.push(printTypeScriptModifiers(path, options, print));
33603 var textBetweenNodeAndItsId = options.originalText.slice(options.locStart(n), options.locStart(n.id)); // Global declaration looks like this:
33604 // (declare)? global { ... }
33606 var isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId);
33608 if (!isGlobalDeclaration) {
33609 parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace ");
33613 parts.push(path.call(print, "id"));
33615 if (bodyIsDeclaration) {
33616 parts.push(path.call(print, "body"));
33617 } else if (n.body) {
33618 parts.push(" ", group$2(path.call(print, "body")));
33623 return concat$6(parts);
33626 case "PrivateName":
33627 return concat$6(["#", path.call(print, "id")]);
33629 case "TSConditionalType":
33630 return printTernaryOperator(path, options, print, {
33631 beforeParts: function beforeParts() {
33632 return [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")];
33634 afterParts: function afterParts() {
33637 shouldCheckJsx: false,
33638 conditionalNodeType: "TSConditionalType",
33639 consequentNodePropertyName: "trueType",
33640 alternateNodePropertyName: "falseType",
33641 testNodePropertyName: "checkType",
33645 case "TSInferType":
33646 return concat$6(["infer", " ", path.call(print, "typeParameter")]);
33648 case "InterpreterDirective":
33649 parts.push("#!", n.value, hardline$4);
33651 if (isNextLineEmpty$2(options.originalText, n, options)) {
33652 parts.push(hardline$4);
33655 return concat$6(parts);
33658 return concat$6([].concat(path.call(print, "node"), !n.node.comments || n.node.comments.length === 0 ? [] : concat$6([" //", n.node.comments[0].value.trimRight()])));
33660 case "NGChainedExpression":
33661 return group$2(join$4(concat$6([";", line$2]), path.map(function (childPath) {
33662 return hasNgSideEffect$1(childPath) ? print(childPath) : concat$6(["(", print(childPath), ")"]);
33663 }, "expressions")));
33665 case "NGEmptyExpression":
33668 case "NGQuotedExpression":
33669 return concat$6([n.prefix, ":", n.value]);
33671 case "NGMicrosyntax":
33672 return concat$6(path.map(function (childPath, index) {
33673 return concat$6([index === 0 ? "" : isNgForOf$1(childPath.getValue(), index, n) ? " " : concat$6([";", line$2]), print(childPath)]);
33676 case "NGMicrosyntaxKey":
33677 return /^[a-z_$][a-z0-9_$]*(-[a-z_$][a-z0-9_$])*$/i.test(n.name) ? n.name : JSON.stringify(n.name);
33679 case "NGMicrosyntaxExpression":
33680 return concat$6([path.call(print, "expression"), n.alias === null ? "" : concat$6([" as ", path.call(print, "alias")])]);
33682 case "NGMicrosyntaxKeyedExpression":
33684 var index = path.getName();
33686 var _parentNode2 = path.getParentNode();
33688 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";
33689 return concat$6([path.call(print, "key"), shouldNotPrintColon ? " " : ": ", path.call(print, "expression")]);
33692 case "NGMicrosyntaxLet":
33693 return concat$6(["let ", path.call(print, "key"), n.value === null ? "" : concat$6([" = ", path.call(print, "value")])]);
33695 case "NGMicrosyntaxAs":
33696 return concat$6([path.call(print, "key"), " as ", path.call(print, "alias")]);
33698 case "ArgumentPlaceholder":
33702 /* istanbul ignore next */
33703 throw new Error("unknown type: " + JSON.stringify(n.type));
33707 function printStatementSequence(path, options, print) {
33709 var bodyNode = path.getNode();
33710 var isClass = bodyNode.type === "ClassBody";
33711 path.map(function (stmtPath, i) {
33712 var stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy
33713 // "statements," it's safer simply to skip them.
33715 /* istanbul ignore if */
33719 } // Skip printing EmptyStatement nodes to avoid leaving stray
33720 // semicolons lying around.
33723 if (stmt.type === "EmptyStatement") {
33727 var stmtPrinted = print(stmtPath);
33728 var text = options.originalText;
33729 var parts = []; // in no-semi mode, prepend statement with semicolon if it might break ASI
33730 // don't prepend the only JSX element in a program with semicolon
33732 if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown$1(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options)) {
33733 if (stmt.comments && stmt.comments.some(function (comment) {
33734 return comment.leading;
33736 parts.push(print(stmtPath, {
33740 parts.push(";", stmtPrinted);
33743 parts.push(stmtPrinted);
33746 if (!options.semi && isClass) {
33747 if (classPropMayCauseASIProblems$1(stmtPath)) {
33749 } else if (stmt.type === "ClassProperty") {
33750 var nextChild = bodyNode.body[i + 1];
33752 if (classChildNeedsASIProtection$1(nextChild)) {
33758 if (isNextLineEmpty$2(text, stmt, options) && !isLastStatement$1(stmtPath)) {
33759 parts.push(hardline$4);
33762 printed.push(concat$6(parts));
33764 return join$4(hardline$4, printed);
33767 function printPropertyKey(path, options, print) {
33768 var node = path.getNode();
33770 if (node.computed) {
33771 return concat$6(["[", path.call(print, "key"), "]"]);
33774 var parent = path.getParentNode();
33775 var key = node.key;
33777 if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) {
33778 var objectHasStringProp = (parent.properties || parent.body || parent.members).some(function (prop) {
33779 return !prop.computed && prop.key && isStringLiteral$1(prop.key) && !isStringPropSafeToCoerceToIdentifier$1(prop, options);
33781 needsQuoteProps.set(parent, objectHasStringProp);
33784 if (key.type === "Identifier" && (options.parser === "json" || options.quoteProps === "consistent" && needsQuoteProps.get(parent))) {
33786 var prop = printString$1(JSON.stringify(key.name), options);
33787 return path.call(function (keyPath) {
33788 return comments.printComments(keyPath, function () {
33794 if (isStringPropSafeToCoerceToIdentifier$1(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) {
33796 return path.call(function (keyPath) {
33797 return comments.printComments(keyPath, function () {
33803 return path.call(print, "key");
33806 function printMethod(path, options, print) {
33807 var node = path.getNode();
33808 var kind = node.kind;
33809 var value = node.value || node;
33812 if (!kind || kind === "init" || kind === "method" || kind === "constructor") {
33814 parts.push("async ");
33817 if (value.generator) {
33821 assert$1.ok(kind === "get" || kind === "set");
33822 parts.push(kind, " ");
33825 parts.push(printPropertyKey(path, options, print), node.optional || node.key.optional ? "?" : "", node === value ? printMethodInternal(path, options, print) : path.call(function (path) {
33826 return printMethodInternal(path, options, print);
33828 return concat$6(parts);
33831 function printMethodInternal(path, options, print) {
33832 var parts = [printFunctionTypeParameters(path, options, print), group$2(concat$6([printFunctionParams(path, print, options), printReturnType(path, print, options)]))];
33834 if (path.getNode().body) {
33835 parts.push(" ", path.call(print, "body"));
33837 parts.push(options.semi ? ";" : "");
33840 return concat$6(parts);
33843 function couldGroupArg(arg) {
33844 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
33845 // https://github.com/prettier/prettier/issues/4070
33846 // export class Thing implements OtherThing {
33847 // do: (type: Type) => Provider<Prop> = memoize(
33848 // (type: ObjectType): Provider<Opts> => {}
33851 // https://github.com/prettier/prettier/issues/6099
33852 // app.get("/", (req, res): void => {
33853 // res.send("Hello World!");
33855 !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));
33858 function shouldGroupLastArg(args) {
33859 var lastArg = getLast$2(args);
33860 var penultimateArg = getPenultimate$1(args);
33861 return !hasLeadingComment$3(lastArg) && !hasTrailingComment$1(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type,
33862 // disable last element expansion.
33863 !penultimateArg || penultimateArg.type !== lastArg.type);
33866 function shouldGroupFirstArg(args) {
33867 if (args.length !== 2) {
33871 var firstArg = args[0];
33872 var secondArg = args[1];
33873 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);
33876 function printJestEachTemplateLiteral(node, expressions, options) {
33879 * ${1} | ${1} | ${2}
33880 * ${1} | ${2} | ${3}
33881 * ${2} | ${1} | ${3}
33883 var headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/);
33885 if (headerNames.length > 1 || headerNames.some(function (headerName) {
33886 return headerName.length !== 0;
33889 var stringifiedExpressions = expressions.map(function (doc) {
33890 return "${" + printDocToString$2(doc, Object.assign({}, options, {
33891 printWidth: Infinity,
33893 })).formatted + "}";
33896 hasLineBreak: false,
33900 for (var i = 1; i < node.quasis.length; i++) {
33901 var row = tableBody[tableBody.length - 1];
33902 var correspondingExpression = stringifiedExpressions[i - 1];
33903 row.cells.push(correspondingExpression);
33905 if (correspondingExpression.indexOf("\n") !== -1) {
33906 row.hasLineBreak = true;
33909 if (node.quasis[i].value.raw.indexOf("\n") !== -1) {
33911 hasLineBreak: false,
33917 var maxColumnCount = tableBody.reduce(function (maxColumnCount, row) {
33918 return Math.max(maxColumnCount, row.cells.length);
33919 }, headerNames.length);
33920 var maxColumnWidths = Array.from(new Array(maxColumnCount), function () {
33925 }].concat(tableBody.filter(function (row) {
33926 return row.cells.length !== 0;
33928 table.filter(function (row) {
33929 return !row.hasLineBreak;
33930 }).forEach(function (row) {
33931 row.cells.forEach(function (cell, index) {
33932 maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$2(cell));
33935 parts.push(lineSuffixBoundary$1, "`", indent$3(concat$6([hardline$4, join$4(hardline$4, table.map(function (row) {
33936 return join$4(" | ", row.cells.map(function (cell, index) {
33937 return row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$2(cell));
33939 }))])), hardline$4, "`");
33940 return concat$6(parts);
33944 function printArgumentsList(path, options, print) {
33945 var node = path.getValue();
33946 var args = node.arguments;
33948 if (args.length === 0) {
33949 return concat$6(["(", comments.printDanglingComments(path, options,
33952 } // useEffect(() => { ... }, [foo, bar, baz])
33955 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) {
33956 return arg.comments;
33958 return concat$6(["(", path.call(print, "arguments", 0), ", ", path.call(print, "arguments", 1), ")"]);
33967 function shouldBreakForArrowFunctionInArguments(arg, argPath) {
33968 if (!arg || arg.type !== "ArrowFunctionExpression" || !arg.body || arg.body.type !== "BlockStatement" || !arg.params || arg.params.length < 1) {
33972 var shouldBreak = false;
33973 argPath.each(function (paramPath) {
33974 var printed = concat$6([print(paramPath)]);
33975 shouldBreak = shouldBreak || willBreak$1(printed);
33977 return shouldBreak;
33980 var anyArgEmptyLine = false;
33981 var shouldBreakForArrowFunction = false;
33982 var hasEmptyLineFollowingFirstArg = false;
33983 var lastArgIndex = args.length - 1;
33984 var printedArguments = path.map(function (argPath, index) {
33985 var arg = argPath.getNode();
33986 var parts = [print(argPath)];
33988 if (index === lastArgIndex) ; else if (isNextLineEmpty$2(options.originalText, arg, options)) {
33990 hasEmptyLineFollowingFirstArg = true;
33993 anyArgEmptyLine = true;
33994 parts.push(",", hardline$4, hardline$4);
33996 parts.push(",", line$2);
33999 shouldBreakForArrowFunction = shouldBreakForArrowFunctionInArguments(arg, argPath);
34000 return concat$6(parts);
34002 var maybeTrailingComma = // Dynamic imports cannot have trailing commas
34003 !(node.callee && node.callee.type === "Import") && shouldPrintComma(options, "all") ? "," : "";
34005 function allArgsBrokenOut() {
34006 return group$2(concat$6(["(", indent$3(concat$6([line$2, concat$6(printedArguments)])), maybeTrailingComma, line$2, ")"]), {
34011 if (isFunctionCompositionArgs$1(args)) {
34012 return allArgsBrokenOut();
34015 var shouldGroupFirst = shouldGroupFirstArg(args);
34016 var shouldGroupLast = shouldGroupLastArg(args);
34018 if (shouldGroupFirst || shouldGroupLast) {
34019 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
34021 var printedExpanded;
34023 path.each(function (argPath) {
34024 if (shouldGroupFirst && i === 0) {
34025 printedExpanded = [concat$6([argPath.call(function (p) {
34027 expandFirstArg: true
34029 }), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$4 : line$2, hasEmptyLineFollowingFirstArg ? hardline$4 : ""])].concat(printedArguments.slice(1));
34032 if (shouldGroupLast && i === args.length - 1) {
34033 printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(function (p) {
34035 expandLastArg: true
34042 var somePrintedArgumentsWillBreak = printedArguments.some(willBreak$1);
34043 var simpleConcat = concat$6(["(", concat$6(printedExpanded), ")"]);
34044 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], {
34046 }), concat$6(printedExpanded.slice(1)), ")"]) : concat$6(["(", concat$6(printedArguments.slice(0, -1)), group$2(getLast$2(printedExpanded), {
34048 }), ")"]), allArgsBrokenOut()], {
34053 var contents = concat$6(["(", indent$3(concat$6([softline$2, concat$6(printedArguments)])), ifBreak$1(maybeTrailingComma), softline$2, ")"]);
34055 if (isLongCurriedCallExpression$1(path)) {
34056 // By not wrapping the arguments in a group, the printer prioritizes
34057 // breaking up these arguments rather than the args of the parent call.
34061 return group$2(contents, {
34062 shouldBreak: printedArguments.some(willBreak$1) || anyArgEmptyLine
34066 function printTypeAnnotation(path, options, print) {
34067 var node = path.getValue();
34069 if (!node.typeAnnotation) {
34073 var parentNode = path.getParentNode();
34074 var isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite;
34075 var isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node;
34077 if (isFlowAnnotationComment$1(options.originalText, node.typeAnnotation, options)) {
34078 return concat$6([" /*: ", path.call(print, "typeAnnotation"), " */"]);
34081 return concat$6([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path.call(print, "typeAnnotation")]);
34084 function printFunctionTypeParameters(path, options, print) {
34085 var fun = path.getValue();
34087 if (fun.typeArguments) {
34088 return path.call(print, "typeArguments");
34091 if (fun.typeParameters) {
34092 return path.call(print, "typeParameters");
34098 function printFunctionParams(path, print, options, expandArg, printTypeParams) {
34099 var fun = path.getValue();
34100 var parent = path.getParentNode();
34101 var paramsField = fun.parameters ? "parameters" : "params";
34102 var isParametersInTestCall = isTestCall$1(parent);
34103 var shouldHugParameters = shouldHugArguments(fun);
34104 var shouldExpandParameters = expandArg && !(fun[paramsField] && fun[paramsField].some(function (n) {
34107 var typeParams = printTypeParams ? printFunctionTypeParameters(path, options, print) : "";
34110 if (fun[paramsField]) {
34111 var lastArgIndex = fun[paramsField].length - 1;
34112 printed = path.map(function (childPath, index) {
34114 var param = childPath.getValue();
34115 parts.push(print(childPath));
34117 if (index === lastArgIndex) {
34119 parts.push(",", line$2);
34121 } else if (isParametersInTestCall || shouldHugParameters || shouldExpandParameters) {
34123 } else if (isNextLineEmpty$2(options.originalText, param, options)) {
34124 parts.push(",", hardline$4, hardline$4);
34126 parts.push(",", line$2);
34129 return concat$6(parts);
34134 printed.push(concat$6(["...", path.call(print, "rest")]));
34137 if (printed.length === 0) {
34138 return concat$6([typeParams, "(", comments.printDanglingComments(path, options,
34140 true, function (comment) {
34141 return getNextNonSpaceNonCommentCharacter$1(options.originalText, comment, options.locEnd) === ")";
34145 var lastParam = getLast$2(fun[paramsField]); // If the parent is a call with the first/last argument expansion and this is the
34146 // params of the first/last argument, we don't want the arguments to break and instead
34147 // want the whole expression to be on a new line.
34150 // verylongcall( verylongcall((
34156 if (shouldExpandParameters) {
34157 return group$2(concat$6([removeLines$1(typeParams), "(", concat$6(printed.map(removeLines$1)), ")"]));
34158 } // Single object destructuring should hug
34167 var hasNotParameterDecorator = fun[paramsField].every(function (param) {
34168 return !param.decorators;
34171 if (shouldHugParameters && hasNotParameterDecorator) {
34172 return concat$6([typeParams, "(", concat$6(printed), ")"]);
34173 } // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
34176 if (isParametersInTestCall) {
34177 return concat$6([typeParams, "(", concat$6(printed), ")"]);
34180 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;
34182 if (isFlowShorthandWithOneArg) {
34183 if (options.arrowParens === "always") {
34184 return concat$6(["(", concat$6(printed), ")"]);
34187 return concat$6(printed);
34190 var canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest;
34191 return concat$6([typeParams, "(", indent$3(concat$6([softline$2, concat$6(printed)])), ifBreak$1(canHaveTrailingComma && shouldPrintComma(options, "all") ? "," : ""), softline$2, ")"]);
34194 function shouldPrintParamsWithoutParens(path, options) {
34195 if (options.arrowParens === "always") {
34199 if (options.arrowParens === "avoid") {
34200 var node = path.getValue();
34201 return canPrintParamsWithoutParens(node);
34202 } // Fallback default; should be unreachable
34208 function canPrintParamsWithoutParens(node) {
34209 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;
34212 function printFunctionDeclaration(path, print, options) {
34213 var n = path.getValue();
34217 parts.push("async ");
34220 parts.push("function");
34227 parts.push(" ", path.call(print, "id"));
34230 parts.push(printFunctionTypeParameters(path, options, print), group$2(concat$6([printFunctionParams(path, print, options), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body"));
34231 return concat$6(parts);
34234 function printReturnType(path, print, options) {
34235 var n = path.getValue();
34236 var returnType = path.call(print, "returnType");
34238 if (n.returnType && isFlowAnnotationComment$1(options.originalText, n.returnType, options)) {
34239 return concat$6([" /*: ", returnType, " */"]);
34242 var parts = [returnType]; // prepend colon to TypeScript type annotation
34244 if (n.returnType && n.returnType.typeAnnotation) {
34245 parts.unshift(": ");
34249 // The return type will already add the colon, but otherwise we
34250 // need to do it ourselves
34251 parts.push(n.returnType ? " " : ": ", path.call(print, "predicate"));
34254 return concat$6(parts);
34257 function printExportDeclaration(path, options, print) {
34258 var decl = path.getValue();
34259 var semi = options.semi ? ";" : "";
34260 var parts = ["export "];
34261 var isDefault = decl["default"] || decl.type === "ExportDefaultDeclaration";
34264 parts.push("default ");
34267 parts.push(comments.printDanglingComments(path, options,
34271 if (needsHardlineAfterDanglingComment$1(decl)) {
34272 parts.push(hardline$4);
34275 if (decl.declaration) {
34276 parts.push(path.call(print, "declaration"));
34278 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") {
34282 if (decl.specifiers && decl.specifiers.length > 0) {
34283 var specifiers = [];
34284 var defaultSpecifiers = [];
34285 var namespaceSpecifiers = [];
34286 path.each(function (specifierPath) {
34287 var specifierType = path.getValue().type;
34289 if (specifierType === "ExportSpecifier") {
34290 specifiers.push(print(specifierPath));
34291 } else if (specifierType === "ExportDefaultSpecifier") {
34292 defaultSpecifiers.push(print(specifierPath));
34293 } else if (specifierType === "ExportNamespaceSpecifier") {
34294 namespaceSpecifiers.push(concat$6(["* as ", print(specifierPath)]));
34297 var isNamespaceFollowed = namespaceSpecifiers.length !== 0 && specifiers.length !== 0;
34298 var isDefaultFollowed = defaultSpecifiers.length !== 0 && (namespaceSpecifiers.length !== 0 || specifiers.length !== 0);
34299 var canBreak = specifiers.length > 1 || defaultSpecifiers.length > 0 || decl.specifiers && decl.specifiers.some(function (node) {
34300 return node.comments;
34304 if (specifiers.length !== 0) {
34306 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, "}"]));
34308 printed = concat$6(["{", options.bracketSpacing ? " " : "", concat$6(specifiers), options.bracketSpacing ? " " : "", "}"]);
34312 parts.push(decl.exportKind === "type" ? "type " : "", concat$6(defaultSpecifiers), concat$6([isDefaultFollowed ? ", " : ""]), concat$6(namespaceSpecifiers), concat$6([isNamespaceFollowed ? ", " : ""]), printed);
34318 parts.push(" from ", path.call(print, "source"));
34324 return concat$6(parts);
34327 function printFlowDeclaration(path, parts) {
34328 var parentExportDecl = getParentExportDeclaration$1(path);
34330 if (parentExportDecl) {
34331 assert$1.strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
34333 // If the parent node has type DeclareExportDeclaration, then it
34334 // will be responsible for printing the "declare" token. Otherwise
34335 // it needs to be printed with this non-exported declaration node.
34336 parts.unshift("declare ");
34339 return concat$6(parts);
34342 function printTypeScriptModifiers(path, options, print) {
34343 var n = path.getValue();
34345 if (!n.modifiers || !n.modifiers.length) {
34349 return concat$6([join$4(" ", path.map(print, "modifiers")), " "]);
34352 function printTypeParameters(path, options, print, paramsKey) {
34353 var n = path.getValue();
34355 if (!n[paramsKey]) {
34357 } // for TypeParameterDeclaration typeParameters is a single node
34360 if (!Array.isArray(n[paramsKey])) {
34361 return path.call(print, paramsKey);
34364 var grandparent = path.getNode(2);
34365 var greatGreatGrandParent = path.getNode(4);
34366 var isParameterInTestCall = grandparent != null && isTestCall$1(grandparent);
34367 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.
34368 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");
34370 if (shouldInline) {
34371 return concat$6(["<", join$4(", ", path.map(print, paramsKey)), ">"]);
34374 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, ">"]));
34377 function printClass(path, options, print) {
34378 var n = path.getValue();
34382 parts.push("abstract ");
34385 parts.push("class");
34388 parts.push(" ", path.call(print, "id"));
34391 parts.push(path.call(print, "typeParameters"));
34392 var partsGroup = [];
34394 if (n.superClass) {
34395 var printed = concat$6(["extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters")]); // Keep old behaviour of extends in same line
34396 // If there is only on extends and there are not comments
34398 if ((!n.implements || n.implements.length === 0) && (!n.superClass.comments || n.superClass.comments.length === 0)) {
34399 parts.push(concat$6([" ", path.call(function (superClass) {
34400 return comments.printComments(superClass, function () {
34403 }, "superClass")]));
34405 partsGroup.push(group$2(concat$6([line$2, path.call(function (superClass) {
34406 return comments.printComments(superClass, function () {
34409 }, "superClass")])));
34411 } else if (n.extends && n.extends.length > 0) {
34412 parts.push(" extends ", join$4(", ", path.map(print, "extends")));
34415 if (n["mixins"] && n["mixins"].length > 0) {
34416 partsGroup.push(line$2, "mixins ", group$2(indent$3(join$4(concat$6([",", line$2]), path.map(print, "mixins")))));
34419 if (n["implements"] && n["implements"].length > 0) {
34420 partsGroup.push(line$2, "implements", group$2(indent$3(concat$6([line$2, join$4(concat$6([",", line$2]), path.map(print, "implements"))]))));
34423 if (partsGroup.length > 0) {
34424 parts.push(group$2(indent$3(concat$6(partsGroup))));
34427 if (n.body && n.body.comments && hasLeadingOwnLineComment$1(options.originalText, n.body, options)) {
34428 parts.push(hardline$4);
34433 parts.push(path.call(print, "body"));
34437 function printOptionalToken(path) {
34438 var node = path.getValue();
34440 if (!node.optional || // It's an optional computed method parsed by typescript-estree.
34441 // "?" is printed in `printMethod`.
34442 node.type === "Identifier" && node === path.getParentNode().key) {
34446 if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) {
34453 function printMemberLookup(path, options, print) {
34454 var property = path.call(print, "property");
34455 var n = path.getValue();
34456 var optional = printOptionalToken(path);
34459 return concat$6([optional, ".", property]);
34462 if (!n.property || isNumericLiteral$1(n.property)) {
34463 return concat$6([optional, "[", property, "]"]);
34466 return group$2(concat$6([optional, "[", indent$3(concat$6([softline$2, property])), softline$2, "]"]));
34469 function printBindExpressionCallee(path, options, print) {
34470 return concat$6(["::", path.call(print, "callee")]);
34471 } // We detect calls on member expressions specially to format a
34472 // common pattern better. The pattern we are looking for is this:
34475 // .map(x => x + 1)
34476 // .filter(x => x > 10)
34477 // .some(x => x % 2)
34479 // The way it is structured in the AST is via a nested sequence of
34480 // MemberExpression and CallExpression. We need to traverse the AST
34481 // and make groups out of it to print it in the desired way.
34484 function printMemberChain(path, options, print) {
34485 // The first phase is to linearize the AST by traversing it down.
34488 // has the following AST structure:
34489 // CallExpression(MemberExpression(CallExpression(Identifier)))
34490 // and we transform it into
34491 // [Identifier, CallExpression, MemberExpression, CallExpression]
34492 var printedNodes = []; // Here we try to retain one typed empty line after each call expression or
34493 // the first group whether it is in parentheses or not
34495 function shouldInsertEmptyLineAfter(node) {
34496 var originalText = options.originalText;
34497 var nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$2(originalText, node, options);
34498 var nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty
34499 // line after that parenthesis
34501 if (nextChar == ")") {
34502 return isNextLineEmptyAfterIndex$1(originalText, nextCharIndex + 1, options);
34505 return isNextLineEmpty$2(originalText, node, options);
34508 function rec(path) {
34509 var node = path.getValue();
34511 if ((node.type === "CallExpression" || node.type === "OptionalCallExpression") && (isMemberish$1(node.callee) || node.callee.type === "CallExpression" || node.callee.type === "OptionalCallExpression")) {
34512 printedNodes.unshift({
34514 printed: concat$6([comments.printComments(path, function () {
34515 return concat$6([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]);
34516 }, options), shouldInsertEmptyLineAfter(node) ? hardline$4 : ""])
34518 path.call(function (callee) {
34519 return rec(callee);
34521 } else if (isMemberish$1(node)) {
34522 printedNodes.unshift({
34524 needsParens: needsParens_1(path, options),
34525 printed: comments.printComments(path, function () {
34526 return node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup(path, options, print) : printBindExpressionCallee(path, options, print);
34529 path.call(function (object) {
34530 return rec(object);
34532 } else if (node.type === "TSNonNullExpression") {
34533 printedNodes.unshift({
34535 printed: comments.printComments(path, function () {
34539 path.call(function (expression) {
34540 return rec(expression);
34543 printedNodes.unshift({
34545 printed: path.call(print)
34548 } // Note: the comments of the root node have already been printed, so we
34549 // need to extract this first call without printing them as they would
34550 // if handled inside of the recursive call.
34553 var node = path.getValue();
34554 printedNodes.unshift({
34556 printed: concat$6([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)])
34558 path.call(function (callee) {
34559 return rec(callee);
34560 }, "callee"); // Once we have a linear list of printed nodes, we want to create groups out
34564 // will be grouped as
34566 // [Identifier, CallExpression],
34567 // [MemberExpression, MemberExpression, CallExpression],
34568 // [MemberExpression, CallExpression],
34569 // [MemberExpression],
34571 // so that we can print it as
34576 // The first group is the first node followed by
34577 // - as many CallExpression as possible
34578 // < fn()()() >.something()
34579 // - as many array accessors as possible
34580 // < fn()[0][1][2] >.something()
34581 // - then, as many MemberExpression as possible but the last one
34582 // < this.items >.something()
34585 var currentGroup = [printedNodes[0]];
34588 for (; i < printedNodes.length; ++i) {
34589 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)) {
34590 currentGroup.push(printedNodes[i]);
34596 if (printedNodes[0].node.type !== "CallExpression" && printedNodes[0].node.type !== "OptionalCallExpression") {
34597 for (; i + 1 < printedNodes.length; ++i) {
34598 if (isMemberish$1(printedNodes[i].node) && isMemberish$1(printedNodes[i + 1].node)) {
34599 currentGroup.push(printedNodes[i]);
34606 groups.push(currentGroup);
34607 currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by
34608 // a sequence of CallExpression. To compute it, we keep adding things to the
34609 // group until we has seen a CallExpression in the past and reach a
34610 // MemberExpression
34612 var hasSeenCallExpression = false;
34614 for (; i < printedNodes.length; ++i) {
34615 if (hasSeenCallExpression && isMemberish$1(printedNodes[i].node)) {
34616 // [0] should be appended at the end of the group instead of the
34617 // beginning of the next one
34618 if (printedNodes[i].node.computed && isNumericLiteral$1(printedNodes[i].node.property)) {
34619 currentGroup.push(printedNodes[i]);
34623 groups.push(currentGroup);
34625 hasSeenCallExpression = false;
34628 if (printedNodes[i].node.type === "CallExpression" || printedNodes[i].node.type === "OptionalCallExpression") {
34629 hasSeenCallExpression = true;
34632 currentGroup.push(printedNodes[i]);
34634 if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(function (comment) {
34635 return comment.trailing;
34637 groups.push(currentGroup);
34639 hasSeenCallExpression = false;
34643 if (currentGroup.length > 0) {
34644 groups.push(currentGroup);
34645 } // There are cases like Object.keys(), Observable.of(), _.values() where
34646 // they are the subject of all the chained calls and therefore should
34647 // be kept on the same line:
34649 // Object.keys(items)
34653 // In order to detect those cases, we use an heuristic: if the first
34654 // node is an identifier with the name starting with a capital
34655 // letter or just a sequence of _$. The rationale is that they are
34656 // likely to be factories.
34659 function isFactory(name) {
34660 return /^[A-Z]|^[_$]+$/.test(name);
34661 } // In case the Identifier is shorter than tab width, we can keep the
34662 // first call in a single line, if it's an ExpressionStatement.
34664 // d3.scaleLinear()
34665 // .domain([0, 100])
34666 // .range([0, width]);
34670 function isShort(name) {
34671 return name.length <= options.tabWidth;
34674 function shouldNotWrap(groups) {
34675 var parent = path.getParentNode();
34676 var isExpression = parent && parent.type === "ExpressionStatement";
34677 var hasComputed = groups[1].length && groups[1][0].node.computed;
34679 if (groups[0].length === 1) {
34680 var firstNode = groups[0][0].node;
34681 return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpression && isShort(firstNode.name) || hasComputed);
34684 var lastNode = getLast$2(groups[0]).node;
34685 return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed);
34688 var shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups);
34690 function printGroup(printedGroup) {
34691 var printed = printedGroup.map(function (tuple) {
34692 return tuple.printed;
34693 }); // Checks if the last node (i.e. the parent node) needs parens and print
34696 if (printedGroup.length > 0 && printedGroup[printedGroup.length - 1].needsParens) {
34697 return concat$6(["("].concat(_toConsumableArray$1(printed), [")"]));
34700 return concat$6(printed);
34703 function printIndentedGroup(groups) {
34704 if (groups.length === 0) {
34708 return indent$3(group$2(concat$6([hardline$4, join$4(hardline$4, groups.map(printGroup))])));
34711 var printedGroups = groups.map(printGroup);
34712 var oneLine = concat$6(printedGroups);
34713 var cutoff = shouldMerge ? 3 : 2;
34714 var flatGroups = groups.slice(0, cutoff).reduce(function (res, group) {
34715 return res.concat(group);
34717 var hasComment = flatGroups.slice(1, -1).some(function (node) {
34718 return hasLeadingComment$3(node.node);
34719 }) || flatGroups.slice(0, -1).some(function (node) {
34720 return hasTrailingComment$1(node.node);
34721 }) || groups[cutoff] && hasLeadingComment$3(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just
34722 // render everything concatenated together.
34724 if (groups.length <= cutoff && !hasComment) {
34725 if (isLongCurriedCallExpression$1(path)) {
34729 return group$2(oneLine);
34730 } // Find out the last node in the first group and check if it has an
34731 // empty line after
34734 var lastNodeBeforeIndent = getLast$2(shouldMerge ? groups.slice(1, 2)[0] : groups[0]).node;
34735 var shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== "CallExpression" && lastNodeBeforeIndent.type !== "OptionalCallExpression" && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
34736 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))]);
34737 var callExpressions = printedNodes.map(function (_ref) {
34738 var node = _ref.node;
34740 }).filter(isCallOrOptionalCallExpression$1); // We don't want to print in one line if there's:
34742 // * 3 or more chained calls.
34743 // * Any group but the last one has a hard line.
34744 // If the last group is a function it's okay to inline if it fits.
34746 if (hasComment || callExpressions.length >= 3 || printedGroups.slice(0, -1).some(willBreak$1) ||
34748 * scopes.filter(scope => scope.value !== '').map((scope, i) => {
34749 * // multi line content
34752 function (lastGroupDoc, lastGroupNode) {
34753 return isCallOrOptionalCallExpression$1(lastGroupNode) && willBreak$1(lastGroupDoc);
34754 }(getLast$2(printedGroups), getLast$2(getLast$2(groups)).node) && callExpressions.slice(0, -1).some(function (n) {
34755 return n.arguments.some(isFunctionOrArrowExpression$1);
34757 return group$2(expanded);
34760 return concat$6([// We only need to check `oneLine` because if `expanded` is chosen
34761 // that means that the parent group has already been broken
34763 willBreak$1(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$2 : "", conditionalGroup$1([oneLine, expanded])]);
34766 function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
34767 if (isFacebookTranslationTag) {
34771 if (childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement) {
34772 return child.length === 1 ? softline$2 : hardline$4;
34778 function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
34779 if (isFacebookTranslationTag) {
34783 if (child.length === 1) {
34784 return childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement ? hardline$4 : softline$2;
34788 } // JSX Children are strange, mostly for two reasons:
34789 // 1. JSX reads newlines into string values, instead of skipping them like JS
34790 // 2. up to one whitespace between elements within a line is significant,
34791 // but not between lines.
34793 // Leading, trailing, and lone whitespace all need to
34794 // turn themselves into the rather ugly `{' '}` when breaking.
34796 // We print JSX using the `fill` doc primitive.
34797 // This requires that we give it an array of alternating
34798 // content and whitespace elements.
34799 // To ensure this we add dummy `""` content elements as needed.
34802 function printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag) {
34803 var n = path.getValue();
34804 var children = []; // using `map` instead of `each` because it provides `i`
34806 path.map(function (childPath, i) {
34807 var child = childPath.getValue();
34809 if (isLiteral$1(child)) {
34810 var text = rawText$1(child); // Contains a non-whitespace character
34812 if (isMeaningfulJSXText$1(child)) {
34813 var words = text.split(matchJsxWhitespaceRegex$1); // Starts with whitespace
34815 if (words[0] === "") {
34819 if (/\n/.test(words[0])) {
34820 var next = n.children[i + 1];
34821 children.push(separatorWithWhitespace(isFacebookTranslationTag, words[1], child, next));
34823 children.push(jsxWhitespace);
34829 var endWhitespace; // Ends with whitespace
34831 if (getLast$2(words) === "") {
34833 endWhitespace = words.pop();
34834 } // This was whitespace only without a new line.
34837 if (words.length === 0) {
34841 words.forEach(function (word, i) {
34843 children.push(line$2);
34845 children.push(word);
34849 if (endWhitespace !== undefined) {
34850 if (/\n/.test(endWhitespace)) {
34851 var _next = n.children[i + 1];
34852 children.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$2(children), child, _next));
34854 children.push(jsxWhitespace);
34857 var _next2 = n.children[i + 1];
34858 children.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$2(children), child, _next2));
34860 } else if (/\n/.test(text)) {
34861 // Keep (up to one) blank line between tags/expressions/text.
34862 // Note: We don't keep blank lines between text elements.
34863 if (text.match(/\n/g).length > 1) {
34865 children.push(hardline$4);
34869 children.push(jsxWhitespace);
34872 var printedChild = print(childPath);
34873 children.push(printedChild);
34874 var _next3 = n.children[i + 1];
34876 var directlyFollowedByMeaningfulText = _next3 && isMeaningfulJSXText$1(_next3);
34878 if (directlyFollowedByMeaningfulText) {
34879 var firstWord = rawText$1(_next3).trim().split(matchJsxWhitespaceRegex$1)[0];
34880 children.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord, child, _next3));
34882 children.push(hardline$4);
34887 } // JSX expands children from the inside-out, instead of the outside-in.
34888 // This is both to break children before attributes,
34889 // and to ensure that when children break, their parents do as well.
34891 // Any element that is written without any newlines and fits on a single line
34892 // is left that way.
34893 // Not only that, any user-written-line containing multiple JSX siblings
34894 // should also be kept on one line if possible,
34895 // so each user-written-line is wrapped in its own group.
34897 // Elements that contain newlines or don't fit on a single line (recursively)
34898 // are fully-split, using hardline and shouldBreak: true.
34900 // To support that case properly, all leading and trailing spaces
34901 // are stripped from the list of children, and replaced with a single hardline.
34904 function printJSXElement(path, options, print) {
34905 var n = path.getValue();
34907 if (n.type === "JSXElement" && isEmptyJSXElement$1(n)) {
34908 return concat$6([path.call(print, "openingElement"), path.call(print, "closingElement")]);
34911 var openingLines = n.type === "JSXElement" ? path.call(print, "openingElement") : path.call(print, "openingFragment");
34912 var closingLines = n.type === "JSXElement" ? path.call(print, "closingElement") : path.call(print, "closingFragment");
34914 if (n.children.length === 1 && n.children[0].type === "JSXExpressionContainer" && (n.children[0].expression.type === "TemplateLiteral" || n.children[0].expression.type === "TaggedTemplateExpression")) {
34915 return concat$6([openingLines, concat$6(path.map(print, "children")), closingLines]);
34916 } // Convert `{" "}` to text nodes containing a space.
34917 // This makes it easy to turn them into `jsxWhitespace` which
34918 // can then print as either a space or `{" "}` when breaking.
34921 n.children = n.children.map(function (child) {
34922 if (isJSXWhitespaceExpression$1(child)) {
34932 var containsTag = n.children.filter(isJSXNode$1).length > 0;
34933 var containsMultipleExpressions = n.children.filter(function (child) {
34934 return child.type === "JSXExpressionContainer";
34936 var containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true.
34938 var forcedBreak = willBreak$1(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions;
34939 var rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}';
34940 var jsxWhitespace = ifBreak$1(concat$6([rawJsxWhitespace, softline$2]), " ");
34941 var isFacebookTranslationTag = n.openingElement && n.openingElement.name && n.openingElement.name.name === "fbt";
34942 var children = printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag);
34943 var containsText = n.children.filter(function (child) {
34944 return isMeaningfulJSXText$1(child);
34945 }).length > 0; // We can end up we multiple whitespace elements with empty string
34946 // content between them.
34947 // We need to remove empty whitespace and softlines before JSX whitespace
34948 // to get the correct output.
34950 for (var i = children.length - 2; i >= 0; i--) {
34951 var isPairOfEmptyStrings = children[i] === "" && children[i + 1] === "";
34952 var isPairOfHardlines = children[i] === hardline$4 && children[i + 1] === "" && children[i + 2] === hardline$4;
34953 var isLineFollowedByJSXWhitespace = (children[i] === softline$2 || children[i] === hardline$4) && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
34954 var isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$2 || children[i + 2] === hardline$4);
34955 var isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
34956 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;
34958 if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace || isPairOfHardOrSoftLines) {
34959 children.splice(i, 2);
34960 } else if (isJSXWhitespaceFollowedByLine) {
34961 children.splice(i + 1, 2);
34963 } // Trim trailing lines (or empty strings)
34966 while (children.length && (isLineNext$1(getLast$2(children)) || isEmpty$1(getLast$2(children)))) {
34968 } // Trim leading lines (or empty strings)
34971 while (children.length && (isLineNext$1(children[0]) || isEmpty$1(children[0])) && (isLineNext$1(children[1]) || isEmpty$1(children[1]))) {
34974 } // Tweak how we format children if outputting this element over multiple lines.
34975 // Also detect whether we will force this element to output over multiple lines.
34978 var multilineChildren = [];
34979 children.forEach(function (child, i) {
34980 // There are a number of situations where we need to ensure we display
34981 // whitespace as `{" "}` when outputting this element over multiple lines.
34982 if (child === jsxWhitespace) {
34983 if (i === 1 && children[i - 1] === "") {
34984 if (children.length === 2) {
34985 // Solitary whitespace
34986 multilineChildren.push(rawJsxWhitespace);
34988 } // Leading whitespace
34991 multilineChildren.push(concat$6([rawJsxWhitespace, hardline$4]));
34993 } else if (i === children.length - 1) {
34994 // Trailing whitespace
34995 multilineChildren.push(rawJsxWhitespace);
34997 } else if (children[i - 1] === "" && children[i - 2] === hardline$4) {
34998 // Whitespace after line break
34999 multilineChildren.push(rawJsxWhitespace);
35004 multilineChildren.push(child);
35006 if (willBreak$1(child)) {
35007 forcedBreak = true;
35009 }); // If there is text we use `fill` to fit as much onto each line as possible.
35010 // When there is no text (just tags and expressions) we use `group`
35011 // to output each on a separate line.
35013 var content = containsText ? fill$2(multilineChildren) : group$2(concat$6(multilineChildren), {
35016 var multiLineElem = group$2(concat$6([openingLines, indent$3(concat$6([hardline$4, content])), hardline$4, closingLines]));
35019 return multiLineElem;
35022 return conditionalGroup$1([group$2(concat$6([openingLines, concat$6(children), closingLines])), multiLineElem]);
35025 function maybeWrapJSXElementInParens(path, elem, options) {
35026 var parent = path.getParentNode();
35032 var NO_WRAP_PARENTS = {
35033 ArrayExpression: true,
35034 JSXAttribute: true,
35036 JSXExpressionContainer: true,
35038 ExpressionStatement: true,
35039 CallExpression: true,
35040 OptionalCallExpression: true,
35041 ConditionalExpression: true,
35042 JsExpressionRoot: true
35045 if (NO_WRAP_PARENTS[parent.type]) {
35049 var shouldBreak = matchAncestorTypes$1(path, ["ArrowFunctionExpression", "CallExpression", "JSXExpressionContainer"]) || matchAncestorTypes$1(path, ["ArrowFunctionExpression", "OptionalCallExpression", "JSXExpressionContainer"]);
35050 var needsParens = needsParens_1(path, options);
35051 return group$2(concat$6([needsParens ? "" : ifBreak$1("("), indent$3(concat$6([softline$2, elem])), softline$2, needsParens ? "" : ifBreak$1(")")]), {
35056 function shouldInlineLogicalExpression(node) {
35057 if (node.type !== "LogicalExpression") {
35061 if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) {
35065 if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) {
35069 if (isJSXNode$1(node.right)) {
35074 } // For binary expressions to be consistent, we need to group
35075 // subsequent operators with the same precedence level under a single
35076 // group. Otherwise they will be nested such that some of them break
35077 // onto new lines but not all. Operators with the same precedence
35078 // level should either all break or not. Because we group them by
35079 // precedence level and the AST is structured based on precedence
35080 // level, things are naturally broken up correctly, i.e. `&&` is
35081 // broken before `+`.
35084 function printBinaryishExpressions(path, print, options, isNested, isInsideParenthesis) {
35086 var node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same.
35088 if (isBinaryish$1(node)) {
35089 // Put all operators with the same precedence level in the same
35090 // group. The reason we only need to do this with the `left`
35091 // expression is because given an expression like `1 + 2 - 3`, it
35092 // is always parsed like `((1 + 2) - 3)`, meaning the `left` side
35093 // is where the rest of the expression will exist. Binary
35094 // expressions on the right side mean they have a difference
35095 // precedence level and should be treated as a separate group, so
35096 // print them normally. (This doesn't hold for the `**` operator,
35097 // which is unique in that it is right-associative.)
35098 if (shouldFlatten$1(node.operator, node.left.operator)) {
35099 // Flatten them out by recursively calling this function.
35100 parts = parts.concat(path.call(function (left) {
35101 return printBinaryishExpressions(left, print, options,
35103 true, isInsideParenthesis);
35106 parts.push(path.call(print, "left"));
35109 var shouldInline = shouldInlineLogicalExpression(node);
35110 var lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment$1(options.originalText, node.right, options);
35111 var operator = node.type === "NGPipeExpression" ? "|" : node.operator;
35112 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) {
35113 return align$1(2, group$2(arg));
35115 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
35116 // in order to avoid having a small right part like -1 be on its own line.
35118 var parent = path.getParentNode();
35119 var shouldGroup = !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type;
35120 parts.push(" ", shouldGroup ? group$2(right) : right); // The root comments are already printed, but we need to manually print
35121 // the other ones since we don't call the normal print on BinaryExpression,
35122 // only for the left and right parts
35124 if (isNested && node.comments) {
35125 parts = comments.printComments(path, function () {
35126 return concat$6(parts);
35130 // Our stopping case. Simply print the node normally.
35131 parts.push(path.call(print));
35137 function printAssignmentRight(leftNode, rightNode, printedRight, options) {
35138 if (hasLeadingOwnLineComment$1(options.originalText, rightNode, options)) {
35139 return indent$3(concat$6([hardline$4, printedRight]));
35142 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
35143 options.parser !== "json" && options.parser !== "json5" || rightNode.type === "SequenceExpression";
35146 return group$2(indent$3(concat$6([line$2, printedRight])));
35149 return concat$6([" ", printedRight]);
35152 function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) {
35154 return printedLeft;
35157 var printed = printAssignmentRight(leftNode, rightNode, printedRight, options);
35158 return group$2(concat$6([printedLeft, operator, printed]));
35161 function adjustClause(node, clause, forceSpace) {
35162 if (node.type === "EmptyStatement") {
35166 if (node.type === "BlockStatement" || forceSpace) {
35167 return concat$6([" ", clause]);
35170 return indent$3(concat$6([line$2, clause]));
35173 function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) {
35174 var raw = rawText$1(node);
35175 var isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral";
35176 return printString$1(raw, options, isDirectiveLiteral);
35179 function printRegex(node) {
35180 var flags = node.flags.split("").sort().join("");
35181 return `/${node.pattern}/${flags}`;
35184 function exprNeedsASIProtection(path, options) {
35185 var node = path.getValue();
35186 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;
35188 if (maybeASIProblem) {
35192 if (!hasNakedLeftSide$2(node)) {
35196 return path.call.apply(path, [function (childPath) {
35197 return exprNeedsASIProtection(childPath, options);
35198 }].concat(getLeftSidePathName$2(path, node)));
35201 function stmtNeedsASIProtection(path, options) {
35202 var node = path.getNode();
35204 if (node.type !== "ExpressionStatement") {
35208 return path.call(function (childPath) {
35209 return exprNeedsASIProtection(childPath, options);
35213 function shouldHugType(node) {
35214 if (isSimpleFlowType$1(node) || isObjectType$1(node)) {
35218 if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") {
35219 var voidCount = node.types.filter(function (n) {
35220 return n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword";
35222 var objectCount = node.types.filter(function (n) {
35223 return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}>
35224 n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference";
35227 if (node.types.length - 1 === voidCount && objectCount > 0) {
35235 function shouldHugArguments(fun) {
35236 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;
35239 function printArrayItems(path, options, printPath, print) {
35240 var printedElements = [];
35241 var separatorParts = [];
35242 path.each(function (childPath) {
35243 printedElements.push(concat$6(separatorParts));
35244 printedElements.push(group$2(print(childPath)));
35245 separatorParts = [",", line$2];
35247 if (childPath.getValue() && isNextLineEmpty$2(options.originalText, childPath.getValue(), options)) {
35248 separatorParts.push(softline$2);
35251 return concat$6(printedElements);
35254 function willPrintOwnComments(path
35257 var node = path.getValue();
35258 var parent = path.getParentNode();
35259 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);
35262 function canAttachComment(node) {
35263 return node.type && node.type !== "CommentBlock" && node.type !== "CommentLine" && node.type !== "Line" && node.type !== "Block" && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import";
35266 function printComment$1(commentPath, options) {
35267 var comment = commentPath.getValue();
35269 switch (comment.type) {
35270 case "CommentBlock":
35273 if (isIndentableBlockComment(comment)) {
35274 var printed = printIndentableBlockComment(comment); // We need to prevent an edge case of a previous trailing comment
35275 // printed as a `lineSuffix` which causes the comments to be
35276 // interleaved. See https://github.com/prettier/prettier/issues/4412
35278 if (comment.trailing && !hasNewline$3(options.originalText, options.locStart(comment), {
35281 return concat$6([hardline$4, printed]);
35287 var isInsideFlowComment = options.originalText.substr(options.locEnd(comment) - 3, 3) === "*-/";
35288 return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/");
35291 case "CommentLine":
35293 // Print shebangs with the proper comment characters
35294 if (options.originalText.slice(options.locStart(comment)).startsWith("#!")) {
35295 return "#!" + comment.value.trimRight();
35298 return "//" + comment.value.trimRight();
35301 throw new Error("Not a comment: " + JSON.stringify(comment));
35305 function isIndentableBlockComment(comment) {
35306 // If the comment has multiple lines and every line starts with a star
35307 // we can fix the indentation of each line. The stars in the `/*` and
35308 // `*/` delimiters are not included in the comment value, so add them
35310 var lines = `*${comment.value}*`.split("\n");
35311 return lines.length > 1 && lines.every(function (line) {
35312 return line.trim()[0] === "*";
35316 function printIndentableBlockComment(comment) {
35317 var lines = comment.value.split("\n");
35318 return concat$6(["/*", join$4(hardline$4, lines.map(function (line, index) {
35319 return index === 0 ? line.trimRight() : " " + (index < lines.length - 1 ? line.trim() : line.trimLeft());
35323 var printerEstree = {
35324 preprocess: preprocess_1,
35325 print: genericPrint,
35327 insertPragma: insertPragma$1,
35328 massageAstNode: clean_1,
35329 hasPrettierIgnore: hasPrettierIgnore$1,
35330 willPrintOwnComments,
35332 printComment: printComment$1,
35333 isBlockComment: comments$1.isBlockComment,
35335 ownLine: comments$1.handleOwnLineComment,
35336 endOfLine: comments$1.handleEndOfLineComment,
35337 remaining: comments$1.handleRemainingComment
35341 var _require$$0$builders$2 = doc.builders,
35342 concat$7 = _require$$0$builders$2.concat,
35343 hardline$5 = _require$$0$builders$2.hardline,
35344 indent$4 = _require$$0$builders$2.indent,
35345 join$5 = _require$$0$builders$2.join;
35347 function genericPrint$1(path, options, print) {
35348 var node = path.getValue();
35350 switch (node.type) {
35352 return concat$7([path.call(print, "node"), hardline$5]);
35354 case "ArrayExpression":
35355 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, "]"]);
35357 case "ObjectExpression":
35358 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, "}"]);
35360 case "ObjectProperty":
35361 return concat$7([path.call(print, "key"), ": ", path.call(print, "value")]);
35363 case "UnaryExpression":
35364 return concat$7([node.operator === "+" ? "" : node.operator, path.call(print, "argument")]);
35366 case "NullLiteral":
35369 case "BooleanLiteral":
35370 return node.value ? "true" : "false";
35372 case "StringLiteral":
35373 case "NumericLiteral":
35374 return JSON.stringify(node.value);
35377 return JSON.stringify(node.name);
35380 /* istanbul ignore next */
35381 throw new Error("unknown type: " + JSON.stringify(node.type));
35385 function clean$1(node, newNode
35388 delete newNode.start;
35389 delete newNode.end;
35390 delete newNode.extra;
35391 delete newNode.loc;
35392 delete newNode.comments;
35393 delete newNode.errors;
35395 if (node.type === "Identifier") {
35397 type: "StringLiteral",
35402 if (node.type === "UnaryExpression" && node.operator === "+") {
35403 return newNode.argument;
35407 var printerEstreeJson = {
35408 preprocess: preprocess_1,
35409 print: genericPrint$1,
35410 massageAstNode: clean$1
35413 var CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
35415 var commonOptions = {
35418 category: CATEGORY_COMMON,
35421 description: "Print spaces between brackets.",
35422 oppositeDescription: "Do not print spaces between brackets."
35426 category: CATEGORY_COMMON,
35429 description: "Use single quotes instead of double quotes."
35433 category: CATEGORY_COMMON,
35442 description: "How to wrap prose.",
35446 description: "Wrap prose if it exceeds the print width."
35450 description: "Do not wrap prose."
35454 description: "Wrap prose as-is."
35457 deprecated: "1.9.0",
35461 deprecated: "1.9.0",
35467 var CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
35472 category: CATEGORY_JAVASCRIPT,
35475 description: "Include parentheses around a sole arrow function parameter.",
35478 description: "Omit parens when possible. Example: `x => x`"
35481 description: "Always include parens. Example: `(x) => x`"
35484 bracketSpacing: commonOptions.bracketSpacing,
35485 jsxBracketSameLine: {
35487 category: CATEGORY_JAVASCRIPT,
35490 description: "Put > on the last line instead of at a new line."
35494 category: CATEGORY_JAVASCRIPT,
35497 description: "Print semicolons.",
35498 oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them."
35500 singleQuote: commonOptions.singleQuote,
35503 category: CATEGORY_JAVASCRIPT,
35506 description: "Use single quotes in JSX."
35510 category: CATEGORY_JAVASCRIPT,
35512 default: "as-needed",
35513 description: "Change when properties in objects are quoted.",
35515 value: "as-needed",
35516 description: "Only add quotes around object properties where required."
35518 value: "consistent",
35519 description: "If at least one property in an object requires quotes, quote all properties."
35522 description: "Respect the input use of quotes in object properties."
35527 category: CATEGORY_JAVASCRIPT,
35536 description: "Print trailing commas wherever possible when multi-line.",
35539 description: "No trailing commas."
35542 description: "Trailing commas where valid in ES5 (objects, arrays, etc.)"
35545 description: "Trailing commas wherever possible (including function arguments)."
35548 deprecated: "0.19.0",
35552 deprecated: "0.19.0",
35558 var createLanguage = function createLanguage(linguistData, transform) {
35561 for (var key in linguistData) {
35562 var newKey = key === "languageId" ? "linguistLanguageId" : key;
35563 language[newKey] = linguistData[key];
35566 return transform(language);
35569 var name$2 = "JavaScript";
35570 var type = "programming";
35571 var tmScope = "source.js";
35572 var aceMode = "javascript";
35573 var codemirrorMode = "javascript";
35574 var codemirrorMimeType = "text/javascript";
35575 var color = "#f1e05a";
35605 var interpreters = [
35614 var languageId = 183;
35620 codemirrorMode: codemirrorMode,
35621 codemirrorMimeType: codemirrorMimeType,
35624 extensions: extensions,
35625 filenames: filenames,
35626 interpreters: interpreters,
35627 languageId: languageId
35630 var JavaScript$1 = /*#__PURE__*/Object.freeze({
35636 codemirrorMode: codemirrorMode,
35637 codemirrorMimeType: codemirrorMimeType,
35640 extensions: extensions,
35641 filenames: filenames,
35642 interpreters: interpreters,
35643 languageId: languageId,
35644 'default': JavaScript
35647 var name$3 = "JSX";
35648 var type$1 = "programming";
35649 var group$3 = "JavaScript";
35650 var extensions$1 = [
35653 var tmScope$1 = "source.js.jsx";
35654 var aceMode$1 = "javascript";
35655 var codemirrorMode$1 = "jsx";
35656 var codemirrorMimeType$1 = "text/jsx";
35657 var languageId$1 = 178;
35662 extensions: extensions$1,
35663 tmScope: tmScope$1,
35664 aceMode: aceMode$1,
35665 codemirrorMode: codemirrorMode$1,
35666 codemirrorMimeType: codemirrorMimeType$1,
35667 languageId: languageId$1
35670 var JSX$1 = /*#__PURE__*/Object.freeze({
35675 extensions: extensions$1,
35676 tmScope: tmScope$1,
35677 aceMode: aceMode$1,
35678 codemirrorMode: codemirrorMode$1,
35679 codemirrorMimeType: codemirrorMimeType$1,
35680 languageId: languageId$1,
35684 var name$4 = "TypeScript";
35685 var type$2 = "programming";
35686 var color$1 = "#2b7489";
35690 var interpreters$1 = [
35694 var extensions$2 = [
35697 var tmScope$2 = "source.ts";
35698 var aceMode$2 = "typescript";
35699 var codemirrorMode$2 = "javascript";
35700 var codemirrorMimeType$2 = "application/typescript";
35701 var languageId$2 = 378;
35706 aliases: aliases$1,
35707 interpreters: interpreters$1,
35708 extensions: extensions$2,
35709 tmScope: tmScope$2,
35710 aceMode: aceMode$2,
35711 codemirrorMode: codemirrorMode$2,
35712 codemirrorMimeType: codemirrorMimeType$2,
35713 languageId: languageId$2
35716 var TypeScript$1 = /*#__PURE__*/Object.freeze({
35721 aliases: aliases$1,
35722 interpreters: interpreters$1,
35723 extensions: extensions$2,
35724 tmScope: tmScope$2,
35725 aceMode: aceMode$2,
35726 codemirrorMode: codemirrorMode$2,
35727 codemirrorMimeType: codemirrorMimeType$2,
35728 languageId: languageId$2,
35729 'default': TypeScript
35732 var name$5 = "TSX";
35733 var type$3 = "programming";
35734 var group$4 = "TypeScript";
35735 var extensions$3 = [
35738 var tmScope$3 = "source.tsx";
35739 var aceMode$3 = "javascript";
35740 var codemirrorMode$3 = "jsx";
35741 var codemirrorMimeType$3 = "text/jsx";
35742 var languageId$3 = 94901924;
35747 extensions: extensions$3,
35748 tmScope: tmScope$3,
35749 aceMode: aceMode$3,
35750 codemirrorMode: codemirrorMode$3,
35751 codemirrorMimeType: codemirrorMimeType$3,
35752 languageId: languageId$3
35755 var TSX$1 = /*#__PURE__*/Object.freeze({
35760 extensions: extensions$3,
35761 tmScope: tmScope$3,
35762 aceMode: aceMode$3,
35763 codemirrorMode: codemirrorMode$3,
35764 codemirrorMimeType: codemirrorMimeType$3,
35765 languageId: languageId$3,
35769 var name$6 = "JSON";
35770 var type$4 = "data";
35771 var tmScope$4 = "source.json";
35772 var aceMode$4 = "json";
35773 var codemirrorMode$4 = "javascript";
35774 var codemirrorMimeType$4 = "application/json";
35775 var searchable = false;
35776 var extensions$4 = [
35783 ".JSON-tmLanguage",
35794 var filenames$1 = [
35803 var languageId$4 = 174;
35807 tmScope: tmScope$4,
35808 aceMode: aceMode$4,
35809 codemirrorMode: codemirrorMode$4,
35810 codemirrorMimeType: codemirrorMimeType$4,
35811 searchable: searchable,
35812 extensions: extensions$4,
35813 filenames: filenames$1,
35814 languageId: languageId$4
35817 var _JSON$1 = /*#__PURE__*/Object.freeze({
35821 tmScope: tmScope$4,
35822 aceMode: aceMode$4,
35823 codemirrorMode: codemirrorMode$4,
35824 codemirrorMimeType: codemirrorMimeType$4,
35825 searchable: searchable,
35826 extensions: extensions$4,
35827 filenames: filenames$1,
35828 languageId: languageId$4,
35832 var name$7 = "JSON with Comments";
35833 var type$5 = "data";
35834 var group$5 = "JSON";
35835 var tmScope$5 = "source.js";
35836 var aceMode$5 = "javascript";
35837 var codemirrorMode$5 = "javascript";
35838 var codemirrorMimeType$5 = "text/javascript";
35842 var extensions$5 = [
35844 ".sublime-commands",
35845 ".sublime-completions",
35849 ".sublime-mousemap",
35850 ".sublime-project",
35851 ".sublime-settings",
35853 ".sublime-workspace",
35854 ".sublime_metrics",
35857 var filenames$2 = [
35864 "language-configuration.json",
35867 var languageId$5 = 423;
35868 var JSON_with_Comments = {
35872 tmScope: tmScope$5,
35873 aceMode: aceMode$5,
35874 codemirrorMode: codemirrorMode$5,
35875 codemirrorMimeType: codemirrorMimeType$5,
35876 aliases: aliases$2,
35877 extensions: extensions$5,
35878 filenames: filenames$2,
35879 languageId: languageId$5
35882 var JSON_with_Comments$1 = /*#__PURE__*/Object.freeze({
35887 tmScope: tmScope$5,
35888 aceMode: aceMode$5,
35889 codemirrorMode: codemirrorMode$5,
35890 codemirrorMimeType: codemirrorMimeType$5,
35891 aliases: aliases$2,
35892 extensions: extensions$5,
35893 filenames: filenames$2,
35894 languageId: languageId$5,
35895 'default': JSON_with_Comments
35898 var name$8 = "JSON5";
35899 var type$6 = "data";
35900 var extensions$6 = [
35903 var tmScope$6 = "source.js";
35904 var aceMode$6 = "javascript";
35905 var codemirrorMode$6 = "javascript";
35906 var codemirrorMimeType$6 = "application/json";
35907 var languageId$6 = 175;
35911 extensions: extensions$6,
35912 tmScope: tmScope$6,
35913 aceMode: aceMode$6,
35914 codemirrorMode: codemirrorMode$6,
35915 codemirrorMimeType: codemirrorMimeType$6,
35916 languageId: languageId$6
35919 var JSON5$1 = /*#__PURE__*/Object.freeze({
35923 extensions: extensions$6,
35924 tmScope: tmScope$6,
35925 aceMode: aceMode$6,
35926 codemirrorMode: codemirrorMode$6,
35927 codemirrorMimeType: codemirrorMimeType$6,
35928 languageId: languageId$6,
35932 var require$$0$1 = getCjsExportFromNamespace(JavaScript$1);
35934 var require$$1 = getCjsExportFromNamespace(JSX$1);
35936 var require$$2 = getCjsExportFromNamespace(TypeScript$1);
35938 var require$$3 = getCjsExportFromNamespace(TSX$1);
35940 var require$$4$1 = getCjsExportFromNamespace(_JSON$1);
35942 var require$$5 = getCjsExportFromNamespace(JSON_with_Comments$1);
35944 var require$$6 = getCjsExportFromNamespace(JSON5$1);
35946 var languages = [createLanguage(require$$0$1, function (data) {
35947 return Object.assign(data, {
35949 parsers: ["babel", "flow"],
35950 vscodeLanguageIds: ["javascript", "mongo"],
35951 interpreters: data.interpreters.concat(["nodejs"])
35953 }), createLanguage(require$$0$1, function (data) {
35954 return Object.assign(data, {
35957 parsers: ["babel", "flow"],
35958 vscodeLanguageIds: ["javascript"],
35961 extensions: [".js.flow"]
35963 }), createLanguage(require$$1, function (data) {
35964 return Object.assign(data, {
35966 parsers: ["babel", "flow"],
35967 vscodeLanguageIds: ["javascriptreact"]
35969 }), createLanguage(require$$2, function (data) {
35970 return Object.assign(data, {
35972 parsers: ["typescript"],
35973 vscodeLanguageIds: ["typescript"]
35975 }), createLanguage(require$$3, function (data) {
35976 return Object.assign(data, {
35978 parsers: ["typescript"],
35979 vscodeLanguageIds: ["typescriptreact"]
35981 }), createLanguage(require$$4$1, function (data) {
35982 return Object.assign(data, {
35983 name: "JSON.stringify",
35985 parsers: ["json-stringify"],
35986 vscodeLanguageIds: ["json"],
35988 // .json file defaults to json instead of json-stringify
35989 filenames: ["package.json", "package-lock.json", "composer.json"]
35991 }), createLanguage(require$$4$1, function (data) {
35992 return Object.assign(data, {
35995 vscodeLanguageIds: ["json"],
35996 filenames: data.filenames.concat([".prettierrc"])
35998 }), createLanguage(require$$5, function (data) {
35999 return Object.assign(data, {
36002 vscodeLanguageIds: ["jsonc"],
36003 filenames: data.filenames.concat([".eslintrc"])
36005 }), createLanguage(require$$6, function (data) {
36006 return Object.assign(data, {
36008 parsers: ["json5"],
36009 vscodeLanguageIds: ["json5"]
36013 estree: printerEstree,
36014 "estree-json": printerEstreeJson
36018 options: options$2,
36173 var htmlTagNames = /*#__PURE__*/Object.freeze({
36178 var htmlTagNames$1 = getCjsExportFromNamespace(htmlTagNames);
36180 function clean$2(ast, newObj, parent) {
36181 ["raw", // front-matter
36182 "raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(function (name) {
36183 delete newObj[name];
36186 if (ast.type === "yaml") {
36187 delete newObj.value;
36188 } // --insert-pragma
36191 if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0 && ( // first non-front-matter comment
36192 parent.nodes[0] === ast || (parent.nodes[0].type === "yaml" || parent.nodes[0].type === "toml") && parent.nodes[1] === ast)) {
36198 delete newObj.text; // standalone pragma
36200 if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) {
36205 if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") {
36206 delete newObj.value;
36209 if (ast.type === "css-rule") {
36210 delete newObj.params;
36213 if (ast.type === "selector-combinator") {
36214 newObj.value = newObj.value.replace(/\s+/g, " ");
36217 if (ast.type === "media-feature") {
36218 newObj.value = newObj.value.replace(/ /g, "");
36221 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") {
36222 newObj.value = newObj.value.toLowerCase();
36225 if (ast.type === "css-decl") {
36226 newObj.prop = newObj.prop.toLowerCase();
36229 if (ast.type === "css-atrule" || ast.type === "css-import") {
36230 newObj.name = newObj.name.toLowerCase();
36233 if (ast.type === "value-number") {
36234 newObj.unit = newObj.unit.toLowerCase();
36237 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) {
36238 newObj.value = cleanCSSStrings(newObj.value);
36241 if (ast.type === "selector-attribute") {
36242 newObj.attribute = newObj.attribute.trim();
36244 if (newObj.namespace) {
36245 if (typeof newObj.namespace === "string") {
36246 newObj.namespace = newObj.namespace.trim();
36248 if (newObj.namespace.length === 0) {
36249 newObj.namespace = true;
36254 if (newObj.value) {
36255 newObj.value = newObj.value.trim().replace(/^['"]|['"]$/g, "");
36256 delete newObj.quoted;
36260 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) {
36261 newObj.value = newObj.value.replace(/([\d.eE+-]+)([a-zA-Z]*)/g, function (match, numStr, unit) {
36262 var num = Number(numStr);
36263 return isNaN(num) ? match : num + unit.toLowerCase();
36267 if (ast.type === "selector-tag") {
36268 var lowercasedValue = ast.value.toLowerCase();
36270 if (htmlTagNames$1.indexOf(lowercasedValue) !== -1) {
36271 newObj.value = lowercasedValue;
36274 if (["from", "to"].indexOf(lowercasedValue) !== -1) {
36275 newObj.value = lowercasedValue;
36277 } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func`
36280 if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") {
36281 delete newObj.value;
36282 } // Workaround for SCSS nested properties
36285 if (ast.type === "selector-unknown") {
36286 delete newObj.value;
36290 function cleanCSSStrings(value) {
36291 return value.replace(/'/g, '"').replace(/\\([^a-fA-F\d])/g, "$1");
36294 var clean_1$1 = clean$2;
36296 var _require$$0$builders$3 = doc.builders,
36297 hardline$6 = _require$$0$builders$3.hardline,
36298 literalline$3 = _require$$0$builders$3.literalline,
36299 concat$8 = _require$$0$builders$3.concat,
36300 markAsRoot$1 = _require$$0$builders$3.markAsRoot,
36301 mapDoc$4 = doc.utils.mapDoc;
36303 function embed$1(path, print, textToDoc
36306 var node = path.getValue();
36308 if (node.type === "yaml") {
36309 return markAsRoot$1(concat$8(["---", hardline$6, node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
36311 })) : "", "---", hardline$6]));
36316 function replaceNewlinesWithLiterallines(doc) {
36317 return mapDoc$4(doc, function (currentDoc) {
36318 return typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$8(currentDoc.split(/(\n)/g).map(function (v, i) {
36319 return i % 2 === 0 ? v : literalline$3;
36325 var embed_1$1 = embed$1;
36327 var DELIMITER_MAP = {
36332 function parse$3(text) {
36333 var delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp).join("|");
36334 var match = text.match( // trailing spaces after delimiters are allowed
36335 new RegExp(`^(${delimiterRegex})[^\\n\\S]*\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)`));
36337 if (match === null) {
36344 var raw = match[0].replace(/\n$/, "");
36345 var delimiter = match[1];
36346 var value = match[2];
36349 type: DELIMITER_MAP[delimiter],
36353 content: match[0].replace(/[^\n]/g, " ") + text.slice(match[0].length)
36357 var frontMatter = parse$3;
36359 function hasPragma$1(text) {
36360 return pragma.hasPragma(frontMatter(text).content);
36363 function insertPragma$2(text) {
36364 var _parseFrontMatter = frontMatter(text),
36365 frontMatter$1 = _parseFrontMatter.frontMatter,
36366 content = _parseFrontMatter.content;
36368 return (frontMatter$1 ? frontMatter$1.raw + "\n\n" : "") + pragma.insertPragma(content);
36372 hasPragma: hasPragma$1,
36373 insertPragma: insertPragma$2
36376 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"];
36378 function getAncestorCounter(path, typeOrTypes) {
36379 var types = [].concat(typeOrTypes);
36383 while (ancestorNode = path.getParentNode(++counter)) {
36384 if (types.indexOf(ancestorNode.type) !== -1) {
36392 function getAncestorNode(path, typeOrTypes) {
36393 var counter = getAncestorCounter(path, typeOrTypes);
36394 return counter === -1 ? null : path.getParentNode(counter);
36397 function getPropOfDeclNode(path) {
36398 var declAncestorNode = getAncestorNode(path, "css-decl");
36399 return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase();
36402 function isSCSS(parser, text) {
36403 var hasExplicitParserChoice = parser === "less" || parser === "scss";
36404 var IS_POSSIBLY_SCSS = /(\w\s*: [^}:]+|#){|@import[^\n]+(url|,)/;
36405 return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text);
36408 function isWideKeywords(value) {
36409 return ["initial", "inherit", "unset", "revert"].indexOf(value.toLowerCase()) !== -1;
36412 function isKeyframeAtRuleKeywords(path, value) {
36413 var atRuleAncestorNode = getAncestorNode(path, "css-atrule");
36414 return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].indexOf(value.toLowerCase()) !== -1;
36417 function maybeToLowerCase(value) {
36418 return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase();
36421 function insideValueFunctionNode(path, functionName) {
36422 var funcAncestorNode = getAncestorNode(path, "value-func");
36423 return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName;
36426 function insideICSSRuleNode(path) {
36427 var ruleAncestorNode = getAncestorNode(path, "css-rule");
36428 return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export"));
36431 function insideAtRuleNode(path, atRuleNameOrAtRuleNames) {
36432 var atRuleNames = [].concat(atRuleNameOrAtRuleNames);
36433 var atRuleAncestorNode = getAncestorNode(path, "css-atrule");
36434 return atRuleAncestorNode && atRuleNames.indexOf(atRuleAncestorNode.name.toLowerCase()) !== -1;
36437 function insideURLFunctionInImportAtRuleNode(path) {
36438 var node = path.getValue();
36439 var atRuleAncestorNode = getAncestorNode(path, "css-atrule");
36440 return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2;
36443 function isURLFunctionNode(node) {
36444 return node.type === "value-func" && node.value.toLowerCase() === "url";
36447 function isLastNode(path, node) {
36448 var parentNode = path.getParentNode();
36454 var nodes = parentNode.nodes;
36455 return nodes && nodes.indexOf(node) === nodes.length - 1;
36458 function isHTMLTag(value) {
36459 return htmlTagNames$1.indexOf(value.toLowerCase()) !== -1;
36462 function isDetachedRulesetDeclarationNode(node) {
36463 // If a Less file ends up being parsed with the SCSS parser, Less
36464 // variable declarations will be parsed as atrules with names ending
36465 // with a colon, so keep the original case then.
36466 if (!node.selector) {
36470 return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value);
36473 function isForKeywordNode(node) {
36474 return node.type === "value-word" && ["from", "through", "end"].indexOf(node.value) !== -1;
36477 function isIfElseKeywordNode(node) {
36478 return node.type === "value-word" && ["and", "or", "not"].indexOf(node.value) !== -1;
36481 function isEachKeywordNode(node) {
36482 return node.type === "value-word" && node.value === "in";
36485 function isMultiplicationNode(node) {
36486 return node.type === "value-operator" && node.value === "*";
36489 function isDivisionNode(node) {
36490 return node.type === "value-operator" && node.value === "/";
36493 function isAdditionNode(node) {
36494 return node.type === "value-operator" && node.value === "+";
36497 function isSubtractionNode(node) {
36498 return node.type === "value-operator" && node.value === "-";
36501 function isModuloNode(node) {
36502 return node.type === "value-operator" && node.value === "%";
36505 function isMathOperatorNode(node) {
36506 return isMultiplicationNode(node) || isDivisionNode(node) || isAdditionNode(node) || isSubtractionNode(node) || isModuloNode(node);
36509 function isEqualityOperatorNode(node) {
36510 return node.type === "value-word" && ["==", "!="].indexOf(node.value) !== -1;
36513 function isRelationalOperatorNode(node) {
36514 return node.type === "value-word" && ["<", ">", "<=", ">="].indexOf(node.value) !== -1;
36517 function isSCSSControlDirectiveNode(node) {
36518 return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].indexOf(node.name) !== -1;
36521 function isSCSSNestedPropertyNode(node) {
36522 if (!node.selector) {
36526 return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":");
36529 function isDetachedRulesetCallNode(node) {
36530 return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params);
36533 function isTemplatePlaceholderNode(node) {
36534 return node.name.startsWith("prettier-placeholder");
36537 function isTemplatePropNode(node) {
36538 return node.prop.startsWith("@prettier-placeholder");
36541 function isPostcssSimpleVarNode(currentNode, nextNode) {
36542 return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before;
36545 function hasComposesNode(node) {
36546 return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes";
36549 function hasParensAroundNode(node) {
36550 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;
36553 function hasEmptyRawBefore(node) {
36554 return node.raws && node.raws.before === "";
36557 function isKeyValuePairNode(node) {
36558 return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon";
36561 function isKeyValuePairInParenGroupNode(node) {
36562 return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode(node.groups[0]);
36565 function isSCSSMapItemNode(path) {
36566 var node = path.getValue(); // Ignore empty item (i.e. `$key: ()`)
36568 if (node.groups.length === 0) {
36572 var parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`)
36574 if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) {
36578 var declNode = getAncestorNode(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`)
36580 if (declNode && declNode.prop && declNode.prop.startsWith("$")) {
36582 } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`)
36585 if (isKeyValuePairInParenGroupNode(parentParentNode)) {
36587 } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`)
36590 if (parentParentNode.type === "value-func") {
36597 function isInlineValueCommentNode(node) {
36598 return node.type === "value-comment" && node.inline;
36601 function isHashNode(node) {
36602 return node.type === "value-word" && node.value === "#";
36605 function isLeftCurlyBraceNode(node) {
36606 return node.type === "value-word" && node.value === "{";
36609 function isRightCurlyBraceNode(node) {
36610 return node.type === "value-word" && node.value === "}";
36613 function isWordNode(node) {
36614 return ["value-word", "value-atword"].indexOf(node.type) !== -1;
36617 function isColonNode(node) {
36618 return node.type === "value-colon";
36621 function isMediaAndSupportsKeywords(node) {
36622 return node.value && ["not", "and", "or"].indexOf(node.value.toLowerCase()) !== -1;
36625 function isColorAdjusterFuncNode(node) {
36626 if (node.type !== "value-func") {
36630 return colorAdjusterFunctions.indexOf(node.value.toLowerCase()) !== -1;
36634 getAncestorCounter,
36638 insideValueFunctionNode,
36639 insideICSSRuleNode,
36641 insideURLFunctionInImportAtRuleNode,
36642 isKeyframeAtRuleKeywords,
36647 isSCSSControlDirectiveNode,
36648 isDetachedRulesetDeclarationNode,
36649 isRelationalOperatorNode,
36650 isEqualityOperatorNode,
36651 isMultiplicationNode,
36656 isMathOperatorNode,
36660 isIfElseKeywordNode,
36662 hasParensAroundNode,
36664 isSCSSNestedPropertyNode,
36665 isDetachedRulesetCallNode,
36666 isTemplatePlaceholderNode,
36667 isTemplatePropNode,
36668 isPostcssSimpleVarNode,
36669 isKeyValuePairNode,
36670 isKeyValuePairInParenGroupNode,
36672 isInlineValueCommentNode,
36674 isLeftCurlyBraceNode,
36675 isRightCurlyBraceNode,
36678 isMediaAndSupportsKeywords,
36679 isColorAdjusterFuncNode
36682 var insertPragma$3 = pragma$1.insertPragma;
36683 var printNumber$2 = util.printNumber,
36684 printString$2 = util.printString,
36685 hasIgnoreComment$3 = util.hasIgnoreComment,
36686 hasNewline$4 = util.hasNewline;
36687 var isNextLineEmpty$3 = utilShared.isNextLineEmpty;
36688 var _require$$3$builders = doc.builders,
36689 concat$9 = _require$$3$builders.concat,
36690 join$6 = _require$$3$builders.join,
36691 line$3 = _require$$3$builders.line,
36692 hardline$7 = _require$$3$builders.hardline,
36693 softline$3 = _require$$3$builders.softline,
36694 group$6 = _require$$3$builders.group,
36695 fill$3 = _require$$3$builders.fill,
36696 indent$5 = _require$$3$builders.indent,
36697 dedent$2 = _require$$3$builders.dedent,
36698 ifBreak$2 = _require$$3$builders.ifBreak,
36699 removeLines$2 = doc.utils.removeLines;
36700 var getAncestorNode$1 = utils$3.getAncestorNode,
36701 getPropOfDeclNode$1 = utils$3.getPropOfDeclNode,
36702 maybeToLowerCase$1 = utils$3.maybeToLowerCase,
36703 insideValueFunctionNode$1 = utils$3.insideValueFunctionNode,
36704 insideICSSRuleNode$1 = utils$3.insideICSSRuleNode,
36705 insideAtRuleNode$1 = utils$3.insideAtRuleNode,
36706 insideURLFunctionInImportAtRuleNode$1 = utils$3.insideURLFunctionInImportAtRuleNode,
36707 isKeyframeAtRuleKeywords$1 = utils$3.isKeyframeAtRuleKeywords,
36708 isHTMLTag$1 = utils$3.isHTMLTag,
36709 isWideKeywords$1 = utils$3.isWideKeywords,
36710 isSCSS$1 = utils$3.isSCSS,
36711 isLastNode$1 = utils$3.isLastNode,
36712 isSCSSControlDirectiveNode$1 = utils$3.isSCSSControlDirectiveNode,
36713 isDetachedRulesetDeclarationNode$1 = utils$3.isDetachedRulesetDeclarationNode,
36714 isRelationalOperatorNode$1 = utils$3.isRelationalOperatorNode,
36715 isEqualityOperatorNode$1 = utils$3.isEqualityOperatorNode,
36716 isMultiplicationNode$1 = utils$3.isMultiplicationNode,
36717 isDivisionNode$1 = utils$3.isDivisionNode,
36718 isAdditionNode$1 = utils$3.isAdditionNode,
36719 isSubtractionNode$1 = utils$3.isSubtractionNode,
36720 isMathOperatorNode$1 = utils$3.isMathOperatorNode,
36721 isEachKeywordNode$1 = utils$3.isEachKeywordNode,
36722 isForKeywordNode$1 = utils$3.isForKeywordNode,
36723 isURLFunctionNode$1 = utils$3.isURLFunctionNode,
36724 isIfElseKeywordNode$1 = utils$3.isIfElseKeywordNode,
36725 hasComposesNode$1 = utils$3.hasComposesNode,
36726 hasParensAroundNode$1 = utils$3.hasParensAroundNode,
36727 hasEmptyRawBefore$1 = utils$3.hasEmptyRawBefore,
36728 isKeyValuePairNode$1 = utils$3.isKeyValuePairNode,
36729 isDetachedRulesetCallNode$1 = utils$3.isDetachedRulesetCallNode,
36730 isTemplatePlaceholderNode$1 = utils$3.isTemplatePlaceholderNode,
36731 isTemplatePropNode$1 = utils$3.isTemplatePropNode,
36732 isPostcssSimpleVarNode$1 = utils$3.isPostcssSimpleVarNode,
36733 isSCSSMapItemNode$1 = utils$3.isSCSSMapItemNode,
36734 isInlineValueCommentNode$1 = utils$3.isInlineValueCommentNode,
36735 isHashNode$1 = utils$3.isHashNode,
36736 isLeftCurlyBraceNode$1 = utils$3.isLeftCurlyBraceNode,
36737 isRightCurlyBraceNode$1 = utils$3.isRightCurlyBraceNode,
36738 isWordNode$1 = utils$3.isWordNode,
36739 isColonNode$1 = utils$3.isColonNode,
36740 isMediaAndSupportsKeywords$1 = utils$3.isMediaAndSupportsKeywords,
36741 isColorAdjusterFuncNode$1 = utils$3.isColorAdjusterFuncNode;
36743 function shouldPrintComma$1(options) {
36744 switch (options.trailingComma) {
36755 function genericPrint$2(path, options, print) {
36756 var node = path.getValue();
36757 /* istanbul ignore if */
36763 if (typeof node === "string") {
36767 switch (node.type) {
36770 return concat$9([node.raw, hardline$7]);
36774 var nodes = printNodeSequence(path, options, print);
36776 if (nodes.parts.length) {
36777 return concat$9([nodes, hardline$7]);
36783 case "css-comment":
36785 if (node.raws.content) {
36786 return node.raws.content;
36789 var text = options.originalText.slice(options.locStart(node), options.locEnd(node));
36790 var rawText = node.raws.text || node.text; // Workaround a bug where the location is off.
36791 // https://github.com/postcss/postcss-scss/issues/63
36793 if (text.indexOf(rawText) === -1) {
36794 if (node.raws.inline) {
36795 return concat$9(["// ", rawText]);
36798 return concat$9(["/* ", rawText, " */"]);
36806 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) ? ";" : ""]) : ";"]);
36811 var parentNode = path.getParentNode();
36812 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] !== ";" ? "" : ";"]);
36817 var _parentNode = path.getParentNode();
36819 return concat$9(["@", // If a Less file ends up being parsed with the SCSS parser, Less
36820 // variable declarations will be parsed as at-rules with names ending
36821 // with a colon, so keep the original case then.
36822 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] !== ";" ? "" : ";"]);
36824 // postcss-media-query-parser
36826 case "media-query-list":
36829 path.each(function (childPath) {
36830 var node = childPath.getValue();
36832 if (node.type === "media-query" && node.value === "") {
36836 parts.push(childPath.call(print));
36838 return group$6(indent$5(join$6(line$3, parts)));
36841 case "media-query":
36843 return concat$9([join$6(" ", path.map(print, "nodes")), isLastNode$1(path, node) ? "" : ","]);
36848 return adjustNumbers(adjustStrings(node.value, options));
36851 case "media-feature-expression":
36857 return concat$9(["(", concat$9(path.map(print, "nodes")), ")"]);
36860 case "media-feature":
36862 return maybeToLowerCase$1(adjustStrings(node.value.replace(/ +/g, " "), options));
36865 case "media-colon":
36867 return concat$9([node.value, " "]);
36870 case "media-value":
36872 return adjustNumbers(adjustStrings(node.value, options));
36875 case "media-keyword":
36877 return adjustStrings(node.value, options);
36882 return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options);
36885 case "media-unknown":
36889 // postcss-selector-parser
36891 case "selector-root":
36893 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"))]));
36896 case "selector-selector":
36898 return group$6(indent$5(concat$9(path.map(print, "nodes"))));
36901 case "selector-comment":
36906 case "selector-string":
36908 return adjustStrings(node.value, options);
36911 case "selector-tag":
36913 var _parentNode2 = path.getParentNode();
36915 var index = _parentNode2 && _parentNode2.nodes.indexOf(node);
36917 var prevNode = index && _parentNode2.nodes[index - 1];
36918 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)]);
36921 case "selector-id":
36923 return concat$9(["#", node.value]);
36926 case "selector-class":
36928 return concat$9([".", adjustNumbers(adjustStrings(node.value, options))]);
36931 case "selector-attribute":
36933 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" : "", "]"]);
36936 case "selector-combinator":
36938 if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") {
36939 var _parentNode3 = path.getParentNode();
36941 var _leading = _parentNode3.type === "selector-selector" && _parentNode3.nodes[0] === node ? "" : line$3;
36943 return concat$9([_leading, node.value, isLastNode$1(path, node) ? "" : " "]);
36946 var leading = node.value.trim().startsWith("(") ? line$3 : "";
36947 var value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$3;
36948 return concat$9([leading, value]);
36951 case "selector-universal":
36953 return concat$9([node.namespace ? concat$9([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]);
36956 case "selector-pseudo":
36958 return concat$9([maybeToLowerCase$1(node.value), node.nodes && node.nodes.length > 0 ? concat$9(["(", join$6(", ", path.map(print, "nodes")), ")"]) : ""]);
36961 case "selector-nesting":
36966 case "selector-unknown":
36968 var ruleAncestorNode = getAncestorNode$1(path, "css-rule"); // Nested SCSS property
36970 if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) {
36971 return adjustNumbers(adjustStrings(maybeToLowerCase$1(node.value), options));
36976 // postcss-values-parser
36978 case "value-value":
36981 return path.call(print, "group");
36984 case "value-comment":
36986 return concat$9([node.inline ? "//" : "/*", node.value, node.inline ? "" : "*/"]);
36989 case "value-comma_group":
36991 var _parentNode4 = path.getParentNode();
36993 var parentParentNode = path.getParentNode(1);
36994 var declAncestorProp = getPropOfDeclNode$1(path);
36995 var isGridValue = declAncestorProp && _parentNode4.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template"));
36996 var atRuleAncestorNode = getAncestorNode$1(path, "css-atrule");
36997 var isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode$1(atRuleAncestorNode);
36998 var printed = path.map(print, "groups");
37000 var insideURLFunction = insideValueFunctionNode$1(path, "url");
37001 var insideSCSSInterpolationInString = false;
37002 var didBreak = false;
37004 for (var i = 0; i < node.groups.length; ++i) {
37005 _parts.push(printed[i]); // Ignore value inside `url()`
37008 if (insideURLFunction) {
37012 var iPrevNode = node.groups[i - 1];
37013 var iNode = node.groups[i];
37014 var iNextNode = node.groups[i + 1];
37015 var iNextNextNode = node.groups[i + 2]; // Ignore after latest node (i.e. before semicolon)
37019 } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`)
37022 var isStartSCSSInterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{");
37023 var isEndingSCSSInterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}");
37025 if (isStartSCSSInterpolationInString || isEndingSCSSInterpolationInString) {
37026 insideSCSSInterpolationInString = !insideSCSSInterpolationInString;
37030 if (insideSCSSInterpolationInString) {
37032 } // Ignore colon (i.e. `:`)
37035 if (isColonNode$1(iNode) || isColonNode$1(iNextNode)) {
37037 } // Ignore `@` in Less (i.e. `@@var;`)
37040 if (iNode.type === "value-atword" && iNode.value === "") {
37042 } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`)
37045 if (iNode.value === "~") {
37047 } // Ignore escape `\`
37050 if (iNode.value && iNode.value.indexOf("\\") !== -1 && iNextNode && iNextNode.type !== "value-comment") {
37052 } // Ignore escaped `/`
37055 if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") {
37057 } // Ignore `\` (i.e. `$variable: \@small;`)
37060 if (iNode.value === "\\") {
37062 } // Ignore `$$` (i.e. `background-color: $$(style)Color;`)
37065 if (isPostcssSimpleVarNode$1(iNode, iNextNode)) {
37067 } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`)
37070 if (isHashNode$1(iNode) || isLeftCurlyBraceNode$1(iNode) || isRightCurlyBraceNode$1(iNextNode) || isLeftCurlyBraceNode$1(iNextNode) && hasEmptyRawBefore$1(iNextNode) || isRightCurlyBraceNode$1(iNode) && hasEmptyRawBefore$1(iNextNode)) {
37072 } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`)
37075 if (iNode.value === "--" && isHashNode$1(iNextNode)) {
37077 } // Formatting math operations
37080 var isMathOperator = isMathOperatorNode$1(iNode);
37081 var isNextMathOperator = isMathOperatorNode$1(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is
37082 // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`)
37083 // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`)
37085 if ((isMathOperator && isHashNode$1(iNextNode) || isNextMathOperator && isRightCurlyBraceNode$1(iNode)) && hasEmptyRawBefore$1(iNextNode)) {
37087 } // Print spaces before and after addition and subtraction math operators as is in `calc` function
37088 // due to the fact that it is not valid syntax
37089 // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`)
37092 if (insideValueFunctionNode$1(path, "calc") && (isAdditionNode$1(iNode) || isAdditionNode$1(iNextNode) || isSubtractionNode$1(iNode) || isSubtractionNode$1(iNextNode)) && hasEmptyRawBefore$1(iNextNode)) {
37094 } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`)
37095 // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is.
37098 var isColorAdjusterNode = (isAdditionNode$1(iNode) || isSubtractionNode$1(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode$1(parentParentNode) && !hasEmptyRawBefore$1(iNextNode);
37099 var requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode$1(iNextNextNode) || iNode.type === "value-func" || isWordNode$1(iNode);
37100 var requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode$1(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode$1(iPrevNode); // Formatting `/`, `+`, `-` sign
37102 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)))) {
37104 } // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`)
37107 if (isInlineValueCommentNode$1(iNode)) {
37108 _parts.push(hardline$7);
37111 } // Handle keywords in SCSS control directive
37114 if (isControlDirective && (isEqualityOperatorNode$1(iNextNode) || isRelationalOperatorNode$1(iNextNode) || isIfElseKeywordNode$1(iNextNode) || isEachKeywordNode$1(iNode) || isForKeywordNode$1(iNode))) {
37118 } // At-rule `namespace` should be in one line
37121 if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") {
37125 } // Formatting `grid` property
37129 if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) {
37130 _parts.push(hardline$7);
37138 } // Add `space` before next math operation
37139 // Note: `grip` property have `/` delimiter and it is not math operation, so
37140 // `grid` property handles above
37143 if (isNextMathOperator) {
37147 } // Be default all values go through `line`
37150 _parts.push(line$3);
37154 _parts.unshift(hardline$7);
37157 if (isControlDirective) {
37158 return group$6(indent$5(concat$9(_parts)));
37159 } // Indent is not needed for import url when url is very long
37160 // and node has two groups
37161 // when type is value-comma_group
37162 // example @import url("verylongurl") projection,tv
37165 if (insideURLFunctionInImportAtRuleNode$1(path)) {
37166 return group$6(fill$3(_parts));
37169 return group$6(indent$5(fill$3(_parts)));
37172 case "value-paren_group":
37174 var _parentNode5 = path.getParentNode();
37176 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:"))) {
37177 return concat$9([node.open ? path.call(print, "open") : "", join$6(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]);
37181 var _printed = path.map(print, "groups");
37185 for (var _i = 0; _i < _printed.length; _i++) {
37187 res.push(concat$9([",", line$3]));
37190 res.push(_printed[_i]);
37193 return group$6(indent$5(fill$3(res)));
37196 var isSCSSMapItem = isSCSSMapItemNode$1(path);
37197 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) {
37198 var node = childPath.getValue();
37199 var printed = print(childPath); // Key/Value pair in open paren already indented
37201 if (isKeyValuePairNode$1(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") {
37202 printed.contents.contents.parts[1] = group$6(printed.contents.contents.parts[1]);
37203 return group$6(dedent$2(printed));
37207 }, "groups"))])), ifBreak$2(isSCSS$1(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma$1(options) ? "," : ""), softline$3, node.close ? path.call(print, "close") : ""]), {
37208 shouldBreak: isSCSSMapItem
37214 return concat$9([node.value, insideAtRuleNode$1(path, "supports") && isMediaAndSupportsKeywords$1(node) ? " " : "", path.call(print, "group")]);
37217 case "value-paren":
37222 case "value-number":
37224 return concat$9([printCssNumber(node.value), maybeToLowerCase$1(node.unit)]);
37227 case "value-operator":
37234 if (node.isColor && node.isHex || isWideKeywords$1(node.value)) {
37235 return node.value.toLowerCase();
37241 case "value-colon":
37243 return concat$9([node.value, // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`)
37244 insideValueFunctionNode$1(path, "url") ? "" : line$3]);
37247 case "value-comma":
37249 return concat$9([node.value, " "]);
37252 case "value-string":
37254 return printString$2(node.raws.quote + node.value + node.raws.quote, options);
37257 case "value-atword":
37259 return concat$9(["@", node.value]);
37262 case "value-unicode-range":
37267 case "value-unknown":
37273 /* istanbul ignore next */
37274 throw new Error(`Unknown postcss type ${JSON.stringify(node.type)}`);
37278 function printNodeSequence(path, options, print) {
37279 var node = path.getValue();
37282 path.map(function (pathChild) {
37283 var prevNode = node.nodes[i - 1];
37285 if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") {
37286 var childNode = pathChild.getValue();
37287 parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode)));
37289 parts.push(pathChild.call(print));
37292 if (i !== node.nodes.length - 1) {
37293 if (node.nodes[i + 1].type === "css-comment" && !hasNewline$4(options.originalText, options.locStart(node.nodes[i + 1]), {
37295 }) && 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") {
37298 parts.push(hardline$7);
37300 if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), options) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml") {
37301 parts.push(hardline$7);
37308 return concat$9(parts);
37311 var STRING_REGEX$1 = /(['"])(?:(?!\1)[^\\]|\\[\s\S])*\1/g;
37312 var NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g;
37313 var STANDARD_UNIT_REGEX = /[a-zA-Z]+/g;
37314 var WORD_PART_REGEX = /[$@]?[a-zA-Z_\u0080-\uFFFF][\w\-\u0080-\uFFFF]*/g;
37315 var ADJUST_NUMBERS_REGEX = RegExp(STRING_REGEX$1.source + `|` + `(${WORD_PART_REGEX.source})?` + `(${NUMBER_REGEX.source})` + `(${STANDARD_UNIT_REGEX.source})?`, "g");
37317 function adjustStrings(value, options) {
37318 return value.replace(STRING_REGEX$1, function (match) {
37319 return printString$2(match, options);
37323 function quoteAttributeValue(value, options) {
37324 var quote = options.singleQuote ? "'" : '"';
37325 return value.includes('"') || value.includes("'") ? value : quote + value + quote;
37328 function adjustNumbers(value) {
37329 return value.replace(ADJUST_NUMBERS_REGEX, function (match, quote, wordPart, number, unit) {
37330 return !wordPart && number ? (wordPart || "") + printCssNumber(number) + maybeToLowerCase$1(unit || "") : match;
37334 function printCssNumber(rawNumber) {
37335 return printNumber$2(rawNumber) // Remove trailing `.0`.
37336 .replace(/\.0(?=$|e)/, "");
37339 var printerPostcss = {
37340 print: genericPrint$2,
37342 insertPragma: insertPragma$3,
37343 hasPrettierIgnore: hasIgnoreComment$3,
37344 massageAstNode: clean_1$1
37348 singleQuote: commonOptions.singleQuote
37351 var name$9 = "CSS";
37352 var type$7 = "markup";
37353 var tmScope$7 = "source.css";
37354 var aceMode$7 = "css";
37355 var codemirrorMode$7 = "css";
37356 var codemirrorMimeType$7 = "text/css";
37357 var color$2 = "#563d7c";
37358 var extensions$7 = [
37361 var languageId$7 = 50;
37365 tmScope: tmScope$7,
37366 aceMode: aceMode$7,
37367 codemirrorMode: codemirrorMode$7,
37368 codemirrorMimeType: codemirrorMimeType$7,
37370 extensions: extensions$7,
37371 languageId: languageId$7
37374 var CSS$1 = /*#__PURE__*/Object.freeze({
37378 tmScope: tmScope$7,
37379 aceMode: aceMode$7,
37380 codemirrorMode: codemirrorMode$7,
37381 codemirrorMimeType: codemirrorMimeType$7,
37383 extensions: extensions$7,
37384 languageId: languageId$7,
37388 var name$a = "PostCSS";
37389 var type$8 = "markup";
37390 var tmScope$8 = "source.postcss";
37391 var group$7 = "CSS";
37392 var extensions$8 = [
37395 var aceMode$8 = "text";
37396 var languageId$8 = 262764437;
37400 tmScope: tmScope$8,
37402 extensions: extensions$8,
37403 aceMode: aceMode$8,
37404 languageId: languageId$8
37407 var PostCSS$1 = /*#__PURE__*/Object.freeze({
37411 tmScope: tmScope$8,
37413 extensions: extensions$8,
37414 aceMode: aceMode$8,
37415 languageId: languageId$8,
37419 var name$b = "Less";
37420 var type$9 = "markup";
37421 var group$8 = "CSS";
37422 var extensions$9 = [
37425 var tmScope$9 = "source.css.less";
37426 var aceMode$9 = "less";
37427 var codemirrorMode$8 = "css";
37428 var codemirrorMimeType$8 = "text/css";
37429 var languageId$9 = 198;
37434 extensions: extensions$9,
37435 tmScope: tmScope$9,
37436 aceMode: aceMode$9,
37437 codemirrorMode: codemirrorMode$8,
37438 codemirrorMimeType: codemirrorMimeType$8,
37439 languageId: languageId$9
37442 var Less$1 = /*#__PURE__*/Object.freeze({
37447 extensions: extensions$9,
37448 tmScope: tmScope$9,
37449 aceMode: aceMode$9,
37450 codemirrorMode: codemirrorMode$8,
37451 codemirrorMimeType: codemirrorMimeType$8,
37452 languageId: languageId$9,
37456 var name$c = "SCSS";
37457 var type$a = "markup";
37458 var tmScope$a = "source.css.scss";
37459 var group$9 = "CSS";
37460 var aceMode$a = "scss";
37461 var codemirrorMode$9 = "css";
37462 var codemirrorMimeType$9 = "text/x-scss";
37463 var extensions$a = [
37466 var languageId$a = 329;
37470 tmScope: tmScope$a,
37472 aceMode: aceMode$a,
37473 codemirrorMode: codemirrorMode$9,
37474 codemirrorMimeType: codemirrorMimeType$9,
37475 extensions: extensions$a,
37476 languageId: languageId$a
37479 var SCSS$1 = /*#__PURE__*/Object.freeze({
37483 tmScope: tmScope$a,
37485 aceMode: aceMode$a,
37486 codemirrorMode: codemirrorMode$9,
37487 codemirrorMimeType: codemirrorMimeType$9,
37488 extensions: extensions$a,
37489 languageId: languageId$a,
37493 var require$$0$2 = getCjsExportFromNamespace(CSS$1);
37495 var require$$1$1 = getCjsExportFromNamespace(PostCSS$1);
37497 var require$$2$1 = getCjsExportFromNamespace(Less$1);
37499 var require$$3$1 = getCjsExportFromNamespace(SCSS$1);
37501 var languages$1 = [createLanguage(require$$0$2, function (data) {
37502 return Object.assign(data, {
37505 vscodeLanguageIds: ["css"]
37507 }), createLanguage(require$$1$1, function (data) {
37508 return Object.assign(data, {
37511 vscodeLanguageIds: ["postcss"],
37512 extensions: data.extensions.concat(".postcss")
37514 }), createLanguage(require$$2$1, function (data) {
37515 return Object.assign(data, {
37518 vscodeLanguageIds: ["less"]
37520 }), createLanguage(require$$3$1, function (data) {
37521 return Object.assign(data, {
37524 vscodeLanguageIds: ["scss"]
37528 postcss: printerPostcss
37530 var languageCss = {
37531 languages: languages$1,
37532 options: options$3,
37533 printers: printers$1
37536 var _require$$0$builders$4 = doc.builders,
37537 concat$a = _require$$0$builders$4.concat,
37538 join$7 = _require$$0$builders$4.join,
37539 softline$4 = _require$$0$builders$4.softline,
37540 hardline$8 = _require$$0$builders$4.hardline,
37541 line$4 = _require$$0$builders$4.line,
37542 group$a = _require$$0$builders$4.group,
37543 indent$6 = _require$$0$builders$4.indent,
37544 ifBreak$3 = _require$$0$builders$4.ifBreak; // http://w3c.github.io/html/single-page.html#void-elements
37546 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:
37547 // https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts
37549 function printChildren(path, options, print) {
37550 return concat$a(path.map(function (childPath, childIndex) {
37551 var childNode = path.getValue();
37552 var isFirstNode = childIndex === 0;
37553 var isLastNode = childIndex == path.getParentNode(0).children.length - 1;
37554 var isLastNodeInMultiNodeList = isLastNode && !isFirstNode;
37555 var isWhitespace = isWhitespaceNode(childNode);
37557 if (isWhitespace && isLastNodeInMultiNodeList) {
37558 return print(childPath, options, print);
37559 } else if (isFirstNode) {
37560 return concat$a([softline$4, print(childPath, options, print)]);
37563 return print(childPath, options, print);
37567 function print(path, options, print) {
37568 var n = path.getValue();
37569 /* istanbul ignore if*/
37580 return group$a(concat$a(path.map(print, "body").filter(function (text) {
37581 return text !== "";
37585 case "ElementNode":
37587 var tagFirstChar = n.tag[0];
37588 var isLocal = n.tag.indexOf(".") !== -1;
37589 var isGlimmerComponent = tagFirstChar.toUpperCase() === tagFirstChar || isLocal;
37590 var hasChildren = n.children.length > 0;
37591 var hasNonWhitespaceChildren = n.children.some(function (n) {
37592 return !isWhitespaceNode(n);
37594 var isVoid = isGlimmerComponent && (!hasChildren || !hasNonWhitespaceChildren) || voidTags.indexOf(n.tag) !== -1;
37595 var closeTagForNoBreak = isVoid ? concat$a([" />", softline$4]) : ">";
37596 var closeTagForBreak = isVoid ? "/>" : ">";
37598 var _getParams = function _getParams(path, print) {
37599 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"))]));
37602 var nextNode = getNextNode(path);
37603 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 : ""]);
37606 case "BlockStatement":
37608 var pp = path.getParentNode(1);
37609 var isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if";
37610 var hasElseIf = n.inverse && n.inverse.body.length === 1 && n.inverse.body[0].type === "BlockStatement" && n.inverse.body[0].path.parts[0] === "if";
37611 var indentElse = hasElseIf ? function (a) {
37616 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)])]);
37617 } else if (isElseIf) {
37618 return concat$a([concat$a(["{{else ", printPathParams(path, print), "}}"]), indent$6(concat$a([hardline$8, path.call(print, "program")]))]);
37621 var _hasNonWhitespaceChildren = n.program.body.some(function (n) {
37622 return !isWhitespaceNode(n);
37625 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)]))]);
37628 case "ElementModifierStatement":
37629 case "MustacheStatement":
37631 var _pp = path.getParentNode(1);
37633 var isConcat = _pp && _pp.type === "ConcatStatement";
37634 return group$a(concat$a([n.escaped === false ? "{{{" : "{{", printPathParams(path, print, {
37636 }), isConcat ? "" : softline$4, n.escaped === false ? "}}}" : "}}"]));
37639 case "SubExpression":
37641 var params = getParams(path, print);
37642 var printedParams = params.length > 0 ? indent$6(concat$a([line$4, group$a(join$7(line$4, params))])) : "";
37643 return group$a(concat$a(["(", printPath(path, print), printedParams, softline$4, ")"]));
37648 var isText = n.value.type === "TextNode";
37650 if (isText && n.value.loc.start.column === n.value.loc.end.column) {
37651 return concat$a([n.name]);
37654 var value = path.call(print, "value");
37655 var quotedValue = isText ? printStringLiteral(value.parts.join(), options) : value;
37656 return concat$a([n.name, "=", quotedValue]);
37659 case "ConcatStatement":
37661 return concat$a(['"', group$a(indent$6(join$7(softline$4, path.map(function (partPath) {
37662 return print(partPath);
37663 }, "parts").filter(function (a) {
37670 return concat$a([join$7(line$4, path.map(print, "pairs"))]);
37675 return concat$a([n.key, "=", path.call(print, "value")]);
37680 var maxLineBreaksToPreserve = 2;
37681 var isFirstElement = !getPreviousNode(path);
37682 var isLastElement = !getNextNode(path);
37683 var isWhitespaceOnly = !/\S/.test(n.chars);
37684 var lineBreaksCount = countNewLines(n.chars);
37685 var hasBlockParent = path.getParentNode(0).type === "Block";
37686 var hasElementParent = path.getParentNode(0).type === "ElementNode";
37687 var hasTemplateParent = path.getParentNode(0).type === "Template";
37688 var leadingLineBreaksCount = countLeadingNewLines(n.chars);
37689 var trailingLineBreaksCount = countTrailingNewLines(n.chars);
37691 if ((isFirstElement || isLastElement) && isWhitespaceOnly && (hasBlockParent || hasElementParent || hasTemplateParent)) {
37695 if (isWhitespaceOnly && lineBreaksCount) {
37696 leadingLineBreaksCount = Math.min(lineBreaksCount, maxLineBreaksToPreserve);
37697 trailingLineBreaksCount = 0;
37699 if (isNextNodeOfType(path, "ElementNode") || isNextNodeOfType(path, "BlockStatement")) {
37700 trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1);
37703 if (isPreviousNodeOfSomeType(path, ["ElementNode"]) || isPreviousNodeOfSomeType(path, ["BlockStatement"])) {
37704 leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1);
37708 var leadingSpace = "";
37709 var trailingSpace = ""; // preserve a space inside of an attribute node where whitespace present,
37710 // when next to mustache statement.
37712 var inAttrNode = path.stack.indexOf("attributes") >= 0;
37715 var parentNode = path.getParentNode(0);
37717 var _isConcat = parentNode.type === "ConcatStatement";
37720 var parts = parentNode.parts;
37721 var partIndex = parts.indexOf(n);
37723 if (partIndex > 0) {
37724 var partType = parts[partIndex - 1].type;
37725 var isMustache = partType === "MustacheStatement";
37728 leadingSpace = " ";
37732 if (partIndex < parts.length - 1) {
37733 var _partType = parts[partIndex + 1].type;
37735 var _isMustache = _partType === "MustacheStatement";
37738 trailingSpace = " ";
37743 if (trailingLineBreaksCount === 0 && isNextNodeOfType(path, "MustacheStatement")) {
37744 trailingSpace = " ";
37747 if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType(path, ["MustacheStatement"])) {
37748 leadingSpace = " ";
37751 if (isFirstElement) {
37752 leadingLineBreaksCount = 0;
37756 if (isLastElement) {
37757 trailingLineBreaksCount = 0;
37758 trailingSpace = "";
37762 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));
37765 case "MustacheCommentStatement":
37767 var dashes = n.value.indexOf("}}") > -1 ? "--" : "";
37768 return concat$a(["{{!", dashes, n.value, dashes, "}}"]);
37771 case "PathExpression":
37776 case "BooleanLiteral":
37778 return String(n.value);
37781 case "CommentStatement":
37783 return concat$a(["<!--", n.value, "-->"]);
37786 case "StringLiteral":
37788 return printStringLiteral(n.value, options);
37791 case "NumberLiteral":
37793 return String(n.value);
37796 case "UndefinedLiteral":
37798 return "undefined";
37801 case "NullLiteral":
37806 /* istanbul ignore next */
37809 throw new Error("unknown glimmer type: " + JSON.stringify(n.type));
37813 * Prints a string literal with the correct surrounding quotes based on
37814 * `options.singleQuote` and the number of escaped quotes contained in
37815 * the string literal. This function is the glimmer equivalent of `printString`
37816 * in `common/util`, but has differences because of the way escaped characters
37817 * are treated in hbs string literals.
37818 * @param {string} stringLiteral - the string literal value
37819 * @param {object} options - the prettier options object
37823 function printStringLiteral(stringLiteral, options) {
37832 var preferred = options.singleQuote ? single : double;
37833 var alternate = preferred === single ? double : single;
37834 var shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for
37835 // enclosing the string, we might want to enclose with the alternate quote
37836 // instead, to minimize the number of escaped quotes.
37838 if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) {
37839 var numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length;
37840 var numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length;
37841 shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes;
37844 var enclosingQuote = shouldUseAlternateQuote ? alternate : preferred;
37845 var escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, `\\${enclosingQuote.quote}`);
37846 return `${enclosingQuote.quote}${escapedStringLiteral}${enclosingQuote.quote}`;
37849 function printPath(path, print) {
37850 return path.call(print, "path");
37853 function getParams(path, print) {
37854 var node = path.getValue();
37857 if (node.params.length > 0) {
37858 parts = parts.concat(path.map(print, "params"));
37861 if (node.hash && node.hash.pairs.length > 0) {
37862 parts.push(path.call(print, "hash"));
37868 function printPathParams(path, print, options) {
37870 options = Object.assign({
37873 parts.push(printPath(path, print));
37874 parts = parts.concat(getParams(path, print));
37876 if (!options.group) {
37877 return indent$6(join$7(line$4, parts));
37880 return indent$6(group$a(join$7(line$4, parts)));
37883 function printBlockParams(path) {
37884 var block = path.getValue();
37886 if (!block.program || !block.program.blockParams.length) {
37890 return concat$a([" as |", block.program.blockParams.join(" "), "|"]);
37893 function printOpenBlock(path, print) {
37894 return group$a(concat$a(["{{#", printPathParams(path, print), printBlockParams(path), softline$4, "}}"]));
37897 function printCloseBlock(path, print) {
37898 return concat$a(["{{/", path.call(print, "path"), "}}"]);
37901 function isWhitespaceNode(node) {
37902 return node.type === "TextNode" && !/\S/.test(node.chars);
37905 function getPreviousNode(path) {
37906 var node = path.getValue();
37907 var parentNode = path.getParentNode(0);
37908 var children = parentNode.children || parentNode.body;
37911 var nodeIndex = children.indexOf(node);
37913 if (nodeIndex > 0) {
37914 var previousNode = children[nodeIndex - 1];
37915 return previousNode;
37920 function getNextNode(path) {
37921 var node = path.getValue();
37922 var parentNode = path.getParentNode(0);
37923 var children = parentNode.children || parentNode.body;
37926 var nodeIndex = children.indexOf(node);
37928 if (nodeIndex < children.length) {
37929 var nextNode = children[nodeIndex + 1];
37935 function isPreviousNodeOfSomeType(path, types) {
37936 var previousNode = getPreviousNode(path);
37938 if (previousNode) {
37939 return types.some(function (type) {
37940 return previousNode.type === type;
37947 function isNextNodeOfType(path, type) {
37948 var nextNode = getNextNode(path);
37949 return nextNode && nextNode.type === type;
37952 function clean$3(ast, newObj) {
37954 delete newObj.selfClosing; // (Glimmer/HTML) ignore TextNode whitespace
37956 if (ast.type === "TextNode") {
37957 if (ast.chars.replace(/\s+/, "") === "") {
37961 newObj.chars = ast.chars.replace(/^\s+/, "").replace(/\s+$/, "");
37965 function countNewLines(string) {
37966 /* istanbul ignore next */
37967 string = typeof string === "string" ? string : "";
37968 return string.split("\n").length - 1;
37971 function countLeadingNewLines(string) {
37972 /* istanbul ignore next */
37973 string = typeof string === "string" ? string : "";
37974 var newLines = (string.match(/^([^\S\r\n]*[\r\n])+/g) || [])[0] || "";
37975 return countNewLines(newLines);
37978 function countTrailingNewLines(string) {
37979 /* istanbul ignore next */
37980 string = typeof string === "string" ? string : "";
37981 var newLines = (string.match(/([\r\n][^\S\r\n]*)+$/g) || [])[0] || "";
37982 return countNewLines(newLines);
37985 function generateHardlines() {
37986 var number = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
37987 var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
37988 return new Array(Math.min(number, max)).fill(hardline$8);
37991 var printerGlimmer = {
37993 massageAstNode: clean$3
37996 var name$d = "Handlebars";
37997 var type$b = "markup";
37998 var group$b = "HTML";
38003 var extensions$b = [
38007 var tmScope$b = "text.html.handlebars";
38008 var aceMode$b = "handlebars";
38009 var languageId$b = 155;
38014 aliases: aliases$3,
38015 extensions: extensions$b,
38016 tmScope: tmScope$b,
38017 aceMode: aceMode$b,
38018 languageId: languageId$b
38021 var Handlebars$1 = /*#__PURE__*/Object.freeze({
38026 aliases: aliases$3,
38027 extensions: extensions$b,
38028 tmScope: tmScope$b,
38029 aceMode: aceMode$b,
38030 languageId: languageId$b,
38031 'default': Handlebars
38034 var require$$0$3 = getCjsExportFromNamespace(Handlebars$1);
38036 var languages$2 = [createLanguage(require$$0$3, function (data) {
38037 return Object.assign(data, {
38040 parsers: ["glimmer"],
38041 vscodeLanguageIds: ["handlebars"]
38045 glimmer: printerGlimmer
38047 var languageHandlebars = {
38048 languages: languages$2,
38049 printers: printers$2
38052 function hasPragma$2(text) {
38053 return /^\s*#[^\n\S]*@(format|prettier)\s*(\n|$)/.test(text);
38056 function insertPragma$4(text) {
38057 return "# @format\n\n" + text;
38061 hasPragma: hasPragma$2,
38062 insertPragma: insertPragma$4
38065 var _require$$0$builders$5 = doc.builders,
38066 concat$b = _require$$0$builders$5.concat,
38067 join$8 = _require$$0$builders$5.join,
38068 hardline$9 = _require$$0$builders$5.hardline,
38069 line$5 = _require$$0$builders$5.line,
38070 softline$5 = _require$$0$builders$5.softline,
38071 group$c = _require$$0$builders$5.group,
38072 indent$7 = _require$$0$builders$5.indent,
38073 ifBreak$4 = _require$$0$builders$5.ifBreak;
38074 var hasIgnoreComment$4 = util.hasIgnoreComment;
38075 var isNextLineEmpty$4 = utilShared.isNextLineEmpty;
38076 var insertPragma$5 = pragma$2.insertPragma;
38078 function genericPrint$3(path, options, print) {
38079 var n = path.getValue();
38085 if (typeof n === "string") {
38093 path.map(function (pathChild, index) {
38094 parts.push(concat$b([pathChild.call(print)]));
38096 if (index !== n.definitions.length - 1) {
38097 parts.push(hardline$9);
38099 if (isNextLineEmpty$4(options.originalText, pathChild.getValue(), options)) {
38100 parts.push(hardline$9);
38104 return concat$b([concat$b(parts), hardline$9]);
38107 case "OperationDefinition":
38109 var hasOperation = options.originalText[options.locStart(n)] !== "{";
38110 var hasName = !!n.name;
38111 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")]);
38114 case "FragmentDefinition":
38116 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")]);
38119 case "SelectionSet":
38121 return concat$b(["{", indent$7(concat$b([hardline$9, join$8(hardline$9, path.call(function (selectionsPath) {
38122 return printSequence(selectionsPath, options, print);
38123 }, "selections"))])), hardline$9, "}"]);
38128 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) {
38129 return printSequence(argsPath, options, print);
38130 }, "arguments"))])), softline$5, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")]));
38138 case "StringValue":
38141 return concat$b(['"""', hardline$9, join$8(hardline$9, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$9, '"""']);
38144 return concat$b(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']);
38154 case "BooleanValue":
38156 return n.value ? "true" : "false";
38166 return concat$b(["$", path.call(print, "name")]);
38171 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, "]"]));
38174 case "ObjectValue":
38176 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 ? " " : ""), "}"]));
38179 case "ObjectField":
38182 return concat$b([path.call(print, "name"), ": ", path.call(print, "value")]);
38187 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) {
38188 return printSequence(argsPath, options, print);
38189 }, "arguments"))])), softline$5, ")"])) : ""]);
38194 return path.call(print, "name");
38197 case "VariableDefinition":
38199 return concat$b([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$b([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
38202 case "TypeExtensionDefinition":
38204 return concat$b(["extend ", path.call(print, "definition")]);
38207 case "ObjectTypeExtension":
38208 case "ObjectTypeDefinition":
38210 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) {
38211 return printSequence(fieldsPath, options, print);
38212 }, "fields"))])), hardline$9, "}"]) : ""]);
38215 case "FieldDefinition":
38217 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) {
38218 return printSequence(argsPath, options, print);
38219 }, "arguments"))])), softline$5, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]);
38222 case "DirectiveDefinition":
38224 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) {
38225 return printSequence(argsPath, options, print);
38226 }, "arguments"))])), softline$5, ")"])) : "", concat$b([" on ", join$8(" | ", path.map(print, "locations"))])]);
38229 case "EnumTypeExtension":
38230 case "EnumTypeDefinition":
38232 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) {
38233 return printSequence(valuesPath, options, print);
38234 }, "values"))])), hardline$9, "}"]) : ""]);
38237 case "EnumValueDefinition":
38239 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", path.call(print, "name"), printDirectives(path, print, n)]);
38242 case "InputValueDefinition":
38244 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)]);
38247 case "InputObjectTypeExtension":
38248 case "InputObjectTypeDefinition":
38250 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) {
38251 return printSequence(fieldsPath, options, print);
38252 }, "fields"))])), hardline$9, "}"]) : ""]);
38255 case "SchemaDefinition":
38257 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) {
38258 return printSequence(opsPath, options, print);
38259 }, "operationTypes"))])) : "", hardline$9, "}"]);
38262 case "OperationTypeDefinition":
38264 return concat$b([path.call(print, "operation"), ": ", path.call(print, "type")]);
38267 case "InterfaceTypeExtension":
38268 case "InterfaceTypeDefinition":
38270 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) {
38271 return printSequence(fieldsPath, options, print);
38272 }, "fields"))])), hardline$9, "}"]) : ""]);
38275 case "FragmentSpread":
38277 return concat$b(["...", path.call(print, "name"), printDirectives(path, print, n)]);
38280 case "InlineFragment":
38282 return concat$b(["...", n.typeCondition ? concat$b([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
38285 case "UnionTypeExtension":
38286 case "UnionTypeDefinition":
38288 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"))]))]) : ""]))]));
38291 case "ScalarTypeExtension":
38292 case "ScalarTypeDefinition":
38294 return concat$b([path.call(print, "description"), n.description ? hardline$9 : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]);
38297 case "NonNullType":
38299 return concat$b([path.call(print, "type"), "!"]);
38304 return concat$b(["[", path.call(print, "type"), "]"]);
38308 /* istanbul ignore next */
38309 throw new Error("unknown graphql type: " + JSON.stringify(n.kind));
38313 function printDirectives(path, print, n) {
38314 if (n.directives.length === 0) {
38318 return concat$b([" ", group$c(indent$7(concat$b([softline$5, join$8(concat$b([ifBreak$4("", " "), softline$5]), path.map(print, "directives"))])))]);
38321 function printSequence(sequencePath, options, print) {
38322 var count = sequencePath.getValue().length;
38323 return sequencePath.map(function (path, i) {
38324 var printed = print(path);
38326 if (isNextLineEmpty$4(options.originalText, path.getValue(), options) && i < count - 1) {
38327 return concat$b([printed, hardline$9]);
38334 function canAttachComment$1(node) {
38335 return node.kind && node.kind !== "Comment";
38338 function printComment$2(commentPath) {
38339 var comment = commentPath.getValue();
38341 if (comment.kind === "Comment") {
38342 return "#" + comment.value.trimRight();
38345 throw new Error("Not a comment: " + JSON.stringify(comment));
38348 function determineInterfaceSeparator(originalSource) {
38349 var start = originalSource.indexOf("implements");
38351 if (start === -1) {
38352 throw new Error("Must implement interfaces: " + originalSource);
38355 var end = originalSource.indexOf("{");
38358 end = originalSource.length;
38361 return originalSource.substr(start, end).includes("&") ? " & " : ", ";
38364 function clean$4(node, newNode
38367 delete newNode.loc;
38368 delete newNode.comments;
38371 var printerGraphql = {
38372 print: genericPrint$3,
38373 massageAstNode: clean$4,
38374 hasPrettierIgnore: hasIgnoreComment$4,
38375 insertPragma: insertPragma$5,
38376 printComment: printComment$2,
38377 canAttachComment: canAttachComment$1
38381 bracketSpacing: commonOptions.bracketSpacing
38384 var name$e = "GraphQL";
38385 var type$c = "data";
38386 var extensions$c = [
38391 var tmScope$c = "source.graphql";
38392 var aceMode$c = "text";
38393 var languageId$c = 139;
38397 extensions: extensions$c,
38398 tmScope: tmScope$c,
38399 aceMode: aceMode$c,
38400 languageId: languageId$c
38403 var GraphQL$1 = /*#__PURE__*/Object.freeze({
38407 extensions: extensions$c,
38408 tmScope: tmScope$c,
38409 aceMode: aceMode$c,
38410 languageId: languageId$c,
38414 var require$$0$4 = getCjsExportFromNamespace(GraphQL$1);
38416 var languages$3 = [createLanguage(require$$0$4, function (data) {
38417 return Object.assign(data, {
38419 parsers: ["graphql"],
38420 vscodeLanguageIds: ["graphql"]
38424 graphql: printerGraphql
38426 var languageGraphql = {
38427 languages: languages$3,
38428 options: options$4,
38429 printers: printers$3
38433 "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]",
38434 "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]",
38435 "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]"
38438 var cjkPattern = json.cjkPattern,
38439 kPattern = json.kPattern,
38440 punctuationPattern = json.punctuationPattern;
38441 var getLast$3 = util.getLast;
38442 var INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"];
38443 var INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]);
38444 var kRegex = new RegExp(kPattern);
38445 var punctuationRegex = new RegExp(punctuationPattern);
38447 * split text into whitespaces and words
38448 * @param {string} text
38449 * @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>}
38452 function splitText(text, options) {
38453 var KIND_NON_CJK = "non-cjk";
38454 var KIND_CJ_LETTER = "cj-letter";
38455 var KIND_K_LETTER = "k-letter";
38456 var KIND_CJK_PUNCTUATION = "cjk-punctuation";
38458 (options.proseWrap === "preserve" ? text : text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")).split(/([ \t\n]+)/).forEach(function (token, index, tokens) {
38460 if (index % 2 === 1) {
38462 type: "whitespace",
38463 value: /\n/.test(token) ? "\n" : " "
38466 } // word separated by whitespace
38469 if ((index === 0 || index === tokens.length - 1) && token === "") {
38473 token.split(new RegExp(`(${cjkPattern})`)).forEach(function (innerToken, innerIndex, innerTokens) {
38474 if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") {
38479 if (innerIndex % 2 === 0) {
38480 if (innerToken !== "") {
38484 kind: KIND_NON_CJK,
38485 hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
38486 hasTrailingPunctuation: punctuationRegex.test(getLast$3(innerToken))
38494 appendNode(punctuationRegex.test(innerToken) ? {
38497 kind: KIND_CJK_PUNCTUATION,
38498 hasLeadingPunctuation: true,
38499 hasTrailingPunctuation: true
38503 kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER,
38504 hasLeadingPunctuation: false,
38505 hasTrailingPunctuation: false
38511 function appendNode(node) {
38512 var lastNode = getLast$3(nodes);
38514 if (lastNode && lastNode.type === "word") {
38515 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) {
38517 type: "whitespace",
38520 } else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace
38521 ![lastNode.value, node.value].some(function (value) {
38522 return /\u3000/.test(value);
38525 type: "whitespace",
38533 function isBetween(kind1, kind2) {
38534 return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1;
38539 function getOrderedListItemInfo(orderListItem, originalText) {
38540 var _originalText$slice$m = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/),
38541 _originalText$slice$m2 = _slicedToArray(_originalText$slice$m, 4),
38542 numberText = _originalText$slice$m2[1],
38543 marker = _originalText$slice$m2[2],
38544 leadingSpaces = _originalText$slice$m2[3];
38551 } // workaround for https://github.com/remarkjs/remark/issues/351
38552 // leading and trailing newlines are stripped by remark
38555 function getFencedCodeBlockValue(node, originalText) {
38556 var text = originalText.slice(node.position.start.offset, node.position.end.offset);
38557 var leadingSpaceCount = text.match(/^\s*/)[0].length;
38558 var replaceRegex = new RegExp(`^\\s{0,${leadingSpaceCount}}`);
38559 var lineContents = text.split("\n");
38560 var markerStyle = text[leadingSpaceCount]; // ` or ~
38562 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
38563 // https://spec.commonmark.org/0.28/#example-93: The closing code fence must be at least as long as the opening fence
38565 var hasEndMarker = new RegExp(`^\\s{0,3}${marker}`).test(lineContents[lineContents.length - 1].slice(getIndent(lineContents.length - 1)));
38566 return lineContents.slice(1, hasEndMarker ? -1 : undefined).map(function (x, i) {
38567 return x.slice(getIndent(i + 1)).replace(replaceRegex, "");
38570 function getIndent(lineIndex) {
38571 return node.position.indent[lineIndex - 1] - 1;
38575 function mapAst(ast, handler) {
38576 return function preorder(node, index, parentStack) {
38577 parentStack = parentStack || [];
38578 var newNode = handler(node, index, parentStack);
38580 if (Array.isArray(newNode)) {
38584 newNode = Object.assign({}, newNode);
38586 if (newNode.children) {
38587 newNode.children = newNode.children.reduce(function (nodes, child, index) {
38588 var newNodes = preorder(child, index, [newNode].concat(parentStack));
38590 if (!Array.isArray(newNodes)) {
38591 newNodes = [newNodes];
38594 nodes.push.apply(nodes, newNodes);
38600 }(ast, null, null);
38606 punctuationPattern,
38607 getFencedCodeBlockValue,
38608 getOrderedListItemInfo,
38610 INLINE_NODE_WRAPPER_TYPES
38613 var _require$$0$builders$6 = doc.builders,
38614 hardline$a = _require$$0$builders$6.hardline,
38615 literalline$4 = _require$$0$builders$6.literalline,
38616 concat$c = _require$$0$builders$6.concat,
38617 markAsRoot$2 = _require$$0$builders$6.markAsRoot,
38618 mapDoc$5 = doc.utils.mapDoc;
38619 var getFencedCodeBlockValue$1 = utils$4.getFencedCodeBlockValue;
38621 function embed$2(path, print, textToDoc, options) {
38622 var node = path.getValue();
38624 if (node.type === "code" && node.lang !== null) {
38625 // only look for the first string so as to support [markdown-preview-enhanced](https://shd101wyy.github.io/markdown-preview-enhanced/#/code-chunk)
38626 var langMatch = node.lang.match(/^[A-Za-z0-9_-]+/);
38627 var lang = langMatch ? langMatch[0] : "";
38628 var parser = getParserName(lang);
38631 var styleUnit = options.__inJsTemplate ? "~" : "`";
38632 var style = styleUnit.repeat(Math.max(3, util.getMaxContinuousCount(node.value, styleUnit) + 1));
38633 var doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), {
38636 return markAsRoot$2(concat$c([style, node.lang, hardline$a, replaceNewlinesWithLiterallines(doc), style]));
38640 if (node.type === "yaml") {
38641 return markAsRoot$2(concat$c(["---", hardline$a, node.value && node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
38643 })) : "", "---"]));
38647 switch (node.type) {
38648 case "importExport":
38649 return textToDoc(node.value, {
38654 return textToDoc(node.value, {
38655 parser: "__js_expression"
38661 function getParserName(lang) {
38662 var supportInfo = support.getSupportInfo(null, {
38663 plugins: options.plugins
38665 var language = supportInfo.languages.find(function (language) {
38666 return language.name.toLowerCase() === lang || language.aliases && language.aliases.indexOf(lang) !== -1 || language.extensions && language.extensions.find(function (ext) {
38667 return ext.substring(1) === lang;
38672 return language.parsers[0];
38678 function replaceNewlinesWithLiterallines(doc) {
38679 return mapDoc$5(doc, function (currentDoc) {
38680 return typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$c(currentDoc.split(/(\n)/g).map(function (v, i) {
38681 return i % 2 === 0 ? v : literalline$4;
38687 var embed_1$2 = embed$2;
38689 var pragmas = ["format", "prettier"];
38691 function startWithPragma(text) {
38692 var pragma = `@(${pragmas.join("|")})`;
38693 var regex = new RegExp([`<!--\\s*${pragma}\\s*-->`, `<!--.*\r?\n[\\s\\S]*(^|\n)[^\\S\n]*${pragma}[^\\S\n]*($|\n)[\\s\\S]*\n.*-->`].join("|"), "m");
38694 var matched = text.match(regex);
38695 return matched && matched.index === 0;
38700 hasPragma: function hasPragma(text) {
38701 return startWithPragma(frontMatter(text).content.trimLeft());
38703 insertPragma: function insertPragma(text) {
38704 var extracted = frontMatter(text);
38705 var pragma = `<!-- @${pragmas[0]} -->`;
38706 return extracted.frontMatter ? `${extracted.frontMatter.raw}\n\n${pragma}\n\n${extracted.content}` : `${pragma}\n\n${extracted.content}`;
38710 var getOrderedListItemInfo$1 = utils$4.getOrderedListItemInfo,
38711 mapAst$1 = utils$4.mapAst,
38712 splitText$1 = utils$4.splitText; // 0x0 ~ 0x10ffff
38713 // eslint-disable-next-line no-control-regex
38715 var isSingleCharRegex = /^([\u0000-\uffff]|[\ud800-\udbff][\udc00-\udfff])$/;
38717 function preprocess$1(ast, options) {
38718 ast = restoreUnescapedCharacter(ast, options);
38719 ast = mergeContinuousTexts(ast);
38720 ast = transformInlineCode(ast);
38721 ast = transformIndentedCodeblockAndMarkItsParentList(ast, options);
38722 ast = markAlignedList(ast, options);
38723 ast = splitTextIntoSentences(ast, options);
38724 ast = transformImportExport(ast);
38725 ast = mergeContinuousImportExport(ast);
38729 function transformImportExport(ast) {
38730 return mapAst$1(ast, function (node) {
38731 if (node.type !== "import" && node.type !== "export") {
38735 return Object.assign({}, node, {
38736 type: "importExport"
38741 function transformInlineCode(ast) {
38742 return mapAst$1(ast, function (node) {
38743 if (node.type !== "inlineCode") {
38747 return Object.assign({}, node, {
38748 value: node.value.replace(/\s+/g, " ")
38753 function restoreUnescapedCharacter(ast, options) {
38754 return mapAst$1(ast, function (node) {
38755 return node.type !== "text" ? node : Object.assign({}, node, {
38756 value: node.value !== "*" && node.value !== "_" && node.value !== "$" && // handle these cases in printer
38757 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
38762 function mergeContinuousImportExport(ast) {
38763 return mergeChildren(ast, function (prevNode, node) {
38764 return prevNode.type === "importExport" && node.type === "importExport";
38765 }, function (prevNode, node) {
38767 type: "importExport",
38768 value: prevNode.value + "\n\n" + node.value,
38770 start: prevNode.position.start,
38771 end: node.position.end
38777 function mergeChildren(ast, shouldMerge, mergeNode) {
38778 return mapAst$1(ast, function (node) {
38779 if (!node.children) {
38783 var children = node.children.reduce(function (current, child) {
38784 var lastChild = current[current.length - 1];
38786 if (lastChild && shouldMerge(lastChild, child)) {
38787 current.splice(-1, 1, mergeNode(lastChild, child));
38789 current.push(child);
38794 return Object.assign({}, node, {
38800 function mergeContinuousTexts(ast) {
38801 return mergeChildren(ast, function (prevNode, node) {
38802 return prevNode.type === "text" && node.type === "text";
38803 }, function (prevNode, node) {
38806 value: prevNode.value + node.value,
38808 start: prevNode.position.start,
38809 end: node.position.end
38815 function splitTextIntoSentences(ast, options) {
38816 return mapAst$1(ast, function (node, index, _ref) {
38817 var _ref2 = _slicedToArray(_ref, 1),
38818 parentNode = _ref2[0];
38820 if (node.type !== "text") {
38824 var value = node.value;
38826 if (parentNode.type === "paragraph") {
38828 value = value.trimLeft();
38831 if (index === parentNode.children.length - 1) {
38832 value = value.trimRight();
38838 position: node.position,
38839 children: splitText$1(value, options)
38844 function transformIndentedCodeblockAndMarkItsParentList(ast, options) {
38845 return mapAst$1(ast, function (node, index, parentStack) {
38846 if (node.type === "code") {
38847 // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it
38848 var isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset));
38849 node.isIndented = isIndented;
38852 for (var i = 0; i < parentStack.length; i++) {
38853 var parent = parentStack[i]; // no need to check checked items
38855 if (parent.hasIndentedCodeblock) {
38859 if (parent.type === "list") {
38860 parent.hasIndentedCodeblock = true;
38870 function markAlignedList(ast, options) {
38871 return mapAst$1(ast, function (node, index, parentStack) {
38872 if (node.type === "list" && node.children.length !== 0) {
38873 // if one of its parents is not aligned, it's not possible to be aligned in sub-lists
38874 for (var i = 0; i < parentStack.length; i++) {
38875 var parent = parentStack[i];
38877 if (parent.type === "list" && !parent.isAligned) {
38878 node.isAligned = false;
38883 node.isAligned = isAligned(node);
38889 function getListItemStart(listItem) {
38890 return listItem.children.length === 0 ? -1 : listItem.children[0].position.start.column - 1;
38893 function isAligned(list) {
38894 if (!list.ordered) {
38902 var _list$children = _slicedToArray(list.children, 2),
38903 firstItem = _list$children[0],
38904 secondItem = _list$children[1];
38906 var firstInfo = getOrderedListItemInfo$1(firstItem, options.originalText);
38908 if (firstInfo.leadingSpaces.length > 1) {
38918 var firstStart = getListItemStart(firstItem);
38920 if (firstStart === -1) {
38930 if (list.children.length === 1) {
38940 return firstStart % options.tabWidth === 0;
38943 var secondStart = getListItemStart(secondItem);
38945 if (firstStart !== secondStart) {
38956 if (firstStart % options.tabWidth === 0) {
38976 var secondInfo = getOrderedListItemInfo$1(secondItem, options.originalText);
38977 return secondInfo.leadingSpaces.length > 1;
38981 var preprocess_1$1 = preprocess$1;
38983 var _require$$0$builders$7 = doc.builders,
38984 breakParent$3 = _require$$0$builders$7.breakParent,
38985 concat$d = _require$$0$builders$7.concat,
38986 join$9 = _require$$0$builders$7.join,
38987 line$6 = _require$$0$builders$7.line,
38988 literalline$5 = _require$$0$builders$7.literalline,
38989 markAsRoot$3 = _require$$0$builders$7.markAsRoot,
38990 hardline$b = _require$$0$builders$7.hardline,
38991 softline$6 = _require$$0$builders$7.softline,
38992 ifBreak$5 = _require$$0$builders$7.ifBreak,
38993 fill$4 = _require$$0$builders$7.fill,
38994 align$2 = _require$$0$builders$7.align,
38995 indent$8 = _require$$0$builders$7.indent,
38996 group$d = _require$$0$builders$7.group,
38997 mapDoc$6 = doc.utils.mapDoc,
38998 printDocToString$3 = doc.printer.printDocToString;
38999 var getFencedCodeBlockValue$2 = utils$4.getFencedCodeBlockValue,
39000 getOrderedListItemInfo$2 = utils$4.getOrderedListItemInfo,
39001 splitText$2 = utils$4.splitText,
39002 punctuationPattern$1 = utils$4.punctuationPattern,
39003 INLINE_NODE_TYPES$1 = utils$4.INLINE_NODE_TYPES,
39004 INLINE_NODE_WRAPPER_TYPES$1 = utils$4.INLINE_NODE_WRAPPER_TYPES;
39005 var replaceEndOfLineWith$1 = util.replaceEndOfLineWith;
39006 var TRAILING_HARDLINE_NODES = ["importExport"];
39007 var SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"];
39008 var SIBLING_NODE_TYPES = ["listItem", "definition", "footnoteDefinition", "jsx"];
39010 function genericPrint$4(path, options, print) {
39011 var node = path.getValue();
39013 if (shouldRemainTheSameContent(path)) {
39014 return concat$d(splitText$2(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(function (node) {
39015 return node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options);
39019 switch (node.type) {
39021 if (node.children.length === 0) {
39025 return concat$d([normalizeDoc(printRoot(path, options, print)), TRAILING_HARDLINE_NODES.indexOf(getLastDescendantNode(node).type) === -1 ? hardline$b : ""]);
39028 return printChildren$1(path, options, print, {
39029 postprocessor: fill$4
39033 return printChildren$1(path, options, print);
39036 return node.value.replace(/[*$]/g, "\\$&") // escape all `*` and `$` (math)
39037 .replace(new RegExp([`(^|${punctuationPattern$1})(_+)`, `(_+)(${punctuationPattern$1}|$)`].join("|"), "g"), function (_, text1, underscore1, underscore2, text2) {
39038 return (underscore1 ? `${text1}${underscore1}` : `${underscore2}${text2}`).replace(/_/g, "\\_");
39040 // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
39044 var parentNode = path.getParentNode();
39045 var index = parentNode.children.indexOf(node);
39046 var nextNode = parentNode.children[index + 1];
39047 var proseWrap = // leading char that may cause different syntax
39048 nextNode && /^>|^([-+*]|#{1,6}|[0-9]+[.)])$/.test(nextNode.value) ? "never" : options.proseWrap;
39049 return printLine(path, node.value, {
39056 var _parentNode = path.getParentNode();
39058 var _index = _parentNode.children.indexOf(node);
39060 var prevNode = _parentNode.children[_index - 1];
39061 var _nextNode = _parentNode.children[_index + 1];
39062 var hasPrevOrNextWord = // `1*2*3` is considered emphasis but `1_2_3` is not
39063 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;
39064 var style = hasPrevOrNextWord || getAncestorNode$2(path, "emphasis") ? "*" : "_";
39065 return concat$d([style, printChildren$1(path, options, print), style]);
39069 return concat$d(["**", printChildren$1(path, options, print), "**"]);
39072 return concat$d(["~~", printChildren$1(path, options, print), "~~"]);
39076 var backtickCount = util.getMinNotPresentContinuousCount(node.value, "`");
39078 var _style = "`".repeat(backtickCount || 1);
39080 var gap = backtickCount ? " " : "";
39081 return concat$d([_style, gap, node.value, gap, _style]);
39085 switch (options.originalText[node.position.start.offset]) {
39088 var mailto = "mailto:";
39089 var url = // <hello@example.com> is parsed as { url: "mailto:hello@example.com" }
39090 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;
39091 return concat$d(["<", url, ">"]);
39095 return concat$d(["[", printChildren$1(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
39098 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
39102 return concat$d(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
39105 return concat$d(["> ", align$2("> ", printChildren$1(path, options, print))]);
39108 return concat$d(["#".repeat(node.depth) + " ", printChildren$1(path, options, print)]);
39112 if (node.isIndented) {
39113 // indented code block
39114 var alignment = " ".repeat(4);
39115 return align$2(alignment, concat$d([alignment, concat$d(replaceEndOfLineWith$1(node.value, hardline$b))]));
39116 } // fenced code block
39119 var styleUnit = options.__inJsTemplate ? "~" : "`";
39121 var _style2 = styleUnit.repeat(Math.max(3, util.getMaxContinuousCount(node.value, styleUnit) + 1));
39123 return concat$d([_style2, node.lang || "", hardline$b, concat$d(replaceEndOfLineWith$1(getFencedCodeBlockValue$2(node, options.originalText), hardline$b)), hardline$b, _style2]);
39128 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
39132 var _parentNode2 = path.getParentNode();
39134 var value = _parentNode2.type === "root" && util.getLast(_parentNode2.children) === node ? node.value.trimRight() : node.value;
39135 var isHtmlComment = /^<!--[\s\S]*-->$/.test(value);
39136 return concat$d(replaceEndOfLineWith$1(value, isHtmlComment ? hardline$b : markAsRoot$3(literalline$5)));
39141 var nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode());
39142 var isGitDiffFriendlyOrderedList = node.ordered && node.children.length > 1 && +getOrderedListItemInfo$2(node.children[1], options.originalText).numberText === 1;
39143 return printChildren$1(path, options, print, {
39144 processor: function processor(childPath, index) {
39145 var prefix = getPrefix();
39146 return concat$d([prefix, align$2(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]);
39148 function getPrefix() {
39149 var rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* ";
39150 return node.isAligned ||
39151 /* workaround for https://github.com/remarkjs/remark/issues/315 */
39152 node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix;
39158 case "thematicBreak":
39160 var counter = getAncestorCounter$1(path, "list");
39162 if (counter === -1) {
39166 var _nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1));
39168 return _nthSiblingIndex % 2 === 0 ? "***" : "---";
39171 case "linkReference":
39172 return concat$d(["[", printChildren$1(path, options, print), "]", node.referenceType === "full" ? concat$d(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]);
39174 case "imageReference":
39175 switch (node.referenceType) {
39177 return concat$d(["![", node.alt || "", "][", node.identifier, "]"]);
39180 return concat$d(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]);
39185 var lineOrSpace = options.proseWrap === "always" ? line$6 : " ";
39186 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)])]))]));
39190 return concat$d(["[^", printChildren$1(path, options, print), "]"]);
39192 case "footnoteReference":
39193 return concat$d(["[^", node.identifier, "]"]);
39195 case "footnoteDefinition":
39197 var _nextNode2 = path.getParentNode().children[path.getName() + 1];
39198 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);
39199 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, {
39200 processor: function processor(childPath, index) {
39201 return index === 0 ? group$d(concat$d([softline$6, softline$6, childPath.call(print)])) : childPath.call(print);
39203 })), _nextNode2 && _nextNode2.type === "footnoteDefinition" ? softline$6 : ""]))]);
39207 return printTable(path, options, print);
39210 return printChildren$1(path, options, print);
39213 return /\s/.test(options.originalText[node.position.start.offset]) ? concat$d([" ", markAsRoot$3(literalline$5)]) : concat$d(["\\", hardline$b]);
39216 return concat$d(replaceEndOfLineWith$1(node.value, hardline$b));
39219 case "importExport":
39222 // fallback to the original text if multiparser failed
39225 return concat$d(["$$", hardline$b, node.value ? concat$d([concat$d(replaceEndOfLineWith$1(node.value, hardline$b)), hardline$b]) : "", "$$"]);
39229 // remark-math trims content but we don't want to remove whitespaces
39230 // since it's very possible that it's recognized as math accidentally
39231 return options.originalText.slice(options.locStart(node), options.locEnd(node));
39234 case "tableRow": // handled in "table"
39236 case "listItem": // handled in "list"
39239 throw new Error(`Unknown markdown type ${JSON.stringify(node.type)}`);
39243 function printListItem(path, options, print, listPrefix) {
39244 var node = path.getValue();
39245 var prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
39246 return concat$d([prefix, printChildren$1(path, options, print, {
39247 processor: function processor(childPath, index) {
39248 if (index === 0 && childPath.getValue().type !== "list") {
39249 return align$2(" ".repeat(prefix.length), childPath.call(print));
39252 var alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
39254 return concat$d([alignment, align$2(alignment, childPath.call(print))]);
39259 function alignListPrefix(prefix, options) {
39260 var additionalSpaces = getAdditionalSpaces();
39261 return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block
39264 function getAdditionalSpaces() {
39265 var restSpaces = prefix.length % options.tabWidth;
39266 return restSpaces === 0 ? 0 : options.tabWidth - restSpaces;
39270 function getNthListSiblingIndex(node, parentNode) {
39271 return getNthSiblingIndex(node, parentNode, function (siblingNode) {
39272 return siblingNode.ordered === node.ordered;
39276 function getNthSiblingIndex(node, parentNode, condition) {
39277 condition = condition || function () {
39282 var _iteratorNormalCompletion = true;
39283 var _didIteratorError = false;
39284 var _iteratorError = undefined;
39287 for (var _iterator = parentNode.children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
39288 var childNode = _step.value;
39290 if (childNode.type === node.type && condition(childNode)) {
39296 if (childNode === node) {
39301 _didIteratorError = true;
39302 _iteratorError = err;
39305 if (!_iteratorNormalCompletion && _iterator.return != null) {
39306 _iterator.return();
39309 if (_didIteratorError) {
39310 throw _iteratorError;
39316 function getAncestorCounter$1(path, typeOrTypes) {
39317 var types = [].concat(typeOrTypes);
39321 while (ancestorNode = path.getParentNode(++counter)) {
39322 if (types.indexOf(ancestorNode.type) !== -1) {
39330 function getAncestorNode$2(path, typeOrTypes) {
39331 var counter = getAncestorCounter$1(path, typeOrTypes);
39332 return counter === -1 ? null : path.getParentNode(counter);
39335 function printLine(path, value, options) {
39336 if (options.proseWrap === "preserve" && value === "\n") {
39340 var isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES);
39341 return value !== "" ? isBreakable ? line$6 : " " : isBreakable ? softline$6 : "";
39344 function printTable(path, options, print) {
39345 var hardlineWithoutBreakParent = hardline$b.parts[0];
39346 var node = path.getValue();
39347 var contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } }
39349 path.map(function (rowPath) {
39350 var rowContents = [];
39351 rowPath.map(function (cellPath) {
39352 rowContents.push(printDocToString$3(cellPath.call(print), options).formatted);
39354 contents.push(rowContents);
39355 }, "children"); // Get the width of each column
39357 var columnMaxWidths = contents.reduce(function (currentWidths, rowContents) {
39358 return currentWidths.map(function (width, columnIndex) {
39359 return Math.max(width, util.getStringWidth(rowContents[columnIndex]));
39361 }, contents[0].map(function () {
39363 }) // minimum width = 3 (---, :--, :-:, --:)
39365 var alignedTable = join$9(hardlineWithoutBreakParent, [printRow(contents[0]), printSeparator(), join$9(hardlineWithoutBreakParent, contents.slice(1).map(function (rowContents) {
39366 return printRow(rowContents);
39369 if (options.proseWrap !== "never") {
39370 return concat$d([breakParent$3, alignedTable]);
39371 } // Only if the --prose-wrap never is set and it exceeds the print width.
39374 var compactTable = join$9(hardlineWithoutBreakParent, [printRow(contents[0],
39376 true), printSeparator(
39378 true), join$9(hardlineWithoutBreakParent, contents.slice(1).map(function (rowContents) {
39379 return printRow(rowContents,
39383 return concat$d([breakParent$3, group$d(ifBreak$5(compactTable, alignedTable))]);
39385 function printSeparator(isCompact) {
39386 return concat$d(["| ", join$9(" | ", columnMaxWidths.map(function (width, index) {
39387 var spaces = isCompact ? 3 : width;
39389 switch (node.align[index]) {
39391 return ":" + "-".repeat(spaces - 1);
39394 return "-".repeat(spaces - 1) + ":";
39397 return ":" + "-".repeat(spaces - 2) + ":";
39400 return "-".repeat(spaces);
39405 function printRow(rowContents, isCompact) {
39406 return concat$d(["| ", join$9(" | ", isCompact ? rowContents : rowContents.map(function (rowContent, columnIndex) {
39407 switch (node.align[columnIndex]) {
39409 return alignRight(rowContent, columnMaxWidths[columnIndex]);
39412 return alignCenter(rowContent, columnMaxWidths[columnIndex]);
39415 return alignLeft(rowContent, columnMaxWidths[columnIndex]);
39420 function alignLeft(text, width) {
39421 var spaces = width - util.getStringWidth(text);
39422 return concat$d([text, " ".repeat(spaces)]);
39425 function alignRight(text, width) {
39426 var spaces = width - util.getStringWidth(text);
39427 return concat$d([" ".repeat(spaces), text]);
39430 function alignCenter(text, width) {
39431 var spaces = width - util.getStringWidth(text);
39432 var left = Math.floor(spaces / 2);
39433 var right = spaces - left;
39434 return concat$d([" ".repeat(left), text, " ".repeat(right)]);
39438 function printRoot(path, options, print) {
39439 /** @typedef {{ index: number, offset: number }} IgnorePosition */
39441 /** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */
39442 var ignoreRanges = [];
39443 /** @type {IgnorePosition | null} */
39445 var ignoreStart = null;
39446 var children = path.getValue().children;
39447 children.forEach(function (childNode, index) {
39448 switch (isPrettierIgnore(childNode)) {
39450 if (ignoreStart === null) {
39453 offset: childNode.position.end.offset
39460 if (ignoreStart !== null) {
39461 ignoreRanges.push({
39462 start: ignoreStart,
39465 offset: childNode.position.start.offset
39468 ignoreStart = null;
39474 return printChildren$1(path, options, print, {
39475 processor: function processor(childPath, index) {
39476 if (ignoreRanges.length !== 0) {
39477 var ignoreRange = ignoreRanges[0];
39479 if (index === ignoreRange.start.index) {
39480 return concat$d([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]);
39483 if (ignoreRange.start.index < index && index < ignoreRange.end.index) {
39487 if (index === ignoreRange.end.index) {
39488 ignoreRanges.shift();
39493 return childPath.call(print);
39498 function printChildren$1(path, options, print, events) {
39499 events = events || {};
39500 var postprocessor = events.postprocessor || concat$d;
39502 var processor = events.processor || function (childPath) {
39503 return childPath.call(print);
39506 var node = path.getValue();
39509 path.map(function (childPath, index) {
39510 var childNode = childPath.getValue();
39511 var result = processor(childPath, index);
39513 if (result !== false) {
39516 prevNode: lastChildNode,
39521 if (!shouldNotPrePrintHardline(childNode, data)) {
39522 parts.push(hardline$b);
39524 if (lastChildNode && TRAILING_HARDLINE_NODES.indexOf(lastChildNode.type) !== -1) {
39525 if (shouldPrePrintTripleHardline(childNode, data)) {
39526 parts.push(hardline$b);
39529 if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
39530 parts.push(hardline$b);
39533 if (shouldPrePrintTripleHardline(childNode, data)) {
39534 parts.push(hardline$b);
39539 parts.push(result);
39540 lastChildNode = childNode;
39543 return postprocessor(parts);
39546 function getLastDescendantNode(node) {
39547 var current = node;
39549 while (current.children && current.children.length !== 0) {
39550 current = current.children[current.children.length - 1];
39555 /** @return {false | 'next' | 'start' | 'end'} */
39558 function isPrettierIgnore(node) {
39559 if (node.type !== "html") {
39563 var match = node.value.match(/^<!--\s*prettier-ignore(?:-(start|end))?\s*-->$/);
39564 return match === null ? false : match[1] ? match[1] : "next";
39567 function isInlineNode(node) {
39568 return node && INLINE_NODE_TYPES$1.indexOf(node.type) !== -1;
39571 function isEndsWithHardLine(node) {
39572 return node && /\n+$/.test(node.value);
39575 function last(nodes) {
39576 return nodes && nodes[nodes.length - 1];
39579 function shouldNotPrePrintHardline(node, _ref) {
39580 var parentNode = _ref.parentNode,
39581 parts = _ref.parts,
39582 prevNode = _ref.prevNode;
39583 var isFirstNode = parts.length === 0;
39584 var isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES$1.indexOf(parentNode.type) !== -1;
39585 var isAfterHardlineNode = prevNode && (isEndsWithHardLine(prevNode) || isEndsWithHardLine(last(prevNode.children)));
39586 return isFirstNode || isInlineNode(node) || isInlineHTML || isAfterHardlineNode;
39589 function shouldPrePrintDoubleHardline(node, _ref2) {
39590 var parentNode = _ref2.parentNode,
39591 prevNode = _ref2.prevNode;
39592 var prevNodeType = prevNode && prevNode.type;
39593 var nodeType = node.type;
39594 var isSequence = prevNodeType === nodeType;
39595 var isSiblingNode = isSequence && SIBLING_NODE_TYPES.indexOf(nodeType) !== -1;
39596 var isInTightListItem = parentNode.type === "listItem" && !parentNode.loose;
39597 var isPrevNodeLooseListItem = prevNodeType === "listItem" && prevNode.loose;
39598 var isPrevNodePrettierIgnore = isPrettierIgnore(prevNode) === "next";
39599 var isBlockHtmlWithoutBlankLineBetweenPrevHtml = nodeType === "html" && prevNodeType === "html" && prevNode.position.end.line + 1 === node.position.start.line;
39600 var isJsxInlineSibling = prevNodeType === "jsx" && isInlineNode(node) || nodeType === "jsx" && isInlineNode(prevNode);
39601 return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml || isJsxInlineSibling);
39604 function shouldPrePrintTripleHardline(node, data) {
39605 var isPrevNodeList = data.prevNode && data.prevNode.type === "list";
39606 var isIndentedCode = node.type === "code" && node.isIndented;
39607 return isPrevNodeList && isIndentedCode;
39610 function shouldRemainTheSameContent(path) {
39611 var ancestorNode = getAncestorNode$2(path, ["linkReference", "imageReference"]);
39612 return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full");
39615 function normalizeDoc(doc) {
39616 return mapDoc$6(doc, function (currentDoc) {
39617 if (!currentDoc.parts) {
39621 if (currentDoc.type === "concat" && currentDoc.parts.length === 1) {
39622 return currentDoc.parts[0];
39626 currentDoc.parts.forEach(function (part) {
39627 if (part.type === "concat") {
39628 parts.push.apply(parts, part.parts);
39629 } else if (part !== "") {
39633 return Object.assign({}, currentDoc, {
39634 parts: normalizeParts(parts)
39639 function printUrl(url, dangerousCharOrChars) {
39640 var dangerousChars = [" "].concat(dangerousCharOrChars || []);
39641 return new RegExp(dangerousChars.map(function (x) {
39643 }).join("|")).test(url) ? `<${url}>` : url;
39646 function printTitle(title, options, printSpace) {
39647 if (printSpace == null) {
39656 return " " + printTitle(title, options, false);
39659 if (title.includes('"') && title.includes("'") && !title.includes(")")) {
39660 return `(${title})`; // avoid escaped quotes
39661 } // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split
39664 var singleCount = title.split("'").length - 1;
39665 var doubleCount = title.split('"').length - 1;
39666 var quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"';
39667 title = title.replace(new RegExp(`(${quote})`, "g"), "\\$1");
39668 return `${quote}${title}${quote}`;
39671 function normalizeParts(parts) {
39672 return parts.reduce(function (current, part) {
39673 var lastPart = util.getLast(current);
39675 if (typeof lastPart === "string" && typeof part === "string") {
39676 current.splice(-1, 1, lastPart + part);
39678 current.push(part);
39685 function clamp(value, min, max) {
39686 return value < min ? min : value > max ? max : value;
39689 function clean$5(ast, newObj, parent) {
39690 delete newObj.position;
39691 delete newObj.raw; // front-matter
39694 if (ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") {
39695 delete newObj.value;
39698 if (ast.type === "list") {
39699 delete newObj.isAligned;
39700 } // texts can be splitted or merged
39703 if (ast.type === "text") {
39707 if (ast.type === "inlineCode") {
39708 newObj.value = ast.value.replace(/[ \t\n]+/g, " ");
39709 } // for insert pragma
39712 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)) {
39717 function hasPrettierIgnore$2(path) {
39718 var index = +path.getName();
39724 var prevNode = path.getParentNode().children[index - 1];
39725 return isPrettierIgnore(prevNode) === "next";
39728 var printerMarkdown = {
39729 preprocess: preprocess_1$1,
39730 print: genericPrint$4,
39732 massageAstNode: clean$5,
39733 hasPrettierIgnore: hasPrettierIgnore$2,
39734 insertPragma: pragma$3.insertPragma
39738 proseWrap: commonOptions.proseWrap,
39739 singleQuote: commonOptions.singleQuote
39742 var name$f = "Markdown";
39743 var type$d = "prose";
39747 var aceMode$d = "markdown";
39748 var codemirrorMode$a = "gfm";
39749 var codemirrorMimeType$a = "text/x-gfm";
39751 var extensions$d = [
39763 var filenames$3 = [
39766 var tmScope$d = "source.gfm";
39767 var languageId$d = 222;
39771 aliases: aliases$4,
39772 aceMode: aceMode$d,
39773 codemirrorMode: codemirrorMode$a,
39774 codemirrorMimeType: codemirrorMimeType$a,
39776 extensions: extensions$d,
39777 filenames: filenames$3,
39778 tmScope: tmScope$d,
39779 languageId: languageId$d
39782 var Markdown$1 = /*#__PURE__*/Object.freeze({
39786 aliases: aliases$4,
39787 aceMode: aceMode$d,
39788 codemirrorMode: codemirrorMode$a,
39789 codemirrorMimeType: codemirrorMimeType$a,
39791 extensions: extensions$d,
39792 filenames: filenames$3,
39793 tmScope: tmScope$d,
39794 languageId: languageId$d,
39795 'default': Markdown
39798 var require$$0$5 = getCjsExportFromNamespace(Markdown$1);
39800 var languages$4 = [createLanguage(require$$0$5, function (data) {
39801 return Object.assign(data, {
39803 parsers: ["remark"],
39804 vscodeLanguageIds: ["markdown"],
39805 filenames: data.filenames.concat(["README"]),
39806 extensions: data.extensions.filter(function (extension) {
39807 return extension !== ".mdx";
39810 }), createLanguage(require$$0$5, function (data) {
39811 return Object.assign(data, {
39815 vscodeLanguageIds: ["mdx"],
39817 extensions: [".mdx"]
39821 mdast: printerMarkdown
39823 var languageMarkdown = {
39824 languages: languages$4,
39825 options: options$5,
39826 printers: printers$4
39829 var clean$6 = function clean(ast, newNode) {
39830 delete newNode.sourceSpan;
39831 delete newNode.startSourceSpan;
39832 delete newNode.endSourceSpan;
39833 delete newNode.nameSpan;
39834 delete newNode.valueSpan;
39836 if (ast.type === "text" || ast.type === "comment") {
39838 } // may be formatted by multiparser
39841 if (ast.type === "yaml" || ast.type === "toml") {
39845 if (ast.type === "attribute") {
39846 delete newNode.value;
39849 if (ast.type === "docType") {
39850 delete newNode.value;
39855 "CSS_DISPLAY_TAGS": {
39858 "basefont": "none",
39859 "datalist": "none",
39864 "noframes": "none",
39870 "template": "inline",
39875 "address": "block",
39876 "blockquote": "block",
39880 "figcaption": "block",
39886 "listing": "block",
39889 "plaintext": "block",
39892 "slot": "contents",
39895 "article": "block",
39905 "section": "block",
39914 "caption": "table-caption",
39915 "colgroup": "table-column-group",
39916 "col": "table-column",
39917 "thead": "table-header-group",
39918 "tbody": "table-row-group",
39919 "tfoot": "table-footer-group",
39921 "td": "table-cell",
39922 "th": "table-cell",
39923 "fieldset": "block",
39924 "button": "inline-block",
39925 "video": "inline-block",
39926 "audio": "inline-block"
39928 "CSS_DISPLAY_DEFAULT": "inline",
39929 "CSS_WHITE_SPACE_TAGS": {
39931 "plaintext": "pre",
39935 "table": "initial",
39936 "textarea": "pre-wrap"
39938 "CSS_WHITE_SPACE_DEFAULT": "normal"
40164 "allowpaymentrequest",
40546 basefont: basefont,
40548 blockquote: blockquote,
40555 colgroup: colgroup,
40565 fieldset: fieldset,
40569 frameset: frameset,
40594 optgroup: optgroup,
40600 progress: progress,
40610 textarea: textarea,
40621 var htmlElementAttributes = /*#__PURE__*/Object.freeze({
40629 basefont: basefont,
40631 blockquote: blockquote,
40638 colgroup: colgroup,
40648 fieldset: fieldset,
40652 frameset: frameset,
40677 optgroup: optgroup,
40683 progress: progress,
40693 textarea: textarea,
40705 var htmlElementAttributes$1 = getCjsExportFromNamespace(htmlElementAttributes);
40707 var CSS_DISPLAY_TAGS = json$1.CSS_DISPLAY_TAGS,
40708 CSS_DISPLAY_DEFAULT = json$1.CSS_DISPLAY_DEFAULT,
40709 CSS_WHITE_SPACE_TAGS = json$1.CSS_WHITE_SPACE_TAGS,
40710 CSS_WHITE_SPACE_DEFAULT = json$1.CSS_WHITE_SPACE_DEFAULT;
40711 var HTML_TAGS = arrayToMap(htmlTagNames$1);
40712 var HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes$1, arrayToMap);
40714 function arrayToMap(array) {
40715 var map = Object.create(null);
40716 var _iteratorNormalCompletion = true;
40717 var _didIteratorError = false;
40718 var _iteratorError = undefined;
40721 for (var _iterator = array[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
40722 var value = _step.value;
40726 _didIteratorError = true;
40727 _iteratorError = err;
40730 if (!_iteratorNormalCompletion && _iterator.return != null) {
40731 _iterator.return();
40734 if (_didIteratorError) {
40735 throw _iteratorError;
40743 function mapObject(object, fn) {
40744 var newObject = Object.create(null);
40746 for (var _i = 0, _Object$keys = Object.keys(object); _i < _Object$keys.length; _i++) {
40747 var key = _Object$keys[_i];
40748 newObject[key] = fn(object[key], key);
40754 function shouldPreserveContent(node, options) {
40755 if (node.type === "element" && node.fullName === "template" && node.attrMap.lang && node.attrMap.lang !== "html") {
40757 } // unterminated node in ie conditional comment
40758 // e.g. <!--[if lt IE 9]><html><![endif]-->
40761 if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) {
40763 } // incomplete html in ie conditional comment
40764 // e.g. <!--[if lt IE 9]></div><![endif]-->
40767 if (node.type === "ieConditionalComment" && !node.complete) {
40769 } // top-level elements (excluding <template>, <style> and <script>) in Vue SFC are considered custom block
40770 // custom blocks can be written in other languages so we should preserve them to not break the code
40773 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>
40774 "html"].indexOf(node.fullName) === -1) {
40776 } // TODO: handle non-text children in <pre>
40779 if (isPreLikeNode(node) && node.children.some(function (child) {
40780 return child.type !== "text" && child.type !== "interpolation";
40788 function hasPrettierIgnore$3(node) {
40789 if (node.type === "attribute" || isTextLikeNode(node)) {
40793 if (!node.parent) {
40797 if (typeof node.index !== "number" || node.index === 0) {
40801 var prevNode = node.parent.children[node.index - 1];
40802 return isPrettierIgnore$1(prevNode);
40805 function isPrettierIgnore$1(node) {
40806 return node.type === "comment" && node.value.trim() === "prettier-ignore";
40809 function getPrettierIgnoreAttributeCommentData(value) {
40810 var match = value.trim().match(/^prettier-ignore-attribute(?:\s+([^]+))?$/);
40820 return match[1].split(/\s+/);
40822 /** there's no opening/closing tag or it's considered not breakable */
40825 function isTextLikeNode(node) {
40826 return node.type === "text" || node.type === "comment";
40829 function isScriptLikeTag(node) {
40830 return node.type === "element" && (node.fullName === "script" || node.fullName === "style" || node.fullName === "svg:style");
40833 function isFrontMatterNode(node) {
40834 return node.type === "yaml" || node.type === "toml";
40837 function canHaveInterpolation(node) {
40838 return node.children && !isScriptLikeTag(node);
40841 function isWhitespaceSensitiveNode(node) {
40842 return isScriptLikeTag(node) || node.type === "interpolation" || isIndentationSensitiveNode(node);
40845 function isIndentationSensitiveNode(node) {
40846 return getNodeCssStyleWhiteSpace(node).startsWith("pre");
40849 function isLeadingSpaceSensitiveNode(node) {
40850 var isLeadingSpaceSensitive = _isLeadingSpaceSensitiveNode();
40852 if (isLeadingSpaceSensitive && !node.prev && node.parent && node.parent.tagDefinition && node.parent.tagDefinition.ignoreFirstLf) {
40853 return node.type === "interpolation";
40856 return isLeadingSpaceSensitive;
40858 function _isLeadingSpaceSensitiveNode() {
40859 if (isFrontMatterNode(node)) {
40863 if ((node.type === "text" || node.type === "interpolation") && node.prev && (node.prev.type === "text" || node.prev.type === "interpolation")) {
40867 if (!node.parent || node.parent.cssDisplay === "none") {
40871 if (isPreLikeNode(node.parent)) {
40875 if (!node.prev && (node.parent.type === "root" || isScriptLikeTag(node.parent) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
40879 if (node.prev && !isNextLeadingSpaceSensitiveCssDisplay(node.prev.cssDisplay)) {
40887 function isTrailingSpaceSensitiveNode(node) {
40888 if (isFrontMatterNode(node)) {
40892 if ((node.type === "text" || node.type === "interpolation") && node.next && (node.next.type === "text" || node.next.type === "interpolation")) {
40896 if (!node.parent || node.parent.cssDisplay === "none") {
40900 if (isPreLikeNode(node.parent)) {
40904 if (!node.next && (node.parent.type === "root" || isScriptLikeTag(node.parent) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
40908 if (node.next && !isPrevTrailingSpaceSensitiveCssDisplay(node.next.cssDisplay)) {
40915 function isDanglingSpaceSensitiveNode(node) {
40916 return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag(node);
40919 function forceNextEmptyLine(node) {
40920 return isFrontMatterNode(node) || node.next && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line;
40922 /** firstChild leadingSpaces and lastChild trailingSpaces */
40925 function forceBreakContent(node) {
40926 return forceBreakChildren(node) || node.type === "element" && node.children.length !== 0 && (["body", "script", "style"].indexOf(node.name) !== -1 || node.children.some(function (child) {
40927 return hasNonTextChild(child);
40928 })) || node.firstChild && node.firstChild === node.lastChild && hasLeadingLineBreak(node.firstChild) && (!node.lastChild.isTrailingSpaceSensitive || hasTrailingLineBreak(node.lastChild));
40930 /** spaces between children */
40933 function forceBreakChildren(node) {
40934 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");
40937 function preferHardlineAsLeadingSpaces(node) {
40938 return preferHardlineAsSurroundingSpaces(node) || node.prev && preferHardlineAsTrailingSpaces(node.prev) || hasSurroundingLineBreak(node);
40941 function preferHardlineAsTrailingSpaces(node) {
40942 return preferHardlineAsSurroundingSpaces(node) || node.type === "element" && node.fullName === "br" || hasSurroundingLineBreak(node);
40945 function hasSurroundingLineBreak(node) {
40946 return hasLeadingLineBreak(node) && hasTrailingLineBreak(node);
40949 function hasLeadingLineBreak(node) {
40950 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);
40953 function hasTrailingLineBreak(node) {
40954 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);
40957 function preferHardlineAsSurroundingSpaces(node) {
40958 switch (node.type) {
40959 case "ieConditionalComment":
40965 return ["script", "select"].indexOf(node.name) !== -1;
40971 function getLastDescendant(node) {
40972 return node.lastChild ? getLastDescendant(node.lastChild) : node;
40975 function hasNonTextChild(node) {
40976 return node.children && node.children.some(function (child) {
40977 return child.type !== "text";
40981 function inferScriptParser(node) {
40982 if (node.name === "script" && !node.attrMap.src) {
40983 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") {
40987 if (node.attrMap.type === "application/x-typescript" || node.attrMap.lang === "ts" || node.attrMap.lang === "tsx") {
40988 return "typescript";
40991 if (node.attrMap.type === "text/markdown") {
40995 if (node.attrMap.type.endsWith("json") || node.attrMap.type.endsWith("importmap")) {
41000 if (node.name === "style") {
41001 if (!node.attrMap.lang || node.attrMap.lang === "postcss" || node.attrMap.lang === "css") {
41005 if (node.attrMap.lang === "scss") {
41009 if (node.attrMap.lang === "less") {
41017 function isBlockLikeCssDisplay(cssDisplay) {
41018 return cssDisplay === "block" || cssDisplay === "list-item" || cssDisplay.startsWith("table");
41021 function isFirstChildLeadingSpaceSensitiveCssDisplay(cssDisplay) {
41022 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
41025 function isLastChildTrailingSpaceSensitiveCssDisplay(cssDisplay) {
41026 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
41029 function isPrevTrailingSpaceSensitiveCssDisplay(cssDisplay) {
41030 return !isBlockLikeCssDisplay(cssDisplay);
41033 function isNextLeadingSpaceSensitiveCssDisplay(cssDisplay) {
41034 return !isBlockLikeCssDisplay(cssDisplay);
41037 function isDanglingSpaceSensitiveCssDisplay(cssDisplay) {
41038 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
41041 function isPreLikeNode(node) {
41042 return getNodeCssStyleWhiteSpace(node).startsWith("pre");
41045 function countParents(path) {
41046 var predicate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {
41051 for (var i = path.stack.length - 1; i >= 0; i--) {
41052 var value = path.stack[i];
41054 if (value && typeof value === "object" && !Array.isArray(value) && predicate(value)) {
41062 function hasParent(node, fn) {
41063 var current = node;
41070 current = current.parent;
41076 function getNodeCssStyleDisplay(node, options) {
41077 if (node.prev && node.prev.type === "comment") {
41078 // <!-- display: block -->
41079 var match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/);
41086 var isInSvgForeignObject = false;
41088 if (node.type === "element" && node.namespace === "svg") {
41089 if (hasParent(node, function (parent) {
41090 return parent.fullName === "svg:foreignObject";
41092 isInSvgForeignObject = true;
41094 return node.name === "svg" ? "inline-block" : "block";
41098 switch (options.htmlWhitespaceSensitivity) {
41106 return node.type === "element" && (!node.namespace || isInSvgForeignObject) && CSS_DISPLAY_TAGS[node.name] || CSS_DISPLAY_DEFAULT;
41110 function getNodeCssStyleWhiteSpace(node) {
41111 return node.type === "element" && !node.namespace && CSS_WHITE_SPACE_TAGS[node.name] || CSS_WHITE_SPACE_DEFAULT;
41114 function getMinIndentation(text) {
41115 var minIndentation = Infinity;
41116 var _iteratorNormalCompletion2 = true;
41117 var _didIteratorError2 = false;
41118 var _iteratorError2 = undefined;
41121 for (var _iterator2 = text.split("\n")[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
41122 var lineText = _step2.value;
41124 if (lineText.length === 0) {
41128 if (/\S/.test(lineText[0])) {
41132 var indentation = lineText.match(/^\s*/)[0].length;
41134 if (lineText.length === indentation) {
41138 if (indentation < minIndentation) {
41139 minIndentation = indentation;
41143 _didIteratorError2 = true;
41144 _iteratorError2 = err;
41147 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
41148 _iterator2.return();
41151 if (_didIteratorError2) {
41152 throw _iteratorError2;
41157 return minIndentation === Infinity ? 0 : minIndentation;
41160 function dedentString(text) {
41161 var minIndent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : getMinIndentation(text);
41162 return minIndent === 0 ? text : text.split("\n").map(function (lineText) {
41163 return lineText.slice(minIndent);
41167 function normalizeParts$1(parts) {
41169 var restParts = parts.slice();
41171 while (restParts.length !== 0) {
41172 var part = restParts.shift();
41178 if (part.type === "concat") {
41179 Array.prototype.unshift.apply(restParts, part.parts);
41183 if (newParts.length !== 0 && typeof newParts[newParts.length - 1] === "string" && typeof part === "string") {
41184 newParts.push(newParts.pop() + part);
41188 newParts.push(part);
41194 function identity$2(x) {
41198 function shouldNotPrintClosingTag(node, options) {
41199 return !node.isSelfClosing && !node.endSourceSpan && (hasPrettierIgnore$3(node) || shouldPreserveContent(node.parent, options));
41202 function countChars(text, char) {
41205 for (var i = 0; i < text.length; i++) {
41206 if (text[i] === char) {
41214 function unescapeQuoteEntities(text) {
41215 return text.replace(/'/g, "'").replace(/"/g, '"');
41219 HTML_ELEMENT_ATTRIBUTES,
41221 canHaveInterpolation,
41225 forceBreakChildren,
41227 forceNextEmptyLine,
41229 getNodeCssStyleDisplay,
41230 getNodeCssStyleWhiteSpace,
41231 getPrettierIgnoreAttributeCommentData,
41232 hasPrettierIgnore: hasPrettierIgnore$3,
41233 identity: identity$2,
41235 isDanglingSpaceSensitiveNode,
41237 isIndentationSensitiveNode,
41238 isLeadingSpaceSensitiveNode,
41242 isTrailingSpaceSensitiveNode,
41243 isWhitespaceSensitiveNode,
41244 normalizeParts: normalizeParts$1,
41245 preferHardlineAsLeadingSpaces,
41246 preferHardlineAsTrailingSpaces,
41247 shouldNotPrintClosingTag,
41248 shouldPreserveContent,
41249 unescapeQuoteEntities
41252 var canHaveInterpolation$1 = utils$5.canHaveInterpolation,
41253 getNodeCssStyleDisplay$1 = utils$5.getNodeCssStyleDisplay,
41254 isDanglingSpaceSensitiveNode$1 = utils$5.isDanglingSpaceSensitiveNode,
41255 isIndentationSensitiveNode$1 = utils$5.isIndentationSensitiveNode,
41256 isLeadingSpaceSensitiveNode$1 = utils$5.isLeadingSpaceSensitiveNode,
41257 isTrailingSpaceSensitiveNode$1 = utils$5.isTrailingSpaceSensitiveNode,
41258 isWhitespaceSensitiveNode$1 = utils$5.isWhitespaceSensitiveNode;
41259 var PREPROCESS_PIPELINE = [removeIgnorableFirstLf, mergeIeConditonalStartEndCommentIntoElementOpeningTag, mergeCdataIntoText, extractInterpolation, extractWhitespaces, addCssDisplay, addIsSelfClosing, addHasHtmComponentClosingTag, addIsSpaceSensitive, mergeSimpleElementIntoText];
41261 function preprocess$2(ast, options) {
41262 var _iteratorNormalCompletion = true;
41263 var _didIteratorError = false;
41264 var _iteratorError = undefined;
41267 for (var _iterator = PREPROCESS_PIPELINE[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
41268 var fn = _step.value;
41269 ast = fn(ast, options);
41272 _didIteratorError = true;
41273 _iteratorError = err;
41276 if (!_iteratorNormalCompletion && _iterator.return != null) {
41277 _iterator.return();
41280 if (_didIteratorError) {
41281 throw _iteratorError;
41289 function removeIgnorableFirstLf(ast
41292 return ast.map(function (node) {
41293 if (node.type === "element" && node.tagDefinition.ignoreFirstLf && node.children.length !== 0 && node.children[0].type === "text" && node.children[0].value[0] === "\n") {
41294 var text = node.children[0];
41295 return node.clone({
41296 children: text.value.length === 1 ? node.children.slice(1) : [].concat(text.clone({
41297 value: text.value.slice(1)
41298 }), node.children.slice(1))
41306 function mergeIeConditonalStartEndCommentIntoElementOpeningTag(ast
41310 * <!--[if ...]><!--><target><!--<![endif]-->
41312 var isTarget = function isTarget(node) {
41313 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;
41316 return ast.map(function (node) {
41317 if (node.children) {
41318 var isTargetResults = node.children.map(isTarget);
41320 if (isTargetResults.some(Boolean)) {
41321 var newChildren = [];
41323 for (var i = 0; i < node.children.length; i++) {
41324 var child = node.children[i];
41326 if (isTargetResults[i + 1]) {
41327 // ieConditionalStartComment
41331 if (isTargetResults[i]) {
41332 var ieConditionalStartComment = child.prev;
41333 var ieConditionalEndComment = child.firstChild;
41334 var ParseSourceSpan = child.sourceSpan.constructor;
41335 var startSourceSpan = new ParseSourceSpan(ieConditionalStartComment.sourceSpan.start, ieConditionalEndComment.sourceSpan.end);
41336 var sourceSpan = new ParseSourceSpan(startSourceSpan.start, child.sourceSpan.end);
41337 newChildren.push(child.clone({
41338 condition: ieConditionalStartComment.condition,
41341 children: child.children.slice(1)
41346 newChildren.push(child);
41349 return node.clone({
41350 children: newChildren
41359 function mergeNodeIntoText(ast, shouldMerge, getValue) {
41360 return ast.map(function (node) {
41361 if (node.children) {
41362 var shouldMergeResults = node.children.map(shouldMerge);
41364 if (shouldMergeResults.some(Boolean)) {
41365 var newChildren = [];
41367 for (var i = 0; i < node.children.length; i++) {
41368 var child = node.children[i];
41370 if (child.type !== "text" && !shouldMergeResults[i]) {
41371 newChildren.push(child);
41375 var newChild = child.type === "text" ? child : child.clone({
41377 value: getValue(child)
41380 if (newChildren.length === 0 || newChildren[newChildren.length - 1].type !== "text") {
41381 newChildren.push(newChild);
41385 var lastChild = newChildren.pop();
41386 var ParseSourceSpan = lastChild.sourceSpan.constructor;
41387 newChildren.push(lastChild.clone({
41388 value: lastChild.value + newChild.value,
41389 sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, newChild.sourceSpan.end)
41393 return node.clone({
41394 children: newChildren
41403 function mergeCdataIntoText(ast
41406 return mergeNodeIntoText(ast, function (node) {
41407 return node.type === "cdata";
41408 }, function (node) {
41409 return `<![CDATA[${node.value}]]>`;
41413 function mergeSimpleElementIntoText(ast
41416 var isSimpleElement = function isSimpleElement(node) {
41417 return node.type === "element" && node.attrs.length === 0 && node.children.length === 1 && node.firstChild.type === "text" && // \xA0: non-breaking whitespace
41418 !/[^\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";
41421 return ast.map(function (node) {
41422 if (node.children) {
41423 var isSimpleElementResults = node.children.map(isSimpleElement);
41425 if (isSimpleElementResults.some(Boolean)) {
41426 var newChildren = [];
41428 for (var i = 0; i < node.children.length; i++) {
41429 var child = node.children[i];
41431 if (isSimpleElementResults[i]) {
41432 var lastChild = newChildren.pop();
41433 var nextChild = node.children[++i];
41434 var ParseSourceSpan = node.sourceSpan.constructor;
41435 var isTrailingSpaceSensitive = nextChild.isTrailingSpaceSensitive,
41436 hasTrailingSpaces = nextChild.hasTrailingSpaces;
41437 newChildren.push(lastChild.clone({
41438 value: lastChild.value + `<${child.rawName}>` + child.firstChild.value + `</${child.rawName}>` + nextChild.value,
41439 sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, nextChild.sourceSpan.end),
41440 isTrailingSpaceSensitive,
41444 newChildren.push(child);
41448 return node.clone({
41449 children: newChildren
41458 function extractInterpolation(ast, options) {
41459 if (options.parser === "html") {
41463 var interpolationRegex = /\{\{([\s\S]+?)\}\}/g;
41464 return ast.map(function (node) {
41465 if (!canHaveInterpolation$1(node)) {
41469 var newChildren = [];
41470 var _iteratorNormalCompletion2 = true;
41471 var _didIteratorError2 = false;
41472 var _iteratorError2 = undefined;
41475 for (var _iterator2 = node.children[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
41476 var child = _step2.value;
41478 if (child.type !== "text") {
41479 newChildren.push(child);
41483 var ParseSourceSpan = child.sourceSpan.constructor;
41484 var startSourceSpan = child.sourceSpan.start;
41485 var endSourceSpan = null;
41486 var components = child.value.split(interpolationRegex);
41488 for (var i = 0; i < components.length; i++, startSourceSpan = endSourceSpan) {
41489 var value = components[i];
41492 endSourceSpan = startSourceSpan.moveBy(value.length);
41494 if (value.length !== 0) {
41498 sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan)
41505 endSourceSpan = startSourceSpan.moveBy(value.length + 4); // `{{` + `}}`
41508 type: "interpolation",
41509 sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan),
41510 children: value.length === 0 ? [] : [{
41513 sourceSpan: new ParseSourceSpan(startSourceSpan.moveBy(2), endSourceSpan.moveBy(-2))
41519 _didIteratorError2 = true;
41520 _iteratorError2 = err;
41523 if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
41524 _iterator2.return();
41527 if (_didIteratorError2) {
41528 throw _iteratorError2;
41533 return node.clone({
41534 children: newChildren
41539 * - add `hasLeadingSpaces` field
41540 * - add `hasTrailingSpaces` field
41541 * - add `hasDanglingSpaces` field for parent nodes
41542 * - add `isWhitespaceSensitive`, `isIndentationSensitive` field for text nodes
41543 * - remove insensitive whitespaces
41547 function extractWhitespaces(ast
41550 var TYPE_WHITESPACE = "whitespace";
41551 return ast.map(function (node) {
41552 if (!node.children) {
41556 if (node.children.length === 0 || node.children.length === 1 && node.children[0].type === "text" && node.children[0].value.trim().length === 0) {
41557 return node.clone({
41559 hasDanglingSpaces: node.children.length !== 0
41563 var isWhitespaceSensitive = isWhitespaceSensitiveNode$1(node);
41564 var isIndentationSensitive = isIndentationSensitiveNode$1(node);
41565 return node.clone({
41566 isWhitespaceSensitive,
41567 isIndentationSensitive,
41568 children: node.children // extract whitespace nodes
41569 .reduce(function (newChildren, child) {
41570 if (child.type !== "text" || isWhitespaceSensitive) {
41571 return newChildren.concat(child);
41574 var localChildren = [];
41576 var _child$value$match = child.value.match(/^(\s*)([\s\S]*?)(\s*)$/),
41577 _child$value$match2 = _slicedToArray(_child$value$match, 4),
41578 leadingSpaces = _child$value$match2[1],
41579 text = _child$value$match2[2],
41580 trailingSpaces = _child$value$match2[3];
41582 if (leadingSpaces) {
41583 localChildren.push({
41584 type: TYPE_WHITESPACE
41588 var ParseSourceSpan = child.sourceSpan.constructor;
41591 localChildren.push({
41594 sourceSpan: new ParseSourceSpan(child.sourceSpan.start.moveBy(leadingSpaces.length), child.sourceSpan.end.moveBy(-trailingSpaces.length))
41598 if (trailingSpaces) {
41599 localChildren.push({
41600 type: TYPE_WHITESPACE
41604 return newChildren.concat(localChildren);
41605 }, []) // set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
41606 .reduce(function (newChildren, child, i, children) {
41607 if (child.type === TYPE_WHITESPACE) {
41608 return newChildren;
41611 var hasLeadingSpaces = i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
41612 var hasTrailingSpaces = i !== children.length - 1 && children[i + 1].type === TYPE_WHITESPACE;
41613 return newChildren.concat(Object.assign({}, child, {
41622 function addIsSelfClosing(ast
41625 return ast.map(function (node) {
41626 return Object.assign(node, {
41627 isSelfClosing: !node.children || node.type === "element" && (node.tagDefinition.isVoid || // self-closing
41628 node.startSourceSpan === node.endSourceSpan)
41633 function addHasHtmComponentClosingTag(ast, options) {
41634 return ast.map(function (node) {
41635 return node.type !== "element" ? node : Object.assign(node, {
41636 hasHtmComponentClosingTag: node.endSourceSpan && /^<\s*\/\s*\/\s*>$/.test(options.originalText.slice(node.endSourceSpan.start.offset, node.endSourceSpan.end.offset))
41641 function addCssDisplay(ast, options) {
41642 return ast.map(function (node) {
41643 return Object.assign(node, {
41644 cssDisplay: getNodeCssStyleDisplay$1(node, options)
41649 * - add `isLeadingSpaceSensitive` field
41650 * - add `isTrailingSpaceSensitive` field
41651 * - add `isDanglingSpaceSensitive` field for parent nodes
41655 function addIsSpaceSensitive(ast
41658 return ast.map(function (node) {
41659 if (!node.children) {
41663 if (node.children.length === 0) {
41664 return node.clone({
41665 isDanglingSpaceSensitive: isDanglingSpaceSensitiveNode$1(node)
41669 return node.clone({
41670 children: node.children.map(function (child) {
41671 return Object.assign({}, child, {
41672 isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode$1(child),
41673 isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode$1(child)
41675 }).map(function (child, index, children) {
41676 return Object.assign({}, child, {
41677 isLeadingSpaceSensitive: index === 0 ? child.isLeadingSpaceSensitive : children[index - 1].isTrailingSpaceSensitive && child.isLeadingSpaceSensitive,
41678 isTrailingSpaceSensitive: index === children.length - 1 ? child.isTrailingSpaceSensitive : children[index + 1].isLeadingSpaceSensitive && child.isTrailingSpaceSensitive
41685 var preprocess_1$2 = preprocess$2;
41687 function hasPragma$3(text) {
41688 return /^\s*<!--\s*@(format|prettier)\s*-->/.test(text);
41691 function insertPragma$6(text) {
41692 return "<!-- @format -->\n\n" + text.replace(/^\s*\n/, "");
41696 hasPragma: hasPragma$3,
41697 insertPragma: insertPragma$6
41700 var _require$$0$builders$8 = doc.builders,
41701 concat$e = _require$$0$builders$8.concat,
41702 group$e = _require$$0$builders$8.group;
41704 * v-for="... in ..."
41705 * v-for="... of ..."
41706 * v-for="(..., ...) in ..."
41707 * v-for="(..., ...) of ..."
41710 function printVueFor(value, textToDoc) {
41711 var _parseVueFor = parseVueFor(value),
41712 left = _parseVueFor.left,
41713 operator = _parseVueFor.operator,
41714 right = _parseVueFor.right;
41716 return concat$e([group$e(textToDoc(`function _(${left}) {}`, {
41718 __isVueForBindingLeft: true
41719 })), " ", operator, " ", textToDoc(right, {
41720 parser: "__js_expression"
41722 } // modified from https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/parser/index.js#L370-L387
41725 function parseVueFor(value) {
41726 var forAliasRE = /([^]*?)\s+(in|of)\s+([^]*)/;
41727 var forIteratorRE = /,([^,}\]]*)(?:,([^,}\]]*))?$/;
41728 var stripParensRE = /^\(|\)$/g;
41729 var inMatch = value.match(forAliasRE);
41736 res.for = inMatch[3].trim();
41737 var alias = inMatch[1].trim().replace(stripParensRE, "");
41738 var iteratorMatch = alias.match(forIteratorRE);
41740 if (iteratorMatch) {
41741 res.alias = alias.replace(forIteratorRE, "");
41742 res.iterator1 = iteratorMatch[1].trim();
41744 if (iteratorMatch[2]) {
41745 res.iterator2 = iteratorMatch[2].trim();
41752 left: `${[res.alias, res.iterator1, res.iterator2].filter(Boolean).join(",")}`,
41753 operator: inMatch[2],
41758 function printVueSlotScope(value, textToDoc) {
41759 return textToDoc(`function _(${value}) {}`, {
41761 __isVueSlotScope: true
41765 function isVueEventBindingExpression$2(eventBindingValue) {
41766 // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/codegen/events.js#L3-L4
41767 // arrow function or anonymous function
41768 var fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; // simple member expression chain (a, a.b, a['b'], a["b"], a[0], a[b])
41770 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
41772 var value = eventBindingValue.trim();
41773 return fnExpRE.test(value) || simplePathRE.test(value);
41777 isVueEventBindingExpression: isVueEventBindingExpression$2,
41782 var parseSrcset = createCommonjsModule(function (module) {
41786 * By Alex Bell | MIT License
41788 * JS Parser for the string value that appears in markup <img srcset="here">
41790 * @returns Array [{url: _, d: _, w: _, h:_}, ...]
41792 * Based super duper closely on the reference algorithm at:
41793 * https://html.spec.whatwg.org/multipage/embedded-content.html#parse-a-srcset-attribute
41795 * Most comments are copied in directly from the spec
41796 * (except for comments in parens).
41798 (function (root, factory) {
41799 if ( module.exports) {
41800 // Node. Does not work with strict CommonJS, but
41801 // only CommonJS-like environments that support module.exports,
41803 module.exports = factory();
41805 // Browser globals (root is window)
41806 root.parseSrcset = factory();
41808 })(this, function () {
41809 // 1. Let input be the value passed to this algorithm.
41810 return function (input, options) {
41811 var logger = options && options.logger || console; // UTILITY FUNCTIONS
41812 // Manual is faster than RegEx
41813 // http://bjorn.tipling.com/state-and-regular-expressions-in-javascript
41814 // http://jsperf.com/whitespace-character/5
41816 function isSpace(c) {
41817 return c === "\u0020" || // space
41818 c === "\u0009" || // horizontal tab
41819 c === "\u000A" || // new line
41820 c === "\u000C" || // form feed
41821 c === "\u000D"; // carriage return
41824 function collectCharacters(regEx) {
41826 match = regEx.exec(input.substring(pos));
41830 pos += chars.length;
41835 var inputLength = input.length,
41836 // (Don't use \s, to avoid matching non-breaking space)
41837 regexLeadingSpaces = /^[ \t\n\r\u000c]+/,
41838 regexLeadingCommasOrSpaces = /^[, \t\n\r\u000c]+/,
41839 regexLeadingNotSpaces = /^[^ \t\n\r\u000c]+/,
41840 regexTrailingCommas = /[,]+$/,
41841 regexNonNegativeInteger = /^\d+$/,
41842 // ( Positive or negative or unsigned integers or decimals, without or without exponents.
41843 // Must include at least one digit.
41844 // According to spec tests any decimal point must be followed by a digit.
41845 // No leading plus sign is allowed.)
41846 // https://html.spec.whatwg.org/multipage/infrastructure.html#valid-floating-point-number
41847 regexFloatingPoint = /^-?(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/,
41853 // 2. Let position be a pointer into input, initially pointing at the start
41856 // 3. Let candidates be an initially empty source set.
41857 candidates = []; // 4. Splitting loop: Collect a sequence of characters that are space
41858 // characters or U+002C COMMA characters. If any U+002C COMMA characters
41859 // were collected, that is a parse error.
41862 collectCharacters(regexLeadingCommasOrSpaces); // 5. If position is past the end of input, return candidates and abort these steps.
41864 if (pos >= inputLength) {
41865 return candidates; // (we're done, this is the sole return path)
41866 } // 6. Collect a sequence of characters that are not space characters,
41867 // and let that be url.
41870 url = collectCharacters(regexLeadingNotSpaces); // 7. Let descriptors be a new empty list.
41872 descriptors = []; // 8. If url ends with a U+002C COMMA character (,), follow these substeps:
41873 // (1). Remove all trailing U+002C COMMA characters from url. If this removed
41874 // more than one character, that is a parse error.
41876 if (url.slice(-1) === ",") {
41877 url = url.replace(regexTrailingCommas, ""); // (Jump ahead to step 9 to skip tokenization and just push the candidate).
41879 parseDescriptors(); // Otherwise, follow these substeps:
41882 } // (close else of step 8)
41883 // 16. Return to the step labeled splitting loop.
41885 } // (Close of big while loop.)
41888 * Tokenizes descriptor properties prior to parsing
41889 * Returns undefined.
41893 function tokenize() {
41894 // 8.1. Descriptor tokeniser: Skip whitespace
41895 collectCharacters(regexLeadingSpaces); // 8.2. Let current descriptor be the empty string.
41897 currentDescriptor = ""; // 8.3. Let state be in descriptor.
41899 state = "in descriptor";
41902 // 8.4. Let c be the character at position.
41903 c = input.charAt(pos); // Do the following depending on the value of state.
41904 // For the purpose of this step, "EOF" is a special character representing
41905 // that position is past the end of input.
41908 if (state === "in descriptor") {
41909 // Do the following, depending on the value of c:
41911 // If current descriptor is not empty, append current descriptor to
41912 // descriptors and let current descriptor be the empty string.
41913 // Set state to after descriptor.
41915 if (currentDescriptor) {
41916 descriptors.push(currentDescriptor);
41917 currentDescriptor = "";
41918 state = "after descriptor";
41919 } // U+002C COMMA (,)
41920 // Advance position to the next character in input. If current descriptor
41921 // is not empty, append current descriptor to descriptors. Jump to the step
41922 // labeled descriptor parser.
41924 } else if (c === ",") {
41927 if (currentDescriptor) {
41928 descriptors.push(currentDescriptor);
41931 parseDescriptors();
41932 return; // U+0028 LEFT PARENTHESIS (()
41933 // Append c to current descriptor. Set state to in parens.
41934 } else if (c === "\u0028") {
41935 currentDescriptor = currentDescriptor + c;
41936 state = "in parens"; // EOF
41937 // If current descriptor is not empty, append current descriptor to
41938 // descriptors. Jump to the step labeled descriptor parser.
41939 } else if (c === "") {
41940 if (currentDescriptor) {
41941 descriptors.push(currentDescriptor);
41944 parseDescriptors();
41945 return; // Anything else
41946 // Append c to current descriptor.
41948 currentDescriptor = currentDescriptor + c;
41949 } // (end "in descriptor"
41952 } else if (state === "in parens") {
41953 // U+0029 RIGHT PARENTHESIS ())
41954 // Append c to current descriptor. Set state to in descriptor.
41956 currentDescriptor = currentDescriptor + c;
41957 state = "in descriptor"; // EOF
41958 // Append current descriptor to descriptors. Jump to the step labeled
41959 // descriptor parser.
41960 } else if (c === "") {
41961 descriptors.push(currentDescriptor);
41962 parseDescriptors();
41963 return; // Anything else
41964 // Append c to current descriptor.
41966 currentDescriptor = currentDescriptor + c;
41967 } // After descriptor
41969 } else if (state === "after descriptor") {
41970 // Do the following, depending on the value of c:
41971 // Space character: Stay in this state.
41972 if (isSpace(c)) ; else if (c === "") {
41973 parseDescriptors();
41974 return; // Anything else
41975 // Set state to in descriptor. Set position to the previous character in input.
41977 state = "in descriptor";
41980 } // Advance position to the next character in input.
41983 pos += 1; // Repeat this step.
41984 } // (close while true loop)
41988 * Adds descriptor properties to a candidate, pushes to the candidates array
41989 * @return undefined
41991 // Declared outside of the while loop so that it's only created once.
41994 function parseDescriptors() {
41995 // 9. Descriptor parser: Let error be no.
41996 var pError = false,
41997 // 10. Let width be absent.
41998 // 11. Let density be absent.
41999 // 12. Let future-compat-h be absent. (We're implementing it now as h)
42009 floatVal; // 13. For each descriptor in descriptors, run the appropriate set of steps
42010 // from the following list:
42012 for (i = 0; i < descriptors.length; i++) {
42013 desc = descriptors[i];
42014 lastChar = desc[desc.length - 1];
42015 value = desc.substring(0, desc.length - 1);
42016 intVal = parseInt(value, 10);
42017 floatVal = parseFloat(value); // If the descriptor consists of a valid non-negative integer followed by
42018 // a U+0077 LATIN SMALL LETTER W character
42020 if (regexNonNegativeInteger.test(value) && lastChar === "w") {
42021 // If width and density are not both absent, then let error be yes.
42024 } // Apply the rules for parsing non-negative integers to the descriptor.
42025 // If the result is zero, let error be yes.
42026 // Otherwise, let width be the result.
42029 if (intVal === 0) {
42033 } // If the descriptor consists of a valid floating-point number followed by
42034 // a U+0078 LATIN SMALL LETTER X character
42036 } else if (regexFloatingPoint.test(value) && lastChar === "x") {
42037 // If width, density and future-compat-h are not all absent, then let error
42041 } // Apply the rules for parsing floating-point number values to the descriptor.
42042 // If the result is less than zero, let error be yes. Otherwise, let density
42046 if (floatVal < 0) {
42050 } // If the descriptor consists of a valid non-negative integer followed by
42051 // a U+0068 LATIN SMALL LETTER H character
42053 } else if (regexNonNegativeInteger.test(value) && lastChar === "h") {
42054 // If height and density are not both absent, then let error be yes.
42057 } // Apply the rules for parsing non-negative integers to the descriptor.
42058 // If the result is zero, let error be yes. Otherwise, let future-compat-h
42062 if (intVal === 0) {
42066 } // Anything else, Let error be yes.
42071 } // (close step 13 for loop)
42072 // 15. If error is still no, then append a new image source to candidates whose
42073 // URL is url, associated with a width width if not absent and a pixel
42074 // density density if not absent. Otherwise, there is a parse error.
42078 candidate.url = url;
42092 candidates.push(candidate);
42093 } else if (logger && logger.error) {
42094 logger.error("Invalid srcset descriptor found in '" + input + "' at '" + desc + "'.");
42096 } // (close parseDescriptors fn)
42102 var _require$$0$builders$9 = doc.builders,
42103 concat$f = _require$$0$builders$9.concat,
42104 ifBreak$6 = _require$$0$builders$9.ifBreak,
42105 join$a = _require$$0$builders$9.join,
42106 line$7 = _require$$0$builders$9.line;
42108 function printImgSrcset(value) {
42109 var srcset = parseSrcset(value, {
42112 throw new Error(message);
42117 var hasW = srcset.some(function (src) {
42120 var hasH = srcset.some(function (src) {
42123 var hasX = srcset.some(function (src) {
42127 if (hasW + hasH + hasX !== 1) {
42128 throw new Error(`Mixed descriptor in srcset is not supported`);
42131 var key = hasW ? "w" : hasH ? "h" : "d";
42132 var unit = hasW ? "w" : hasH ? "h" : "x";
42134 var getMax = function getMax(values) {
42135 return Math.max.apply(Math, values);
42138 var urls = srcset.map(function (src) {
42141 var maxUrlLength = getMax(urls.map(function (url) {
42144 var descriptors = srcset.map(function (src) {
42146 }).map(function (descriptor) {
42147 return descriptor ? descriptor.toString() : "";
42149 var descriptorLeftLengths = descriptors.map(function (descriptor) {
42150 var index = descriptor.indexOf(".");
42151 return index === -1 ? descriptor.length : index;
42153 var maxDescriptorLeftLength = getMax(descriptorLeftLengths);
42154 return join$a(concat$f([",", line$7]), urls.map(function (url, index) {
42156 var descriptor = descriptors[index];
42159 var urlPadding = maxUrlLength - url.length + 1;
42160 var descriptorPadding = maxDescriptorLeftLength - descriptorLeftLengths[index];
42161 var alignment = " ".repeat(urlPadding + descriptorPadding);
42162 parts.push(ifBreak$6(alignment, " "), descriptor + unit);
42165 return concat$f(parts);
42169 var syntaxAttribute = {
42173 var builders = doc.builders,
42174 _require$$0$utils = doc.utils,
42175 stripTrailingHardline$2 = _require$$0$utils.stripTrailingHardline,
42176 mapDoc$7 = _require$$0$utils.mapDoc;
42177 var breakParent$4 = builders.breakParent,
42178 dedentToRoot$2 = builders.dedentToRoot,
42179 fill$5 = builders.fill,
42180 group$f = builders.group,
42181 hardline$c = builders.hardline,
42182 ifBreak$7 = builders.ifBreak,
42183 indent$9 = builders.indent,
42184 join$b = builders.join,
42185 line$8 = builders.line,
42186 literalline$6 = builders.literalline,
42187 markAsRoot$4 = builders.markAsRoot,
42188 softline$7 = builders.softline;
42189 var countChars$1 = utils$5.countChars,
42190 countParents$1 = utils$5.countParents,
42191 dedentString$1 = utils$5.dedentString,
42192 forceBreakChildren$1 = utils$5.forceBreakChildren,
42193 forceBreakContent$1 = utils$5.forceBreakContent,
42194 forceNextEmptyLine$1 = utils$5.forceNextEmptyLine,
42195 getLastDescendant$1 = utils$5.getLastDescendant,
42196 getPrettierIgnoreAttributeCommentData$1 = utils$5.getPrettierIgnoreAttributeCommentData,
42197 hasPrettierIgnore$4 = utils$5.hasPrettierIgnore,
42198 inferScriptParser$1 = utils$5.inferScriptParser,
42199 isScriptLikeTag$1 = utils$5.isScriptLikeTag,
42200 isTextLikeNode$1 = utils$5.isTextLikeNode,
42201 normalizeParts$2 = utils$5.normalizeParts,
42202 preferHardlineAsLeadingSpaces$1 = utils$5.preferHardlineAsLeadingSpaces,
42203 shouldNotPrintClosingTag$1 = utils$5.shouldNotPrintClosingTag,
42204 shouldPreserveContent$1 = utils$5.shouldPreserveContent,
42205 unescapeQuoteEntities$1 = utils$5.unescapeQuoteEntities;
42206 var replaceEndOfLineWith$2 = util.replaceEndOfLineWith;
42207 var insertPragma$7 = pragma$4.insertPragma;
42208 var printVueFor$1 = syntaxVue.printVueFor,
42209 printVueSlotScope$1 = syntaxVue.printVueSlotScope,
42210 isVueEventBindingExpression$3 = syntaxVue.isVueEventBindingExpression;
42211 var printImgSrcset$1 = syntaxAttribute.printImgSrcset;
42213 function concat$g(parts) {
42214 var newParts = normalizeParts$2(parts);
42215 return newParts.length === 0 ? "" : newParts.length === 1 ? newParts[0] : builders.concat(newParts);
42218 function embed$4(path, print, textToDoc, options) {
42219 var node = path.getValue();
42221 switch (node.type) {
42224 if (isScriptLikeTag$1(node.parent)) {
42225 var parser = inferScriptParser$1(node.parent);
42228 var value = parser === "markdown" ? dedentString$1(node.value.replace(/^[^\S\n]*?\n/, "")) : node.value;
42229 return builders.concat([concat$g([breakParent$4, printOpeningTagPrefix(node, options), stripTrailingHardline$2(textToDoc(value, {
42231 })), printClosingTagSuffix(node, options)])]);
42233 } else if (node.parent.type === "interpolation") {
42234 return concat$g([indent$9(concat$g([line$8, textToDoc(node.value, Object.assign({
42235 __isInHtmlInterpolation: true // to avoid unexpected `}}`
42237 }, options.parser === "angular" ? {
42238 parser: "__ng_interpolation",
42239 trailingComma: "none"
42240 } : options.parser === "vue" ? {
42241 parser: "__vue_expression"
42243 parser: "__js_expression"
42244 }))])), node.parent.next && needsToBorrowPrevClosingTagEndMarker(node.parent.next) ? " " : line$8]);
42254 } // lit-html: html`<my-element obj=${obj}></my-element>`
42257 if (/^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
42258 return concat$g([node.rawName, "=", node.value]);
42259 } // lwc: html`<my-element data-for={value}></my-element>`
42262 if (options.parser === "lwc") {
42263 var interpolationRegex = /^\{[\s\S]*\}$/;
42265 if (interpolationRegex.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
42266 return concat$g([node.rawName, "=", node.value]);
42270 var embeddedAttributeValueDoc = printEmbeddedAttributeValue(node, function (code, opts) {
42271 return (// strictly prefer single quote to avoid unnecessary html entity escape
42272 textToDoc(code, Object.assign({
42273 __isInHtmlAttribute: true
42278 if (embeddedAttributeValueDoc) {
42279 return concat$g([node.rawName, '="', group$f(mapDoc$7(embeddedAttributeValueDoc, function (doc) {
42280 return typeof doc === "string" ? doc.replace(/"/g, """) : doc;
42288 return markAsRoot$4(concat$g(["---", hardline$c, node.value.trim().length === 0 ? "" : textToDoc(node.value, {
42294 function genericPrint$5(path, options, print) {
42295 var node = path.getValue();
42297 switch (node.type) {
42299 // use original concat to not break stripTrailingHardline
42300 return builders.concat([group$f(printChildren$2(path, options, print)), hardline$c]);
42303 case "ieConditionalComment":
42314 * exception: break if the opening tag breaks
42325 var shouldHugContent = node.children.length === 1 && node.firstChild.type === "interpolation" && node.firstChild.isLeadingSpaceSensitive && !node.firstChild.hasLeadingSpaces && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces;
42326 var attrGroupId = Symbol("element-attr-group-id");
42327 return concat$g([group$f(concat$g([group$f(printOpeningTag(path, options, print), {
42329 }), node.children.length === 0 ? node.hasDanglingSpaces && node.isDanglingSpaceSensitive ? line$8 : "" : concat$g([forceBreakContent$1(node) ? breakParent$4 : "", function (childrenDoc) {
42330 return shouldHugContent ? ifBreak$7(indent$9(childrenDoc), childrenDoc, {
42331 groupId: attrGroupId
42332 }) : isScriptLikeTag$1(node) && node.parent.type === "root" && options.parser === "vue" && !options.vueIndentScriptAndStyle ? childrenDoc : indent$9(childrenDoc);
42333 }(concat$g([shouldHugContent ? ifBreak$7(softline$7, "", {
42334 groupId: attrGroupId
42335 }) : 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, "", {
42336 groupId: attrGroupId
42337 }) : 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) {
42338 return n.parent && n.parent.type !== "root";
42339 })}}$`).test(node.lastChild.value) ?
42348 "" : softline$7])])), printClosingTag(node, options)]);
42351 case "ieConditionalStartComment":
42352 case "ieConditionalEndComment":
42353 return concat$g([printOpeningTagStart(node), printClosingTagEnd(node)]);
42355 case "interpolation":
42356 return concat$g([printOpeningTagStart(node, options), concat$g(path.map(print, "children")), printClosingTagEnd(node, options)]);
42360 if (node.parent.type === "interpolation") {
42361 // replace the trailing literalline with hardline for better readability
42362 var trailingNewlineRegex = /\n[^\S\n]*?$/;
42363 var hasTrailingNewline = trailingNewlineRegex.test(node.value);
42364 var value = hasTrailingNewline ? node.value.replace(trailingNewlineRegex, "") : node.value;
42365 return concat$g([concat$g(replaceEndOfLineWith$2(value, literalline$6)), hasTrailingNewline ? hardline$c : ""]);
42368 return fill$5(normalizeParts$2([].concat(printOpeningTagPrefix(node, options), getTextValueParts(node), printClosingTagSuffix(node, options))));
42372 return concat$g([group$f(concat$g([printOpeningTagStart(node, options), " ", node.value.replace(/^html\b/i, "html").replace(/\s+/g, " ")])), printClosingTagEnd(node, options)]);
42376 return concat$g([printOpeningTagPrefix(node, options), concat$g(replaceEndOfLineWith$2(options.originalText.slice(options.locStart(node), options.locEnd(node)), literalline$6)), printClosingTagSuffix(node, options)]);
42381 if (node.value === null) {
42382 return node.rawName;
42385 var _value = unescapeQuoteEntities$1(node.value);
42387 var singleQuoteCount = countChars$1(_value, "'");
42388 var doubleQuoteCount = countChars$1(_value, '"');
42389 var quote = singleQuoteCount < doubleQuoteCount ? "'" : '"';
42390 return concat$g([node.rawName, concat$g(["=", quote, concat$g(replaceEndOfLineWith$2(quote === '"' ? _value.replace(/"/g, """) : _value.replace(/'/g, "'"), literalline$6)), quote])]);
42395 return concat$g(replaceEndOfLineWith$2(node.raw, literalline$6));
42398 throw new Error(`Unexpected node type ${node.type}`);
42402 function printChildren$2(path, options, print) {
42403 var node = path.getValue();
42405 if (forceBreakChildren$1(node)) {
42406 return concat$g([breakParent$4, concat$g(path.map(function (childPath) {
42407 var childNode = childPath.getValue();
42408 var prevBetweenLine = !childNode.prev ? "" : printBetweenLine(childNode.prev, childNode);
42409 return concat$g([!prevBetweenLine ? "" : concat$g([prevBetweenLine, forceNextEmptyLine$1(childNode.prev) ? hardline$c : ""]), printChild(childPath)]);
42413 var groupIds = node.children.map(function () {
42416 return concat$g(path.map(function (childPath, childIndex) {
42417 var childNode = childPath.getValue();
42419 if (isTextLikeNode$1(childNode)) {
42420 if (childNode.prev && isTextLikeNode$1(childNode.prev)) {
42421 var _prevBetweenLine = printBetweenLine(childNode.prev, childNode);
42423 if (_prevBetweenLine) {
42424 if (forceNextEmptyLine$1(childNode.prev)) {
42425 return concat$g([hardline$c, hardline$c, printChild(childPath)]);
42428 return concat$g([_prevBetweenLine, printChild(childPath)]);
42432 return printChild(childPath);
42435 var prevParts = [];
42436 var leadingParts = [];
42437 var trailingParts = [];
42438 var nextParts = [];
42439 var prevBetweenLine = childNode.prev ? printBetweenLine(childNode.prev, childNode) : "";
42440 var nextBetweenLine = childNode.next ? printBetweenLine(childNode, childNode.next) : "";
42442 if (prevBetweenLine) {
42443 if (forceNextEmptyLine$1(childNode.prev)) {
42444 prevParts.push(hardline$c, hardline$c);
42445 } else if (prevBetweenLine === hardline$c) {
42446 prevParts.push(hardline$c);
42448 if (isTextLikeNode$1(childNode.prev)) {
42449 leadingParts.push(prevBetweenLine);
42451 leadingParts.push(ifBreak$7("", softline$7, {
42452 groupId: groupIds[childIndex - 1]
42458 if (nextBetweenLine) {
42459 if (forceNextEmptyLine$1(childNode)) {
42460 if (isTextLikeNode$1(childNode.next)) {
42461 nextParts.push(hardline$c, hardline$c);
42463 } else if (nextBetweenLine === hardline$c) {
42464 if (isTextLikeNode$1(childNode.next)) {
42465 nextParts.push(hardline$c);
42468 trailingParts.push(nextBetweenLine);
42472 return concat$g([].concat(prevParts, group$f(concat$g([concat$g(leadingParts), group$f(concat$g([printChild(childPath), concat$g(trailingParts)]), {
42473 id: groupIds[childIndex]
42474 })])), nextParts));
42477 function printChild(childPath) {
42478 var child = childPath.getValue();
42480 if (hasPrettierIgnore$4(child)) {
42481 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)));
42484 if (shouldPreserveContent$1(child, options)) {
42485 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)));
42488 return print(childPath);
42491 function printBetweenLine(prevNode, nextNode) {
42492 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) && (
42498 nextNode.firstChild ||
42504 nextNode.isSelfClosing ||
42510 nextNode.type === "element" && nextNode.attrs.length !== 0) ||
42517 prevNode.type === "element" && prevNode.isSelfClosing && needsToBorrowPrevClosingTagEndMarker(nextNode) ? "" : !nextNode.isLeadingSpaceSensitive || preferHardlineAsLeadingSpaces$1(nextNode) ||
42519 * Want to write us a letter? Use our<a
42520 * ><b><a>mailing address</a></b></a
42524 needsToBorrowPrevClosingTagEndMarker(nextNode) && prevNode.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild) && prevNode.lastChild.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild.lastChild) ? hardline$c : nextNode.hasLeadingSpaces ? line$8 : softline$7;
42528 function printOpeningTag(path, options, print) {
42529 var node = path.getValue();
42530 var forceNotToBreakAttrContent = node.type === "element" && node.fullName === "script" && node.attrs.length === 1 && node.attrs[0].fullName === "src" && node.children.length === 0;
42531 return concat$g([printOpeningTagStart(node, options), !node.attrs || node.attrs.length === 0 ? node.isSelfClosing ?
42536 " " : "" : concat$g([indent$9(concat$g([forceNotToBreakAttrContent ? " " : line$8, join$b(line$8, function (ignoreAttributeData) {
42537 var hasPrettierIgnoreAttribute = typeof ignoreAttributeData === "boolean" ? function () {
42538 return ignoreAttributeData;
42539 } : Array.isArray(ignoreAttributeData) ? function (attr) {
42540 return ignoreAttributeData.indexOf(attr.rawName) !== -1;
42544 return path.map(function (attrPath) {
42545 var attr = attrPath.getValue();
42546 return hasPrettierIgnoreAttribute(attr) ? concat$g(replaceEndOfLineWith$2(options.originalText.slice(options.locStart(attr), options.locEnd(attr)), literalline$6)) : print(attrPath);
42548 }(node.prev && node.prev.type === "comment" && getPrettierIgnoreAttributeCommentData$1(node.prev.value)))])),
42555 node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ||
42562 node.isSelfClosing && needsToBorrowLastChildClosingTagEndMarker(node.parent) ? "" : node.isSelfClosing ? forceNotToBreakAttrContent ? " " : line$8 : forceNotToBreakAttrContent ? "" : softline$7]), node.isSelfClosing ? "" : printOpeningTagEnd(node)]);
42565 function printOpeningTagStart(node, options) {
42566 return node.prev && needsToBorrowNextOpeningTagStartMarker(node.prev) ? "" : concat$g([printOpeningTagPrefix(node, options), printOpeningTagStartMarker(node)]);
42569 function printOpeningTagEnd(node) {
42570 return node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ? "" : printOpeningTagEndMarker(node);
42573 function printClosingTag(node, options) {
42574 return concat$g([node.isSelfClosing ? "" : printClosingTagStart(node, options), printClosingTagEnd(node, options)]);
42577 function printClosingTagStart(node, options) {
42578 return node.lastChild && needsToBorrowParentClosingTagStartMarker(node.lastChild) ? "" : concat$g([printClosingTagPrefix(node, options), printClosingTagStartMarker(node, options)]);
42581 function printClosingTagEnd(node, options) {
42582 return (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? "" : concat$g([printClosingTagEndMarker(node, options), printClosingTagSuffix(node, options)]);
42585 function needsToBorrowNextOpeningTagStartMarker(node) {
42591 return node.next && !isTextLikeNode$1(node.next) && isTextLikeNode$1(node) && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces;
42594 function needsToBorrowParentOpeningTagEndMarker(node) {
42604 return !node.prev && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
42607 function needsToBorrowPrevClosingTagEndMarker(node) {
42617 return node.prev && !isTextLikeNode$1(node.prev) && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
42620 function needsToBorrowLastChildClosingTagEndMarker(node) {
42628 return node.lastChild && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces && !isTextLikeNode$1(getLastDescendant$1(node.lastChild));
42631 function needsToBorrowParentClosingTagStartMarker(node) {
42643 return !node.next && !node.hasTrailingSpaces && node.isTrailingSpaceSensitive && isTextLikeNode$1(getLastDescendant$1(node));
42646 function printOpeningTagPrefix(node, options) {
42647 return needsToBorrowParentOpeningTagEndMarker(node) ? printOpeningTagEndMarker(node.parent) : needsToBorrowPrevClosingTagEndMarker(node) ? printClosingTagEndMarker(node.prev, options) : "";
42650 function printClosingTagPrefix(node, options) {
42651 return needsToBorrowLastChildClosingTagEndMarker(node) ? printClosingTagEndMarker(node.lastChild, options) : "";
42654 function printClosingTagSuffix(node, options) {
42655 return needsToBorrowParentClosingTagStartMarker(node) ? printClosingTagStartMarker(node.parent, options) : needsToBorrowNextOpeningTagStartMarker(node) ? printOpeningTagStartMarker(node.next) : "";
42658 function printOpeningTagStartMarker(node) {
42659 switch (node.type) {
42660 case "ieConditionalComment":
42661 case "ieConditionalStartComment":
42662 return `<!--[if ${node.condition}`;
42664 case "ieConditionalEndComment":
42667 case "interpolation":
42671 return "<!DOCTYPE";
42674 if (node.condition) {
42675 return `<!--[if ${node.condition}]><!--><${node.rawName}`;
42681 return `<${node.rawName}`;
42685 function printOpeningTagEndMarker(node) {
42686 assert$1(!node.isSelfClosing);
42688 switch (node.type) {
42689 case "ieConditionalComment":
42693 if (node.condition) {
42694 return `><!--<![endif]-->`;
42704 function printClosingTagStartMarker(node, options) {
42705 assert$1(!node.isSelfClosing);
42707 if (shouldNotPrintClosingTag$1(node, options)) {
42711 switch (node.type) {
42712 case "ieConditionalComment":
42716 if (node.hasHtmComponentClosingTag) {
42723 return `</${node.rawName}`;
42727 function printClosingTagEndMarker(node, options) {
42728 if (shouldNotPrintClosingTag$1(node, options)) {
42732 switch (node.type) {
42733 case "ieConditionalComment":
42734 case "ieConditionalEndComment":
42735 return `[endif]-->`;
42737 case "ieConditionalStartComment":
42740 case "interpolation":
42744 if (node.isSelfClosing) {
42755 function getTextValueParts(node) {
42756 var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : node.value;
42757 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
42758 join$b(line$8, value.split(/[\t\n\f\r ]+/)).parts;
42761 function printEmbeddedAttributeValue(node, originalTextToDoc, options) {
42762 var isKeyMatched = function isKeyMatched(patterns) {
42763 return new RegExp(patterns.join("|")).test(node.fullName);
42766 var getValue = function getValue() {
42767 return unescapeQuoteEntities$1(node.value);
42770 var shouldHug = false;
42772 var __onHtmlBindingRoot = function __onHtmlBindingRoot(root) {
42773 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;
42775 if (rootNode && (rootNode.type === "ObjectExpression" || rootNode.type === "ArrayExpression")) {
42780 var printHug = function printHug(doc) {
42781 return group$f(doc);
42784 var printExpand = function printExpand(doc) {
42785 return group$f(concat$g([indent$9(concat$g([softline$7, doc])), softline$7]));
42788 var printMaybeHug = function printMaybeHug(doc) {
42789 return shouldHug ? printHug(doc) : printExpand(doc);
42792 var textToDoc = function textToDoc(code, opts) {
42793 return originalTextToDoc(code, Object.assign({
42794 __onHtmlBindingRoot
42798 if (node.fullName === "srcset" && (node.parent.fullName === "img" || node.parent.fullName === "source")) {
42799 return printExpand(printImgSrcset$1(getValue()));
42802 if (options.parser === "vue") {
42803 if (node.fullName === "v-for") {
42804 return printVueFor$1(getValue(), textToDoc);
42807 if (node.fullName === "slot-scope") {
42808 return printVueSlotScope$1(getValue(), textToDoc);
42811 * @click="jsStatement"
42812 * @click="jsExpression"
42813 * v-on:click="jsStatement"
42814 * v-on:click="jsExpression"
42818 var vueEventBindingPatterns = ["^@", "^v-on:"];
42820 * :class="vueExpression"
42821 * v-bind:id="vueExpression"
42824 var vueExpressionBindingPatterns = ["^:", "^v-bind:"];
42826 * v-if="jsExpression"
42829 var jsExpressionBindingPatterns = ["^v-"];
42831 if (isKeyMatched(vueEventBindingPatterns)) {
42832 var value = getValue();
42833 return printMaybeHug(isVueEventBindingExpression$3(value) ? textToDoc(value, {
42834 parser: "__js_expression"
42835 }) : stripTrailingHardline$2(textToDoc(value, {
42836 parser: "__vue_event_binding"
42840 if (isKeyMatched(vueExpressionBindingPatterns)) {
42841 return printMaybeHug(textToDoc(getValue(), {
42842 parser: "__vue_expression"
42846 if (isKeyMatched(jsExpressionBindingPatterns)) {
42847 return printMaybeHug(textToDoc(getValue(), {
42848 parser: "__js_expression"
42853 if (options.parser === "angular") {
42854 var ngTextToDoc = function ngTextToDoc(code, opts) {
42855 return (// angular does not allow trailing comma
42856 textToDoc(code, Object.assign({
42857 trailingComma: "none"
42862 * *directive="angularDirective"
42866 var ngDirectiveBindingPatterns = ["^\\*"];
42868 * (click)="angularStatement"
42869 * on-click="angularStatement"
42872 var ngStatementBindingPatterns = ["^\\(.+\\)$", "^on-"];
42874 * [target]="angularExpression"
42875 * bind-target="angularExpression"
42876 * [(target)]="angularExpression"
42877 * bindon-target="angularExpression"
42880 var ngExpressionBindingPatterns = ["^\\[.+\\]$", "^bind(on)?-"];
42882 * i18n="longDescription"
42883 * i18n-attr="longDescription"
42886 var ngI18nPatterns = ["^i18n(-.+)?$"];
42888 if (isKeyMatched(ngStatementBindingPatterns)) {
42889 return printMaybeHug(ngTextToDoc(getValue(), {
42890 parser: "__ng_action"
42894 if (isKeyMatched(ngExpressionBindingPatterns)) {
42895 return printMaybeHug(ngTextToDoc(getValue(), {
42896 parser: "__ng_binding"
42900 if (isKeyMatched(ngI18nPatterns)) {
42901 return printExpand(fill$5(getTextValueParts(node, getValue())));
42904 if (isKeyMatched(ngDirectiveBindingPatterns)) {
42905 return printMaybeHug(ngTextToDoc(getValue(), {
42906 parser: "__ng_directive"
42910 var interpolationRegex = /\{\{([\s\S]+?)\}\}/g;
42912 var _value2 = getValue();
42914 if (interpolationRegex.test(_value2)) {
42917 _value2.split(interpolationRegex).forEach(function (part, index) {
42918 if (index % 2 === 0) {
42919 parts.push(concat$g(replaceEndOfLineWith$2(part, literalline$6)));
42922 parts.push(group$f(concat$g(["{{", indent$9(concat$g([line$8, ngTextToDoc(part, {
42923 parser: "__ng_interpolation",
42924 __isInHtmlInterpolation: true // to avoid unexpected `}}`
42926 })])), line$8, "}}"])));
42928 parts.push("{{", concat$g(replaceEndOfLineWith$2(part, literalline$6)), "}}");
42933 return group$f(concat$g(parts));
42940 var printerHtml = {
42941 preprocess: preprocess_1$2,
42942 print: genericPrint$5,
42943 insertPragma: insertPragma$7,
42944 massageAstNode: clean$6,
42948 var CATEGORY_HTML = "HTML"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
42951 htmlWhitespaceSensitivity: {
42953 category: CATEGORY_HTML,
42956 description: "How to handle whitespaces in HTML.",
42959 description: "Respect the default value of CSS display property."
42962 description: "Whitespaces are considered sensitive."
42965 description: "Whitespaces are considered insensitive."
42968 vueIndentScriptAndStyle: {
42970 category: CATEGORY_HTML,
42973 description: "Indent script and style tags in Vue files."
42977 var name$g = "HTML";
42978 var type$e = "markup";
42979 var tmScope$e = "text.html.basic";
42980 var aceMode$e = "html";
42981 var codemirrorMode$b = "htmlmixed";
42982 var codemirrorMimeType$b = "text/html";
42983 var color$3 = "#e34c26";
42987 var extensions$e = [
42996 var languageId$e = 146;
43000 tmScope: tmScope$e,
43001 aceMode: aceMode$e,
43002 codemirrorMode: codemirrorMode$b,
43003 codemirrorMimeType: codemirrorMimeType$b,
43005 aliases: aliases$5,
43006 extensions: extensions$e,
43007 languageId: languageId$e
43010 var HTML$1 = /*#__PURE__*/Object.freeze({
43014 tmScope: tmScope$e,
43015 aceMode: aceMode$e,
43016 codemirrorMode: codemirrorMode$b,
43017 codemirrorMimeType: codemirrorMimeType$b,
43019 aliases: aliases$5,
43020 extensions: extensions$e,
43021 languageId: languageId$e,
43025 var name$h = "Vue";
43026 var type$f = "markup";
43027 var color$4 = "#2c3e50";
43028 var extensions$f = [
43031 var tmScope$f = "text.html.vue";
43032 var aceMode$f = "html";
43033 var languageId$f = 391;
43038 extensions: extensions$f,
43039 tmScope: tmScope$f,
43040 aceMode: aceMode$f,
43041 languageId: languageId$f
43044 var Vue$1 = /*#__PURE__*/Object.freeze({
43049 extensions: extensions$f,
43050 tmScope: tmScope$f,
43051 aceMode: aceMode$f,
43052 languageId: languageId$f,
43056 var require$$0$6 = getCjsExportFromNamespace(HTML$1);
43058 var require$$1$2 = getCjsExportFromNamespace(Vue$1);
43060 var languages$5 = [createLanguage(require$$0$6, function (data) {
43061 return Object.assign(data, {
43064 parsers: ["angular"],
43065 vscodeLanguageIds: ["html"],
43066 extensions: [".component.html"],
43069 }), createLanguage(require$$0$6, function (data) {
43070 return Object.assign(data, {
43073 vscodeLanguageIds: ["html"],
43074 extensions: data.extensions.concat([".mjml" // MJML is considered XML in Linguist but it should be formatted as HTML
43077 }), createLanguage(require$$0$6, function (data) {
43078 return Object.assign(data, {
43079 name: "Lightning Web Components",
43082 vscodeLanguageIds: ["html"],
43086 }), createLanguage(require$$1$2, function (data) {
43087 return Object.assign(data, {
43090 vscodeLanguageIds: ["vue"]
43096 var languageHtml = {
43097 languages: languages$5,
43098 printers: printers$5,
43102 function isPragma(text) {
43103 return /^\s*@(prettier|format)\s*$/.test(text);
43106 function hasPragma$4(text) {
43107 return /^\s*#[^\n\S]*@(prettier|format)\s*?(\n|$)/.test(text);
43110 function insertPragma$8(text) {
43111 return `# @format\n\n${text}`;
43116 hasPragma: hasPragma$4,
43117 insertPragma: insertPragma$8
43120 var getLast$4 = util.getLast;
43122 function getAncestorCount(path, filter) {
43124 var pathStackLength = path.stack.length - 1;
43126 for (var i = 0; i < pathStackLength; i++) {
43127 var value = path.stack[i];
43129 if (isNode$1(value) && filter(value)) {
43137 * @param {any} value
43138 * @param {string[]=} types
43142 function isNode$1(value, types) {
43143 return value && typeof value.type === "string" && (!types || types.indexOf(value.type) !== -1);
43146 function mapNode(node, callback, parent) {
43147 return callback("children" in node ? Object.assign({}, node, {
43148 children: node.children.map(function (childNode) {
43149 return mapNode(childNode, callback, node);
43151 }) : node, parent);
43154 function defineShortcut(x, key, getter) {
43155 Object.defineProperty(x, key, {
43161 function isNextLineEmpty$5(node, text) {
43162 var newlineCount = 0;
43163 var textLength = text.length;
43165 for (var i = node.position.end.offset - 1; i < textLength; i++) {
43166 var char = text[i];
43168 if (char === "\n") {
43172 if (newlineCount === 1 && /\S/.test(char)) {
43176 if (newlineCount === 2) {
43184 function isLastDescendantNode(path) {
43185 var node = path.getValue();
43187 switch (node.type) {
43194 var pathStackLength = path.stack.length;
43196 for (var i = 1; i < pathStackLength; i++) {
43197 var item = path.stack[i];
43198 var parentItem = path.stack[i - 1];
43200 if (Array.isArray(parentItem) && typeof item === "number" && item !== parentItem.length - 1) {
43208 function getLastDescendantNode$1(node) {
43209 return "children" in node && node.children.length !== 0 ? getLastDescendantNode$1(getLast$4(node.children)) : node;
43212 function isPrettierIgnore$2(comment) {
43213 return comment.value.trim() === "prettier-ignore";
43216 function hasPrettierIgnore$5(path) {
43217 var node = path.getValue();
43219 if (node.type === "documentBody") {
43220 var document = path.getParentNode();
43221 return hasEndComments(document.head) && isPrettierIgnore$2(getLast$4(document.head.endComments));
43224 return hasLeadingComments(node) && isPrettierIgnore$2(getLast$4(node.leadingComments));
43227 function isEmptyNode(node) {
43228 return (!node.children || node.children.length === 0) && !hasComments(node);
43231 function hasComments(node) {
43232 return hasLeadingComments(node) || hasMiddleComments(node) || hasIndicatorComment(node) || hasTrailingComment$2(node) || hasEndComments(node);
43235 function hasLeadingComments(node) {
43236 return node && node.leadingComments && node.leadingComments.length !== 0;
43239 function hasMiddleComments(node) {
43240 return node && node.middleComments && node.middleComments.length !== 0;
43243 function hasIndicatorComment(node) {
43244 return node && node.indicatorComment;
43247 function hasTrailingComment$2(node) {
43248 return node && node.trailingComment;
43251 function hasEndComments(node) {
43252 return node && node.endComments && node.endComments.length !== 0;
43255 * " a b c d e f " -> [" a b", "c d", "e f "]
43259 function splitWithSingleSpace(text) {
43261 var lastPart = undefined;
43262 var _iteratorNormalCompletion = true;
43263 var _didIteratorError = false;
43264 var _iteratorError = undefined;
43267 for (var _iterator = text.split(/( +)/g)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
43268 var part = _step.value;
43270 if (part !== " ") {
43271 if (lastPart === " ") {
43274 parts.push((parts.pop() || "") + part);
43276 } else if (lastPart === undefined) {
43283 _didIteratorError = true;
43284 _iteratorError = err;
43287 if (!_iteratorNormalCompletion && _iterator.return != null) {
43288 _iterator.return();
43291 if (_didIteratorError) {
43292 throw _iteratorError;
43297 if (lastPart === " ") {
43298 parts.push((parts.pop() || "") + " ");
43301 if (parts[0] === "") {
43303 parts.unshift(" " + (parts.shift() || ""));
43309 function getFlowScalarLineContents(nodeType, content, options) {
43310 var rawLineContents = content.split("\n").map(function (lineContent, index, lineContents) {
43311 return index === 0 && index === lineContents.length - 1 ? lineContent : index !== 0 && index !== lineContents.length - 1 ? lineContent.trim() : index === 0 ? lineContent.trimRight() : lineContent.trimLeft();
43314 if (options.proseWrap === "preserve") {
43315 return rawLineContents.map(function (lineContent) {
43316 return lineContent.length === 0 ? [] : [lineContent];
43320 return rawLineContents.map(function (lineContent) {
43321 return lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent);
43322 }).reduce(function (reduced, lineContentWords, index) {
43323 return index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !( // trailing backslash in quoteDouble should be preserved
43324 nodeType === "quoteDouble" && getLast$4(getLast$4(reduced)).endsWith("\\")) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]);
43325 }, []).map(function (lineContentWords) {
43326 return options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords;
43330 function getBlockValueLineContents(node, _ref) {
43331 var parentIndent = _ref.parentIndent,
43332 isLastDescendant = _ref.isLastDescendant,
43333 options = _ref.options;
43334 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 `|`
43335 .match(/^[^\n]*?\n([\s\S]*)$/)[1];
43336 var leadingSpaceCount = node.indent === null ? function (match) {
43337 return match ? match[1].length : Infinity;
43338 }(content.match(/^( *)\S/m)) : node.indent - 1 + parentIndent;
43339 var rawLineContents = content.split("\n").map(function (lineContent) {
43340 return lineContent.slice(leadingSpaceCount);
43343 if (options.proseWrap === "preserve" || node.type === "blockLiteral") {
43344 return removeUnnecessaryTrailingNewlines(rawLineContents.map(function (lineContent) {
43345 return lineContent.length === 0 ? [] : [lineContent];
43349 return removeUnnecessaryTrailingNewlines(rawLineContents.map(function (lineContent) {
43350 return lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent);
43351 }).reduce(function (reduced, lineContentWords, index) {
43352 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]);
43353 }, []).map(function (lineContentWords) {
43354 return lineContentWords.reduce(function (reduced, word) {
43355 return (// disallow trailing spaces
43356 reduced.length !== 0 && /\s$/.test(getLast$4(reduced)) ? reduced.concat(reduced.pop() + " " + word) : reduced.concat(word)
43359 }).map(function (lineContentWords) {
43360 return options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords;
43363 function removeUnnecessaryTrailingNewlines(lineContents) {
43364 if (node.chomping === "keep") {
43365 return getLast$4(lineContents).length === 0 ? lineContents.slice(0, -1) : lineContents;
43368 var trailingNewlineCount = 0;
43370 for (var i = lineContents.length - 1; i >= 0; i--) {
43371 if (lineContents[i].length === 0) {
43372 trailingNewlineCount++;
43378 return trailingNewlineCount === 0 ? lineContents : trailingNewlineCount >= 2 && !isLastDescendant ? // next empty line
43379 lineContents.slice(0, -(trailingNewlineCount - 1)) : lineContents.slice(0, -trailingNewlineCount);
43384 getLast: getLast$4,
43390 isNextLineEmpty: isNextLineEmpty$5,
43391 isLastDescendantNode,
43392 getBlockValueLineContents,
43393 getFlowScalarLineContents,
43394 getLastDescendantNode: getLastDescendantNode$1,
43395 hasPrettierIgnore: hasPrettierIgnore$5,
43396 hasLeadingComments,
43398 hasIndicatorComment,
43399 hasTrailingComment: hasTrailingComment$2,
43403 var insertPragma$9 = pragma$5.insertPragma,
43404 isPragma$1 = pragma$5.isPragma;
43405 var getAncestorCount$1 = utils$6.getAncestorCount,
43406 getBlockValueLineContents$1 = utils$6.getBlockValueLineContents,
43407 getFlowScalarLineContents$1 = utils$6.getFlowScalarLineContents,
43408 getLast$5 = utils$6.getLast,
43409 getLastDescendantNode$2 = utils$6.getLastDescendantNode,
43410 hasLeadingComments$1 = utils$6.hasLeadingComments,
43411 hasMiddleComments$1 = utils$6.hasMiddleComments,
43412 hasIndicatorComment$1 = utils$6.hasIndicatorComment,
43413 hasTrailingComment$3 = utils$6.hasTrailingComment,
43414 hasEndComments$1 = utils$6.hasEndComments,
43415 hasPrettierIgnore$6 = utils$6.hasPrettierIgnore,
43416 isLastDescendantNode$1 = utils$6.isLastDescendantNode,
43417 isNextLineEmpty$6 = utils$6.isNextLineEmpty,
43418 isNode$2 = utils$6.isNode,
43419 isEmptyNode$1 = utils$6.isEmptyNode,
43420 defineShortcut$1 = utils$6.defineShortcut,
43421 mapNode$1 = utils$6.mapNode;
43422 var docBuilders$2 = doc.builders;
43423 var conditionalGroup$2 = docBuilders$2.conditionalGroup,
43424 breakParent$5 = docBuilders$2.breakParent,
43425 concat$h = docBuilders$2.concat,
43426 dedent$3 = docBuilders$2.dedent,
43427 dedentToRoot$3 = docBuilders$2.dedentToRoot,
43428 fill$6 = docBuilders$2.fill,
43429 group$g = docBuilders$2.group,
43430 hardline$d = docBuilders$2.hardline,
43431 ifBreak$8 = docBuilders$2.ifBreak,
43432 join$c = docBuilders$2.join,
43433 line$9 = docBuilders$2.line,
43434 lineSuffix$2 = docBuilders$2.lineSuffix,
43435 literalline$7 = docBuilders$2.literalline,
43436 markAsRoot$5 = docBuilders$2.markAsRoot,
43437 softline$8 = docBuilders$2.softline;
43438 var replaceEndOfLineWith$3 = util.replaceEndOfLineWith;
43440 function preprocess$3(ast) {
43441 return mapNode$1(ast, defineShortcuts);
43444 function defineShortcuts(node) {
43445 switch (node.type) {
43447 defineShortcut$1(node, "head", function () {
43448 return node.children[0];
43450 defineShortcut$1(node, "body", function () {
43451 return node.children[1];
43455 case "documentBody":
43456 case "sequenceItem":
43457 case "flowSequenceItem":
43459 case "mappingValue":
43460 defineShortcut$1(node, "content", function () {
43461 return node.children[0];
43465 case "mappingItem":
43466 case "flowMappingItem":
43467 defineShortcut$1(node, "key", function () {
43468 return node.children[0];
43470 defineShortcut$1(node, "value", function () {
43471 return node.children[1];
43479 function genericPrint$6(path, options, print) {
43480 var node = path.getValue();
43481 var parentNode = path.getParentNode();
43482 var tag = !node.tag ? "" : path.call(print, "tag");
43483 var anchor = !node.anchor ? "" : path.call(print, "anchor");
43484 var nextEmptyLine = isNode$2(node, ["mapping", "sequence", "comment", "directive", "mappingItem", "sequenceItem"]) && !isLastDescendantNode$1(path) ? printNextEmptyLine(path, options.originalText) : "";
43485 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"))])) : ""]);
43488 function _print(node, parentNode, path, options, print) {
43489 switch (node.type) {
43491 return concat$h([join$c(hardline$d, path.map(function (childPath, index) {
43492 var document = node.children[index];
43493 var nextDocument = node.children[index + 1];
43494 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, "---"])]);
43495 }, "children")), node.children.length === 0 || function (lastDescendantNode) {
43496 return isNode$2(lastDescendantNode, ["blockLiteral", "blockFolded"]) && lastDescendantNode.chomping === "keep";
43497 }(getLastDescendantNode$2(node)) ? "" : hardline$d]);
43501 var nextDocument = parentNode.children[path.getName() + 1];
43502 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));
43505 case "documentHead":
43506 return join$c(hardline$d, [].concat(path.map(print, "children"), path.map(print, "endComments")));
43508 case "documentBody":
43510 var children = join$c(hardline$d, path.map(print, "children")).parts;
43511 var endComments = join$c(hardline$d, path.map(print, "endComments")).parts;
43512 var separator = children.length === 0 || endComments.length === 0 ? "" : function (lastDescendantNode) {
43513 return isNode$2(lastDescendantNode, ["blockFolded", "blockLiteral"]) ? lastDescendantNode.chomping === "keep" ? // there's already a newline printed at the end of blockValue (chomping=keep, lastDescendant=true)
43514 "" : // an extra newline for better readability
43515 concat$h([hardline$d, hardline$d]) : hardline$d;
43516 }(getLastDescendantNode$2(node));
43517 return concat$h([].concat(children, separator, endComments));
43521 return concat$h(["%", join$c(" ", [node.name].concat(node.parameters))]);
43524 return concat$h(["#", node.value]);
43527 return concat$h(["*", node.value]);
43530 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
43533 return concat$h(["&", node.value]);
43536 return printFlowScalarContent(node.type, options.originalText.slice(node.position.start.offset, node.position.end.offset), options);
43538 case "quoteDouble":
43539 case "quoteSingle":
43541 var singleQuote = "'";
43542 var doubleQuote = '"';
43543 var raw = options.originalText.slice(node.position.start.offset + 1, node.position.end.offset - 1);
43545 if (node.type === "quoteSingle" && raw.includes("\\") || node.type === "quoteDouble" && /\\[^"]/.test(raw)) {
43546 // only quoteDouble can use escape chars
43547 // and quoteSingle do not need to escape backslashes
43548 var originalQuote = node.type === "quoteDouble" ? doubleQuote : singleQuote;
43549 return concat$h([originalQuote, printFlowScalarContent(node.type, raw, options), originalQuote]);
43550 } else if (raw.includes(doubleQuote)) {
43551 return concat$h([singleQuote, printFlowScalarContent(node.type, node.type === "quoteDouble" ? raw // double quote needs to be escaped by backslash in quoteDouble
43552 .replace(/\\"/g, doubleQuote).replace(/'/g, singleQuote.repeat(2)) : raw, options), singleQuote]);
43555 if (raw.includes(singleQuote)) {
43556 return concat$h([doubleQuote, printFlowScalarContent(node.type, node.type === "quoteSingle" ? // single quote needs to be escaped by 2 single quotes in quoteSingle
43557 raw.replace(/''/g, singleQuote) : raw, options), doubleQuote]);
43560 var quote = options.singleQuote ? singleQuote : doubleQuote;
43561 return concat$h([quote, printFlowScalarContent(node.type, raw, options), quote]);
43564 case "blockFolded":
43565 case "blockLiteral":
43567 var parentIndent = getAncestorCount$1(path, function (ancestorNode) {
43568 return isNode$2(ancestorNode, ["sequence", "mapping"]);
43570 var isLastDescendant = isLastDescendantNode$1(path);
43571 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, {
43575 }).reduce(function (reduced, lineWords, index, lineContents) {
43576 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) : "");
43581 return join$c(hardline$d, path.map(print, "children"));
43583 case "sequenceItem":
43584 return concat$h(["- ", align$3(2, !node.content ? "" : path.call(print, "content"))]);
43587 return !node.content ? "" : path.call(print, "content");
43589 case "mappingValue":
43590 return !node.content ? "" : path.call(print, "content");
43593 return join$c(hardline$d, path.map(print, "children"));
43595 case "mappingItem":
43596 case "flowMappingItem":
43598 var isEmptyMappingKey = isEmptyNode$1(node.key);
43599 var isEmptyMappingValue = isEmptyNode$1(node.value);
43601 if (isEmptyMappingKey && isEmptyMappingValue) {
43602 return concat$h([": "]);
43605 var key = path.call(print, "key");
43606 var value = path.call(print, "value");
43608 if (isEmptyMappingValue) {
43609 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)]);
43612 if (isEmptyMappingKey) {
43613 return concat$h([": ", align$3(2, value)]);
43616 var groupId = Symbol("mappingKey");
43617 var forceExplicitKey = hasLeadingComments$1(node.value) || !isInlineNode$1(node.key.content);
43618 return forceExplicitKey ? concat$h(["? ", align$3(2, key), hardline$d, join$c("", path.map(print, "value", "leadingComments").map(function (comment) {
43619 return concat$h([comment, hardline$d]);
43620 })), ": ", align$3(2, value)]) : // force singleline
43621 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), {
43623 })])), 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])), {
43628 case "flowMapping":
43629 case "flowSequence":
43631 var openMarker = node.type === "flowMapping" ? "{" : "[";
43632 var closeMarker = node.type === "flowMapping" ? "}" : "]";
43633 var bracketSpacing = node.type === "flowMapping" && node.children.length !== 0 && options.bracketSpacing ? line$9 : softline$8;
43635 var isLastItemEmptyMappingItem = node.children.length !== 0 && function (lastItem) {
43636 return lastItem.type === "flowMappingItem" && isEmptyNode$1(lastItem.key) && isEmptyNode$1(lastItem.value);
43637 }(getLast$5(node.children));
43639 return concat$h([openMarker, indent(concat$h([bracketSpacing, concat$h(path.map(function (childPath, index) {
43640 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) : ""])]);
43641 }, "children")), ifBreak$8(",", "")])), isLastItemEmptyMappingItem ? "" : bracketSpacing, closeMarker]);
43644 case "flowSequenceItem":
43645 return path.call(print, "content");
43646 // istanbul ignore next
43649 throw new Error(`Unexpected node type ${node.type}`);
43652 function indent(doc) {
43653 return docBuilders$2.align(" ".repeat(options.tabWidth), doc);
43657 function align$3(n, doc) {
43658 return typeof n === "number" && n > 0 ? docBuilders$2.align(" ".repeat(n), doc) : docBuilders$2.align(n, doc);
43661 function isInlineNode$1(node) {
43666 switch (node.type) {
43668 case "quoteDouble":
43669 case "quoteSingle":
43671 case "flowMapping":
43672 case "flowSequence":
43680 function isSingleLineNode(node) {
43685 switch (node.type) {
43687 case "quoteDouble":
43688 case "quoteSingle":
43689 return node.position.start.line === node.position.end.line;
43699 function shouldPrintDocumentBody(document) {
43700 return document.body.children.length !== 0 || hasEndComments$1(document.body);
43703 function shouldPrintDocumentEndMarker(document, nextDocument) {
43706 *... # trailingComment
43708 hasTrailingComment$3(document) || nextDocument && (
43714 nextDocument.head.children.length !== 0 ||
43720 hasEndComments$1(nextDocument.head))
43724 function shouldPrintDocumentHeadEndMarker(document, nextDocument, root, options) {
43728 * preserve the first document head end marker
43730 root.children[0] === document && /---(\s|$)/.test(options.originalText.slice(options.locStart(document), options.locStart(document) + 4)) ||
43735 document.head.children.length !== 0 ||
43740 hasEndComments$1(document.head) ||
43742 * --- # trailing comment
43744 hasTrailingComment$3(document.head)) {
43748 if (shouldPrintDocumentEndMarker(document, nextDocument)) {
43752 return nextDocument ? "root" : false;
43755 function isAbsolutelyPrintedAsSingleLineNode(node, options) {
43760 switch (node.type) {
43762 case "quoteSingle":
43763 case "quoteDouble":
43773 if (options.proseWrap === "preserve") {
43774 return node.position.start.line === node.position.end.line;
43777 if ( // backslash-newline
43778 /\\$/m.test(options.originalText.slice(node.position.start.offset, node.position.end.offset))) {
43782 switch (options.proseWrap) {
43784 return node.value.indexOf("\n") === -1;
43787 return !/[\n ]/.test(node.value);
43788 // istanbul ignore next
43795 function needsSpaceInFrontOfMappingValue(node) {
43796 return node.key.content && node.key.content.type === "alias";
43799 function printNextEmptyLine(path, originalText) {
43800 var node = path.getValue();
43801 var root = path.stack[0];
43802 root.isNextEmptyLinePrintedChecklist = root.isNextEmptyLinePrintedChecklist || [];
43804 if (!root.isNextEmptyLinePrintedChecklist[node.position.end.line]) {
43805 if (isNextLineEmpty$6(node, originalText)) {
43806 root.isNextEmptyLinePrintedChecklist[node.position.end.line] = true;
43814 function printFlowScalarContent(nodeType, content, options) {
43815 var lineContents = getFlowScalarLineContents$1(nodeType, content, options);
43816 return join$c(hardline$d, lineContents.map(function (lineContentWords) {
43817 return fill$6(join$c(line$9, lineContentWords).parts);
43821 function clean$7(node, newNode
43824 if (isNode$2(newNode)) {
43825 delete newNode.position;
43827 switch (newNode.type) {
43830 if (isPragma$1(newNode.value)) {
43836 case "quoteDouble":
43837 case "quoteSingle":
43838 newNode.type = "quote";
43844 var printerYaml = {
43845 preprocess: preprocess$3,
43846 print: genericPrint$6,
43847 massageAstNode: clean$7,
43848 insertPragma: insertPragma$9
43852 bracketSpacing: commonOptions.bracketSpacing,
43853 singleQuote: commonOptions.singleQuote,
43854 proseWrap: commonOptions.proseWrap
43857 var name$i = "YAML";
43858 var type$g = "data";
43859 var tmScope$g = "source.yaml";
43863 var extensions$g = [
43871 ".yaml-tmlanguage",
43874 var filenames$4 = [
43880 var aceMode$g = "yaml";
43881 var codemirrorMode$c = "yaml";
43882 var codemirrorMimeType$c = "text/x-yaml";
43883 var languageId$g = 407;
43887 tmScope: tmScope$g,
43888 aliases: aliases$6,
43889 extensions: extensions$g,
43890 filenames: filenames$4,
43891 aceMode: aceMode$g,
43892 codemirrorMode: codemirrorMode$c,
43893 codemirrorMimeType: codemirrorMimeType$c,
43894 languageId: languageId$g
43897 var YAML$1 = /*#__PURE__*/Object.freeze({
43901 tmScope: tmScope$g,
43902 aliases: aliases$6,
43903 extensions: extensions$g,
43904 filenames: filenames$4,
43905 aceMode: aceMode$g,
43906 codemirrorMode: codemirrorMode$c,
43907 codemirrorMimeType: codemirrorMimeType$c,
43908 languageId: languageId$g,
43912 var require$$0$7 = getCjsExportFromNamespace(YAML$1);
43914 var languages$6 = [createLanguage(require$$0$7, function (data) {
43915 return Object.assign(data, {
43918 vscodeLanguageIds: ["yaml"]
43921 var languageYaml = {
43922 languages: languages$6,
43929 // plugin will look for `eval("require")()` and transform to `require()` in the bundle,
43930 // and rewrite the paths to require from the top-level.
43931 // We need to list the parsers and getters so we can load them only when necessary.
43934 var internalPlugins = [// JS
43939 return require("./parser-babylon").parsers.babel;
43942 get "babel-flow"() {
43943 return require("./parser-babylon").parsers["babel-flow"];
43947 return require("./parser-babylon").parsers.babel;
43951 return require("./parser-babylon").parsers.json;
43955 return require("./parser-babylon").parsers.json5;
43958 get "json-stringify"() {
43959 return require("./parser-babylon").parsers["json-stringify"];
43962 get __js_expression() {
43963 return require("./parser-babylon").parsers.__js_expression;
43966 get __vue_expression() {
43967 return require("./parser-babylon").parsers.__vue_expression;
43970 get __vue_event_binding() {
43971 return require("./parser-babylon").parsers.__vue_event_binding;
43976 return require("./parser-flow").parsers.flow;
43981 return require("./parser-typescript").parsers.typescript;
43985 * TODO: Remove this old alias in a major version
43987 get "typescript-eslint"() {
43988 return require("./parser-typescript").parsers.typescript;
43991 // JS - Angular Action
43992 get __ng_action() {
43993 return require("./parser-angular").parsers.__ng_action;
43996 // JS - Angular Binding
43997 get __ng_binding() {
43998 return require("./parser-angular").parsers.__ng_binding;
44001 // JS - Angular Interpolation
44002 get __ng_interpolation() {
44003 return require("./parser-angular").parsers.__ng_interpolation;
44006 // JS - Angular Directive
44007 get __ng_directive() {
44008 return require("./parser-angular").parsers.__ng_directive;
44015 // TODO: switch these to just `postcss` and use `language` instead.
44017 return require("./parser-postcss").parsers.css;
44021 return require("./parser-postcss").parsers.css;
44025 return require("./parser-postcss").parsers.css;
44030 languageHandlebars, {
44033 return require("./parser-glimmer").parsers.glimmer;
44041 return require("./parser-graphql").parsers.graphql;
44046 languageMarkdown, {
44049 return require("./parser-markdown").parsers.remark;
44052 // TODO: Delete this in 2.0
44054 return require("./parser-markdown").parsers.remark;
44058 return require("./parser-markdown").parsers.mdx;
44066 return require("./parser-html").parsers.html;
44071 return require("./parser-html").parsers.vue;
44076 return require("./parser-html").parsers.angular;
44079 // Lightning Web Components
44081 return require("./parser-html").parsers.lwc;
44089 return require("./parser-yaml").parsers.yaml;
44095 var partition = function partition(array, fn) {
44098 array.forEach(function (item) {
44108 function loadPlugins(plugins, pluginSearchDirs) {
44113 if (!pluginSearchDirs) {
44114 pluginSearchDirs = [];
44115 } // unless pluginSearchDirs are provided, auto-load plugins from node_modules that are parent to Prettier
44118 if (!pluginSearchDirs.length) {
44119 var autoLoadDir = thirdParty.findParentDir(__dirname, "node_modules");
44122 pluginSearchDirs = [autoLoadDir];
44126 var _partition = partition(plugins, function (plugin) {
44127 return typeof plugin === "string";
44129 _partition2 = _slicedToArray(_partition, 2),
44130 externalPluginNames = _partition2[0],
44131 externalPluginInstances = _partition2[1];
44133 var externalManualLoadPluginInfos = externalPluginNames.map(function (pluginName) {
44138 requirePath = resolve.sync(path$2.resolve(process.cwd(), pluginName));
44140 // try node modules
44141 requirePath = resolve.sync(pluginName, {
44142 basedir: process.cwd()
44151 var externalAutoLoadPluginInfos = pluginSearchDirs.map(function (pluginSearchDir) {
44152 var resolvedPluginSearchDir = path$2.resolve(process.cwd(), pluginSearchDir);
44153 var nodeModulesDir = path$2.resolve(resolvedPluginSearchDir, "node_modules"); // In some fringe cases (ex: files "mounted" as virtual directories), the
44154 // isDirectory(resolvedPluginSearchDir) check might be false even though
44155 // the node_modules actually exists.
44157 if (!isDirectory(nodeModulesDir) && !isDirectory(resolvedPluginSearchDir)) {
44158 throw new Error(`${pluginSearchDir} does not exist or is not a directory`);
44161 return findPluginsInNodeModules(nodeModulesDir).map(function (pluginName) {
44164 requirePath: resolve.sync(pluginName, {
44165 basedir: resolvedPluginSearchDir
44169 }).reduce(function (a, b) {
44170 return a.concat(b);
44172 var externalPlugins = lodash_uniqby(externalManualLoadPluginInfos.concat(externalAutoLoadPluginInfos), "requirePath").map(function (externalPluginInfo) {
44173 return Object.assign({
44174 name: externalPluginInfo.name
44175 }, require(externalPluginInfo.requirePath));
44176 }).concat(externalPluginInstances);
44177 return internalPlugins.concat(externalPlugins);
44180 function findPluginsInNodeModules(nodeModulesDir) {
44181 var pluginPackageJsonPaths = globby.sync(["prettier-plugin-*/package.json", "@*/prettier-plugin-*/package.json", "@prettier/plugin-*/package.json"], {
44182 cwd: nodeModulesDir
44184 return pluginPackageJsonPaths.map(path$2.dirname);
44187 function isDirectory(dir) {
44189 return fs$1.statSync(dir).isDirectory();
44195 var loadPlugins_1 = loadPlugins;
44197 var version$3 = require$$0.version;
44198 var getSupportInfo$2 = support.getSupportInfo; // Luckily `opts` is always the 2nd argument
44200 function _withPlugins(fn) {
44201 return function () {
44202 var args = Array.from(arguments);
44203 var opts = args[1] || {};
44204 args[1] = Object.assign({}, opts, {
44205 plugins: loadPlugins_1(opts.plugins, opts.pluginSearchDirs)
44207 return fn.apply(null, args);
44211 function withPlugins(fn) {
44212 var resultingFn = _withPlugins(fn);
44215 resultingFn.sync = _withPlugins(fn.sync);
44218 return resultingFn;
44221 var formatWithCursor = withPlugins(core.formatWithCursor);
44225 format(text, opts) {
44226 return formatWithCursor(text, opts).formatted;
44229 check: function check(text, opts) {
44230 var formatted = formatWithCursor(text, opts).formatted;
44231 return formatted === text;
44234 resolveConfig: resolveConfig_1.resolveConfig,
44235 resolveConfigFile: resolveConfig_1.resolveConfigFile,
44236 clearConfigCache: resolveConfig_1.clearCache,
44237 getFileInfo: withPlugins(getFileInfo_1),
44238 getSupportInfo: withPlugins(getSupportInfo$2),
44239 version: version$3,
44242 /* istanbul ignore next */
44244 parse: withPlugins(core.parse),
44245 formatAST: withPlugins(core.formatAST),
44246 formatDoc: withPlugins(core.formatDoc),
44247 printToDoc: withPlugins(core.printToDoc),
44248 printDocToString: withPlugins(core.printDocToString)
44252 var prettier = src$1;
44254 module.exports = prettier;