1 (function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3 typeof define === 'function' && define.amd ? define(factory) :
4 (global = global || self, global.prettier = factory());
5 }(this, (function () { 'use strict';
9 var description = "Prettier is an opinionated code formatter";
10 var bin = "./bin/prettier.js";
11 var repository = "prettier/prettier";
12 var homepage = "https://prettier.io";
13 var author = "James Long";
15 var main = "./index.js";
20 "@angular/compiler": "9.0.5",
21 "@babel/code-frame": "7.8.0",
22 "@babel/parser": "7.9.4",
23 "@glimmer/syntax": "0.50.0",
24 "@iarna/toml": "2.2.3",
25 "@typescript-eslint/typescript-estree": "2.26.0",
26 "angular-estree-parser": "1.3.0",
27 "angular-html-parser": "1.4.0",
30 "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540",
36 editorconfig: "0.15.3",
37 "editorconfig-to-prettier": "0.1.1",
38 "escape-string-regexp": "2.0.0",
41 "find-parent-dir": "0.3.0",
42 "find-project-root": "1.1.1",
43 "flow-parser": "0.122.0",
44 "get-stream": "5.1.0",
47 "html-element-attributes": "2.2.1",
48 "html-styles": "1.0.0",
49 "html-tag-names": "1.1.5",
51 "jest-docblock": "25.2.6",
52 "json-stable-stringify": "1.0.1",
54 "lines-and-columns": "1.1.6",
55 "linguist-languages": "7.9.0",
60 "n-readlines": "1.0.0",
61 "please-upgrade-node": "3.2.0",
62 "postcss-less": "3.1.4",
63 "postcss-media-query-parser": "0.2.3",
64 "postcss-scss": "2.0.0",
65 "postcss-selector-parser": "2.2.3",
66 "postcss-values-parser": "2.0.1",
67 "regexp-util": "1.2.2",
68 "remark-math": "1.0.6",
69 "remark-parse": "5.0.0",
73 "string-width": "4.2.0",
75 "unicode-regex": "3.0.0",
78 "yaml-unist-parser": "1.1.1"
80 var devDependencies = {
81 "@babel/core": "7.9.0",
82 "@babel/preset-env": "7.9.0",
83 "@rollup/plugin-alias": "3.0.1",
84 "@rollup/plugin-commonjs": "11.0.2",
85 "@rollup/plugin-json": "4.0.2",
86 "@rollup/plugin-node-resolve": "7.1.1",
87 "@rollup/plugin-replace": "2.3.1",
88 "babel-loader": "8.1.0",
90 "builtin-modules": "3.1.0",
95 "eslint-config-prettier": "6.10.1",
96 "eslint-formatter-friendly": "7.0.0",
97 "eslint-plugin-import": "2.20.2",
98 "eslint-plugin-prettier": "3.1.2",
99 "eslint-plugin-react": "7.19.0",
100 "eslint-plugin-unicorn": "18.0.1",
103 "jest-snapshot-serializer-ansi": "1.0.0",
104 "jest-snapshot-serializer-raw": "1.1.0",
105 "jest-watch-typeahead": "0.5.0",
109 "rollup-plugin-babel": "4.4.0",
110 "rollup-plugin-node-globals": "1.4.0",
111 "rollup-plugin-terser": "5.3.0",
113 "snapshot-diff": "0.7.0",
114 "strip-ansi": "6.0.0",
115 "synchronous-promise": "2.0.10",
117 "terser-webpack-plugin": "2.3.5",
121 prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1",
122 "prepare-release": "yarn && yarn build && yarn test:dist",
124 "test:dist": "cross-env NODE_ENV=production jest",
125 "test:dist-standalone": "cross-env NODE_ENV=production TEST_STANDALONE=1 jest tests/",
126 "test:integration": "jest tests_integration",
127 "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",
128 "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",
129 "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",
130 "lint:typecheck": "tsc",
131 "lint:eslint": "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly",
132 "lint:changelog": "node ./scripts/lint-changelog.js",
133 "lint:prettier": "prettier \"**/*.{md,json,yml,html,css}\" --check",
134 "lint:dist": "eslint --no-eslintrc --no-ignore --env=es6,browser --parser-options=ecmaVersion:2016 \"dist/!(bin-prettier|index|third-party).js\"",
135 "lint:spellcheck": "cspell {bin,scripts,src,website}/**/*.js {docs,website/blog,changelog_unreleased}/**/*.md",
136 "lint:deps": "node ./scripts/check-deps.js",
137 build: "node --max-old-space-size=3072 ./scripts/build/build.js",
138 "build-docs": "node ./scripts/build-docs.js"
143 description: description,
145 repository: repository,
151 dependencies: dependencies,
152 devDependencies: devDependencies,
156 var _package$1 = /*#__PURE__*/Object.freeze({
160 description: description,
162 repository: repository,
168 dependencies: dependencies,
169 devDependencies: devDependencies,
177 diff: function diff(oldString, newString) {
178 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
179 var callback = options.callback;
181 if (typeof options === 'function') {
186 this.options = options;
189 function done(value) {
191 setTimeout(function () {
192 callback(undefined, value);
198 } // Allow subclasses to massage the input prior to running
201 oldString = this.castInput(oldString);
202 newString = this.castInput(newString);
203 oldString = this.removeEmpty(this.tokenize(oldString));
204 newString = this.removeEmpty(this.tokenize(newString));
205 var newLen = newString.length,
206 oldLen = oldString.length;
208 var maxEditLength = newLen + oldLen;
212 }]; // Seed editLength = 0, i.e. the content starts with the same values
214 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
216 if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
217 // Identity per the equality and tokenizer
219 value: this.join(newString),
220 count: newString.length
222 } // Main worker method. checks all permutations of a given edit length for acceptance.
225 function execEditLength() {
226 for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
227 var basePath = void 0;
229 var addPath = bestPath[diagonalPath - 1],
230 removePath = bestPath[diagonalPath + 1],
231 _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
234 // No one else is going to attempt to use this value, clear it
235 bestPath[diagonalPath - 1] = undefined;
238 var canAdd = addPath && addPath.newPos + 1 < newLen,
239 canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
241 if (!canAdd && !canRemove) {
242 // If this path is a terminal then prune
243 bestPath[diagonalPath] = undefined;
245 } // Select the diagonal that we want to branch from. We select the prior
246 // path whose position in the new string is the farthest from the origin
247 // and does not pass the bounds of the diff graph
250 if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
251 basePath = clonePath(removePath);
252 self.pushComponent(basePath.components, undefined, true);
254 basePath = addPath; // No need to clone, we've pulled it from the list
257 self.pushComponent(basePath.components, true, undefined);
260 _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
262 if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
263 return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
265 // Otherwise track this path as a potential candidate and continue.
266 bestPath[diagonalPath] = basePath;
271 } // Performs the length of edit iteration. Is a bit fugly as this has to support the
272 // sync and async mode which is never fun. Loops over execEditLength until a value
278 setTimeout(function () {
279 // This should not happen, but we want to be safe.
281 /* istanbul ignore next */
282 if (editLength > maxEditLength) {
286 if (!execEditLength()) {
292 while (editLength <= maxEditLength) {
293 var ret = execEditLength();
301 pushComponent: function pushComponent(components, added, removed) {
302 var last = components[components.length - 1];
304 if (last && last.added === added && last.removed === removed) {
305 // We need to clone here as the component clone operation is just
306 // as shallow array clone
307 components[components.length - 1] = {
308 count: last.count + 1,
320 extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
321 var newLen = newString.length,
322 oldLen = oldString.length,
323 newPos = basePath.newPos,
324 oldPos = newPos - diagonalPath,
327 while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
334 basePath.components.push({
339 basePath.newPos = newPos;
342 equals: function equals(left, right) {
343 if (this.options.comparator) {
344 return this.options.comparator(left, right);
346 return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
349 removeEmpty: function removeEmpty(array) {
352 for (var i = 0; i < array.length; i++) {
360 castInput: function castInput(value) {
363 tokenize: function tokenize(value) {
364 return value.split('');
366 join: function join(chars) {
367 return chars.join('');
371 function buildValues(diff, components, newString, oldString, useLongestToken) {
372 var componentPos = 0,
373 componentLen = components.length,
377 for (; componentPos < componentLen; componentPos++) {
378 var component = components[componentPos];
380 if (!component.removed) {
381 if (!component.added && useLongestToken) {
382 var value = newString.slice(newPos, newPos + component.count);
383 value = value.map(function (value, i) {
384 var oldValue = oldString[oldPos + i];
385 return oldValue.length > value.length ? oldValue : value;
387 component.value = diff.join(value);
389 component.value = diff.join(newString.slice(newPos, newPos + component.count));
392 newPos += component.count; // Common case
394 if (!component.added) {
395 oldPos += component.count;
398 component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
399 oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
400 // The diffing algorithm is tied to add then remove output and this is the simplest
401 // route to get the desired output with minimal overhead.
403 if (componentPos && components[componentPos - 1].added) {
404 var tmp = components[componentPos - 1];
405 components[componentPos - 1] = components[componentPos];
406 components[componentPos] = tmp;
409 } // Special case handle for when one terminal is ignored (i.e. whitespace).
410 // For this case we merge the terminal into the prior string and drop the change.
411 // This is only available for string mode.
414 var lastComponent = components[componentLen - 1];
416 if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
417 components[componentLen - 2].value += lastComponent.value;
424 function clonePath(path) {
427 components: path.components.slice(0)
431 var characterDiff = new Diff();
433 function diffChars(oldStr, newStr, options) {
434 return characterDiff.diff(oldStr, newStr, options);
437 function generateOptions(options, defaults) {
438 if (typeof options === 'function') {
439 defaults.callback = options;
440 } else if (options) {
441 for (var name in options) {
442 /* istanbul ignore else */
443 if (options.hasOwnProperty(name)) {
444 defaults[name] = options[name];
451 // Ranges and exceptions:
452 // Latin-1 Supplement, 0080–00FF
453 // - U+00D7 × Multiplication sign
454 // - U+00F7 ÷ Division sign
455 // Latin Extended-A, 0100–017F
456 // Latin Extended-B, 0180–024F
457 // IPA Extensions, 0250–02AF
458 // Spacing Modifier Letters, 02B0–02FF
459 // - U+02C7 ˇ ˇ Caron
460 // - U+02D8 ˘ ˘ Breve
461 // - U+02D9 ˙ ˙ Dot Above
462 // - U+02DA ˚ ˚ Ring Above
463 // - U+02DB ˛ ˛ Ogonek
464 // - U+02DC ˜ ˜ Small Tilde
465 // - U+02DD ˝ ˝ Double Acute Accent
466 // Latin Extended Additional, 1E00–1EFF
469 var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
470 var reWhitespace = /\S/;
471 var wordDiff = new Diff();
473 wordDiff.equals = function (left, right) {
474 if (this.options.ignoreCase) {
475 left = left.toLowerCase();
476 right = right.toLowerCase();
479 return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
482 wordDiff.tokenize = function (value) {
483 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.
485 for (var i = 0; i < tokens.length - 1; i++) {
486 // If we have an empty string in the next field and we have only word chars before and after, merge
487 if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
488 tokens[i] += tokens[i + 2];
489 tokens.splice(i + 1, 2);
497 function diffWords(oldStr, newStr, options) {
498 options = generateOptions(options, {
499 ignoreWhitespace: true
501 return wordDiff.diff(oldStr, newStr, options);
504 function diffWordsWithSpace(oldStr, newStr, options) {
505 return wordDiff.diff(oldStr, newStr, options);
508 var lineDiff = new Diff();
510 lineDiff.tokenize = function (value) {
512 linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
514 if (!linesAndNewlines[linesAndNewlines.length - 1]) {
515 linesAndNewlines.pop();
516 } // Merge the content and line separators into single tokens
519 for (var i = 0; i < linesAndNewlines.length; i++) {
520 var line = linesAndNewlines[i];
522 if (i % 2 && !this.options.newlineIsToken) {
523 retLines[retLines.length - 1] += line;
525 if (this.options.ignoreWhitespace) {
536 function diffLines(oldStr, newStr, callback) {
537 return lineDiff.diff(oldStr, newStr, callback);
540 function diffTrimmedLines(oldStr, newStr, callback) {
541 var options = generateOptions(callback, {
542 ignoreWhitespace: true
544 return lineDiff.diff(oldStr, newStr, options);
547 var sentenceDiff = new Diff();
549 sentenceDiff.tokenize = function (value) {
550 return value.split(/(\S.+?[.!?])(?=\s+|$)/);
553 function diffSentences(oldStr, newStr, callback) {
554 return sentenceDiff.diff(oldStr, newStr, callback);
557 var cssDiff = new Diff();
559 cssDiff.tokenize = function (value) {
560 return value.split(/([{}:;,]|\s+)/);
563 function diffCss(oldStr, newStr, callback) {
564 return cssDiff.diff(oldStr, newStr, callback);
567 function _typeof(obj) {
568 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
569 _typeof = function _typeof(obj) {
573 _typeof = function _typeof(obj) {
574 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
581 function _toConsumableArray(arr) {
582 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
585 function _arrayWithoutHoles(arr) {
586 if (Array.isArray(arr)) {
587 for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
593 function _iterableToArray(iter) {
594 if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
597 function _nonIterableSpread() {
598 throw new TypeError("Invalid attempt to spread non-iterable instance");
601 var objectPrototypeToString = Object.prototype.toString;
602 var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
603 // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
605 jsonDiff.useLongestToken = true;
606 jsonDiff.tokenize = lineDiff.tokenize;
608 jsonDiff.castInput = function (value) {
609 var _this$options = this.options,
610 undefinedReplacement = _this$options.undefinedReplacement,
611 _this$options$stringi = _this$options.stringifyReplacer,
612 stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
613 return typeof v === 'undefined' ? undefinedReplacement : v;
614 } : _this$options$stringi;
615 return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
618 jsonDiff.equals = function (left, right) {
619 return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
622 function diffJson(oldObj, newObj, options) {
623 return jsonDiff.diff(oldObj, newObj, options);
624 } // This function handles the presence of circular references by bailing out when encountering an
625 // object that is already on the "stack" of items being processed. Accepts an optional replacer
628 function canonicalize(obj, stack, replacementStack, replacer, key) {
630 replacementStack = replacementStack || [];
633 obj = replacer(key, obj);
638 for (i = 0; i < stack.length; i += 1) {
639 if (stack[i] === obj) {
640 return replacementStack[i];
644 var canonicalizedObj;
646 if ('[object Array]' === objectPrototypeToString.call(obj)) {
648 canonicalizedObj = new Array(obj.length);
649 replacementStack.push(canonicalizedObj);
651 for (i = 0; i < obj.length; i += 1) {
652 canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
656 replacementStack.pop();
657 return canonicalizedObj;
660 if (obj && obj.toJSON) {
664 if (_typeof(obj) === 'object' && obj !== null) {
666 canonicalizedObj = {};
667 replacementStack.push(canonicalizedObj);
673 /* istanbul ignore else */
674 if (obj.hasOwnProperty(_key)) {
675 sortedKeys.push(_key);
681 for (i = 0; i < sortedKeys.length; i += 1) {
682 _key = sortedKeys[i];
683 canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
687 replacementStack.pop();
689 canonicalizedObj = obj;
692 return canonicalizedObj;
695 var arrayDiff = new Diff();
697 arrayDiff.tokenize = function (value) {
698 return value.slice();
701 arrayDiff.join = arrayDiff.removeEmpty = function (value) {
705 function diffArrays(oldArr, newArr, callback) {
706 return arrayDiff.diff(oldArr, newArr, callback);
709 function parsePatch(uniDiff) {
710 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
711 var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
712 delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
716 function parseIndex() {
718 list.push(index); // Parse diff metadata
720 while (i < diffstr.length) {
721 var line = diffstr[i]; // File header found, end parsing diff metadata
723 if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
728 var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
731 index.index = header[1];
735 } // Parse file headers if they are defined. Unified diff requires them, but
736 // there's no technical issues to have an isolated hunk without file header
739 parseFileHeader(index);
740 parseFileHeader(index); // Parse hunks
744 while (i < diffstr.length) {
745 var _line = diffstr[i];
747 if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
749 } else if (/^@@/.test(_line)) {
750 index.hunks.push(parseHunk());
751 } else if (_line && options.strict) {
752 // Ignore unexpected content unless in strict mode
753 throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
758 } // Parses the --- and +++ headers, if none are found, no lines
762 function parseFileHeader(index) {
763 var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
766 var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
767 var data = fileHeader[2].split('\t', 2);
768 var fileName = data[0].replace(/\\\\/g, '\\');
770 if (/^".*"$/.test(fileName)) {
771 fileName = fileName.substr(1, fileName.length - 2);
774 index[keyPrefix + 'FileName'] = fileName;
775 index[keyPrefix + 'Header'] = (data[1] || '').trim();
779 // This assumes that we are at the start of a hunk.
782 function parseHunk() {
783 var chunkHeaderIndex = i,
784 chunkHeaderLine = diffstr[i++],
785 chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
787 oldStart: +chunkHeader[1],
788 oldLines: +chunkHeader[2] || 1,
789 newStart: +chunkHeader[3],
790 newLines: +chunkHeader[4] || 1,
797 for (; i < diffstr.length; i++) {
798 // Lines starting with '---' could be mistaken for the "remove line" operation
799 // But they could be the header for the next file. Therefore prune such cases out.
800 if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
804 var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
806 if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
807 hunk.lines.push(diffstr[i]);
808 hunk.linedelimiters.push(delimiters[i] || '\n');
810 if (operation === '+') {
812 } else if (operation === '-') {
814 } else if (operation === ' ') {
821 } // Handle the empty block count case
824 if (!addCount && hunk.newLines === 1) {
828 if (!removeCount && hunk.oldLines === 1) {
830 } // Perform optional sanity checking
833 if (options.strict) {
834 if (addCount !== hunk.newLines) {
835 throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
838 if (removeCount !== hunk.oldLines) {
839 throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
846 while (i < diffstr.length) {
851 } // Iterator that traverses in the range of [min, max], stepping
852 // by distance from a given start position. I.e. for [0, 4], with
853 // start of 2, this will iterate 2, 3, 1, 4, 0.
856 function distanceIterator(start, minLine, maxLine) {
857 var wantForward = true,
858 backwardExhausted = false,
859 forwardExhausted = false,
861 return function iterator() {
862 if (wantForward && !forwardExhausted) {
863 if (backwardExhausted) {
867 } // Check if trying to fit beyond text length, and if not, check it fits
868 // after offset location (or desired location on first iteration)
871 if (start + localOffset <= maxLine) {
875 forwardExhausted = true;
878 if (!backwardExhausted) {
879 if (!forwardExhausted) {
881 } // Check if trying to fit before text beginning, and if not, check it fits
882 // before offset location
885 if (minLine <= start - localOffset) {
886 return -localOffset++;
889 backwardExhausted = true;
891 } // We tried to fit hunk before text beginning and beyond text length, then
892 // hunk can't fit on the text. Return undefined
897 function applyPatch(source, uniDiff) {
898 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
900 if (typeof uniDiff === 'string') {
901 uniDiff = parsePatch(uniDiff);
904 if (Array.isArray(uniDiff)) {
905 if (uniDiff.length > 1) {
906 throw new Error('applyPatch only works with a single input.');
909 uniDiff = uniDiff[0];
910 } // Apply the diff to the input
913 var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
914 delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
915 hunks = uniDiff.hunks,
916 compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
917 return line === patchContent;
920 fuzzFactor = options.fuzzFactor || 0,
926 * Checks if the hunk exactly fits on the provided location
930 function hunkFits(hunk, toPos) {
931 for (var j = 0; j < hunk.lines.length; j++) {
932 var line = hunk.lines[j],
933 operation = line.length > 0 ? line[0] : ' ',
934 content = line.length > 0 ? line.substr(1) : line;
936 if (operation === ' ' || operation === '-') {
937 // Context sanity check
938 if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
941 if (errorCount > fuzzFactor) {
951 } // Search best fit offsets for each hunk based on the previous ones
954 for (var i = 0; i < hunks.length; i++) {
956 maxLine = lines.length - hunk.oldLines,
958 toPos = offset + hunk.oldStart - 1;
959 var iterator = distanceIterator(toPos, minLine, maxLine);
961 for (; localOffset !== undefined; localOffset = iterator()) {
962 if (hunkFits(hunk, toPos + localOffset)) {
963 hunk.offset = offset += localOffset;
968 if (localOffset === undefined) {
970 } // Set lower text limit to end of the current hunk, so next ones don't try
971 // to fit over already patched text
974 minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
975 } // Apply patch hunks
980 for (var _i = 0; _i < hunks.length; _i++) {
981 var _hunk = hunks[_i],
982 _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
984 diffOffset += _hunk.newLines - _hunk.oldLines;
987 // Creating a new file
991 for (var j = 0; j < _hunk.lines.length; j++) {
992 var line = _hunk.lines[j],
993 operation = line.length > 0 ? line[0] : ' ',
994 content = line.length > 0 ? line.substr(1) : line,
995 delimiter = _hunk.linedelimiters[j];
997 if (operation === ' ') {
999 } else if (operation === '-') {
1000 lines.splice(_toPos, 1);
1001 delimiters.splice(_toPos, 1);
1002 /* istanbul ignore else */
1003 } else if (operation === '+') {
1004 lines.splice(_toPos, 0, content);
1005 delimiters.splice(_toPos, 0, delimiter);
1007 } else if (operation === '\\') {
1008 var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
1010 if (previousOperation === '+') {
1012 } else if (previousOperation === '-') {
1017 } // Handle EOFNL insertion/removal
1021 while (!lines[lines.length - 1]) {
1025 } else if (addEOFNL) {
1027 delimiters.push('\n');
1030 for (var _k = 0; _k < lines.length - 1; _k++) {
1031 lines[_k] = lines[_k] + delimiters[_k];
1034 return lines.join('');
1035 } // Wrapper that supports multiple file patches via callbacks.
1038 function applyPatches(uniDiff, options) {
1039 if (typeof uniDiff === 'string') {
1040 uniDiff = parsePatch(uniDiff);
1043 var currentIndex = 0;
1045 function processIndex() {
1046 var index = uniDiff[currentIndex++];
1049 return options.complete();
1052 options.loadFile(index, function (err, data) {
1054 return options.complete(err);
1057 var updatedContent = applyPatch(data, index, options);
1058 options.patched(index, updatedContent, function (err) {
1060 return options.complete(err);
1071 function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1076 if (typeof options.context === 'undefined') {
1077 options.context = 4;
1080 var diff = diffLines(oldStr, newStr, options);
1084 }); // Append an empty value to make cleanup easier
1086 function contextLines(lines) {
1087 return lines.map(function (entry) {
1093 var oldRangeStart = 0,
1099 var _loop = function _loop(i) {
1100 var current = diff[i],
1101 lines = current.lines || current.value.replace(/\n$/, '').split('\n');
1102 current.lines = lines;
1104 if (current.added || current.removed) {
1105 var _curRange; // If we have previous context, start with that
1108 if (!oldRangeStart) {
1109 var prev = diff[i - 1];
1110 oldRangeStart = oldLine;
1111 newRangeStart = newLine;
1114 curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
1115 oldRangeStart -= curRange.length;
1116 newRangeStart -= curRange.length;
1118 } // Output our changes
1121 (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
1122 return (current.added ? '+' : '-') + entry;
1123 }))); // Track the updated file position
1126 if (current.added) {
1127 newLine += lines.length;
1129 oldLine += lines.length;
1132 // Identical context lines. Track line changes
1133 if (oldRangeStart) {
1134 // Close out any changes that have been output (or join overlapping)
1135 if (lines.length <= options.context * 2 && i < diff.length - 2) {
1136 var _curRange2; // Overlapping
1139 (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
1141 var _curRange3; // end the range and output
1144 var contextSize = Math.min(lines.length, options.context);
1146 (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
1149 oldStart: oldRangeStart,
1150 oldLines: oldLine - oldRangeStart + contextSize,
1151 newStart: newRangeStart,
1152 newLines: newLine - newRangeStart + contextSize,
1156 if (i >= diff.length - 2 && lines.length <= options.context) {
1157 // EOF is inside this hunk
1158 var oldEOFNewline = /\n$/.test(oldStr);
1159 var newEOFNewline = /\n$/.test(newStr);
1160 var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
1162 if (!oldEOFNewline && noNlBeforeAdds) {
1163 // special case: old has no eol and no trailing context; no-nl can end up before adds
1164 curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
1167 if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
1168 curRange.push('\\ No newline at end of file');
1179 oldLine += lines.length;
1180 newLine += lines.length;
1184 for (var i = 0; i < diff.length; i++) {
1189 oldFileName: oldFileName,
1190 newFileName: newFileName,
1191 oldHeader: oldHeader,
1192 newHeader: newHeader,
1197 function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
1198 var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options);
1201 if (oldFileName == newFileName) {
1202 ret.push('Index: ' + oldFileName);
1205 ret.push('===================================================================');
1206 ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
1207 ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
1209 for (var i = 0; i < diff.hunks.length; i++) {
1210 var hunk = diff.hunks[i];
1211 ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
1212 ret.push.apply(ret, hunk.lines);
1215 return ret.join('\n') + '\n';
1218 function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
1219 return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
1222 function arrayEqual(a, b) {
1223 if (a.length !== b.length) {
1227 return arrayStartsWith(a, b);
1230 function arrayStartsWith(array, start) {
1231 if (start.length > array.length) {
1235 for (var i = 0; i < start.length; i++) {
1236 if (start[i] !== array[i]) {
1244 function calcLineCount(hunk) {
1245 var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
1246 oldLines = _calcOldNewLineCount.oldLines,
1247 newLines = _calcOldNewLineCount.newLines;
1249 if (oldLines !== undefined) {
1250 hunk.oldLines = oldLines;
1252 delete hunk.oldLines;
1255 if (newLines !== undefined) {
1256 hunk.newLines = newLines;
1258 delete hunk.newLines;
1262 function merge(mine, theirs, base) {
1263 mine = loadPatch(mine, base);
1264 theirs = loadPatch(theirs, base);
1265 var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
1266 // Leaving sanity checks on this to the API consumer that may know more about the
1267 // meaning in their own context.
1269 if (mine.index || theirs.index) {
1270 ret.index = mine.index || theirs.index;
1273 if (mine.newFileName || theirs.newFileName) {
1274 if (!fileNameChanged(mine)) {
1275 // No header or no change in ours, use theirs (and ours if theirs does not exist)
1276 ret.oldFileName = theirs.oldFileName || mine.oldFileName;
1277 ret.newFileName = theirs.newFileName || mine.newFileName;
1278 ret.oldHeader = theirs.oldHeader || mine.oldHeader;
1279 ret.newHeader = theirs.newHeader || mine.newHeader;
1280 } else if (!fileNameChanged(theirs)) {
1281 // No header or no change in theirs, use ours
1282 ret.oldFileName = mine.oldFileName;
1283 ret.newFileName = mine.newFileName;
1284 ret.oldHeader = mine.oldHeader;
1285 ret.newHeader = mine.newHeader;
1287 // Both changed... figure it out
1288 ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
1289 ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
1290 ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
1291 ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
1301 while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
1302 var mineCurrent = mine.hunks[mineIndex] || {
1305 theirsCurrent = theirs.hunks[theirsIndex] || {
1309 if (hunkBefore(mineCurrent, theirsCurrent)) {
1310 // This patch does not overlap with any of the others, yay.
1311 ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
1313 theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
1314 } else if (hunkBefore(theirsCurrent, mineCurrent)) {
1315 // This patch does not overlap with any of the others, yay.
1316 ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
1318 mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
1320 // Overlap, merge as best we can
1322 oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
1324 newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
1328 mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
1331 ret.hunks.push(mergedHunk);
1338 function loadPatch(param, base) {
1339 if (typeof param === 'string') {
1340 if (/^@@/m.test(param) || /^Index:/m.test(param)) {
1341 return parsePatch(param)[0];
1345 throw new Error('Must provide a base reference or pass in a patch');
1348 return structuredPatch(undefined, undefined, base, param);
1354 function fileNameChanged(patch) {
1355 return patch.newFileName && patch.newFileName !== patch.oldFileName;
1358 function selectField(index, mine, theirs) {
1359 if (mine === theirs) {
1362 index.conflict = true;
1370 function hunkBefore(test, check) {
1371 return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
1374 function cloneHunk(hunk, offset) {
1376 oldStart: hunk.oldStart,
1377 oldLines: hunk.oldLines,
1378 newStart: hunk.newStart + offset,
1379 newLines: hunk.newLines,
1384 function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
1385 // This will generally result in a conflicted hunk, but there are cases where the context
1386 // is the only overlap where we can successfully merge the content here.
1393 offset: theirOffset,
1396 }; // Handle any leading content
1398 insertLeading(hunk, mine, their);
1399 insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
1401 while (mine.index < mine.lines.length && their.index < their.lines.length) {
1402 var mineCurrent = mine.lines[mine.index],
1403 theirCurrent = their.lines[their.index];
1405 if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
1406 // Both modified ...
1407 mutualChange(hunk, mine, their);
1408 } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
1409 var _hunk$lines; // Mine inserted
1412 (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
1413 } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
1414 var _hunk$lines2; // Theirs inserted
1417 (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
1418 } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
1419 // Mine removed or edited
1420 removal(hunk, mine, their);
1421 } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
1422 // Their removed or edited
1423 removal(hunk, their, mine, true);
1424 } else if (mineCurrent === theirCurrent) {
1426 hunk.lines.push(mineCurrent);
1431 conflict(hunk, collectChange(mine), collectChange(their));
1433 } // Now push anything that may be remaining
1436 insertTrailing(hunk, mine);
1437 insertTrailing(hunk, their);
1438 calcLineCount(hunk);
1441 function mutualChange(hunk, mine, their) {
1442 var myChanges = collectChange(mine),
1443 theirChanges = collectChange(their);
1445 if (allRemoves(myChanges) && allRemoves(theirChanges)) {
1446 // Special case for remove changes that are supersets of one another
1447 if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
1450 (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
1453 } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
1456 (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
1460 } else if (arrayEqual(myChanges, theirChanges)) {
1463 (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
1468 conflict(hunk, myChanges, theirChanges);
1471 function removal(hunk, mine, their, swap) {
1472 var myChanges = collectChange(mine),
1473 theirChanges = collectContext(their, myChanges);
1475 if (theirChanges.merged) {
1478 (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
1480 conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
1484 function conflict(hunk, mine, their) {
1485 hunk.conflict = true;
1493 function insertLeading(hunk, insert, their) {
1494 while (insert.offset < their.offset && insert.index < insert.lines.length) {
1495 var line = insert.lines[insert.index++];
1496 hunk.lines.push(line);
1501 function insertTrailing(hunk, insert) {
1502 while (insert.index < insert.lines.length) {
1503 var line = insert.lines[insert.index++];
1504 hunk.lines.push(line);
1508 function collectChange(state) {
1510 operation = state.lines[state.index][0];
1512 while (state.index < state.lines.length) {
1513 var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
1515 if (operation === '-' && line[0] === '+') {
1519 if (operation === line[0]) {
1530 function collectContext(state, matchChanges) {
1534 contextChanges = false,
1537 while (matchIndex < matchChanges.length && state.index < state.lines.length) {
1538 var change = state.lines[state.index],
1539 match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
1541 if (match[0] === '+') {
1545 contextChanges = contextChanges || change[0] !== ' ';
1547 matchIndex++; // Consume any additions in the other block as a conflict to attempt
1548 // to pull in the remaining context after this
1550 if (change[0] === '+') {
1553 while (change[0] === '+') {
1554 changes.push(change);
1555 change = state.lines[++state.index];
1559 if (match.substr(1) === change.substr(1)) {
1560 changes.push(change);
1567 if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
1575 while (matchIndex < matchChanges.length) {
1576 merged.push(matchChanges[matchIndex++]);
1585 function allRemoves(changes) {
1586 return changes.reduce(function (prev, change) {
1587 return prev && change[0] === '-';
1591 function skipRemoveSuperset(state, removeChanges, delta) {
1592 for (var i = 0; i < delta; i++) {
1593 var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
1595 if (state.lines[state.index + i] !== ' ' + changeContent) {
1600 state.index += delta;
1604 function calcOldNewLineCount(lines) {
1607 lines.forEach(function (line) {
1608 if (typeof line !== 'string') {
1609 var myCount = calcOldNewLineCount(line.mine);
1610 var theirCount = calcOldNewLineCount(line.theirs);
1612 if (oldLines !== undefined) {
1613 if (myCount.oldLines === theirCount.oldLines) {
1614 oldLines += myCount.oldLines;
1616 oldLines = undefined;
1620 if (newLines !== undefined) {
1621 if (myCount.newLines === theirCount.newLines) {
1622 newLines += myCount.newLines;
1624 newLines = undefined;
1628 if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
1632 if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
1641 } // See: http://code.google.com/p/google-diff-match-patch/wiki/API
1644 function convertChangesToDMP(changes) {
1649 for (var i = 0; i < changes.length; i++) {
1650 change = changes[i];
1654 } else if (change.removed) {
1660 ret.push([operation, change.value]);
1666 function convertChangesToXML(changes) {
1669 for (var i = 0; i < changes.length; i++) {
1670 var change = changes[i];
1674 } else if (change.removed) {
1678 ret.push(escapeHTML(change.value));
1682 } else if (change.removed) {
1687 return ret.join('');
1690 function escapeHTML(s) {
1692 n = n.replace(/&/g, '&');
1693 n = n.replace(/</g, '<');
1694 n = n.replace(/>/g, '>');
1695 n = n.replace(/"/g, '"');
1699 var index_es6 = /*#__PURE__*/Object.freeze({
1702 diffChars: diffChars,
1703 diffWords: diffWords,
1704 diffWordsWithSpace: diffWordsWithSpace,
1705 diffLines: diffLines,
1706 diffTrimmedLines: diffTrimmedLines,
1707 diffSentences: diffSentences,
1710 diffArrays: diffArrays,
1711 structuredPatch: structuredPatch,
1712 createTwoFilesPatch: createTwoFilesPatch,
1713 createPatch: createPatch,
1714 applyPatch: applyPatch,
1715 applyPatches: applyPatches,
1716 parsePatch: parsePatch,
1718 convertChangesToDMP: convertChangesToDMP,
1719 convertChangesToXML: convertChangesToXML,
1720 canonicalize: canonicalize
1725 var _shim_fs$1 = /*#__PURE__*/Object.freeze({
1730 const sep = /[\\/]/;
1731 function extname(path) {
1732 const filename = basename(path);
1733 const dotIndex = filename.lastIndexOf(".");
1734 if (dotIndex === -1) return "";
1735 return filename.slice(dotIndex);
1737 function basename(path) {
1738 return path.split(sep).pop();
1740 function isAbsolute() {
1744 var path = /*#__PURE__*/Object.freeze({
1748 isAbsolute: isAbsolute
1751 var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
1755 var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
1760 var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
1762 for (var i = 0, len = code.length; i < len; ++i) {
1763 lookup[i] = code[i];
1764 revLookup[code.charCodeAt(i)] = i;
1767 revLookup['-'.charCodeAt(0)] = 62;
1768 revLookup['_'.charCodeAt(0)] = 63;
1771 function toByteArray(b64) {
1776 var i, j, l, tmp, placeHolders, arr;
1777 var len = b64.length;
1780 throw new Error('Invalid string. Length must be a multiple of 4');
1781 } // the number of equal signs (place holders)
1782 // if there are two placeholders, than the two characters before it
1783 // represent one byte
1784 // if there is only one, then the three characters before it represent 2 bytes
1785 // this is just a cheap hack to not do indexOf twice
1788 placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; // base64 is 4/3 + up to two characters of the original data
1790 arr = new Arr(len * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars
1792 l = placeHolders > 0 ? len - 4 : len;
1795 for (i = 0, j = 0; i < l; i += 4, j += 3) {
1796 tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
1797 arr[L++] = tmp >> 16 & 0xFF;
1798 arr[L++] = tmp >> 8 & 0xFF;
1799 arr[L++] = tmp & 0xFF;
1802 if (placeHolders === 2) {
1803 tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
1804 arr[L++] = tmp & 0xFF;
1805 } else if (placeHolders === 1) {
1806 tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
1807 arr[L++] = tmp >> 8 & 0xFF;
1808 arr[L++] = tmp & 0xFF;
1814 function tripletToBase64(num) {
1815 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F];
1818 function encodeChunk(uint8, start, end) {
1822 for (var i = start; i < end; i += 3) {
1823 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2];
1824 output.push(tripletToBase64(tmp));
1827 return output.join('');
1830 function fromByteArray(uint8) {
1836 var len = uint8.length;
1837 var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
1841 var maxChunkLength = 16383; // must be multiple of 3
1842 // go through the array every three bytes, we'll deal with trailing stuff later
1844 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1845 parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
1846 } // pad the end with zeros, but make sure to not forget the extra bytes
1849 if (extraBytes === 1) {
1850 tmp = uint8[len - 1];
1851 output += lookup[tmp >> 2];
1852 output += lookup[tmp << 4 & 0x3F];
1854 } else if (extraBytes === 2) {
1855 tmp = (uint8[len - 2] << 8) + uint8[len - 1];
1856 output += lookup[tmp >> 10];
1857 output += lookup[tmp >> 4 & 0x3F];
1858 output += lookup[tmp << 2 & 0x3F];
1863 return parts.join('');
1866 function read(buffer, offset, isLE, mLen, nBytes) {
1868 var eLen = nBytes * 8 - mLen - 1;
1869 var eMax = (1 << eLen) - 1;
1870 var eBias = eMax >> 1;
1872 var i = isLE ? nBytes - 1 : 0;
1873 var d = isLE ? -1 : 1;
1874 var s = buffer[offset + i];
1876 e = s & (1 << -nBits) - 1;
1880 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
1882 m = e & (1 << -nBits) - 1;
1886 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
1890 } else if (e === eMax) {
1891 return m ? NaN : (s ? -1 : 1) * Infinity;
1893 m = m + Math.pow(2, mLen);
1897 return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
1899 function write(buffer, value, offset, isLE, mLen, nBytes) {
1901 var eLen = nBytes * 8 - mLen - 1;
1902 var eMax = (1 << eLen) - 1;
1903 var eBias = eMax >> 1;
1904 var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
1905 var i = isLE ? 0 : nBytes - 1;
1906 var d = isLE ? 1 : -1;
1907 var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
1908 value = Math.abs(value);
1910 if (isNaN(value) || value === Infinity) {
1911 m = isNaN(value) ? 1 : 0;
1914 e = Math.floor(Math.log(value) / Math.LN2);
1916 if (value * (c = Math.pow(2, -e)) < 1) {
1921 if (e + eBias >= 1) {
1924 value += rt * Math.pow(2, 1 - eBias);
1927 if (value * c >= 2) {
1932 if (e + eBias >= eMax) {
1935 } else if (e + eBias >= 1) {
1936 m = (value * c - 1) * Math.pow(2, mLen);
1939 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
1944 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
1949 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
1951 buffer[offset + i - d] |= s * 128;
1954 var toString = {}.toString;
1955 var isArray = Array.isArray || function (arr) {
1956 return toString.call(arr) == '[object Array]';
1959 var INSPECT_MAX_BYTES = 50;
1961 * If `Buffer.TYPED_ARRAY_SUPPORT`:
1962 * === true Use Uint8Array implementation (fastest)
1963 * === false Use Object implementation (most compatible, even IE6)
1965 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
1966 * Opera 11.6+, iOS 4.2+.
1968 * Due to various browser bugs, sometimes the Object implementation will be used even
1969 * when the browser supports typed arrays.
1973 * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
1974 * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
1976 * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
1978 * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
1979 * incorrect length in some situations.
1981 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
1982 * get the Object implementation, which is slower but behaves correctly.
1985 Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true;
1987 function kMaxLength() {
1988 return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff;
1991 function createBuffer(that, length) {
1992 if (kMaxLength() < length) {
1993 throw new RangeError('Invalid typed array length');
1996 if (Buffer.TYPED_ARRAY_SUPPORT) {
1997 // Return an augmented `Uint8Array` instance, for best performance
1998 that = new Uint8Array(length);
1999 that.__proto__ = Buffer.prototype;
2001 // Fallback: Return an object instance of the Buffer class
2002 if (that === null) {
2003 that = new Buffer(length);
2006 that.length = length;
2012 * The Buffer constructor returns instances of `Uint8Array` that have their
2013 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
2014 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
2015 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
2016 * returns a single octet.
2018 * The `Uint8Array` prototype remains unmodified.
2022 function Buffer(arg, encodingOrOffset, length) {
2023 if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
2024 return new Buffer(arg, encodingOrOffset, length);
2028 if (typeof arg === 'number') {
2029 if (typeof encodingOrOffset === 'string') {
2030 throw new Error('If encoding is specified then the first argument must be a string');
2033 return allocUnsafe(this, arg);
2036 return from(this, arg, encodingOrOffset, length);
2038 Buffer.poolSize = 8192; // not used by this implementation
2039 // TODO: Legacy, not needed anymore. Remove in next major version.
2041 Buffer._augment = function (arr) {
2042 arr.__proto__ = Buffer.prototype;
2046 function from(that, value, encodingOrOffset, length) {
2047 if (typeof value === 'number') {
2048 throw new TypeError('"value" argument must not be a number');
2051 if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
2052 return fromArrayBuffer(that, value, encodingOrOffset, length);
2055 if (typeof value === 'string') {
2056 return fromString(that, value, encodingOrOffset);
2059 return fromObject(that, value);
2062 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
2063 * if value is a number.
2064 * Buffer.from(str[, encoding])
2065 * Buffer.from(array)
2066 * Buffer.from(buffer)
2067 * Buffer.from(arrayBuffer[, byteOffset[, length]])
2071 Buffer.from = function (value, encodingOrOffset, length) {
2072 return from(null, value, encodingOrOffset, length);
2075 if (Buffer.TYPED_ARRAY_SUPPORT) {
2076 Buffer.prototype.__proto__ = Uint8Array.prototype;
2077 Buffer.__proto__ = Uint8Array;
2080 function assertSize(size) {
2081 if (typeof size !== 'number') {
2082 throw new TypeError('"size" argument must be a number');
2083 } else if (size < 0) {
2084 throw new RangeError('"size" argument must not be negative');
2088 function alloc(that, size, fill, encoding) {
2092 return createBuffer(that, size);
2095 if (fill !== undefined) {
2096 // Only pay attention to encoding if it's a string. This
2097 // prevents accidentally sending in a number that would
2098 // be interpretted as a start offset.
2099 return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill);
2102 return createBuffer(that, size);
2105 * Creates a new filled Buffer instance.
2106 * alloc(size[, fill[, encoding]])
2110 Buffer.alloc = function (size, fill, encoding) {
2111 return alloc(null, size, fill, encoding);
2114 function allocUnsafe(that, size) {
2116 that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
2118 if (!Buffer.TYPED_ARRAY_SUPPORT) {
2119 for (var i = 0; i < size; ++i) {
2127 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
2131 Buffer.allocUnsafe = function (size) {
2132 return allocUnsafe(null, size);
2135 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
2139 Buffer.allocUnsafeSlow = function (size) {
2140 return allocUnsafe(null, size);
2143 function fromString(that, string, encoding) {
2144 if (typeof encoding !== 'string' || encoding === '') {
2148 if (!Buffer.isEncoding(encoding)) {
2149 throw new TypeError('"encoding" must be a valid string encoding');
2152 var length = byteLength(string, encoding) | 0;
2153 that = createBuffer(that, length);
2154 var actual = that.write(string, encoding);
2156 if (actual !== length) {
2157 // Writing a hex string, for example, that contains invalid characters will
2158 // cause everything after the first invalid character to be ignored. (e.g.
2159 // 'abxxcd' will be treated as 'ab')
2160 that = that.slice(0, actual);
2166 function fromArrayLike(that, array) {
2167 var length = array.length < 0 ? 0 : checked(array.length) | 0;
2168 that = createBuffer(that, length);
2170 for (var i = 0; i < length; i += 1) {
2171 that[i] = array[i] & 255;
2177 function fromArrayBuffer(that, array, byteOffset, length) {
2178 array.byteLength; // this throws if `array` is not a valid ArrayBuffer
2180 if (byteOffset < 0 || array.byteLength < byteOffset) {
2181 throw new RangeError('\'offset\' is out of bounds');
2184 if (array.byteLength < byteOffset + (length || 0)) {
2185 throw new RangeError('\'length\' is out of bounds');
2188 if (byteOffset === undefined && length === undefined) {
2189 array = new Uint8Array(array);
2190 } else if (length === undefined) {
2191 array = new Uint8Array(array, byteOffset);
2193 array = new Uint8Array(array, byteOffset, length);
2196 if (Buffer.TYPED_ARRAY_SUPPORT) {
2197 // Return an augmented `Uint8Array` instance, for best performance
2199 that.__proto__ = Buffer.prototype;
2201 // Fallback: Return an object instance of the Buffer class
2202 that = fromArrayLike(that, array);
2208 function fromObject(that, obj) {
2209 if (internalIsBuffer(obj)) {
2210 var len = checked(obj.length) | 0;
2211 that = createBuffer(that, len);
2213 if (that.length === 0) {
2217 obj.copy(that, 0, 0, len);
2222 if (typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer || 'length' in obj) {
2223 if (typeof obj.length !== 'number' || isnan(obj.length)) {
2224 return createBuffer(that, 0);
2227 return fromArrayLike(that, obj);
2230 if (obj.type === 'Buffer' && isArray(obj.data)) {
2231 return fromArrayLike(that, obj.data);
2235 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.');
2238 function checked(length) {
2239 // Note: cannot use `length < kMaxLength()` here because that fails when
2240 // length is NaN (which is otherwise coerced to zero.)
2241 if (length >= kMaxLength()) {
2242 throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes');
2247 Buffer.isBuffer = isBuffer;
2249 function internalIsBuffer(b) {
2250 return !!(b != null && b._isBuffer);
2253 Buffer.compare = function compare(a, b) {
2254 if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
2255 throw new TypeError('Arguments must be Buffers');
2258 if (a === b) return 0;
2262 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
2263 if (a[i] !== b[i]) {
2270 if (x < y) return -1;
2271 if (y < x) return 1;
2275 Buffer.isEncoding = function isEncoding(encoding) {
2276 switch (String(encoding).toLowerCase()) {
2295 Buffer.concat = function concat(list, length) {
2296 if (!isArray(list)) {
2297 throw new TypeError('"list" argument must be an Array of Buffers');
2300 if (list.length === 0) {
2301 return Buffer.alloc(0);
2306 if (length === undefined) {
2309 for (i = 0; i < list.length; ++i) {
2310 length += list[i].length;
2314 var buffer = Buffer.allocUnsafe(length);
2317 for (i = 0; i < list.length; ++i) {
2320 if (!internalIsBuffer(buf)) {
2321 throw new TypeError('"list" argument must be an Array of Buffers');
2324 buf.copy(buffer, pos);
2331 function byteLength(string, encoding) {
2332 if (internalIsBuffer(string)) {
2333 return string.length;
2336 if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
2337 return string.byteLength;
2340 if (typeof string !== 'string') {
2341 string = '' + string;
2344 var len = string.length;
2345 if (len === 0) return 0; // Use a for loop to avoid recursion
2347 var loweredCase = false;
2359 return utf8ToBytes(string).length;
2371 return base64ToBytes(string).length;
2374 if (loweredCase) return utf8ToBytes(string).length; // assume utf8
2376 encoding = ('' + encoding).toLowerCase();
2382 Buffer.byteLength = byteLength;
2384 function slowToString(encoding, start, end) {
2385 var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
2386 // property of a typed array.
2387 // This behaves neither like String nor Uint8Array in that we set start/end
2388 // to their upper/lower bounds if the value passed is out of range.
2389 // undefined is handled specially as per ECMA-262 6th Edition,
2390 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
2392 if (start === undefined || start < 0) {
2394 } // Return early if start > this.length. Done here to prevent potential uint32
2395 // coercion fail below.
2398 if (start > this.length) {
2402 if (end === undefined || end > this.length) {
2408 } // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
2418 if (!encoding) encoding = 'utf8';
2423 return hexSlice(this, start, end);
2427 return utf8Slice(this, start, end);
2430 return asciiSlice(this, start, end);
2434 return latin1Slice(this, start, end);
2437 return base64Slice(this, start, end);
2443 return utf16leSlice(this, start, end);
2446 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
2447 encoding = (encoding + '').toLowerCase();
2451 } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
2452 // Buffer instances.
2455 Buffer.prototype._isBuffer = true;
2457 function swap(b, n, m) {
2463 Buffer.prototype.swap16 = function swap16() {
2464 var len = this.length;
2466 if (len % 2 !== 0) {
2467 throw new RangeError('Buffer size must be a multiple of 16-bits');
2470 for (var i = 0; i < len; i += 2) {
2471 swap(this, i, i + 1);
2477 Buffer.prototype.swap32 = function swap32() {
2478 var len = this.length;
2480 if (len % 4 !== 0) {
2481 throw new RangeError('Buffer size must be a multiple of 32-bits');
2484 for (var i = 0; i < len; i += 4) {
2485 swap(this, i, i + 3);
2486 swap(this, i + 1, i + 2);
2492 Buffer.prototype.swap64 = function swap64() {
2493 var len = this.length;
2495 if (len % 8 !== 0) {
2496 throw new RangeError('Buffer size must be a multiple of 64-bits');
2499 for (var i = 0; i < len; i += 8) {
2500 swap(this, i, i + 7);
2501 swap(this, i + 1, i + 6);
2502 swap(this, i + 2, i + 5);
2503 swap(this, i + 3, i + 4);
2509 Buffer.prototype.toString = function toString() {
2510 var length = this.length | 0;
2511 if (length === 0) return '';
2512 if (arguments.length === 0) return utf8Slice(this, 0, length);
2513 return slowToString.apply(this, arguments);
2516 Buffer.prototype.equals = function equals(b) {
2517 if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer');
2518 if (this === b) return true;
2519 return Buffer.compare(this, b) === 0;
2522 Buffer.prototype.inspect = function inspect() {
2524 var max = INSPECT_MAX_BYTES;
2526 if (this.length > 0) {
2527 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
2528 if (this.length > max) str += ' ... ';
2531 return '<Buffer ' + str + '>';
2534 Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
2535 if (!internalIsBuffer(target)) {
2536 throw new TypeError('Argument must be a Buffer');
2539 if (start === undefined) {
2543 if (end === undefined) {
2544 end = target ? target.length : 0;
2547 if (thisStart === undefined) {
2551 if (thisEnd === undefined) {
2552 thisEnd = this.length;
2555 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
2556 throw new RangeError('out of range index');
2559 if (thisStart >= thisEnd && start >= end) {
2563 if (thisStart >= thisEnd) {
2575 if (this === target) return 0;
2576 var x = thisEnd - thisStart;
2577 var y = end - start;
2578 var len = Math.min(x, y);
2579 var thisCopy = this.slice(thisStart, thisEnd);
2580 var targetCopy = target.slice(start, end);
2582 for (var i = 0; i < len; ++i) {
2583 if (thisCopy[i] !== targetCopy[i]) {
2590 if (x < y) return -1;
2591 if (y < x) return 1;
2593 }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
2594 // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
2597 // - buffer - a Buffer to search
2598 // - val - a string, Buffer, or number
2599 // - byteOffset - an index into `buffer`; will be clamped to an int32
2600 // - encoding - an optional encoding, relevant is val is a string
2601 // - dir - true for indexOf, false for lastIndexOf
2604 function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
2605 // Empty buffer means no match
2606 if (buffer.length === 0) return -1; // Normalize byteOffset
2608 if (typeof byteOffset === 'string') {
2609 encoding = byteOffset;
2611 } else if (byteOffset > 0x7fffffff) {
2612 byteOffset = 0x7fffffff;
2613 } else if (byteOffset < -0x80000000) {
2614 byteOffset = -0x80000000;
2617 byteOffset = +byteOffset; // Coerce to Number.
2619 if (isNaN(byteOffset)) {
2620 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
2621 byteOffset = dir ? 0 : buffer.length - 1;
2622 } // Normalize byteOffset: negative offsets start from the end of the buffer
2625 if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
2627 if (byteOffset >= buffer.length) {
2628 if (dir) return -1;else byteOffset = buffer.length - 1;
2629 } else if (byteOffset < 0) {
2630 if (dir) byteOffset = 0;else return -1;
2634 if (typeof val === 'string') {
2635 val = Buffer.from(val, encoding);
2636 } // Finally, search either indexOf (if dir is true) or lastIndexOf
2639 if (internalIsBuffer(val)) {
2640 // Special case: looking for empty string/buffer always fails
2641 if (val.length === 0) {
2645 return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
2646 } else if (typeof val === 'number') {
2647 val = val & 0xFF; // Search for a byte value [0-255]
2649 if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') {
2651 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
2653 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
2657 return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
2660 throw new TypeError('val must be string, number or Buffer');
2663 function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
2665 var arrLength = arr.length;
2666 var valLength = val.length;
2668 if (encoding !== undefined) {
2669 encoding = String(encoding).toLowerCase();
2671 if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') {
2672 if (arr.length < 2 || val.length < 2) {
2683 function read(buf, i) {
2684 if (indexSize === 1) {
2687 return buf.readUInt16BE(i * indexSize);
2694 var foundIndex = -1;
2696 for (i = byteOffset; i < arrLength; i++) {
2697 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
2698 if (foundIndex === -1) foundIndex = i;
2699 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
2701 if (foundIndex !== -1) i -= i - foundIndex;
2706 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
2708 for (i = byteOffset; i >= 0; i--) {
2711 for (var j = 0; j < valLength; j++) {
2712 if (read(arr, i + j) !== read(val, j)) {
2718 if (found) return i;
2725 Buffer.prototype.includes = function includes(val, byteOffset, encoding) {
2726 return this.indexOf(val, byteOffset, encoding) !== -1;
2729 Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
2730 return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
2733 Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
2734 return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
2737 function hexWrite(buf, string, offset, length) {
2738 offset = Number(offset) || 0;
2739 var remaining = buf.length - offset;
2744 length = Number(length);
2746 if (length > remaining) {
2749 } // must be an even number of digits
2752 var strLen = string.length;
2753 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string');
2755 if (length > strLen / 2) {
2756 length = strLen / 2;
2759 for (var i = 0; i < length; ++i) {
2760 var parsed = parseInt(string.substr(i * 2, 2), 16);
2761 if (isNaN(parsed)) return i;
2762 buf[offset + i] = parsed;
2768 function utf8Write(buf, string, offset, length) {
2769 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
2772 function asciiWrite(buf, string, offset, length) {
2773 return blitBuffer(asciiToBytes(string), buf, offset, length);
2776 function latin1Write(buf, string, offset, length) {
2777 return asciiWrite(buf, string, offset, length);
2780 function base64Write(buf, string, offset, length) {
2781 return blitBuffer(base64ToBytes(string), buf, offset, length);
2784 function ucs2Write(buf, string, offset, length) {
2785 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
2788 Buffer.prototype.write = function write(string, offset, length, encoding) {
2789 // Buffer#write(string)
2790 if (offset === undefined) {
2792 length = this.length;
2793 offset = 0; // Buffer#write(string, encoding)
2794 } else if (length === undefined && typeof offset === 'string') {
2796 length = this.length;
2797 offset = 0; // Buffer#write(string, offset[, length][, encoding])
2798 } else if (isFinite(offset)) {
2799 offset = offset | 0;
2801 if (isFinite(length)) {
2802 length = length | 0;
2803 if (encoding === undefined) encoding = 'utf8';
2807 } // legacy write(string, encoding, offset, length) - remove in v0.13
2810 throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported');
2813 var remaining = this.length - offset;
2814 if (length === undefined || length > remaining) length = remaining;
2816 if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
2817 throw new RangeError('Attempt to write outside buffer bounds');
2820 if (!encoding) encoding = 'utf8';
2821 var loweredCase = false;
2826 return hexWrite(this, string, offset, length);
2830 return utf8Write(this, string, offset, length);
2833 return asciiWrite(this, string, offset, length);
2837 return latin1Write(this, string, offset, length);
2840 // Warning: maxLength not taken into account in base64Write
2841 return base64Write(this, string, offset, length);
2847 return ucs2Write(this, string, offset, length);
2850 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding);
2851 encoding = ('' + encoding).toLowerCase();
2857 Buffer.prototype.toJSON = function toJSON() {
2860 data: Array.prototype.slice.call(this._arr || this, 0)
2864 function base64Slice(buf, start, end) {
2865 if (start === 0 && end === buf.length) {
2866 return fromByteArray(buf);
2868 return fromByteArray(buf.slice(start, end));
2872 function utf8Slice(buf, start, end) {
2873 end = Math.min(buf.length, end);
2878 var firstByte = buf[i];
2879 var codePoint = null;
2880 var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1;
2882 if (i + bytesPerSequence <= end) {
2883 var secondByte, thirdByte, fourthByte, tempCodePoint;
2885 switch (bytesPerSequence) {
2887 if (firstByte < 0x80) {
2888 codePoint = firstByte;
2894 secondByte = buf[i + 1];
2896 if ((secondByte & 0xC0) === 0x80) {
2897 tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F;
2899 if (tempCodePoint > 0x7F) {
2900 codePoint = tempCodePoint;
2907 secondByte = buf[i + 1];
2908 thirdByte = buf[i + 2];
2910 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
2911 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F;
2913 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
2914 codePoint = tempCodePoint;
2921 secondByte = buf[i + 1];
2922 thirdByte = buf[i + 2];
2923 fourthByte = buf[i + 3];
2925 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
2926 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F;
2928 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
2929 codePoint = tempCodePoint;
2936 if (codePoint === null) {
2937 // we did not generate a valid codePoint so insert a
2938 // replacement char (U+FFFD) and advance only 1 byte
2940 bytesPerSequence = 1;
2941 } else if (codePoint > 0xFFFF) {
2942 // encode to utf16 (surrogate pair dance)
2943 codePoint -= 0x10000;
2944 res.push(codePoint >>> 10 & 0x3FF | 0xD800);
2945 codePoint = 0xDC00 | codePoint & 0x3FF;
2948 res.push(codePoint);
2949 i += bytesPerSequence;
2952 return decodeCodePointsArray(res);
2953 } // Based on http://stackoverflow.com/a/22747272/680742, the browser with
2954 // the lowest limit is Chrome, with 0x10000 args.
2955 // We go 1 magnitude less, for safety
2958 var MAX_ARGUMENTS_LENGTH = 0x1000;
2960 function decodeCodePointsArray(codePoints) {
2961 var len = codePoints.length;
2963 if (len <= MAX_ARGUMENTS_LENGTH) {
2964 return String.fromCharCode.apply(String, codePoints); // avoid extra slice()
2965 } // Decode in chunks to avoid "call stack size exceeded".
2972 res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH));
2978 function asciiSlice(buf, start, end) {
2980 end = Math.min(buf.length, end);
2982 for (var i = start; i < end; ++i) {
2983 ret += String.fromCharCode(buf[i] & 0x7F);
2989 function latin1Slice(buf, start, end) {
2991 end = Math.min(buf.length, end);
2993 for (var i = start; i < end; ++i) {
2994 ret += String.fromCharCode(buf[i]);
3000 function hexSlice(buf, start, end) {
3001 var len = buf.length;
3002 if (!start || start < 0) start = 0;
3003 if (!end || end < 0 || end > len) end = len;
3006 for (var i = start; i < end; ++i) {
3007 out += toHex(buf[i]);
3013 function utf16leSlice(buf, start, end) {
3014 var bytes = buf.slice(start, end);
3017 for (var i = 0; i < bytes.length; i += 2) {
3018 res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
3024 Buffer.prototype.slice = function slice(start, end) {
3025 var len = this.length;
3027 end = end === undefined ? len : ~~end;
3031 if (start < 0) start = 0;
3032 } else if (start > len) {
3038 if (end < 0) end = 0;
3039 } else if (end > len) {
3043 if (end < start) end = start;
3046 if (Buffer.TYPED_ARRAY_SUPPORT) {
3047 newBuf = this.subarray(start, end);
3048 newBuf.__proto__ = Buffer.prototype;
3050 var sliceLen = end - start;
3051 newBuf = new Buffer(sliceLen, undefined);
3053 for (var i = 0; i < sliceLen; ++i) {
3054 newBuf[i] = this[i + start];
3061 * Need to make sure that buffer isn't trying to write out of bounds.
3065 function checkOffset(offset, ext, length) {
3066 if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint');
3067 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length');
3070 Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) {
3071 offset = offset | 0;
3072 byteLength = byteLength | 0;
3073 if (!noAssert) checkOffset(offset, byteLength, this.length);
3074 var val = this[offset];
3078 while (++i < byteLength && (mul *= 0x100)) {
3079 val += this[offset + i] * mul;
3085 Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) {
3086 offset = offset | 0;
3087 byteLength = byteLength | 0;
3090 checkOffset(offset, byteLength, this.length);
3093 var val = this[offset + --byteLength];
3096 while (byteLength > 0 && (mul *= 0x100)) {
3097 val += this[offset + --byteLength] * mul;
3103 Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) {
3104 if (!noAssert) checkOffset(offset, 1, this.length);
3105 return this[offset];
3108 Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
3109 if (!noAssert) checkOffset(offset, 2, this.length);
3110 return this[offset] | this[offset + 1] << 8;
3113 Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
3114 if (!noAssert) checkOffset(offset, 2, this.length);
3115 return this[offset] << 8 | this[offset + 1];
3118 Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
3119 if (!noAssert) checkOffset(offset, 4, this.length);
3120 return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000;
3123 Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
3124 if (!noAssert) checkOffset(offset, 4, this.length);
3125 return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
3128 Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) {
3129 offset = offset | 0;
3130 byteLength = byteLength | 0;
3131 if (!noAssert) checkOffset(offset, byteLength, this.length);
3132 var val = this[offset];
3136 while (++i < byteLength && (mul *= 0x100)) {
3137 val += this[offset + i] * mul;
3141 if (val >= mul) val -= Math.pow(2, 8 * byteLength);
3145 Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) {
3146 offset = offset | 0;
3147 byteLength = byteLength | 0;
3148 if (!noAssert) checkOffset(offset, byteLength, this.length);
3151 var val = this[offset + --i];
3153 while (i > 0 && (mul *= 0x100)) {
3154 val += this[offset + --i] * mul;
3158 if (val >= mul) val -= Math.pow(2, 8 * byteLength);
3162 Buffer.prototype.readInt8 = function readInt8(offset, noAssert) {
3163 if (!noAssert) checkOffset(offset, 1, this.length);
3164 if (!(this[offset] & 0x80)) return this[offset];
3165 return (0xff - this[offset] + 1) * -1;
3168 Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
3169 if (!noAssert) checkOffset(offset, 2, this.length);
3170 var val = this[offset] | this[offset + 1] << 8;
3171 return val & 0x8000 ? val | 0xFFFF0000 : val;
3174 Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
3175 if (!noAssert) checkOffset(offset, 2, this.length);
3176 var val = this[offset + 1] | this[offset] << 8;
3177 return val & 0x8000 ? val | 0xFFFF0000 : val;
3180 Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
3181 if (!noAssert) checkOffset(offset, 4, this.length);
3182 return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
3185 Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
3186 if (!noAssert) checkOffset(offset, 4, this.length);
3187 return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
3190 Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
3191 if (!noAssert) checkOffset(offset, 4, this.length);
3192 return read(this, offset, true, 23, 4);
3195 Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
3196 if (!noAssert) checkOffset(offset, 4, this.length);
3197 return read(this, offset, false, 23, 4);
3200 Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
3201 if (!noAssert) checkOffset(offset, 8, this.length);
3202 return read(this, offset, true, 52, 8);
3205 Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
3206 if (!noAssert) checkOffset(offset, 8, this.length);
3207 return read(this, offset, false, 52, 8);
3210 function checkInt(buf, value, offset, ext, max, min) {
3211 if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
3212 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
3213 if (offset + ext > buf.length) throw new RangeError('Index out of range');
3216 Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) {
3218 offset = offset | 0;
3219 byteLength = byteLength | 0;
3222 var maxBytes = Math.pow(2, 8 * byteLength) - 1;
3223 checkInt(this, value, offset, byteLength, maxBytes, 0);
3228 this[offset] = value & 0xFF;
3230 while (++i < byteLength && (mul *= 0x100)) {
3231 this[offset + i] = value / mul & 0xFF;
3234 return offset + byteLength;
3237 Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) {
3239 offset = offset | 0;
3240 byteLength = byteLength | 0;
3243 var maxBytes = Math.pow(2, 8 * byteLength) - 1;
3244 checkInt(this, value, offset, byteLength, maxBytes, 0);
3247 var i = byteLength - 1;
3249 this[offset + i] = value & 0xFF;
3251 while (--i >= 0 && (mul *= 0x100)) {
3252 this[offset + i] = value / mul & 0xFF;
3255 return offset + byteLength;
3258 Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
3260 offset = offset | 0;
3261 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
3262 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
3263 this[offset] = value & 0xff;
3267 function objectWriteUInt16(buf, value, offset, littleEndian) {
3268 if (value < 0) value = 0xffff + value + 1;
3270 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
3271 buf[offset + i] = (value & 0xff << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8;
3275 Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
3277 offset = offset | 0;
3278 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
3280 if (Buffer.TYPED_ARRAY_SUPPORT) {
3281 this[offset] = value & 0xff;
3282 this[offset + 1] = value >>> 8;
3284 objectWriteUInt16(this, value, offset, true);
3290 Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
3292 offset = offset | 0;
3293 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
3295 if (Buffer.TYPED_ARRAY_SUPPORT) {
3296 this[offset] = value >>> 8;
3297 this[offset + 1] = value & 0xff;
3299 objectWriteUInt16(this, value, offset, false);
3305 function objectWriteUInt32(buf, value, offset, littleEndian) {
3306 if (value < 0) value = 0xffffffff + value + 1;
3308 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
3309 buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 0xff;
3313 Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
3315 offset = offset | 0;
3316 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
3318 if (Buffer.TYPED_ARRAY_SUPPORT) {
3319 this[offset + 3] = value >>> 24;
3320 this[offset + 2] = value >>> 16;
3321 this[offset + 1] = value >>> 8;
3322 this[offset] = value & 0xff;
3324 objectWriteUInt32(this, value, offset, true);
3330 Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
3332 offset = offset | 0;
3333 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
3335 if (Buffer.TYPED_ARRAY_SUPPORT) {
3336 this[offset] = value >>> 24;
3337 this[offset + 1] = value >>> 16;
3338 this[offset + 2] = value >>> 8;
3339 this[offset + 3] = value & 0xff;
3341 objectWriteUInt32(this, value, offset, false);
3347 Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) {
3349 offset = offset | 0;
3352 var limit = Math.pow(2, 8 * byteLength - 1);
3353 checkInt(this, value, offset, byteLength, limit - 1, -limit);
3359 this[offset] = value & 0xFF;
3361 while (++i < byteLength && (mul *= 0x100)) {
3362 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
3366 this[offset + i] = (value / mul >> 0) - sub & 0xFF;
3369 return offset + byteLength;
3372 Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) {
3374 offset = offset | 0;
3377 var limit = Math.pow(2, 8 * byteLength - 1);
3378 checkInt(this, value, offset, byteLength, limit - 1, -limit);
3381 var i = byteLength - 1;
3384 this[offset + i] = value & 0xFF;
3386 while (--i >= 0 && (mul *= 0x100)) {
3387 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
3391 this[offset + i] = (value / mul >> 0) - sub & 0xFF;
3394 return offset + byteLength;
3397 Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
3399 offset = offset | 0;
3400 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
3401 if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
3402 if (value < 0) value = 0xff + value + 1;
3403 this[offset] = value & 0xff;
3407 Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
3409 offset = offset | 0;
3410 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
3412 if (Buffer.TYPED_ARRAY_SUPPORT) {
3413 this[offset] = value & 0xff;
3414 this[offset + 1] = value >>> 8;
3416 objectWriteUInt16(this, value, offset, true);
3422 Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
3424 offset = offset | 0;
3425 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
3427 if (Buffer.TYPED_ARRAY_SUPPORT) {
3428 this[offset] = value >>> 8;
3429 this[offset + 1] = value & 0xff;
3431 objectWriteUInt16(this, value, offset, false);
3437 Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
3439 offset = offset | 0;
3440 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
3442 if (Buffer.TYPED_ARRAY_SUPPORT) {
3443 this[offset] = value & 0xff;
3444 this[offset + 1] = value >>> 8;
3445 this[offset + 2] = value >>> 16;
3446 this[offset + 3] = value >>> 24;
3448 objectWriteUInt32(this, value, offset, true);
3454 Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
3456 offset = offset | 0;
3457 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
3458 if (value < 0) value = 0xffffffff + value + 1;
3460 if (Buffer.TYPED_ARRAY_SUPPORT) {
3461 this[offset] = value >>> 24;
3462 this[offset + 1] = value >>> 16;
3463 this[offset + 2] = value >>> 8;
3464 this[offset + 3] = value & 0xff;
3466 objectWriteUInt32(this, value, offset, false);
3472 function checkIEEE754(buf, value, offset, ext, max, min) {
3473 if (offset + ext > buf.length) throw new RangeError('Index out of range');
3474 if (offset < 0) throw new RangeError('Index out of range');
3477 function writeFloat(buf, value, offset, littleEndian, noAssert) {
3479 checkIEEE754(buf, value, offset, 4);
3482 write(buf, value, offset, littleEndian, 23, 4);
3486 Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
3487 return writeFloat(this, value, offset, true, noAssert);
3490 Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
3491 return writeFloat(this, value, offset, false, noAssert);
3494 function writeDouble(buf, value, offset, littleEndian, noAssert) {
3496 checkIEEE754(buf, value, offset, 8);
3499 write(buf, value, offset, littleEndian, 52, 8);
3503 Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
3504 return writeDouble(this, value, offset, true, noAssert);
3507 Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
3508 return writeDouble(this, value, offset, false, noAssert);
3509 }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
3512 Buffer.prototype.copy = function copy(target, targetStart, start, end) {
3513 if (!start) start = 0;
3514 if (!end && end !== 0) end = this.length;
3515 if (targetStart >= target.length) targetStart = target.length;
3516 if (!targetStart) targetStart = 0;
3517 if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done
3519 if (end === start) return 0;
3520 if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions
3522 if (targetStart < 0) {
3523 throw new RangeError('targetStart out of bounds');
3526 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds');
3527 if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob?
3529 if (end > this.length) end = this.length;
3531 if (target.length - targetStart < end - start) {
3532 end = target.length - targetStart + start;
3535 var len = end - start;
3538 if (this === target && start < targetStart && targetStart < end) {
3539 // descending copy from end
3540 for (i = len - 1; i >= 0; --i) {
3541 target[i + targetStart] = this[i + start];
3543 } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
3544 // ascending copy from start
3545 for (i = 0; i < len; ++i) {
3546 target[i + targetStart] = this[i + start];
3549 Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart);
3554 // buffer.fill(number[, offset[, end]])
3555 // buffer.fill(buffer[, offset[, end]])
3556 // buffer.fill(string[, offset[, end]][, encoding])
3559 Buffer.prototype.fill = function fill(val, start, end, encoding) {
3560 // Handle string cases:
3561 if (typeof val === 'string') {
3562 if (typeof start === 'string') {
3566 } else if (typeof end === 'string') {
3571 if (val.length === 1) {
3572 var code = val.charCodeAt(0);
3579 if (encoding !== undefined && typeof encoding !== 'string') {
3580 throw new TypeError('encoding must be a string');
3583 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
3584 throw new TypeError('Unknown encoding: ' + encoding);
3586 } else if (typeof val === 'number') {
3588 } // Invalid ranges are not set to a default, so can range check early.
3591 if (start < 0 || this.length < start || this.length < end) {
3592 throw new RangeError('Out of range index');
3599 start = start >>> 0;
3600 end = end === undefined ? this.length : end >>> 0;
3604 if (typeof val === 'number') {
3605 for (i = start; i < end; ++i) {
3609 var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString());
3610 var len = bytes.length;
3612 for (i = 0; i < end - start; ++i) {
3613 this[i + start] = bytes[i % len];
3618 }; // HELPER FUNCTIONS
3622 var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
3624 function base64clean(str) {
3625 // Node strips out invalid characters like \n and \t from the string, base64-js does not
3626 str = stringtrim(str).replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to ''
3628 if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
3630 while (str.length % 4 !== 0) {
3637 function stringtrim(str) {
3638 if (str.trim) return str.trim();
3639 return str.replace(/^\s+|\s+$/g, '');
3643 if (n < 16) return '0' + n.toString(16);
3644 return n.toString(16);
3647 function utf8ToBytes(string, units) {
3648 units = units || Infinity;
3650 var length = string.length;
3651 var leadSurrogate = null;
3654 for (var i = 0; i < length; ++i) {
3655 codePoint = string.charCodeAt(i); // is surrogate component
3657 if (codePoint > 0xD7FF && codePoint < 0xE000) {
3658 // last char was a lead
3659 if (!leadSurrogate) {
3661 if (codePoint > 0xDBFF) {
3663 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
3665 } else if (i + 1 === length) {
3667 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
3672 leadSurrogate = codePoint;
3674 } // 2 leads in a row
3677 if (codePoint < 0xDC00) {
3678 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
3679 leadSurrogate = codePoint;
3681 } // valid surrogate pair
3684 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
3685 } else if (leadSurrogate) {
3686 // valid bmp char, but last char was a lead
3687 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
3690 leadSurrogate = null; // encode utf8
3692 if (codePoint < 0x80) {
3693 if ((units -= 1) < 0) break;
3694 bytes.push(codePoint);
3695 } else if (codePoint < 0x800) {
3696 if ((units -= 2) < 0) break;
3697 bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80);
3698 } else if (codePoint < 0x10000) {
3699 if ((units -= 3) < 0) break;
3700 bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
3701 } else if (codePoint < 0x110000) {
3702 if ((units -= 4) < 0) break;
3703 bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);
3705 throw new Error('Invalid code point');
3712 function asciiToBytes(str) {
3715 for (var i = 0; i < str.length; ++i) {
3716 // Node's code seems to be doing this and not & 0x7F..
3717 byteArray.push(str.charCodeAt(i) & 0xFF);
3723 function utf16leToBytes(str, units) {
3727 for (var i = 0; i < str.length; ++i) {
3728 if ((units -= 2) < 0) break;
3729 c = str.charCodeAt(i);
3739 function base64ToBytes(str) {
3740 return toByteArray(base64clean(str));
3743 function blitBuffer(src, dst, offset, length) {
3744 for (var i = 0; i < length; ++i) {
3745 if (i + offset >= dst.length || i >= src.length) break;
3746 dst[i + offset] = src[i];
3752 function isnan(val) {
3753 return val !== val; // eslint-disable-line no-self-compare
3754 } // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
3755 // The _isBuffer check is for Safari 5-7 support, because it's missing
3756 // Object.prototype.constructor. Remove this eventually
3759 function isBuffer(obj) {
3760 return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj));
3763 function isFastBuffer(obj) {
3764 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj);
3765 } // For Node v0.10 support. Remove this eventually.
3768 function isSlowBuffer(obj) {
3769 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0));
3772 var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
3774 function unwrapExports (x) {
3775 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
3778 function createCommonjsModule(fn, module) {
3779 return module = { exports: {} }, fn(module, module.exports), module.exports;
3782 function getCjsExportFromNamespace (n) {
3783 return n && n['default'] || n;
3786 var fs = getCjsExportFromNamespace(_shim_fs$1);
3794 constructor(file, options) {
3795 options = options || {};
3796 if (!options.readChunk) options.readChunk = 1024;
3798 if (!options.newLineCharacter) {
3799 options.newLineCharacter = 0x0a; //linux line ending
3801 options.newLineCharacter = options.newLineCharacter.charCodeAt(0);
3804 if (typeof file === 'number') {
3807 this.fd = fs.openSync(file, 'r');
3810 this.options = options;
3811 this.newLineCharacter = options.newLineCharacter;
3815 _searchInBuffer(buffer, hexNeedle) {
3818 for (let i = 0; i <= buffer.length; i++) {
3819 let b_byte = buffer[i];
3821 if (b_byte === hexNeedle) {
3831 this.eofReached = false;
3832 this.linesCache = [];
3833 this.fdPosition = 0;
3837 fs.closeSync(this.fd);
3841 _extractLines(buffer) {
3844 let bufferPosition = 0;
3845 let lastNewLineBufferPosition = 0;
3848 let bufferPositionValue = buffer[bufferPosition++];
3850 if (bufferPositionValue === this.newLineCharacter) {
3851 line = buffer.slice(lastNewLineBufferPosition, bufferPosition);
3853 lastNewLineBufferPosition = bufferPosition;
3854 } else if (!bufferPositionValue) {
3859 let leftovers = buffer.slice(lastNewLineBufferPosition, bufferPosition);
3861 if (leftovers.length) {
3862 lines.push(leftovers);
3868 _readChunk(lineLeftovers) {
3869 let totalBytesRead = 0;
3874 const readBuffer = new Buffer(this.options.readChunk);
3875 bytesRead = fs.readSync(this.fd, readBuffer, 0, this.options.readChunk, this.fdPosition);
3876 totalBytesRead = totalBytesRead + bytesRead;
3877 this.fdPosition = this.fdPosition + bytesRead;
3878 buffers.push(readBuffer);
3879 } while (bytesRead && this._searchInBuffer(buffers[buffers.length - 1], this.options.newLineCharacter) === -1);
3881 let bufferData = Buffer.concat(buffers);
3883 if (bytesRead < this.options.readChunk) {
3884 this.eofReached = true;
3885 bufferData = bufferData.slice(0, totalBytesRead);
3888 if (totalBytesRead) {
3889 this.linesCache = this._extractLines(bufferData);
3891 if (lineLeftovers) {
3892 this.linesCache[0] = Buffer.concat([lineLeftovers, this.linesCache[0]]);
3896 return totalBytesRead;
3900 if (!this.fd) return false;
3903 if (this.eofReached && this.linesCache.length === 0) {
3909 if (!this.linesCache.length) {
3910 bytesRead = this._readChunk();
3913 if (this.linesCache.length) {
3914 line = this.linesCache.shift();
3915 const lastLineCharacter = line[line.length - 1];
3917 if (lastLineCharacter !== 0x0a) {
3918 bytesRead = this._readChunk(line);
3921 line = this.linesCache.shift();
3926 if (this.eofReached && this.linesCache.length === 0) {
3930 if (line && line[line.length - 1] === this.newLineCharacter) {
3931 line = line.slice(0, line.length - 1);
3939 var readlines = LineByLine;
3942 * The inverse of `_.toPairs`; this method returns an object composed
3943 * from key-value `pairs`.
3949 * @param {Array} pairs The key-value pairs.
3950 * @returns {Object} Returns the new object.
3953 * _.fromPairs([['a', 1], ['b', 2]]);
3954 * // => { 'a': 1, 'b': 2 }
3956 function fromPairs(pairs) {
3958 length = pairs == null ? 0 : pairs.length,
3961 while (++index < length) {
3962 var pair = pairs[index];
3963 result[pair[0]] = pair[1];
3969 var fromPairs_1 = fromPairs;
3971 class ConfigError extends Error {}
3973 class DebugError extends Error {}
3975 class UndefinedParserError extends Error {}
3980 UndefinedParserError
3983 function _objectWithoutPropertiesLoose(source, excluded) {
3984 if (source == null) return {};
3986 var sourceKeys = Object.keys(source);
3989 for (i = 0; i < sourceKeys.length; i++) {
3990 key = sourceKeys[i];
3991 if (excluded.indexOf(key) >= 0) continue;
3992 target[key] = source[key];
3998 function _taggedTemplateLiteral(strings, raw) {
4000 raw = strings.slice(0);
4003 return Object.freeze(Object.defineProperties(strings, {
4005 value: Object.freeze(raw)
4010 // based off https://github.com/defunctzombie/node-process/blob/master/browser.js
4012 function defaultSetTimout() {
4013 throw new Error('setTimeout has not been defined');
4016 function defaultClearTimeout() {
4017 throw new Error('clearTimeout has not been defined');
4020 var cachedSetTimeout = defaultSetTimout;
4021 var cachedClearTimeout = defaultClearTimeout;
4023 if (typeof global$1.setTimeout === 'function') {
4024 cachedSetTimeout = setTimeout;
4027 if (typeof global$1.clearTimeout === 'function') {
4028 cachedClearTimeout = clearTimeout;
4031 function runTimeout(fun) {
4032 if (cachedSetTimeout === setTimeout) {
4033 //normal enviroments in sane situations
4034 return setTimeout(fun, 0);
4035 } // if setTimeout wasn't available but was latter defined
4038 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
4039 cachedSetTimeout = setTimeout;
4040 return setTimeout(fun, 0);
4044 // when when somebody has screwed with setTimeout but no I.E. maddness
4045 return cachedSetTimeout(fun, 0);
4048 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
4049 return cachedSetTimeout.call(null, fun, 0);
4051 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
4052 return cachedSetTimeout.call(this, fun, 0);
4057 function runClearTimeout(marker) {
4058 if (cachedClearTimeout === clearTimeout) {
4059 //normal enviroments in sane situations
4060 return clearTimeout(marker);
4061 } // if clearTimeout wasn't available but was latter defined
4064 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
4065 cachedClearTimeout = clearTimeout;
4066 return clearTimeout(marker);
4070 // when when somebody has screwed with setTimeout but no I.E. maddness
4071 return cachedClearTimeout(marker);
4074 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
4075 return cachedClearTimeout.call(null, marker);
4077 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
4078 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
4079 return cachedClearTimeout.call(this, marker);
4085 var draining = false;
4087 var queueIndex = -1;
4089 function cleanUpNextTick() {
4090 if (!draining || !currentQueue) {
4096 if (currentQueue.length) {
4097 queue = currentQueue.concat(queue);
4107 function drainQueue() {
4112 var timeout = runTimeout(cleanUpNextTick);
4114 var len = queue.length;
4117 currentQueue = queue;
4120 while (++queueIndex < len) {
4122 currentQueue[queueIndex].run();
4130 currentQueue = null;
4132 runClearTimeout(timeout);
4135 function nextTick(fun) {
4136 var args = new Array(arguments.length - 1);
4138 if (arguments.length > 1) {
4139 for (var i = 1; i < arguments.length; i++) {
4140 args[i - 1] = arguments[i];
4144 queue.push(new Item(fun, args));
4146 if (queue.length === 1 && !draining) {
4147 runTimeout(drainQueue);
4149 } // v8 likes predictible objects
4151 function Item(fun, array) {
4156 Item.prototype.run = function () {
4157 this.fun.apply(null, this.array);
4160 var title = 'browser';
4161 var platform = 'browser';
4165 var version$1 = ''; // empty string to avoid regexp issues
4174 var addListener = noop;
4177 var removeListener = noop;
4178 var removeAllListeners = noop;
4180 function binding(name) {
4181 throw new Error('process.binding is not supported');
4186 function chdir(dir) {
4187 throw new Error('process.chdir is not supported');
4191 } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js
4193 var performance = global$1.performance || {};
4195 var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () {
4196 return new Date().getTime();
4197 }; // generate timestamp or delta
4198 // see http://nodejs.org/api/process.html#process_process_hrtime
4201 function hrtime(previousTimestamp) {
4202 var clocktime = performanceNow.call(performance) * 1e-3;
4203 var seconds = Math.floor(clocktime);
4204 var nanoseconds = Math.floor(clocktime % 1 * 1e9);
4206 if (previousTimestamp) {
4207 seconds = seconds - previousTimestamp[0];
4208 nanoseconds = nanoseconds - previousTimestamp[1];
4210 if (nanoseconds < 0) {
4216 return [seconds, nanoseconds];
4218 var startTime = new Date();
4220 var currentTime = new Date();
4221 var dif = currentTime - startTime;
4233 addListener: addListener,
4236 removeListener: removeListener,
4237 removeAllListeners: removeAllListeners,
4250 const debug = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error('SEMVER', ...args) : () => {};
4251 var debug_1 = debug;
4253 // Note: this is the semver.org version of the spec that it implements
4254 // Not necessarily the package version of this code.
4255 const SEMVER_SPEC_VERSION = '2.0.0';
4256 const MAX_LENGTH = 256;
4257 const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
4258 /* istanbul ignore next */
4259 9007199254740991; // Max safe segment length for coercion.
4261 const MAX_SAFE_COMPONENT_LENGTH = 16;
4263 SEMVER_SPEC_VERSION,
4266 MAX_SAFE_COMPONENT_LENGTH
4269 var re_1 = createCommonjsModule(function (module, exports) {
4271 MAX_SAFE_COMPONENT_LENGTH
4273 exports = module.exports = {}; // The actual regexps go on exports.re
4275 const re = exports.re = [];
4276 const src = exports.src = [];
4277 const t = exports.t = {};
4280 const createToken = (name, value, isGlobal) => {
4282 debug_1(index, value);
4285 re[index] = new RegExp(value, isGlobal ? 'g' : undefined);
4286 }; // The following Regular Expressions can be used for tokenizing,
4287 // validating, and parsing SemVer version strings.
4288 // ## Numeric Identifier
4289 // A single `0`, or a non-zero digit followed by zero or more digits.
4292 createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*');
4293 createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); // ## Non-numeric Identifier
4294 // Zero or more digits, followed by a letter or hyphen, and then zero or
4295 // more letters, digits, or hyphens.
4297 createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); // ## Main Version
4298 // Three dot-separated numeric identifiers.
4300 createToken('MAINVERSION', "(".concat(src[t.NUMERICIDENTIFIER], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIER], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIER], ")"));
4301 createToken('MAINVERSIONLOOSE', "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")")); // ## Pre-release Version Identifier
4302 // A numeric identifier, or a non-numeric identifier.
4304 createToken('PRERELEASEIDENTIFIER', "(?:".concat(src[t.NUMERICIDENTIFIER], "|").concat(src[t.NONNUMERICIDENTIFIER], ")"));
4305 createToken('PRERELEASEIDENTIFIERLOOSE', "(?:".concat(src[t.NUMERICIDENTIFIERLOOSE], "|").concat(src[t.NONNUMERICIDENTIFIER], ")")); // ## Pre-release Version
4306 // Hyphen, followed by one or more dot-separated pre-release version
4309 createToken('PRERELEASE', "(?:-(".concat(src[t.PRERELEASEIDENTIFIER], "(?:\\.").concat(src[t.PRERELEASEIDENTIFIER], ")*))"));
4310 createToken('PRERELEASELOOSE', "(?:-?(".concat(src[t.PRERELEASEIDENTIFIERLOOSE], "(?:\\.").concat(src[t.PRERELEASEIDENTIFIERLOOSE], ")*))")); // ## Build Metadata Identifier
4311 // Any combination of digits, letters, or hyphens.
4313 createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); // ## Build Metadata
4314 // Plus sign, followed by one or more period-separated build metadata
4317 createToken('BUILD', "(?:\\+(".concat(src[t.BUILDIDENTIFIER], "(?:\\.").concat(src[t.BUILDIDENTIFIER], ")*))")); // ## Full Version String
4318 // A main version, followed optionally by a pre-release version and
4320 // Note that the only major, minor, patch, and pre-release sections of
4321 // the version string are capturing groups. The build metadata is not a
4322 // capturing group, because it should not ever be used in version
4325 createToken('FULLPLAIN', "v?".concat(src[t.MAINVERSION]).concat(src[t.PRERELEASE], "?").concat(src[t.BUILD], "?"));
4326 createToken('FULL', "^".concat(src[t.FULLPLAIN], "$")); // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
4327 // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
4328 // common in the npm registry.
4330 createToken('LOOSEPLAIN', "[v=\\s]*".concat(src[t.MAINVERSIONLOOSE]).concat(src[t.PRERELEASELOOSE], "?").concat(src[t.BUILD], "?"));
4331 createToken('LOOSE', "^".concat(src[t.LOOSEPLAIN], "$"));
4332 createToken('GTLT', '((?:<|>)?=?)'); // Something like "2.*" or "1.2.x".
4333 // Note that "x.x" is a valid xRange identifer, meaning "any version"
4334 // Only the first item is strictly required.
4336 createToken('XRANGEIDENTIFIERLOOSE', "".concat(src[t.NUMERICIDENTIFIERLOOSE], "|x|X|\\*"));
4337 createToken('XRANGEIDENTIFIER', "".concat(src[t.NUMERICIDENTIFIER], "|x|X|\\*"));
4338 createToken('XRANGEPLAIN', "[v=\\s]*(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:".concat(src[t.PRERELEASE], ")?").concat(src[t.BUILD], "?") + ")?)?");
4339 createToken('XRANGEPLAINLOOSE', "[v=\\s]*(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:".concat(src[t.PRERELEASELOOSE], ")?").concat(src[t.BUILD], "?") + ")?)?");
4340 createToken('XRANGE', "^".concat(src[t.GTLT], "\\s*").concat(src[t.XRANGEPLAIN], "$"));
4341 createToken('XRANGELOOSE', "^".concat(src[t.GTLT], "\\s*").concat(src[t.XRANGEPLAINLOOSE], "$")); // Coercion.
4342 // Extract anything that could conceivably be a part of a valid semver
4344 createToken('COERCE', "".concat('(^|[^\\d])' + '(\\d{1,').concat(MAX_SAFE_COMPONENT_LENGTH, "})") + "(?:\\.(\\d{1,".concat(MAX_SAFE_COMPONENT_LENGTH, "}))?") + "(?:\\.(\\d{1,".concat(MAX_SAFE_COMPONENT_LENGTH, "}))?") + "(?:$|[^\\d])");
4345 createToken('COERCERTL', src[t.COERCE], true); // Tilde ranges.
4346 // Meaning is "reasonably at or greater than"
4348 createToken('LONETILDE', '(?:~>?)');
4349 createToken('TILDETRIM', "(\\s*)".concat(src[t.LONETILDE], "\\s+"), true);
4350 exports.tildeTrimReplace = '$1~';
4351 createToken('TILDE', "^".concat(src[t.LONETILDE]).concat(src[t.XRANGEPLAIN], "$"));
4352 createToken('TILDELOOSE', "^".concat(src[t.LONETILDE]).concat(src[t.XRANGEPLAINLOOSE], "$")); // Caret ranges.
4353 // Meaning is "at least and backwards compatible with"
4355 createToken('LONECARET', '(?:\\^)');
4356 createToken('CARETTRIM', "(\\s*)".concat(src[t.LONECARET], "\\s+"), true);
4357 exports.caretTrimReplace = '$1^';
4358 createToken('CARET', "^".concat(src[t.LONECARET]).concat(src[t.XRANGEPLAIN], "$"));
4359 createToken('CARETLOOSE', "^".concat(src[t.LONECARET]).concat(src[t.XRANGEPLAINLOOSE], "$")); // A simple gt/lt/eq thing, or just "" to indicate "any version"
4361 createToken('COMPARATORLOOSE', "^".concat(src[t.GTLT], "\\s*(").concat(src[t.LOOSEPLAIN], ")$|^$"));
4362 createToken('COMPARATOR', "^".concat(src[t.GTLT], "\\s*(").concat(src[t.FULLPLAIN], ")$|^$")); // An expression to strip any whitespace between the gtlt and the thing
4363 // it modifies, so that `> 1.2.3` ==> `>1.2.3`
4365 createToken('COMPARATORTRIM', "(\\s*)".concat(src[t.GTLT], "\\s*(").concat(src[t.LOOSEPLAIN], "|").concat(src[t.XRANGEPLAIN], ")"), true);
4366 exports.comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
4367 // Note that these all use the loose form, because they'll be
4368 // checked against either the strict or loose comparator form
4371 createToken('HYPHENRANGE', "^\\s*(".concat(src[t.XRANGEPLAIN], ")") + "\\s+-\\s+" + "(".concat(src[t.XRANGEPLAIN], ")") + "\\s*$");
4372 createToken('HYPHENRANGELOOSE', "^\\s*(".concat(src[t.XRANGEPLAINLOOSE], ")") + "\\s+-\\s+" + "(".concat(src[t.XRANGEPLAINLOOSE], ")") + "\\s*$"); // Star ranges basically just allow anything at all.
4374 createToken('STAR', '(<|>)?=?\\s*\\*');
4377 var re_3 = re_1.src;
4379 var re_5 = re_1.tildeTrimReplace;
4380 var re_6 = re_1.caretTrimReplace;
4381 var re_7 = re_1.comparatorTrimReplace;
4383 const numeric = /^[0-9]+$/;
4385 const compareIdentifiers = (a, b) => {
4386 const anum = numeric.test(a);
4387 const bnum = numeric.test(b);
4394 return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
4397 const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a);
4405 MAX_LENGTH: MAX_LENGTH$1,
4406 MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1
4413 compareIdentifiers: compareIdentifiers$1
4417 constructor(version, options) {
4418 if (!options || typeof options !== 'object') {
4421 includePrerelease: false
4425 if (version instanceof SemVer) {
4426 if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
4429 version = version.version;
4431 } else if (typeof version !== 'string') {
4432 throw new TypeError("Invalid Version: ".concat(version));
4435 if (version.length > MAX_LENGTH$1) {
4436 throw new TypeError("version is longer than ".concat(MAX_LENGTH$1, " characters"));
4439 debug_1('SemVer', version, options);
4440 this.options = options;
4441 this.loose = !!options.loose; // this isn't actually relevant for versions, but keep it so that we
4442 // don't run into trouble passing this.options around.
4444 this.includePrerelease = !!options.includePrerelease;
4445 const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]);
4448 throw new TypeError("Invalid Version: ".concat(version));
4451 this.raw = version; // these are actually numbers
4457 if (this.major > MAX_SAFE_INTEGER$1 || this.major < 0) {
4458 throw new TypeError('Invalid major version');
4461 if (this.minor > MAX_SAFE_INTEGER$1 || this.minor < 0) {
4462 throw new TypeError('Invalid minor version');
4465 if (this.patch > MAX_SAFE_INTEGER$1 || this.patch < 0) {
4466 throw new TypeError('Invalid patch version');
4467 } // numberify any prerelease numeric ids
4471 this.prerelease = [];
4473 this.prerelease = m[4].split('.').map(id => {
4474 if (/^[0-9]+$/.test(id)) {
4477 if (num >= 0 && num < MAX_SAFE_INTEGER$1) {
4486 this.build = m[5] ? m[5].split('.') : [];
4491 this.version = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch);
4493 if (this.prerelease.length) {
4494 this.version += "-".concat(this.prerelease.join('.'));
4497 return this.version;
4501 return this.version;
4505 debug_1('SemVer.compare', this.version, this.options, other);
4507 if (!(other instanceof SemVer)) {
4508 if (typeof other === 'string' && other === this.version) {
4512 other = new SemVer(other, this.options);
4515 if (other.version === this.version) {
4519 return this.compareMain(other) || this.comparePre(other);
4522 compareMain(other) {
4523 if (!(other instanceof SemVer)) {
4524 other = new SemVer(other, this.options);
4527 return compareIdentifiers$1(this.major, other.major) || compareIdentifiers$1(this.minor, other.minor) || compareIdentifiers$1(this.patch, other.patch);
4531 if (!(other instanceof SemVer)) {
4532 other = new SemVer(other, this.options);
4533 } // NOT having a prerelease is > having one
4536 if (this.prerelease.length && !other.prerelease.length) {
4538 } else if (!this.prerelease.length && other.prerelease.length) {
4540 } else if (!this.prerelease.length && !other.prerelease.length) {
4547 const a = this.prerelease[i];
4548 const b = other.prerelease[i];
4549 debug_1('prerelease compare', i, a, b);
4551 if (a === undefined && b === undefined) {
4553 } else if (b === undefined) {
4555 } else if (a === undefined) {
4557 } else if (a === b) {
4560 return compareIdentifiers$1(a, b);
4565 compareBuild(other) {
4566 if (!(other instanceof SemVer)) {
4567 other = new SemVer(other, this.options);
4573 const a = this.build[i];
4574 const b = other.build[i];
4575 debug_1('prerelease compare', i, a, b);
4577 if (a === undefined && b === undefined) {
4579 } else if (b === undefined) {
4581 } else if (a === undefined) {
4583 } else if (a === b) {
4586 return compareIdentifiers$1(a, b);
4589 } // preminor will bump the version up to the next minor release, and immediately
4590 // down to pre-release. premajor and prepatch work the same way.
4593 inc(release, identifier) {
4596 this.prerelease.length = 0;
4600 this.inc('pre', identifier);
4604 this.prerelease.length = 0;
4607 this.inc('pre', identifier);
4611 // If this is already a prerelease, it will bump to the next version
4612 // drop any prereleases that might already exist, since they are not
4613 // relevant at this point.
4614 this.prerelease.length = 0;
4615 this.inc('patch', identifier);
4616 this.inc('pre', identifier);
4618 // If the input is a non-prerelease version, this acts the same as
4622 if (this.prerelease.length === 0) {
4623 this.inc('patch', identifier);
4626 this.inc('pre', identifier);
4630 // If this is a pre-major version, bump up to the same major version.
4631 // Otherwise increment major.
4632 // 1.0.0-5 bumps to 1.0.0
4633 // 1.1.0 bumps to 2.0.0
4634 if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
4640 this.prerelease = [];
4644 // If this is a pre-minor version, bump up to the same minor version.
4645 // Otherwise increment minor.
4646 // 1.2.0-5 bumps to 1.2.0
4647 // 1.2.1 bumps to 1.3.0
4648 if (this.patch !== 0 || this.prerelease.length === 0) {
4653 this.prerelease = [];
4657 // If this is not a pre-release version, it will increment the patch.
4658 // If it is a pre-release it will bump up to the same patch version.
4659 // 1.2.0-5 patches to 1.2.0
4660 // 1.2.0 patches to 1.2.1
4661 if (this.prerelease.length === 0) {
4665 this.prerelease = [];
4667 // This probably shouldn't be used publicly.
4668 // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
4671 if (this.prerelease.length === 0) {
4672 this.prerelease = [0];
4674 let i = this.prerelease.length;
4677 if (typeof this.prerelease[i] === 'number') {
4678 this.prerelease[i]++;
4684 // didn't increment anything
4685 this.prerelease.push(0);
4690 // 1.2.0-beta.1 bumps to 1.2.0-beta.2,
4691 // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
4692 if (this.prerelease[0] === identifier) {
4693 if (isNaN(this.prerelease[1])) {
4694 this.prerelease = [identifier, 0];
4697 this.prerelease = [identifier, 0];
4704 throw new Error("invalid increment argument: ".concat(release));
4708 this.raw = this.version;
4714 var semver = SemVer;
4716 const compare = (a, b, loose) => new semver(a, loose).compare(new semver(b, loose));
4718 var compare_1 = compare;
4720 const lt = (a, b, loose) => compare_1(a, b, loose) < 0;
4724 const gte = (a, b, loose) => compare_1(a, b, loose) >= 0;
4728 var arrayify = (object, keyName) => Object.entries(object).map(([key, value]) => Object.assign({
4732 var dedent_1 = createCommonjsModule(function (module) {
4734 function dedent(strings) {
4737 if (typeof strings === "string") {
4738 // dedent can be used as a plain function
4742 } // first, perform interpolation
4747 for (var i = 0; i < raw.length; i++) {
4748 result += raw[i]. // join lines when there is a suppressed newline
4749 replace(/\\\n[ \t]*/g, ""). // handle escaped backticks
4750 replace(/\\`/g, "`");
4752 if (i < (arguments.length <= 1 ? 0 : arguments.length - 1)) {
4753 result += arguments.length <= i + 1 ? undefined : arguments[i + 1];
4755 } // now strip indentation
4758 var lines = result.split("\n");
4760 lines.forEach(function (l) {
4761 var m = l.match(/^(\s+)\S+/);
4764 var indent = m[1].length;
4767 // this is the first indented line
4770 mindent = Math.min(mindent, indent);
4775 if (mindent !== null) {
4776 result = lines.map(function (l) {
4777 return l[0] === " " ? l.slice(mindent) : l;
4779 } // dedent eats leading and trailing whitespace too
4782 result = result.trim(); // handle escaped newlines at the end to ensure they don't get stripped too
4784 return result.replace(/\\n/g, "\n");
4788 module.exports = dedent;
4792 function _templateObject6() {
4793 const data = _taggedTemplateLiteral(["\n Require either '@prettier' or '@format' to be present in the file's first docblock comment\n in order for it to be formatted.\n "]);
4795 _templateObject6 = function _templateObject6() {
4802 function _templateObject5() {
4803 const data = _taggedTemplateLiteral(["\n Format code starting at a given character offset.\n The range will extend backwards to the start of the first line containing the selected statement.\n This option cannot be used with --cursor-offset.\n "]);
4805 _templateObject5 = function _templateObject5() {
4812 function _templateObject4() {
4813 const data = _taggedTemplateLiteral(["\n Format code ending at a given character offset (exclusive).\n The range will extend forwards to the end of the selected statement.\n This option cannot be used with --cursor-offset.\n "]);
4815 _templateObject4 = function _templateObject4() {
4822 function _templateObject3() {
4823 const data = _taggedTemplateLiteral(["\n Custom directory that contains prettier plugins in node_modules subdirectory.\n Overrides default behavior when plugins are searched relatively to the location of Prettier.\n Multiple values are accepted.\n "]);
4825 _templateObject3 = function _templateObject3() {
4832 function _templateObject2() {
4833 const data = _taggedTemplateLiteral(["\n Maintain existing\n (mixed values within one file are normalised by looking at what's used after the first line)\n "]);
4835 _templateObject2 = function _templateObject2() {
4842 function _templateObject() {
4843 const data = _taggedTemplateLiteral(["\n Print (to stderr) where a cursor at the given position would move to after formatting.\n This option cannot be used with --range-start and --range-end.\n "]);
4845 _templateObject = function _templateObject() {
4852 const CATEGORY_CONFIG = "Config";
4853 const CATEGORY_EDITOR = "Editor";
4854 const CATEGORY_FORMAT = "Format";
4855 const CATEGORY_OTHER = "Other";
4856 const CATEGORY_OUTPUT = "Output";
4857 const CATEGORY_GLOBAL = "Global";
4858 const CATEGORY_SPECIAL = "Special";
4860 * @typedef {Object} OptionInfo
4861 * @property {string} [since] - available since version
4862 * @property {string} category
4863 * @property {'int' | 'boolean' | 'choice' | 'path'} type
4864 * @property {boolean} [array] - indicate it's an array of the specified type
4865 * @property {OptionValueInfo} [default]
4866 * @property {OptionRangeInfo} [range] - for type int
4867 * @property {string} description
4868 * @property {string} [deprecated] - deprecated since version
4869 * @property {OptionRedirectInfo} [redirect] - redirect deprecated option
4870 * @property {(value: any) => boolean} [exception]
4871 * @property {OptionChoiceInfo[]} [choices] - for type choice
4872 * @property {string} [cliName]
4873 * @property {string} [cliCategory]
4874 * @property {string} [cliDescription]
4876 * @typedef {number | boolean | string} OptionValue
4877 * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo
4879 * @typedef {Object} OptionRedirectInfo
4880 * @property {string} option
4881 * @property {OptionValue} value
4883 * @typedef {Object} OptionRangeInfo
4884 * @property {number} start - recommended range start
4885 * @property {number} end - recommended range end
4886 * @property {number} step - recommended range step
4888 * @typedef {Object} OptionChoiceInfo
4889 * @property {boolean | string} value - boolean for the option that is originally boolean type
4890 * @property {string} description
4891 * @property {string} [since] - undefined if available since the first version of the option
4892 * @property {string} [deprecated] - deprecated since version
4893 * @property {OptionValueInfo} [redirect] - redirect deprecated value
4896 /** @type {{ [name: string]: OptionInfo }} */
4901 category: CATEGORY_SPECIAL,
4909 description: dedent_1(_templateObject()),
4910 cliCategory: CATEGORY_EDITOR
4914 category: CATEGORY_GLOBAL,
4923 description: "Which end of line characters to apply.",
4926 description: "Line Feed only (\\n), common on Linux and macOS as well as inside git repos"
4929 description: "Carriage Return + Line Feed characters (\\r\\n), common on Windows"
4932 description: "Carriage Return character only (\\r), used very rarely"
4935 description: dedent_1(_templateObject2())
4940 category: CATEGORY_SPECIAL,
4942 description: "Specify the input filepath. This will be used to do parser inference.",
4943 cliName: "stdin-filepath",
4944 cliCategory: CATEGORY_OTHER,
4945 cliDescription: "Path to the file to pretend that stdin comes from."
4949 category: CATEGORY_SPECIAL,
4952 description: "Insert @format pragma into file's first docblock comment.",
4953 cliCategory: CATEGORY_OTHER
4957 category: CATEGORY_GLOBAL,
4966 description: "Which parser to use.",
4967 exception: value => typeof value === "string" || typeof value === "function",
4974 description: "JavaScript"
4976 value: "babel-flow",
4982 description: "TypeScript"
4984 value: "typescript",
4986 description: "TypeScript"
5006 description: "JSON5"
5008 value: "json-stringify",
5010 description: "JSON.stringify"
5014 description: "GraphQL"
5018 description: "Markdown"
5034 description: "Handlebars"
5042 description: "Angular"
5046 description: "Lightning Web Components"
5056 category: CATEGORY_GLOBAL,
5057 description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.",
5058 exception: value => typeof value === "string" || typeof value === "object",
5060 cliCategory: CATEGORY_CONFIG
5069 category: CATEGORY_GLOBAL,
5070 description: dedent_1(_templateObject3()),
5071 exception: value => typeof value === "string" || typeof value === "object",
5072 cliName: "plugin-search-dir",
5073 cliCategory: CATEGORY_CONFIG
5077 category: CATEGORY_GLOBAL,
5080 description: "The line length where Prettier will try wrap.",
5089 category: CATEGORY_SPECIAL,
5097 description: dedent_1(_templateObject4()),
5098 cliCategory: CATEGORY_EDITOR
5102 category: CATEGORY_SPECIAL,
5110 description: dedent_1(_templateObject5()),
5111 cliCategory: CATEGORY_EDITOR
5115 category: CATEGORY_SPECIAL,
5118 description: dedent_1(_templateObject6()),
5119 cliCategory: CATEGORY_OTHER
5123 category: CATEGORY_GLOBAL,
5125 description: "Number of spaces per indentation level.",
5134 category: CATEGORY_GLOBAL,
5137 description: "Indent with tabs instead of spaces."
5151 var require$$0 = getCjsExportFromNamespace(_package$1);
5158 const currentVersion = require$$0.version;
5159 const coreOptions$1 = coreOptions.options;
5161 * Strings in `plugins` and `pluginSearchDirs` are handled by a wrapped version
5162 * of this function created by `withPlugins`. Don't pass them here directly.
5163 * @param {object} param0
5164 * @param {(string | object)[]=} param0.plugins Strings are resolved by `withPlugins`.
5165 * @param {string[]=} param0.pluginSearchDirs Added by `withPlugins`.
5166 * @param {boolean=} param0.showUnreleased
5167 * @param {boolean=} param0.showDeprecated
5168 * @param {boolean=} param0.showInternal
5171 function getSupportInfo({
5173 showUnreleased = false,
5174 showDeprecated = false,
5175 showInternal = false
5177 // pre-release version is smaller than the normal version in semver,
5178 // we need to treat it as the normal one so as to test new features.
5179 const version = currentVersion.split("-", 1)[0];
5180 const options = arrayify(Object.assign({}, ...plugins.map(({
5182 }) => options), coreOptions$1), "name").filter(option => filterSince(option) && filterDeprecated(option)).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1).map(mapInternal).map(option => {
5183 option = Object.assign({}, option);
5185 if (Array.isArray(option.default)) {
5186 option.default = option.default.length === 1 ? option.default[0].value : option.default.filter(filterSince).sort((info1, info2) => semver$1.compare(info2.since, info1.since))[0].value;
5189 if (Array.isArray(option.choices)) {
5190 option.choices = option.choices.filter(option => filterSince(option) && filterDeprecated(option));
5193 const filteredPlugins = plugins.filter(plugin => plugin.defaultOptions && plugin.defaultOptions[option.name] !== undefined);
5194 const pluginDefaults = filteredPlugins.reduce((reduced, plugin) => {
5195 reduced[plugin.name] = plugin.defaultOptions[option.name];
5198 return Object.assign({}, option, {
5202 const languages = plugins.reduce((all, plugin) => all.concat(plugin.languages || []), []).filter(filterSince);
5208 function filterSince(object) {
5209 return showUnreleased || !("since" in object) || object.since && semver$1.gte(version, object.since);
5212 function filterDeprecated(object) {
5213 return showDeprecated || !("deprecated" in object) || object.deprecated && semver$1.lt(version, object.deprecated);
5216 function mapInternal(object) {
5221 const newObject = _objectWithoutPropertiesLoose(object, ["cliName", "cliCategory", "cliDescription"]);
5231 /*! *****************************************************************************
\r
5232 Copyright (c) Microsoft Corporation. All rights reserved.
\r
5233 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
\r
5234 this file except in compliance with the License. You may obtain a copy of the
\r
5235 License at http://www.apache.org/licenses/LICENSE-2.0
\r
5237 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
\r
5238 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
\r
5239 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
\r
5240 MERCHANTABLITY OR NON-INFRINGEMENT.
\r
5242 See the Apache Version 2.0 License for specific language governing permissions
\r
5243 and limitations under the License.
\r
5244 ***************************************************************************** */
5246 /* global Reflect, Promise */
5247 var _extendStatics = function extendStatics(d, b) {
5248 _extendStatics = Object.setPrototypeOf || {
5250 } instanceof Array && function (d, b) {
5252 } || function (d, b) {
5253 for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
5256 return _extendStatics(d, b);
5259 function __extends(d, b) {
5260 _extendStatics(d, b);
5263 this.constructor = d;
5266 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5269 var _assign = function __assign() {
5270 _assign = Object.assign || function __assign(t) {
5271 for (var s, i = 1, n = arguments.length; i < n; i++) {
5274 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
5280 return _assign.apply(this, arguments);
5282 function __rest(s, e) {
5285 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
5287 if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
5288 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
5292 function __decorate(decorators, target, key, desc) {
5293 var c = arguments.length,
5294 r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
5296 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5297 return c > 3 && r && Object.defineProperty(target, key, r), r;
5299 function __param(paramIndex, decorator) {
5300 return function (target, key) {
5301 decorator(target, key, paramIndex);
5304 function __metadata(metadataKey, metadataValue) {
5305 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
5307 function __awaiter(thisArg, _arguments, P, generator) {
5308 return new (P || (P = Promise))(function (resolve, reject) {
5309 function fulfilled(value) {
5311 step(generator.next(value));
5317 function rejected(value) {
5319 step(generator["throw"](value));
5325 function step(result) {
5326 result.done ? resolve(result.value) : new P(function (resolve) {
5327 resolve(result.value);
5328 }).then(fulfilled, rejected);
5331 step((generator = generator.apply(thisArg, _arguments || [])).next());
5334 function __generator(thisArg, body) {
5337 sent: function sent() {
5338 if (t[0] & 1) throw t[1];
5352 }, typeof Symbol === "function" && (g[Symbol.iterator] = function () {
5357 return function (v) {
5358 return step([n, v]);
5363 if (f) throw new TypeError("Generator is already executing.");
5366 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;
5367 if (y = 0, t) op = [op[0] & 2, t.value];
5396 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
5401 if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
5406 if (op[0] === 6 && _.label < t[1]) {
5412 if (t && _.label < t[2]) {
5420 if (t[2]) _.ops.pop();
5427 op = body.call(thisArg, _);
5435 if (op[0] & 5) throw op[1];
5437 value: op[0] ? op[1] : void 0,
5442 function __exportStar(m, exports) {
5443 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
5445 function __values(o) {
5446 var m = typeof Symbol === "function" && o[Symbol.iterator],
5448 if (m) return m.call(o);
5450 next: function next() {
5451 if (o && i >= o.length) o = void 0;
5459 function __read(o, n) {
5460 var m = typeof Symbol === "function" && o[Symbol.iterator];
5468 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
5475 if (r && !r.done && (m = i["return"])) m.call(i);
5477 if (e) throw e.error;
5483 function __spread() {
5484 for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
5488 function __spreadArrays() {
5489 for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
5491 for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j];
5495 function __await(v) {
5496 return this instanceof __await ? (this.v = v, this) : new __await(v);
5498 function __asyncGenerator(thisArg, _arguments, generator) {
5499 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
5500 var g = generator.apply(thisArg, _arguments || []),
5503 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () {
5508 if (g[n]) i[n] = function (v) {
5509 return new Promise(function (a, b) {
5510 q.push([n, v, a, b]) > 1 || resume(n, v);
5515 function resume(n, v) {
5524 r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
5527 function fulfill(value) {
5528 resume("next", value);
5531 function reject(value) {
5532 resume("throw", value);
5535 function settle(f, v) {
5536 if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
5539 function __asyncDelegator(o) {
5541 return i = {}, verb("next"), verb("throw", function (e) {
5543 }), verb("return"), i[Symbol.iterator] = function () {
5547 function verb(n, f) {
5548 i[n] = o[n] ? function (v) {
5550 value: __await(o[n](v)),
5551 done: n === "return"
5556 function __asyncValues(o) {
5557 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
5558 var m = o[Symbol.asyncIterator],
5560 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 () {
5565 i[n] = o[n] && function (v) {
5566 return new Promise(function (resolve, reject) {
5567 v = o[n](v), settle(resolve, reject, v.done, v.value);
5572 function settle(resolve, reject, d, v) {
5573 Promise.resolve(v).then(function (v) {
5581 function __makeTemplateObject(cooked, raw) {
5582 if (Object.defineProperty) {
5583 Object.defineProperty(cooked, "raw", {
5592 function __importStar(mod) {
5593 if (mod && mod.__esModule) return mod;
5595 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
5596 result.default = mod;
5599 function __importDefault(mod) {
5600 return mod && mod.__esModule ? mod : {
5605 var tslib_es6 = /*#__PURE__*/Object.freeze({
5607 __extends: __extends,
5608 get __assign () { return _assign; },
5610 __decorate: __decorate,
5612 __metadata: __metadata,
5613 __awaiter: __awaiter,
5614 __generator: __generator,
5615 __exportStar: __exportStar,
5619 __spreadArrays: __spreadArrays,
5621 __asyncGenerator: __asyncGenerator,
5622 __asyncDelegator: __asyncDelegator,
5623 __asyncValues: __asyncValues,
5624 __makeTemplateObject: __makeTemplateObject,
5625 __importStar: __importStar,
5626 __importDefault: __importDefault
5629 var api = createCommonjsModule(function (module, exports) {
5631 Object.defineProperty(exports, "__esModule", {
5634 exports.apiDescriptor = {
5635 key: _key => /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(_key) ? _key : JSON.stringify(_key),
5638 if (value === null || typeof value !== 'object') {
5639 return JSON.stringify(value);
5642 if (Array.isArray(value)) {
5643 return "[".concat(value.map(subValue => exports.apiDescriptor.value(subValue)).join(', '), "]");
5646 const keys = Object.keys(value);
5647 return keys.length === 0 ? '{}' : "{ ".concat(keys.map(key => "".concat(exports.apiDescriptor.key(key), ": ").concat(exports.apiDescriptor.value(value[key]))).join(', '), " }");
5653 }) => exports.apiDescriptor.value({
5659 var api_1 = api.apiDescriptor;
5661 var tslib_1 = getCjsExportFromNamespace(tslib_es6);
5663 var descriptors = createCommonjsModule(function (module, exports) {
5665 Object.defineProperty(exports, "__esModule", {
5669 tslib_1.__exportStar(api, exports);
5671 unwrapExports(descriptors);
5673 var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
5675 var escapeStringRegexp = function escapeStringRegexp(str) {
5676 if (typeof str !== 'string') {
5677 throw new TypeError('Expected a string');
5680 return str.replace(matchOperatorsRe, '\\$&');
5684 "aliceblue": [240, 248, 255],
5685 "antiquewhite": [250, 235, 215],
5686 "aqua": [0, 255, 255],
5687 "aquamarine": [127, 255, 212],
5688 "azure": [240, 255, 255],
5689 "beige": [245, 245, 220],
5690 "bisque": [255, 228, 196],
5692 "blanchedalmond": [255, 235, 205],
5693 "blue": [0, 0, 255],
5694 "blueviolet": [138, 43, 226],
5695 "brown": [165, 42, 42],
5696 "burlywood": [222, 184, 135],
5697 "cadetblue": [95, 158, 160],
5698 "chartreuse": [127, 255, 0],
5699 "chocolate": [210, 105, 30],
5700 "coral": [255, 127, 80],
5701 "cornflowerblue": [100, 149, 237],
5702 "cornsilk": [255, 248, 220],
5703 "crimson": [220, 20, 60],
5704 "cyan": [0, 255, 255],
5705 "darkblue": [0, 0, 139],
5706 "darkcyan": [0, 139, 139],
5707 "darkgoldenrod": [184, 134, 11],
5708 "darkgray": [169, 169, 169],
5709 "darkgreen": [0, 100, 0],
5710 "darkgrey": [169, 169, 169],
5711 "darkkhaki": [189, 183, 107],
5712 "darkmagenta": [139, 0, 139],
5713 "darkolivegreen": [85, 107, 47],
5714 "darkorange": [255, 140, 0],
5715 "darkorchid": [153, 50, 204],
5716 "darkred": [139, 0, 0],
5717 "darksalmon": [233, 150, 122],
5718 "darkseagreen": [143, 188, 143],
5719 "darkslateblue": [72, 61, 139],
5720 "darkslategray": [47, 79, 79],
5721 "darkslategrey": [47, 79, 79],
5722 "darkturquoise": [0, 206, 209],
5723 "darkviolet": [148, 0, 211],
5724 "deeppink": [255, 20, 147],
5725 "deepskyblue": [0, 191, 255],
5726 "dimgray": [105, 105, 105],
5727 "dimgrey": [105, 105, 105],
5728 "dodgerblue": [30, 144, 255],
5729 "firebrick": [178, 34, 34],
5730 "floralwhite": [255, 250, 240],
5731 "forestgreen": [34, 139, 34],
5732 "fuchsia": [255, 0, 255],
5733 "gainsboro": [220, 220, 220],
5734 "ghostwhite": [248, 248, 255],
5735 "gold": [255, 215, 0],
5736 "goldenrod": [218, 165, 32],
5737 "gray": [128, 128, 128],
5738 "green": [0, 128, 0],
5739 "greenyellow": [173, 255, 47],
5740 "grey": [128, 128, 128],
5741 "honeydew": [240, 255, 240],
5742 "hotpink": [255, 105, 180],
5743 "indianred": [205, 92, 92],
5744 "indigo": [75, 0, 130],
5745 "ivory": [255, 255, 240],
5746 "khaki": [240, 230, 140],
5747 "lavender": [230, 230, 250],
5748 "lavenderblush": [255, 240, 245],
5749 "lawngreen": [124, 252, 0],
5750 "lemonchiffon": [255, 250, 205],
5751 "lightblue": [173, 216, 230],
5752 "lightcoral": [240, 128, 128],
5753 "lightcyan": [224, 255, 255],
5754 "lightgoldenrodyellow": [250, 250, 210],
5755 "lightgray": [211, 211, 211],
5756 "lightgreen": [144, 238, 144],
5757 "lightgrey": [211, 211, 211],
5758 "lightpink": [255, 182, 193],
5759 "lightsalmon": [255, 160, 122],
5760 "lightseagreen": [32, 178, 170],
5761 "lightskyblue": [135, 206, 250],
5762 "lightslategray": [119, 136, 153],
5763 "lightslategrey": [119, 136, 153],
5764 "lightsteelblue": [176, 196, 222],
5765 "lightyellow": [255, 255, 224],
5766 "lime": [0, 255, 0],
5767 "limegreen": [50, 205, 50],
5768 "linen": [250, 240, 230],
5769 "magenta": [255, 0, 255],
5770 "maroon": [128, 0, 0],
5771 "mediumaquamarine": [102, 205, 170],
5772 "mediumblue": [0, 0, 205],
5773 "mediumorchid": [186, 85, 211],
5774 "mediumpurple": [147, 112, 219],
5775 "mediumseagreen": [60, 179, 113],
5776 "mediumslateblue": [123, 104, 238],
5777 "mediumspringgreen": [0, 250, 154],
5778 "mediumturquoise": [72, 209, 204],
5779 "mediumvioletred": [199, 21, 133],
5780 "midnightblue": [25, 25, 112],
5781 "mintcream": [245, 255, 250],
5782 "mistyrose": [255, 228, 225],
5783 "moccasin": [255, 228, 181],
5784 "navajowhite": [255, 222, 173],
5785 "navy": [0, 0, 128],
5786 "oldlace": [253, 245, 230],
5787 "olive": [128, 128, 0],
5788 "olivedrab": [107, 142, 35],
5789 "orange": [255, 165, 0],
5790 "orangered": [255, 69, 0],
5791 "orchid": [218, 112, 214],
5792 "palegoldenrod": [238, 232, 170],
5793 "palegreen": [152, 251, 152],
5794 "paleturquoise": [175, 238, 238],
5795 "palevioletred": [219, 112, 147],
5796 "papayawhip": [255, 239, 213],
5797 "peachpuff": [255, 218, 185],
5798 "peru": [205, 133, 63],
5799 "pink": [255, 192, 203],
5800 "plum": [221, 160, 221],
5801 "powderblue": [176, 224, 230],
5802 "purple": [128, 0, 128],
5803 "rebeccapurple": [102, 51, 153],
5805 "rosybrown": [188, 143, 143],
5806 "royalblue": [65, 105, 225],
5807 "saddlebrown": [139, 69, 19],
5808 "salmon": [250, 128, 114],
5809 "sandybrown": [244, 164, 96],
5810 "seagreen": [46, 139, 87],
5811 "seashell": [255, 245, 238],
5812 "sienna": [160, 82, 45],
5813 "silver": [192, 192, 192],
5814 "skyblue": [135, 206, 235],
5815 "slateblue": [106, 90, 205],
5816 "slategray": [112, 128, 144],
5817 "slategrey": [112, 128, 144],
5818 "snow": [255, 250, 250],
5819 "springgreen": [0, 255, 127],
5820 "steelblue": [70, 130, 180],
5821 "tan": [210, 180, 140],
5822 "teal": [0, 128, 128],
5823 "thistle": [216, 191, 216],
5824 "tomato": [255, 99, 71],
5825 "turquoise": [64, 224, 208],
5826 "violet": [238, 130, 238],
5827 "wheat": [245, 222, 179],
5828 "white": [255, 255, 255],
5829 "whitesmoke": [245, 245, 245],
5830 "yellow": [255, 255, 0],
5831 "yellowgreen": [154, 205, 50]
5834 var conversions = createCommonjsModule(function (module) {
5836 // NOTE: conversions should only return primitive values (i.e. arrays, or
5837 // values that give correct `typeof` results).
5838 // do not use box values types (i.e. Number(), String(), etc.)
5839 var reverseKeywords = {};
5841 for (var key in colorName) {
5842 if (colorName.hasOwnProperty(key)) {
5843 reverseKeywords[colorName[key]] = key;
5847 var convert = module.exports = {
5898 labels: ['h', 'c', 'g']
5902 labels: ['r16', 'g16', 'b16']
5908 }; // hide .channels and .labels properties
5910 for (var model in convert) {
5911 if (convert.hasOwnProperty(model)) {
5912 if (!('channels' in convert[model])) {
5913 throw new Error('missing channels property: ' + model);
5916 if (!('labels' in convert[model])) {
5917 throw new Error('missing channel labels property: ' + model);
5920 if (convert[model].labels.length !== convert[model].channels) {
5921 throw new Error('channel and label counts mismatch: ' + model);
5924 var channels = convert[model].channels;
5925 var labels = convert[model].labels;
5926 delete convert[model].channels;
5927 delete convert[model].labels;
5928 Object.defineProperty(convert[model], 'channels', {
5931 Object.defineProperty(convert[model], 'labels', {
5937 convert.rgb.hsl = function (rgb) {
5938 var r = rgb[0] / 255;
5939 var g = rgb[1] / 255;
5940 var b = rgb[2] / 255;
5941 var min = Math.min(r, g, b);
5942 var max = Math.max(r, g, b);
5943 var delta = max - min;
5950 } else if (r === max) {
5951 h = (g - b) / delta;
5952 } else if (g === max) {
5953 h = 2 + (b - r) / delta;
5954 } else if (b === max) {
5955 h = 4 + (r - g) / delta;
5958 h = Math.min(h * 60, 360);
5964 l = (min + max) / 2;
5968 } else if (l <= 0.5) {
5969 s = delta / (max + min);
5971 s = delta / (2 - max - min);
5974 return [h, s * 100, l * 100];
5977 convert.rgb.hsv = function (rgb) {
5983 var r = rgb[0] / 255;
5984 var g = rgb[1] / 255;
5985 var b = rgb[2] / 255;
5986 var v = Math.max(r, g, b);
5987 var diff = v - Math.min(r, g, b);
5989 var diffc = function diffc(c) {
5990 return (v - c) / 6 / diff + 1 / 2;
6003 } else if (g === v) {
6004 h = 1 / 3 + rdif - bdif;
6005 } else if (b === v) {
6006 h = 2 / 3 + gdif - rdif;
6016 return [h * 360, s * 100, v * 100];
6019 convert.rgb.hwb = function (rgb) {
6023 var h = convert.rgb.hsl(rgb)[0];
6024 var w = 1 / 255 * Math.min(r, Math.min(g, b));
6025 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
6026 return [h, w * 100, b * 100];
6029 convert.rgb.cmyk = function (rgb) {
6030 var r = rgb[0] / 255;
6031 var g = rgb[1] / 255;
6032 var b = rgb[2] / 255;
6037 k = Math.min(1 - r, 1 - g, 1 - b);
6038 c = (1 - r - k) / (1 - k) || 0;
6039 m = (1 - g - k) / (1 - k) || 0;
6040 y = (1 - b - k) / (1 - k) || 0;
6041 return [c * 100, m * 100, y * 100, k * 100];
6044 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
6048 function comparativeDistance(x, y) {
6049 return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
6052 convert.rgb.keyword = function (rgb) {
6053 var reversed = reverseKeywords[rgb];
6059 var currentClosestDistance = Infinity;
6060 var currentClosestKeyword;
6062 for (var keyword in colorName) {
6063 if (colorName.hasOwnProperty(keyword)) {
6064 var value = colorName[keyword]; // Compute comparative distance
6066 var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
6068 if (distance < currentClosestDistance) {
6069 currentClosestDistance = distance;
6070 currentClosestKeyword = keyword;
6075 return currentClosestKeyword;
6078 convert.keyword.rgb = function (keyword) {
6079 return colorName[keyword];
6082 convert.rgb.xyz = function (rgb) {
6083 var r = rgb[0] / 255;
6084 var g = rgb[1] / 255;
6085 var b = rgb[2] / 255; // assume sRGB
6087 r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
6088 g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
6089 b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
6090 var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
6091 var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
6092 var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
6093 return [x * 100, y * 100, z * 100];
6096 convert.rgb.lab = function (rgb) {
6097 var xyz = convert.rgb.xyz(rgb);
6107 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
6108 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
6109 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
6116 convert.hsl.rgb = function (hsl) {
6117 var h = hsl[0] / 360;
6118 var s = hsl[1] / 100;
6119 var l = hsl[2] / 100;
6128 return [val, val, val];
6140 for (var i = 0; i < 3; i++) {
6141 t3 = h + 1 / 3 * -(i - 1);
6152 val = t1 + (t2 - t1) * 6 * t3;
6153 } else if (2 * t3 < 1) {
6155 } else if (3 * t3 < 2) {
6156 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
6167 convert.hsl.hsv = function (hsl) {
6169 var s = hsl[1] / 100;
6170 var l = hsl[2] / 100;
6172 var lmin = Math.max(l, 0.01);
6176 s *= l <= 1 ? l : 2 - l;
6177 smin *= lmin <= 1 ? lmin : 2 - lmin;
6179 sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
6180 return [h, sv * 100, v * 100];
6183 convert.hsv.rgb = function (hsv) {
6184 var h = hsv[0] / 60;
6185 var s = hsv[1] / 100;
6186 var v = hsv[2] / 100;
6187 var hi = Math.floor(h) % 6;
6188 var f = h - Math.floor(h);
6189 var p = 255 * v * (1 - s);
6190 var q = 255 * v * (1 - s * f);
6191 var t = 255 * v * (1 - s * (1 - f));
6215 convert.hsv.hsl = function (hsv) {
6217 var s = hsv[1] / 100;
6218 var v = hsv[2] / 100;
6219 var vmin = Math.max(v, 0.01);
6224 lmin = (2 - s) * vmin;
6226 sl /= lmin <= 1 ? lmin : 2 - lmin;
6229 return [h, sl * 100, l * 100];
6230 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
6233 convert.hwb.rgb = function (hwb) {
6234 var h = hwb[0] / 360;
6235 var wh = hwb[1] / 100;
6236 var bl = hwb[2] / 100;
6237 var ratio = wh + bl;
6241 var n; // wh + bl cant be > 1
6248 i = Math.floor(6 * h);
6252 if ((i & 0x01) !== 0) {
6256 n = wh + f * (v - wh); // linear interpolation
6302 return [r * 255, g * 255, b * 255];
6305 convert.cmyk.rgb = function (cmyk) {
6306 var c = cmyk[0] / 100;
6307 var m = cmyk[1] / 100;
6308 var y = cmyk[2] / 100;
6309 var k = cmyk[3] / 100;
6313 r = 1 - Math.min(1, c * (1 - k) + k);
6314 g = 1 - Math.min(1, m * (1 - k) + k);
6315 b = 1 - Math.min(1, y * (1 - k) + k);
6316 return [r * 255, g * 255, b * 255];
6319 convert.xyz.rgb = function (xyz) {
6320 var x = xyz[0] / 100;
6321 var y = xyz[1] / 100;
6322 var z = xyz[2] / 100;
6326 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
6327 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
6328 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
6330 r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
6331 g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
6332 b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
6333 r = Math.min(Math.max(0, r), 1);
6334 g = Math.min(Math.max(0, g), 1);
6335 b = Math.min(Math.max(0, b), 1);
6336 return [r * 255, g * 255, b * 255];
6339 convert.xyz.lab = function (xyz) {
6349 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
6350 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
6351 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
6358 convert.lab.xyz = function (lab) {
6368 var y2 = Math.pow(y, 3);
6369 var x2 = Math.pow(x, 3);
6370 var z2 = Math.pow(z, 3);
6371 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
6372 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
6373 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
6380 convert.lab.lch = function (lab) {
6387 hr = Math.atan2(b, a);
6388 h = hr * 360 / 2 / Math.PI;
6394 c = Math.sqrt(a * a + b * b);
6398 convert.lch.lab = function (lch) {
6405 hr = h / 360 * 2 * Math.PI;
6406 a = c * Math.cos(hr);
6407 b = c * Math.sin(hr);
6411 convert.rgb.ansi16 = function (args) {
6415 var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
6417 value = Math.round(value / 50);
6423 var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
6432 convert.hsv.ansi16 = function (args) {
6433 // optimization here; we already know the value and don't need to get
6434 // it converted for us.
6435 return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
6438 convert.rgb.ansi256 = function (args) {
6441 var b = args[2]; // we use the extended greyscale palette here, with the exception of
6442 // black and white. normal palette only has 4 greyscale shades.
6444 if (r === g && g === b) {
6453 return Math.round((r - 8) / 247 * 24) + 232;
6456 var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
6460 convert.ansi16.rgb = function (args) {
6461 var color = args % 10; // handle greyscale
6463 if (color === 0 || color === 7) {
6468 color = color / 10.5 * 255;
6469 return [color, color, color];
6472 var mult = (~~(args > 50) + 1) * 0.5;
6473 var r = (color & 1) * mult * 255;
6474 var g = (color >> 1 & 1) * mult * 255;
6475 var b = (color >> 2 & 1) * mult * 255;
6479 convert.ansi256.rgb = function (args) {
6482 var c = (args - 232) * 10 + 8;
6488 var r = Math.floor(args / 36) / 5 * 255;
6489 var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
6490 var b = rem % 6 / 5 * 255;
6494 convert.rgb.hex = function (args) {
6495 var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
6496 var string = integer.toString(16).toUpperCase();
6497 return '000000'.substring(string.length) + string;
6500 convert.hex.rgb = function (args) {
6501 var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
6507 var colorString = match[0];
6509 if (match[0].length === 3) {
6510 colorString = colorString.split('').map(function (char) {
6515 var integer = parseInt(colorString, 16);
6516 var r = integer >> 16 & 0xFF;
6517 var g = integer >> 8 & 0xFF;
6518 var b = integer & 0xFF;
6522 convert.rgb.hcg = function (rgb) {
6523 var r = rgb[0] / 255;
6524 var g = rgb[1] / 255;
6525 var b = rgb[2] / 255;
6526 var max = Math.max(Math.max(r, g), b);
6527 var min = Math.min(Math.min(r, g), b);
6528 var chroma = max - min;
6533 grayscale = min / (1 - chroma);
6540 } else if (max === r) {
6541 hue = (g - b) / chroma % 6;
6542 } else if (max === g) {
6543 hue = 2 + (b - r) / chroma;
6545 hue = 4 + (r - g) / chroma + 4;
6550 return [hue * 360, chroma * 100, grayscale * 100];
6553 convert.hsl.hcg = function (hsl) {
6554 var s = hsl[1] / 100;
6555 var l = hsl[2] / 100;
6562 c = 2.0 * s * (1.0 - l);
6566 f = (l - 0.5 * c) / (1.0 - c);
6569 return [hsl[0], c * 100, f * 100];
6572 convert.hsv.hcg = function (hsv) {
6573 var s = hsv[1] / 100;
6574 var v = hsv[2] / 100;
6579 f = (v - c) / (1 - c);
6582 return [hsv[0], c * 100, f * 100];
6585 convert.hcg.rgb = function (hcg) {
6586 var h = hcg[0] / 360;
6587 var c = hcg[1] / 100;
6588 var g = hcg[2] / 100;
6591 return [g * 255, g * 255, g * 255];
6594 var pure = [0, 0, 0];
6600 switch (Math.floor(hi)) {
6638 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
6641 convert.hcg.hsv = function (hcg) {
6642 var c = hcg[1] / 100;
6643 var g = hcg[2] / 100;
6644 var v = c + g * (1.0 - c);
6651 return [hcg[0], f * 100, v * 100];
6654 convert.hcg.hsl = function (hcg) {
6655 var c = hcg[1] / 100;
6656 var g = hcg[2] / 100;
6657 var l = g * (1.0 - c) + 0.5 * c;
6660 if (l > 0.0 && l < 0.5) {
6662 } else if (l >= 0.5 && l < 1.0) {
6663 s = c / (2 * (1 - l));
6666 return [hcg[0], s * 100, l * 100];
6669 convert.hcg.hwb = function (hcg) {
6670 var c = hcg[1] / 100;
6671 var g = hcg[2] / 100;
6672 var v = c + g * (1.0 - c);
6673 return [hcg[0], (v - c) * 100, (1 - v) * 100];
6676 convert.hwb.hcg = function (hwb) {
6677 var w = hwb[1] / 100;
6678 var b = hwb[2] / 100;
6684 g = (v - c) / (1 - c);
6687 return [hwb[0], c * 100, g * 100];
6690 convert.apple.rgb = function (apple) {
6691 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
6694 convert.rgb.apple = function (rgb) {
6695 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
6698 convert.gray.rgb = function (args) {
6699 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
6702 convert.gray.hsl = convert.gray.hsv = function (args) {
6703 return [0, 0, args[0]];
6706 convert.gray.hwb = function (gray) {
6707 return [0, 100, gray[0]];
6710 convert.gray.cmyk = function (gray) {
6711 return [0, 0, 0, gray[0]];
6714 convert.gray.lab = function (gray) {
6715 return [gray[0], 0, 0];
6718 convert.gray.hex = function (gray) {
6719 var val = Math.round(gray[0] / 100 * 255) & 0xFF;
6720 var integer = (val << 16) + (val << 8) + val;
6721 var string = integer.toString(16).toUpperCase();
6722 return '000000'.substring(string.length) + string;
6725 convert.rgb.gray = function (rgb) {
6726 var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
6727 return [val / 255 * 100];
6730 var conversions_1 = conversions.rgb;
6731 var conversions_2 = conversions.hsl;
6732 var conversions_3 = conversions.hsv;
6733 var conversions_4 = conversions.hwb;
6734 var conversions_5 = conversions.cmyk;
6735 var conversions_6 = conversions.xyz;
6736 var conversions_7 = conversions.lab;
6737 var conversions_8 = conversions.lch;
6738 var conversions_9 = conversions.hex;
6739 var conversions_10 = conversions.keyword;
6740 var conversions_11 = conversions.ansi16;
6741 var conversions_12 = conversions.ansi256;
6742 var conversions_13 = conversions.hcg;
6743 var conversions_14 = conversions.apple;
6744 var conversions_15 = conversions.gray;
6747 this function routes a model to all other models.
6749 all functions that are routed have a property `.conversion` attached
6750 to the returned synthetic function. This property is an array
6751 of strings, each with the steps in between the 'from' and 'to'
6752 color models (inclusive).
6754 conversions that are not possible simply are not included.
6757 function buildGraph() {
6758 var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
6760 var models = Object.keys(conversions);
6762 for (var len = models.length, i = 0; i < len; i++) {
6763 graph[models[i]] = {
6764 // http://jsperf.com/1-vs-infinity
6765 // micro-opt, but this is simple.
6772 } // https://en.wikipedia.org/wiki/Breadth-first_search
6775 function deriveBFS(fromModel) {
6776 var graph = buildGraph();
6777 var queue = [fromModel]; // unshift -> queue -> pop
6779 graph[fromModel].distance = 0;
6781 while (queue.length) {
6782 var current = queue.pop();
6783 var adjacents = Object.keys(conversions[current]);
6785 for (var len = adjacents.length, i = 0; i < len; i++) {
6786 var adjacent = adjacents[i];
6787 var node = graph[adjacent];
6789 if (node.distance === -1) {
6790 node.distance = graph[current].distance + 1;
6791 node.parent = current;
6792 queue.unshift(adjacent);
6800 function link(from, to) {
6801 return function (args) {
6802 return to(from(args));
6806 function wrapConversion(toModel, graph) {
6807 var path = [graph[toModel].parent, toModel];
6808 var fn = conversions[graph[toModel].parent][toModel];
6809 var cur = graph[toModel].parent;
6811 while (graph[cur].parent) {
6812 path.unshift(graph[cur].parent);
6813 fn = link(conversions[graph[cur].parent][cur], fn);
6814 cur = graph[cur].parent;
6817 fn.conversion = path;
6821 var route = function route(fromModel) {
6822 var graph = deriveBFS(fromModel);
6823 var conversion = {};
6824 var models = Object.keys(graph);
6826 for (var len = models.length, i = 0; i < len; i++) {
6827 var toModel = models[i];
6828 var node = graph[toModel];
6830 if (node.parent === null) {
6831 // no possible conversion, or this node is the source model.
6835 conversion[toModel] = wrapConversion(toModel, graph);
6842 var models = Object.keys(conversions);
6844 function wrapRaw(fn) {
6845 var wrappedFn = function wrappedFn(args) {
6846 if (args === undefined || args === null) {
6850 if (arguments.length > 1) {
6851 args = Array.prototype.slice.call(arguments);
6855 }; // preserve .conversion property if there is one
6858 if ('conversion' in fn) {
6859 wrappedFn.conversion = fn.conversion;
6865 function wrapRounded(fn) {
6866 var wrappedFn = function wrappedFn(args) {
6867 if (args === undefined || args === null) {
6871 if (arguments.length > 1) {
6872 args = Array.prototype.slice.call(arguments);
6875 var result = fn(args); // we're assuming the result is an array here.
6876 // see notice in conversions.js; don't use box types
6877 // in conversion functions.
6879 if (typeof result === 'object') {
6880 for (var len = result.length, i = 0; i < len; i++) {
6881 result[i] = Math.round(result[i]);
6886 }; // preserve .conversion property if there is one
6889 if ('conversion' in fn) {
6890 wrappedFn.conversion = fn.conversion;
6896 models.forEach(function (fromModel) {
6897 convert[fromModel] = {};
6898 Object.defineProperty(convert[fromModel], 'channels', {
6899 value: conversions[fromModel].channels
6901 Object.defineProperty(convert[fromModel], 'labels', {
6902 value: conversions[fromModel].labels
6904 var routes = route(fromModel);
6905 var routeModels = Object.keys(routes);
6906 routeModels.forEach(function (toModel) {
6907 var fn = routes[toModel];
6908 convert[fromModel][toModel] = wrapRounded(fn);
6909 convert[fromModel][toModel].raw = wrapRaw(fn);
6912 var colorConvert = convert;
6914 var ansiStyles = createCommonjsModule(function (module) {
6916 const wrapAnsi16 = (fn, offset) => function () {
6917 const code = fn.apply(colorConvert, arguments);
6918 return "\x1B[".concat(code + offset, "m");
6921 const wrapAnsi256 = (fn, offset) => function () {
6922 const code = fn.apply(colorConvert, arguments);
6923 return "\x1B[".concat(38 + offset, ";5;").concat(code, "m");
6926 const wrapAnsi16m = (fn, offset) => function () {
6927 const rgb = fn.apply(colorConvert, arguments);
6928 return "\x1B[".concat(38 + offset, ";2;").concat(rgb[0], ";").concat(rgb[1], ";").concat(rgb[2], "m");
6931 function assembleStyles() {
6932 const codes = new Map();
6936 // 21 isn't widely supported and 22 does the same thing
6943 strikethrough: [9, 29]
6956 redBright: [91, 39],
6957 greenBright: [92, 39],
6958 yellowBright: [93, 39],
6959 blueBright: [94, 39],
6960 magentaBright: [95, 39],
6961 cyanBright: [96, 39],
6962 whiteBright: [97, 39]
6970 bgMagenta: [45, 49],
6974 bgBlackBright: [100, 49],
6975 bgRedBright: [101, 49],
6976 bgGreenBright: [102, 49],
6977 bgYellowBright: [103, 49],
6978 bgBlueBright: [104, 49],
6979 bgMagentaBright: [105, 49],
6980 bgCyanBright: [106, 49],
6981 bgWhiteBright: [107, 49]
6985 styles.color.grey = styles.color.gray;
6987 for (const groupName of Object.keys(styles)) {
6988 const group = styles[groupName];
6990 for (const styleName of Object.keys(group)) {
6991 const style = group[styleName];
6992 styles[styleName] = {
6993 open: "\x1B[".concat(style[0], "m"),
6994 close: "\x1B[".concat(style[1], "m")
6996 group[styleName] = styles[styleName];
6997 codes.set(style[0], style[1]);
7000 Object.defineProperty(styles, groupName, {
7004 Object.defineProperty(styles, 'codes', {
7010 const ansi2ansi = n => n;
7012 const rgb2rgb = (r, g, b) => [r, g, b];
7014 styles.color.close = '\u001B[39m';
7015 styles.bgColor.close = '\u001B[49m';
7016 styles.color.ansi = {
7017 ansi: wrapAnsi16(ansi2ansi, 0)
7019 styles.color.ansi256 = {
7020 ansi256: wrapAnsi256(ansi2ansi, 0)
7022 styles.color.ansi16m = {
7023 rgb: wrapAnsi16m(rgb2rgb, 0)
7025 styles.bgColor.ansi = {
7026 ansi: wrapAnsi16(ansi2ansi, 10)
7028 styles.bgColor.ansi256 = {
7029 ansi256: wrapAnsi256(ansi2ansi, 10)
7031 styles.bgColor.ansi16m = {
7032 rgb: wrapAnsi16m(rgb2rgb, 10)
7035 for (let key of Object.keys(colorConvert)) {
7036 if (typeof colorConvert[key] !== 'object') {
7040 const suite = colorConvert[key];
7042 if (key === 'ansi16') {
7046 if ('ansi16' in suite) {
7047 styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
7048 styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
7051 if ('ansi256' in suite) {
7052 styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
7053 styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
7056 if ('rgb' in suite) {
7057 styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
7058 styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
7063 } // Make the export immutable
7066 Object.defineProperty(module, 'exports', {
7072 var require$$0$1 = {
7076 var hasFlag = (flag, argv) => {
7077 argv = argv || process.argv;
7078 const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
7079 const pos = argv.indexOf(prefix + flag);
7080 const terminatorPos = argv.indexOf('--');
7081 return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
7084 const env$1 = process.env;
7087 if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
7089 } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
7093 if ('FORCE_COLOR' in env$1) {
7094 forceColor = env$1.FORCE_COLOR.length === 0 || parseInt(env$1.FORCE_COLOR, 10) !== 0;
7097 function translateLevel(level) {
7110 function supportsColor(stream) {
7111 if (forceColor === false) {
7115 if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
7119 if (hasFlag('color=256')) {
7123 if (stream && !stream.isTTY && forceColor !== true) {
7127 const min = forceColor ? 1 : 0;
7129 if (process.platform === 'win32') {
7130 // Node.js 7.5.0 is the first version of Node.js to include a patch to
7131 // libuv that enables 256 color output on Windows. Anything earlier and it
7132 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
7133 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
7134 // release that supports 256 colors. Windows 10 build 14931 is the first release
7135 // that supports 16m/TrueColor.
7136 const osRelease = require$$0$1.release().split('.');
7138 if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
7139 return Number(osRelease[2]) >= 14931 ? 3 : 2;
7145 if ('CI' in env$1) {
7146 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') {
7153 if ('TEAMCITY_VERSION' in env$1) {
7154 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0;
7157 if (env$1.COLORTERM === 'truecolor') {
7161 if ('TERM_PROGRAM' in env$1) {
7162 const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
7164 switch (env$1.TERM_PROGRAM) {
7166 return version >= 3 ? 3 : 2;
7168 case 'Apple_Terminal':
7174 if (/-256(color)?$/i.test(env$1.TERM)) {
7178 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) {
7182 if ('COLORTERM' in env$1) {
7186 if (env$1.TERM === 'dumb') {
7193 function getSupportLevel(stream) {
7194 const level = supportsColor(stream);
7195 return translateLevel(level);
7198 var supportsColor_1 = {
7199 supportsColor: getSupportLevel,
7200 stdout: getSupportLevel(process.stdout),
7201 stderr: getSupportLevel(process.stderr)
7204 const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
7205 const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
7206 const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
7207 const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
7208 const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
7210 function unescape(c) {
7211 if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
7212 return String.fromCharCode(parseInt(c.slice(1), 16));
7215 return ESCAPES.get(c) || c;
7218 function parseArguments(name, args) {
7220 const chunks = args.trim().split(/\s*,\s*/g);
7223 for (const chunk of chunks) {
7224 if (!isNaN(chunk)) {
7225 results.push(Number(chunk));
7226 } else if (matches = chunk.match(STRING_REGEX)) {
7227 results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
7229 throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')"));
7236 function parseStyle(style) {
7237 STYLE_REGEX.lastIndex = 0;
7241 while ((matches = STYLE_REGEX.exec(style)) !== null) {
7242 const name = matches[1];
7245 const args = parseArguments(name, matches[2]);
7246 results.push([name].concat(args));
7248 results.push([name]);
7255 function buildStyle(chalk, styles) {
7258 for (const layer of styles) {
7259 for (const style of layer.styles) {
7260 enabled[style[0]] = layer.inverse ? null : style.slice(1);
7264 let current = chalk;
7266 for (const styleName of Object.keys(enabled)) {
7267 if (Array.isArray(enabled[styleName])) {
7268 if (!(styleName in current)) {
7269 throw new Error("Unknown Chalk style: ".concat(styleName));
7272 if (enabled[styleName].length > 0) {
7273 current = current[styleName].apply(current, enabled[styleName]);
7275 current = current[styleName];
7283 var templates = (chalk, tmp) => {
7286 let chunk = []; // eslint-disable-next-line max-params
7288 tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
7290 chunk.push(unescape(escapeChar));
7292 const str = chunk.join('');
7294 chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
7297 styles: parseStyle(style)
7300 if (styles.length === 0) {
7301 throw new Error('Found extraneous } in Chalk template literal');
7304 chunks.push(buildStyle(chalk, styles)(chunk.join('')));
7311 chunks.push(chunk.join(''));
7313 if (styles.length > 0) {
7314 const errMsg = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)");
7315 throw new Error(errMsg);
7318 return chunks.join('');
7321 var chalk = createCommonjsModule(function (module) {
7323 const stdoutColor = supportsColor_1.stdout;
7324 const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
7326 const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
7328 const skipModels = new Set(['gray']);
7329 const styles = Object.create(null);
7331 function applyOptions(obj, options) {
7332 options = options || {}; // Detect level if not set manually
7334 const scLevel = stdoutColor ? stdoutColor.level : 0;
7335 obj.level = options.level === undefined ? scLevel : options.level;
7336 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
7339 function Chalk(options) {
7340 // We check for this.template here since calling `chalk.constructor()`
7341 // by itself will have a `this` of a previously constructed chalk object
7342 if (!this || !(this instanceof Chalk) || this.template) {
7344 applyOptions(chalk, options);
7346 chalk.template = function () {
7347 const args = [].slice.call(arguments);
7348 return chalkTag.apply(null, [chalk.template].concat(args));
7351 Object.setPrototypeOf(chalk, Chalk.prototype);
7352 Object.setPrototypeOf(chalk.template, chalk);
7353 chalk.template.constructor = Chalk;
7354 return chalk.template;
7357 applyOptions(this, options);
7358 } // Use bright blue on Windows as the normal blue color is illegible
7361 if (isSimpleWindowsTerm) {
7362 ansiStyles.blue.open = '\u001B[94m';
7365 for (const key of Object.keys(ansiStyles)) {
7366 ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
7369 const codes = ansiStyles[key];
7370 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
7378 return build.call(this, this._styles || [], true, 'visible');
7382 ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
7384 for (const model of Object.keys(ansiStyles.color.ansi)) {
7385 if (skipModels.has(model)) {
7391 const level = this.level;
7392 return function () {
7393 const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
7396 close: ansiStyles.color.close,
7397 closeRe: ansiStyles.color.closeRe
7399 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
7406 ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
7408 for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
7409 if (skipModels.has(model)) {
7413 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
7416 const level = this.level;
7417 return function () {
7418 const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
7421 close: ansiStyles.bgColor.close,
7422 closeRe: ansiStyles.bgColor.closeRe
7424 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
7431 const proto = Object.defineProperties(() => {}, styles);
7433 function build(_styles, _empty, key) {
7434 const builder = function builder() {
7435 return applyStyle.apply(builder, arguments);
7438 builder._styles = _styles;
7439 builder._empty = _empty;
7441 Object.defineProperty(builder, 'level', {
7453 Object.defineProperty(builder, 'enabled', {
7457 return self.enabled;
7461 self.enabled = enabled;
7464 }); // See below for fix regarding invisible grey/dim combination on Windows
7466 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
7467 // no way to create a function with a different prototype
7469 builder.__proto__ = proto; // eslint-disable-line no-proto
7474 function applyStyle() {
7475 // Support varags, but simply cast to string in case there's only one arg
7476 const args = arguments;
7477 const argsLen = args.length;
7478 let str = String(arguments[0]);
7480 if (argsLen === 0) {
7485 // Don't slice `arguments`, it prevents V8 optimizations
7486 for (let a = 1; a < argsLen; a++) {
7487 str += ' ' + args[a];
7491 if (!this.enabled || this.level <= 0 || !str) {
7492 return this._empty ? '' : str;
7493 } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
7494 // see https://github.com/chalk/chalk/issues/58
7495 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
7498 const originalDim = ansiStyles.dim.open;
7500 if (isSimpleWindowsTerm && this.hasGrey) {
7501 ansiStyles.dim.open = '';
7504 for (const code of this._styles.slice().reverse()) {
7505 // Replace any instances already present with a re-opening code
7506 // otherwise only the part of the string until said closing code
7507 // will be colored, and the rest will simply be 'plain'.
7508 str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
7509 // after next line to fix a bleed issue on macOS
7510 // https://github.com/chalk/chalk/pull/92
7512 str = str.replace(/\r?\n/g, "".concat(code.close, "$&").concat(code.open));
7513 } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
7516 ansiStyles.dim.open = originalDim;
7520 function chalkTag(chalk, strings) {
7521 if (!Array.isArray(strings)) {
7522 // If chalk() was called by itself or with a string,
7523 // return the string itself as a string.
7524 return [].slice.call(arguments, 1).join(' ');
7527 const args = [].slice.call(arguments, 2);
7528 const parts = [strings.raw[0]];
7530 for (let i = 1; i < strings.length; i++) {
7531 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
7532 parts.push(String(strings.raw[i]));
7535 return templates(chalk, parts.join(''));
7538 Object.defineProperties(Chalk.prototype, styles);
7539 module.exports = Chalk(); // eslint-disable-line new-cap
7541 module.exports.supportsColor = stdoutColor;
7542 module.exports.default = module.exports; // For TypeScript
7544 var chalk_1 = chalk.supportsColor;
7546 var common = createCommonjsModule(function (module, exports) {
7548 Object.defineProperty(exports, "__esModule", {
7552 exports.commonDeprecatedHandler = (keyOrPair, redirectTo, {
7555 const messages = ["".concat(chalk.default.yellow(typeof keyOrPair === 'string' ? descriptor.key(keyOrPair) : descriptor.pair(keyOrPair)), " is deprecated")];
7558 messages.push("we now treat it as ".concat(chalk.default.blue(typeof redirectTo === 'string' ? descriptor.key(redirectTo) : descriptor.pair(redirectTo))));
7561 return messages.join('; ') + '.';
7564 unwrapExports(common);
7565 var common_1 = common.commonDeprecatedHandler;
7567 var deprecated = createCommonjsModule(function (module, exports) {
7569 Object.defineProperty(exports, "__esModule", {
7573 tslib_1.__exportStar(common, exports);
7575 unwrapExports(deprecated);
7577 var common$1 = createCommonjsModule(function (module, exports) {
7579 Object.defineProperty(exports, "__esModule", {
7583 exports.commonInvalidHandler = (key, value, utils) => ["Invalid ".concat(chalk.default.red(utils.descriptor.key(key)), " value."), "Expected ".concat(chalk.default.blue(utils.schemas[key].expected(utils)), ","), "but received ".concat(chalk.default.red(utils.descriptor.value(value)), ".")].join(' ');
7585 unwrapExports(common$1);
7586 var common_1$1 = common$1.commonInvalidHandler;
7588 var invalid = createCommonjsModule(function (module, exports) {
7590 Object.defineProperty(exports, "__esModule", {
7594 tslib_1.__exportStar(common$1, exports);
7596 unwrapExports(invalid);
7598 /* eslint-disable no-nested-ternary */
7601 var charCodeCache = [];
7603 var leven = function leven(a, b) {
7608 var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the
7609 // shortest & which one is the longest
7611 if (a.length > b.length) {
7616 var aLen = a.length;
7617 var bLen = b.length;
7625 } // Performing suffix trimming:
7626 // We can linearly drop suffix common to both strings since they
7627 // don't increase distance at all
7628 // Note: `~-` is the bitwise way to perform a `- 1` operation
7631 while (aLen > 0 && a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen)) {
7638 } // Performing prefix trimming
7639 // We can linearly drop prefix common to both strings since they
7640 // don't increase distance at all
7645 while (start < aLen && a.charCodeAt(start) === b.charCodeAt(start)) {
7664 charCodeCache[start + i] = a.charCodeAt(start + i);
7669 bCharCode = b.charCodeAt(start + j);
7673 for (i = 0; i < aLen; i++) {
7674 tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1;
7676 ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2;
7683 var leven_1 = createCommonjsModule(function (module, exports) {
7685 Object.defineProperty(exports, "__esModule", {
7689 exports.levenUnknownHandler = (key, value, {
7694 const messages = ["Ignored unknown option ".concat(chalk.default.yellow(descriptor.pair({
7698 const suggestion = Object.keys(schemas).sort().find(knownKey => leven(key, knownKey) < 3);
7701 messages.push("Did you mean ".concat(chalk.default.blue(descriptor.key(suggestion)), "?"));
7704 logger.warn(messages.join(' '));
7707 unwrapExports(leven_1);
7708 var leven_2 = leven_1.levenUnknownHandler;
7710 var unknown = createCommonjsModule(function (module, exports) {
7712 Object.defineProperty(exports, "__esModule", {
7716 tslib_1.__exportStar(leven_1, exports);
7718 unwrapExports(unknown);
7720 var handlers = createCommonjsModule(function (module, exports) {
7722 Object.defineProperty(exports, "__esModule", {
7726 tslib_1.__exportStar(deprecated, exports);
7728 tslib_1.__exportStar(invalid, exports);
7730 tslib_1.__exportStar(unknown, exports);
7732 unwrapExports(handlers);
7734 var schema = createCommonjsModule(function (module, exports) {
7736 Object.defineProperty(exports, "__esModule", {
7739 const HANDLER_KEYS = ['default', 'expected', 'validate', 'deprecated', 'forward', 'redirect', 'overlap', 'preprocess', 'postprocess'];
7741 function createSchema(SchemaConstructor, parameters) {
7742 const schema = new SchemaConstructor(parameters);
7743 const subSchema = Object.create(schema);
7745 for (const handlerKey of HANDLER_KEYS) {
7746 if (handlerKey in parameters) {
7747 subSchema[handlerKey] = normalizeHandler(parameters[handlerKey], schema, Schema.prototype[handlerKey].length);
7754 exports.createSchema = createSchema;
7757 constructor(parameters) {
7758 this.name = parameters.name;
7761 static create(parameters) {
7762 // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/5863
7763 return createSchema(this, parameters);
7768 } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
7773 } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length`
7776 validate(_value, _utils) {
7780 deprecated(_value, _utils) {
7784 forward(_value, _utils) {
7788 redirect(_value, _utils) {
7792 overlap(currentValue, _newValue, _utils) {
7793 return currentValue;
7796 preprocess(value, _utils) {
7800 postprocess(value, _utils) {
7806 exports.Schema = Schema;
7808 function normalizeHandler(handler, superSchema, handlerArgumentsLength) {
7809 return typeof handler === 'function' ? (...args) => handler(...args.slice(0, handlerArgumentsLength - 1), superSchema, ...args.slice(handlerArgumentsLength - 1)) : () => handler;
7812 unwrapExports(schema);
7813 var schema_1 = schema.createSchema;
7814 var schema_2 = schema.Schema;
7816 var alias = createCommonjsModule(function (module, exports) {
7818 Object.defineProperty(exports, "__esModule", {
7822 class AliasSchema extends schema.Schema {
7823 constructor(parameters) {
7825 this._sourceName = parameters.sourceName;
7829 return utils.schemas[this._sourceName].expected(utils);
7832 validate(value, utils) {
7833 return utils.schemas[this._sourceName].validate(value, utils);
7836 redirect(_value, _utils) {
7837 return this._sourceName;
7842 exports.AliasSchema = AliasSchema;
7844 unwrapExports(alias);
7845 var alias_1 = alias.AliasSchema;
7847 var any = createCommonjsModule(function (module, exports) {
7849 Object.defineProperty(exports, "__esModule", {
7853 class AnySchema extends schema.Schema {
7864 exports.AnySchema = AnySchema;
7867 var any_1 = any.AnySchema;
7869 var array = createCommonjsModule(function (module, exports) {
7871 Object.defineProperty(exports, "__esModule", {
7875 class ArraySchema extends schema.Schema {
7879 name = valueSchema.name
7881 handlers = tslib_1.__rest(_a, ["valueSchema", "name"]);
7883 super(Object.assign({}, handlers, {
7886 this._valueSchema = valueSchema;
7890 return "an array of ".concat(this._valueSchema.expected(utils));
7893 validate(value, utils) {
7894 if (!Array.isArray(value)) {
7898 const invalidValues = [];
7900 for (const subValue of value) {
7901 const subValidateResult = utils.normalizeValidateResult(this._valueSchema.validate(subValue, utils), subValue);
7903 if (subValidateResult !== true) {
7904 invalidValues.push(subValidateResult.value);
7908 return invalidValues.length === 0 ? true : {
7909 value: invalidValues
7913 deprecated(value, utils) {
7914 const deprecatedResult = [];
7916 for (const subValue of value) {
7917 const subDeprecatedResult = utils.normalizeDeprecatedResult(this._valueSchema.deprecated(subValue, utils), subValue);
7919 if (subDeprecatedResult !== false) {
7920 deprecatedResult.push(...subDeprecatedResult.map(({
7921 value: deprecatedValue
7923 value: [deprecatedValue]
7928 return deprecatedResult;
7931 forward(value, utils) {
7932 const forwardResult = [];
7934 for (const subValue of value) {
7935 const subForwardResult = utils.normalizeForwardResult(this._valueSchema.forward(subValue, utils), subValue);
7936 forwardResult.push(...subForwardResult.map(wrapTransferResult));
7939 return forwardResult;
7942 redirect(value, utils) {
7944 const redirect = [];
7946 for (const subValue of value) {
7947 const subRedirectResult = utils.normalizeRedirectResult(this._valueSchema.redirect(subValue, utils), subValue);
7949 if ('remain' in subRedirectResult) {
7950 remain.push(subRedirectResult.remain);
7953 redirect.push(...subRedirectResult.redirect.map(wrapTransferResult));
7956 return remain.length === 0 ? {
7964 overlap(currentValue, newValue) {
7965 return currentValue.concat(newValue);
7970 exports.ArraySchema = ArraySchema;
7972 function wrapTransferResult({
7982 unwrapExports(array);
7983 var array_1 = array.ArraySchema;
7985 var boolean_1 = createCommonjsModule(function (module, exports) {
7987 Object.defineProperty(exports, "__esModule", {
7991 class BooleanSchema extends schema.Schema {
7993 return 'true or false';
7997 return typeof value === 'boolean';
8002 exports.BooleanSchema = BooleanSchema;
8004 unwrapExports(boolean_1);
8005 var boolean_2 = boolean_1.BooleanSchema;
8007 var utils = createCommonjsModule(function (module, exports) {
8009 Object.defineProperty(exports, "__esModule", {
8013 function recordFromArray(array, mainKey) {
8014 const record = Object.create(null);
8016 for (const value of array) {
8017 const key = value[mainKey]; // istanbul ignore next
8020 throw new Error("Duplicate ".concat(mainKey, " ").concat(JSON.stringify(key)));
8024 record[key] = value;
8030 exports.recordFromArray = recordFromArray;
8032 function mapFromArray(array, mainKey) {
8033 const map = new Map();
8035 for (const value of array) {
8036 const key = value[mainKey]; // istanbul ignore next
8039 throw new Error("Duplicate ".concat(mainKey, " ").concat(JSON.stringify(key)));
8042 map.set(key, value);
8048 exports.mapFromArray = mapFromArray;
8050 function createAutoChecklist() {
8051 const map = Object.create(null);
8053 const idString = JSON.stringify(id);
8055 if (map[idString]) {
8059 map[idString] = true;
8064 exports.createAutoChecklist = createAutoChecklist;
8066 function partition(array, predicate) {
8067 const trueArray = [];
8068 const falseArray = [];
8070 for (const value of array) {
8071 if (predicate(value)) {
8072 trueArray.push(value);
8074 falseArray.push(value);
8078 return [trueArray, falseArray];
8081 exports.partition = partition;
8083 function isInt(value) {
8084 return value === Math.floor(value);
8087 exports.isInt = isInt;
8089 function comparePrimitive(a, b) {
8094 const typeofA = typeof a;
8095 const typeofB = typeof b;
8096 const orders = ['undefined', 'object', 'boolean', 'number', 'string'];
8098 if (typeofA !== typeofB) {
8099 return orders.indexOf(typeofA) - orders.indexOf(typeofB);
8102 if (typeofA !== 'string') {
8103 return Number(a) - Number(b);
8106 return a.localeCompare(b);
8109 exports.comparePrimitive = comparePrimitive;
8111 function normalizeDefaultResult(result) {
8112 return result === undefined ? {} : result;
8115 exports.normalizeDefaultResult = normalizeDefaultResult;
8117 function normalizeValidateResult(result, value) {
8118 return result === true ? true : result === false ? {
8123 exports.normalizeValidateResult = normalizeValidateResult;
8125 function normalizeDeprecatedResult(result, value, doNotNormalizeTrue = false) {
8126 return result === false ? false : result === true ? doNotNormalizeTrue ? true : [{
8128 }] : 'value' in result ? [result] : result.length === 0 ? false : result;
8131 exports.normalizeDeprecatedResult = normalizeDeprecatedResult;
8133 function normalizeTransferResult(result, value) {
8134 return typeof result === 'string' || 'key' in result ? {
8137 } : 'from' in result ? {
8146 exports.normalizeTransferResult = normalizeTransferResult;
8148 function normalizeForwardResult(result, value) {
8149 return result === undefined ? [] : Array.isArray(result) ? result.map(transferResult => normalizeTransferResult(transferResult, value)) : [normalizeTransferResult(result, value)];
8152 exports.normalizeForwardResult = normalizeForwardResult;
8154 function normalizeRedirectResult(result, value) {
8155 const redirect = normalizeForwardResult(typeof result === 'object' && 'redirect' in result ? result.redirect : result, value);
8156 return redirect.length === 0 ? {
8159 } : typeof result === 'object' && 'remain' in result ? {
8160 remain: result.remain,
8167 exports.normalizeRedirectResult = normalizeRedirectResult;
8169 unwrapExports(utils);
8170 var utils_1 = utils.recordFromArray;
8171 var utils_2 = utils.mapFromArray;
8172 var utils_3 = utils.createAutoChecklist;
8173 var utils_4 = utils.partition;
8174 var utils_5 = utils.isInt;
8175 var utils_6 = utils.comparePrimitive;
8176 var utils_7 = utils.normalizeDefaultResult;
8177 var utils_8 = utils.normalizeValidateResult;
8178 var utils_9 = utils.normalizeDeprecatedResult;
8179 var utils_10 = utils.normalizeTransferResult;
8180 var utils_11 = utils.normalizeForwardResult;
8181 var utils_12 = utils.normalizeRedirectResult;
8183 var choice = createCommonjsModule(function (module, exports) {
8185 Object.defineProperty(exports, "__esModule", {
8189 class ChoiceSchema extends schema.Schema {
8190 constructor(parameters) {
8192 this._choices = utils.mapFromArray(parameters.choices.map(choice => choice && typeof choice === 'object' ? choice : {
8200 const choiceValues = Array.from(this._choices.keys()).map(value => this._choices.get(value)).filter(choiceInfo => !choiceInfo.deprecated).map(choiceInfo => choiceInfo.value).sort(utils.comparePrimitive).map(descriptor.value);
8201 const head = choiceValues.slice(0, -2);
8202 const tail = choiceValues.slice(-2);
8203 return head.concat(tail.join(' or ')).join(', ');
8207 return this._choices.has(value);
8211 const choiceInfo = this._choices.get(value);
8213 return choiceInfo && choiceInfo.deprecated ? {
8219 const choiceInfo = this._choices.get(value);
8221 return choiceInfo ? choiceInfo.forward : undefined;
8225 const choiceInfo = this._choices.get(value);
8227 return choiceInfo ? choiceInfo.redirect : undefined;
8232 exports.ChoiceSchema = ChoiceSchema;
8234 unwrapExports(choice);
8235 var choice_1 = choice.ChoiceSchema;
8237 var number = createCommonjsModule(function (module, exports) {
8239 Object.defineProperty(exports, "__esModule", {
8243 class NumberSchema extends schema.Schema {
8248 validate(value, _utils) {
8249 return typeof value === 'number';
8254 exports.NumberSchema = NumberSchema;
8256 unwrapExports(number);
8257 var number_1 = number.NumberSchema;
8259 var integer = createCommonjsModule(function (module, exports) {
8261 Object.defineProperty(exports, "__esModule", {
8265 class IntegerSchema extends number.NumberSchema {
8267 return 'an integer';
8270 validate(value, utils$1) {
8271 return utils$1.normalizeValidateResult(super.validate(value, utils$1), value) === true && utils.isInt(value);
8276 exports.IntegerSchema = IntegerSchema;
8278 unwrapExports(integer);
8279 var integer_1 = integer.IntegerSchema;
8281 var string = createCommonjsModule(function (module, exports) {
8283 Object.defineProperty(exports, "__esModule", {
8287 class StringSchema extends schema.Schema {
8293 return typeof value === 'string';
8298 exports.StringSchema = StringSchema;
8300 unwrapExports(string);
8301 var string_1 = string.StringSchema;
8303 var schemas = createCommonjsModule(function (module, exports) {
8305 Object.defineProperty(exports, "__esModule", {
8309 tslib_1.__exportStar(alias, exports);
8311 tslib_1.__exportStar(any, exports);
8313 tslib_1.__exportStar(array, exports);
8315 tslib_1.__exportStar(boolean_1, exports);
8317 tslib_1.__exportStar(choice, exports);
8319 tslib_1.__exportStar(integer, exports);
8321 tslib_1.__exportStar(number, exports);
8323 tslib_1.__exportStar(string, exports);
8325 unwrapExports(schemas);
8327 var defaults = createCommonjsModule(function (module, exports) {
8329 Object.defineProperty(exports, "__esModule", {
8332 exports.defaultDescriptor = api.apiDescriptor;
8333 exports.defaultUnknownHandler = leven_1.levenUnknownHandler;
8334 exports.defaultInvalidHandler = invalid.commonInvalidHandler;
8335 exports.defaultDeprecatedHandler = common.commonDeprecatedHandler;
8337 unwrapExports(defaults);
8338 var defaults_1 = defaults.defaultDescriptor;
8339 var defaults_2 = defaults.defaultUnknownHandler;
8340 var defaults_3 = defaults.defaultInvalidHandler;
8341 var defaults_4 = defaults.defaultDeprecatedHandler;
8343 var normalize = createCommonjsModule(function (module, exports) {
8345 Object.defineProperty(exports, "__esModule", {
8349 exports.normalize = (options, schemas, opts) => new Normalizer(schemas, opts).normalize(options);
8352 constructor(schemas, opts) {
8353 // istanbul ignore next
8356 descriptor = defaults.defaultDescriptor,
8357 unknown = defaults.defaultUnknownHandler,
8358 invalid = defaults.defaultInvalidHandler,
8359 deprecated = defaults.defaultDeprecatedHandler
8364 /* istanbul ignore next */
8368 schemas: utils.recordFromArray(schemas, 'name'),
8369 normalizeDefaultResult: utils.normalizeDefaultResult,
8370 normalizeDeprecatedResult: utils.normalizeDeprecatedResult,
8371 normalizeForwardResult: utils.normalizeForwardResult,
8372 normalizeRedirectResult: utils.normalizeRedirectResult,
8373 normalizeValidateResult: utils.normalizeValidateResult
8375 this._unknownHandler = unknown;
8376 this._invalidHandler = invalid;
8377 this._deprecatedHandler = deprecated;
8378 this.cleanHistory();
8382 this._hasDeprecationWarned = utils.createAutoChecklist();
8385 normalize(options) {
8386 const normalized = {};
8387 const restOptionsArray = [options];
8389 const applyNormalization = () => {
8390 while (restOptionsArray.length !== 0) {
8391 const currentOptions = restOptionsArray.shift();
8393 const transferredOptionsArray = this._applyNormalization(currentOptions, normalized);
8395 restOptionsArray.push(...transferredOptionsArray);
8399 applyNormalization();
8401 for (const key of Object.keys(this._utils.schemas)) {
8402 const schema = this._utils.schemas[key];
8404 if (!(key in normalized)) {
8405 const defaultResult = utils.normalizeDefaultResult(schema.default(this._utils));
8407 if ('value' in defaultResult) {
8408 restOptionsArray.push({
8409 [key]: defaultResult.value
8415 applyNormalization();
8417 for (const key of Object.keys(this._utils.schemas)) {
8418 const schema = this._utils.schemas[key];
8420 if (key in normalized) {
8421 normalized[key] = schema.postprocess(normalized[key], this._utils);
8428 _applyNormalization(options, normalized) {
8429 const transferredOptionsArray = [];
8430 const [knownOptionNames, unknownOptionNames] = utils.partition(Object.keys(options), key => key in this._utils.schemas);
8432 for (const key of knownOptionNames) {
8433 const schema = this._utils.schemas[key];
8434 const value = schema.preprocess(options[key], this._utils);
8435 const validateResult = utils.normalizeValidateResult(schema.validate(value, this._utils), value);
8437 if (validateResult !== true) {
8442 const errorMessageOrError = this._invalidHandler(key, invalidValue, this._utils);
8444 throw typeof errorMessageOrError === 'string' ? new Error(errorMessageOrError) :
8445 /* istanbul ignore next*/
8446 errorMessageOrError;
8449 const appendTransferredOptions = ({
8453 transferredOptionsArray.push(typeof to === 'string' ? {
8460 const warnDeprecated = ({
8461 value: currentValue,
8464 const deprecatedResult = utils.normalizeDeprecatedResult(schema.deprecated(currentValue, this._utils), value,
8465 /* doNotNormalizeTrue */
8468 if (deprecatedResult === false) {
8472 if (deprecatedResult === true) {
8473 if (!this._hasDeprecationWarned(key)) {
8474 this._utils.logger.warn(this._deprecatedHandler(key, redirectTo, this._utils));
8478 value: deprecatedValue
8479 } of deprecatedResult) {
8482 value: deprecatedValue
8485 if (!this._hasDeprecationWarned(pair)) {
8486 const redirectToPair = typeof redirectTo === 'string' ? {
8488 value: deprecatedValue
8491 this._utils.logger.warn(this._deprecatedHandler(pair, redirectToPair, this._utils));
8497 const forwardResult = utils.normalizeForwardResult(schema.forward(value, this._utils), value);
8498 forwardResult.forEach(appendTransferredOptions);
8499 const redirectResult = utils.normalizeRedirectResult(schema.redirect(value, this._utils), value);
8500 redirectResult.redirect.forEach(appendTransferredOptions);
8502 if ('remain' in redirectResult) {
8503 const remainingValue = redirectResult.remain;
8504 normalized[key] = key in normalized ? schema.overlap(normalized[key], remainingValue, this._utils) : remainingValue;
8506 value: remainingValue
8513 } of redirectResult.redirect) {
8521 for (const key of unknownOptionNames) {
8522 const value = options[key];
8524 const unknownResult = this._unknownHandler(key, value, this._utils);
8526 if (unknownResult) {
8527 for (const unknownKey of Object.keys(unknownResult)) {
8528 const unknownOption = {
8529 [unknownKey]: unknownResult[unknownKey]
8532 if (unknownKey in this._utils.schemas) {
8533 transferredOptionsArray.push(unknownOption);
8535 Object.assign(normalized, unknownOption);
8541 return transferredOptionsArray;
8546 exports.Normalizer = Normalizer;
8548 unwrapExports(normalize);
8549 var normalize_1 = normalize.normalize;
8550 var normalize_2 = normalize.Normalizer;
8552 var lib = createCommonjsModule(function (module, exports) {
8554 Object.defineProperty(exports, "__esModule", {
8558 tslib_1.__exportStar(descriptors, exports);
8560 tslib_1.__exportStar(handlers, exports);
8562 tslib_1.__exportStar(schemas, exports);
8564 tslib_1.__exportStar(normalize, exports);
8566 tslib_1.__exportStar(schema, exports);
8571 const charCodeCache$1 = [];
8573 const leven$1 = (left, right) => {
8574 if (left === right) {
8578 const swap = left; // Swapping the strings if `a` is longer than `b` so we know which one is the
8579 // shortest & which one is the longest
8581 if (left.length > right.length) {
8586 let leftLength = left.length;
8587 let rightLength = right.length; // Performing suffix trimming:
8588 // We can linearly drop suffix common to both strings since they
8589 // don't increase distance at all
8590 // Note: `~-` is the bitwise way to perform a `- 1` operation
8592 while (leftLength > 0 && left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength)) {
8595 } // Performing prefix trimming
8596 // We can linearly drop prefix common to both strings since they
8597 // don't increase distance at all
8602 while (start < leftLength && left.charCodeAt(start) === right.charCodeAt(start)) {
8606 leftLength -= start;
8607 rightLength -= start;
8609 if (leftLength === 0) {
8620 while (i < leftLength) {
8621 charCodeCache$1[i] = left.charCodeAt(start + i);
8625 while (j < rightLength) {
8626 bCharCode = right.charCodeAt(start + j);
8630 for (i = 0; i < leftLength; i++) {
8631 temp2 = bCharCode === charCodeCache$1[i] ? temp : temp + 1;
8632 temp = array$1[i]; // eslint-disable-next-line no-multi-assign
8634 result = array$1[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2;
8641 var leven_1$1 = leven$1; // TODO: Remove this for the next major release
8643 var default_1 = leven$1;
8644 leven_1$1.default = default_1;
8647 "aliceblue": [240, 248, 255],
8648 "antiquewhite": [250, 235, 215],
8649 "aqua": [0, 255, 255],
8650 "aquamarine": [127, 255, 212],
8651 "azure": [240, 255, 255],
8652 "beige": [245, 245, 220],
8653 "bisque": [255, 228, 196],
8655 "blanchedalmond": [255, 235, 205],
8656 "blue": [0, 0, 255],
8657 "blueviolet": [138, 43, 226],
8658 "brown": [165, 42, 42],
8659 "burlywood": [222, 184, 135],
8660 "cadetblue": [95, 158, 160],
8661 "chartreuse": [127, 255, 0],
8662 "chocolate": [210, 105, 30],
8663 "coral": [255, 127, 80],
8664 "cornflowerblue": [100, 149, 237],
8665 "cornsilk": [255, 248, 220],
8666 "crimson": [220, 20, 60],
8667 "cyan": [0, 255, 255],
8668 "darkblue": [0, 0, 139],
8669 "darkcyan": [0, 139, 139],
8670 "darkgoldenrod": [184, 134, 11],
8671 "darkgray": [169, 169, 169],
8672 "darkgreen": [0, 100, 0],
8673 "darkgrey": [169, 169, 169],
8674 "darkkhaki": [189, 183, 107],
8675 "darkmagenta": [139, 0, 139],
8676 "darkolivegreen": [85, 107, 47],
8677 "darkorange": [255, 140, 0],
8678 "darkorchid": [153, 50, 204],
8679 "darkred": [139, 0, 0],
8680 "darksalmon": [233, 150, 122],
8681 "darkseagreen": [143, 188, 143],
8682 "darkslateblue": [72, 61, 139],
8683 "darkslategray": [47, 79, 79],
8684 "darkslategrey": [47, 79, 79],
8685 "darkturquoise": [0, 206, 209],
8686 "darkviolet": [148, 0, 211],
8687 "deeppink": [255, 20, 147],
8688 "deepskyblue": [0, 191, 255],
8689 "dimgray": [105, 105, 105],
8690 "dimgrey": [105, 105, 105],
8691 "dodgerblue": [30, 144, 255],
8692 "firebrick": [178, 34, 34],
8693 "floralwhite": [255, 250, 240],
8694 "forestgreen": [34, 139, 34],
8695 "fuchsia": [255, 0, 255],
8696 "gainsboro": [220, 220, 220],
8697 "ghostwhite": [248, 248, 255],
8698 "gold": [255, 215, 0],
8699 "goldenrod": [218, 165, 32],
8700 "gray": [128, 128, 128],
8701 "green": [0, 128, 0],
8702 "greenyellow": [173, 255, 47],
8703 "grey": [128, 128, 128],
8704 "honeydew": [240, 255, 240],
8705 "hotpink": [255, 105, 180],
8706 "indianred": [205, 92, 92],
8707 "indigo": [75, 0, 130],
8708 "ivory": [255, 255, 240],
8709 "khaki": [240, 230, 140],
8710 "lavender": [230, 230, 250],
8711 "lavenderblush": [255, 240, 245],
8712 "lawngreen": [124, 252, 0],
8713 "lemonchiffon": [255, 250, 205],
8714 "lightblue": [173, 216, 230],
8715 "lightcoral": [240, 128, 128],
8716 "lightcyan": [224, 255, 255],
8717 "lightgoldenrodyellow": [250, 250, 210],
8718 "lightgray": [211, 211, 211],
8719 "lightgreen": [144, 238, 144],
8720 "lightgrey": [211, 211, 211],
8721 "lightpink": [255, 182, 193],
8722 "lightsalmon": [255, 160, 122],
8723 "lightseagreen": [32, 178, 170],
8724 "lightskyblue": [135, 206, 250],
8725 "lightslategray": [119, 136, 153],
8726 "lightslategrey": [119, 136, 153],
8727 "lightsteelblue": [176, 196, 222],
8728 "lightyellow": [255, 255, 224],
8729 "lime": [0, 255, 0],
8730 "limegreen": [50, 205, 50],
8731 "linen": [250, 240, 230],
8732 "magenta": [255, 0, 255],
8733 "maroon": [128, 0, 0],
8734 "mediumaquamarine": [102, 205, 170],
8735 "mediumblue": [0, 0, 205],
8736 "mediumorchid": [186, 85, 211],
8737 "mediumpurple": [147, 112, 219],
8738 "mediumseagreen": [60, 179, 113],
8739 "mediumslateblue": [123, 104, 238],
8740 "mediumspringgreen": [0, 250, 154],
8741 "mediumturquoise": [72, 209, 204],
8742 "mediumvioletred": [199, 21, 133],
8743 "midnightblue": [25, 25, 112],
8744 "mintcream": [245, 255, 250],
8745 "mistyrose": [255, 228, 225],
8746 "moccasin": [255, 228, 181],
8747 "navajowhite": [255, 222, 173],
8748 "navy": [0, 0, 128],
8749 "oldlace": [253, 245, 230],
8750 "olive": [128, 128, 0],
8751 "olivedrab": [107, 142, 35],
8752 "orange": [255, 165, 0],
8753 "orangered": [255, 69, 0],
8754 "orchid": [218, 112, 214],
8755 "palegoldenrod": [238, 232, 170],
8756 "palegreen": [152, 251, 152],
8757 "paleturquoise": [175, 238, 238],
8758 "palevioletred": [219, 112, 147],
8759 "papayawhip": [255, 239, 213],
8760 "peachpuff": [255, 218, 185],
8761 "peru": [205, 133, 63],
8762 "pink": [255, 192, 203],
8763 "plum": [221, 160, 221],
8764 "powderblue": [176, 224, 230],
8765 "purple": [128, 0, 128],
8766 "rebeccapurple": [102, 51, 153],
8768 "rosybrown": [188, 143, 143],
8769 "royalblue": [65, 105, 225],
8770 "saddlebrown": [139, 69, 19],
8771 "salmon": [250, 128, 114],
8772 "sandybrown": [244, 164, 96],
8773 "seagreen": [46, 139, 87],
8774 "seashell": [255, 245, 238],
8775 "sienna": [160, 82, 45],
8776 "silver": [192, 192, 192],
8777 "skyblue": [135, 206, 235],
8778 "slateblue": [106, 90, 205],
8779 "slategray": [112, 128, 144],
8780 "slategrey": [112, 128, 144],
8781 "snow": [255, 250, 250],
8782 "springgreen": [0, 255, 127],
8783 "steelblue": [70, 130, 180],
8784 "tan": [210, 180, 140],
8785 "teal": [0, 128, 128],
8786 "thistle": [216, 191, 216],
8787 "tomato": [255, 99, 71],
8788 "turquoise": [64, 224, 208],
8789 "violet": [238, 130, 238],
8790 "wheat": [245, 222, 179],
8791 "white": [255, 255, 255],
8792 "whitesmoke": [245, 245, 245],
8793 "yellow": [255, 255, 0],
8794 "yellowgreen": [154, 205, 50]
8799 /* eslint-disable no-mixed-operators */
8800 // NOTE: conversions should only return primitive values (i.e. arrays, or
8801 // values that give correct `typeof` results).
8802 // do not use box values types (i.e. Number(), String(), etc.)
8804 const reverseKeywords = {};
8806 for (const key of Object.keys(colorName$1)) {
8807 reverseKeywords[colorName$1[key]] = key;
8861 labels: ['h', 'c', 'g']
8865 labels: ['r16', 'g16', 'b16']
8872 var conversions$1 = convert$1; // Hide .channels and .labels properties
8874 for (const model of Object.keys(convert$1)) {
8875 if (!('channels' in convert$1[model])) {
8876 throw new Error('missing channels property: ' + model);
8879 if (!('labels' in convert$1[model])) {
8880 throw new Error('missing channel labels property: ' + model);
8883 if (convert$1[model].labels.length !== convert$1[model].channels) {
8884 throw new Error('channel and label counts mismatch: ' + model);
8890 } = convert$1[model];
8891 delete convert$1[model].channels;
8892 delete convert$1[model].labels;
8893 Object.defineProperty(convert$1[model], 'channels', {
8896 Object.defineProperty(convert$1[model], 'labels', {
8901 convert$1.rgb.hsl = function (rgb) {
8902 const r = rgb[0] / 255;
8903 const g = rgb[1] / 255;
8904 const b = rgb[2] / 255;
8905 const min = Math.min(r, g, b);
8906 const max = Math.max(r, g, b);
8907 const delta = max - min;
8913 } else if (r === max) {
8914 h = (g - b) / delta;
8915 } else if (g === max) {
8916 h = 2 + (b - r) / delta;
8917 } else if (b === max) {
8918 h = 4 + (r - g) / delta;
8921 h = Math.min(h * 60, 360);
8927 const l = (min + max) / 2;
8931 } else if (l <= 0.5) {
8932 s = delta / (max + min);
8934 s = delta / (2 - max - min);
8937 return [h, s * 100, l * 100];
8940 convert$1.rgb.hsv = function (rgb) {
8946 const r = rgb[0] / 255;
8947 const g = rgb[1] / 255;
8948 const b = rgb[2] / 255;
8949 const v = Math.max(r, g, b);
8950 const diff = v - Math.min(r, g, b);
8952 const diffc = function diffc(c) {
8953 return (v - c) / 6 / diff + 1 / 2;
8967 } else if (g === v) {
8968 h = 1 / 3 + rdif - bdif;
8969 } else if (b === v) {
8970 h = 2 / 3 + gdif - rdif;
8980 return [h * 360, s * 100, v * 100];
8983 convert$1.rgb.hwb = function (rgb) {
8987 const h = convert$1.rgb.hsl(rgb)[0];
8988 const w = 1 / 255 * Math.min(r, Math.min(g, b));
8989 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
8990 return [h, w * 100, b * 100];
8993 convert$1.rgb.cmyk = function (rgb) {
8994 const r = rgb[0] / 255;
8995 const g = rgb[1] / 255;
8996 const b = rgb[2] / 255;
8997 const k = Math.min(1 - r, 1 - g, 1 - b);
8998 const c = (1 - r - k) / (1 - k) || 0;
8999 const m = (1 - g - k) / (1 - k) || 0;
9000 const y = (1 - b - k) / (1 - k) || 0;
9001 return [c * 100, m * 100, y * 100, k * 100];
9004 function comparativeDistance(x, y) {
9006 See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
9008 return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2;
9011 convert$1.rgb.keyword = function (rgb) {
9012 const reversed = reverseKeywords[rgb];
9018 let currentClosestDistance = Infinity;
9019 let currentClosestKeyword;
9021 for (const keyword of Object.keys(colorName$1)) {
9022 const value = colorName$1[keyword]; // Compute comparative distance
9024 const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
9026 if (distance < currentClosestDistance) {
9027 currentClosestDistance = distance;
9028 currentClosestKeyword = keyword;
9032 return currentClosestKeyword;
9035 convert$1.keyword.rgb = function (keyword) {
9036 return colorName$1[keyword];
9039 convert$1.rgb.xyz = function (rgb) {
9040 let r = rgb[0] / 255;
9041 let g = rgb[1] / 255;
9042 let b = rgb[2] / 255; // Assume sRGB
9044 r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92;
9045 g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92;
9046 b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92;
9047 const x = r * 0.4124 + g * 0.3576 + b * 0.1805;
9048 const y = r * 0.2126 + g * 0.7152 + b * 0.0722;
9049 const z = r * 0.0193 + g * 0.1192 + b * 0.9505;
9050 return [x * 100, y * 100, z * 100];
9053 convert$1.rgb.lab = function (rgb) {
9054 const xyz = convert$1.rgb.xyz(rgb);
9061 x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
9062 y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
9063 z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
9064 const l = 116 * y - 16;
9065 const a = 500 * (x - y);
9066 const b = 200 * (y - z);
9070 convert$1.hsl.rgb = function (hsl) {
9071 const h = hsl[0] / 360;
9072 const s = hsl[1] / 100;
9073 const l = hsl[2] / 100;
9080 return [val, val, val];
9089 const t1 = 2 * l - t2;
9090 const rgb = [0, 0, 0];
9092 for (let i = 0; i < 3; i++) {
9093 t3 = h + 1 / 3 * -(i - 1);
9104 val = t1 + (t2 - t1) * 6 * t3;
9105 } else if (2 * t3 < 1) {
9107 } else if (3 * t3 < 2) {
9108 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
9119 convert$1.hsl.hsv = function (hsl) {
9121 let s = hsl[1] / 100;
9122 let l = hsl[2] / 100;
9124 const lmin = Math.max(l, 0.01);
9126 s *= l <= 1 ? l : 2 - l;
9127 smin *= lmin <= 1 ? lmin : 2 - lmin;
9128 const v = (l + s) / 2;
9129 const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
9130 return [h, sv * 100, v * 100];
9133 convert$1.hsv.rgb = function (hsv) {
9134 const h = hsv[0] / 60;
9135 const s = hsv[1] / 100;
9136 let v = hsv[2] / 100;
9137 const hi = Math.floor(h) % 6;
9138 const f = h - Math.floor(h);
9139 const p = 255 * v * (1 - s);
9140 const q = 255 * v * (1 - s * f);
9141 const t = 255 * v * (1 - s * (1 - f));
9165 convert$1.hsv.hsl = function (hsv) {
9167 const s = hsv[1] / 100;
9168 const v = hsv[2] / 100;
9169 const vmin = Math.max(v, 0.01);
9173 const lmin = (2 - s) * vmin;
9175 sl /= lmin <= 1 ? lmin : 2 - lmin;
9178 return [h, sl * 100, l * 100];
9179 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
9182 convert$1.hwb.rgb = function (hwb) {
9183 const h = hwb[0] / 360;
9184 let wh = hwb[1] / 100;
9185 let bl = hwb[2] / 100;
9186 const ratio = wh + bl;
9187 let f; // Wh + bl cant be > 1
9194 const i = Math.floor(6 * h);
9198 if ((i & 0x01) !== 0) {
9202 const n = wh + f * (v - wh); // Linear interpolation
9207 /* eslint-disable max-statements-per-line,no-multi-spaces */
9248 /* eslint-enable max-statements-per-line,no-multi-spaces */
9251 return [r * 255, g * 255, b * 255];
9254 convert$1.cmyk.rgb = function (cmyk) {
9255 const c = cmyk[0] / 100;
9256 const m = cmyk[1] / 100;
9257 const y = cmyk[2] / 100;
9258 const k = cmyk[3] / 100;
9259 const r = 1 - Math.min(1, c * (1 - k) + k);
9260 const g = 1 - Math.min(1, m * (1 - k) + k);
9261 const b = 1 - Math.min(1, y * (1 - k) + k);
9262 return [r * 255, g * 255, b * 255];
9265 convert$1.xyz.rgb = function (xyz) {
9266 const x = xyz[0] / 100;
9267 const y = xyz[1] / 100;
9268 const z = xyz[2] / 100;
9272 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
9273 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
9274 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // Assume sRGB
9276 r = r > 0.0031308 ? 1.055 * r ** (1.0 / 2.4) - 0.055 : r * 12.92;
9277 g = g > 0.0031308 ? 1.055 * g ** (1.0 / 2.4) - 0.055 : g * 12.92;
9278 b = b > 0.0031308 ? 1.055 * b ** (1.0 / 2.4) - 0.055 : b * 12.92;
9279 r = Math.min(Math.max(0, r), 1);
9280 g = Math.min(Math.max(0, g), 1);
9281 b = Math.min(Math.max(0, b), 1);
9282 return [r * 255, g * 255, b * 255];
9285 convert$1.xyz.lab = function (xyz) {
9292 x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
9293 y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
9294 z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
9295 const l = 116 * y - 16;
9296 const a = 500 * (x - y);
9297 const b = 200 * (y - z);
9301 convert$1.lab.xyz = function (lab) {
9314 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
9315 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
9316 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
9323 convert$1.lab.lch = function (lab) {
9328 const hr = Math.atan2(b, a);
9329 h = hr * 360 / 2 / Math.PI;
9335 const c = Math.sqrt(a * a + b * b);
9339 convert$1.lch.lab = function (lch) {
9343 const hr = h / 360 * 2 * Math.PI;
9344 const a = c * Math.cos(hr);
9345 const b = c * Math.sin(hr);
9349 convert$1.rgb.ansi16 = function (args, saturation = null) {
9350 const [r, g, b] = args;
9351 let value = saturation === null ? convert$1.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
9353 value = Math.round(value / 50);
9359 let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
9368 convert$1.hsv.ansi16 = function (args) {
9369 // Optimization here; we already know the value and don't need to get
9370 // it converted for us.
9371 return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]);
9374 convert$1.rgb.ansi256 = function (args) {
9377 const b = args[2]; // We use the extended greyscale palette here, with the exception of
9378 // black and white. normal palette only has 4 greyscale shades.
9380 if (r === g && g === b) {
9389 return Math.round((r - 8) / 247 * 24) + 232;
9392 const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
9396 convert$1.ansi16.rgb = function (args) {
9397 let color = args % 10; // Handle greyscale
9399 if (color === 0 || color === 7) {
9404 color = color / 10.5 * 255;
9405 return [color, color, color];
9408 const mult = (~~(args > 50) + 1) * 0.5;
9409 const r = (color & 1) * mult * 255;
9410 const g = (color >> 1 & 1) * mult * 255;
9411 const b = (color >> 2 & 1) * mult * 255;
9415 convert$1.ansi256.rgb = function (args) {
9418 const c = (args - 232) * 10 + 8;
9424 const r = Math.floor(args / 36) / 5 * 255;
9425 const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
9426 const b = rem % 6 / 5 * 255;
9430 convert$1.rgb.hex = function (args) {
9431 const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
9432 const string = integer.toString(16).toUpperCase();
9433 return '000000'.substring(string.length) + string;
9436 convert$1.hex.rgb = function (args) {
9437 const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
9443 let colorString = match[0];
9445 if (match[0].length === 3) {
9446 colorString = colorString.split('').map(char => {
9451 const integer = parseInt(colorString, 16);
9452 const r = integer >> 16 & 0xFF;
9453 const g = integer >> 8 & 0xFF;
9454 const b = integer & 0xFF;
9458 convert$1.rgb.hcg = function (rgb) {
9459 const r = rgb[0] / 255;
9460 const g = rgb[1] / 255;
9461 const b = rgb[2] / 255;
9462 const max = Math.max(Math.max(r, g), b);
9463 const min = Math.min(Math.min(r, g), b);
9464 const chroma = max - min;
9469 grayscale = min / (1 - chroma);
9476 } else if (max === r) {
9477 hue = (g - b) / chroma % 6;
9478 } else if (max === g) {
9479 hue = 2 + (b - r) / chroma;
9481 hue = 4 + (r - g) / chroma;
9486 return [hue * 360, chroma * 100, grayscale * 100];
9489 convert$1.hsl.hcg = function (hsl) {
9490 const s = hsl[1] / 100;
9491 const l = hsl[2] / 100;
9492 const c = l < 0.5 ? 2.0 * s * l : 2.0 * s * (1.0 - l);
9496 f = (l - 0.5 * c) / (1.0 - c);
9499 return [hsl[0], c * 100, f * 100];
9502 convert$1.hsv.hcg = function (hsv) {
9503 const s = hsv[1] / 100;
9504 const v = hsv[2] / 100;
9509 f = (v - c) / (1 - c);
9512 return [hsv[0], c * 100, f * 100];
9515 convert$1.hcg.rgb = function (hcg) {
9516 const h = hcg[0] / 360;
9517 const c = hcg[1] / 100;
9518 const g = hcg[2] / 100;
9521 return [g * 255, g * 255, g * 255];
9524 const pure = [0, 0, 0];
9525 const hi = h % 1 * 6;
9529 /* eslint-disable max-statements-per-line */
9531 switch (Math.floor(hi)) {
9567 /* eslint-enable max-statements-per-line */
9571 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
9574 convert$1.hcg.hsv = function (hcg) {
9575 const c = hcg[1] / 100;
9576 const g = hcg[2] / 100;
9577 const v = c + g * (1.0 - c);
9584 return [hcg[0], f * 100, v * 100];
9587 convert$1.hcg.hsl = function (hcg) {
9588 const c = hcg[1] / 100;
9589 const g = hcg[2] / 100;
9590 const l = g * (1.0 - c) + 0.5 * c;
9593 if (l > 0.0 && l < 0.5) {
9595 } else if (l >= 0.5 && l < 1.0) {
9596 s = c / (2 * (1 - l));
9599 return [hcg[0], s * 100, l * 100];
9602 convert$1.hcg.hwb = function (hcg) {
9603 const c = hcg[1] / 100;
9604 const g = hcg[2] / 100;
9605 const v = c + g * (1.0 - c);
9606 return [hcg[0], (v - c) * 100, (1 - v) * 100];
9609 convert$1.hwb.hcg = function (hwb) {
9610 const w = hwb[1] / 100;
9611 const b = hwb[2] / 100;
9617 g = (v - c) / (1 - c);
9620 return [hwb[0], c * 100, g * 100];
9623 convert$1.apple.rgb = function (apple) {
9624 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
9627 convert$1.rgb.apple = function (rgb) {
9628 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
9631 convert$1.gray.rgb = function (args) {
9632 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
9635 convert$1.gray.hsl = function (args) {
9636 return [0, 0, args[0]];
9639 convert$1.gray.hsv = convert$1.gray.hsl;
9641 convert$1.gray.hwb = function (gray) {
9642 return [0, 100, gray[0]];
9645 convert$1.gray.cmyk = function (gray) {
9646 return [0, 0, 0, gray[0]];
9649 convert$1.gray.lab = function (gray) {
9650 return [gray[0], 0, 0];
9653 convert$1.gray.hex = function (gray) {
9654 const val = Math.round(gray[0] / 100 * 255) & 0xFF;
9655 const integer = (val << 16) + (val << 8) + val;
9656 const string = integer.toString(16).toUpperCase();
9657 return '000000'.substring(string.length) + string;
9660 convert$1.rgb.gray = function (rgb) {
9661 const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
9662 return [val / 255 * 100];
9666 This function routes a model to all other models.
9668 all functions that are routed have a property `.conversion` attached
9669 to the returned synthetic function. This property is an array
9670 of strings, each with the steps in between the 'from' and 'to'
9671 color models (inclusive).
9673 conversions that are not possible simply are not included.
9676 function buildGraph$1() {
9677 const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
9679 const models = Object.keys(conversions$1);
9681 for (let len = models.length, i = 0; i < len; i++) {
9682 graph[models[i]] = {
9683 // http://jsperf.com/1-vs-infinity
9684 // micro-opt, but this is simple.
9691 } // https://en.wikipedia.org/wiki/Breadth-first_search
9694 function deriveBFS$1(fromModel) {
9695 const graph = buildGraph$1();
9696 const queue = [fromModel]; // Unshift -> queue -> pop
9698 graph[fromModel].distance = 0;
9700 while (queue.length) {
9701 const current = queue.pop();
9702 const adjacents = Object.keys(conversions$1[current]);
9704 for (let len = adjacents.length, i = 0; i < len; i++) {
9705 const adjacent = adjacents[i];
9706 const node = graph[adjacent];
9708 if (node.distance === -1) {
9709 node.distance = graph[current].distance + 1;
9710 node.parent = current;
9711 queue.unshift(adjacent);
9719 function link$1(from, to) {
9720 return function (args) {
9721 return to(from(args));
9725 function wrapConversion$1(toModel, graph) {
9726 const path = [graph[toModel].parent, toModel];
9727 let fn = conversions$1[graph[toModel].parent][toModel];
9728 let cur = graph[toModel].parent;
9730 while (graph[cur].parent) {
9731 path.unshift(graph[cur].parent);
9732 fn = link$1(conversions$1[graph[cur].parent][cur], fn);
9733 cur = graph[cur].parent;
9736 fn.conversion = path;
9740 var route$1 = function route(fromModel) {
9741 const graph = deriveBFS$1(fromModel);
9742 const conversion = {};
9743 const models = Object.keys(graph);
9745 for (let len = models.length, i = 0; i < len; i++) {
9746 const toModel = models[i];
9747 const node = graph[toModel];
9749 if (node.parent === null) {
9750 // No possible conversion, or this node is the source model.
9754 conversion[toModel] = wrapConversion$1(toModel, graph);
9760 const convert$2 = {};
9761 const models$1 = Object.keys(conversions$1);
9763 function wrapRaw$1(fn) {
9764 const wrappedFn = function wrappedFn(...args) {
9765 const arg0 = args[0];
9767 if (arg0 === undefined || arg0 === null) {
9771 if (arg0.length > 1) {
9776 }; // Preserve .conversion property if there is one
9779 if ('conversion' in fn) {
9780 wrappedFn.conversion = fn.conversion;
9786 function wrapRounded$1(fn) {
9787 const wrappedFn = function wrappedFn(...args) {
9788 const arg0 = args[0];
9790 if (arg0 === undefined || arg0 === null) {
9794 if (arg0.length > 1) {
9798 const result = fn(args); // We're assuming the result is an array here.
9799 // see notice in conversions.js; don't use box types
9800 // in conversion functions.
9802 if (typeof result === 'object') {
9803 for (let len = result.length, i = 0; i < len; i++) {
9804 result[i] = Math.round(result[i]);
9809 }; // Preserve .conversion property if there is one
9812 if ('conversion' in fn) {
9813 wrappedFn.conversion = fn.conversion;
9819 models$1.forEach(fromModel => {
9820 convert$2[fromModel] = {};
9821 Object.defineProperty(convert$2[fromModel], 'channels', {
9822 value: conversions$1[fromModel].channels
9824 Object.defineProperty(convert$2[fromModel], 'labels', {
9825 value: conversions$1[fromModel].labels
9827 const routes = route$1(fromModel);
9828 const routeModels = Object.keys(routes);
9829 routeModels.forEach(toModel => {
9830 const fn = routes[toModel];
9831 convert$2[fromModel][toModel] = wrapRounded$1(fn);
9832 convert$2[fromModel][toModel].raw = wrapRaw$1(fn);
9835 var colorConvert$1 = convert$2;
9837 var ansiStyles$1 = createCommonjsModule(function (module) {
9839 const wrapAnsi16 = (fn, offset) => (...args) => {
9840 const code = fn(...args);
9841 return "\x1B[".concat(code + offset, "m");
9844 const wrapAnsi256 = (fn, offset) => (...args) => {
9845 const code = fn(...args);
9846 return "\x1B[".concat(38 + offset, ";5;").concat(code, "m");
9849 const wrapAnsi16m = (fn, offset) => (...args) => {
9850 const rgb = fn(...args);
9851 return "\x1B[".concat(38 + offset, ";2;").concat(rgb[0], ";").concat(rgb[1], ";").concat(rgb[2], "m");
9854 const ansi2ansi = n => n;
9856 const rgb2rgb = (r, g, b) => [r, g, b];
9858 const setLazyProperty = (object, property, _get) => {
9859 Object.defineProperty(object, property, {
9861 const value = _get();
9863 Object.defineProperty(object, property, {
9874 /** @type {typeof import('color-convert')} */
9879 const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
9880 if (colorConvert === undefined) {
9881 colorConvert = colorConvert$1;
9884 const offset = isBackground ? 10 : 0;
9887 for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
9888 const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
9890 if (sourceSpace === targetSpace) {
9891 styles[name] = wrap(identity, offset);
9892 } else if (typeof suite === 'object') {
9893 styles[name] = wrap(suite[targetSpace], offset);
9900 function assembleStyles() {
9901 const codes = new Map();
9905 // 21 isn't widely supported and 22 does the same thing
9912 strikethrough: [9, 29]
9924 blackBright: [90, 39],
9925 redBright: [91, 39],
9926 greenBright: [92, 39],
9927 yellowBright: [93, 39],
9928 blueBright: [94, 39],
9929 magentaBright: [95, 39],
9930 cyanBright: [96, 39],
9931 whiteBright: [97, 39]
9939 bgMagenta: [45, 49],
9943 bgBlackBright: [100, 49],
9944 bgRedBright: [101, 49],
9945 bgGreenBright: [102, 49],
9946 bgYellowBright: [103, 49],
9947 bgBlueBright: [104, 49],
9948 bgMagentaBright: [105, 49],
9949 bgCyanBright: [106, 49],
9950 bgWhiteBright: [107, 49]
9952 }; // Alias bright black as gray (and grey)
9954 styles.color.gray = styles.color.blackBright;
9955 styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
9956 styles.color.grey = styles.color.blackBright;
9957 styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
9959 for (const [groupName, group] of Object.entries(styles)) {
9960 for (const [styleName, style] of Object.entries(group)) {
9961 styles[styleName] = {
9962 open: "\x1B[".concat(style[0], "m"),
9963 close: "\x1B[".concat(style[1], "m")
9965 group[styleName] = styles[styleName];
9966 codes.set(style[0], style[1]);
9969 Object.defineProperty(styles, groupName, {
9975 Object.defineProperty(styles, 'codes', {
9979 styles.color.close = '\u001B[39m';
9980 styles.bgColor.close = '\u001B[49m';
9981 setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
9982 setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
9983 setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
9984 setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
9985 setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
9986 setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
9988 } // Make the export immutable
9991 Object.defineProperty(module, 'exports', {
10004 var hasFlag$1 = (flag, argv = process.argv) => {
10005 const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
10006 const position = argv.indexOf(prefix + flag);
10007 const terminatorPosition = argv.indexOf('--');
10008 return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
10016 if (hasFlag$1('no-color') || hasFlag$1('no-colors') || hasFlag$1('color=false') || hasFlag$1('color=never')) {
10018 } else if (hasFlag$1('color') || hasFlag$1('colors') || hasFlag$1('color=true') || hasFlag$1('color=always')) {
10022 if ('FORCE_COLOR' in env$2) {
10023 if (env$2.FORCE_COLOR === 'true') {
10025 } else if (env$2.FORCE_COLOR === 'false') {
10028 forceColor$1 = env$2.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$2.FORCE_COLOR, 10), 3);
10032 function translateLevel$1(level) {
10040 has256: level >= 2,
10045 function supportsColor$1(haveStream, streamIsTTY) {
10046 if (forceColor$1 === 0) {
10050 if (hasFlag$1('color=16m') || hasFlag$1('color=full') || hasFlag$1('color=truecolor')) {
10054 if (hasFlag$1('color=256')) {
10058 if (haveStream && !streamIsTTY && forceColor$1 === undefined) {
10062 const min = forceColor$1 || 0;
10064 if (env$2.TERM === 'dumb') {
10068 if (process.platform === 'win32') {
10069 // Windows 10 build 10586 is the first Windows release that supports 256 colors.
10070 // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
10071 const osRelease = require$$0$1.release().split('.');
10073 if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
10074 return Number(osRelease[2]) >= 14931 ? 3 : 2;
10080 if ('CI' in env$2) {
10081 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') {
10088 if ('TEAMCITY_VERSION' in env$2) {
10089 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0;
10092 if ('GITHUB_ACTIONS' in env$2) {
10096 if (env$2.COLORTERM === 'truecolor') {
10100 if ('TERM_PROGRAM' in env$2) {
10101 const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
10103 switch (env$2.TERM_PROGRAM) {
10105 return version >= 3 ? 3 : 2;
10107 case 'Apple_Terminal':
10113 if (/-256(color)?$/i.test(env$2.TERM)) {
10117 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) {
10121 if ('COLORTERM' in env$2) {
10128 function getSupportLevel$1(stream) {
10129 const level = supportsColor$1(stream, stream && stream.isTTY);
10130 return translateLevel$1(level);
10133 var supportsColor_1$1 = {
10134 supportsColor: getSupportLevel$1,
10135 stdout: translateLevel$1(supportsColor$1(true, tty.isatty(1))),
10136 stderr: translateLevel$1(supportsColor$1(true, tty.isatty(2)))
10139 const stringReplaceAll = (string, substring, replacer) => {
10140 let index = string.indexOf(substring);
10142 if (index === -1) {
10146 const substringLength = substring.length;
10148 let returnValue = '';
10151 returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
10152 endIndex = index + substringLength;
10153 index = string.indexOf(substring, endIndex);
10154 } while (index !== -1);
10156 returnValue += string.substr(endIndex);
10157 return returnValue;
10160 const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
10162 let returnValue = '';
10165 const gotCR = string[index - 1] === '\r';
10166 returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
10167 endIndex = index + 1;
10168 index = string.indexOf('\n', endIndex);
10169 } while (index !== -1);
10171 returnValue += string.substr(endIndex);
10172 return returnValue;
10177 stringEncaseCRLFWithFirstIndex
10180 const TEMPLATE_REGEX$1 = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
10181 const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
10182 const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
10183 const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
10184 const ESCAPES$1 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
10186 function unescape$1(c) {
10187 const u = c[0] === 'u';
10188 const bracket = c[1] === '{';
10190 if (u && !bracket && c.length === 5 || c[0] === 'x' && c.length === 3) {
10191 return String.fromCharCode(parseInt(c.slice(1), 16));
10194 if (u && bracket) {
10195 return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
10198 return ESCAPES$1.get(c) || c;
10201 function parseArguments$1(name, arguments_) {
10202 const results = [];
10203 const chunks = arguments_.trim().split(/\s*,\s*/g);
10206 for (const chunk of chunks) {
10207 const number = Number(chunk);
10209 if (!Number.isNaN(number)) {
10210 results.push(number);
10211 } else if (matches = chunk.match(STRING_REGEX$1)) {
10212 results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$1(escape) : character));
10214 throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')"));
10221 function parseStyle$1(style) {
10222 STYLE_REGEX$1.lastIndex = 0;
10223 const results = [];
10226 while ((matches = STYLE_REGEX$1.exec(style)) !== null) {
10227 const name = matches[1];
10230 const args = parseArguments$1(name, matches[2]);
10231 results.push([name].concat(args));
10233 results.push([name]);
10240 function buildStyle$1(chalk, styles) {
10241 const enabled = {};
10243 for (const layer of styles) {
10244 for (const style of layer.styles) {
10245 enabled[style[0]] = layer.inverse ? null : style.slice(1);
10249 let current = chalk;
10251 for (const [styleName, styles] of Object.entries(enabled)) {
10252 if (!Array.isArray(styles)) {
10256 if (!(styleName in current)) {
10257 throw new Error("Unknown Chalk style: ".concat(styleName));
10260 current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
10266 var templates$1 = (chalk, temporary) => {
10269 let chunk = []; // eslint-disable-next-line max-params
10271 temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => {
10272 if (escapeCharacter) {
10273 chunk.push(unescape$1(escapeCharacter));
10274 } else if (style) {
10275 const string = chunk.join('');
10277 chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string));
10280 styles: parseStyle$1(style)
10282 } else if (close) {
10283 if (styles.length === 0) {
10284 throw new Error('Found extraneous } in Chalk template literal');
10287 chunks.push(buildStyle$1(chalk, styles)(chunk.join('')));
10291 chunk.push(character);
10294 chunks.push(chunk.join(''));
10296 if (styles.length > 0) {
10297 const errMessage = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)");
10298 throw new Error(errMessage);
10301 return chunks.join('');
10305 stdout: stdoutColor,
10306 stderr: stderrColor
10307 } = supportsColor_1$1;
10309 stringReplaceAll: stringReplaceAll$1,
10310 stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
10311 } = util; // `supportsColor.level` → `ansiStyles.color[name]` mapping
10313 const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
10314 const styles = Object.create(null);
10316 const applyOptions = (object, options = {}) => {
10317 if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
10318 throw new Error('The `level` option should be an integer from 0 to 3');
10319 } // Detect level if not set manually
10322 const colorLevel = stdoutColor ? stdoutColor.level : 0;
10323 object.level = options.level === undefined ? colorLevel : options.level;
10327 constructor(options) {
10328 // eslint-disable-next-line no-constructor-return
10329 return chalkFactory(options);
10334 const chalkFactory = options => {
10336 applyOptions(chalk, options);
10338 chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
10340 Object.setPrototypeOf(chalk, Chalk.prototype);
10341 Object.setPrototypeOf(chalk.template, chalk);
10343 chalk.template.constructor = () => {
10344 throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
10347 chalk.template.Instance = ChalkClass;
10348 return chalk.template;
10351 function Chalk(options) {
10352 return chalkFactory(options);
10355 for (const [styleName, style] of Object.entries(ansiStyles$1)) {
10356 styles[styleName] = {
10358 const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
10359 Object.defineProperty(this, styleName, {
10370 const builder = createBuilder(this, this._styler, true);
10371 Object.defineProperty(this, 'visible', {
10378 const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
10380 for (const model of usedModels) {
10386 return function (...arguments_) {
10387 const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler);
10388 return createBuilder(this, styler, this._isEmpty);
10395 for (const model of usedModels) {
10396 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
10397 styles[bgModel] = {
10402 return function (...arguments_) {
10403 const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler);
10404 return createBuilder(this, styler, this._isEmpty);
10411 const proto = Object.defineProperties(() => {}, Object.assign({}, styles, {
10416 return this._generator.level;
10420 this._generator.level = level;
10426 const createStyler = (open, close, parent) => {
10430 if (parent === undefined) {
10434 openAll = parent.openAll + open;
10435 closeAll = close + parent.closeAll;
10447 const createBuilder = (self, _styler, _isEmpty) => {
10448 const builder = (...arguments_) => {
10449 // Single argument is hot path, implicit coercion is faster than anything
10450 // eslint-disable-next-line no-implicit-coercion
10451 return applyStyle(builder, arguments_.length === 1 ? '' + arguments_[0] : arguments_.join(' '));
10452 }; // We alter the prototype because we must return a function, but there is
10453 // no way to create a function with a different prototype
10456 Object.setPrototypeOf(builder, proto);
10457 builder._generator = self;
10458 builder._styler = _styler;
10459 builder._isEmpty = _isEmpty;
10463 const applyStyle = (self, string) => {
10464 if (self.level <= 0 || !string) {
10465 return self._isEmpty ? '' : string;
10468 let styler = self._styler;
10470 if (styler === undefined) {
10479 if (string.indexOf('\u001B') !== -1) {
10480 while (styler !== undefined) {
10481 // Replace any instances already present with a re-opening code
10482 // otherwise only the part of the string until said closing code
10483 // will be colored, and the rest will simply be 'plain'.
10484 string = stringReplaceAll$1(string, styler.close, styler.open);
10485 styler = styler.parent;
10487 } // We can move both next actions out of loop, because remaining actions in loop won't have
10488 // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
10489 // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
10492 const lfIndex = string.indexOf('\n');
10494 if (lfIndex !== -1) {
10495 string = stringEncaseCRLFWithFirstIndex$1(string, closeAll, openAll, lfIndex);
10498 return openAll + string + closeAll;
10503 const chalkTag = (chalk, ...strings) => {
10504 const [firstString] = strings;
10506 if (!Array.isArray(firstString)) {
10507 // If chalk() was called by itself or with a string,
10508 // return the string itself as a string.
10509 return strings.join(' ');
10512 const arguments_ = strings.slice(1);
10513 const parts = [firstString.raw[0]];
10515 for (let i = 1; i < firstString.length; i++) {
10516 parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]));
10519 if (template === undefined) {
10520 template = templates$1;
10523 return template(chalk, parts.join(''));
10526 Object.defineProperties(Chalk.prototype, styles);
10527 const chalk$1 = Chalk(); // eslint-disable-line new-cap
10529 chalk$1.supportsColor = stdoutColor;
10530 chalk$1.stderr = Chalk({
10531 level: stderrColor ? stderrColor.level : 0
10532 }); // eslint-disable-line new-cap
10534 chalk$1.stderr.supportsColor = stderrColor;
10535 var source = chalk$1;
10537 const cliDescriptor = {
10538 key: _key => _key.length === 1 ? "-".concat(_key) : "--".concat(_key),
10539 value: _value => lib.apiDescriptor.value(_value),
10543 }) => value === false ? "--no-".concat(key) : value === true ? cliDescriptor.key(key) : value === "" ? "".concat(cliDescriptor.key(key), " without an argument") : "".concat(cliDescriptor.key(key), "=").concat(value)
10546 class FlagSchema extends lib.ChoiceSchema {
10555 this._flags = flags.slice().sort();
10558 preprocess(value, utils) {
10559 if (typeof value === "string" && value.length !== 0 && !this._flags.includes(value)) {
10560 const suggestion = this._flags.find(flag => leven_1$1(flag, value) < 3);
10563 utils.logger.warn(["Unknown flag ".concat(source.yellow(utils.descriptor.value(value)), ","), "did you mean ".concat(source.blue(utils.descriptor.value(suggestion)), "?")].join(" "));
10577 let hasDeprecationWarned;
10579 function normalizeOptions(options, optionInfos, {
10582 passThrough = false
10584 const unknown = !passThrough ? lib.levenUnknownHandler : Array.isArray(passThrough) ? (key, value) => !passThrough.includes(key) ? undefined : {
10586 } : (key, value) => ({
10589 const descriptor = isCLI ? cliDescriptor : lib.apiDescriptor;
10590 const schemas = optionInfosToSchemas(optionInfos, {
10593 const normalizer = new lib.Normalizer(schemas, {
10598 const shouldSuppressDuplicateDeprecationWarnings = logger !== false;
10600 if (shouldSuppressDuplicateDeprecationWarnings && hasDeprecationWarned) {
10601 normalizer._hasDeprecationWarned = hasDeprecationWarned;
10604 const normalized = normalizer.normalize(options);
10606 if (shouldSuppressDuplicateDeprecationWarnings) {
10607 hasDeprecationWarned = normalizer._hasDeprecationWarned;
10613 function optionInfosToSchemas(optionInfos, {
10616 const schemas = [];
10619 schemas.push(lib.AnySchema.create({
10624 for (const optionInfo of optionInfos) {
10625 schemas.push(optionInfoToSchema(optionInfo, {
10630 if (optionInfo.alias && isCLI) {
10631 schemas.push(lib.AliasSchema.create({
10632 name: optionInfo.alias,
10633 sourceName: optionInfo.name
10641 function optionInfoToSchema(optionInfo, {
10645 let SchemaConstructor;
10646 const parameters = {
10647 name: optionInfo.name
10649 const handlers = {};
10651 switch (optionInfo.type) {
10653 SchemaConstructor = lib.IntegerSchema;
10656 parameters.preprocess = value => Number(value);
10662 SchemaConstructor = lib.StringSchema;
10666 SchemaConstructor = lib.ChoiceSchema;
10667 parameters.choices = optionInfo.choices.map(choiceInfo => typeof choiceInfo === "object" && choiceInfo.redirect ? Object.assign({}, choiceInfo, {
10670 key: optionInfo.name,
10671 value: choiceInfo.redirect
10678 SchemaConstructor = lib.BooleanSchema;
10682 SchemaConstructor = FlagSchema;
10683 parameters.flags = optionInfos.map(optionInfo => [].concat(optionInfo.alias || [], optionInfo.description ? optionInfo.name : [], optionInfo.oppositeDescription ? "no-".concat(optionInfo.name) : [])).reduce((a, b) => a.concat(b), []);
10687 SchemaConstructor = lib.StringSchema;
10691 throw new Error("Unexpected type ".concat(optionInfo.type));
10694 if (optionInfo.exception) {
10695 parameters.validate = (value, schema, utils) => {
10696 return optionInfo.exception(value) || schema.validate(value, utils);
10699 parameters.validate = (value, schema, utils) => {
10700 return value === undefined || schema.validate(value, utils);
10704 if (optionInfo.redirect) {
10705 handlers.redirect = value => !value ? undefined : {
10707 key: optionInfo.redirect.option,
10708 value: optionInfo.redirect.value
10713 if (optionInfo.deprecated) {
10714 handlers.deprecated = true;
10715 } // allow CLI overriding, e.g., prettier package.json --tab-width 1 --tab-width 2
10718 if (isCLI && !optionInfo.array) {
10719 const originalPreprocess = parameters.preprocess || (x => x);
10721 parameters.preprocess = (value, schema, utils) => schema.preprocess(originalPreprocess(Array.isArray(value) ? value[value.length - 1] : value), utils);
10724 return optionInfo.array ? lib.ArraySchema.create(Object.assign({}, isCLI ? {
10725 preprocess: v => [].concat(v)
10726 } : {}, {}, handlers, {
10727 valueSchema: SchemaConstructor.create(parameters)
10728 })) : SchemaConstructor.create(Object.assign({}, parameters, {}, handlers));
10731 function normalizeApiOptions(options, optionInfos, opts) {
10732 return normalizeOptions(options, optionInfos, opts);
10735 function normalizeCliOptions(options, optionInfos, opts) {
10736 return normalizeOptions(options, optionInfos, Object.assign({
10741 var optionsNormalizer = {
10742 normalizeApiOptions,
10743 normalizeCliOptions
10746 var getLast = arr => arr[arr.length - 1];
10748 function locStart(node, opts) {
10749 opts = opts || {}; // Handle nodes with decorators. They should start at the first decorator
10751 if (!opts.ignoreDecorators && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0) {
10752 return locStart(node.declaration.decorators[0]);
10755 if (!opts.ignoreDecorators && node.decorators && node.decorators.length > 0) {
10756 return locStart(node.decorators[0]);
10759 if (node.__location) {
10760 return node.__location.startOffset;
10764 return node.range[0];
10767 if (typeof node.start === "number") {
10772 return node.loc.start;
10778 function locEnd(node) {
10779 const endNode = node.nodes && getLast(node.nodes);
10781 if (endNode && node.source && !node.source.end) {
10785 if (node.__location) {
10786 return node.__location.endOffset;
10789 const loc = node.range ? node.range[1] : typeof node.end === "number" ? node.end : null;
10791 if (node.typeAnnotation) {
10792 return Math.max(loc, locEnd(node.typeAnnotation));
10795 if (node.loc && !loc) {
10796 return node.loc.end;
10802 function composeLoc(startNode, endNodeOrLength = startNode) {
10803 const length = typeof endNodeOrLength === "number" ? endNodeOrLength : -1;
10804 const start = locStart(startNode);
10805 const end = length !== -1 ? start + length : locEnd(endNodeOrLength);
10806 const startLoc = startNode.loc.start;
10810 range: [start, end],
10813 end: length !== -1 ? {
10814 line: startLoc.line,
10815 column: startLoc.column + length
10816 } : endNodeOrLength.loc.end
10827 var jsTokens = createCommonjsModule(function (module, exports) {
10828 // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell
10829 // License: MIT. (See LICENSE.)
10830 Object.defineProperty(exports, "__esModule", {
10832 }); // This regex comes from regex.coffee, and is inserted here by generate-index.js
10833 // (run `npm run build`).
10835 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;
10837 exports.matchToToken = function (match) {
10843 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";
10847 unwrapExports(jsTokens);
10848 var jsTokens_1 = jsTokens.matchToToken;
10850 var ast = createCommonjsModule(function (module) {
10852 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
10854 Redistribution and use in source and binary forms, with or without
10855 modification, are permitted provided that the following conditions are met:
10857 * Redistributions of source code must retain the above copyright
10858 notice, this list of conditions and the following disclaimer.
10859 * Redistributions in binary form must reproduce the above copyright
10860 notice, this list of conditions and the following disclaimer in the
10861 documentation and/or other materials provided with the distribution.
10863 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
10864 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
10865 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
10866 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
10867 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
10868 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
10869 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
10870 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
10871 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
10872 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
10876 function isExpression(node) {
10877 if (node == null) {
10881 switch (node.type) {
10882 case 'ArrayExpression':
10883 case 'AssignmentExpression':
10884 case 'BinaryExpression':
10885 case 'CallExpression':
10886 case 'ConditionalExpression':
10887 case 'FunctionExpression':
10890 case 'LogicalExpression':
10891 case 'MemberExpression':
10892 case 'NewExpression':
10893 case 'ObjectExpression':
10894 case 'SequenceExpression':
10895 case 'ThisExpression':
10896 case 'UnaryExpression':
10897 case 'UpdateExpression':
10904 function isIterationStatement(node) {
10905 if (node == null) {
10909 switch (node.type) {
10910 case 'DoWhileStatement':
10911 case 'ForInStatement':
10912 case 'ForStatement':
10913 case 'WhileStatement':
10920 function isStatement(node) {
10921 if (node == null) {
10925 switch (node.type) {
10926 case 'BlockStatement':
10927 case 'BreakStatement':
10928 case 'ContinueStatement':
10929 case 'DebuggerStatement':
10930 case 'DoWhileStatement':
10931 case 'EmptyStatement':
10932 case 'ExpressionStatement':
10933 case 'ForInStatement':
10934 case 'ForStatement':
10935 case 'IfStatement':
10936 case 'LabeledStatement':
10937 case 'ReturnStatement':
10938 case 'SwitchStatement':
10939 case 'ThrowStatement':
10940 case 'TryStatement':
10941 case 'VariableDeclaration':
10942 case 'WhileStatement':
10943 case 'WithStatement':
10950 function isSourceElement(node) {
10951 return isStatement(node) || node != null && node.type === 'FunctionDeclaration';
10954 function trailingStatement(node) {
10955 switch (node.type) {
10956 case 'IfStatement':
10957 if (node.alternate != null) {
10958 return node.alternate;
10961 return node.consequent;
10963 case 'LabeledStatement':
10964 case 'ForStatement':
10965 case 'ForInStatement':
10966 case 'WhileStatement':
10967 case 'WithStatement':
10974 function isProblematicIfStatement(node) {
10977 if (node.type !== 'IfStatement') {
10981 if (node.alternate == null) {
10985 current = node.consequent;
10988 if (current.type === 'IfStatement') {
10989 if (current.alternate == null) {
10994 current = trailingStatement(current);
11001 isExpression: isExpression,
11002 isStatement: isStatement,
11003 isIterationStatement: isIterationStatement,
11004 isSourceElement: isSourceElement,
11005 isProblematicIfStatement: isProblematicIfStatement,
11006 trailingStatement: trailingStatement
11009 /* vim: set sw=4 ts=4 et tw=80 : */
11012 var ast_1 = ast.isExpression;
11013 var ast_2 = ast.isStatement;
11014 var ast_3 = ast.isIterationStatement;
11015 var ast_4 = ast.isSourceElement;
11016 var ast_5 = ast.isProblematicIfStatement;
11017 var ast_6 = ast.trailingStatement;
11019 var code = createCommonjsModule(function (module) {
11021 Copyright (C) 2013-2014 Yusuke Suzuki <utatane.tea@gmail.com>
11022 Copyright (C) 2014 Ivan Nikulin <ifaaan@gmail.com>
11024 Redistribution and use in source and binary forms, with or without
11025 modification, are permitted provided that the following conditions are met:
11027 * Redistributions of source code must retain the above copyright
11028 notice, this list of conditions and the following disclaimer.
11029 * Redistributions in binary form must reproduce the above copyright
11030 notice, this list of conditions and the following disclaimer in the
11031 documentation and/or other materials provided with the distribution.
11033 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
11034 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
11035 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
11036 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
11037 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
11038 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
11039 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
11040 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11041 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
11042 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11046 var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`.
11049 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart:
11050 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]/,
11051 // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart:
11052 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]/
11055 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart:
11056 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]/,
11057 // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart:
11058 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]/
11061 function isDecimalDigit(ch) {
11062 return 0x30 <= ch && ch <= 0x39; // 0..9
11065 function isHexDigit(ch) {
11066 return 0x30 <= ch && ch <= 0x39 || // 0..9
11067 0x61 <= ch && ch <= 0x66 || // a..f
11068 0x41 <= ch && ch <= 0x46; // A..F
11071 function isOctalDigit(ch) {
11072 return ch >= 0x30 && ch <= 0x37; // 0..7
11073 } // 7.2 White Space
11076 NON_ASCII_WHITESPACES = [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF];
11078 function isWhiteSpace(ch) {
11079 return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0;
11080 } // 7.3 Line Terminators
11083 function isLineTerminator(ch) {
11084 return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029;
11085 } // 7.6 Identifier Names and Identifiers
11088 function fromCodePoint(cp) {
11089 if (cp <= 0xFFFF) {
11090 return String.fromCharCode(cp);
11093 var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800);
11094 var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00);
11098 IDENTIFIER_START = new Array(0x80);
11100 for (ch = 0; ch < 0x80; ++ch) {
11101 IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
11102 ch >= 0x41 && ch <= 0x5A || // A..Z
11103 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
11106 IDENTIFIER_PART = new Array(0x80);
11108 for (ch = 0; ch < 0x80; ++ch) {
11109 IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z
11110 ch >= 0x41 && ch <= 0x5A || // A..Z
11111 ch >= 0x30 && ch <= 0x39 || // 0..9
11112 ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore)
11115 function isIdentifierStartES5(ch) {
11116 return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
11119 function isIdentifierPartES5(ch) {
11120 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
11123 function isIdentifierStartES6(ch) {
11124 return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch));
11127 function isIdentifierPartES6(ch) {
11128 return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch));
11132 isDecimalDigit: isDecimalDigit,
11133 isHexDigit: isHexDigit,
11134 isOctalDigit: isOctalDigit,
11135 isWhiteSpace: isWhiteSpace,
11136 isLineTerminator: isLineTerminator,
11137 isIdentifierStartES5: isIdentifierStartES5,
11138 isIdentifierPartES5: isIdentifierPartES5,
11139 isIdentifierStartES6: isIdentifierStartES6,
11140 isIdentifierPartES6: isIdentifierPartES6
11143 /* vim: set sw=4 ts=4 et tw=80 : */
11146 var code_1 = code.isDecimalDigit;
11147 var code_2 = code.isHexDigit;
11148 var code_3 = code.isOctalDigit;
11149 var code_4 = code.isWhiteSpace;
11150 var code_5 = code.isLineTerminator;
11151 var code_6 = code.isIdentifierStartES5;
11152 var code_7 = code.isIdentifierPartES5;
11153 var code_8 = code.isIdentifierStartES6;
11154 var code_9 = code.isIdentifierPartES6;
11156 var keyword = createCommonjsModule(function (module) {
11158 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
11160 Redistribution and use in source and binary forms, with or without
11161 modification, are permitted provided that the following conditions are met:
11163 * Redistributions of source code must retain the above copyright
11164 notice, this list of conditions and the following disclaimer.
11165 * Redistributions in binary form must reproduce the above copyright
11166 notice, this list of conditions and the following disclaimer in the
11167 documentation and/or other materials provided with the distribution.
11169 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
11170 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
11171 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
11172 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
11173 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
11174 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
11175 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
11176 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11177 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
11178 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11184 function isStrictModeReservedWordES6(id) {
11201 function isKeywordES5(id, strict) {
11202 // yield should not be treated as keyword under non-strict mode.
11203 if (!strict && id === 'yield') {
11207 return isKeywordES6(id, strict);
11210 function isKeywordES6(id, strict) {
11211 if (strict && isStrictModeReservedWordES6(id)) {
11215 switch (id.length) {
11217 return id === 'if' || id === 'in' || id === 'do';
11220 return id === 'var' || id === 'for' || id === 'new' || id === 'try';
11223 return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum';
11226 return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super';
11229 return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import';
11232 return id === 'default' || id === 'finally' || id === 'extends';
11235 return id === 'function' || id === 'continue' || id === 'debugger';
11238 return id === 'instanceof';
11245 function isReservedWordES5(id, strict) {
11246 return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict);
11249 function isReservedWordES6(id, strict) {
11250 return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict);
11253 function isRestrictedWord(id) {
11254 return id === 'eval' || id === 'arguments';
11257 function isIdentifierNameES5(id) {
11260 if (id.length === 0) {
11264 ch = id.charCodeAt(0);
11266 if (!code$1.isIdentifierStartES5(ch)) {
11270 for (i = 1, iz = id.length; i < iz; ++i) {
11271 ch = id.charCodeAt(i);
11273 if (!code$1.isIdentifierPartES5(ch)) {
11281 function decodeUtf16(lead, trail) {
11282 return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
11285 function isIdentifierNameES6(id) {
11286 var i, iz, ch, lowCh, check;
11288 if (id.length === 0) {
11292 check = code$1.isIdentifierStartES6;
11294 for (i = 0, iz = id.length; i < iz; ++i) {
11295 ch = id.charCodeAt(i);
11297 if (0xD800 <= ch && ch <= 0xDBFF) {
11304 lowCh = id.charCodeAt(i);
11306 if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) {
11310 ch = decodeUtf16(ch, lowCh);
11317 check = code$1.isIdentifierPartES6;
11323 function isIdentifierES5(id, strict) {
11324 return isIdentifierNameES5(id) && !isReservedWordES5(id, strict);
11327 function isIdentifierES6(id, strict) {
11328 return isIdentifierNameES6(id) && !isReservedWordES6(id, strict);
11332 isKeywordES5: isKeywordES5,
11333 isKeywordES6: isKeywordES6,
11334 isReservedWordES5: isReservedWordES5,
11335 isReservedWordES6: isReservedWordES6,
11336 isRestrictedWord: isRestrictedWord,
11337 isIdentifierNameES5: isIdentifierNameES5,
11338 isIdentifierNameES6: isIdentifierNameES6,
11339 isIdentifierES5: isIdentifierES5,
11340 isIdentifierES6: isIdentifierES6
11343 /* vim: set sw=4 ts=4 et tw=80 : */
11346 var keyword_1 = keyword.isKeywordES5;
11347 var keyword_2 = keyword.isKeywordES6;
11348 var keyword_3 = keyword.isReservedWordES5;
11349 var keyword_4 = keyword.isReservedWordES6;
11350 var keyword_5 = keyword.isRestrictedWord;
11351 var keyword_6 = keyword.isIdentifierNameES5;
11352 var keyword_7 = keyword.isIdentifierNameES6;
11353 var keyword_8 = keyword.isIdentifierES5;
11354 var keyword_9 = keyword.isIdentifierES6;
11356 var utils$1 = createCommonjsModule(function (module, exports) {
11358 Copyright (C) 2013 Yusuke Suzuki <utatane.tea@gmail.com>
11360 Redistribution and use in source and binary forms, with or without
11361 modification, are permitted provided that the following conditions are met:
11363 * Redistributions of source code must retain the above copyright
11364 notice, this list of conditions and the following disclaimer.
11365 * Redistributions in binary form must reproduce the above copyright
11366 notice, this list of conditions and the following disclaimer in the
11367 documentation and/or other materials provided with the distribution.
11369 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
11370 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
11371 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
11372 ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
11373 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
11374 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
11375 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
11376 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11377 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
11378 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11383 exports.code = code;
11384 exports.keyword = keyword;
11386 /* vim: set sw=4 ts=4 et tw=80 : */
11389 var utils_1$1 = utils$1.ast;
11390 var utils_2$1 = utils$1.code;
11391 var utils_3$1 = utils$1.keyword;
11393 var matchOperatorsRe$1 = /[|\\{}()[\]^$+*?.]/g;
11395 var escapeStringRegexp$1 = function escapeStringRegexp(str) {
11396 if (typeof str !== 'string') {
11397 throw new TypeError('Expected a string');
11400 return str.replace(matchOperatorsRe$1, '\\$&');
11403 var colorName$2 = {
11404 "aliceblue": [240, 248, 255],
11405 "antiquewhite": [250, 235, 215],
11406 "aqua": [0, 255, 255],
11407 "aquamarine": [127, 255, 212],
11408 "azure": [240, 255, 255],
11409 "beige": [245, 245, 220],
11410 "bisque": [255, 228, 196],
11411 "black": [0, 0, 0],
11412 "blanchedalmond": [255, 235, 205],
11413 "blue": [0, 0, 255],
11414 "blueviolet": [138, 43, 226],
11415 "brown": [165, 42, 42],
11416 "burlywood": [222, 184, 135],
11417 "cadetblue": [95, 158, 160],
11418 "chartreuse": [127, 255, 0],
11419 "chocolate": [210, 105, 30],
11420 "coral": [255, 127, 80],
11421 "cornflowerblue": [100, 149, 237],
11422 "cornsilk": [255, 248, 220],
11423 "crimson": [220, 20, 60],
11424 "cyan": [0, 255, 255],
11425 "darkblue": [0, 0, 139],
11426 "darkcyan": [0, 139, 139],
11427 "darkgoldenrod": [184, 134, 11],
11428 "darkgray": [169, 169, 169],
11429 "darkgreen": [0, 100, 0],
11430 "darkgrey": [169, 169, 169],
11431 "darkkhaki": [189, 183, 107],
11432 "darkmagenta": [139, 0, 139],
11433 "darkolivegreen": [85, 107, 47],
11434 "darkorange": [255, 140, 0],
11435 "darkorchid": [153, 50, 204],
11436 "darkred": [139, 0, 0],
11437 "darksalmon": [233, 150, 122],
11438 "darkseagreen": [143, 188, 143],
11439 "darkslateblue": [72, 61, 139],
11440 "darkslategray": [47, 79, 79],
11441 "darkslategrey": [47, 79, 79],
11442 "darkturquoise": [0, 206, 209],
11443 "darkviolet": [148, 0, 211],
11444 "deeppink": [255, 20, 147],
11445 "deepskyblue": [0, 191, 255],
11446 "dimgray": [105, 105, 105],
11447 "dimgrey": [105, 105, 105],
11448 "dodgerblue": [30, 144, 255],
11449 "firebrick": [178, 34, 34],
11450 "floralwhite": [255, 250, 240],
11451 "forestgreen": [34, 139, 34],
11452 "fuchsia": [255, 0, 255],
11453 "gainsboro": [220, 220, 220],
11454 "ghostwhite": [248, 248, 255],
11455 "gold": [255, 215, 0],
11456 "goldenrod": [218, 165, 32],
11457 "gray": [128, 128, 128],
11458 "green": [0, 128, 0],
11459 "greenyellow": [173, 255, 47],
11460 "grey": [128, 128, 128],
11461 "honeydew": [240, 255, 240],
11462 "hotpink": [255, 105, 180],
11463 "indianred": [205, 92, 92],
11464 "indigo": [75, 0, 130],
11465 "ivory": [255, 255, 240],
11466 "khaki": [240, 230, 140],
11467 "lavender": [230, 230, 250],
11468 "lavenderblush": [255, 240, 245],
11469 "lawngreen": [124, 252, 0],
11470 "lemonchiffon": [255, 250, 205],
11471 "lightblue": [173, 216, 230],
11472 "lightcoral": [240, 128, 128],
11473 "lightcyan": [224, 255, 255],
11474 "lightgoldenrodyellow": [250, 250, 210],
11475 "lightgray": [211, 211, 211],
11476 "lightgreen": [144, 238, 144],
11477 "lightgrey": [211, 211, 211],
11478 "lightpink": [255, 182, 193],
11479 "lightsalmon": [255, 160, 122],
11480 "lightseagreen": [32, 178, 170],
11481 "lightskyblue": [135, 206, 250],
11482 "lightslategray": [119, 136, 153],
11483 "lightslategrey": [119, 136, 153],
11484 "lightsteelblue": [176, 196, 222],
11485 "lightyellow": [255, 255, 224],
11486 "lime": [0, 255, 0],
11487 "limegreen": [50, 205, 50],
11488 "linen": [250, 240, 230],
11489 "magenta": [255, 0, 255],
11490 "maroon": [128, 0, 0],
11491 "mediumaquamarine": [102, 205, 170],
11492 "mediumblue": [0, 0, 205],
11493 "mediumorchid": [186, 85, 211],
11494 "mediumpurple": [147, 112, 219],
11495 "mediumseagreen": [60, 179, 113],
11496 "mediumslateblue": [123, 104, 238],
11497 "mediumspringgreen": [0, 250, 154],
11498 "mediumturquoise": [72, 209, 204],
11499 "mediumvioletred": [199, 21, 133],
11500 "midnightblue": [25, 25, 112],
11501 "mintcream": [245, 255, 250],
11502 "mistyrose": [255, 228, 225],
11503 "moccasin": [255, 228, 181],
11504 "navajowhite": [255, 222, 173],
11505 "navy": [0, 0, 128],
11506 "oldlace": [253, 245, 230],
11507 "olive": [128, 128, 0],
11508 "olivedrab": [107, 142, 35],
11509 "orange": [255, 165, 0],
11510 "orangered": [255, 69, 0],
11511 "orchid": [218, 112, 214],
11512 "palegoldenrod": [238, 232, 170],
11513 "palegreen": [152, 251, 152],
11514 "paleturquoise": [175, 238, 238],
11515 "palevioletred": [219, 112, 147],
11516 "papayawhip": [255, 239, 213],
11517 "peachpuff": [255, 218, 185],
11518 "peru": [205, 133, 63],
11519 "pink": [255, 192, 203],
11520 "plum": [221, 160, 221],
11521 "powderblue": [176, 224, 230],
11522 "purple": [128, 0, 128],
11523 "rebeccapurple": [102, 51, 153],
11524 "red": [255, 0, 0],
11525 "rosybrown": [188, 143, 143],
11526 "royalblue": [65, 105, 225],
11527 "saddlebrown": [139, 69, 19],
11528 "salmon": [250, 128, 114],
11529 "sandybrown": [244, 164, 96],
11530 "seagreen": [46, 139, 87],
11531 "seashell": [255, 245, 238],
11532 "sienna": [160, 82, 45],
11533 "silver": [192, 192, 192],
11534 "skyblue": [135, 206, 235],
11535 "slateblue": [106, 90, 205],
11536 "slategray": [112, 128, 144],
11537 "slategrey": [112, 128, 144],
11538 "snow": [255, 250, 250],
11539 "springgreen": [0, 255, 127],
11540 "steelblue": [70, 130, 180],
11541 "tan": [210, 180, 140],
11542 "teal": [0, 128, 128],
11543 "thistle": [216, 191, 216],
11544 "tomato": [255, 99, 71],
11545 "turquoise": [64, 224, 208],
11546 "violet": [238, 130, 238],
11547 "wheat": [245, 222, 179],
11548 "white": [255, 255, 255],
11549 "whitesmoke": [245, 245, 245],
11550 "yellow": [255, 255, 0],
11551 "yellowgreen": [154, 205, 50]
11554 var conversions$2 = createCommonjsModule(function (module) {
11556 // NOTE: conversions should only return primitive values (i.e. arrays, or
11557 // values that give correct `typeof` results).
11558 // do not use box values types (i.e. Number(), String(), etc.)
11559 var reverseKeywords = {};
11561 for (var key in colorName$2) {
11562 if (colorName$2.hasOwnProperty(key)) {
11563 reverseKeywords[colorName$2[key]] = key;
11567 var convert = module.exports = {
11606 labels: ['keyword']
11614 labels: ['ansi256']
11618 labels: ['h', 'c', 'g']
11622 labels: ['r16', 'g16', 'b16']
11628 }; // hide .channels and .labels properties
11630 for (var model in convert) {
11631 if (convert.hasOwnProperty(model)) {
11632 if (!('channels' in convert[model])) {
11633 throw new Error('missing channels property: ' + model);
11636 if (!('labels' in convert[model])) {
11637 throw new Error('missing channel labels property: ' + model);
11640 if (convert[model].labels.length !== convert[model].channels) {
11641 throw new Error('channel and label counts mismatch: ' + model);
11644 var channels = convert[model].channels;
11645 var labels = convert[model].labels;
11646 delete convert[model].channels;
11647 delete convert[model].labels;
11648 Object.defineProperty(convert[model], 'channels', {
11651 Object.defineProperty(convert[model], 'labels', {
11657 convert.rgb.hsl = function (rgb) {
11658 var r = rgb[0] / 255;
11659 var g = rgb[1] / 255;
11660 var b = rgb[2] / 255;
11661 var min = Math.min(r, g, b);
11662 var max = Math.max(r, g, b);
11663 var delta = max - min;
11670 } else if (r === max) {
11671 h = (g - b) / delta;
11672 } else if (g === max) {
11673 h = 2 + (b - r) / delta;
11674 } else if (b === max) {
11675 h = 4 + (r - g) / delta;
11678 h = Math.min(h * 60, 360);
11684 l = (min + max) / 2;
11688 } else if (l <= 0.5) {
11689 s = delta / (max + min);
11691 s = delta / (2 - max - min);
11694 return [h, s * 100, l * 100];
11697 convert.rgb.hsv = function (rgb) {
11703 var r = rgb[0] / 255;
11704 var g = rgb[1] / 255;
11705 var b = rgb[2] / 255;
11706 var v = Math.max(r, g, b);
11707 var diff = v - Math.min(r, g, b);
11709 var diffc = function diffc(c) {
11710 return (v - c) / 6 / diff + 1 / 2;
11723 } else if (g === v) {
11724 h = 1 / 3 + rdif - bdif;
11725 } else if (b === v) {
11726 h = 2 / 3 + gdif - rdif;
11731 } else if (h > 1) {
11736 return [h * 360, s * 100, v * 100];
11739 convert.rgb.hwb = function (rgb) {
11743 var h = convert.rgb.hsl(rgb)[0];
11744 var w = 1 / 255 * Math.min(r, Math.min(g, b));
11745 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
11746 return [h, w * 100, b * 100];
11749 convert.rgb.cmyk = function (rgb) {
11750 var r = rgb[0] / 255;
11751 var g = rgb[1] / 255;
11752 var b = rgb[2] / 255;
11757 k = Math.min(1 - r, 1 - g, 1 - b);
11758 c = (1 - r - k) / (1 - k) || 0;
11759 m = (1 - g - k) / (1 - k) || 0;
11760 y = (1 - b - k) / (1 - k) || 0;
11761 return [c * 100, m * 100, y * 100, k * 100];
11764 * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
11768 function comparativeDistance(x, y) {
11769 return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2);
11772 convert.rgb.keyword = function (rgb) {
11773 var reversed = reverseKeywords[rgb];
11779 var currentClosestDistance = Infinity;
11780 var currentClosestKeyword;
11782 for (var keyword in colorName$2) {
11783 if (colorName$2.hasOwnProperty(keyword)) {
11784 var value = colorName$2[keyword]; // Compute comparative distance
11786 var distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
11788 if (distance < currentClosestDistance) {
11789 currentClosestDistance = distance;
11790 currentClosestKeyword = keyword;
11795 return currentClosestKeyword;
11798 convert.keyword.rgb = function (keyword) {
11799 return colorName$2[keyword];
11802 convert.rgb.xyz = function (rgb) {
11803 var r = rgb[0] / 255;
11804 var g = rgb[1] / 255;
11805 var b = rgb[2] / 255; // assume sRGB
11807 r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92;
11808 g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92;
11809 b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92;
11810 var x = r * 0.4124 + g * 0.3576 + b * 0.1805;
11811 var y = r * 0.2126 + g * 0.7152 + b * 0.0722;
11812 var z = r * 0.0193 + g * 0.1192 + b * 0.9505;
11813 return [x * 100, y * 100, z * 100];
11816 convert.rgb.lab = function (rgb) {
11817 var xyz = convert.rgb.xyz(rgb);
11827 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
11828 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
11829 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
11836 convert.hsl.rgb = function (hsl) {
11837 var h = hsl[0] / 360;
11838 var s = hsl[1] / 100;
11839 var l = hsl[2] / 100;
11848 return [val, val, val];
11854 t2 = l + s - l * s;
11860 for (var i = 0; i < 3; i++) {
11861 t3 = h + 1 / 3 * -(i - 1);
11872 val = t1 + (t2 - t1) * 6 * t3;
11873 } else if (2 * t3 < 1) {
11875 } else if (3 * t3 < 2) {
11876 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
11881 rgb[i] = val * 255;
11887 convert.hsl.hsv = function (hsl) {
11889 var s = hsl[1] / 100;
11890 var l = hsl[2] / 100;
11892 var lmin = Math.max(l, 0.01);
11896 s *= l <= 1 ? l : 2 - l;
11897 smin *= lmin <= 1 ? lmin : 2 - lmin;
11899 sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
11900 return [h, sv * 100, v * 100];
11903 convert.hsv.rgb = function (hsv) {
11904 var h = hsv[0] / 60;
11905 var s = hsv[1] / 100;
11906 var v = hsv[2] / 100;
11907 var hi = Math.floor(h) % 6;
11908 var f = h - Math.floor(h);
11909 var p = 255 * v * (1 - s);
11910 var q = 255 * v * (1 - s * f);
11911 var t = 255 * v * (1 - s * (1 - f));
11935 convert.hsv.hsl = function (hsv) {
11937 var s = hsv[1] / 100;
11938 var v = hsv[2] / 100;
11939 var vmin = Math.max(v, 0.01);
11944 lmin = (2 - s) * vmin;
11946 sl /= lmin <= 1 ? lmin : 2 - lmin;
11949 return [h, sl * 100, l * 100];
11950 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
11953 convert.hwb.rgb = function (hwb) {
11954 var h = hwb[0] / 360;
11955 var wh = hwb[1] / 100;
11956 var bl = hwb[2] / 100;
11957 var ratio = wh + bl;
11961 var n; // wh + bl cant be > 1
11968 i = Math.floor(6 * h);
11972 if ((i & 0x01) !== 0) {
11976 n = wh + f * (v - wh); // linear interpolation
12022 return [r * 255, g * 255, b * 255];
12025 convert.cmyk.rgb = function (cmyk) {
12026 var c = cmyk[0] / 100;
12027 var m = cmyk[1] / 100;
12028 var y = cmyk[2] / 100;
12029 var k = cmyk[3] / 100;
12033 r = 1 - Math.min(1, c * (1 - k) + k);
12034 g = 1 - Math.min(1, m * (1 - k) + k);
12035 b = 1 - Math.min(1, y * (1 - k) + k);
12036 return [r * 255, g * 255, b * 255];
12039 convert.xyz.rgb = function (xyz) {
12040 var x = xyz[0] / 100;
12041 var y = xyz[1] / 100;
12042 var z = xyz[2] / 100;
12046 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
12047 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
12048 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // assume sRGB
12050 r = r > 0.0031308 ? 1.055 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92;
12051 g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92;
12052 b = b > 0.0031308 ? 1.055 * Math.pow(b, 1.0 / 2.4) - 0.055 : b * 12.92;
12053 r = Math.min(Math.max(0, r), 1);
12054 g = Math.min(Math.max(0, g), 1);
12055 b = Math.min(Math.max(0, b), 1);
12056 return [r * 255, g * 255, b * 255];
12059 convert.xyz.lab = function (xyz) {
12069 x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116;
12070 y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116;
12071 z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116;
12078 convert.lab.xyz = function (lab) {
12085 y = (l + 16) / 116;
12088 var y2 = Math.pow(y, 3);
12089 var x2 = Math.pow(x, 3);
12090 var z2 = Math.pow(z, 3);
12091 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
12092 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
12093 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
12100 convert.lab.lch = function (lab) {
12107 hr = Math.atan2(b, a);
12108 h = hr * 360 / 2 / Math.PI;
12114 c = Math.sqrt(a * a + b * b);
12118 convert.lch.lab = function (lch) {
12125 hr = h / 360 * 2 * Math.PI;
12126 a = c * Math.cos(hr);
12127 b = c * Math.sin(hr);
12131 convert.rgb.ansi16 = function (args) {
12135 var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
12137 value = Math.round(value / 50);
12143 var ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
12152 convert.hsv.ansi16 = function (args) {
12153 // optimization here; we already know the value and don't need to get
12154 // it converted for us.
12155 return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
12158 convert.rgb.ansi256 = function (args) {
12161 var b = args[2]; // we use the extended greyscale palette here, with the exception of
12162 // black and white. normal palette only has 4 greyscale shades.
12164 if (r === g && g === b) {
12173 return Math.round((r - 8) / 247 * 24) + 232;
12176 var ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
12180 convert.ansi16.rgb = function (args) {
12181 var color = args % 10; // handle greyscale
12183 if (color === 0 || color === 7) {
12188 color = color / 10.5 * 255;
12189 return [color, color, color];
12192 var mult = (~~(args > 50) + 1) * 0.5;
12193 var r = (color & 1) * mult * 255;
12194 var g = (color >> 1 & 1) * mult * 255;
12195 var b = (color >> 2 & 1) * mult * 255;
12199 convert.ansi256.rgb = function (args) {
12200 // handle greyscale
12202 var c = (args - 232) * 10 + 8;
12208 var r = Math.floor(args / 36) / 5 * 255;
12209 var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
12210 var b = rem % 6 / 5 * 255;
12214 convert.rgb.hex = function (args) {
12215 var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
12216 var string = integer.toString(16).toUpperCase();
12217 return '000000'.substring(string.length) + string;
12220 convert.hex.rgb = function (args) {
12221 var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
12227 var colorString = match[0];
12229 if (match[0].length === 3) {
12230 colorString = colorString.split('').map(function (char) {
12231 return char + char;
12235 var integer = parseInt(colorString, 16);
12236 var r = integer >> 16 & 0xFF;
12237 var g = integer >> 8 & 0xFF;
12238 var b = integer & 0xFF;
12242 convert.rgb.hcg = function (rgb) {
12243 var r = rgb[0] / 255;
12244 var g = rgb[1] / 255;
12245 var b = rgb[2] / 255;
12246 var max = Math.max(Math.max(r, g), b);
12247 var min = Math.min(Math.min(r, g), b);
12248 var chroma = max - min;
12253 grayscale = min / (1 - chroma);
12260 } else if (max === r) {
12261 hue = (g - b) / chroma % 6;
12262 } else if (max === g) {
12263 hue = 2 + (b - r) / chroma;
12265 hue = 4 + (r - g) / chroma + 4;
12270 return [hue * 360, chroma * 100, grayscale * 100];
12273 convert.hsl.hcg = function (hsl) {
12274 var s = hsl[1] / 100;
12275 var l = hsl[2] / 100;
12282 c = 2.0 * s * (1.0 - l);
12286 f = (l - 0.5 * c) / (1.0 - c);
12289 return [hsl[0], c * 100, f * 100];
12292 convert.hsv.hcg = function (hsv) {
12293 var s = hsv[1] / 100;
12294 var v = hsv[2] / 100;
12299 f = (v - c) / (1 - c);
12302 return [hsv[0], c * 100, f * 100];
12305 convert.hcg.rgb = function (hcg) {
12306 var h = hcg[0] / 360;
12307 var c = hcg[1] / 100;
12308 var g = hcg[2] / 100;
12311 return [g * 255, g * 255, g * 255];
12314 var pure = [0, 0, 0];
12315 var hi = h % 1 * 6;
12320 switch (Math.floor(hi)) {
12357 mg = (1.0 - c) * g;
12358 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
12361 convert.hcg.hsv = function (hcg) {
12362 var c = hcg[1] / 100;
12363 var g = hcg[2] / 100;
12364 var v = c + g * (1.0 - c);
12371 return [hcg[0], f * 100, v * 100];
12374 convert.hcg.hsl = function (hcg) {
12375 var c = hcg[1] / 100;
12376 var g = hcg[2] / 100;
12377 var l = g * (1.0 - c) + 0.5 * c;
12380 if (l > 0.0 && l < 0.5) {
12382 } else if (l >= 0.5 && l < 1.0) {
12383 s = c / (2 * (1 - l));
12386 return [hcg[0], s * 100, l * 100];
12389 convert.hcg.hwb = function (hcg) {
12390 var c = hcg[1] / 100;
12391 var g = hcg[2] / 100;
12392 var v = c + g * (1.0 - c);
12393 return [hcg[0], (v - c) * 100, (1 - v) * 100];
12396 convert.hwb.hcg = function (hwb) {
12397 var w = hwb[1] / 100;
12398 var b = hwb[2] / 100;
12404 g = (v - c) / (1 - c);
12407 return [hwb[0], c * 100, g * 100];
12410 convert.apple.rgb = function (apple) {
12411 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
12414 convert.rgb.apple = function (rgb) {
12415 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
12418 convert.gray.rgb = function (args) {
12419 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
12422 convert.gray.hsl = convert.gray.hsv = function (args) {
12423 return [0, 0, args[0]];
12426 convert.gray.hwb = function (gray) {
12427 return [0, 100, gray[0]];
12430 convert.gray.cmyk = function (gray) {
12431 return [0, 0, 0, gray[0]];
12434 convert.gray.lab = function (gray) {
12435 return [gray[0], 0, 0];
12438 convert.gray.hex = function (gray) {
12439 var val = Math.round(gray[0] / 100 * 255) & 0xFF;
12440 var integer = (val << 16) + (val << 8) + val;
12441 var string = integer.toString(16).toUpperCase();
12442 return '000000'.substring(string.length) + string;
12445 convert.rgb.gray = function (rgb) {
12446 var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
12447 return [val / 255 * 100];
12450 var conversions_1$1 = conversions$2.rgb;
12451 var conversions_2$1 = conversions$2.hsl;
12452 var conversions_3$1 = conversions$2.hsv;
12453 var conversions_4$1 = conversions$2.hwb;
12454 var conversions_5$1 = conversions$2.cmyk;
12455 var conversions_6$1 = conversions$2.xyz;
12456 var conversions_7$1 = conversions$2.lab;
12457 var conversions_8$1 = conversions$2.lch;
12458 var conversions_9$1 = conversions$2.hex;
12459 var conversions_10$1 = conversions$2.keyword;
12460 var conversions_11$1 = conversions$2.ansi16;
12461 var conversions_12$1 = conversions$2.ansi256;
12462 var conversions_13$1 = conversions$2.hcg;
12463 var conversions_14$1 = conversions$2.apple;
12464 var conversions_15$1 = conversions$2.gray;
12467 this function routes a model to all other models.
12469 all functions that are routed have a property `.conversion` attached
12470 to the returned synthetic function. This property is an array
12471 of strings, each with the steps in between the 'from' and 'to'
12472 color models (inclusive).
12474 conversions that are not possible simply are not included.
12477 function buildGraph$2() {
12478 var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
12480 var models = Object.keys(conversions$2);
12482 for (var len = models.length, i = 0; i < len; i++) {
12483 graph[models[i]] = {
12484 // http://jsperf.com/1-vs-infinity
12485 // micro-opt, but this is simple.
12492 } // https://en.wikipedia.org/wiki/Breadth-first_search
12495 function deriveBFS$2(fromModel) {
12496 var graph = buildGraph$2();
12497 var queue = [fromModel]; // unshift -> queue -> pop
12499 graph[fromModel].distance = 0;
12501 while (queue.length) {
12502 var current = queue.pop();
12503 var adjacents = Object.keys(conversions$2[current]);
12505 for (var len = adjacents.length, i = 0; i < len; i++) {
12506 var adjacent = adjacents[i];
12507 var node = graph[adjacent];
12509 if (node.distance === -1) {
12510 node.distance = graph[current].distance + 1;
12511 node.parent = current;
12512 queue.unshift(adjacent);
12520 function link$2(from, to) {
12521 return function (args) {
12522 return to(from(args));
12526 function wrapConversion$2(toModel, graph) {
12527 var path = [graph[toModel].parent, toModel];
12528 var fn = conversions$2[graph[toModel].parent][toModel];
12529 var cur = graph[toModel].parent;
12531 while (graph[cur].parent) {
12532 path.unshift(graph[cur].parent);
12533 fn = link$2(conversions$2[graph[cur].parent][cur], fn);
12534 cur = graph[cur].parent;
12537 fn.conversion = path;
12541 var route$2 = function route(fromModel) {
12542 var graph = deriveBFS$2(fromModel);
12543 var conversion = {};
12544 var models = Object.keys(graph);
12546 for (var len = models.length, i = 0; i < len; i++) {
12547 var toModel = models[i];
12548 var node = graph[toModel];
12550 if (node.parent === null) {
12551 // no possible conversion, or this node is the source model.
12555 conversion[toModel] = wrapConversion$2(toModel, graph);
12561 var convert$3 = {};
12562 var models$2 = Object.keys(conversions$2);
12564 function wrapRaw$2(fn) {
12565 var wrappedFn = function wrappedFn(args) {
12566 if (args === undefined || args === null) {
12570 if (arguments.length > 1) {
12571 args = Array.prototype.slice.call(arguments);
12575 }; // preserve .conversion property if there is one
12578 if ('conversion' in fn) {
12579 wrappedFn.conversion = fn.conversion;
12585 function wrapRounded$2(fn) {
12586 var wrappedFn = function wrappedFn(args) {
12587 if (args === undefined || args === null) {
12591 if (arguments.length > 1) {
12592 args = Array.prototype.slice.call(arguments);
12595 var result = fn(args); // we're assuming the result is an array here.
12596 // see notice in conversions.js; don't use box types
12597 // in conversion functions.
12599 if (typeof result === 'object') {
12600 for (var len = result.length, i = 0; i < len; i++) {
12601 result[i] = Math.round(result[i]);
12606 }; // preserve .conversion property if there is one
12609 if ('conversion' in fn) {
12610 wrappedFn.conversion = fn.conversion;
12616 models$2.forEach(function (fromModel) {
12617 convert$3[fromModel] = {};
12618 Object.defineProperty(convert$3[fromModel], 'channels', {
12619 value: conversions$2[fromModel].channels
12621 Object.defineProperty(convert$3[fromModel], 'labels', {
12622 value: conversions$2[fromModel].labels
12624 var routes = route$2(fromModel);
12625 var routeModels = Object.keys(routes);
12626 routeModels.forEach(function (toModel) {
12627 var fn = routes[toModel];
12628 convert$3[fromModel][toModel] = wrapRounded$2(fn);
12629 convert$3[fromModel][toModel].raw = wrapRaw$2(fn);
12632 var colorConvert$2 = convert$3;
12634 var ansiStyles$2 = createCommonjsModule(function (module) {
12636 const wrapAnsi16 = (fn, offset) => function () {
12637 const code = fn.apply(colorConvert$2, arguments);
12638 return "\x1B[".concat(code + offset, "m");
12641 const wrapAnsi256 = (fn, offset) => function () {
12642 const code = fn.apply(colorConvert$2, arguments);
12643 return "\x1B[".concat(38 + offset, ";5;").concat(code, "m");
12646 const wrapAnsi16m = (fn, offset) => function () {
12647 const rgb = fn.apply(colorConvert$2, arguments);
12648 return "\x1B[".concat(38 + offset, ";2;").concat(rgb[0], ";").concat(rgb[1], ";").concat(rgb[2], "m");
12651 function assembleStyles() {
12652 const codes = new Map();
12656 // 21 isn't widely supported and 22 does the same thing
12660 underline: [4, 24],
12663 strikethrough: [9, 29]
12676 redBright: [91, 39],
12677 greenBright: [92, 39],
12678 yellowBright: [93, 39],
12679 blueBright: [94, 39],
12680 magentaBright: [95, 39],
12681 cyanBright: [96, 39],
12682 whiteBright: [97, 39]
12688 bgYellow: [43, 49],
12690 bgMagenta: [45, 49],
12694 bgBlackBright: [100, 49],
12695 bgRedBright: [101, 49],
12696 bgGreenBright: [102, 49],
12697 bgYellowBright: [103, 49],
12698 bgBlueBright: [104, 49],
12699 bgMagentaBright: [105, 49],
12700 bgCyanBright: [106, 49],
12701 bgWhiteBright: [107, 49]
12705 styles.color.grey = styles.color.gray;
12707 for (const groupName of Object.keys(styles)) {
12708 const group = styles[groupName];
12710 for (const styleName of Object.keys(group)) {
12711 const style = group[styleName];
12712 styles[styleName] = {
12713 open: "\x1B[".concat(style[0], "m"),
12714 close: "\x1B[".concat(style[1], "m")
12716 group[styleName] = styles[styleName];
12717 codes.set(style[0], style[1]);
12720 Object.defineProperty(styles, groupName, {
12724 Object.defineProperty(styles, 'codes', {
12730 const ansi2ansi = n => n;
12732 const rgb2rgb = (r, g, b) => [r, g, b];
12734 styles.color.close = '\u001B[39m';
12735 styles.bgColor.close = '\u001B[49m';
12736 styles.color.ansi = {
12737 ansi: wrapAnsi16(ansi2ansi, 0)
12739 styles.color.ansi256 = {
12740 ansi256: wrapAnsi256(ansi2ansi, 0)
12742 styles.color.ansi16m = {
12743 rgb: wrapAnsi16m(rgb2rgb, 0)
12745 styles.bgColor.ansi = {
12746 ansi: wrapAnsi16(ansi2ansi, 10)
12748 styles.bgColor.ansi256 = {
12749 ansi256: wrapAnsi256(ansi2ansi, 10)
12751 styles.bgColor.ansi16m = {
12752 rgb: wrapAnsi16m(rgb2rgb, 10)
12755 for (let key of Object.keys(colorConvert$2)) {
12756 if (typeof colorConvert$2[key] !== 'object') {
12760 const suite = colorConvert$2[key];
12762 if (key === 'ansi16') {
12766 if ('ansi16' in suite) {
12767 styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
12768 styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
12771 if ('ansi256' in suite) {
12772 styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
12773 styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
12776 if ('rgb' in suite) {
12777 styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
12778 styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
12783 } // Make the export immutable
12786 Object.defineProperty(module, 'exports', {
12788 get: assembleStyles
12792 const env$3 = process.env;
12795 if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
12796 forceColor$2 = false;
12797 } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
12798 forceColor$2 = true;
12801 if ('FORCE_COLOR' in env$3) {
12802 forceColor$2 = env$3.FORCE_COLOR.length === 0 || parseInt(env$3.FORCE_COLOR, 10) !== 0;
12805 function translateLevel$2(level) {
12813 has256: level >= 2,
12818 function supportsColor$2(stream) {
12819 if (forceColor$2 === false) {
12823 if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
12827 if (hasFlag('color=256')) {
12831 if (stream && !stream.isTTY && forceColor$2 !== true) {
12835 const min = forceColor$2 ? 1 : 0;
12837 if (process.platform === 'win32') {
12838 // Node.js 7.5.0 is the first version of Node.js to include a patch to
12839 // libuv that enables 256 color output on Windows. Anything earlier and it
12840 // won't work. However, here we target Node.js 8 at minimum as it is an LTS
12841 // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows
12842 // release that supports 256 colors. Windows 10 build 14931 is the first release
12843 // that supports 16m/TrueColor.
12844 const osRelease = require$$0$1.release().split('.');
12846 if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
12847 return Number(osRelease[2]) >= 14931 ? 3 : 2;
12853 if ('CI' in env$3) {
12854 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$3) || env$3.CI_NAME === 'codeship') {
12861 if ('TEAMCITY_VERSION' in env$3) {
12862 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$3.TEAMCITY_VERSION) ? 1 : 0;
12865 if (env$3.COLORTERM === 'truecolor') {
12869 if ('TERM_PROGRAM' in env$3) {
12870 const version = parseInt((env$3.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
12872 switch (env$3.TERM_PROGRAM) {
12874 return version >= 3 ? 3 : 2;
12876 case 'Apple_Terminal':
12882 if (/-256(color)?$/i.test(env$3.TERM)) {
12886 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$3.TERM)) {
12890 if ('COLORTERM' in env$3) {
12894 if (env$3.TERM === 'dumb') {
12901 function getSupportLevel$2(stream) {
12902 const level = supportsColor$2(stream);
12903 return translateLevel$2(level);
12906 var supportsColor_1$2 = {
12907 supportsColor: getSupportLevel$2,
12908 stdout: getSupportLevel$2(process.stdout),
12909 stderr: getSupportLevel$2(process.stderr)
12912 const TEMPLATE_REGEX$2 = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
12913 const STYLE_REGEX$2 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
12914 const STRING_REGEX$2 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
12915 const ESCAPE_REGEX$2 = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
12916 const ESCAPES$2 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
12918 function unescape$2(c) {
12919 if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) {
12920 return String.fromCharCode(parseInt(c.slice(1), 16));
12923 return ESCAPES$2.get(c) || c;
12926 function parseArguments$2(name, args) {
12927 const results = [];
12928 const chunks = args.trim().split(/\s*,\s*/g);
12931 for (const chunk of chunks) {
12932 if (!isNaN(chunk)) {
12933 results.push(Number(chunk));
12934 } else if (matches = chunk.match(STRING_REGEX$2)) {
12935 results.push(matches[2].replace(ESCAPE_REGEX$2, (m, escape, chr) => escape ? unescape$2(escape) : chr));
12937 throw new Error("Invalid Chalk template style argument: ".concat(chunk, " (in style '").concat(name, "')"));
12944 function parseStyle$2(style) {
12945 STYLE_REGEX$2.lastIndex = 0;
12946 const results = [];
12949 while ((matches = STYLE_REGEX$2.exec(style)) !== null) {
12950 const name = matches[1];
12953 const args = parseArguments$2(name, matches[2]);
12954 results.push([name].concat(args));
12956 results.push([name]);
12963 function buildStyle$2(chalk, styles) {
12964 const enabled = {};
12966 for (const layer of styles) {
12967 for (const style of layer.styles) {
12968 enabled[style[0]] = layer.inverse ? null : style.slice(1);
12972 let current = chalk;
12974 for (const styleName of Object.keys(enabled)) {
12975 if (Array.isArray(enabled[styleName])) {
12976 if (!(styleName in current)) {
12977 throw new Error("Unknown Chalk style: ".concat(styleName));
12980 if (enabled[styleName].length > 0) {
12981 current = current[styleName].apply(current, enabled[styleName]);
12983 current = current[styleName];
12991 var templates$2 = (chalk, tmp) => {
12994 let chunk = []; // eslint-disable-next-line max-params
12996 tmp.replace(TEMPLATE_REGEX$2, (m, escapeChar, inverse, style, close, chr) => {
12998 chunk.push(unescape$2(escapeChar));
12999 } else if (style) {
13000 const str = chunk.join('');
13002 chunks.push(styles.length === 0 ? str : buildStyle$2(chalk, styles)(str));
13005 styles: parseStyle$2(style)
13007 } else if (close) {
13008 if (styles.length === 0) {
13009 throw new Error('Found extraneous } in Chalk template literal');
13012 chunks.push(buildStyle$2(chalk, styles)(chunk.join('')));
13019 chunks.push(chunk.join(''));
13021 if (styles.length > 0) {
13022 const errMsg = "Chalk template literal is missing ".concat(styles.length, " closing bracket").concat(styles.length === 1 ? '' : 's', " (`}`)");
13023 throw new Error(errMsg);
13026 return chunks.join('');
13029 var chalk$2 = createCommonjsModule(function (module) {
13031 const stdoutColor = supportsColor_1$2.stdout;
13032 const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping
13034 const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such
13036 const skipModels = new Set(['gray']);
13037 const styles = Object.create(null);
13039 function applyOptions(obj, options) {
13040 options = options || {}; // Detect level if not set manually
13042 const scLevel = stdoutColor ? stdoutColor.level : 0;
13043 obj.level = options.level === undefined ? scLevel : options.level;
13044 obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
13047 function Chalk(options) {
13048 // We check for this.template here since calling `chalk.constructor()`
13049 // by itself will have a `this` of a previously constructed chalk object
13050 if (!this || !(this instanceof Chalk) || this.template) {
13052 applyOptions(chalk, options);
13054 chalk.template = function () {
13055 const args = [].slice.call(arguments);
13056 return chalkTag.apply(null, [chalk.template].concat(args));
13059 Object.setPrototypeOf(chalk, Chalk.prototype);
13060 Object.setPrototypeOf(chalk.template, chalk);
13061 chalk.template.constructor = Chalk;
13062 return chalk.template;
13065 applyOptions(this, options);
13066 } // Use bright blue on Windows as the normal blue color is illegible
13069 if (isSimpleWindowsTerm) {
13070 ansiStyles$2.blue.open = '\u001B[94m';
13073 for (const key of Object.keys(ansiStyles$2)) {
13074 ansiStyles$2[key].closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2[key].close), 'g');
13077 const codes = ansiStyles$2[key];
13078 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
13086 return build.call(this, this._styles || [], true, 'visible');
13090 ansiStyles$2.color.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2.color.close), 'g');
13092 for (const model of Object.keys(ansiStyles$2.color.ansi)) {
13093 if (skipModels.has(model)) {
13099 const level = this.level;
13100 return function () {
13101 const open = ansiStyles$2.color[levelMapping[level]][model].apply(null, arguments);
13104 close: ansiStyles$2.color.close,
13105 closeRe: ansiStyles$2.color.closeRe
13107 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
13114 ansiStyles$2.bgColor.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles$2.bgColor.close), 'g');
13116 for (const model of Object.keys(ansiStyles$2.bgColor.ansi)) {
13117 if (skipModels.has(model)) {
13121 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
13122 styles[bgModel] = {
13124 const level = this.level;
13125 return function () {
13126 const open = ansiStyles$2.bgColor[levelMapping[level]][model].apply(null, arguments);
13129 close: ansiStyles$2.bgColor.close,
13130 closeRe: ansiStyles$2.bgColor.closeRe
13132 return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
13139 const proto = Object.defineProperties(() => {}, styles);
13141 function build(_styles, _empty, key) {
13142 const builder = function builder() {
13143 return applyStyle.apply(builder, arguments);
13146 builder._styles = _styles;
13147 builder._empty = _empty;
13149 Object.defineProperty(builder, 'level', {
13157 self.level = level;
13161 Object.defineProperty(builder, 'enabled', {
13165 return self.enabled;
13169 self.enabled = enabled;
13172 }); // See below for fix regarding invisible grey/dim combination on Windows
13174 builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is
13175 // no way to create a function with a different prototype
13177 builder.__proto__ = proto; // eslint-disable-line no-proto
13182 function applyStyle() {
13183 // Support varags, but simply cast to string in case there's only one arg
13184 const args = arguments;
13185 const argsLen = args.length;
13186 let str = String(arguments[0]);
13188 if (argsLen === 0) {
13193 // Don't slice `arguments`, it prevents V8 optimizations
13194 for (let a = 1; a < argsLen; a++) {
13195 str += ' ' + args[a];
13199 if (!this.enabled || this.level <= 0 || !str) {
13200 return this._empty ? '' : str;
13201 } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
13202 // see https://github.com/chalk/chalk/issues/58
13203 // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
13206 const originalDim = ansiStyles$2.dim.open;
13208 if (isSimpleWindowsTerm && this.hasGrey) {
13209 ansiStyles$2.dim.open = '';
13212 for (const code of this._styles.slice().reverse()) {
13213 // Replace any instances already present with a re-opening code
13214 // otherwise only the part of the string until said closing code
13215 // will be colored, and the rest will simply be 'plain'.
13216 str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen
13217 // after next line to fix a bleed issue on macOS
13218 // https://github.com/chalk/chalk/pull/92
13220 str = str.replace(/\r?\n/g, "".concat(code.close, "$&").concat(code.open));
13221 } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
13224 ansiStyles$2.dim.open = originalDim;
13228 function chalkTag(chalk, strings) {
13229 if (!Array.isArray(strings)) {
13230 // If chalk() was called by itself or with a string,
13231 // return the string itself as a string.
13232 return [].slice.call(arguments, 1).join(' ');
13235 const args = [].slice.call(arguments, 2);
13236 const parts = [strings.raw[0]];
13238 for (let i = 1; i < strings.length; i++) {
13239 parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
13240 parts.push(String(strings.raw[i]));
13243 return templates$2(chalk, parts.join(''));
13246 Object.defineProperties(Chalk.prototype, styles);
13247 module.exports = Chalk(); // eslint-disable-line new-cap
13249 module.exports.supportsColor = stdoutColor;
13250 module.exports.default = module.exports; // For TypeScript
13252 var chalk_1$1 = chalk$2.supportsColor;
13254 var lib$1 = createCommonjsModule(function (module, exports) {
13256 Object.defineProperty(exports, "__esModule", {
13259 exports.shouldHighlight = shouldHighlight;
13260 exports.getChalk = getChalk;
13261 exports.default = highlight;
13263 var _jsTokens = _interopRequireWildcard(jsTokens);
13265 var _esutils = _interopRequireDefault(utils$1);
13267 var _chalk = _interopRequireDefault(chalk$2);
13269 function _interopRequireDefault(obj) {
13270 return obj && obj.__esModule ? obj : {
13275 function _getRequireWildcardCache() {
13276 if (typeof WeakMap !== "function") return null;
13277 var cache = new WeakMap();
13279 _getRequireWildcardCache = function _getRequireWildcardCache() {
13286 function _interopRequireWildcard(obj) {
13287 if (obj && obj.__esModule) {
13291 if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
13297 var cache = _getRequireWildcardCache();
13299 if (cache && cache.has(obj)) {
13300 return cache.get(obj);
13304 var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
13306 for (var key in obj) {
13307 if (Object.prototype.hasOwnProperty.call(obj, key)) {
13308 var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
13310 if (desc && (desc.get || desc.set)) {
13311 Object.defineProperty(newObj, key, desc);
13313 newObj[key] = obj[key];
13318 newObj.default = obj;
13321 cache.set(obj, newObj);
13327 function getDefs(chalk) {
13329 keyword: chalk.cyan,
13330 capitalized: chalk.yellow,
13331 jsx_tag: chalk.yellow,
13332 punctuator: chalk.yellow,
13333 number: chalk.magenta,
13334 string: chalk.green,
13335 regex: chalk.magenta,
13336 comment: chalk.grey,
13337 invalid: chalk.white.bgRed.bold
13341 const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
13342 const JSX_TAG = /^[a-z][\w-]*$/i;
13343 const BRACKET = /^[()[\]{}]$/;
13345 function getTokenType(match) {
13346 const [offset, text] = match.slice(-2);
13347 const token = (0, _jsTokens.matchToToken)(match);
13349 if (token.type === "name") {
13350 if (_esutils.default.keyword.isReservedWordES6(token.value)) {
13354 if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
13358 if (token.value[0] !== token.value[0].toLowerCase()) {
13359 return "capitalized";
13363 if (token.type === "punctuator" && BRACKET.test(token.value)) {
13367 if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
13368 return "punctuator";
13374 function highlightTokens(defs, text) {
13375 return text.replace(_jsTokens.default, function (...args) {
13376 const type = getTokenType(args);
13377 const colorize = defs[type];
13380 return args[0].split(NEWLINE).map(str => colorize(str)).join("\n");
13387 function shouldHighlight(options) {
13388 return _chalk.default.supportsColor || options.forceColor;
13391 function getChalk(options) {
13392 let chalk = _chalk.default;
13394 if (options.forceColor) {
13395 chalk = new _chalk.default.constructor({
13404 function highlight(code, options = {}) {
13405 if (shouldHighlight(options)) {
13406 const chalk = getChalk(options);
13407 const defs = getDefs(chalk);
13408 return highlightTokens(defs, code);
13414 unwrapExports(lib$1);
13415 var lib_1 = lib$1.shouldHighlight;
13416 var lib_2 = lib$1.getChalk;
13418 var lib$2 = createCommonjsModule(function (module, exports) {
13420 Object.defineProperty(exports, "__esModule", {
13423 exports.codeFrameColumns = codeFrameColumns;
13424 exports.default = _default;
13426 var _highlight = _interopRequireWildcard(lib$1);
13428 function _getRequireWildcardCache() {
13429 if (typeof WeakMap !== "function") return null;
13430 var cache = new WeakMap();
13432 _getRequireWildcardCache = function _getRequireWildcardCache() {
13439 function _interopRequireWildcard(obj) {
13440 if (obj && obj.__esModule) {
13444 if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
13450 var cache = _getRequireWildcardCache();
13452 if (cache && cache.has(obj)) {
13453 return cache.get(obj);
13457 var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
13459 for (var key in obj) {
13460 if (Object.prototype.hasOwnProperty.call(obj, key)) {
13461 var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
13463 if (desc && (desc.get || desc.set)) {
13464 Object.defineProperty(newObj, key, desc);
13466 newObj[key] = obj[key];
13471 newObj.default = obj;
13474 cache.set(obj, newObj);
13480 let deprecationWarningShown = false;
13482 function getDefs(chalk) {
13484 gutter: chalk.grey,
13485 marker: chalk.red.bold,
13486 message: chalk.red.bold
13490 const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
13492 function getMarkerLines(loc, source, opts) {
13493 const startLoc = Object.assign({
13497 const endLoc = Object.assign({}, startLoc, {}, loc.end);
13502 const startLine = startLoc.line;
13503 const startColumn = startLoc.column;
13504 const endLine = endLoc.line;
13505 const endColumn = endLoc.column;
13506 let start = Math.max(startLine - (linesAbove + 1), 0);
13507 let end = Math.min(source.length, endLine + linesBelow);
13509 if (startLine === -1) {
13513 if (endLine === -1) {
13514 end = source.length;
13517 const lineDiff = endLine - startLine;
13518 const markerLines = {};
13521 for (let i = 0; i <= lineDiff; i++) {
13522 const lineNumber = i + startLine;
13524 if (!startColumn) {
13525 markerLines[lineNumber] = true;
13526 } else if (i === 0) {
13527 const sourceLength = source[lineNumber - 1].length;
13528 markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
13529 } else if (i === lineDiff) {
13530 markerLines[lineNumber] = [0, endColumn];
13532 const sourceLength = source[lineNumber - i].length;
13533 markerLines[lineNumber] = [0, sourceLength];
13537 if (startColumn === endColumn) {
13539 markerLines[startLine] = [startColumn, 0];
13541 markerLines[startLine] = true;
13544 markerLines[startLine] = [startColumn, endColumn - startColumn];
13555 function codeFrameColumns(rawLines, loc, opts = {}) {
13556 const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts);
13557 const chalk = (0, _highlight.getChalk)(opts);
13558 const defs = getDefs(chalk);
13560 const maybeHighlight = (chalkFn, string) => {
13561 return highlighted ? chalkFn(string) : string;
13564 const lines = rawLines.split(NEWLINE);
13569 } = getMarkerLines(loc, lines, opts);
13570 const hasColumns = loc.start && typeof loc.start.column === "number";
13571 const numberMaxWidth = String(end).length;
13572 const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines;
13573 let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => {
13574 const number = start + 1 + index;
13575 const paddedNumber = " ".concat(number).slice(-numberMaxWidth);
13576 const gutter = " ".concat(paddedNumber, " | ");
13577 const hasMarker = markerLines[number];
13578 const lastMarkerLine = !markerLines[number + 1];
13581 let markerLine = "";
13583 if (Array.isArray(hasMarker)) {
13584 const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
13585 const numberOfMarkers = hasMarker[1] || 1;
13586 markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
13588 if (lastMarkerLine && opts.message) {
13589 markerLine += " " + maybeHighlight(defs.message, opts.message);
13593 return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
13595 return " ".concat(maybeHighlight(defs.gutter, gutter)).concat(line);
13599 if (opts.message && !hasColumns) {
13600 frame = "".concat(" ".repeat(numberMaxWidth + 1)).concat(opts.message, "\n").concat(frame);
13604 return chalk.reset(frame);
13610 function _default(rawLines, lineNumber, colNumber, opts = {}) {
13611 if (!deprecationWarningShown) {
13612 deprecationWarningShown = true;
13613 const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
13615 if (process.emitWarning) {
13616 process.emitWarning(message, "DeprecationWarning");
13618 const deprecationError = new Error(message);
13619 deprecationError.name = "DeprecationWarning";
13620 console.warn(new Error(message));
13624 colNumber = Math.max(colNumber, 0);
13631 return codeFrameColumns(rawLines, location, opts);
13634 unwrapExports(lib$2);
13635 var lib_1$1 = lib$2.codeFrameColumns;
13638 ConfigError: ConfigError$1
13641 locStart: locStart$1,
13643 } = loc; // Use defineProperties()/getOwnPropertyDescriptor() to prevent
13644 // triggering the parsers getters.
13646 const ownNames = Object.getOwnPropertyNames;
13647 const ownDescriptor = Object.getOwnPropertyDescriptor;
13649 function getParsers(options) {
13650 const parsers = {};
13652 for (const plugin of options.plugins) {
13653 if (!plugin.parsers) {
13657 for (const name of ownNames(plugin.parsers)) {
13658 Object.defineProperty(parsers, name, ownDescriptor(plugin.parsers, name));
13665 function resolveParser(opts, parsers) {
13666 parsers = parsers || getParsers(opts);
13668 if (typeof opts.parser === "function") {
13669 // Custom parser API always works with JavaScript.
13671 parse: opts.parser,
13672 astFormat: "estree",
13673 locStart: locStart$1,
13678 if (typeof opts.parser === "string") {
13679 if (Object.prototype.hasOwnProperty.call(parsers, opts.parser)) {
13680 return parsers[opts.parser];
13682 /* istanbul ignore next */
13686 throw new ConfigError$1("Couldn't resolve parser \"".concat(opts.parser, "\". Parsers must be explicitly added to the standalone bundle."));
13691 function parse(text, opts) {
13692 const parsers = getParsers(opts); // Create a new object {parserName: parseFn}. Uses defineProperty() to only call
13693 // the parsers getters when actually calling the parser `parse` function.
13695 const parsersForCustomParserApi = Object.keys(parsers).reduce((object, parserName) => Object.defineProperty(object, parserName, {
13699 return parsers[parserName].parse;
13703 const parser = resolveParser(opts, parsers);
13706 if (parser.preprocess) {
13707 text = parser.preprocess(text, opts);
13712 ast: parser.parse(text, parsersForCustomParserApi, opts)
13720 const codeFrame = lib$2;
13721 error.codeFrame = codeFrame.codeFrameColumns(text, loc, {
13722 highlightCode: true
13724 error.message += "\n" + error.codeFrame;
13727 /* istanbul ignore next */
13740 UndefinedParserError: UndefinedParserError$1
13743 getSupportInfo: getSupportInfo$1
13746 resolveParser: resolveParser$1
13748 const hiddenDefaults = {
13749 astFormat: "estree",
13751 originalText: undefined,
13754 }; // Copy options and fill in default values.
13756 function normalize$1(options, opts) {
13758 const rawOptions = Object.assign({}, options);
13759 const supportOptions = getSupportInfo$1({
13760 plugins: options.plugins,
13761 showUnreleased: true,
13762 showDeprecated: true
13764 const defaults = Object.assign({}, hiddenDefaults, {}, fromPairs_1(supportOptions.filter(optionInfo => optionInfo.default !== undefined).map(option => [option.name, option.default])));
13766 if (!rawOptions.parser) {
13767 if (!rawOptions.filepath) {
13768 const logger = opts.logger || console;
13769 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.");
13770 rawOptions.parser = "babel";
13772 rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins);
13774 if (!rawOptions.parser) {
13775 throw new UndefinedParserError$1("No parser could be inferred for file: ".concat(rawOptions.filepath));
13780 const parser = resolveParser$1(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(x => x.name === "parser")], {
13784 rawOptions.astFormat = parser.astFormat;
13785 rawOptions.locEnd = parser.locEnd;
13786 rawOptions.locStart = parser.locStart;
13787 const plugin = getPlugin(rawOptions);
13788 rawOptions.printer = plugin.printers[rawOptions.astFormat];
13789 const pluginDefaults = supportOptions.filter(optionInfo => optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name] !== undefined).reduce((reduced, optionInfo) => Object.assign(reduced, {
13790 [optionInfo.name]: optionInfo.pluginDefaults[plugin.name]
13792 const mixedDefaults = Object.assign({}, defaults, {}, pluginDefaults);
13793 Object.keys(mixedDefaults).forEach(k => {
13794 if (rawOptions[k] == null) {
13795 rawOptions[k] = mixedDefaults[k];
13799 if (rawOptions.parser === "json") {
13800 rawOptions.trailingComma = "none";
13803 return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({
13804 passThrough: Object.keys(hiddenDefaults)
13808 function getPlugin(options) {
13814 throw new Error("getPlugin() requires astFormat to be set");
13817 const printerPlugin = options.plugins.find(plugin => plugin.printers && plugin.printers[astFormat]);
13819 if (!printerPlugin) {
13820 throw new Error("Couldn't find plugin for AST format \"".concat(astFormat, "\""));
13823 return printerPlugin;
13826 function getInterpreter(filepath) {
13827 if (typeof filepath !== "string") {
13834 fd = fs.openSync(filepath, "r");
13836 // istanbul ignore next
13841 const liner = new readlines(fd);
13842 const firstLine = liner.next().toString("utf8"); // #!/bin/env node, #!/usr/bin/env node
13844 const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/);
13848 } // #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node
13851 const m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/);
13859 // There are some weird cases where paths are missing, causing Jest
13860 // failures. It's unclear what these correspond to in the real world.
13864 // There are some weird cases where paths are missing, causing Jest
13865 // failures. It's unclear what these correspond to in the real world.
13867 } catch (err) {// nop
13872 function inferParser(filepath, plugins) {
13873 const filename = path.basename(filepath).toLowerCase();
13874 const languages = getSupportInfo$1({
13876 }).languages.filter(language => language.since !== null); // If the file has no extension, we can try to infer the language from the
13877 // interpreter in the shebang line, if any; but since this requires FS access,
13880 let language = languages.find(language => language.extensions && language.extensions.some(extension => filename.endsWith(extension)) || language.filenames && language.filenames.find(name => name.toLowerCase() === filename));
13882 if (!language && !filename.includes(".")) {
13883 const interpreter = getInterpreter(filepath);
13884 language = languages.find(language => language.interpreters && language.interpreters.includes(interpreter));
13887 return language && language.parsers[0];
13891 normalize: normalize$1,
13896 function massageAST(ast, options, parent) {
13897 if (Array.isArray(ast)) {
13898 return ast.map(e => massageAST(e, options, parent)).filter(Boolean);
13901 if (!ast || typeof ast !== "object") {
13907 for (const key of Object.keys(ast)) {
13908 if (typeof ast[key] !== "function") {
13909 newObj[key] = massageAST(ast[key], options, ast);
13913 if (options.printer.massageAstNode) {
13914 const result = options.printer.massageAstNode(ast, newObj, parent);
13916 if (result === null) {
13928 var massageAst = massageAST;
13930 function assert() {}
13932 assert.ok = function () {};
13934 assert.strictEqual = function () {};
13937 * @param {Doc[]} parts
13942 function concat(parts) {
13943 // access the internals of a document directly.
13944 // if(parts.length === 1) {
13945 // // If it's a single document, no need to concat it.
13946 // return parts[0];
13956 * @param {Doc} contents
13961 function indent(contents) {
13969 * @param {number} n
13970 * @param {Doc} contents
13975 function align(n, contents) {
13984 * @param {Doc} contents
13985 * @param {object} [opts] - TBD ???
13990 function group(contents, opts) {
13997 break: !!opts.shouldBreak,
13998 expandedStates: opts.expandedStates
14002 * @param {Doc} contents
14007 function dedentToRoot(contents) {
14008 return align(-Infinity, contents);
14011 * @param {Doc} contents
14016 function markAsRoot(contents) {
14017 // @ts-ignore - TBD ???:
14023 * @param {Doc} contents
14028 function dedent(contents) {
14029 return align(-1, contents);
14032 * @param {Doc[]} states
14033 * @param {object} [opts] - TBD ???
14038 function conditionalGroup(states, opts) {
14039 return group(states[0], Object.assign({}, opts, {
14040 expandedStates: states
14044 * @param {Doc[]} parts
14049 function fill(parts) {
14057 * @param {Doc} [breakContents]
14058 * @param {Doc} [flatContents]
14059 * @param {object} [opts] - TBD ???
14064 function ifBreak(breakContents, flatContents, opts) {
14071 groupId: opts.groupId
14075 * @param {Doc} contents
14080 function lineSuffix(contents) {
14083 type: "line-suffix",
14088 const lineSuffixBoundary = {
14089 type: "line-suffix-boundary"
14091 const breakParent = {
14092 type: "break-parent"
14104 const hardline = concat([{
14108 const literalline = concat([{
14115 placeholder: Symbol("cursor")
14119 * @param {Doc[]} arr
14123 function join(sep, arr) {
14126 for (let i = 0; i < arr.length; i++) {
14134 return concat(res);
14138 * @param {number} size
14139 * @param {number} tabWidth
14143 function addAlignmentToDoc(doc, size, tabWidth) {
14147 // Use indent to add tabs for all the levels of tabs we need
14148 for (let i = 0; i < Math.floor(size / tabWidth); ++i) {
14149 aligned = indent(aligned);
14150 } // Use align for all the spaces that are needed
14153 aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current
14154 // indentation, so we use -Infinity to reset the indentation to 0
14156 aligned = align(-Infinity, aligned);
14162 var docBuilders = {
14173 lineSuffixBoundary,
14189 const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'].join('|');
14190 return new RegExp(pattern, onlyFirst ? undefined : 'g');
14193 var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
14195 /* eslint-disable yoda */
14197 const isFullwidthCodePoint = codePoint => {
14198 if (Number.isNaN(codePoint)) {
14200 } // Code points are derived from:
14201 // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
14204 if (codePoint >= 0x1100 && (codePoint <= 0x115F || // Hangul Jamo
14205 codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET
14206 codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET
14207 // CJK Radicals Supplement .. Enclosed CJK Letters and Months
14208 0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
14209 0x3250 <= codePoint && codePoint <= 0x4DBF || // CJK Unified Ideographs .. Yi Radicals
14210 0x4E00 <= codePoint && codePoint <= 0xA4C6 || // Hangul Jamo Extended-A
14211 0xA960 <= codePoint && codePoint <= 0xA97C || // Hangul Syllables
14212 0xAC00 <= codePoint && codePoint <= 0xD7A3 || // CJK Compatibility Ideographs
14213 0xF900 <= codePoint && codePoint <= 0xFAFF || // Vertical Forms
14214 0xFE10 <= codePoint && codePoint <= 0xFE19 || // CJK Compatibility Forms .. Small Form Variants
14215 0xFE30 <= codePoint && codePoint <= 0xFE6B || // Halfwidth and Fullwidth Forms
14216 0xFF01 <= codePoint && codePoint <= 0xFF60 || 0xFFE0 <= codePoint && codePoint <= 0xFFE6 || // Kana Supplement
14217 0x1B000 <= codePoint && codePoint <= 0x1B001 || // Enclosed Ideographic Supplement
14218 0x1F200 <= codePoint && codePoint <= 0x1F251 || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
14219 0x20000 <= codePoint && codePoint <= 0x3FFFD)) {
14226 var isFullwidthCodePoint_1 = isFullwidthCodePoint;
14227 var default_1$1 = isFullwidthCodePoint;
14228 isFullwidthCodePoint_1.default = default_1$1;
14230 var emojiRegex = function emojiRegex() {
14231 // https://mths.be/emoji
14232 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;
14235 const stringWidth = string => {
14236 string = string.replace(emojiRegex(), ' ');
14238 if (typeof string !== 'string' || string.length === 0) {
14242 string = stripAnsi(string);
14245 for (let i = 0; i < string.length; i++) {
14246 const code = string.codePointAt(i); // Ignore control characters
14248 if (code <= 0x1F || code >= 0x7F && code <= 0x9F) {
14250 } // Ignore combining characters
14253 if (code >= 0x300 && code <= 0x36F) {
14258 if (code > 0xFFFF) {
14262 width += isFullwidthCodePoint_1(code) ? 2 : 1;
14268 var stringWidth_1 = stringWidth; // TODO: remove this in the next major version
14270 var default_1$2 = stringWidth;
14271 stringWidth_1.default = default_1$2;
14273 const matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g;
14275 var escapeStringRegexp$2 = string => {
14276 if (typeof string !== 'string') {
14277 throw new TypeError('Expected a string');
14280 return string.replace(matchOperatorsRegex, '\\$&');
14283 const notAsciiRegex = /[^\x20-\x7F]/;
14285 function getPenultimate(arr) {
14286 if (arr.length > 1) {
14287 return arr[arr.length - 2];
14293 * @typedef {{backwards?: boolean}} SkipOptions
14297 * @param {string | RegExp} chars
14298 * @returns {(text: string, index: number | false, opts?: SkipOptions) => number | false}
14302 function skip(chars) {
14303 return (text, index, opts) => {
14304 const backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having
14305 // to check for failures (did someone say monads?).
14307 if (index === false) {
14314 let cursor = index;
14316 while (cursor >= 0 && cursor < length) {
14317 const c = text.charAt(cursor);
14319 if (chars instanceof RegExp) {
14320 if (!chars.test(c)) {
14323 } else if (!chars.includes(c)) {
14327 backwards ? cursor-- : cursor++;
14330 if (cursor === -1 || cursor === length) {
14331 // If we reached the beginning or end of the file, return the
14332 // out-of-bounds cursor. It's up to the caller to handle this
14333 // correctly. We don't want to indicate `false` though if it
14334 // actually skipped valid characters.
14342 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
14346 const skipWhitespace = skip(/\s/);
14348 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
14351 const skipSpaces = skip(" \t");
14353 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
14356 const skipToLineEnd = skip(",; \t");
14358 * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false}
14361 const skipEverythingButNewLine = skip(/[^\r\n]/);
14363 * @param {string} text
14364 * @param {number | false} index
14365 * @returns {number | false}
14368 function skipInlineComment(text, index) {
14369 if (index === false) {
14373 if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") {
14374 for (let i = index + 2; i < text.length; ++i) {
14375 if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") {
14384 * @param {string} text
14385 * @param {number | false} index
14386 * @returns {number | false}
14390 function skipTrailingComment(text, index) {
14391 if (index === false) {
14395 if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") {
14396 return skipEverythingButNewLine(text, index);
14400 } // This one doesn't use the above helper function because it wants to
14401 // test \r\n in order and `skip` doesn't support ordering and we only
14402 // want to skip one newline. It's simple to implement.
14405 * @param {string} text
14406 * @param {number | false} index
14407 * @param {SkipOptions=} opts
14408 * @returns {number | false}
14412 function skipNewline(text, index, opts) {
14413 const backwards = opts && opts.backwards;
14415 if (index === false) {
14419 const atIndex = text.charAt(index);
14422 if (text.charAt(index - 1) === "\r" && atIndex === "\n") {
14426 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
14430 if (atIndex === "\r" && text.charAt(index + 1) === "\n") {
14434 if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") {
14442 * @param {string} text
14443 * @param {number} index
14444 * @param {SkipOptions=} opts
14445 * @returns {boolean}
14449 function hasNewline(text, index, opts) {
14451 const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
14452 const idx2 = skipNewline(text, idx, opts);
14453 return idx !== idx2;
14456 * @param {string} text
14457 * @param {number} start
14458 * @param {number} end
14459 * @returns {boolean}
14463 function hasNewlineInRange(text, start, end) {
14464 for (let i = start; i < end; ++i) {
14465 if (text.charAt(i) === "\n") {
14471 } // Note: this function doesn't ignore leading comments unlike isNextLineEmpty
14475 * @param {string} text
14477 * @param {(node: N) => number} locStart
14481 function isPreviousLineEmpty(text, node, locStart) {
14482 /** @type {number | false} */
14483 let idx = locStart(node) - 1;
14484 idx = skipSpaces(text, idx, {
14487 idx = skipNewline(text, idx, {
14490 idx = skipSpaces(text, idx, {
14493 const idx2 = skipNewline(text, idx, {
14496 return idx !== idx2;
14499 * @param {string} text
14500 * @param {number} index
14501 * @returns {boolean}
14505 function isNextLineEmptyAfterIndex(text, index) {
14506 /** @type {number | false} */
14508 /** @type {number | false} */
14512 while (idx !== oldIdx) {
14513 // We need to skip all the potential trailing inline comments
14515 idx = skipToLineEnd(text, idx);
14516 idx = skipInlineComment(text, idx);
14517 idx = skipSpaces(text, idx);
14520 idx = skipTrailingComment(text, idx);
14521 idx = skipNewline(text, idx);
14522 return idx !== false && hasNewline(text, idx);
14526 * @param {string} text
14528 * @param {(node: N) => number} locEnd
14529 * @returns {boolean}
14533 function isNextLineEmpty(text, node, locEnd) {
14534 return isNextLineEmptyAfterIndex(text, locEnd(node));
14537 * @param {string} text
14538 * @param {number} idx
14539 * @returns {number | false}
14543 function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) {
14544 /** @type {number | false} */
14546 /** @type {number | false} */
14550 while (nextIdx !== oldIdx) {
14552 nextIdx = skipSpaces(text, nextIdx);
14553 nextIdx = skipInlineComment(text, nextIdx);
14554 nextIdx = skipTrailingComment(text, nextIdx);
14555 nextIdx = skipNewline(text, nextIdx);
14562 * @param {string} text
14564 * @param {(node: N) => number} locEnd
14565 * @returns {number | false}
14569 function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) {
14570 return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node));
14574 * @param {string} text
14576 * @param {(node: N) => number} locEnd
14577 * @returns {string}
14581 function getNextNonSpaceNonCommentCharacter(text, node, locEnd) {
14582 return text.charAt( // @ts-ignore => TBD: can return false, should we define a fallback?
14583 getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd));
14586 * @param {string} text
14587 * @param {number} index
14588 * @param {SkipOptions=} opts
14589 * @returns {boolean}
14593 function hasSpaces(text, index, opts) {
14595 const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts);
14596 return idx !== index;
14599 * @param {{range?: [number, number], start?: number}} node
14600 * @param {number} index
14604 function setLocStart(node, index) {
14606 node.range[0] = index;
14608 node.start = index;
14612 * @param {{range?: [number, number], end?: number}} node
14613 * @param {number} index
14617 function setLocEnd(node, index) {
14619 node.range[1] = index;
14625 const PRECEDENCE = {};
14626 [["|>"], ["??"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach((tier, i) => {
14627 tier.forEach(op => {
14628 PRECEDENCE[op] = i;
14632 function getPrecedence(op) {
14633 return PRECEDENCE[op];
14636 const equalityOperators = {
14642 const multiplicativeOperators = {
14647 const bitshiftOperators = {
14653 function shouldFlatten(parentOp, nodeOp) {
14654 if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) {
14656 } // ** is right-associative
14657 // x ** y ** z --> x ** (y ** z)
14660 if (parentOp === "**") {
14662 } // x == y == z --> (x == y) == z
14665 if (equalityOperators[parentOp] && equalityOperators[nodeOp]) {
14667 } // x * y % z --> (x * y) % z
14670 if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) {
14672 } // x * y / z --> (x * y) / z
14673 // x / y * z --> (x / y) * z
14676 if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) {
14678 } // x << y << z --> (x << y) << z
14681 if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) {
14688 function isBitwiseOperator(operator) {
14689 return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&";
14690 } // Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr
14691 // holds) `function`, `class`, or `do {}`. Will be overzealous if there's
14692 // already necessary grouping parentheses.
14695 function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) {
14696 node = getLeftMost(node);
14698 switch (node.type) {
14699 case "FunctionExpression":
14700 case "ClassExpression":
14701 case "DoExpression":
14702 return forbidFunctionClassAndDoExpr;
14704 case "ObjectExpression":
14707 case "MemberExpression":
14708 case "OptionalMemberExpression":
14709 return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
14711 case "TaggedTemplateExpression":
14712 if (node.tag.type === "FunctionExpression") {
14713 // IIFEs are always already parenthesized
14717 return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr);
14719 case "CallExpression":
14720 case "OptionalCallExpression":
14721 if (node.callee.type === "FunctionExpression") {
14722 // IIFEs are always already parenthesized
14726 return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr);
14728 case "ConditionalExpression":
14729 return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr);
14731 case "UpdateExpression":
14732 return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr);
14734 case "BindExpression":
14735 return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr);
14737 case "SequenceExpression":
14738 return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr);
14740 case "TSAsExpression":
14741 return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr);
14748 function getLeftMost(node) {
14750 return getLeftMost(node.left);
14756 * @param {string} value
14757 * @param {number} tabWidth
14758 * @param {number=} startIndex
14759 * @returns {number}
14763 function getAlignmentSize(value, tabWidth, startIndex) {
14764 startIndex = startIndex || 0;
14767 for (let i = startIndex; i < value.length; ++i) {
14768 if (value[i] === "\t") {
14769 // Tabs behave in a way that they are aligned to the nearest
14770 // multiple of tabWidth:
14771 // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4
14772 // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ...
14773 size = size + tabWidth - size % tabWidth;
14782 * @param {string} value
14783 * @param {number} tabWidth
14784 * @returns {number}
14788 function getIndentSize(value, tabWidth) {
14789 const lastNewlineIndex = value.lastIndexOf("\n");
14791 if (lastNewlineIndex === -1) {
14795 return getAlignmentSize( // All the leading whitespaces
14796 value.slice(lastNewlineIndex + 1).match(/^[ \t]*/)[0], tabWidth);
14799 * @typedef {'"' | "'"} Quote
14804 * @param {string} raw
14805 * @param {Quote} preferredQuote
14810 function getPreferredQuote(raw, preferredQuote) {
14811 // `rawContent` is the string exactly like it appeared in the input source
14812 // code, without its enclosing quotes.
14813 const rawContent = raw.slice(1, -1);
14814 /** @type {{ quote: '"', regex: RegExp }} */
14820 /** @type {{ quote: "'", regex: RegExp }} */
14826 const preferred = preferredQuote === "'" ? single : double;
14827 const alternate = preferred === single ? double : single;
14828 let result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing
14829 // the string, we might want to enclose with the alternate quote instead, to
14830 // minimize the number of escaped quotes.
14832 if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) {
14833 const numPreferredQuotes = (rawContent.match(preferred.regex) || []).length;
14834 const numAlternateQuotes = (rawContent.match(alternate.regex) || []).length;
14835 result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote;
14841 function printString(raw, options, isDirectiveLiteral) {
14842 // `rawContent` is the string exactly like it appeared in the input source
14843 // code, without its enclosing quotes.
14844 const rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap
14845 // the quotes on a DirectiveLiteral.
14847 const canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'");
14848 /** @type {Quote} */
14850 const enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't
14851 // change the escape sequences they use.
14852 // See https://github.com/prettier/prettier/issues/1555
14853 // and https://tc39.github.io/ecma262/#directive-prologue
14855 if (isDirectiveLiteral) {
14856 if (canChangeDirectiveQuotes) {
14857 return enclosingQuote + rawContent + enclosingQuote;
14861 } // It might sound unnecessary to use `makeString` even if the string already
14862 // is enclosed with `enclosingQuote`, but it isn't. The string could contain
14863 // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes
14864 // sure that we consistently output the minimum amount of escaped quotes.
14867 return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.embeddedInHtml));
14870 * @param {string} rawContent
14871 * @param {Quote} enclosingQuote
14872 * @param {boolean=} unescapeUnnecessaryEscapes
14873 * @returns {string}
14877 function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) {
14878 const otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double).
14880 const regex = /\\([\s\S])|(['"])/g; // Escape and unescape single and double quotes as needed to be able to
14881 // enclose `rawContent` with `enclosingQuote`.
14883 const newContent = rawContent.replace(regex, (match, escaped, quote) => {
14884 // If we matched an escape, and the escaped character is a quote of the
14885 // other type than we intend to enclose the string with, there's no need for
14886 // it to be escaped, so return it _without_ the backslash.
14887 if (escaped === otherQuote) {
14889 } // If we matched an unescaped quote and it is of the _same_ type as we
14890 // intend to enclose the string with, it must be escaped, so return it with
14894 if (quote === enclosingQuote) {
14895 return "\\" + quote;
14900 } // Unescape any unnecessarily escaped character.
14901 // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27
14904 return unescapeUnnecessaryEscapes && /^[^\\nrvtbfux\r\n\u2028\u2029"'0-7]$/.test(escaped) ? escaped : "\\" + escaped;
14906 return enclosingQuote + newContent + enclosingQuote;
14909 function printNumber(rawNumber) {
14910 return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation.
14911 .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0).
14912 .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit.
14913 .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes.
14914 .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot.
14915 .replace(/\.(?=e|$)/, "");
14918 * @param {string} str
14919 * @param {string} target
14920 * @returns {number}
14924 function getMaxContinuousCount(str, target) {
14925 const results = str.match(new RegExp("(".concat(escapeStringRegexp$2(target), ")+"), "g"));
14927 if (results === null) {
14931 return results.reduce((maxCount, result) => Math.max(maxCount, result.length / target.length), 0);
14934 function getMinNotPresentContinuousCount(str, target) {
14935 const matches = str.match(new RegExp("(".concat(escapeStringRegexp$2(target), ")+"), "g"));
14937 if (matches === null) {
14941 const countPresent = new Map();
14944 for (const match of matches) {
14945 const count = match.length / target.length;
14946 countPresent.set(count, true);
14953 for (let i = 1; i < max; i++) {
14954 if (!countPresent.get(i)) {
14962 * @param {string} text
14963 * @returns {number}
14967 function getStringWidth(text) {
14970 } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width`
14973 if (!notAsciiRegex.test(text)) {
14974 return text.length;
14977 return stringWidth_1(text);
14980 function hasIgnoreComment(path) {
14981 const node = path.getValue();
14982 return hasNodeIgnoreComment(node);
14985 function hasNodeIgnoreComment(node) {
14986 return node && (node.comments && node.comments.length > 0 && node.comments.some(comment => isNodeIgnoreComment(comment) && !comment.unignore) || node.prettierIgnore);
14989 function isNodeIgnoreComment(comment) {
14990 return comment.value.trim() === "prettier-ignore";
14993 function addCommentHelper(node, comment) {
14994 const comments = node.comments || (node.comments = []);
14995 comments.push(comment);
14996 comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment
14997 // We already "print" it via the raw text, we don't need to re-print it as a
15000 if (node.type === "JSXText") {
15001 comment.printed = true;
15005 function addLeadingComment(node, comment) {
15006 comment.leading = true;
15007 comment.trailing = false;
15008 addCommentHelper(node, comment);
15011 function addDanglingComment(node, comment) {
15012 comment.leading = false;
15013 comment.trailing = false;
15014 addCommentHelper(node, comment);
15017 function addTrailingComment(node, comment) {
15018 comment.leading = false;
15019 comment.trailing = true;
15020 addCommentHelper(node, comment);
15023 function isWithinParentArrayProperty(path, propertyName) {
15024 const node = path.getValue();
15025 const parent = path.getParentNode();
15027 if (parent == null) {
15031 if (!Array.isArray(parent[propertyName])) {
15035 const key = path.getName();
15036 return parent[propertyName][key] === node;
15039 function replaceEndOfLineWith(text, replacement) {
15042 for (const part of text.split("\n")) {
15043 if (parts.length !== 0) {
15044 parts.push(replacement);
15054 replaceEndOfLineWith,
15056 getMaxContinuousCount,
15057 getMinNotPresentContinuousCount,
15063 getNextNonSpaceNonCommentCharacterIndexWithStartIndex,
15064 getNextNonSpaceNonCommentCharacterIndex,
15065 getNextNonSpaceNonCommentCharacter,
15070 skipEverythingButNewLine,
15072 skipTrailingComment,
15074 isNextLineEmptyAfterIndex,
15076 isPreviousLineEmpty,
15082 startsWithNoLookaheadToken,
15089 hasNodeIgnoreComment,
15090 isNodeIgnoreComment,
15093 addDanglingComment,
15094 addTrailingComment,
15095 isWithinParentArrayProperty
15098 function guessEndOfLine(text) {
15099 const index = text.indexOf("\r");
15102 return text.charAt(index + 1) === "\n" ? "crlf" : "cr";
15108 function convertEndOfLineToChars(value) {
15123 convertEndOfLineToChars
15127 getStringWidth: getStringWidth$1
15130 convertEndOfLineToChars: convertEndOfLineToChars$1
15137 /** @type {Record<symbol, typeof MODE_BREAK | typeof MODE_FLAT>} */
15140 const MODE_BREAK = 1;
15141 const MODE_FLAT = 2;
15143 function rootIndent() {
15151 function makeIndent(ind, options) {
15152 return generateInd(ind, {
15157 function makeAlign(ind, n, options) {
15158 return n === -Infinity ? ind.root || rootIndent() : n < 0 ? generateInd(ind, {
15160 }, options) : !n ? ind : n.type === "root" ? Object.assign({}, ind, {
15162 }) : typeof n === "string" ? generateInd(ind, {
15163 type: "stringAlign",
15165 }, options) : generateInd(ind, {
15166 type: "numberAlign",
15171 function generateInd(ind, newPart, options) {
15172 const queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart);
15176 let lastSpaces = 0;
15178 for (const part of queue) {
15179 switch (part.type) {
15183 if (options.useTabs) {
15186 addSpaces(options.tabWidth);
15191 case "stringAlign":
15194 length += part.n.length;
15197 case "numberAlign":
15199 lastSpaces += part.n;
15202 /* istanbul ignore next */
15205 throw new Error("Unexpected type '".concat(part.type, "'"));
15210 return Object.assign({}, ind, {
15216 function addTabs(count) {
15217 value += "\t".repeat(count);
15218 length += options.tabWidth * count;
15221 function addSpaces(count) {
15222 value += " ".repeat(count);
15227 if (options.useTabs) {
15234 function flushTabs() {
15235 if (lastTabs > 0) {
15242 function flushSpaces() {
15243 if (lastSpaces > 0) {
15244 addSpaces(lastSpaces);
15250 function resetLast() {
15256 function trim$1(out) {
15257 if (out.length === 0) {
15261 let trimCount = 0; // Trim whitespace at the end of line
15263 while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[ \t]*$/)) {
15264 trimCount += out.pop().length;
15267 if (out.length && typeof out[out.length - 1] === "string") {
15268 const trimmed = out[out.length - 1].replace(/[ \t]*$/, "");
15269 trimCount += out[out.length - 1].length - trimmed.length;
15270 out[out.length - 1] = trimmed;
15276 function fits(next, restCommands, width, options, mustBeFlat) {
15277 let restIdx = restCommands.length;
15278 const cmds = [next]; // `out` is only used for width counting because `trim` requires to look
15279 // backwards for space characters.
15283 while (width >= 0) {
15284 if (cmds.length === 0) {
15285 if (restIdx === 0) {
15289 cmds.push(restCommands[restIdx - 1]);
15294 const [ind, mode, doc] = cmds.pop();
15296 if (typeof doc === "string") {
15298 width -= getStringWidth$1(doc);
15300 switch (doc.type) {
15302 for (let i = doc.parts.length - 1; i >= 0; i--) {
15303 cmds.push([ind, mode, doc.parts[i]]);
15309 cmds.push([makeIndent(ind, options), mode, doc.contents]);
15313 cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
15317 width += trim$1(out);
15321 if (mustBeFlat && doc.break) {
15325 cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]);
15328 groupModeMap[doc.id] = cmds[cmds.length - 1][1];
15334 for (let i = doc.parts.length - 1; i >= 0; i--) {
15335 cmds.push([ind, mode, doc.parts[i]]);
15342 const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
15344 if (groupMode === MODE_BREAK) {
15345 if (doc.breakContents) {
15346 cmds.push([ind, mode, doc.breakContents]);
15350 if (groupMode === MODE_FLAT) {
15351 if (doc.flatContents) {
15352 cmds.push([ind, mode, doc.flatContents]);
15386 function printDocToString(doc, options) {
15388 const width = options.printWidth;
15389 const newLine = convertEndOfLineToChars$1(options.endOfLine);
15390 let pos = 0; // cmds is basically a stack. We've turned a recursive call into a
15391 // while loop which is much faster. The while loop below adds new
15392 // cmds to the array instead of recursively calling `print`.
15394 const cmds = [[rootIndent(), MODE_BREAK, doc]];
15396 let shouldRemeasure = false;
15397 let lineSuffix = [];
15399 while (cmds.length !== 0) {
15400 const [ind, mode, doc] = cmds.pop();
15402 if (typeof doc === "string") {
15403 const formatted = newLine !== "\n" && doc.includes("\n") ? doc.replace(/\n/g, newLine) : doc;
15404 out.push(formatted);
15405 pos += getStringWidth$1(formatted);
15407 switch (doc.type) {
15409 out.push(cursor$1.placeholder);
15413 for (let i = doc.parts.length - 1; i >= 0; i--) {
15414 cmds.push([ind, mode, doc.parts[i]]);
15420 cmds.push([makeIndent(ind, options), mode, doc.contents]);
15424 cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]);
15428 pos -= trim$1(out);
15434 if (!shouldRemeasure) {
15435 cmds.push([ind, doc.break ? MODE_BREAK : MODE_FLAT, doc.contents]);
15443 shouldRemeasure = false;
15444 const next = [ind, MODE_FLAT, doc.contents];
15445 const rem = width - pos;
15447 if (!doc.break && fits(next, cmds, rem, options)) {
15450 // Expanded states are a rare case where a document
15451 // can manually provide multiple representations of
15452 // itself. It provides an array of documents
15453 // going from the least expanded (most flattened)
15454 // representation first to the most expanded. If a
15455 // group has these, we need to manually go through
15456 // these states and find the first one that fits.
15457 if (doc.expandedStates) {
15458 const mostExpanded = doc.expandedStates[doc.expandedStates.length - 1];
15461 cmds.push([ind, MODE_BREAK, mostExpanded]);
15464 for (let i = 1; i < doc.expandedStates.length + 1; i++) {
15465 if (i >= doc.expandedStates.length) {
15466 cmds.push([ind, MODE_BREAK, mostExpanded]);
15469 const state = doc.expandedStates[i];
15470 const cmd = [ind, MODE_FLAT, state];
15472 if (fits(cmd, cmds, rem, options)) {
15480 cmds.push([ind, MODE_BREAK, doc.contents]);
15489 groupModeMap[doc.id] = cmds[cmds.length - 1][1];
15493 // Fills each line with as much code as possible before moving to a new
15494 // line with the same indentation.
15496 // Expects doc.parts to be an array of alternating content and
15497 // whitespace. The whitespace contains the linebreaks.
15500 // ["I", line, "love", line, "monkeys"]
15502 // [{ type: group, ... }, softline, { type: group, ... }]
15504 // It uses this parts structure to handle three main layout cases:
15505 // * The first two content items fit on the same line without
15507 // -> output the first content item and the whitespace "flat".
15508 // * Only the first content item fits on the line without breaking
15509 // -> output the first content item "flat" and the whitespace with
15511 // * Neither content item fits on the line without breaking
15512 // -> output the first content item and the whitespace with "break".
15516 const rem = width - pos;
15521 if (parts.length === 0) {
15525 const [content, whitespace] = parts;
15526 const contentFlatCmd = [ind, MODE_FLAT, content];
15527 const contentBreakCmd = [ind, MODE_BREAK, content];
15528 const contentFits = fits(contentFlatCmd, [], rem, options, true);
15530 if (parts.length === 1) {
15532 cmds.push(contentFlatCmd);
15534 cmds.push(contentBreakCmd);
15540 const whitespaceFlatCmd = [ind, MODE_FLAT, whitespace];
15541 const whitespaceBreakCmd = [ind, MODE_BREAK, whitespace];
15543 if (parts.length === 2) {
15545 cmds.push(whitespaceFlatCmd);
15546 cmds.push(contentFlatCmd);
15548 cmds.push(whitespaceBreakCmd);
15549 cmds.push(contentBreakCmd);
15553 } // At this point we've handled the first pair (context, separator)
15554 // and will create a new fill doc for the rest of the content.
15555 // Ideally we wouldn't mutate the array here but copying all the
15556 // elements to a new array would make this algorithm quadratic,
15557 // which is unusable for large arrays (e.g. large texts in JSX).
15560 parts.splice(0, 2);
15561 const remainingCmd = [ind, mode, fill$1(parts)];
15562 const secondContent = parts[0];
15563 const firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$1([content, whitespace, secondContent])];
15564 const firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], rem, options, true);
15566 if (firstAndSecondContentFits) {
15567 cmds.push(remainingCmd);
15568 cmds.push(whitespaceFlatCmd);
15569 cmds.push(contentFlatCmd);
15570 } else if (contentFits) {
15571 cmds.push(remainingCmd);
15572 cmds.push(whitespaceBreakCmd);
15573 cmds.push(contentFlatCmd);
15575 cmds.push(remainingCmd);
15576 cmds.push(whitespaceBreakCmd);
15577 cmds.push(contentBreakCmd);
15585 const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode;
15587 if (groupMode === MODE_BREAK) {
15588 if (doc.breakContents) {
15589 cmds.push([ind, mode, doc.breakContents]);
15593 if (groupMode === MODE_FLAT) {
15594 if (doc.flatContents) {
15595 cmds.push([ind, mode, doc.flatContents]);
15602 case "line-suffix":
15603 lineSuffix.push([ind, mode, doc.contents]);
15606 case "line-suffix-boundary":
15607 if (lineSuffix.length > 0) {
15608 cmds.push([ind, mode, {
15627 // This line was forced into the output even if we
15628 // were in flattened mode, so we need to tell the next
15629 // group that no matter what, it needs to remeasure
15630 // because the previous measurement didn't accurately
15631 // capture the entire expression (this is necessary
15632 // for nested groups)
15633 shouldRemeasure = true;
15639 if (lineSuffix.length) {
15640 cmds.push([ind, mode, doc]);
15641 cmds.push(...lineSuffix.reverse());
15648 out.push(newLine, ind.root.value);
15649 pos = ind.root.length;
15655 pos -= trim$1(out);
15656 out.push(newLine + ind.value);
15668 const cursorPlaceholderIndex = out.indexOf(cursor$1.placeholder);
15670 if (cursorPlaceholderIndex !== -1) {
15671 const otherCursorPlaceholderIndex = out.indexOf(cursor$1.placeholder, cursorPlaceholderIndex + 1);
15672 const beforeCursor = out.slice(0, cursorPlaceholderIndex).join("");
15673 const aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join("");
15674 const afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join("");
15676 formatted: beforeCursor + aroundCursor + afterCursor,
15677 cursorNodeStart: beforeCursor.length,
15678 cursorNodeText: aroundCursor
15683 formatted: out.join("")
15691 const traverseDocOnExitStackMarker = {};
15693 function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) {
15694 const docsStack = [doc];
15696 while (docsStack.length !== 0) {
15697 const doc = docsStack.pop();
15699 if (doc === traverseDocOnExitStackMarker) {
15700 onExit(docsStack.pop());
15704 let shouldRecurse = true;
15707 if (onEnter(doc) === false) {
15708 shouldRecurse = false;
15713 docsStack.push(doc);
15714 docsStack.push(traverseDocOnExitStackMarker);
15717 if (shouldRecurse) {
15718 // When there are multiple parts to process,
15719 // the parts need to be pushed onto the stack in reverse order,
15720 // so that they are processed in the original order
15721 // when the stack is popped.
15722 if (doc.type === "concat" || doc.type === "fill") {
15723 for (let ic = doc.parts.length, i = ic - 1; i >= 0; --i) {
15724 docsStack.push(doc.parts[i]);
15726 } else if (doc.type === "if-break") {
15727 if (doc.flatContents) {
15728 docsStack.push(doc.flatContents);
15731 if (doc.breakContents) {
15732 docsStack.push(doc.breakContents);
15734 } else if (doc.type === "group" && doc.expandedStates) {
15735 if (shouldTraverseConditionalGroups) {
15736 for (let ic = doc.expandedStates.length, i = ic - 1; i >= 0; --i) {
15737 docsStack.push(doc.expandedStates[i]);
15740 docsStack.push(doc.contents);
15742 } else if (doc.contents) {
15743 docsStack.push(doc.contents);
15749 function mapDoc(doc, cb) {
15750 if (doc.type === "concat" || doc.type === "fill") {
15751 const parts = doc.parts.map(part => mapDoc(part, cb));
15752 return cb(Object.assign({}, doc, {
15755 } else if (doc.type === "if-break") {
15756 const breakContents = doc.breakContents && mapDoc(doc.breakContents, cb);
15757 const flatContents = doc.flatContents && mapDoc(doc.flatContents, cb);
15758 return cb(Object.assign({}, doc, {
15762 } else if (doc.contents) {
15763 const contents = mapDoc(doc.contents, cb);
15764 return cb(Object.assign({}, doc, {
15772 function findInDoc(doc, fn, defaultValue) {
15773 let result = defaultValue;
15774 let hasStopped = false;
15776 function findInDocOnEnterFn(doc) {
15777 const maybeResult = fn(doc);
15779 if (maybeResult !== undefined) {
15781 result = maybeResult;
15789 traverseDoc(doc, findInDocOnEnterFn);
15793 function isEmpty(n) {
15794 return typeof n === "string" && n.length === 0;
15797 function isLineNextFn(doc) {
15798 if (typeof doc === "string") {
15802 if (doc.type === "line") {
15807 function isLineNext(doc) {
15808 return findInDoc(doc, isLineNextFn, false);
15811 function willBreakFn(doc) {
15812 if (doc.type === "group" && doc.break) {
15816 if (doc.type === "line" && doc.hard) {
15820 if (doc.type === "break-parent") {
15825 function willBreak(doc) {
15826 return findInDoc(doc, willBreakFn, false);
15829 function breakParentGroup(groupStack) {
15830 if (groupStack.length > 0) {
15831 const parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because
15832 // the user is expected to manually handle what breaks.
15834 if (!parentGroup.expandedStates) {
15835 parentGroup.break = true;
15842 function propagateBreaks(doc) {
15843 const alreadyVisitedSet = new Set();
15844 const groupStack = [];
15846 function propagateBreaksOnEnterFn(doc) {
15847 if (doc.type === "break-parent") {
15848 breakParentGroup(groupStack);
15851 if (doc.type === "group") {
15852 groupStack.push(doc);
15854 if (alreadyVisitedSet.has(doc)) {
15858 alreadyVisitedSet.add(doc);
15862 function propagateBreaksOnExitFn(doc) {
15863 if (doc.type === "group") {
15864 const group = groupStack.pop();
15867 breakParentGroup(groupStack);
15872 traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn,
15873 /* shouldTraverseConditionalGroups */
15877 function removeLinesFn(doc) {
15878 // Force this doc into flat mode by statically converting all
15879 // lines into spaces (or soft lines into nothing). Hard lines
15880 // should still output because there's too great of a chance
15881 // of breaking existing assumptions otherwise.
15882 if (doc.type === "line" && !doc.hard) {
15883 return doc.soft ? "" : " ";
15884 } else if (doc.type === "if-break") {
15885 return doc.flatContents || "";
15891 function removeLines(doc) {
15892 return mapDoc(doc, removeLinesFn);
15895 function stripTrailingHardline(doc) {
15896 // HACK remove ending hardline, original PR: #1984
15897 if (doc.type === "concat" && doc.parts.length !== 0) {
15898 const lastPart = doc.parts[doc.parts.length - 1];
15900 if (lastPart.type === "concat") {
15901 if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") {
15904 parts: doc.parts.slice(0, -1)
15910 parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart))
15927 stripTrailingHardline
15930 function flattenDoc(doc) {
15931 if (doc.type === "concat") {
15934 for (let i = 0; i < doc.parts.length; ++i) {
15935 const doc2 = doc.parts[i];
15937 if (typeof doc2 !== "string" && doc2.type === "concat") {
15938 res.push(...flattenDoc(doc2).parts);
15940 const flattened = flattenDoc(doc2);
15942 if (flattened !== "") {
15943 res.push(flattened);
15948 return Object.assign({}, doc, {
15951 } else if (doc.type === "if-break") {
15952 return Object.assign({}, doc, {
15953 breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null,
15954 flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null
15956 } else if (doc.type === "group") {
15957 return Object.assign({}, doc, {
15958 contents: flattenDoc(doc.contents),
15959 expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates
15961 } else if (doc.contents) {
15962 return Object.assign({}, doc, {
15963 contents: flattenDoc(doc.contents)
15970 function printDoc(doc) {
15971 if (typeof doc === "string") {
15972 return JSON.stringify(doc);
15975 if (doc.type === "line") {
15977 return "literalline";
15991 if (doc.type === "break-parent") {
15992 return "breakParent";
15995 if (doc.type === "trim") {
15999 if (doc.type === "concat") {
16000 return "[" + doc.parts.map(printDoc).join(", ") + "]";
16003 if (doc.type === "indent") {
16004 return "indent(" + printDoc(doc.contents) + ")";
16007 if (doc.type === "align") {
16008 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) + ")";
16011 if (doc.type === "if-break") {
16012 return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")";
16015 if (doc.type === "group") {
16016 if (doc.expandedStates) {
16017 return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])";
16020 return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")";
16023 if (doc.type === "fill") {
16024 return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")";
16027 if (doc.type === "line-suffix") {
16028 return "lineSuffix(" + printDoc(doc.contents) + ")";
16031 if (doc.type === "line-suffix-boundary") {
16032 return "lineSuffixBoundary";
16035 throw new Error("Unknown doc type " + doc.type);
16039 printDocToDebug(doc) {
16040 return printDoc(flattenDoc(doc));
16046 builders: docBuilders,
16047 printer: docPrinter,
16053 getMaxContinuousCount: getMaxContinuousCount$1,
16054 getStringWidth: getStringWidth$2,
16055 getAlignmentSize: getAlignmentSize$1,
16056 getIndentSize: getIndentSize$1,
16058 skipWhitespace: skipWhitespace$1,
16059 skipSpaces: skipSpaces$1,
16060 skipNewline: skipNewline$1,
16061 skipToLineEnd: skipToLineEnd$1,
16062 skipEverythingButNewLine: skipEverythingButNewLine$1,
16063 skipInlineComment: skipInlineComment$1,
16064 skipTrailingComment: skipTrailingComment$1,
16065 hasNewline: hasNewline$1,
16066 hasNewlineInRange: hasNewlineInRange$1,
16067 hasSpaces: hasSpaces$1,
16068 isNextLineEmpty: isNextLineEmpty$1,
16069 isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1,
16070 isPreviousLineEmpty: isPreviousLineEmpty$1,
16071 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1,
16072 makeString: makeString$1,
16073 addLeadingComment: addLeadingComment$1,
16074 addDanglingComment: addDanglingComment$1,
16075 addTrailingComment: addTrailingComment$1
16078 getMaxContinuousCount: getMaxContinuousCount$1,
16079 getStringWidth: getStringWidth$2,
16080 getAlignmentSize: getAlignmentSize$1,
16081 getIndentSize: getIndentSize$1,
16083 skipWhitespace: skipWhitespace$1,
16084 skipSpaces: skipSpaces$1,
16085 skipNewline: skipNewline$1,
16086 skipToLineEnd: skipToLineEnd$1,
16087 skipEverythingButNewLine: skipEverythingButNewLine$1,
16088 skipInlineComment: skipInlineComment$1,
16089 skipTrailingComment: skipTrailingComment$1,
16090 hasNewline: hasNewline$1,
16091 hasNewlineInRange: hasNewlineInRange$1,
16092 hasSpaces: hasSpaces$1,
16093 isNextLineEmpty: isNextLineEmpty$1,
16094 isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1,
16095 isPreviousLineEmpty: isPreviousLineEmpty$1,
16096 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1,
16097 makeString: makeString$1,
16098 addLeadingComment: addLeadingComment$1,
16099 addDanglingComment: addDanglingComment$1,
16100 addTrailingComment: addTrailingComment$1
16106 hardline: hardline$1,
16107 breakParent: breakParent$1,
16109 lineSuffix: lineSuffix$1,
16112 } = document.builders;
16114 hasNewline: hasNewline$2,
16115 skipNewline: skipNewline$2,
16116 isPreviousLineEmpty: isPreviousLineEmpty$2
16119 addLeadingComment: addLeadingComment$2,
16120 addDanglingComment: addDanglingComment$2,
16121 addTrailingComment: addTrailingComment$2
16123 const childNodesCacheKey = Symbol("child-nodes");
16125 function getSortedChildNodes(node, options, resultArray) {
16137 if (printer.canAttachComment && printer.canAttachComment(node)) {
16138 // This reverse insertion sort almost always takes constant
16139 // time because we almost always (maybe always?) append the
16140 // nodes in order anyway.
16143 for (i = resultArray.length - 1; i >= 0; --i) {
16144 if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) {
16149 resultArray.splice(i + 1, 0, node);
16152 } else if (node[childNodesCacheKey]) {
16153 return node[childNodesCacheKey];
16156 const childNodes = printer.getCommentChildNodes && printer.getCommentChildNodes(node, options) || typeof node === "object" && Object.keys(node).filter(n => n !== "enclosingNode" && n !== "precedingNode" && n !== "followingNode").map(n => node[n]);
16162 if (!resultArray) {
16163 Object.defineProperty(node, childNodesCacheKey, {
16164 value: resultArray = [],
16169 childNodes.forEach(childNode => {
16170 getSortedChildNodes(childNode, options, resultArray);
16172 return resultArray;
16173 } // As efficiently as possible, decorate the comment object with
16174 // .precedingNode, .enclosingNode, and/or .followingNode properties, at
16175 // least one of which is guaranteed to be defined.
16178 function decorateComment(node, comment, options) {
16183 const childNodes = getSortedChildNodes(node, options);
16185 let followingNode; // Time to dust off the old binary search robes and wizard hat.
16188 let right = childNodes.length;
16190 while (left < right) {
16191 const middle = left + right >> 1;
16192 const child = childNodes[middle];
16194 if (locStart(child) - locStart(comment) <= 0 && locEnd(comment) - locEnd(child) <= 0) {
16195 // The comment is completely contained by this child node.
16196 comment.enclosingNode = child;
16197 decorateComment(child, comment, options);
16198 return; // Abandon the binary search at this level.
16201 if (locEnd(child) - locStart(comment) <= 0) {
16202 // This child node falls completely before the comment.
16203 // Because we will never consider this node or any nodes
16204 // before it again, this node must be the closest preceding
16205 // node we have encountered so far.
16206 precedingNode = child;
16211 if (locEnd(comment) - locStart(child) <= 0) {
16212 // This child node falls completely after the comment.
16213 // Because we will never consider this node or any nodes after
16214 // it again, this node must be the closest following node we
16215 // have encountered so far.
16216 followingNode = child;
16220 /* istanbul ignore next */
16223 throw new Error("Comment location overlaps with node location");
16224 } // We don't want comments inside of different expressions inside of the same
16225 // template literal to move to another expression.
16228 if (comment.enclosingNode && comment.enclosingNode.type === "TemplateLiteral") {
16231 } = comment.enclosingNode;
16232 const commentIndex = findExpressionIndexForComment(quasis, comment, options);
16234 if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) {
16235 precedingNode = null;
16238 if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) {
16239 followingNode = null;
16243 if (precedingNode) {
16244 comment.precedingNode = precedingNode;
16247 if (followingNode) {
16248 comment.followingNode = followingNode;
16252 function attach(comments, ast, text, options) {
16253 if (!Array.isArray(comments)) {
16257 const tiesToBreak = [];
16262 comments.forEach((comment, i) => {
16263 if (options.parser === "json" || options.parser === "json5" || options.parser === "__js_expression" || options.parser === "__vue_expression") {
16264 if (locStart(comment) - locStart(ast) <= 0) {
16265 addLeadingComment$2(ast, comment);
16269 if (locEnd(comment) - locEnd(ast) >= 0) {
16270 addTrailingComment$2(ast, comment);
16275 decorateComment(ast, comment, options);
16281 const pluginHandleOwnLineComment = options.printer.handleComments && options.printer.handleComments.ownLine ? options.printer.handleComments.ownLine : () => false;
16282 const pluginHandleEndOfLineComment = options.printer.handleComments && options.printer.handleComments.endOfLine ? options.printer.handleComments.endOfLine : () => false;
16283 const pluginHandleRemainingComment = options.printer.handleComments && options.printer.handleComments.remaining ? options.printer.handleComments.remaining : () => false;
16284 const isLastComment = comments.length - 1 === i;
16286 if (hasNewline$2(text, locStart(comment), {
16289 // If a comment exists on its own line, prefer a leading comment.
16290 // We also need to check if it's the first line of the file.
16291 if (pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)) ; else if (followingNode) {
16292 // Always a leading comment.
16293 addLeadingComment$2(followingNode, comment);
16294 } else if (precedingNode) {
16295 addTrailingComment$2(precedingNode, comment);
16296 } else if (enclosingNode) {
16297 addDanglingComment$2(enclosingNode, comment);
16299 // There are no nodes, let's attach it to the root of the ast
16301 /* istanbul ignore next */
16302 addDanglingComment$2(ast, comment);
16304 } else if (hasNewline$2(text, locEnd(comment))) {
16305 if (pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode) {
16306 // There is content before this comment on the same line, but
16307 // none after it, so prefer a trailing comment of the previous node.
16308 addTrailingComment$2(precedingNode, comment);
16309 } else if (followingNode) {
16310 addLeadingComment$2(followingNode, comment);
16311 } else if (enclosingNode) {
16312 addDanglingComment$2(enclosingNode, comment);
16314 // There are no nodes, let's attach it to the root of the ast
16316 /* istanbul ignore next */
16317 addDanglingComment$2(ast, comment);
16320 if (pluginHandleRemainingComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode && followingNode) {
16321 // Otherwise, text exists both before and after the comment on
16322 // the same line. If there is both a preceding and following
16323 // node, use a tie-breaking algorithm to determine if it should
16324 // be attached to the next or previous node. In the last case,
16325 // simply attach the right node;
16326 const tieCount = tiesToBreak.length;
16328 if (tieCount > 0) {
16329 const lastTie = tiesToBreak[tieCount - 1];
16331 if (lastTie.followingNode !== comment.followingNode) {
16332 breakTies(tiesToBreak, text, options);
16336 tiesToBreak.push(comment);
16337 } else if (precedingNode) {
16338 addTrailingComment$2(precedingNode, comment);
16339 } else if (followingNode) {
16340 addLeadingComment$2(followingNode, comment);
16341 } else if (enclosingNode) {
16342 addDanglingComment$2(enclosingNode, comment);
16344 // There are no nodes, let's attach it to the root of the ast
16346 /* istanbul ignore next */
16347 addDanglingComment$2(ast, comment);
16351 breakTies(tiesToBreak, text, options);
16352 comments.forEach(comment => {
16353 // These node references were useful for breaking ties, but we
16354 // don't need them anymore, and they create cycles in the AST that
16355 // may lead to infinite recursion if we don't delete them here.
16356 delete comment.precedingNode;
16357 delete comment.enclosingNode;
16358 delete comment.followingNode;
16362 function breakTies(tiesToBreak, text, options) {
16363 const tieCount = tiesToBreak.length;
16365 if (tieCount === 0) {
16373 } = tiesToBreak[0];
16374 const gapRegExp = options.printer.getGapRegex && options.printer.getGapRegex(enclosingNode) || /^[\s(]*$/;
16375 let gapEndPos = options.locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps
16376 // between the tied comments. In order to qualify as leading, a
16377 // comment must be separated from followingNode by an unbroken series of
16378 // gaps (or other comments). Gaps should only contain whitespace or open
16381 let indexOfFirstLeadingComment;
16383 for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) {
16384 const comment = tiesToBreak[indexOfFirstLeadingComment - 1];
16385 assert.strictEqual(comment.precedingNode, precedingNode);
16386 assert.strictEqual(comment.followingNode, followingNode);
16387 const gap = text.slice(options.locEnd(comment), gapEndPos);
16389 if (gapRegExp.test(gap)) {
16390 gapEndPos = options.locStart(comment);
16392 // The gap string contained something other than whitespace or open
16398 tiesToBreak.forEach((comment, i) => {
16399 if (i < indexOfFirstLeadingComment) {
16400 addTrailingComment$2(precedingNode, comment);
16402 addLeadingComment$2(followingNode, comment);
16405 tiesToBreak.length = 0;
16408 function printComment(commentPath, options) {
16409 const comment = commentPath.getValue();
16410 comment.printed = true;
16411 return options.printer.printComment(commentPath, options);
16414 function findExpressionIndexForComment(quasis, comment, options) {
16415 const startPos = options.locStart(comment) - 1;
16417 for (let i = 1; i < quasis.length; ++i) {
16418 if (startPos < getQuasiRange(quasis[i]).start) {
16421 } // We haven't found it, it probably means that some of the locations are off.
16422 // Let's just return the first one.
16424 /* istanbul ignore next */
16430 function getQuasiRange(expr) {
16431 if (expr.start !== undefined) {
16441 start: expr.range[0],
16446 function printLeadingComment(commentPath, print, options) {
16447 const comment = commentPath.getValue();
16448 const contents = printComment(commentPath, options);
16454 const isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // Leading block comments should see if they need to stay on the
16455 // same line or not.
16458 const lineBreak = hasNewline$2(options.originalText, options.locEnd(comment)) ? hasNewline$2(options.originalText, options.locStart(comment), {
16460 }) ? hardline$1 : line$1 : " ";
16461 return concat$2([contents, lineBreak]);
16464 return concat$2([contents, hardline$1]);
16467 function printTrailingComment(commentPath, print, options) {
16468 const comment = commentPath.getValue();
16469 const contents = printComment(commentPath, options);
16475 const isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // We don't want the line to break
16476 // when the parentParentNode is a ClassDeclaration/-Expression
16477 // And the parentNode is in the superClass property
16479 const parentNode = commentPath.getNode(1);
16480 const parentParentNode = commentPath.getNode(2);
16481 const isParentSuperClass = parentParentNode && (parentParentNode.type === "ClassDeclaration" || parentParentNode.type === "ClassExpression") && parentParentNode.superClass === parentNode;
16483 if (hasNewline$2(options.originalText, options.locStart(comment), {
16486 // This allows comments at the end of nested structures:
16492 // Those kinds of comments are almost always leading comments, but
16493 // here it doesn't go "outside" the block and turns it into a
16494 // trailing comment for `2`. We can simulate the above by checking
16495 // if this a comment on its own line; normal trailing comments are
16496 // always at the end of another expression.
16497 const isLineBeforeEmpty = isPreviousLineEmpty$2(options.originalText, comment, options.locStart);
16498 return lineSuffix$1(concat$2([hardline$1, isLineBeforeEmpty ? hardline$1 : "", contents]));
16499 } else if (isBlock || isParentSuperClass) {
16500 // Trailing block comments never need a newline
16501 return concat$2([" ", contents]);
16504 return concat$2([lineSuffix$1(concat$2([" ", contents])), !isBlock ? breakParent$1 : ""]);
16507 function printDanglingComments(path, options, sameIndent, filter) {
16509 const node = path.getValue();
16511 if (!node || !node.comments) {
16515 path.each(commentPath => {
16516 const comment = commentPath.getValue();
16518 if (comment && !comment.leading && !comment.trailing && (!filter || filter(comment))) {
16519 parts.push(printComment(commentPath, options));
16523 if (parts.length === 0) {
16528 return join$1(hardline$1, parts);
16531 return indent$1(concat$2([hardline$1, join$1(hardline$1, parts)]));
16534 function prependCursorPlaceholder(path, options, printed) {
16535 if (path.getNode() === options.cursorNode && path.getValue()) {
16536 return concat$2([cursor$2, printed, cursor$2]);
16542 function printComments(path, print, options, needsSemi) {
16543 const value = path.getValue();
16544 const printed = print(path);
16545 const comments = value && value.comments;
16547 if (!comments || comments.length === 0) {
16548 return prependCursorPlaceholder(path, options, printed);
16551 const leadingParts = [];
16552 const trailingParts = [needsSemi ? ";" : "", printed];
16553 path.each(commentPath => {
16554 const comment = commentPath.getValue();
16561 const contents = printLeadingComment(commentPath, print, options);
16567 leadingParts.push(contents);
16568 const text = options.originalText;
16569 const index = skipNewline$2(text, options.locEnd(comment));
16571 if (index !== false && hasNewline$2(text, index)) {
16572 leadingParts.push(hardline$1);
16574 } else if (trailing) {
16575 trailingParts.push(printTrailingComment(commentPath, print, options));
16578 return prependCursorPlaceholder(path, options, concat$2(leadingParts.concat(trailingParts)));
16584 printDanglingComments,
16585 getSortedChildNodes
16588 function getNodeHelper(path, count) {
16589 const stackIndex = getNodeStackIndexHelper(path.stack, count);
16590 return stackIndex === -1 ? null : path.stack[stackIndex];
16593 function getNodeStackIndexHelper(stack, count) {
16594 for (let i = stack.length - 1; i >= 0; i -= 2) {
16595 const value = stack[i];
16597 if (value && !Array.isArray(value) && --count < 0) {
16606 constructor(value) {
16607 this.stack = [value];
16608 } // The name of the current property is always the penultimate element of
16609 // this.stack, and always a String.
16621 return stack[length - 2];
16622 } // Since the name is always a string, null is a safe sentinel value to
16623 // return if we do not know the name of the (root) value.
16625 /* istanbul ignore next */
16629 } // The value of the current property is always the final element of
16634 return getLast(this.stack);
16637 getNode(count = 0) {
16638 return getNodeHelper(this, count);
16641 getParentNode(count = 0) {
16642 return getNodeHelper(this, count + 1);
16643 } // Temporarily push properties named by string arguments given after the
16644 // callback function onto this.stack, then call the callback with a
16645 // reference to this (modified) FastPath object. Note that the stack will
16646 // be restored to its original state after the callback is finished, so it
16647 // is probably a mistake to retain a reference to the path.
16650 call(callback, ...names) {
16657 let value = getLast(stack);
16659 for (const name of names) {
16660 value = value[name];
16661 stack.push(name, value);
16664 const result = callback(this);
16665 stack.length = length;
16669 callParent(callback, count = 0) {
16670 const stackIndex = getNodeStackIndexHelper(this.stack, count + 1);
16671 const parentValues = this.stack.splice(stackIndex + 1);
16672 const result = callback(this);
16673 this.stack.push(...parentValues);
16675 } // Similar to FastPath.prototype.call, except that the value obtained by
16676 // accessing this.getValue()[name1][name2]... should be array-like. The
16677 // callback will be called with a reference to this path object for each
16678 // element of the array.
16681 each(callback, ...names) {
16688 let value = getLast(stack);
16690 for (const name of names) {
16691 value = value[name];
16692 stack.push(name, value);
16695 for (let i = 0; i < value.length; ++i) {
16697 stack.push(i, value[i]); // If the callback needs to know the value of i, call
16698 // path.getName(), assuming path is the parameter name.
16705 stack.length = length;
16706 } // Similar to FastPath.prototype.each, except that the results of the
16707 // callback function invocations are stored in an array and returned at
16708 // the end of the iteration.
16711 map(callback, ...names) {
16718 let value = getLast(stack);
16720 for (const name of names) {
16721 value = value[name];
16722 stack.push(name, value);
16725 const result = new Array(value.length);
16727 for (let i = 0; i < value.length; ++i) {
16729 stack.push(i, value[i]);
16730 result[i] = callback(this, i);
16735 stack.length = length;
16740 * | ((node: any, name: string | null, number: number | null) => boolean)
16746 match(...predicates) {
16747 let stackPointer = this.stack.length - 1;
16749 let node = this.stack[stackPointer--];
16751 for (const predicate of predicates) {
16752 if (node === undefined) {
16754 } // skip index/array
16759 if (typeof name === "number") {
16761 name = this.stack[stackPointer--];
16762 node = this.stack[stackPointer--];
16765 if (predicate && !predicate(node, name, number)) {
16769 name = this.stack[stackPointer--];
16770 node = this.stack[stackPointer--];
16778 var fastPath = FastPath;
16781 normalize: normalize$2
16784 function printSubtree(path, print, options, printAstToDoc) {
16785 if (options.printer.embed) {
16786 return options.printer.embed(path, print, (text, partialNextOptions) => textToDoc(text, partialNextOptions, options, printAstToDoc), options);
16790 function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc) {
16791 const nextOptions = normalize$2(Object.assign({}, parentOptions, {}, partialNextOptions, {
16792 parentParser: parentOptions.parser,
16793 embeddedInHtml: !!(parentOptions.embeddedInHtml || parentOptions.parser === "html" || parentOptions.parser === "vue" || parentOptions.parser === "angular" || parentOptions.parser === "lwc"),
16798 const result = parser.parse(text, nextOptions);
16802 text = result.text;
16803 const astComments = ast.comments;
16804 delete ast.comments;
16805 comments.attach(astComments, ast, text, nextOptions);
16806 return printAstToDoc(ast, nextOptions);
16809 var multiparser = {
16813 const doc = document;
16814 const docBuilders$1 = doc.builders;
16817 hardline: hardline$2,
16818 addAlignmentToDoc: addAlignmentToDoc$1
16820 const docUtils$1 = doc.utils;
16822 * Takes an abstract syntax tree (AST) and recursively converts it to a
16823 * document (series of printing primitives).
16825 * This is done by descending down the AST recursively. The recursion
16826 * involves two functions that call each other:
16828 * 1. printGenerically(), which is defined as an inner function here.
16829 * It basically takes care of node caching.
16830 * 2. callPluginPrintFunction(), which checks for some options, and
16831 * ultimately calls the print() function provided by the plugin.
16833 * The plugin function will call printGenerically() again for child nodes
16834 * of the current node, which will do its housekeeping, then call the
16835 * plugin function again, and so on.
16837 * All the while, these functions pass a "path" variable around, which
16838 * is a stack-like data structure (FastPath) that maintains the current
16839 * state of the recursion. It is called "path", because it represents
16840 * the path to the current node through the Abstract Syntax Tree.
16843 function printAstToDoc(ast, options, alignmentSize = 0) {
16848 if (printer.preprocess) {
16849 ast = printer.preprocess(ast, options);
16852 const cache = new Map();
16854 function printGenerically(path, args) {
16855 const node = path.getValue();
16856 const shouldCache = node && typeof node === "object" && args === undefined;
16858 if (shouldCache && cache.has(node)) {
16859 return cache.get(node);
16860 } // We let JSXElement print its comments itself because it adds () around
16861 // UnionTypeAnnotation has to align the child without the comments
16866 if (printer.willPrintOwnComments && printer.willPrintOwnComments(path, options)) {
16867 res = callPluginPrintFunction(path, options, printGenerically, args);
16869 // printComments will call the plugin print function and check for
16870 // comments to print
16871 res = comments.printComments(path, p => callPluginPrintFunction(p, options, printGenerically, args), options, args && args.needsSemi);
16875 cache.set(node, res);
16881 let doc = printGenerically(new fastPath(ast));
16883 if (alignmentSize > 0) {
16884 // Add a hardline to make the indents take effect
16885 // It should be removed in index.js format()
16886 doc = addAlignmentToDoc$1(concat$3([hardline$2, doc]), alignmentSize, options.tabWidth);
16889 docUtils$1.propagateBreaks(doc);
16893 function callPluginPrintFunction(path, options, printPath, args) {
16894 assert.ok(path instanceof fastPath);
16895 const node = path.getValue();
16898 } = options; // Escape hatch
16900 if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path)) {
16901 return options.originalText.slice(options.locStart(node), options.locEnd(node));
16906 // Potentially switch to a different parser
16907 const sub = multiparser.printSubtree(path, printPath, options, printAstToDoc);
16913 /* istanbul ignore if */
16914 if (commonjsGlobal.PRETTIER_DEBUG) {
16916 } // Continue with current parser
16921 return printer.print(path, options, printPath, args);
16924 var astToDoc = printAstToDoc;
16926 function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) {
16927 let resultStartNode = startNodeAndParents.node;
16928 let resultEndNode = endNodeAndParents.node;
16930 if (resultStartNode === resultEndNode) {
16932 startNode: resultStartNode,
16933 endNode: resultEndNode
16937 for (const endParent of endNodeAndParents.parentNodes) {
16938 if (endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node)) {
16939 resultEndNode = endParent;
16945 for (const startParent of startNodeAndParents.parentNodes) {
16946 if (startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node)) {
16947 resultStartNode = startParent;
16954 startNode: resultStartNode,
16955 endNode: resultEndNode
16959 function findNodeAtOffset(node, offset, options, predicate, parentNodes) {
16960 predicate = predicate || (() => true);
16962 parentNodes = parentNodes || [];
16963 const start = options.locStart(node, options.locStart);
16964 const end = options.locEnd(node, options.locEnd);
16966 if (start <= offset && offset <= end) {
16967 for (const childNode of comments.getSortedChildNodes(node, options)) {
16968 const childResult = findNodeAtOffset(childNode, offset, options, predicate, [node].concat(parentNodes));
16971 return childResult;
16975 if (predicate(node)) {
16982 } // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5
16985 function isSourceElement(opts, node) {
16986 if (node == null) {
16988 } // JS and JS like to avoid repetitions
16991 const jsSourceElements = ["FunctionDeclaration", "BlockStatement", "BreakStatement", "ContinueStatement", "DebuggerStatement", "DoWhileStatement", "EmptyStatement", "ExpressionStatement", "ForInStatement", "ForStatement", "IfStatement", "LabeledStatement", "ReturnStatement", "SwitchStatement", "ThrowStatement", "TryStatement", "VariableDeclaration", "WhileStatement", "WithStatement", "ClassDeclaration", // ES 2015
16992 "ImportDeclaration", // Module
16993 "ExportDefaultDeclaration", // Module
16994 "ExportNamedDeclaration", // Module
16995 "ExportAllDeclaration", // Module
16996 "TypeAlias", // Flow
16997 "InterfaceDeclaration", // Flow, TypeScript
16998 "TypeAliasDeclaration", // TypeScript
16999 "ExportAssignment", // TypeScript
17000 "ExportDeclaration" // TypeScript
17002 const jsonSourceElements = ["ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"];
17003 const graphqlSourceElements = ["OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition"];
17005 switch (opts.parser) {
17011 return jsSourceElements.includes(node.type);
17014 return jsonSourceElements.includes(node.type);
17017 return graphqlSourceElements.includes(node.kind);
17020 return node.tag !== "root";
17026 function calculateRange(text, opts, ast) {
17027 // Contract the range so that it has non-whitespace characters at its endpoints.
17028 // This ensures we can format a range that doesn't end on a node.
17029 const rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd);
17030 const startNonWhitespace = Math.max(opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart);
17031 let endNonWhitespace;
17033 for (endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace) {
17034 if (text[endNonWhitespace - 1].match(/\S/)) {
17039 const startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace, opts, node => isSourceElement(opts, node));
17040 const endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace, opts, node => isSourceElement(opts, node));
17042 if (!startNodeAndParents || !endNodeAndParents) {
17049 const siblingAncestors = findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts);
17053 } = siblingAncestors;
17054 const rangeStart = Math.min(opts.locStart(startNode, opts.locStart), opts.locStart(endNode, opts.locStart));
17055 const rangeEnd = Math.max(opts.locEnd(startNode, opts.locEnd), opts.locEnd(endNode, opts.locEnd));
17067 var diff = getCjsExportFromNamespace(index_es6);
17069 const normalizeOptions$1 = options$1.normalize;
17071 guessEndOfLine: guessEndOfLine$1,
17072 convertEndOfLineToChars: convertEndOfLineToChars$2
17076 printDocToString: printDocToString$1
17082 const BOM = "\uFEFF";
17083 const CURSOR = Symbol("cursor");
17084 const PLACEHOLDERS = {
17085 cursorOffset: "<<<PRETTIER_CURSOR>>>",
17086 rangeStart: "<<<PRETTIER_RANGE_START>>>",
17087 rangeEnd: "<<<PRETTIER_RANGE_END>>>"
17090 function ensureAllCommentsPrinted(astComments) {
17091 if (!astComments) {
17095 for (let i = 0; i < astComments.length; ++i) {
17096 if (util$1.isNodeIgnoreComment(astComments[i])) {
17097 // If there's a prettier-ignore, we're not printing that sub-tree so we
17098 // don't know if the comments was printed or not.
17103 astComments.forEach(comment => {
17104 if (!comment.printed) {
17105 throw new Error('Comment "' + comment.value.trim() + '" was not printed. Please report this error!');
17108 delete comment.printed;
17112 function attachComments(text, ast, opts) {
17113 const astComments = ast.comments;
17116 delete ast.comments;
17117 comments.attach(astComments, ast, text, opts);
17121 opts.originalText = opts.parser === "yaml" ? text : text.trimEnd();
17122 return astComments;
17125 function coreFormat(text, opts, addAlignmentSize) {
17126 if (!text || !text.trim().length) {
17133 addAlignmentSize = addAlignmentSize || 0;
17134 const parsed = parser.parse(text, opts);
17138 text = parsed.text;
17140 if (opts.cursorOffset >= 0) {
17141 const nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts);
17143 if (nodeResult && nodeResult.node) {
17144 opts.cursorNode = nodeResult.node;
17148 const astComments = attachComments(text, ast, opts);
17149 const doc = astToDoc(ast, opts, addAlignmentSize);
17150 const result = printDocToString$1(doc, opts);
17151 ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline
17153 if (addAlignmentSize > 0) {
17154 const trimmed = result.formatted.trim();
17156 if (result.cursorNodeStart !== undefined) {
17157 result.cursorNodeStart -= result.formatted.indexOf(trimmed);
17160 result.formatted = trimmed + convertEndOfLineToChars$2(opts.endOfLine);
17163 if (opts.cursorOffset >= 0) {
17164 let oldCursorNodeStart;
17165 let oldCursorNodeText;
17166 let cursorOffsetRelativeToOldCursorNode;
17167 let newCursorNodeStart;
17168 let newCursorNodeText;
17170 if (opts.cursorNode && result.cursorNodeText) {
17171 oldCursorNodeStart = opts.locStart(opts.cursorNode);
17172 oldCursorNodeText = text.slice(oldCursorNodeStart, opts.locEnd(opts.cursorNode));
17173 cursorOffsetRelativeToOldCursorNode = opts.cursorOffset - oldCursorNodeStart;
17174 newCursorNodeStart = result.cursorNodeStart;
17175 newCursorNodeText = result.cursorNodeText;
17177 oldCursorNodeStart = 0;
17178 oldCursorNodeText = text;
17179 cursorOffsetRelativeToOldCursorNode = opts.cursorOffset;
17180 newCursorNodeStart = 0;
17181 newCursorNodeText = result.formatted;
17184 if (oldCursorNodeText === newCursorNodeText) {
17186 formatted: result.formatted,
17187 cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode
17189 } // diff old and new cursor node texts, with a special cursor
17190 // symbol inserted to find out where it moves to
17193 const oldCursorNodeCharArray = oldCursorNodeText.split("");
17194 oldCursorNodeCharArray.splice(cursorOffsetRelativeToOldCursorNode, 0, CURSOR);
17195 const newCursorNodeCharArray = newCursorNodeText.split("");
17196 const cursorNodeDiff = diff.diffArrays(oldCursorNodeCharArray, newCursorNodeCharArray);
17197 let cursorOffset = newCursorNodeStart;
17199 for (const entry of cursorNodeDiff) {
17200 if (entry.removed) {
17201 if (entry.value.includes(CURSOR)) {
17205 cursorOffset += entry.count;
17210 formatted: result.formatted,
17216 formatted: result.formatted
17220 function formatRange(text, opts) {
17221 const parsed = parser.parse(text, opts);
17225 text = parsed.text;
17226 const range = rangeUtil.calculateRange(text, opts, ast);
17231 const rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line.
17232 // This is so we can detect indentation correctly and restore it.
17233 // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0
17235 const rangeStart2 = Math.min(rangeStart, text.lastIndexOf("\n", rangeStart) + 1);
17236 const indentString = text.slice(rangeStart2, rangeStart);
17237 const alignmentSize = util$1.getAlignmentSize(indentString, opts.tabWidth);
17238 const rangeResult = coreFormat(rangeString, Object.assign({}, opts, {
17240 rangeEnd: Infinity,
17241 // track the cursor offset only if it's within our range
17242 cursorOffset: opts.cursorOffset >= rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart : -1
17243 }), alignmentSize); // Since the range contracts to avoid trailing whitespace,
17244 // we need to remove the newline that was inserted by the `format` call.
17246 const rangeTrimmed = rangeResult.formatted.trimEnd();
17247 const rangeLeft = text.slice(0, rangeStart);
17248 const rangeRight = text.slice(rangeEnd);
17253 if (opts.cursorOffset >= rangeEnd) {
17254 // handle the case where the cursor was past the end of the range
17255 cursorOffset = opts.cursorOffset - rangeEnd + (rangeStart + rangeTrimmed.length);
17256 } else if (rangeResult.cursorOffset !== undefined) {
17257 // handle the case where the cursor was in the range
17258 cursorOffset = rangeResult.cursorOffset + rangeStart;
17259 } // keep the cursor as it was if it was before the start of the range
17264 if (opts.endOfLine === "lf") {
17265 formatted = rangeLeft + rangeTrimmed + rangeRight;
17267 const eol = convertEndOfLineToChars$2(opts.endOfLine);
17269 if (cursorOffset >= 0) {
17270 const parts = [rangeLeft, rangeTrimmed, rangeRight];
17272 let partOffset = cursorOffset;
17274 while (partIndex < parts.length) {
17275 const part = parts[partIndex];
17277 if (partOffset < part.length) {
17278 parts[partIndex] = parts[partIndex].slice(0, partOffset) + PLACEHOLDERS.cursorOffset + parts[partIndex].slice(partOffset);
17283 partOffset -= part.length;
17286 const [newRangeLeft, newRangeTrimmed, newRangeRight] = parts;
17287 formatted = (newRangeLeft.replace(/\n/g, eol) + newRangeTrimmed + newRangeRight.replace(/\n/g, eol)).replace(PLACEHOLDERS.cursorOffset, (_, index) => {
17288 cursorOffset = index;
17292 formatted = rangeLeft.replace(/\n/g, eol) + rangeTrimmed + rangeRight.replace(/\n/g, eol);
17302 function format(text, opts) {
17303 const selectedParser = parser.resolveParser(opts);
17304 const hasPragma = !selectedParser.hasPragma || selectedParser.hasPragma(text);
17306 if (opts.requirePragma && !hasPragma) {
17312 if (opts.endOfLine === "auto") {
17313 opts.endOfLine = guessEndOfLine$1(text);
17316 const hasCursor = opts.cursorOffset >= 0;
17317 const hasRangeStart = opts.rangeStart > 0;
17318 const hasRangeEnd = opts.rangeEnd < text.length; // get rid of CR/CRLF parsing
17320 if (text.includes("\r")) {
17321 const offsetKeys = [hasCursor && "cursorOffset", hasRangeStart && "rangeStart", hasRangeEnd && "rangeEnd"].filter(Boolean).sort((aKey, bKey) => opts[aKey] - opts[bKey]);
17323 for (let i = offsetKeys.length - 1; i >= 0; i--) {
17324 const key = offsetKeys[i];
17325 text = text.slice(0, opts[key]) + PLACEHOLDERS[key] + text.slice(opts[key]);
17328 text = text.replace(/\r\n?/g, "\n");
17330 for (let i = 0; i < offsetKeys.length; i++) {
17331 const key = offsetKeys[i];
17332 text = text.replace(PLACEHOLDERS[key], (_, index) => {
17339 const hasUnicodeBOM = text.charAt(0) === BOM;
17341 if (hasUnicodeBOM) {
17342 text = text.slice(1);
17345 opts.cursorOffset++;
17348 if (hasRangeStart) {
17358 opts.cursorOffset = -1;
17361 if (opts.rangeStart < 0) {
17362 opts.rangeStart = 0;
17365 if (opts.rangeEnd > text.length) {
17366 opts.rangeEnd = text.length;
17369 const result = hasRangeStart || hasRangeEnd ? formatRange(text, opts) : coreFormat(opts.insertPragma && opts.printer.insertPragma && !hasPragma ? opts.printer.insertPragma(text) : text, opts);
17371 if (hasUnicodeBOM) {
17372 result.formatted = BOM + result.formatted;
17375 result.cursorOffset++;
17383 formatWithCursor(text, opts) {
17384 opts = normalizeOptions$1(opts);
17385 return format(text, opts);
17388 parse(text, opts, massage) {
17389 opts = normalizeOptions$1(opts);
17391 if (text.includes("\r")) {
17392 text = text.replace(/\r\n?/g, "\n");
17395 const parsed = parser.parse(text, opts);
17398 parsed.ast = massageAst(parsed.ast, opts);
17404 formatAST(ast, opts) {
17405 opts = normalizeOptions$1(opts);
17406 const doc = astToDoc(ast, opts);
17407 return printDocToString$1(doc, opts);
17410 // Doesn't handle shebang for now
17411 formatDoc(doc, opts) {
17412 const debug = printDocToDebug(doc);
17413 opts = normalizeOptions$1(Object.assign({}, opts, {
17416 return format(debug, opts).formatted;
17419 printToDoc(text, opts) {
17420 opts = normalizeOptions$1(opts);
17421 const parsed = parser.parse(text, opts);
17425 text = parsed.text;
17426 attachComments(text, ast, opts);
17427 return astToDoc(ast, opts);
17430 printDocToString(doc, opts) {
17431 return printDocToString$1(doc, normalizeOptions$1(opts));
17436 function clean(ast, newObj, parent) {
17437 ["raw", // front-matter
17438 "raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(name => {
17439 delete newObj[name];
17442 if (ast.type === "yaml") {
17443 delete newObj.value;
17444 } // --insert-pragma
17447 if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0 && ( // first non-front-matter comment
17448 parent.nodes[0] === ast || (parent.nodes[0].type === "yaml" || parent.nodes[0].type === "toml") && parent.nodes[1] === ast)) {
17454 delete newObj.text; // standalone pragma
17456 if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) {
17461 if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") {
17462 delete newObj.value;
17465 if (ast.type === "css-rule") {
17466 delete newObj.params;
17469 if (ast.type === "selector-combinator") {
17470 newObj.value = newObj.value.replace(/\s+/g, " ");
17473 if (ast.type === "media-feature") {
17474 newObj.value = newObj.value.replace(/ /g, "");
17477 if (ast.type === "value-word" && (ast.isColor && ast.isHex || ["initial", "inherit", "unset", "revert"].includes(newObj.value.replace().toLowerCase())) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || ast.type === "selector-pseudo") {
17478 newObj.value = newObj.value.toLowerCase();
17481 if (ast.type === "css-decl") {
17482 newObj.prop = newObj.prop.toLowerCase();
17485 if (ast.type === "css-atrule" || ast.type === "css-import") {
17486 newObj.name = newObj.name.toLowerCase();
17489 if (ast.type === "value-number") {
17490 newObj.unit = newObj.unit.toLowerCase();
17493 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) {
17494 newObj.value = cleanCSSStrings(newObj.value);
17497 if (ast.type === "selector-attribute") {
17498 newObj.attribute = newObj.attribute.trim();
17500 if (newObj.namespace) {
17501 if (typeof newObj.namespace === "string") {
17502 newObj.namespace = newObj.namespace.trim();
17504 if (newObj.namespace.length === 0) {
17505 newObj.namespace = true;
17510 if (newObj.value) {
17511 newObj.value = newObj.value.trim().replace(/^['"]|['"]$/g, "");
17512 delete newObj.quoted;
17516 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) {
17517 newObj.value = newObj.value.replace(/([\d.eE+-]+)([a-zA-Z]*)/g, (match, numStr, unit) => {
17518 const num = Number(numStr);
17519 return isNaN(num) ? match : num + unit.toLowerCase();
17523 if (ast.type === "selector-tag") {
17524 const lowercasedValue = ast.value.toLowerCase();
17526 if (["from", "to"].includes(lowercasedValue)) {
17527 newObj.value = lowercasedValue;
17529 } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func`
17532 if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") {
17533 delete newObj.value;
17534 } // Workaround for SCSS nested properties
17537 if (ast.type === "selector-unknown") {
17538 delete newObj.value;
17542 function cleanCSSStrings(value) {
17543 return value.replace(/'/g, '"').replace(/\\([^a-fA-F\d])/g, "$1");
17546 var clean_1 = clean;
17550 hardline: hardline$3,
17551 literalline: literalline$1,
17553 markAsRoot: markAsRoot$1
17560 function embed(path, print, textToDoc
17563 const node = path.getValue();
17565 if (node.type === "yaml") {
17566 return markAsRoot$1(concat$4(["---", hardline$3, node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
17568 })) : "", "---", hardline$3]));
17573 function replaceNewlinesWithLiterallines(doc) {
17574 return mapDoc$1(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$4(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$1)) : currentDoc);
17578 var embed_1 = embed;
17580 const detectNewline = string => {
17581 if (typeof string !== 'string') {
17582 throw new TypeError('Expected a string');
17585 const newlines = string.match(/(?:\r?\n)/g) || [];
17587 if (newlines.length === 0) {
17591 const crlf = newlines.filter(newline => newline === '\r\n').length;
17592 const lf = newlines.length - crlf;
17593 return crlf > lf ? '\r\n' : '\n';
17596 var detectNewline_1 = detectNewline;
17598 var graceful = string => typeof string === 'string' && detectNewline(string) || '\n';
17599 detectNewline_1.graceful = graceful;
17601 var build = createCommonjsModule(function (module, exports) {
17603 Object.defineProperty(exports, '__esModule', {
17606 exports.extract = extract;
17607 exports.strip = strip;
17608 exports.parse = parse;
17609 exports.parseWithComments = parseWithComments;
17610 exports.print = print;
17613 const data = require$$0$1;
17615 _os = function _os() {
17622 function _detectNewline() {
17623 const data = _interopRequireDefault(detectNewline_1);
17625 _detectNewline = function _detectNewline() {
17632 function _interopRequireDefault(obj) {
17633 return obj && obj.__esModule ? obj : {
17638 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
17640 * This source code is licensed under the MIT license found in the
17641 * LICENSE file in the root directory of this source tree.
17645 const commentEndRe = /\*\/$/;
17646 const commentStartRe = /^\/\*\*/;
17647 const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/;
17648 const lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g;
17649 const ltrimNewlineRe = /^(\r?\n)+/;
17650 const multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
17651 const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
17652 const stringStartRe = /(\r?\n|^) *\* ?/g;
17654 function extract(contents) {
17655 const match = contents.match(docblockRe);
17656 return match ? match[0].trimLeft() : '';
17659 function strip(contents) {
17660 const match = contents.match(docblockRe);
17661 return match && match[0] ? contents.substring(match[0].length) : contents;
17664 function parse(docblock) {
17665 return parseWithComments(docblock).pragmas;
17668 function parseWithComments(docblock) {
17669 const line = (0, _detectNewline().default)(docblock) || _os().EOL;
17671 docblock = docblock.replace(commentStartRe, '').replace(commentEndRe, '').replace(stringStartRe, '$1'); // Normalize multi-line directives
17675 while (prev !== docblock) {
17677 docblock = docblock.replace(multilineRe, "".concat(line, "$1 $2").concat(line));
17680 docblock = docblock.replace(ltrimNewlineRe, '').trimRight();
17681 const result = Object.create(null);
17682 const comments = docblock.replace(propertyRe, '').replace(ltrimNewlineRe, '').trimRight();
17685 while (match = propertyRe.exec(docblock)) {
17686 // strip linecomments from pragmas
17687 const nextPragma = match[2].replace(lineCommentRe, '');
17689 if (typeof result[match[1]] === 'string' || Array.isArray(result[match[1]])) {
17690 result[match[1]] = [].concat(result[match[1]], nextPragma);
17692 result[match[1]] = nextPragma;
17706 const line = (0, _detectNewline().default)(comments) || _os().EOL;
17708 const head = '/**';
17709 const start = ' *';
17710 const tail = ' */';
17711 const keys = Object.keys(pragmas);
17712 const printedObject = keys.map(key => printKeyValues(key, pragmas[key])).reduce((arr, next) => arr.concat(next), []).map(keyValue => start + ' ' + keyValue + line).join('');
17715 if (keys.length === 0) {
17719 if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) {
17720 const value = pragmas[keys[0]];
17721 return "".concat(head, " ").concat(printKeyValues(keys[0], value)[0]).concat(tail);
17725 const printedComments = comments.split(line).map(textLine => "".concat(start, " ").concat(textLine)).join(line) + line;
17726 return head + line + (comments ? printedComments : '') + (comments && keys.length ? start + line : '') + printedObject + tail;
17729 function printKeyValues(key, valueOrArray) {
17730 return [].concat(valueOrArray).map(value => "@".concat(key, " ").concat(value).trim());
17733 unwrapExports(build);
17734 var build_1 = build.extract;
17735 var build_2 = build.strip;
17736 var build_3 = build.parse;
17737 var build_4 = build.parseWithComments;
17738 var build_5 = build.print;
17740 function hasPragma(text) {
17741 const pragmas = Object.keys(build.parse(build.extract(text)));
17742 return pragmas.includes("prettier") || pragmas.includes("format");
17745 function insertPragma(text) {
17746 const parsedDocblock = build.parseWithComments(build.extract(text));
17747 const pragmas = Object.assign({
17749 }, parsedDocblock.pragmas);
17750 const newDocblock = build.print({
17752 comments: parsedDocblock.comments.replace(/^(\s+?\r?\n)+/, "") // remove leading newlines
17754 }).replace(/(\r\n|\r)/g, "\n"); // normalise newlines (mitigate use of os.EOL by jest-docblock)
17756 const strippedText = build.strip(text);
17757 const separatingNewlines = strippedText.startsWith("\n") ? "\n" : "\n\n";
17758 return newDocblock + separatingNewlines + strippedText;
17766 const DELIMITER_MAP = {
17771 function parse$1(text) {
17772 const delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp$2).join("|");
17773 const match = text.match( // trailing spaces after delimiters are allowed
17774 new RegExp("^(".concat(delimiterRegex, ")[^\\n\\S]*\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)")));
17776 if (match === null) {
17783 const [raw, delimiter, value] = match;
17786 type: DELIMITER_MAP[delimiter],
17788 raw: raw.replace(/\n$/, "")
17790 content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length)
17794 var frontMatter = parse$1;
17796 function hasPragma$1(text) {
17797 return pragma.hasPragma(frontMatter(text).content);
17800 function insertPragma$1(text) {
17802 frontMatter: frontMatter$1,
17804 } = frontMatter(text);
17805 return (frontMatter$1 ? frontMatter$1.raw + "\n\n" : "") + pragma.insertPragma(content);
17809 hasPragma: hasPragma$1,
17810 insertPragma: insertPragma$1
17813 var lineColumnToIndex = function lineColumnToIndex(lineColumn, text) {
17816 for (let i = 0; i < lineColumn.line - 1; ++i) {
17817 index = text.indexOf("\n", index) + 1;
17819 if (index === -1) {
17824 return index + lineColumn.column;
17828 getLast: getLast$1,
17829 skipEverythingButNewLine: skipEverythingButNewLine$2
17832 function calculateLocStart(node, text) {
17834 return lineColumnToIndex(node.source.start, text) - 1;
17840 function calculateLocEnd(node, text) {
17841 if (node.type === "css-comment" && node.inline) {
17842 return skipEverythingButNewLine$2(text, node.source.startOffset);
17845 const endNode = node.nodes && getLast$1(node.nodes);
17847 if (endNode && node.source && !node.source.end) {
17851 if (node.source && node.source.end) {
17852 return lineColumnToIndex(node.source.end, text);
17858 function calculateLoc(node, text) {
17859 if (node && typeof node === "object") {
17861 node.source.startOffset = calculateLocStart(node, text);
17862 node.source.endOffset = calculateLocEnd(node, text);
17865 for (const key in node) {
17866 calculateLoc(node[key], text);
17871 * Workaround for a bug: quotes in inline comments corrupt loc data of subsequent nodes.
17872 * This function replaces the quotes with U+FFFE and U+FFFF. Later, when the comments are printed,
17873 * their content is extracted from the original text or restored by replacing the placeholder
17874 * characters back with quotes.
17875 * - https://github.com/prettier/prettier/issues/7780
17876 * - https://github.com/shellscape/postcss-less/issues/145
17877 * - About noncharacters (U+FFFE and U+FFFF): http://www.unicode.org/faq/private_use.html#nonchar1
17878 * @param text {string}
17882 function replaceQuotesInInlineComments(text) {
17883 /** @typedef { 'initial' | 'single-quotes' | 'double-quotes' | 'url' | 'comment-block' | 'comment-inline' } State */
17885 /** @type {State} */
17886 let state = "initial";
17887 /** @type {State} */
17889 let stateToReturnFromQuotes = "initial";
17890 let inlineCommentStartIndex;
17891 let inlineCommentContainsQuotes = false;
17892 const inlineCommentsToReplace = [];
17894 for (let i = 0; i < text.length; i++) {
17900 state = "single-quotes";
17905 state = "double-quotes";
17909 if ((c === "u" || c === "U") && text.slice(i, i + 4).toLowerCase() === "url(") {
17915 if (c === "*" && text[i - 1] === "/") {
17916 state = "comment-block";
17920 if (c === "/" && text[i - 1] === "/") {
17921 state = "comment-inline";
17922 inlineCommentStartIndex = i - 1;
17928 case "single-quotes":
17929 if (c === "'" && text[i - 1] !== "\\") {
17930 state = stateToReturnFromQuotes;
17931 stateToReturnFromQuotes = "initial";
17934 if (c === "\n" || c === "\r") {
17935 return text; // invalid input
17940 case "double-quotes":
17941 if (c === '"' && text[i - 1] !== "\\") {
17942 state = stateToReturnFromQuotes;
17943 stateToReturnFromQuotes = "initial";
17946 if (c === "\n" || c === "\r") {
17947 return text; // invalid input
17957 if (c === "\n" || c === "\r") {
17958 return text; // invalid input
17962 state = "single-quotes";
17963 stateToReturnFromQuotes = "url";
17968 state = "double-quotes";
17969 stateToReturnFromQuotes = "url";
17975 case "comment-block":
17976 if (c === "/" && text[i - 1] === "*") {
17982 case "comment-inline":
17983 if (c === '"' || c === "'") {
17984 inlineCommentContainsQuotes = true;
17987 if (c === "\n" || c === "\r") {
17988 if (inlineCommentContainsQuotes) {
17989 inlineCommentsToReplace.push([inlineCommentStartIndex, i]);
17993 inlineCommentContainsQuotes = false;
18000 for (const [start, end] of inlineCommentsToReplace) {
18001 text = text.slice(0, start) + text.slice(start, end).replace(/'/g, "\ufffe").replace(/"/g, "\uffff") + text.slice(end);
18007 function restoreQuotesInInlineComments(text) {
18008 return text.replace(/\ufffe/g, "'").replace(/\uffff/g, '"');
18013 replaceQuotesInInlineComments,
18014 restoreQuotesInInlineComments
18017 const colorAdjusterFunctions = ["red", "green", "blue", "alpha", "a", "rgb", "hue", "h", "saturation", "s", "lightness", "l", "whiteness", "w", "blackness", "b", "tint", "shade", "blend", "blenda", "contrast", "hsl", "hsla", "hwb", "hwba"];
18019 function getAncestorCounter(path, typeOrTypes) {
18020 const types = [].concat(typeOrTypes);
18024 while (ancestorNode = path.getParentNode(++counter)) {
18025 if (types.includes(ancestorNode.type)) {
18033 function getAncestorNode(path, typeOrTypes) {
18034 const counter = getAncestorCounter(path, typeOrTypes);
18035 return counter === -1 ? null : path.getParentNode(counter);
18038 function getPropOfDeclNode(path) {
18039 const declAncestorNode = getAncestorNode(path, "css-decl");
18040 return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase();
18043 function isSCSS(parser, text) {
18044 const hasExplicitParserChoice = parser === "less" || parser === "scss";
18045 const IS_POSSIBLY_SCSS = /(\w\s*:\s*[^}:]+|#){|@import[^\n]+(?:url|,)/;
18046 return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text);
18049 function isWideKeywords(value) {
18050 return ["initial", "inherit", "unset", "revert"].includes(value.toLowerCase());
18053 function isKeyframeAtRuleKeywords(path, value) {
18054 const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
18055 return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].includes(value.toLowerCase());
18058 function maybeToLowerCase(value) {
18059 return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase();
18062 function insideValueFunctionNode(path, functionName) {
18063 const funcAncestorNode = getAncestorNode(path, "value-func");
18064 return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName;
18067 function insideICSSRuleNode(path) {
18068 const ruleAncestorNode = getAncestorNode(path, "css-rule");
18069 return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export"));
18072 function insideAtRuleNode(path, atRuleNameOrAtRuleNames) {
18073 const atRuleNames = [].concat(atRuleNameOrAtRuleNames);
18074 const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
18075 return atRuleAncestorNode && atRuleNames.includes(atRuleAncestorNode.name.toLowerCase());
18078 function insideURLFunctionInImportAtRuleNode(path) {
18079 const node = path.getValue();
18080 const atRuleAncestorNode = getAncestorNode(path, "css-atrule");
18081 return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2;
18084 function isURLFunctionNode(node) {
18085 return node.type === "value-func" && node.value.toLowerCase() === "url";
18088 function isLastNode(path, node) {
18089 const parentNode = path.getParentNode();
18098 return nodes && nodes.indexOf(node) === nodes.length - 1;
18101 function isDetachedRulesetDeclarationNode(node) {
18102 // If a Less file ends up being parsed with the SCSS parser, Less
18103 // variable declarations will be parsed as atrules with names ending
18104 // with a colon, so keep the original case then.
18105 if (!node.selector) {
18109 return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value);
18112 function isForKeywordNode(node) {
18113 return node.type === "value-word" && ["from", "through", "end"].includes(node.value);
18116 function isIfElseKeywordNode(node) {
18117 return node.type === "value-word" && ["and", "or", "not"].includes(node.value);
18120 function isEachKeywordNode(node) {
18121 return node.type === "value-word" && node.value === "in";
18124 function isMultiplicationNode(node) {
18125 return node.type === "value-operator" && node.value === "*";
18128 function isDivisionNode(node) {
18129 return node.type === "value-operator" && node.value === "/";
18132 function isAdditionNode(node) {
18133 return node.type === "value-operator" && node.value === "+";
18136 function isSubtractionNode(node) {
18137 return node.type === "value-operator" && node.value === "-";
18140 function isModuloNode(node) {
18141 return node.type === "value-operator" && node.value === "%";
18144 function isMathOperatorNode(node) {
18145 return isMultiplicationNode(node) || isDivisionNode(node) || isAdditionNode(node) || isSubtractionNode(node) || isModuloNode(node);
18148 function isEqualityOperatorNode(node) {
18149 return node.type === "value-word" && ["==", "!="].includes(node.value);
18152 function isRelationalOperatorNode(node) {
18153 return node.type === "value-word" && ["<", ">", "<=", ">="].includes(node.value);
18156 function isSCSSControlDirectiveNode(node) {
18157 return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].includes(node.name);
18160 function isSCSSNestedPropertyNode(node) {
18161 if (!node.selector) {
18165 return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":");
18168 function isDetachedRulesetCallNode(node) {
18169 return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params);
18172 function isTemplatePlaceholderNode(node) {
18173 return node.name.startsWith("prettier-placeholder");
18176 function isTemplatePropNode(node) {
18177 return node.prop.startsWith("@prettier-placeholder");
18180 function isPostcssSimpleVarNode(currentNode, nextNode) {
18181 return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before;
18184 function hasComposesNode(node) {
18185 return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes";
18188 function hasParensAroundNode(node) {
18189 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;
18192 function hasEmptyRawBefore(node) {
18193 return node.raws && node.raws.before === "";
18196 function isKeyValuePairNode(node) {
18197 return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon";
18200 function isKeyValuePairInParenGroupNode(node) {
18201 return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode(node.groups[0]);
18204 function isSCSSMapItemNode(path) {
18205 const node = path.getValue(); // Ignore empty item (i.e. `$key: ()`)
18207 if (node.groups.length === 0) {
18211 const parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`)
18213 if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) {
18217 const declNode = getAncestorNode(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`)
18219 if (declNode && declNode.prop && declNode.prop.startsWith("$")) {
18221 } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`)
18224 if (isKeyValuePairInParenGroupNode(parentParentNode)) {
18226 } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`)
18229 if (parentParentNode.type === "value-func") {
18236 function isInlineValueCommentNode(node) {
18237 return node.type === "value-comment" && node.inline;
18240 function isHashNode(node) {
18241 return node.type === "value-word" && node.value === "#";
18244 function isLeftCurlyBraceNode(node) {
18245 return node.type === "value-word" && node.value === "{";
18248 function isRightCurlyBraceNode(node) {
18249 return node.type === "value-word" && node.value === "}";
18252 function isWordNode(node) {
18253 return ["value-word", "value-atword"].includes(node.type);
18256 function isColonNode(node) {
18257 return node.type === "value-colon";
18260 function isMediaAndSupportsKeywords(node) {
18261 return node.value && ["not", "and", "or"].includes(node.value.toLowerCase());
18264 function isColorAdjusterFuncNode(node) {
18265 if (node.type !== "value-func") {
18269 return colorAdjusterFunctions.includes(node.value.toLowerCase());
18270 } // TODO: only check `less` when we don't use `less` to parse `css`
18273 function isLessParser(options) {
18274 return options.parser === "css" || options.parser === "less";
18277 function lastLineHasInlineComment(text) {
18278 return /\/\//.test(text.split(/[\r\n]/).pop());
18282 getAncestorCounter,
18286 insideValueFunctionNode,
18287 insideICSSRuleNode,
18289 insideURLFunctionInImportAtRuleNode,
18290 isKeyframeAtRuleKeywords,
18295 isSCSSControlDirectiveNode,
18296 isDetachedRulesetDeclarationNode,
18297 isRelationalOperatorNode,
18298 isEqualityOperatorNode,
18299 isMultiplicationNode,
18304 isMathOperatorNode,
18308 isIfElseKeywordNode,
18310 hasParensAroundNode,
18312 isSCSSNestedPropertyNode,
18313 isDetachedRulesetCallNode,
18314 isTemplatePlaceholderNode,
18315 isTemplatePropNode,
18316 isPostcssSimpleVarNode,
18317 isKeyValuePairNode,
18318 isKeyValuePairInParenGroupNode,
18320 isInlineValueCommentNode,
18322 isLeftCurlyBraceNode,
18323 isRightCurlyBraceNode,
18326 isMediaAndSupportsKeywords,
18327 isColorAdjusterFuncNode,
18328 lastLineHasInlineComment
18332 insertPragma: insertPragma$2
18335 printNumber: printNumber$1,
18336 printString: printString$1,
18337 hasIgnoreComment: hasIgnoreComment$1,
18338 hasNewline: hasNewline$3
18341 isNextLineEmpty: isNextLineEmpty$2
18344 restoreQuotesInInlineComments: restoreQuotesInInlineComments$1
18351 hardline: hardline$4,
18352 softline: softline$1,
18360 removeLines: removeLines$1
18364 getAncestorNode: getAncestorNode$1,
18365 getPropOfDeclNode: getPropOfDeclNode$1,
18366 maybeToLowerCase: maybeToLowerCase$1,
18367 insideValueFunctionNode: insideValueFunctionNode$1,
18368 insideICSSRuleNode: insideICSSRuleNode$1,
18369 insideAtRuleNode: insideAtRuleNode$1,
18370 insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1,
18371 isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1,
18372 isWideKeywords: isWideKeywords$1,
18374 isLastNode: isLastNode$1,
18375 isLessParser: isLessParser$1,
18376 isSCSSControlDirectiveNode: isSCSSControlDirectiveNode$1,
18377 isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode$1,
18378 isRelationalOperatorNode: isRelationalOperatorNode$1,
18379 isEqualityOperatorNode: isEqualityOperatorNode$1,
18380 isMultiplicationNode: isMultiplicationNode$1,
18381 isDivisionNode: isDivisionNode$1,
18382 isAdditionNode: isAdditionNode$1,
18383 isSubtractionNode: isSubtractionNode$1,
18384 isMathOperatorNode: isMathOperatorNode$1,
18385 isEachKeywordNode: isEachKeywordNode$1,
18386 isForKeywordNode: isForKeywordNode$1,
18387 isURLFunctionNode: isURLFunctionNode$1,
18388 isIfElseKeywordNode: isIfElseKeywordNode$1,
18389 hasComposesNode: hasComposesNode$1,
18390 hasParensAroundNode: hasParensAroundNode$1,
18391 hasEmptyRawBefore: hasEmptyRawBefore$1,
18392 isKeyValuePairNode: isKeyValuePairNode$1,
18393 isDetachedRulesetCallNode: isDetachedRulesetCallNode$1,
18394 isTemplatePlaceholderNode: isTemplatePlaceholderNode$1,
18395 isTemplatePropNode: isTemplatePropNode$1,
18396 isPostcssSimpleVarNode: isPostcssSimpleVarNode$1,
18397 isSCSSMapItemNode: isSCSSMapItemNode$1,
18398 isInlineValueCommentNode: isInlineValueCommentNode$1,
18399 isHashNode: isHashNode$1,
18400 isLeftCurlyBraceNode: isLeftCurlyBraceNode$1,
18401 isRightCurlyBraceNode: isRightCurlyBraceNode$1,
18402 isWordNode: isWordNode$1,
18403 isColonNode: isColonNode$1,
18404 isMediaAndSupportsKeywords: isMediaAndSupportsKeywords$1,
18405 isColorAdjusterFuncNode: isColorAdjusterFuncNode$1,
18406 lastLineHasInlineComment: lastLineHasInlineComment$1
18409 function shouldPrintComma(options) {
18410 switch (options.trailingComma) {
18421 function genericPrint(path, options, print) {
18422 const node = path.getValue();
18423 /* istanbul ignore if */
18429 if (typeof node === "string") {
18433 switch (node.type) {
18436 return concat$5([node.raw, hardline$4]);
18440 const nodes = printNodeSequence(path, options, print);
18442 if (nodes.parts.length) {
18443 return concat$5([nodes, options.__isHTMLStyleAttribute ? "" : hardline$4]);
18449 case "css-comment":
18451 const isInlineComment = node.inline || node.raws.inline;
18452 const text = options.originalText.slice(options.locStart(node), options.locEnd(node));
18453 return isInlineComment ? text.trimEnd() : text;
18458 return concat$5([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$5([node.selector && node.selector.type === "selector-unknown" && lastLineHasInlineComment$1(node.selector.value) ? line$2 : " ", "{", node.nodes.length > 0 ? indent$2(concat$5([hardline$4, printNodeSequence(path, options, print)])) : "", hardline$4, "}", isDetachedRulesetDeclarationNode$1(node) ? ";" : ""]) : ";"]);
18463 const parentNode = path.getParentNode();
18464 return concat$5([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode$1(path) ? node.prop : maybeToLowerCase$1(node.prop), node.raws.between.trim() === ":" ? ":" : node.raws.between.trim(), node.extend ? "" : " ", hasComposesNode$1(node) ? removeLines$1(path.call(print, "value")) : path.call(print, "value"), node.raws.important ? node.raws.important.replace(/\s*!\s*important/i, " !important") : node.important ? " !important" : "", node.raws.scssDefault ? node.raws.scssDefault.replace(/\s*!default/i, " !default") : node.scssDefault ? " !default" : "", node.raws.scssGlobal ? node.raws.scssGlobal.replace(/\s*!global/i, " !global") : node.scssGlobal ? " !global" : "", node.nodes ? concat$5([" {", indent$2(concat$5([softline$1, printNodeSequence(path, options, print)])), softline$1, "}"]) : isTemplatePropNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : ";"]);
18469 const parentNode = path.getParentNode();
18470 const isTemplatePlaceholderNodeWithoutSemiColon = isTemplatePlaceholderNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";";
18472 if (isLessParser$1(options)) {
18474 return concat$5([path.call(print, "selector"), node.important ? " !important" : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
18477 if (node.function) {
18478 return concat$5([node.name, concat$5([path.call(print, "params")]), isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
18481 if (node.variable) {
18482 return concat$5(["@", node.name, ": ", node.value ? concat$5([path.call(print, "value")]) : "", node.raws.between.trim() ? node.raws.between.trim() + " " : "", node.nodes ? concat$5(["{", indent$2(concat$5([node.nodes.length > 0 ? softline$1 : "", printNodeSequence(path, options, print)])), softline$1, "}"]) : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
18486 return concat$5(["@", // If a Less file ends up being parsed with the SCSS parser, Less
18487 // variable declarations will be parsed as at-rules with names ending
18488 // with a colon, so keep the original case then.
18489 isDetachedRulesetCallNode$1(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase$1(node.name), node.params ? concat$5([isDetachedRulesetCallNode$1(node) ? "" : isTemplatePlaceholderNode$1(node) ? node.raws.afterName === "" ? "" : node.name.endsWith(":") ? " " : /^\s*\n\s*\n/.test(node.raws.afterName) ? concat$5([hardline$4, hardline$4]) : /^\s*\n/.test(node.raws.afterName) ? hardline$4 : " " : " ", path.call(print, "params")]) : "", node.selector ? indent$2(concat$5([" ", path.call(print, "selector")])) : "", node.value ? group$1(concat$5([" ", path.call(print, "value"), isSCSSControlDirectiveNode$1(node) ? hasParensAroundNode$1(node) ? " " : line$2 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$5([isSCSSControlDirectiveNode$1(node) ? "" : " ", "{", indent$2(concat$5([node.nodes.length > 0 ? softline$1 : "", printNodeSequence(path, options, print)])), softline$1, "}"]) : isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]);
18491 // postcss-media-query-parser
18493 case "media-query-list":
18496 path.each(childPath => {
18497 const node = childPath.getValue();
18499 if (node.type === "media-query" && node.value === "") {
18503 parts.push(childPath.call(print));
18505 return group$1(indent$2(join$2(line$2, parts)));
18508 case "media-query":
18510 return concat$5([join$2(" ", path.map(print, "nodes")), isLastNode$1(path, node) ? "" : ","]);
18515 return adjustNumbers(adjustStrings(node.value, options));
18518 case "media-feature-expression":
18524 return concat$5(["(", concat$5(path.map(print, "nodes")), ")"]);
18527 case "media-feature":
18529 return maybeToLowerCase$1(adjustStrings(node.value.replace(/ +/g, " "), options));
18532 case "media-colon":
18534 return concat$5([node.value, " "]);
18537 case "media-value":
18539 return adjustNumbers(adjustStrings(node.value, options));
18542 case "media-keyword":
18544 return adjustStrings(node.value, options);
18549 return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options);
18552 case "media-unknown":
18556 // postcss-selector-parser
18558 case "selector-root":
18560 return group$1(concat$5([insideAtRuleNode$1(path, "custom-selector") ? concat$5([getAncestorNode$1(path, "css-atrule").customSelector, line$2]) : "", join$2(concat$5([",", insideAtRuleNode$1(path, ["extend", "custom-selector", "nest"]) ? line$2 : hardline$4]), path.map(print, "nodes"))]));
18563 case "selector-selector":
18565 return group$1(indent$2(concat$5(path.map(print, "nodes"))));
18568 case "selector-comment":
18573 case "selector-string":
18575 return adjustStrings(node.value, options);
18578 case "selector-tag":
18580 const parentNode = path.getParentNode();
18581 const index = parentNode && parentNode.nodes.indexOf(node);
18582 const prevNode = index && parentNode.nodes[index - 1];
18583 return concat$5([node.namespace ? concat$5([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isKeyframeAtRuleKeywords$1(path, node.value) ? node.value.toLowerCase() : node.value)]);
18586 case "selector-id":
18588 return concat$5(["#", node.value]);
18591 case "selector-class":
18593 return concat$5([".", adjustNumbers(adjustStrings(node.value, options))]);
18596 case "selector-attribute":
18598 return concat$5(["[", node.namespace ? concat$5([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.attribute.trim(), node.operator ? node.operator : "", node.value ? quoteAttributeValue(adjustStrings(node.value.trim(), options), options) : "", node.insensitive ? " i" : "", "]"]);
18601 case "selector-combinator":
18603 if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") {
18604 const parentNode = path.getParentNode();
18605 const leading = parentNode.type === "selector-selector" && parentNode.nodes[0] === node ? "" : line$2;
18606 return concat$5([leading, node.value, isLastNode$1(path, node) ? "" : " "]);
18609 const leading = node.value.trim().startsWith("(") ? line$2 : "";
18610 const value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$2;
18611 return concat$5([leading, value]);
18614 case "selector-universal":
18616 return concat$5([node.namespace ? concat$5([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]);
18619 case "selector-pseudo":
18621 return concat$5([maybeToLowerCase$1(node.value), node.nodes && node.nodes.length > 0 ? concat$5(["(", join$2(", ", path.map(print, "nodes")), ")"]) : ""]);
18624 case "selector-nesting":
18629 case "selector-unknown":
18631 const ruleAncestorNode = getAncestorNode$1(path, "css-rule"); // Nested SCSS property
18633 if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) {
18634 return adjustNumbers(adjustStrings(maybeToLowerCase$1(node.value), options));
18635 } // originalText has to be used for Less, see replaceQuotesInInlineComments in loc.js
18638 const parentNode = path.getParentNode();
18640 if (parentNode.raws && parentNode.raws.selector) {
18641 const start = options.locStart(parentNode);
18642 const end = start + parentNode.raws.selector.length;
18643 return options.originalText.slice(start, end).trim();
18648 // postcss-values-parser
18650 case "value-value":
18653 return path.call(print, "group");
18656 case "value-comment":
18658 return concat$5([node.inline ? "//" : "/*", // see replaceQuotesInInlineComments in loc.js
18659 // value-* nodes don't have correct location data, so we have to rely on placeholder characters.
18660 restoreQuotesInInlineComments$1(node.value), node.inline ? "" : "*/"]);
18663 case "value-comma_group":
18665 const parentNode = path.getParentNode();
18666 const parentParentNode = path.getParentNode(1);
18667 const declAncestorProp = getPropOfDeclNode$1(path);
18668 const isGridValue = declAncestorProp && parentNode.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template"));
18669 const atRuleAncestorNode = getAncestorNode$1(path, "css-atrule");
18670 const isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode$1(atRuleAncestorNode);
18671 const printed = path.map(print, "groups");
18673 const insideURLFunction = insideValueFunctionNode$1(path, "url");
18674 let insideSCSSInterpolationInString = false;
18675 let didBreak = false;
18677 for (let i = 0; i < node.groups.length; ++i) {
18678 parts.push(printed[i]);
18679 const iPrevNode = node.groups[i - 1];
18680 const iNode = node.groups[i];
18681 const iNextNode = node.groups[i + 1];
18682 const iNextNextNode = node.groups[i + 2];
18684 if (insideURLFunction) {
18685 if (iNextNode && isAdditionNode$1(iNextNode) || isAdditionNode$1(iNode)) {
18690 } // Ignore after latest node (i.e. before semicolon)
18695 } // styled.div` background: var(--${one}); `
18698 if (!iPrevNode && iNode.value === "--" && iNextNode.type === "value-atword") {
18700 } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`)
18703 const isStartSCSSInterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{");
18704 const isEndingSCSSInterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}");
18706 if (isStartSCSSInterpolationInString || isEndingSCSSInterpolationInString) {
18707 insideSCSSInterpolationInString = !insideSCSSInterpolationInString;
18711 if (insideSCSSInterpolationInString) {
18713 } // Ignore colon (i.e. `:`)
18716 if (isColonNode$1(iNode) || isColonNode$1(iNextNode)) {
18718 } // Ignore `@` in Less (i.e. `@@var;`)
18721 if (iNode.type === "value-atword" && iNode.value === "") {
18723 } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`)
18726 if (iNode.value === "~") {
18728 } // Ignore escape `\`
18731 if (iNode.value && iNode.value.includes("\\") && iNextNode && iNextNode.type !== "value-comment") {
18733 } // Ignore escaped `/`
18736 if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") {
18738 } // Ignore `\` (i.e. `$variable: \@small;`)
18741 if (iNode.value === "\\") {
18743 } // Ignore `$$` (i.e. `background-color: $$(style)Color;`)
18746 if (isPostcssSimpleVarNode$1(iNode, iNextNode)) {
18748 } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`)
18751 if (isHashNode$1(iNode) || isLeftCurlyBraceNode$1(iNode) || isRightCurlyBraceNode$1(iNextNode) || isLeftCurlyBraceNode$1(iNextNode) && hasEmptyRawBefore$1(iNextNode) || isRightCurlyBraceNode$1(iNode) && hasEmptyRawBefore$1(iNextNode)) {
18753 } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`)
18756 if (iNode.value === "--" && isHashNode$1(iNextNode)) {
18758 } // Formatting math operations
18761 const isMathOperator = isMathOperatorNode$1(iNode);
18762 const isNextMathOperator = isMathOperatorNode$1(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is
18763 // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`)
18764 // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`)
18766 if ((isMathOperator && isHashNode$1(iNextNode) || isNextMathOperator && isRightCurlyBraceNode$1(iNode)) && hasEmptyRawBefore$1(iNextNode)) {
18768 } // Print spaces before and after addition and subtraction math operators as is in `calc` function
18769 // due to the fact that it is not valid syntax
18770 // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`)
18773 if (insideValueFunctionNode$1(path, "calc") && (isAdditionNode$1(iNode) || isAdditionNode$1(iNextNode) || isSubtractionNode$1(iNode) || isSubtractionNode$1(iNextNode)) && hasEmptyRawBefore$1(iNextNode)) {
18775 } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`)
18776 // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is.
18779 const isColorAdjusterNode = (isAdditionNode$1(iNode) || isSubtractionNode$1(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode$1(parentParentNode) && !hasEmptyRawBefore$1(iNextNode);
18780 const requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode$1(iNextNextNode) || iNode.type === "value-func" || isWordNode$1(iNode);
18781 const requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode$1(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode$1(iPrevNode); // Formatting `/`, `+`, `-` sign
18783 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)))) {
18785 } // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`)
18788 if (isInlineValueCommentNode$1(iNode)) {
18789 parts.push(hardline$4);
18791 } // Handle keywords in SCSS control directive
18794 if (isControlDirective && (isEqualityOperatorNode$1(iNextNode) || isRelationalOperatorNode$1(iNextNode) || isIfElseKeywordNode$1(iNextNode) || isEachKeywordNode$1(iNode) || isForKeywordNode$1(iNode))) {
18797 } // At-rule `namespace` should be in one line
18800 if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") {
18803 } // Formatting `grid` property
18807 if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) {
18808 parts.push(hardline$4);
18815 } // Add `space` before next math operation
18816 // Note: `grip` property have `/` delimiter and it is not math operation, so
18817 // `grid` property handles above
18820 if (isNextMathOperator) {
18823 } // Be default all values go through `line`
18826 parts.push(line$2);
18830 parts.unshift(hardline$4);
18833 if (isControlDirective) {
18834 return group$1(indent$2(concat$5(parts)));
18835 } // Indent is not needed for import url when url is very long
18836 // and node has two groups
18837 // when type is value-comma_group
18838 // example @import url("verylongurl") projection,tv
18841 if (insideURLFunctionInImportAtRuleNode$1(path)) {
18842 return group$1(fill$2(parts));
18845 return group$1(indent$2(fill$2(parts)));
18848 case "value-paren_group":
18850 const parentNode = path.getParentNode();
18852 if (parentNode && isURLFunctionNode$1(parentNode) && (node.groups.length === 1 || node.groups.length > 0 && node.groups[0].type === "value-comma_group" && node.groups[0].groups.length > 0 && node.groups[0].groups[0].type === "value-word" && node.groups[0].groups[0].value.startsWith("data:"))) {
18853 return concat$5([node.open ? path.call(print, "open") : "", join$2(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]);
18857 const printed = path.map(print, "groups");
18860 for (let i = 0; i < printed.length; i++) {
18862 res.push(concat$5([",", line$2]));
18865 res.push(printed[i]);
18868 return group$1(indent$2(fill$2(res)));
18871 const isSCSSMapItem = isSCSSMapItemNode$1(path);
18872 const lastItem = node.groups[node.groups.length - 1];
18873 const isLastItemComment = lastItem && lastItem.type === "value-comment";
18874 return group$1(concat$5([node.open ? path.call(print, "open") : "", indent$2(concat$5([softline$1, join$2(concat$5([",", line$2]), path.map(childPath => {
18875 const node = childPath.getValue();
18876 const printed = print(childPath); // Key/Value pair in open paren already indented
18878 if (isKeyValuePairNode$1(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") {
18879 printed.contents.contents.parts[1] = group$1(printed.contents.contents.parts[1]);
18880 return group$1(dedent$1(printed));
18884 }, "groups"))])), ifBreak$1(!isLastItemComment && isSCSS$1(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma(options) ? "," : ""), softline$1, node.close ? path.call(print, "close") : ""]), {
18885 shouldBreak: isSCSSMapItem
18891 return concat$5([node.value, insideAtRuleNode$1(path, "supports") && isMediaAndSupportsKeywords$1(node) ? " " : "", path.call(print, "group")]);
18894 case "value-paren":
18899 case "value-number":
18901 return concat$5([printCssNumber(node.value), maybeToLowerCase$1(node.unit)]);
18904 case "value-operator":
18911 if (node.isColor && node.isHex || isWideKeywords$1(node.value)) {
18912 return node.value.toLowerCase();
18918 case "value-colon":
18920 return concat$5([node.value, // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`)
18921 insideValueFunctionNode$1(path, "url") ? "" : line$2]);
18924 case "value-comma":
18926 return concat$5([node.value, " "]);
18929 case "value-string":
18931 return printString$1(node.raws.quote + node.value + node.raws.quote, options);
18934 case "value-atword":
18936 return concat$5(["@", node.value]);
18939 case "value-unicode-range":
18944 case "value-unknown":
18950 /* istanbul ignore next */
18951 throw new Error("Unknown postcss type ".concat(JSON.stringify(node.type)));
18955 function printNodeSequence(path, options, print) {
18956 const node = path.getValue();
18959 path.map(pathChild => {
18960 const prevNode = node.nodes[i - 1];
18962 if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") {
18963 const childNode = pathChild.getValue();
18964 parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode)));
18966 parts.push(pathChild.call(print));
18969 if (i !== node.nodes.length - 1) {
18970 if (node.nodes[i + 1].type === "css-comment" && !hasNewline$3(options.originalText, options.locStart(node.nodes[i + 1]), {
18972 }) && 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") {
18975 parts.push(options.__isHTMLStyleAttribute ? line$2 : hardline$4);
18977 if (isNextLineEmpty$2(options.originalText, pathChild.getValue(), options.locEnd) && node.nodes[i].type !== "yaml" && node.nodes[i].type !== "toml") {
18978 parts.push(hardline$4);
18985 return concat$5(parts);
18988 const STRING_REGEX$3 = /(['"])(?:(?!\1)[^\\]|\\[\s\S])*\1/g;
18989 const NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g;
18990 const STANDARD_UNIT_REGEX = /[a-zA-Z]+/g;
18991 const WORD_PART_REGEX = /[$@]?[a-zA-Z_\u0080-\uFFFF][\w\-\u0080-\uFFFF]*/g;
18992 const ADJUST_NUMBERS_REGEX = new RegExp(STRING_REGEX$3.source + "|" + "(".concat(WORD_PART_REGEX.source, ")?") + "(".concat(NUMBER_REGEX.source, ")") + "(".concat(STANDARD_UNIT_REGEX.source, ")?"), "g");
18994 function adjustStrings(value, options) {
18995 return value.replace(STRING_REGEX$3, match => printString$1(match, options));
18998 function quoteAttributeValue(value, options) {
18999 const quote = options.singleQuote ? "'" : '"';
19000 return value.includes('"') || value.includes("'") ? value : quote + value + quote;
19003 function adjustNumbers(value) {
19004 return value.replace(ADJUST_NUMBERS_REGEX, (match, quote, wordPart, number, unit) => !wordPart && number ? printCssNumber(number) + maybeToLowerCase$1(unit || "") : match);
19007 function printCssNumber(rawNumber) {
19008 return printNumber$1(rawNumber) // Remove trailing `.0`.
19009 .replace(/\.0(?=$|e)/, "");
19012 var printerPostcss = {
19013 print: genericPrint,
19015 insertPragma: insertPragma$2,
19016 hasPrettierIgnore: hasIgnoreComment$1,
19017 massageAstNode: clean_1
19020 const CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
19022 var commonOptions = {
19025 category: CATEGORY_COMMON,
19028 description: "Print spaces between brackets.",
19029 oppositeDescription: "Do not print spaces between brackets."
19033 category: CATEGORY_COMMON,
19036 description: "Use single quotes instead of double quotes."
19040 category: CATEGORY_COMMON,
19049 description: "How to wrap prose.",
19053 description: "Wrap prose if it exceeds the print width."
19057 description: "Do not wrap prose."
19061 description: "Wrap prose as-is."
19067 singleQuote: commonOptions.singleQuote
19070 var createLanguage = function createLanguage(linguistData, override) {
19074 rest = _objectWithoutPropertiesLoose(linguistData, ["languageId"]);
19076 return Object.assign({
19077 linguistLanguageId: languageId
19078 }, rest, {}, override(linguistData));
19081 var name$1 = "CSS";
19082 var type = "markup";
19083 var tmScope = "source.css";
19084 var aceMode = "css";
19085 var codemirrorMode = "css";
19086 var codemirrorMimeType = "text/css";
19087 var color = "#563d7c";
19091 var languageId = 50;
19097 codemirrorMode: codemirrorMode,
19098 codemirrorMimeType: codemirrorMimeType,
19100 extensions: extensions,
19101 languageId: languageId
19104 var CSS$1 = /*#__PURE__*/Object.freeze({
19110 codemirrorMode: codemirrorMode,
19111 codemirrorMimeType: codemirrorMimeType,
19113 extensions: extensions,
19114 languageId: languageId,
19118 var name$2 = "PostCSS";
19119 var type$1 = "markup";
19120 var tmScope$1 = "source.postcss";
19121 var group$2 = "CSS";
19122 var extensions$1 = [
19126 var aceMode$1 = "text";
19127 var languageId$1 = 262764437;
19131 tmScope: tmScope$1,
19133 extensions: extensions$1,
19134 aceMode: aceMode$1,
19135 languageId: languageId$1
19138 var PostCSS$1 = /*#__PURE__*/Object.freeze({
19142 tmScope: tmScope$1,
19144 extensions: extensions$1,
19145 aceMode: aceMode$1,
19146 languageId: languageId$1,
19150 var name$3 = "Less";
19151 var type$2 = "markup";
19152 var group$3 = "CSS";
19153 var extensions$2 = [
19156 var tmScope$2 = "source.css.less";
19157 var aceMode$2 = "less";
19158 var codemirrorMode$1 = "css";
19159 var codemirrorMimeType$1 = "text/css";
19160 var languageId$2 = 198;
19165 extensions: extensions$2,
19166 tmScope: tmScope$2,
19167 aceMode: aceMode$2,
19168 codemirrorMode: codemirrorMode$1,
19169 codemirrorMimeType: codemirrorMimeType$1,
19170 languageId: languageId$2
19173 var Less$1 = /*#__PURE__*/Object.freeze({
19178 extensions: extensions$2,
19179 tmScope: tmScope$2,
19180 aceMode: aceMode$2,
19181 codemirrorMode: codemirrorMode$1,
19182 codemirrorMimeType: codemirrorMimeType$1,
19183 languageId: languageId$2,
19187 var name$4 = "SCSS";
19188 var type$3 = "markup";
19189 var tmScope$3 = "source.css.scss";
19190 var group$4 = "CSS";
19191 var aceMode$3 = "scss";
19192 var codemirrorMode$2 = "css";
19193 var codemirrorMimeType$2 = "text/x-scss";
19194 var extensions$3 = [
19197 var languageId$3 = 329;
19201 tmScope: tmScope$3,
19203 aceMode: aceMode$3,
19204 codemirrorMode: codemirrorMode$2,
19205 codemirrorMimeType: codemirrorMimeType$2,
19206 extensions: extensions$3,
19207 languageId: languageId$3
19210 var SCSS$1 = /*#__PURE__*/Object.freeze({
19214 tmScope: tmScope$3,
19216 aceMode: aceMode$3,
19217 codemirrorMode: codemirrorMode$2,
19218 codemirrorMimeType: codemirrorMimeType$2,
19219 extensions: extensions$3,
19220 languageId: languageId$3,
19224 var require$$0$2 = getCjsExportFromNamespace(CSS$1);
19226 var require$$1 = getCjsExportFromNamespace(PostCSS$1);
19228 var require$$2 = getCjsExportFromNamespace(Less$1);
19230 var require$$3 = getCjsExportFromNamespace(SCSS$1);
19232 const languages = [createLanguage(require$$0$2, () => ({
19235 vscodeLanguageIds: ["css"]
19236 })), createLanguage(require$$1, () => ({
19239 vscodeLanguageIds: ["postcss"]
19240 })), createLanguage(require$$2, () => ({
19243 vscodeLanguageIds: ["less"]
19244 })), createLanguage(require$$3, () => ({
19247 vscodeLanguageIds: ["scss"]
19250 postcss: printerPostcss
19252 var languageCss = {
19254 options: options$2,
19258 function hasPragma$2(text) {
19259 return /^\s*#[^\n\S]*@(format|prettier)\s*(\n|$)/.test(text);
19262 function insertPragma$3(text) {
19263 return "# @format\n\n" + text;
19267 hasPragma: hasPragma$2,
19268 insertPragma: insertPragma$3
19274 hardline: hardline$5,
19276 softline: softline$2,
19280 } = document.builders;
19282 hasIgnoreComment: hasIgnoreComment$2
19285 isNextLineEmpty: isNextLineEmpty$3
19288 insertPragma: insertPragma$4
19291 function genericPrint$1(path, options, print) {
19292 const n = path.getValue();
19298 if (typeof n === "string") {
19306 path.map((pathChild, index) => {
19307 parts.push(concat$6([pathChild.call(print)]));
19309 if (index !== n.definitions.length - 1) {
19310 parts.push(hardline$5);
19312 if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), options.locEnd)) {
19313 parts.push(hardline$5);
19317 return concat$6([concat$6(parts), hardline$5]);
19320 case "OperationDefinition":
19322 const hasOperation = options.originalText[options.locStart(n)] !== "{";
19323 const hasName = !!n.name;
19324 return concat$6([hasOperation ? n.operation : "", hasOperation && hasName ? concat$6([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "variableDefinitions"))])), softline$2, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]);
19327 case "FragmentDefinition":
19329 return concat$6(["fragment ", path.call(print, "name"), n.variableDefinitions && n.variableDefinitions.length ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "variableDefinitions"))])), softline$2, ")"])) : "", " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
19332 case "SelectionSet":
19334 return concat$6(["{", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(selectionsPath => printSequence(selectionsPath, options, print), "selections"))])), hardline$5, "}"]);
19339 return group$5(concat$6([n.alias ? concat$6([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")]));
19347 case "StringValue":
19350 return concat$6(['"""', hardline$5, join$3(hardline$5, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$5, '"""']);
19353 return concat$6(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']);
19363 case "BooleanValue":
19365 return n.value ? "true" : "false";
19375 return concat$6(["$", path.call(print, "name")]);
19380 return group$5(concat$6(["[", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "values"))])), softline$2, "]"]));
19383 case "ObjectValue":
19385 return group$5(concat$6(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.map(print, "fields"))])), softline$2, ifBreak$2("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"]));
19388 case "ObjectField":
19391 return concat$6([path.call(print, "name"), ": ", path.call(print, "value")]);
19396 return concat$6(["@", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : ""]);
19401 return path.call(print, "name");
19404 case "VariableDefinition":
19406 return concat$6([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$6([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
19409 case "TypeExtensionDefinition":
19411 return concat$6(["extend ", path.call(print, "definition")]);
19414 case "ObjectTypeExtension":
19415 case "ObjectTypeDefinition":
19417 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$6([" implements ", concat$6(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$5, "}"]) : ""]);
19420 case "FieldDefinition":
19422 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]);
19425 case "DirectiveDefinition":
19427 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$5(concat$6(["(", indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", ", "), softline$2]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$2, ")"])) : "", n.repeatable ? " repeatable" : "", concat$6([" on ", join$3(" | ", path.map(print, "locations"))])]);
19430 case "EnumTypeExtension":
19431 case "EnumTypeDefinition":
19433 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(valuesPath => printSequence(valuesPath, options, print), "values"))])), hardline$5, "}"]) : ""]);
19436 case "EnumValueDefinition":
19438 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", path.call(print, "name"), printDirectives(path, print, n)]);
19441 case "InputValueDefinition":
19443 return concat$6([path.call(print, "description"), n.description ? n.description.block ? hardline$5 : line$3 : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$6([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]);
19446 case "InputObjectTypeExtension":
19447 case "InputObjectTypeDefinition":
19449 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$5, "}"]) : ""]);
19452 case "SchemaDefinition":
19454 return concat$6(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(opsPath => printSequence(opsPath, options, print), "operationTypes"))])) : "", hardline$5, "}"]);
19457 case "OperationTypeDefinition":
19459 return concat$6([path.call(print, "operation"), ": ", path.call(print, "type")]);
19462 case "InterfaceTypeExtension":
19463 case "InterfaceTypeDefinition":
19465 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$6([" {", indent$3(concat$6([hardline$5, join$3(hardline$5, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$5, "}"]) : ""]);
19468 case "FragmentSpread":
19470 return concat$6(["...", path.call(print, "name"), printDirectives(path, print, n)]);
19473 case "InlineFragment":
19475 return concat$6(["...", n.typeCondition ? concat$6([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]);
19478 case "UnionTypeExtension":
19479 case "UnionTypeDefinition":
19481 return group$5(concat$6([path.call(print, "description"), n.description ? hardline$5 : "", group$5(concat$6([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$6([" =", ifBreak$2("", " "), indent$3(concat$6([ifBreak$2(concat$6([line$3, " "])), join$3(concat$6([line$3, "| "]), path.map(print, "types"))]))]) : ""]))]));
19484 case "ScalarTypeExtension":
19485 case "ScalarTypeDefinition":
19487 return concat$6([path.call(print, "description"), n.description ? hardline$5 : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]);
19490 case "NonNullType":
19492 return concat$6([path.call(print, "type"), "!"]);
19497 return concat$6(["[", path.call(print, "type"), "]"]);
19501 /* istanbul ignore next */
19502 throw new Error("unknown graphql type: " + JSON.stringify(n.kind));
19506 function printDirectives(path, print, n) {
19507 if (n.directives.length === 0) {
19511 return concat$6([" ", group$5(indent$3(concat$6([softline$2, join$3(concat$6([ifBreak$2("", " "), softline$2]), path.map(print, "directives"))])))]);
19514 function printSequence(sequencePath, options, print) {
19515 const count = sequencePath.getValue().length;
19516 return sequencePath.map((path, i) => {
19517 const printed = print(path);
19519 if (isNextLineEmpty$3(options.originalText, path.getValue(), options.locEnd) && i < count - 1) {
19520 return concat$6([printed, hardline$5]);
19527 function canAttachComment(node) {
19528 return node.kind && node.kind !== "Comment";
19531 function printComment$1(commentPath) {
19532 const comment = commentPath.getValue();
19534 if (comment.kind === "Comment") {
19535 return "#" + comment.value.trimEnd();
19538 throw new Error("Not a comment: " + JSON.stringify(comment));
19541 function determineInterfaceSeparatorBetween(first, second, options) {
19542 const textBetween = options.originalText.slice(first.loc.end, second.loc.start).replace(/#.*/g, "").trim();
19543 return textBetween === "," ? ", " : " & ";
19546 function printInterfaces(path, options, print) {
19547 const node = path.getNode();
19552 const printed = path.map(node => print(node), "interfaces");
19554 for (let index = 0; index < interfaces.length; index++) {
19555 const interfaceNode = interfaces[index];
19558 parts.push(determineInterfaceSeparatorBetween(interfaces[index - 1], interfaceNode, options));
19561 parts.push(printed[index]);
19567 function clean$1(node, newNode
19570 delete newNode.loc;
19571 delete newNode.comments;
19574 var printerGraphql = {
19575 print: genericPrint$1,
19576 massageAstNode: clean$1,
19577 hasPrettierIgnore: hasIgnoreComment$2,
19578 insertPragma: insertPragma$4,
19579 printComment: printComment$1,
19584 bracketSpacing: commonOptions.bracketSpacing
19587 var name$5 = "GraphQL";
19588 var type$4 = "data";
19589 var extensions$4 = [
19594 var tmScope$4 = "source.graphql";
19595 var aceMode$4 = "text";
19596 var languageId$4 = 139;
19600 extensions: extensions$4,
19601 tmScope: tmScope$4,
19602 aceMode: aceMode$4,
19603 languageId: languageId$4
19606 var GraphQL$1 = /*#__PURE__*/Object.freeze({
19610 extensions: extensions$4,
19611 tmScope: tmScope$4,
19612 aceMode: aceMode$4,
19613 languageId: languageId$4,
19617 var require$$0$3 = getCjsExportFromNamespace(GraphQL$1);
19619 const languages$1 = [createLanguage(require$$0$3, () => ({
19621 parsers: ["graphql"],
19622 vscodeLanguageIds: ["graphql"]
19624 const printers$1 = {
19625 graphql: printerGraphql
19627 var languageGraphql = {
19628 languages: languages$1,
19629 options: options$3,
19630 printers: printers$1
19633 var clean$2 = function clean(ast, newNode) {
19634 delete newNode.loc;
19635 delete newNode.selfClosing; // (Glimmer/HTML) ignore TextNode whitespace
19637 if (ast.type === "TextNode") {
19638 const trimmed = ast.chars.trim();
19644 newNode.chars = trimmed;
19648 function isUppercase(string) {
19649 return string.toUpperCase() === string;
19652 function isGlimmerComponent(node) {
19653 return isNodeOfSomeType(node, ["ElementNode"]) && typeof node.tag === "string" && (isUppercase(node.tag[0]) || node.tag.includes("."));
19656 function isWhitespaceNode(node) {
19657 return isNodeOfSomeType(node, ["TextNode"]) && !/\S/.test(node.chars);
19660 function isNodeOfSomeType(node, types) {
19661 return node && types.some(type => node.type === type);
19664 function isParentOfSomeType(path, types) {
19665 const parentNode = path.getParentNode(0);
19666 return isNodeOfSomeType(parentNode, types);
19669 function isPreviousNodeOfSomeType(path, types) {
19670 const previousNode = getPreviousNode(path);
19671 return isNodeOfSomeType(previousNode, types);
19674 function isNextNodeOfSomeType(path, types) {
19675 const nextNode = getNextNode(path);
19676 return isNodeOfSomeType(nextNode, types);
19679 function getSiblingNode(path, offset) {
19680 const node = path.getValue();
19681 const parentNode = path.getParentNode(0) || {};
19682 const children = parentNode.children || parentNode.body || [];
19683 const index = children.indexOf(node);
19684 return index !== -1 && children[index + offset];
19687 function getPreviousNode(path, lookBack = 1) {
19688 return getSiblingNode(path, -lookBack);
19691 function getNextNode(path) {
19692 return getSiblingNode(path, 1);
19695 function isPrettierIgnoreNode(node) {
19696 return isNodeOfSomeType(node, ["MustacheCommentStatement"]) && typeof node.value === "string" && node.value.trim() === "prettier-ignore";
19699 function hasPrettierIgnore(path) {
19700 const node = path.getValue();
19701 const previousPreviousNode = getPreviousNode(path, 2);
19702 return isPrettierIgnoreNode(node) || isPrettierIgnoreNode(previousPreviousNode);
19709 isGlimmerComponent,
19710 isNextNodeOfSomeType,
19712 isParentOfSomeType,
19713 isPreviousNodeOfSomeType,
19720 softline: softline$3,
19721 hardline: hardline$6,
19726 } = document.builders;
19728 getNextNode: getNextNode$1,
19729 getPreviousNode: getPreviousNode$1,
19730 hasPrettierIgnore: hasPrettierIgnore$1,
19731 isGlimmerComponent: isGlimmerComponent$1,
19732 isNextNodeOfSomeType: isNextNodeOfSomeType$1,
19733 isParentOfSomeType: isParentOfSomeType$1,
19734 isPreviousNodeOfSomeType: isPreviousNodeOfSomeType$1,
19735 isWhitespaceNode: isWhitespaceNode$1
19736 } = utils$3; // http://w3c.github.io/html/single-page.html#void-elements
19738 const voidTags = ["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]; // Formatter based on @glimmerjs/syntax's built-in test formatter:
19739 // https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts
19741 function print(path, options, print) {
19742 const n = path.getValue();
19743 /* istanbul ignore if*/
19749 if (hasPrettierIgnore$1(path)) {
19750 const startOffset = locationToOffset(options.originalText, n.loc.start.line - 1, n.loc.start.column);
19751 const endOffset = locationToOffset(options.originalText, n.loc.end.line - 1, n.loc.end.column);
19752 const ignoredText = options.originalText.slice(startOffset, endOffset);
19753 return ignoredText;
19761 return group$6(concat$7(path.map(print, "body")));
19764 case "ElementNode":
19766 const hasChildren = n.children.length > 0;
19767 const hasNonWhitespaceChildren = n.children.some(n => !isWhitespaceNode$1(n));
19768 const isVoid = isGlimmerComponent$1(n) && (!hasChildren || !hasNonWhitespaceChildren) || voidTags.includes(n.tag);
19769 const closeTagForNoBreak = isVoid ? concat$7([" />", softline$3]) : ">";
19770 const closeTagForBreak = isVoid ? "/>" : ">";
19772 const printParams = (path, print) => indent$4(concat$7([n.attributes.length ? line$4 : "", join$4(line$4, path.map(print, "attributes")), n.modifiers.length ? line$4 : "", join$4(line$4, path.map(print, "modifiers")), n.comments.length ? line$4 : "", join$4(line$4, path.map(print, "comments"))]));
19774 const nextNode = getNextNode$1(path);
19775 return concat$7([group$6(concat$7(["<", n.tag, printParams(path, print), n.blockParams.length ? " as |".concat(n.blockParams.join(" "), "|") : "", ifBreak$3(softline$3, ""), ifBreak$3(closeTagForBreak, closeTagForNoBreak)])), !isVoid ? group$6(concat$7([hasNonWhitespaceChildren ? indent$4(printChildren(path, options, print)) : "", ifBreak$3(hasChildren ? hardline$6 : "", ""), concat$7(["</", n.tag, ">"])])) : "", nextNode && nextNode.type === "ElementNode" ? hardline$6 : ""]);
19778 case "BlockStatement":
19780 const pp = path.getParentNode(1);
19781 const isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if";
19782 const hasElseIf = n.inverse && n.inverse.body.length === 1 && n.inverse.body[0].type === "BlockStatement" && n.inverse.body[0].path.parts[0] === "if";
19783 const indentElse = hasElseIf ? a => a : indent$4;
19784 const inverseElseStatement = (n.inverseStrip.open ? "{{~" : "{{") + "else" + (n.inverseStrip.close ? "~}}" : "}}");
19787 return concat$7([isElseIf ? concat$7([n.openStrip.open ? "{{~else " : "{{else ", printPathParams(path, print), n.openStrip.close ? "~}}" : "}}"]) : printOpenBlock(path, print, n.openStrip), indent$4(concat$7([hardline$6, path.call(print, "program")])), n.inverse && !hasElseIf ? concat$7([hardline$6, inverseElseStatement]) : "", n.inverse ? indentElse(concat$7([hardline$6, path.call(print, "inverse")])) : "", isElseIf ? "" : concat$7([hardline$6, printCloseBlock(path, print, n.closeStrip)])]);
19788 } else if (isElseIf) {
19789 return concat$7([concat$7([n.openStrip.open ? "{{~else" : "{{else ", printPathParams(path, print), n.openStrip.close ? "~}}" : "}}"]), indent$4(concat$7([hardline$6, path.call(print, "program")]))]);
19792 const hasNonWhitespaceChildren = n.program.body.some(n => !isWhitespaceNode$1(n));
19793 return concat$7([printOpenBlock(path, print, n.openStrip), group$6(concat$7([indent$4(concat$7([softline$3, path.call(print, "program")])), hasNonWhitespaceChildren ? hardline$6 : softline$3, printCloseBlock(path, print, n.closeStrip)]))]);
19796 case "ElementModifierStatement":
19798 return group$6(concat$7(["{{", printPathParams(path, print), softline$3, "}}"]));
19801 case "MustacheStatement":
19803 const isEscaped = n.escaped === false;
19808 const opening = (isEscaped ? "{{{" : "{{") + (openStrip ? "~" : "");
19809 const closing = (closeStrip ? "~" : "") + (isEscaped ? "}}}" : "}}");
19810 const leading = isParentOfSomeType$1(path, ["AttrNode", "ConcatStatement", "ElementNode"]) ? [opening, indent$4(softline$3)] : [opening];
19811 return group$6(concat$7([...leading, printPathParams(path, print), softline$3, closing]));
19814 case "SubExpression":
19816 const params = printParams(path, print);
19817 const printedParams = params.length > 0 ? indent$4(concat$7([line$4, group$6(join$4(line$4, params))])) : "";
19818 return group$6(concat$7(["(", printPath(path, print), printedParams, softline$3, ")"]));
19823 const isText = n.value.type === "TextNode";
19824 const isEmptyText = isText && n.value.chars === ""; // If the text is empty and the value's loc start and end columns are the
19825 // same, there is no value for this AttrNode and it should be printed
19826 // without the `=""`. Example: `<img data-test>` -> `<img data-test>`
19828 const isEmptyValue = isEmptyText && n.value.loc.start.column === n.value.loc.end.column;
19830 if (isEmptyValue) {
19831 return concat$7([n.name]);
19834 const value = path.call(print, "value");
19835 const quotedValue = isText ? printStringLiteral(value.parts.join(), options) : value;
19836 return concat$7([n.name, "=", quotedValue]);
19839 case "ConcatStatement":
19841 return concat$7(['"', concat$7(path.map(partPath => print(partPath), "parts").filter(a => a !== "")), '"']);
19846 return concat$7([join$4(line$4, path.map(print, "pairs"))]);
19851 return concat$7([n.key, "=", path.call(print, "value")]);
19856 const maxLineBreaksToPreserve = 2;
19857 const isFirstElement = !getPreviousNode$1(path);
19858 const isLastElement = !getNextNode$1(path);
19859 const isWhitespaceOnly = !/\S/.test(n.chars);
19860 const lineBreaksCount = countNewLines(n.chars);
19861 const hasBlockParent = path.getParentNode(0).type === "Block";
19862 const hasElementParent = path.getParentNode(0).type === "ElementNode";
19863 const hasTemplateParent = path.getParentNode(0).type === "Template";
19864 let leadingLineBreaksCount = countLeadingNewLines(n.chars);
19865 let trailingLineBreaksCount = countTrailingNewLines(n.chars);
19867 if ((isFirstElement || isLastElement) && isWhitespaceOnly && (hasBlockParent || hasElementParent || hasTemplateParent)) {
19871 if (isWhitespaceOnly && lineBreaksCount) {
19872 leadingLineBreaksCount = Math.min(lineBreaksCount, maxLineBreaksToPreserve);
19873 trailingLineBreaksCount = 0;
19875 if (isNextNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) {
19876 trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1);
19879 if (isPreviousNodeOfSomeType$1(path, ["ElementNode"]) || isPreviousNodeOfSomeType$1(path, ["BlockStatement"])) {
19880 leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1);
19884 let leadingSpace = "";
19885 let trailingSpace = ""; // preserve a space inside of an attribute node where whitespace present,
19886 // when next to mustache statement.
19888 const inAttrNode = path.stack.includes("attributes");
19891 const parentNode = path.getParentNode(0);
19892 const isConcat = parentNode.type === "ConcatStatement";
19898 const partIndex = parts.indexOf(n);
19900 if (partIndex > 0) {
19901 const partType = parts[partIndex - 1].type;
19902 const isMustache = partType === "MustacheStatement";
19905 leadingSpace = " ";
19909 if (partIndex < parts.length - 1) {
19910 const partType = parts[partIndex + 1].type;
19911 const isMustache = partType === "MustacheStatement";
19914 trailingSpace = " ";
19919 if (trailingLineBreaksCount === 0 && isNextNodeOfSomeType$1(path, ["MustacheStatement"])) {
19920 trailingSpace = " ";
19923 if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) {
19924 leadingSpace = " ";
19927 if (isFirstElement) {
19928 leadingLineBreaksCount = 0;
19932 if (isLastElement) {
19933 trailingLineBreaksCount = 0;
19934 trailingSpace = "";
19938 return concat$7([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), n.chars.replace(/^[\s ]+/g, leadingSpace).replace(/[\s ]+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)].filter(Boolean));
19941 case "MustacheCommentStatement":
19943 const dashes = n.value.includes("}}") ? "--" : "";
19944 return concat$7(["{{!", dashes, n.value, dashes, "}}"]);
19947 case "PathExpression":
19952 case "BooleanLiteral":
19954 return String(n.value);
19957 case "CommentStatement":
19959 return concat$7(["<!--", n.value, "-->"]);
19962 case "StringLiteral":
19964 return printStringLiteral(n.value, options);
19967 case "NumberLiteral":
19969 return String(n.value);
19972 case "UndefinedLiteral":
19974 return "undefined";
19977 case "NullLiteral":
19982 /* istanbul ignore next */
19985 throw new Error("unknown glimmer type: " + JSON.stringify(n.type));
19989 function printChildren(path, options, print) {
19990 return concat$7(path.map((childPath, childIndex) => {
19991 const childNode = path.getValue();
19992 const isFirstNode = childIndex === 0;
19993 const isLastNode = childIndex === path.getParentNode(0).children.length - 1;
19994 const isLastNodeInMultiNodeList = isLastNode && !isFirstNode;
19995 const isWhitespace = isWhitespaceNode$1(childNode);
19997 if (isWhitespace && isLastNodeInMultiNodeList) {
19998 return print(childPath, options, print);
19999 } else if (isFirstNode) {
20000 return concat$7([softline$3, print(childPath, options, print)]);
20003 return print(childPath, options, print);
20007 * Prints a string literal with the correct surrounding quotes based on
20008 * `options.singleQuote` and the number of escaped quotes contained in
20009 * the string literal. This function is the glimmer equivalent of `printString`
20010 * in `common/util`, but has differences because of the way escaped characters
20011 * are treated in hbs string literals.
20012 * @param {string} stringLiteral - the string literal value
20013 * @param {object} options - the prettier options object
20017 function printStringLiteral(stringLiteral, options) {
20026 const preferred = options.singleQuote ? single : double;
20027 const alternate = preferred === single ? double : single;
20028 let shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for
20029 // enclosing the string, we might want to enclose with the alternate quote
20030 // instead, to minimize the number of escaped quotes.
20032 if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) {
20033 const numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length;
20034 const numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length;
20035 shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes;
20038 const enclosingQuote = shouldUseAlternateQuote ? alternate : preferred;
20039 const escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, "\\".concat(enclosingQuote.quote));
20040 return concat$7([enclosingQuote.quote, escapedStringLiteral, enclosingQuote.quote]);
20043 function printPath(path, print) {
20044 return path.call(print, "path");
20047 function printParams(path, print) {
20048 const node = path.getValue();
20051 if (node.params.length > 0) {
20052 parts = parts.concat(path.map(print, "params"));
20055 if (node.hash && node.hash.pairs.length > 0) {
20056 parts.push(path.call(print, "hash"));
20062 function printPathParams(path, print) {
20063 const printedPath = printPath(path, print);
20064 const printedParams = printParams(path, print);
20065 const parts = [printedPath, ...printedParams];
20066 return indent$4(group$6(join$4(line$4, parts)));
20069 function printBlockParams(path) {
20070 const block = path.getValue();
20072 if (!block.program || !block.program.blockParams.length) {
20076 return concat$7([" as |", block.program.blockParams.join(" "), "|"]);
20079 function printOpenBlock(path, print, {
20080 open: isOpenStrip = false,
20081 close: isCloseStrip = false
20083 return group$6(concat$7([isOpenStrip ? "{{~#" : "{{#", printPathParams(path, print), printBlockParams(path), softline$3, isCloseStrip ? "~}}" : "}}"]));
20086 function printCloseBlock(path, print, {
20087 open: isOpenStrip = false,
20088 close: isCloseStrip = false
20090 return concat$7([isOpenStrip ? "{{~/" : "{{/", path.call(print, "path"), isCloseStrip ? "~}}" : "}}"]);
20093 function countNewLines(string) {
20094 /* istanbul ignore next */
20095 string = typeof string === "string" ? string : "";
20096 return string.split("\n").length - 1;
20099 function countLeadingNewLines(string) {
20100 /* istanbul ignore next */
20101 string = typeof string === "string" ? string : "";
20102 const newLines = (string.match(/^([^\S\r\n]*[\r\n])+/g) || [])[0] || "";
20103 return countNewLines(newLines);
20106 function countTrailingNewLines(string) {
20107 /* istanbul ignore next */
20108 string = typeof string === "string" ? string : "";
20109 const newLines = (string.match(/([\r\n][^\S\r\n]*)+$/g) || [])[0] || "";
20110 return countNewLines(newLines);
20113 function generateHardlines(number = 0, max = 0) {
20114 return new Array(Math.min(number, max)).fill(hardline$6);
20116 /* istanbul ignore next
20117 https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/compiler/lib/location.ts#L5-L29
20121 function locationToOffset(source, line, column) {
20123 let seenChars = 0; // eslint-disable-next-line no-constant-condition
20126 if (seenChars === source.length) {
20130 let nextLine = source.indexOf("\n", seenChars);
20132 if (nextLine === -1) {
20133 nextLine = source.length;
20136 if (seenLines === line) {
20137 if (seenChars + column > nextLine) {
20141 return seenChars + column;
20142 } else if (nextLine === -1) {
20147 seenChars = nextLine + 1;
20151 var printerGlimmer = {
20153 massageAstNode: clean$2
20156 var name$6 = "Handlebars";
20157 var type$5 = "markup";
20158 var group$7 = "HTML";
20163 var extensions$5 = [
20167 var tmScope$5 = "text.html.handlebars";
20168 var aceMode$5 = "handlebars";
20169 var languageId$5 = 155;
20175 extensions: extensions$5,
20176 tmScope: tmScope$5,
20177 aceMode: aceMode$5,
20178 languageId: languageId$5
20181 var Handlebars$1 = /*#__PURE__*/Object.freeze({
20187 extensions: extensions$5,
20188 tmScope: tmScope$5,
20189 aceMode: aceMode$5,
20190 languageId: languageId$5,
20191 'default': Handlebars
20194 var require$$0$4 = getCjsExportFromNamespace(Handlebars$1);
20196 const languages$2 = [createLanguage(require$$0$4, () => ({
20199 parsers: ["glimmer"],
20200 vscodeLanguageIds: ["handlebars"]
20202 const printers$2 = {
20203 glimmer: printerGlimmer
20205 var languageHandlebars = {
20206 languages: languages$2,
20207 printers: printers$2
20210 var clean$3 = function clean(ast, newNode) {
20211 delete newNode.sourceSpan;
20212 delete newNode.startSourceSpan;
20213 delete newNode.endSourceSpan;
20214 delete newNode.nameSpan;
20215 delete newNode.valueSpan;
20217 if (ast.type === "text" || ast.type === "comment") {
20219 } // may be formatted by multiparser
20222 if (ast.type === "yaml" || ast.type === "toml") {
20226 if (ast.type === "attribute") {
20227 delete newNode.value;
20230 if (ast.type === "docType") {
20231 delete newNode.value;
20236 "CSS_DISPLAY_TAGS": {
20239 "basefont": "none",
20240 "datalist": "none",
20245 "noframes": "none",
20251 "template": "inline",
20256 "address": "block",
20257 "blockquote": "block",
20261 "figcaption": "block",
20267 "listing": "block",
20270 "plaintext": "block",
20273 "slot": "contents",
20276 "article": "block",
20286 "section": "block",
20295 "caption": "table-caption",
20296 "colgroup": "table-column-group",
20297 "col": "table-column",
20298 "thead": "table-header-group",
20299 "tbody": "table-row-group",
20300 "tfoot": "table-footer-group",
20302 "td": "table-cell",
20303 "th": "table-cell",
20304 "fieldset": "block",
20305 "button": "inline-block",
20306 "video": "inline-block",
20307 "audio": "inline-block"
20309 "CSS_DISPLAY_DEFAULT": "inline",
20310 "CSS_WHITE_SPACE_TAGS": {
20312 "plaintext": "pre",
20316 "table": "initial",
20317 "textarea": "pre-wrap"
20319 "CSS_WHITE_SPACE_DEFAULT": "normal"
20473 var htmlTagNames = /*#__PURE__*/Object.freeze({
20701 "allowpaymentrequest",
21083 basefont: basefont,
21085 blockquote: blockquote,
21092 colgroup: colgroup,
21102 fieldset: fieldset,
21106 frameset: frameset,
21131 optgroup: optgroup,
21137 progress: progress,
21147 textarea: textarea,
21158 var htmlElementAttributes = /*#__PURE__*/Object.freeze({
21166 basefont: basefont,
21168 blockquote: blockquote,
21175 colgroup: colgroup,
21185 fieldset: fieldset,
21189 frameset: frameset,
21214 optgroup: optgroup,
21220 progress: progress,
21230 textarea: textarea,
21242 var htmlTagNames$1 = getCjsExportFromNamespace(htmlTagNames);
21244 var htmlElementAttributes$1 = getCjsExportFromNamespace(htmlElementAttributes);
21248 CSS_DISPLAY_DEFAULT,
21249 CSS_WHITE_SPACE_TAGS,
21250 CSS_WHITE_SPACE_DEFAULT
21252 const HTML_TAGS = arrayToMap(htmlTagNames$1);
21253 const HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes$1, arrayToMap);
21255 function arrayToMap(array) {
21256 const map = Object.create(null);
21258 for (const value of array) {
21265 function mapObject(object, fn) {
21266 const newObject = Object.create(null);
21268 for (const key of Object.keys(object)) {
21269 newObject[key] = fn(object[key], key);
21275 function shouldPreserveContent(node, options) {
21276 if (!node.endSourceSpan) {
21280 if (node.type === "element" && node.fullName === "template" && node.attrMap.lang && node.attrMap.lang !== "html") {
21282 } // unterminated node in ie conditional comment
21283 // e.g. <!--[if lt IE 9]><html><![endif]-->
21286 if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) {
21288 } // incomplete html in ie conditional comment
21289 // e.g. <!--[if lt IE 9]></div><![endif]-->
21292 if (node.type === "ieConditionalComment" && !node.complete) {
21294 } // top-level elements (excluding <template>, <style> and <script>) in Vue SFC are considered custom block
21295 // custom blocks can be written in other languages so we should preserve them to not break the code
21298 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>
21299 "html"].includes(node.fullName)) {
21301 } // TODO: handle non-text children in <pre>
21304 if (isPreLikeNode(node) && node.children.some(child => child.type !== "text" && child.type !== "interpolation")) {
21311 function hasPrettierIgnore$2(node) {
21312 if (node.type === "attribute") {
21316 if (!node.parent) {
21320 if (typeof node.index !== "number" || node.index === 0) {
21324 const prevNode = node.parent.children[node.index - 1];
21325 return isPrettierIgnore(prevNode);
21328 function isPrettierIgnore(node) {
21329 return node.type === "comment" && node.value.trim() === "prettier-ignore";
21332 function getPrettierIgnoreAttributeCommentData(value) {
21333 const match = value.trim().match(/^prettier-ignore-attribute(?:\s+([^]+))?$/);
21343 return match[1].split(/\s+/);
21345 /** there's no opening/closing tag or it's considered not breakable */
21348 function isTextLikeNode(node) {
21349 return node.type === "text" || node.type === "comment";
21352 function isScriptLikeTag(node) {
21353 return node.type === "element" && (node.fullName === "script" || node.fullName === "style" || node.fullName === "svg:style" || isUnknownNamespace(node) && (node.name === "script" || node.name === "style"));
21356 function isFrontMatterNode(node) {
21357 return node.type === "yaml" || node.type === "toml";
21360 function canHaveInterpolation(node) {
21361 return node.children && !isScriptLikeTag(node);
21364 function isWhitespaceSensitiveNode(node) {
21365 return isScriptLikeTag(node) || node.type === "interpolation" || isIndentationSensitiveNode(node);
21368 function isIndentationSensitiveNode(node) {
21369 return getNodeCssStyleWhiteSpace(node).startsWith("pre");
21372 function isLeadingSpaceSensitiveNode(node) {
21373 const isLeadingSpaceSensitive = _isLeadingSpaceSensitiveNode();
21375 if (isLeadingSpaceSensitive && !node.prev && node.parent && node.parent.tagDefinition && node.parent.tagDefinition.ignoreFirstLf) {
21376 return node.type === "interpolation";
21379 return isLeadingSpaceSensitive;
21381 function _isLeadingSpaceSensitiveNode() {
21382 if (isFrontMatterNode(node)) {
21386 if ((node.type === "text" || node.type === "interpolation") && node.prev && (node.prev.type === "text" || node.prev.type === "interpolation")) {
21390 if (!node.parent || node.parent.cssDisplay === "none") {
21394 if (isPreLikeNode(node.parent)) {
21398 if (!node.prev && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
21402 if (node.prev && !isNextLeadingSpaceSensitiveCssDisplay(node.prev.cssDisplay)) {
21410 function isTrailingSpaceSensitiveNode(node) {
21411 if (isFrontMatterNode(node)) {
21415 if ((node.type === "text" || node.type === "interpolation") && node.next && (node.next.type === "text" || node.next.type === "interpolation")) {
21419 if (!node.parent || node.parent.cssDisplay === "none") {
21423 if (isPreLikeNode(node.parent)) {
21427 if (!node.next && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
21431 if (node.next && !isPrevTrailingSpaceSensitiveCssDisplay(node.next.cssDisplay)) {
21438 function isDanglingSpaceSensitiveNode(node) {
21439 return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag(node);
21442 function forceNextEmptyLine(node) {
21443 return isFrontMatterNode(node) || node.next && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line;
21445 /** firstChild leadingSpaces and lastChild trailingSpaces */
21448 function forceBreakContent(node) {
21449 return forceBreakChildren(node) || node.type === "element" && node.children.length !== 0 && (["body", "script", "style"].includes(node.name) || node.children.some(child => hasNonTextChild(child))) || node.firstChild && node.firstChild === node.lastChild && hasLeadingLineBreak(node.firstChild) && (!node.lastChild.isTrailingSpaceSensitive || hasTrailingLineBreak(node.lastChild));
21451 /** spaces between children */
21454 function forceBreakChildren(node) {
21455 return node.type === "element" && node.children.length !== 0 && (["html", "head", "ul", "ol", "select"].includes(node.name) || node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell");
21458 function preferHardlineAsLeadingSpaces(node) {
21459 return preferHardlineAsSurroundingSpaces(node) || node.prev && preferHardlineAsTrailingSpaces(node.prev) || hasSurroundingLineBreak(node);
21462 function preferHardlineAsTrailingSpaces(node) {
21463 return preferHardlineAsSurroundingSpaces(node) || node.type === "element" && node.fullName === "br" || hasSurroundingLineBreak(node);
21466 function hasSurroundingLineBreak(node) {
21467 return hasLeadingLineBreak(node) && hasTrailingLineBreak(node);
21470 function hasLeadingLineBreak(node) {
21471 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);
21474 function hasTrailingLineBreak(node) {
21475 return node.hasTrailingSpaces && (node.next ? node.next.sourceSpan.start.line > node.sourceSpan.end.line : node.parent.type === "root" || node.parent.endSourceSpan && node.parent.endSourceSpan.start.line > node.sourceSpan.end.line);
21478 function preferHardlineAsSurroundingSpaces(node) {
21479 switch (node.type) {
21480 case "ieConditionalComment":
21486 return ["script", "select"].includes(node.name);
21492 function getLastDescendant(node) {
21493 return node.lastChild ? getLastDescendant(node.lastChild) : node;
21496 function hasNonTextChild(node) {
21497 return node.children && node.children.some(child => child.type !== "text");
21500 function inferScriptParser(node) {
21501 if (node.name === "script" && !node.attrMap.src) {
21502 if (!node.attrMap.lang && !node.attrMap.type || node.attrMap.type === "module" || node.attrMap.type === "text/javascript" || node.attrMap.type === "text/babel" || node.attrMap.type === "application/javascript" || node.attrMap.lang === "jsx") {
21506 if (node.attrMap.type === "application/x-typescript" || node.attrMap.lang === "ts" || node.attrMap.lang === "tsx") {
21507 return "typescript";
21510 if (node.attrMap.type === "text/markdown") {
21514 if (node.attrMap.type.endsWith("json") || node.attrMap.type.endsWith("importmap")) {
21518 if (node.attrMap.type === "text/x-handlebars-template") {
21523 if (node.name === "style") {
21524 if (!node.attrMap.lang || node.attrMap.lang === "postcss" || node.attrMap.lang === "css") {
21528 if (node.attrMap.lang === "scss") {
21532 if (node.attrMap.lang === "less") {
21540 function isBlockLikeCssDisplay(cssDisplay) {
21541 return cssDisplay === "block" || cssDisplay === "list-item" || cssDisplay.startsWith("table");
21544 function isFirstChildLeadingSpaceSensitiveCssDisplay(cssDisplay) {
21545 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
21548 function isLastChildTrailingSpaceSensitiveCssDisplay(cssDisplay) {
21549 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
21552 function isPrevTrailingSpaceSensitiveCssDisplay(cssDisplay) {
21553 return !isBlockLikeCssDisplay(cssDisplay);
21556 function isNextLeadingSpaceSensitiveCssDisplay(cssDisplay) {
21557 return !isBlockLikeCssDisplay(cssDisplay);
21560 function isDanglingSpaceSensitiveCssDisplay(cssDisplay) {
21561 return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
21564 function isPreLikeNode(node) {
21565 return getNodeCssStyleWhiteSpace(node).startsWith("pre");
21568 function countParents(path, predicate = () => true) {
21571 for (let i = path.stack.length - 1; i >= 0; i--) {
21572 const value = path.stack[i];
21574 if (value && typeof value === "object" && !Array.isArray(value) && predicate(value)) {
21582 function hasParent(node, fn) {
21583 let current = node;
21590 current = current.parent;
21596 function getNodeCssStyleDisplay(node, options) {
21597 if (node.prev && node.prev.type === "comment") {
21598 // <!-- display: block -->
21599 const match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/);
21606 let isInSvgForeignObject = false;
21608 if (node.type === "element" && node.namespace === "svg") {
21609 if (hasParent(node, parent => parent.fullName === "svg:foreignObject")) {
21610 isInSvgForeignObject = true;
21612 return node.name === "svg" ? "inline-block" : "block";
21616 switch (options.htmlWhitespaceSensitivity) {
21624 return node.type === "element" && (!node.namespace || isInSvgForeignObject || isUnknownNamespace(node)) && CSS_DISPLAY_TAGS[node.name] || CSS_DISPLAY_DEFAULT;
21628 function isUnknownNamespace(node) {
21629 return node.type === "element" && !node.hasExplicitNamespace && !["html", "svg"].includes(node.namespace);
21632 function getNodeCssStyleWhiteSpace(node) {
21633 return node.type === "element" && (!node.namespace || isUnknownNamespace(node)) && CSS_WHITE_SPACE_TAGS[node.name] || CSS_WHITE_SPACE_DEFAULT;
21636 function getMinIndentation(text) {
21637 let minIndentation = Infinity;
21639 for (const lineText of text.split("\n")) {
21640 if (lineText.length === 0) {
21644 if (/\S/.test(lineText[0])) {
21648 const indentation = lineText.match(/^\s*/)[0].length;
21650 if (lineText.length === indentation) {
21654 if (indentation < minIndentation) {
21655 minIndentation = indentation;
21659 return minIndentation === Infinity ? 0 : minIndentation;
21662 function dedentString(text, minIndent = getMinIndentation(text)) {
21663 return minIndent === 0 ? text : text.split("\n").map(lineText => lineText.slice(minIndent)).join("\n");
21666 function normalizeParts(parts) {
21667 const newParts = [];
21668 const restParts = parts.slice();
21670 while (restParts.length !== 0) {
21671 const part = restParts.shift();
21677 if (part.type === "concat") {
21678 restParts.unshift(...part.parts);
21682 if (newParts.length !== 0 && typeof newParts[newParts.length - 1] === "string" && typeof part === "string") {
21683 newParts.push(newParts.pop() + part);
21687 newParts.push(part);
21693 function identity(x) {
21697 function shouldNotPrintClosingTag(node, options) {
21698 return !node.isSelfClosing && !node.endSourceSpan && (hasPrettierIgnore$2(node) || shouldPreserveContent(node.parent, options));
21701 function countChars(text, char) {
21704 for (let i = 0; i < text.length; i++) {
21705 if (text[i] === char) {
21713 function unescapeQuoteEntities(text) {
21714 return text.replace(/'/g, "'").replace(/"/g, '"');
21718 HTML_ELEMENT_ATTRIBUTES,
21720 canHaveInterpolation,
21724 forceBreakChildren,
21726 forceNextEmptyLine,
21728 getNodeCssStyleDisplay,
21729 getNodeCssStyleWhiteSpace,
21730 getPrettierIgnoreAttributeCommentData,
21731 hasPrettierIgnore: hasPrettierIgnore$2,
21734 isDanglingSpaceSensitiveNode,
21736 isIndentationSensitiveNode,
21737 isLeadingSpaceSensitiveNode,
21741 isTrailingSpaceSensitiveNode,
21742 isWhitespaceSensitiveNode,
21743 isUnknownNamespace,
21745 preferHardlineAsLeadingSpaces,
21746 preferHardlineAsTrailingSpaces,
21747 shouldNotPrintClosingTag,
21748 shouldPreserveContent,
21749 unescapeQuoteEntities
21753 canHaveInterpolation: canHaveInterpolation$1,
21754 getNodeCssStyleDisplay: getNodeCssStyleDisplay$1,
21755 isDanglingSpaceSensitiveNode: isDanglingSpaceSensitiveNode$1,
21756 isIndentationSensitiveNode: isIndentationSensitiveNode$1,
21757 isLeadingSpaceSensitiveNode: isLeadingSpaceSensitiveNode$1,
21758 isTrailingSpaceSensitiveNode: isTrailingSpaceSensitiveNode$1,
21759 isWhitespaceSensitiveNode: isWhitespaceSensitiveNode$1
21761 const PREPROCESS_PIPELINE = [removeIgnorableFirstLf, mergeIeConditonalStartEndCommentIntoElementOpeningTag, mergeCdataIntoText, extractInterpolation, extractWhitespaces, addCssDisplay, addIsSelfClosing, addHasHtmComponentClosingTag, addIsSpaceSensitive, mergeSimpleElementIntoText];
21763 function preprocess(ast, options) {
21764 for (const fn of PREPROCESS_PIPELINE) {
21765 ast = fn(ast, options);
21771 function removeIgnorableFirstLf(ast
21774 return ast.map(node => {
21775 if (node.type === "element" && node.tagDefinition.ignoreFirstLf && node.children.length !== 0 && node.children[0].type === "text" && node.children[0].value[0] === "\n") {
21776 const [text, ...rest] = node.children;
21777 return node.clone({
21778 children: text.value.length === 1 ? rest : [text.clone({
21779 value: text.value.slice(1)
21788 function mergeIeConditonalStartEndCommentIntoElementOpeningTag(ast
21792 * <!--[if ...]><!--><target><!--<![endif]-->
21794 const isTarget = node => node.type === "element" && node.prev && node.prev.type === "ieConditionalStartComment" && node.prev.sourceSpan.end.offset === node.startSourceSpan.start.offset && node.firstChild && node.firstChild.type === "ieConditionalEndComment" && node.firstChild.sourceSpan.start.offset === node.startSourceSpan.end.offset;
21796 return ast.map(node => {
21797 if (node.children) {
21798 const isTargetResults = node.children.map(isTarget);
21800 if (isTargetResults.some(Boolean)) {
21801 const newChildren = [];
21803 for (let i = 0; i < node.children.length; i++) {
21804 const child = node.children[i];
21806 if (isTargetResults[i + 1]) {
21807 // ieConditionalStartComment
21811 if (isTargetResults[i]) {
21812 const ieConditionalStartComment = child.prev;
21813 const ieConditionalEndComment = child.firstChild;
21814 const ParseSourceSpan = child.sourceSpan.constructor;
21815 const startSourceSpan = new ParseSourceSpan(ieConditionalStartComment.sourceSpan.start, ieConditionalEndComment.sourceSpan.end);
21816 const sourceSpan = new ParseSourceSpan(startSourceSpan.start, child.sourceSpan.end);
21817 newChildren.push(child.clone({
21818 condition: ieConditionalStartComment.condition,
21821 children: child.children.slice(1)
21826 newChildren.push(child);
21829 return node.clone({
21830 children: newChildren
21839 function mergeNodeIntoText(ast, shouldMerge, getValue) {
21840 return ast.map(node => {
21841 if (node.children) {
21842 const shouldMergeResults = node.children.map(shouldMerge);
21844 if (shouldMergeResults.some(Boolean)) {
21845 const newChildren = [];
21847 for (let i = 0; i < node.children.length; i++) {
21848 const child = node.children[i];
21850 if (child.type !== "text" && !shouldMergeResults[i]) {
21851 newChildren.push(child);
21855 const newChild = child.type === "text" ? child : child.clone({
21857 value: getValue(child)
21860 if (newChildren.length === 0 || newChildren[newChildren.length - 1].type !== "text") {
21861 newChildren.push(newChild);
21865 const lastChild = newChildren.pop();
21866 const ParseSourceSpan = lastChild.sourceSpan.constructor;
21867 newChildren.push(lastChild.clone({
21868 value: lastChild.value + newChild.value,
21869 sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, newChild.sourceSpan.end)
21873 return node.clone({
21874 children: newChildren
21883 function mergeCdataIntoText(ast
21886 return mergeNodeIntoText(ast, node => node.type === "cdata", node => "<![CDATA[".concat(node.value, "]]>"));
21889 function mergeSimpleElementIntoText(ast
21892 const isSimpleElement = node => node.type === "element" && node.attrs.length === 0 && node.children.length === 1 && node.firstChild.type === "text" && // \xA0: non-breaking whitespace
21893 !/[^\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";
21895 return ast.map(node => {
21896 if (node.children) {
21897 const isSimpleElementResults = node.children.map(isSimpleElement);
21899 if (isSimpleElementResults.some(Boolean)) {
21900 const newChildren = [];
21902 for (let i = 0; i < node.children.length; i++) {
21903 const child = node.children[i];
21905 if (isSimpleElementResults[i]) {
21906 const lastChild = newChildren.pop();
21907 const nextChild = node.children[++i];
21908 const ParseSourceSpan = node.sourceSpan.constructor;
21910 isTrailingSpaceSensitive,
21913 newChildren.push(lastChild.clone({
21914 value: lastChild.value + "<".concat(child.rawName, ">") + child.firstChild.value + "</".concat(child.rawName, ">") + nextChild.value,
21915 sourceSpan: new ParseSourceSpan(lastChild.sourceSpan.start, nextChild.sourceSpan.end),
21916 isTrailingSpaceSensitive,
21920 newChildren.push(child);
21924 return node.clone({
21925 children: newChildren
21934 function extractInterpolation(ast, options) {
21935 if (options.parser === "html") {
21939 const interpolationRegex = /\{\{([\s\S]+?)\}\}/g;
21940 return ast.map(node => {
21941 if (!canHaveInterpolation$1(node)) {
21945 const newChildren = [];
21947 for (const child of node.children) {
21948 if (child.type !== "text") {
21949 newChildren.push(child);
21953 const ParseSourceSpan = child.sourceSpan.constructor;
21954 let startSourceSpan = child.sourceSpan.start;
21955 let endSourceSpan = null;
21956 const components = child.value.split(interpolationRegex);
21958 for (let i = 0; i < components.length; i++, startSourceSpan = endSourceSpan) {
21959 const value = components[i];
21962 endSourceSpan = startSourceSpan.moveBy(value.length);
21964 if (value.length !== 0) {
21968 sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan)
21975 endSourceSpan = startSourceSpan.moveBy(value.length + 4); // `{{` + `}}`
21978 type: "interpolation",
21979 sourceSpan: new ParseSourceSpan(startSourceSpan, endSourceSpan),
21980 children: value.length === 0 ? [] : [{
21983 sourceSpan: new ParseSourceSpan(startSourceSpan.moveBy(2), endSourceSpan.moveBy(-2))
21989 return node.clone({
21990 children: newChildren
21995 * - add `hasLeadingSpaces` field
21996 * - add `hasTrailingSpaces` field
21997 * - add `hasDanglingSpaces` field for parent nodes
21998 * - add `isWhitespaceSensitive`, `isIndentationSensitive` field for text nodes
21999 * - remove insensitive whitespaces
22003 function extractWhitespaces(ast
22006 const TYPE_WHITESPACE = "whitespace";
22007 return ast.map(node => {
22008 if (!node.children) {
22012 if (node.children.length === 0 || node.children.length === 1 && node.children[0].type === "text" && node.children[0].value.trim().length === 0) {
22013 return node.clone({
22015 hasDanglingSpaces: node.children.length !== 0
22019 const isWhitespaceSensitive = isWhitespaceSensitiveNode$1(node);
22020 const isIndentationSensitive = isIndentationSensitiveNode$1(node);
22021 return node.clone({
22022 isWhitespaceSensitive,
22023 isIndentationSensitive,
22024 children: node.children // extract whitespace nodes
22025 .reduce((newChildren, child) => {
22026 if (child.type !== "text" || isWhitespaceSensitive) {
22027 return newChildren.concat(child);
22030 const localChildren = [];
22031 const [, leadingSpaces, text, trailingSpaces] = child.value.match(/^(\s*)([\s\S]*?)(\s*)$/);
22033 if (leadingSpaces) {
22034 localChildren.push({
22035 type: TYPE_WHITESPACE
22039 const ParseSourceSpan = child.sourceSpan.constructor;
22042 localChildren.push({
22045 sourceSpan: new ParseSourceSpan(child.sourceSpan.start.moveBy(leadingSpaces.length), child.sourceSpan.end.moveBy(-trailingSpaces.length))
22049 if (trailingSpaces) {
22050 localChildren.push({
22051 type: TYPE_WHITESPACE
22055 return newChildren.concat(localChildren);
22056 }, []) // set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
22057 .reduce((newChildren, child, i, children) => {
22058 if (child.type === TYPE_WHITESPACE) {
22059 return newChildren;
22062 const hasLeadingSpaces = i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
22063 const hasTrailingSpaces = i !== children.length - 1 && children[i + 1].type === TYPE_WHITESPACE;
22064 return newChildren.concat(Object.assign({}, child, {
22073 function addIsSelfClosing(ast
22076 return ast.map(node => Object.assign(node, {
22077 isSelfClosing: !node.children || node.type === "element" && (node.tagDefinition.isVoid || // self-closing
22078 node.startSourceSpan === node.endSourceSpan)
22082 function addHasHtmComponentClosingTag(ast, options) {
22083 return ast.map(node => node.type !== "element" ? node : Object.assign(node, {
22084 hasHtmComponentClosingTag: node.endSourceSpan && /^<\s*\/\s*\/\s*>$/.test(options.originalText.slice(node.endSourceSpan.start.offset, node.endSourceSpan.end.offset))
22088 function addCssDisplay(ast, options) {
22089 return ast.map(node => Object.assign(node, {
22090 cssDisplay: getNodeCssStyleDisplay$1(node, options)
22094 * - add `isLeadingSpaceSensitive` field
22095 * - add `isTrailingSpaceSensitive` field
22096 * - add `isDanglingSpaceSensitive` field for parent nodes
22100 function addIsSpaceSensitive(ast
22103 return ast.map(node => {
22104 if (!node.children) {
22108 if (node.children.length === 0) {
22109 return node.clone({
22110 isDanglingSpaceSensitive: isDanglingSpaceSensitiveNode$1(node)
22114 return node.clone({
22115 children: node.children.map(child => {
22116 return Object.assign({}, child, {
22117 isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode$1(child),
22118 isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode$1(child)
22120 }).map((child, index, children) => Object.assign({}, child, {
22121 isLeadingSpaceSensitive: index === 0 ? child.isLeadingSpaceSensitive : children[index - 1].isTrailingSpaceSensitive && child.isLeadingSpaceSensitive,
22122 isTrailingSpaceSensitive: index === children.length - 1 ? child.isTrailingSpaceSensitive : children[index + 1].isLeadingSpaceSensitive && child.isTrailingSpaceSensitive
22128 var preprocess_1 = preprocess;
22130 function hasPragma$3(text) {
22131 return /^\s*<!--\s*@(format|prettier)\s*-->/.test(text);
22134 function insertPragma$5(text) {
22135 return "<!-- @format -->\n\n" + text.replace(/^\s*\n/, "");
22139 hasPragma: hasPragma$3,
22140 insertPragma: insertPragma$5
22150 * v-for="... in ..."
22151 * v-for="... of ..."
22152 * v-for="(..., ...) in ..."
22153 * v-for="(..., ...) of ..."
22156 function printVueFor(value, textToDoc) {
22161 } = parseVueFor(value);
22162 return concat$8([group$8(textToDoc("function _(".concat(left, ") {}"), {
22164 __isVueForBindingLeft: true
22165 })), " ", operator, " ", textToDoc(right, {
22166 parser: "__js_expression"
22168 } // modified from https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/parser/index.js#L370-L387
22171 function parseVueFor(value) {
22172 const forAliasRE = /([^]*?)\s+(in|of)\s+([^]*)/;
22173 const forIteratorRE = /,([^,}\]]*)(?:,([^,}\]]*))?$/;
22174 const stripParensRE = /^\(|\)$/g;
22175 const inMatch = value.match(forAliasRE);
22182 res.for = inMatch[3].trim();
22183 const alias = inMatch[1].trim().replace(stripParensRE, "");
22184 const iteratorMatch = alias.match(forIteratorRE);
22186 if (iteratorMatch) {
22187 res.alias = alias.replace(forIteratorRE, "");
22188 res.iterator1 = iteratorMatch[1].trim();
22190 if (iteratorMatch[2]) {
22191 res.iterator2 = iteratorMatch[2].trim();
22198 left: "".concat([res.alias, res.iterator1, res.iterator2].filter(Boolean).join(",")),
22199 operator: inMatch[2],
22204 function printVueSlotScope(value, textToDoc) {
22205 return textToDoc("function _(".concat(value, ") {}"), {
22207 __isVueSlotScope: true
22211 function isVueEventBindingExpression(eventBindingValue) {
22212 // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/codegen/events.js#L3-L4
22213 // arrow function or anonymous function
22214 const fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; // simple member expression chain (a, a.b, a['b'], a["b"], a[0], a[b])
22216 const simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/; // https://github.com/vuejs/vue/blob/v2.5.17/src/compiler/helpers.js#L104
22218 const value = eventBindingValue.trim();
22219 return fnExpRE.test(value) || simplePathRE.test(value);
22223 isVueEventBindingExpression,
22228 const integerRegex = /^\d+$/;
22230 function deepUnique(array) {
22231 return array.sort().filter((element, index) => {
22232 return JSON.stringify(element) !== JSON.stringify(array[index - 1]);
22236 var parse$2 = string => {
22237 return deepUnique(string.split(',').map(part => {
22239 part.trim().split(/\s+/).forEach((element, index) => {
22241 result.url = element;
22245 const value = element.slice(0, element.length - 1);
22246 const postfix = element[element.length - 1];
22247 const integerValue = parseInt(value, 10);
22248 const floatValue = parseFloat(value);
22250 if (postfix === 'w' && integerRegex.test(value)) {
22251 result.width = integerValue;
22252 } else if (postfix === 'h' && integerRegex.test(value)) {
22253 result.height = integerValue;
22254 } else if (postfix === 'x' && !Number.isNaN(floatValue)) {
22255 result.density = floatValue;
22257 throw new Error("Invalid srcset descriptor: ".concat(element));
22264 var stringify = array => {
22265 return [...new Set(array.map(element => {
22266 if (!element.url) {
22267 throw new Error('URL is required');
22270 const result = [element.url];
22272 if (element.width) {
22273 result.push("".concat(element.width, "w"));
22276 if (element.height) {
22277 result.push("".concat(element.height, "h"));
22280 if (element.density) {
22281 result.push("".concat(element.density, "x"));
22284 return result.join(' ');
22290 stringify: stringify
22296 ifBreak: ifBreak$4,
22301 const parseSrcset = srcset.parse;
22303 function printImgSrcset(value) {
22304 const srcset = parseSrcset(value);
22305 const hasW = srcset.some(src => src.width);
22306 const hasH = srcset.some(src => src.height);
22307 const hasX = srcset.some(src => src.density);
22309 if (hasW + hasH + hasX > 1) {
22310 throw new Error("Mixed descriptor in srcset is not supported");
22313 const key = hasW ? "width" : hasH ? "height" : "density";
22314 const unit = hasW ? "w" : hasH ? "h" : "x";
22316 const getMax = values => Math.max(...values);
22318 const urls = srcset.map(src => src.url);
22319 const maxUrlLength = getMax(urls.map(url => url.length));
22320 const descriptors = srcset.map(src => src[key]).map(descriptor => descriptor ? descriptor.toString() : "");
22321 const descriptorLeftLengths = descriptors.map(descriptor => {
22322 const index = descriptor.indexOf(".");
22323 return index === -1 ? descriptor.length : index;
22325 const maxDescriptorLeftLength = getMax(descriptorLeftLengths);
22326 return join$5(concat$9([",", line$5]), urls.map((url, index) => {
22327 const parts = [url];
22328 const descriptor = descriptors[index];
22331 const urlPadding = maxUrlLength - url.length + 1;
22332 const descriptorPadding = maxDescriptorLeftLength - descriptorLeftLengths[index];
22333 const alignment = " ".repeat(urlPadding + descriptorPadding);
22334 parts.push(ifBreak$4(alignment, " "), descriptor + unit);
22337 return concat$9(parts);
22341 function printClassNames(value) {
22342 return value.trim().split(/\s+/).join(" ");
22345 var syntaxAttribute = {
22353 stripTrailingHardline: stripTrailingHardline$1,
22358 breakParent: breakParent$2,
22359 dedentToRoot: dedentToRoot$1,
22362 hardline: hardline$7,
22363 ifBreak: ifBreak$5,
22367 literalline: literalline$2,
22368 markAsRoot: markAsRoot$2,
22369 softline: softline$4
22372 countChars: countChars$1,
22373 countParents: countParents$1,
22374 dedentString: dedentString$1,
22375 forceBreakChildren: forceBreakChildren$1,
22376 forceBreakContent: forceBreakContent$1,
22377 forceNextEmptyLine: forceNextEmptyLine$1,
22378 getLastDescendant: getLastDescendant$1,
22379 getPrettierIgnoreAttributeCommentData: getPrettierIgnoreAttributeCommentData$1,
22380 hasPrettierIgnore: hasPrettierIgnore$3,
22381 inferScriptParser: inferScriptParser$1,
22382 isScriptLikeTag: isScriptLikeTag$1,
22383 isTextLikeNode: isTextLikeNode$1,
22384 normalizeParts: normalizeParts$1,
22385 preferHardlineAsLeadingSpaces: preferHardlineAsLeadingSpaces$1,
22386 shouldNotPrintClosingTag: shouldNotPrintClosingTag$1,
22387 shouldPreserveContent: shouldPreserveContent$1,
22388 unescapeQuoteEntities: unescapeQuoteEntities$1
22391 replaceEndOfLineWith: replaceEndOfLineWith$1
22394 insertPragma: insertPragma$6
22397 printVueFor: printVueFor$1,
22398 printVueSlotScope: printVueSlotScope$1,
22399 isVueEventBindingExpression: isVueEventBindingExpression$1
22402 printImgSrcset: printImgSrcset$1,
22403 printClassNames: printClassNames$1
22404 } = syntaxAttribute;
22406 function concat$a(parts) {
22407 const newParts = normalizeParts$1(parts);
22408 return newParts.length === 0 ? "" : newParts.length === 1 ? newParts[0] : builders.concat(newParts);
22411 function embed$2(path, print, textToDoc, options) {
22412 const node = path.getValue();
22414 switch (node.type) {
22417 if (isScriptLikeTag$1(node.parent)) {
22418 const parser = inferScriptParser$1(node.parent);
22421 const value = parser === "markdown" ? dedentString$1(node.value.replace(/^[^\S\n]*?\n/, "")) : node.value;
22422 return builders.concat([concat$a([breakParent$2, printOpeningTagPrefix(node, options), stripTrailingHardline$1(textToDoc(value, {
22424 })), printClosingTagSuffix(node, options)])]);
22426 } else if (node.parent.type === "interpolation") {
22427 return concat$a([indent$5(concat$a([line$6, textToDoc(node.value, Object.assign({
22428 __isInHtmlInterpolation: true
22429 }, options.parser === "angular" ? {
22430 parser: "__ng_interpolation",
22431 trailingComma: "none"
22432 } : options.parser === "vue" ? {
22433 parser: "__vue_expression"
22435 parser: "__js_expression"
22436 }))])), node.parent.next && needsToBorrowPrevClosingTagEndMarker(node.parent.next) ? " " : line$6]);
22446 } // lit-html: html`<my-element obj=${obj}></my-element>`
22449 if (/^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
22450 return concat$a([node.rawName, "=", node.value]);
22451 } // lwc: html`<my-element data-for={value}></my-element>`
22454 if (options.parser === "lwc") {
22455 const interpolationRegex = /^\{[\s\S]*\}$/;
22457 if (interpolationRegex.test(options.originalText.slice(node.valueSpan.start.offset, node.valueSpan.end.offset))) {
22458 return concat$a([node.rawName, "=", node.value]);
22462 const embeddedAttributeValueDoc = printEmbeddedAttributeValue(node, (code, opts) => // strictly prefer single quote to avoid unnecessary html entity escape
22463 textToDoc(code, Object.assign({
22464 __isInHtmlAttribute: true
22465 }, opts)), options);
22467 if (embeddedAttributeValueDoc) {
22468 return concat$a([node.rawName, '="', group$9(mapDoc$2(embeddedAttributeValueDoc, doc => typeof doc === "string" ? doc.replace(/"/g, """) : doc)), '"']);
22475 return markAsRoot$2(concat$a(["---", hardline$7, node.value.trim().length === 0 ? "" : textToDoc(node.value, {
22481 function genericPrint$2(path, options, print) {
22482 const node = path.getValue();
22484 switch (node.type) {
22486 if (options.__onHtmlRoot) {
22487 options.__onHtmlRoot(node);
22488 } // use original concat to not break stripTrailingHardline
22491 return builders.concat([group$9(printChildren$1(path, options, print)), hardline$7]);
22494 case "ieConditionalComment":
22505 * exception: break if the opening tag breaks
22516 const shouldHugContent = node.children.length === 1 && node.firstChild.type === "interpolation" && node.firstChild.isLeadingSpaceSensitive && !node.firstChild.hasLeadingSpaces && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces;
22517 const attrGroupId = Symbol("element-attr-group-id");
22518 return concat$a([group$9(concat$a([group$9(printOpeningTag(path, options, print), {
22520 }), node.children.length === 0 ? node.hasDanglingSpaces && node.isDanglingSpaceSensitive ? line$6 : "" : concat$a([forceBreakContent$1(node) ? breakParent$2 : "", (childrenDoc => shouldHugContent ? ifBreak$5(indent$5(childrenDoc), childrenDoc, {
22521 groupId: attrGroupId
22522 }) : isScriptLikeTag$1(node) && node.parent.type === "root" && options.parser === "vue" && !options.vueIndentScriptAndStyle ? childrenDoc : indent$5(childrenDoc))(concat$a([shouldHugContent ? ifBreak$5(softline$4, "", {
22523 groupId: attrGroupId
22524 }) : node.firstChild.hasLeadingSpaces && node.firstChild.isLeadingSpaceSensitive ? line$6 : node.firstChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive ? dedentToRoot$1(softline$4) : softline$4, printChildren$1(path, options, print)])), (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? " " : "" : shouldHugContent ? ifBreak$5(softline$4, "", {
22525 groupId: attrGroupId
22526 }) : node.lastChild.hasTrailingSpaces && node.lastChild.isTrailingSpaceSensitive ? line$6 : (node.lastChild.type === "comment" || node.lastChild.type === "text" && node.isWhitespaceSensitive && node.isIndentationSensitive) && new RegExp("\\n\\s{".concat(options.tabWidth * countParents$1(path, n => n.parent && n.parent.type !== "root"), "}$")).test(node.lastChild.value) ?
22535 "" : softline$4])])), printClosingTag(node, options)]);
22538 case "ieConditionalStartComment":
22539 case "ieConditionalEndComment":
22540 return concat$a([printOpeningTagStart(node), printClosingTagEnd(node)]);
22542 case "interpolation":
22543 return concat$a([printOpeningTagStart(node, options), concat$a(path.map(print, "children")), printClosingTagEnd(node, options)]);
22547 if (node.parent.type === "interpolation") {
22548 // replace the trailing literalline with hardline for better readability
22549 const trailingNewlineRegex = /\n[^\S\n]*?$/;
22550 const hasTrailingNewline = trailingNewlineRegex.test(node.value);
22551 const value = hasTrailingNewline ? node.value.replace(trailingNewlineRegex, "") : node.value;
22552 return concat$a([concat$a(replaceEndOfLineWith$1(value, literalline$2)), hasTrailingNewline ? hardline$7 : ""]);
22555 return fill$3(normalizeParts$1([].concat(printOpeningTagPrefix(node, options), getTextValueParts(node), printClosingTagSuffix(node, options))));
22559 return concat$a([group$9(concat$a([printOpeningTagStart(node, options), " ", node.value.replace(/^html\b/i, "html").replace(/\s+/g, " ")])), printClosingTagEnd(node, options)]);
22563 return concat$a([printOpeningTagPrefix(node, options), concat$a(replaceEndOfLineWith$1(options.originalText.slice(options.locStart(node), options.locEnd(node)), literalline$2)), printClosingTagSuffix(node, options)]);
22568 if (node.value === null) {
22569 return node.rawName;
22572 const value = unescapeQuoteEntities$1(node.value);
22573 const singleQuoteCount = countChars$1(value, "'");
22574 const doubleQuoteCount = countChars$1(value, '"');
22575 const quote = singleQuoteCount < doubleQuoteCount ? "'" : '"';
22576 return concat$a([node.rawName, concat$a(["=", quote, concat$a(replaceEndOfLineWith$1(quote === '"' ? value.replace(/"/g, """) : value.replace(/'/g, "'"), literalline$2)), quote])]);
22581 return concat$a(replaceEndOfLineWith$1(node.raw, literalline$2));
22584 throw new Error("Unexpected node type ".concat(node.type));
22588 function printChildren$1(path, options, print) {
22589 const node = path.getValue();
22591 if (forceBreakChildren$1(node)) {
22592 return concat$a([breakParent$2, concat$a(path.map(childPath => {
22593 const childNode = childPath.getValue();
22594 const prevBetweenLine = !childNode.prev ? "" : printBetweenLine(childNode.prev, childNode);
22595 return concat$a([!prevBetweenLine ? "" : concat$a([prevBetweenLine, forceNextEmptyLine$1(childNode.prev) ? hardline$7 : ""]), printChild(childPath)]);
22599 const groupIds = node.children.map(() => Symbol(""));
22600 return concat$a(path.map((childPath, childIndex) => {
22601 const childNode = childPath.getValue();
22603 if (isTextLikeNode$1(childNode)) {
22604 if (childNode.prev && isTextLikeNode$1(childNode.prev)) {
22605 const prevBetweenLine = printBetweenLine(childNode.prev, childNode);
22607 if (prevBetweenLine) {
22608 if (forceNextEmptyLine$1(childNode.prev)) {
22609 return concat$a([hardline$7, hardline$7, printChild(childPath)]);
22612 return concat$a([prevBetweenLine, printChild(childPath)]);
22616 return printChild(childPath);
22619 const prevParts = [];
22620 const leadingParts = [];
22621 const trailingParts = [];
22622 const nextParts = [];
22623 const prevBetweenLine = childNode.prev ? printBetweenLine(childNode.prev, childNode) : "";
22624 const nextBetweenLine = childNode.next ? printBetweenLine(childNode, childNode.next) : "";
22626 if (prevBetweenLine) {
22627 if (forceNextEmptyLine$1(childNode.prev)) {
22628 prevParts.push(hardline$7, hardline$7);
22629 } else if (prevBetweenLine === hardline$7) {
22630 prevParts.push(hardline$7);
22632 if (isTextLikeNode$1(childNode.prev)) {
22633 leadingParts.push(prevBetweenLine);
22635 leadingParts.push(ifBreak$5("", softline$4, {
22636 groupId: groupIds[childIndex - 1]
22642 if (nextBetweenLine) {
22643 if (forceNextEmptyLine$1(childNode)) {
22644 if (isTextLikeNode$1(childNode.next)) {
22645 nextParts.push(hardline$7, hardline$7);
22647 } else if (nextBetweenLine === hardline$7) {
22648 if (isTextLikeNode$1(childNode.next)) {
22649 nextParts.push(hardline$7);
22652 trailingParts.push(nextBetweenLine);
22656 return concat$a([].concat(prevParts, group$9(concat$a([concat$a(leadingParts), group$9(concat$a([printChild(childPath), concat$a(trailingParts)]), {
22657 id: groupIds[childIndex]
22658 })])), nextParts));
22661 function printChild(childPath) {
22662 const child = childPath.getValue();
22664 if (hasPrettierIgnore$3(child)) {
22665 return concat$a([].concat(printOpeningTagPrefix(child, options), replaceEndOfLineWith$1(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$2), printClosingTagSuffix(child, options)));
22668 if (shouldPreserveContent$1(child, options)) {
22669 return concat$a([].concat(printOpeningTagPrefix(child, options), group$9(printOpeningTag(childPath, options, print)), replaceEndOfLineWith$1(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$2), printClosingTag(child, options), printClosingTagSuffix(child, options)));
22672 return print(childPath);
22675 function printBetweenLine(prevNode, nextNode) {
22676 return isTextLikeNode$1(prevNode) && isTextLikeNode$1(nextNode) ? prevNode.isTrailingSpaceSensitive ? prevNode.hasTrailingSpaces ? preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$7 : line$6 : "" : preferHardlineAsLeadingSpaces$1(nextNode) ? hardline$7 : softline$4 : needsToBorrowNextOpeningTagStartMarker(prevNode) && (hasPrettierIgnore$3(nextNode) ||
22682 nextNode.firstChild ||
22688 nextNode.isSelfClosing ||
22694 nextNode.type === "element" && nextNode.attrs.length !== 0) ||
22701 prevNode.type === "element" && prevNode.isSelfClosing && needsToBorrowPrevClosingTagEndMarker(nextNode) ? "" : !nextNode.isLeadingSpaceSensitive || preferHardlineAsLeadingSpaces$1(nextNode) ||
22703 * Want to write us a letter? Use our<a
22704 * ><b><a>mailing address</a></b></a
22708 needsToBorrowPrevClosingTagEndMarker(nextNode) && prevNode.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild) && prevNode.lastChild.lastChild && needsToBorrowParentClosingTagStartMarker(prevNode.lastChild.lastChild) ? hardline$7 : nextNode.hasLeadingSpaces ? line$6 : softline$4;
22712 function printOpeningTag(path, options, print) {
22713 const node = path.getValue();
22714 const forceNotToBreakAttrContent = node.type === "element" && node.fullName === "script" && node.attrs.length === 1 && node.attrs[0].fullName === "src" && node.children.length === 0;
22715 return concat$a([printOpeningTagStart(node, options), !node.attrs || node.attrs.length === 0 ? node.isSelfClosing ?
22720 " " : "" : concat$a([indent$5(concat$a([forceNotToBreakAttrContent ? " " : line$6, join$6(line$6, (ignoreAttributeData => {
22721 const hasPrettierIgnoreAttribute = typeof ignoreAttributeData === "boolean" ? () => ignoreAttributeData : Array.isArray(ignoreAttributeData) ? attr => ignoreAttributeData.includes(attr.rawName) : () => false;
22722 return path.map(attrPath => {
22723 const attr = attrPath.getValue();
22724 return hasPrettierIgnoreAttribute(attr) ? concat$a(replaceEndOfLineWith$1(options.originalText.slice(options.locStart(attr), options.locEnd(attr)), literalline$2)) : print(attrPath);
22726 })(node.prev && node.prev.type === "comment" && getPrettierIgnoreAttributeCommentData$1(node.prev.value)))])),
22733 node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ||
22740 node.isSelfClosing && needsToBorrowLastChildClosingTagEndMarker(node.parent) ? node.isSelfClosing ? " " : "" : node.isSelfClosing ? forceNotToBreakAttrContent ? " " : line$6 : forceNotToBreakAttrContent ? "" : softline$4]), node.isSelfClosing ? "" : printOpeningTagEnd(node)]);
22743 function printOpeningTagStart(node, options) {
22744 return node.prev && needsToBorrowNextOpeningTagStartMarker(node.prev) ? "" : concat$a([printOpeningTagPrefix(node, options), printOpeningTagStartMarker(node)]);
22747 function printOpeningTagEnd(node) {
22748 return node.firstChild && needsToBorrowParentOpeningTagEndMarker(node.firstChild) ? "" : printOpeningTagEndMarker(node);
22751 function printClosingTag(node, options) {
22752 return concat$a([node.isSelfClosing ? "" : printClosingTagStart(node, options), printClosingTagEnd(node, options)]);
22755 function printClosingTagStart(node, options) {
22756 return node.lastChild && needsToBorrowParentClosingTagStartMarker(node.lastChild) ? "" : concat$a([printClosingTagPrefix(node, options), printClosingTagStartMarker(node, options)]);
22759 function printClosingTagEnd(node, options) {
22760 return (node.next ? needsToBorrowPrevClosingTagEndMarker(node.next) : needsToBorrowLastChildClosingTagEndMarker(node.parent)) ? "" : concat$a([printClosingTagEndMarker(node, options), printClosingTagSuffix(node, options)]);
22763 function needsToBorrowNextOpeningTagStartMarker(node) {
22769 return node.next && !isTextLikeNode$1(node.next) && isTextLikeNode$1(node) && node.isTrailingSpaceSensitive && !node.hasTrailingSpaces;
22772 function needsToBorrowParentOpeningTagEndMarker(node) {
22782 return !node.prev && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
22785 function needsToBorrowPrevClosingTagEndMarker(node) {
22795 return node.prev && !isTextLikeNode$1(node.prev) && node.isLeadingSpaceSensitive && !node.hasLeadingSpaces;
22798 function needsToBorrowLastChildClosingTagEndMarker(node) {
22806 return node.lastChild && node.lastChild.isTrailingSpaceSensitive && !node.lastChild.hasTrailingSpaces && !isTextLikeNode$1(getLastDescendant$1(node.lastChild));
22809 function needsToBorrowParentClosingTagStartMarker(node) {
22821 return !node.next && !node.hasTrailingSpaces && node.isTrailingSpaceSensitive && isTextLikeNode$1(getLastDescendant$1(node));
22824 function printOpeningTagPrefix(node, options) {
22825 return needsToBorrowParentOpeningTagEndMarker(node) ? printOpeningTagEndMarker(node.parent) : needsToBorrowPrevClosingTagEndMarker(node) ? printClosingTagEndMarker(node.prev, options) : "";
22828 function printClosingTagPrefix(node, options) {
22829 return needsToBorrowLastChildClosingTagEndMarker(node) ? printClosingTagEndMarker(node.lastChild, options) : "";
22832 function printClosingTagSuffix(node, options) {
22833 return needsToBorrowParentClosingTagStartMarker(node) ? printClosingTagStartMarker(node.parent, options) : needsToBorrowNextOpeningTagStartMarker(node) ? printOpeningTagStartMarker(node.next) : "";
22836 function printOpeningTagStartMarker(node) {
22837 switch (node.type) {
22838 case "ieConditionalComment":
22839 case "ieConditionalStartComment":
22840 return "<!--[if ".concat(node.condition);
22842 case "ieConditionalEndComment":
22845 case "interpolation":
22849 return "<!DOCTYPE";
22852 if (node.condition) {
22853 return "<!--[if ".concat(node.condition, "]><!--><").concat(node.rawName);
22859 return "<".concat(node.rawName);
22863 function printOpeningTagEndMarker(node) {
22864 assert(!node.isSelfClosing);
22866 switch (node.type) {
22867 case "ieConditionalComment":
22871 if (node.condition) {
22872 return "><!--<![endif]-->";
22882 function printClosingTagStartMarker(node, options) {
22883 assert(!node.isSelfClosing);
22885 if (shouldNotPrintClosingTag$1(node, options)) {
22889 switch (node.type) {
22890 case "ieConditionalComment":
22894 if (node.hasHtmComponentClosingTag) {
22901 return "</".concat(node.rawName);
22905 function printClosingTagEndMarker(node, options) {
22906 if (shouldNotPrintClosingTag$1(node, options)) {
22910 switch (node.type) {
22911 case "ieConditionalComment":
22912 case "ieConditionalEndComment":
22913 return "[endif]-->";
22915 case "ieConditionalStartComment":
22918 case "interpolation":
22922 if (node.isSelfClosing) {
22933 function getTextValueParts(node, value = node.value) {
22934 return node.parent.isWhitespaceSensitive ? node.parent.isIndentationSensitive ? replaceEndOfLineWith$1(value, literalline$2) : replaceEndOfLineWith$1(dedentString$1(value.replace(/^\s*?\n|\n\s*?$/g, "")), hardline$7) : // https://infra.spec.whatwg.org/#ascii-whitespace
22935 join$6(line$6, value.split(/[\t\n\f\r ]+/)).parts;
22938 function printEmbeddedAttributeValue(node, originalTextToDoc, options) {
22939 const isKeyMatched = patterns => new RegExp(patterns.join("|")).test(node.fullName);
22941 const getValue = () => unescapeQuoteEntities$1(node.value);
22943 let shouldHug = false;
22945 const __onHtmlBindingRoot = (root, options) => {
22946 const rootNode = root.type === "NGRoot" ? root.node.type === "NGMicrosyntax" && root.node.body.length === 1 && root.node.body[0].type === "NGMicrosyntaxExpression" ? root.node.body[0].expression : root.node : root.type === "JsExpressionRoot" ? root.node : root;
22948 if (rootNode && (rootNode.type === "ObjectExpression" || rootNode.type === "ArrayExpression" || options.parser === "__vue_expression" && (rootNode.type === "TemplateLiteral" || rootNode.type === "StringLiteral"))) {
22953 const printHug = doc => group$9(doc);
22955 const printExpand = (doc, canHaveTrailingWhitespace = true) => group$9(concat$a([indent$5(concat$a([softline$4, doc])), canHaveTrailingWhitespace ? softline$4 : ""]));
22957 const printMaybeHug = doc => shouldHug ? printHug(doc) : printExpand(doc);
22959 const textToDoc = (code, opts) => originalTextToDoc(code, Object.assign({
22960 __onHtmlBindingRoot
22963 if (node.fullName === "srcset" && (node.parent.fullName === "img" || node.parent.fullName === "source")) {
22964 return printExpand(printImgSrcset$1(getValue()));
22967 if (node.fullName === "class" && !options.parentParser) {
22968 const value = getValue();
22970 if (!value.includes("{{")) {
22971 return printClassNames$1(value);
22975 if (node.fullName === "style" && !options.parentParser) {
22976 const value = getValue();
22978 if (!value.includes("{{")) {
22979 return printExpand(textToDoc(value, {
22981 __isHTMLStyleAttribute: true
22986 if (options.parser === "vue") {
22987 if (node.fullName === "v-for") {
22988 return printVueFor$1(getValue(), textToDoc);
22991 if (node.fullName === "slot-scope") {
22992 return printVueSlotScope$1(getValue(), textToDoc);
22995 * @click="jsStatement"
22996 * @click="jsExpression"
22997 * v-on:click="jsStatement"
22998 * v-on:click="jsExpression"
23002 const vueEventBindingPatterns = ["^@", "^v-on:"];
23004 * :class="vueExpression"
23005 * v-bind:id="vueExpression"
23008 const vueExpressionBindingPatterns = ["^:", "^v-bind:"];
23010 * v-if="jsExpression"
23013 const jsExpressionBindingPatterns = ["^v-"];
23015 if (isKeyMatched(vueEventBindingPatterns)) {
23016 const value = getValue();
23017 return printMaybeHug(isVueEventBindingExpression$1(value) ? textToDoc(value, {
23018 parser: "__js_expression"
23019 }) : stripTrailingHardline$1(textToDoc(value, {
23020 parser: "__vue_event_binding"
23024 if (isKeyMatched(vueExpressionBindingPatterns)) {
23025 return printMaybeHug(textToDoc(getValue(), {
23026 parser: "__vue_expression"
23030 if (isKeyMatched(jsExpressionBindingPatterns)) {
23031 return printMaybeHug(textToDoc(getValue(), {
23032 parser: "__js_expression"
23037 if (options.parser === "angular") {
23038 const ngTextToDoc = (code, opts) => // angular does not allow trailing comma
23039 textToDoc(code, Object.assign({}, opts, {
23040 trailingComma: "none"
23043 * *directive="angularDirective"
23047 const ngDirectiveBindingPatterns = ["^\\*"];
23049 * (click)="angularStatement"
23050 * on-click="angularStatement"
23053 const ngStatementBindingPatterns = ["^\\(.+\\)$", "^on-"];
23055 * [target]="angularExpression"
23056 * bind-target="angularExpression"
23057 * [(target)]="angularExpression"
23058 * bindon-target="angularExpression"
23061 const ngExpressionBindingPatterns = ["^\\[.+\\]$", "^bind(on)?-", // Unofficial rudimentary support for some of the most used directives of AngularJS 1.x
23062 "^ng-(if|show|hide|class|style)$"];
23064 * i18n="longDescription"
23065 * i18n-attr="longDescription"
23068 const ngI18nPatterns = ["^i18n(-.+)?$"];
23070 if (isKeyMatched(ngStatementBindingPatterns)) {
23071 return printMaybeHug(ngTextToDoc(getValue(), {
23072 parser: "__ng_action"
23076 if (isKeyMatched(ngExpressionBindingPatterns)) {
23077 return printMaybeHug(ngTextToDoc(getValue(), {
23078 parser: "__ng_binding"
23082 if (isKeyMatched(ngI18nPatterns)) {
23083 const value = getValue().trim();
23084 return printExpand(fill$3(getTextValueParts(node, value)), !value.includes("@@"));
23087 if (isKeyMatched(ngDirectiveBindingPatterns)) {
23088 return printMaybeHug(ngTextToDoc(getValue(), {
23089 parser: "__ng_directive"
23093 const interpolationRegex = /\{\{([\s\S]+?)\}\}/g;
23094 const value = getValue();
23096 if (interpolationRegex.test(value)) {
23098 value.split(interpolationRegex).forEach((part, index) => {
23099 if (index % 2 === 0) {
23100 parts.push(concat$a(replaceEndOfLineWith$1(part, literalline$2)));
23103 parts.push(group$9(concat$a(["{{", indent$5(concat$a([line$6, ngTextToDoc(part, {
23104 parser: "__ng_interpolation",
23105 __isInHtmlInterpolation: true // to avoid unexpected `}}`
23107 })])), line$6, "}}"])));
23109 parts.push("{{", concat$a(replaceEndOfLineWith$1(part, literalline$2)), "}}");
23113 return group$9(concat$a(parts));
23120 var printerHtml = {
23121 preprocess: preprocess_1,
23122 print: genericPrint$2,
23123 insertPragma: insertPragma$6,
23124 massageAstNode: clean$3,
23128 const CATEGORY_HTML = "HTML"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
23131 htmlWhitespaceSensitivity: {
23133 category: CATEGORY_HTML,
23136 description: "How to handle whitespaces in HTML.",
23139 description: "Respect the default value of CSS display property."
23142 description: "Whitespaces are considered sensitive."
23145 description: "Whitespaces are considered insensitive."
23148 vueIndentScriptAndStyle: {
23150 category: CATEGORY_HTML,
23153 description: "Indent script and style tags in Vue files."
23157 var name$7 = "HTML";
23158 var type$6 = "markup";
23159 var tmScope$6 = "text.html.basic";
23160 var aceMode$6 = "html";
23161 var codemirrorMode$3 = "htmlmixed";
23162 var codemirrorMimeType$3 = "text/html";
23163 var color$1 = "#e34c26";
23167 var extensions$6 = [
23176 var languageId$6 = 146;
23180 tmScope: tmScope$6,
23181 aceMode: aceMode$6,
23182 codemirrorMode: codemirrorMode$3,
23183 codemirrorMimeType: codemirrorMimeType$3,
23185 aliases: aliases$1,
23186 extensions: extensions$6,
23187 languageId: languageId$6
23190 var HTML$1 = /*#__PURE__*/Object.freeze({
23194 tmScope: tmScope$6,
23195 aceMode: aceMode$6,
23196 codemirrorMode: codemirrorMode$3,
23197 codemirrorMimeType: codemirrorMimeType$3,
23199 aliases: aliases$1,
23200 extensions: extensions$6,
23201 languageId: languageId$6,
23205 var name$8 = "Vue";
23206 var type$7 = "markup";
23207 var color$2 = "#2c3e50";
23208 var extensions$7 = [
23211 var tmScope$7 = "text.html.vue";
23212 var aceMode$7 = "html";
23213 var languageId$7 = 391;
23218 extensions: extensions$7,
23219 tmScope: tmScope$7,
23220 aceMode: aceMode$7,
23221 languageId: languageId$7
23224 var Vue$1 = /*#__PURE__*/Object.freeze({
23229 extensions: extensions$7,
23230 tmScope: tmScope$7,
23231 aceMode: aceMode$7,
23232 languageId: languageId$7,
23236 var require$$0$5 = getCjsExportFromNamespace(HTML$1);
23238 var require$$1$1 = getCjsExportFromNamespace(Vue$1);
23240 const languages$3 = [createLanguage(require$$0$5, () => ({
23243 parsers: ["angular"],
23244 vscodeLanguageIds: ["html"],
23245 extensions: [".component.html"],
23247 })), createLanguage(require$$0$5, data => ({
23250 vscodeLanguageIds: ["html"],
23251 extensions: data.extensions.concat([".mjml" // MJML is considered XML in Linguist but it should be formatted as HTML
23253 })), createLanguage(require$$0$5, () => ({
23254 name: "Lightning Web Components",
23257 vscodeLanguageIds: ["html"],
23260 })), createLanguage(require$$1$1, () => ({
23263 vscodeLanguageIds: ["vue"]
23265 const printers$3 = {
23268 var languageHtml = {
23269 languages: languages$3,
23270 printers: printers$3,
23275 addLeadingComment: addLeadingComment$3,
23276 addTrailingComment: addTrailingComment$3,
23277 addDanglingComment: addDanglingComment$3,
23278 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$2
23281 function handleOwnLineComment(comment, text, options, ast, isLastComment) {
23287 return handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleMemberExpressionComments(enclosingNode, followingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleImportSpecifierComments(enclosingNode, comment) || handleForComments(enclosingNode, precedingNode, comment) || handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) || handleAssignmentPatternComments(enclosingNode, comment) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) || handleLabeledStatementComments(enclosingNode, comment);
23290 function handleEndOfLineComment(comment, text, options, ast, isLastComment) {
23296 return handleClosureTypeCastComments(followingNode, comment) || handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) || handleImportSpecifierComments(enclosingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleLabeledStatementComments(enclosingNode, comment) || handleCallExpressionComments(precedingNode, enclosingNode, comment) || handlePropertyComments(enclosingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleTypeAliasComments(enclosingNode, followingNode, comment) || handleVariableDeclaratorComments(enclosingNode, followingNode, comment);
23299 function handleRemainingComment(comment, text, options, ast, isLastComment) {
23306 if (handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) || handleCommentInEmptyParens(text, enclosingNode, comment, options) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleCommentAfterArrowParams(text, enclosingNode, comment, options) || handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) || handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) || handleBreakAndContinueStatementComments(enclosingNode, comment) || handleTSFunctionTrailingComments(text, enclosingNode, followingNode, comment, options)) {
23313 function addBlockStatementFirstComment(node, comment) {
23314 const body = node.body.filter(n => n.type !== "EmptyStatement");
23316 if (body.length === 0) {
23317 addDanglingComment$3(node, comment);
23319 addLeadingComment$3(body[0], comment);
23323 function addBlockOrNotComment(node, comment) {
23324 if (node.type === "BlockStatement") {
23325 addBlockStatementFirstComment(node, comment);
23327 addLeadingComment$3(node, comment);
23331 function handleClosureTypeCastComments(followingNode, comment) {
23332 if (followingNode && isTypeCastComment(comment)) {
23333 addLeadingComment$3(followingNode, comment);
23338 } // There are often comments before the else clause of if statements like
23344 // They are being attached as leading comments of the BlockExpression which
23345 // is not well printed. What we want is to instead move the comment inside
23346 // of the block and make it leadingComment of the first element of the block
23347 // or dangling comment of the block if there is nothing inside
23356 function handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
23357 if (!enclosingNode || enclosingNode.type !== "IfStatement" || !followingNode) {
23359 } // We unfortunately have no way using the AST or location of nodes to know
23360 // if the comment is positioned before the condition parenthesis:
23361 // if (a /* comment */) {}
23362 // The only workaround I found is to look at the next character to see if
23366 const nextCharacter = util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd);
23368 if (nextCharacter === ")") {
23369 addTrailingComment$3(precedingNode, comment);
23371 } // Comments before `else`:
23372 // - treat as trailing comments of the consequent, if it's a BlockStatement
23373 // - treat as a dangling comment otherwise
23376 if (precedingNode === enclosingNode.consequent && followingNode === enclosingNode.alternate) {
23377 if (precedingNode.type === "BlockStatement") {
23378 addTrailingComment$3(precedingNode, comment);
23380 addDanglingComment$3(enclosingNode, comment);
23386 if (followingNode.type === "BlockStatement") {
23387 addBlockStatementFirstComment(followingNode, comment);
23391 if (followingNode.type === "IfStatement") {
23392 addBlockOrNotComment(followingNode.consequent, comment);
23394 } // For comments positioned after the condition parenthesis in an if statement
23395 // before the consequent without brackets on, such as
23396 // if (a) /* comment */ true,
23397 // we look at the next character to see if the following node
23398 // is the consequent for the if statement
23401 if (enclosingNode.consequent === followingNode) {
23402 addLeadingComment$3(followingNode, comment);
23409 function handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
23410 if (!enclosingNode || enclosingNode.type !== "WhileStatement" || !followingNode) {
23412 } // We unfortunately have no way using the AST or location of nodes to know
23413 // if the comment is positioned before the condition parenthesis:
23414 // while (a /* comment */) {}
23415 // The only workaround I found is to look at the next character to see if
23419 const nextCharacter = util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd);
23421 if (nextCharacter === ")") {
23422 addTrailingComment$3(precedingNode, comment);
23426 if (followingNode.type === "BlockStatement") {
23427 addBlockStatementFirstComment(followingNode, comment);
23432 } // Same as IfStatement but for TryStatement
23435 function handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) {
23436 if (!enclosingNode || enclosingNode.type !== "TryStatement" && enclosingNode.type !== "CatchClause" || !followingNode) {
23440 if (enclosingNode.type === "CatchClause" && precedingNode) {
23441 addTrailingComment$3(precedingNode, comment);
23445 if (followingNode.type === "BlockStatement") {
23446 addBlockStatementFirstComment(followingNode, comment);
23450 if (followingNode.type === "TryStatement") {
23451 addBlockOrNotComment(followingNode.finalizer, comment);
23455 if (followingNode.type === "CatchClause") {
23456 addBlockOrNotComment(followingNode.body, comment);
23463 function handleMemberExpressionComments(enclosingNode, followingNode, comment) {
23464 if (enclosingNode && (enclosingNode.type === "MemberExpression" || enclosingNode.type === "OptionalMemberExpression") && followingNode && followingNode.type === "Identifier") {
23465 addLeadingComment$3(enclosingNode, comment);
23472 function handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) {
23473 const isSameLineAsPrecedingNode = precedingNode && !util$1.hasNewlineInRange(text, options.locEnd(precedingNode), options.locStart(comment));
23475 if ((!precedingNode || !isSameLineAsPrecedingNode) && enclosingNode && enclosingNode.type === "ConditionalExpression" && followingNode) {
23476 addLeadingComment$3(followingNode, comment);
23483 function handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) {
23484 if (enclosingNode && (enclosingNode.type === "ObjectProperty" || enclosingNode.type === "Property") && enclosingNode.shorthand && enclosingNode.key === precedingNode && enclosingNode.value.type === "AssignmentPattern") {
23485 addTrailingComment$3(enclosingNode.value.left, comment);
23492 function handleClassComments(enclosingNode, precedingNode, followingNode, comment) {
23493 if (enclosingNode && (enclosingNode.type === "ClassDeclaration" || enclosingNode.type === "ClassExpression") && enclosingNode.decorators && enclosingNode.decorators.length > 0 && !(followingNode && followingNode.type === "Decorator")) {
23494 if (!enclosingNode.decorators || enclosingNode.decorators.length === 0) {
23495 addLeadingComment$3(enclosingNode, comment);
23497 addTrailingComment$3(enclosingNode.decorators[enclosingNode.decorators.length - 1], comment);
23506 function handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) {
23507 // This is only needed for estree parsers (flow, typescript) to attach
23508 // after a method name:
23509 // obj = { fn /*comment*/() {} };
23510 if (enclosingNode && precedingNode && ( // "MethodDefinition" is handled in getCommentChildNodes
23511 enclosingNode.type === "Property" || enclosingNode.type === "TSDeclareMethod" || enclosingNode.type === "TSAbstractMethodDefinition") && precedingNode.type === "Identifier" && enclosingNode.key === precedingNode && // special Property case: { key: /*comment*/(value) };
23512 // comment should be attached to value instead of key
23513 util$1.getNextNonSpaceNonCommentCharacter(text, precedingNode, options.locEnd) !== ":") {
23514 addTrailingComment$3(precedingNode, comment);
23516 } // Print comments between decorators and class methods as a trailing comment
23517 // on the decorator node instead of the method node
23520 if (precedingNode && enclosingNode && precedingNode.type === "Decorator" && (enclosingNode.type === "ClassMethod" || enclosingNode.type === "ClassProperty" || enclosingNode.type === "TSAbstractClassProperty" || enclosingNode.type === "TSAbstractMethodDefinition" || enclosingNode.type === "TSDeclareMethod" || enclosingNode.type === "MethodDefinition")) {
23521 addTrailingComment$3(precedingNode, comment);
23528 function handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) {
23529 if (util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== "(") {
23533 if (precedingNode && enclosingNode && (enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ClassMethod" || enclosingNode.type === "MethodDefinition" || enclosingNode.type === "ObjectMethod")) {
23534 addTrailingComment$3(precedingNode, comment);
23541 function handleCommentAfterArrowParams(text, enclosingNode, comment, options) {
23542 if (!(enclosingNode && enclosingNode.type === "ArrowFunctionExpression")) {
23546 const index = getNextNonSpaceNonCommentCharacterIndex$2(text, comment, options.locEnd);
23548 if (text.slice(index, index + 2) === "=>") {
23549 addDanglingComment$3(enclosingNode, comment);
23556 function handleCommentInEmptyParens(text, enclosingNode, comment, options) {
23557 if (util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) !== ")") {
23559 } // Only add dangling comments to fix the case when no params are present,
23560 // i.e. a function without any argument.
23563 if (enclosingNode && (isRealFunctionLikeNode(enclosingNode) && // `params` vs `parameters` - see https://github.com/babel/babel/issues/9231
23564 (enclosingNode.params || enclosingNode.parameters).length === 0 || (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression" || enclosingNode.type === "NewExpression") && enclosingNode.arguments.length === 0)) {
23565 addDanglingComment$3(enclosingNode, comment);
23569 if (enclosingNode && enclosingNode.type === "MethodDefinition" && enclosingNode.value.params.length === 0) {
23570 addDanglingComment$3(enclosingNode.value, comment);
23577 function handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) {
23578 // Flow function type definitions
23579 if (precedingNode && precedingNode.type === "FunctionTypeParam" && enclosingNode && enclosingNode.type === "FunctionTypeAnnotation" && followingNode && followingNode.type !== "FunctionTypeParam") {
23580 addTrailingComment$3(precedingNode, comment);
23582 } // Real functions and TypeScript function type definitions
23585 if (precedingNode && (precedingNode.type === "Identifier" || precedingNode.type === "AssignmentPattern") && enclosingNode && isRealFunctionLikeNode(enclosingNode) && util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) === ")") {
23586 addTrailingComment$3(precedingNode, comment);
23590 if (enclosingNode && enclosingNode.type === "FunctionDeclaration" && followingNode && followingNode.type === "BlockStatement") {
23591 const functionParamRightParenIndex = (() => {
23592 if ((enclosingNode.params || enclosingNode.parameters).length !== 0) {
23593 return util$1.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(util$1.getLast(enclosingNode.params || enclosingNode.parameters)));
23596 const functionParamLeftParenIndex = util$1.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, options.locEnd(enclosingNode.id));
23597 return util$1.getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, functionParamLeftParenIndex + 1);
23600 if (options.locStart(comment) > functionParamRightParenIndex) {
23601 addBlockStatementFirstComment(followingNode, comment);
23609 function handleImportSpecifierComments(enclosingNode, comment) {
23610 if (enclosingNode && enclosingNode.type === "ImportSpecifier") {
23611 addLeadingComment$3(enclosingNode, comment);
23618 function handleLabeledStatementComments(enclosingNode, comment) {
23619 if (enclosingNode && enclosingNode.type === "LabeledStatement") {
23620 addLeadingComment$3(enclosingNode, comment);
23627 function handleBreakAndContinueStatementComments(enclosingNode, comment) {
23628 if (enclosingNode && (enclosingNode.type === "ContinueStatement" || enclosingNode.type === "BreakStatement") && !enclosingNode.label) {
23629 addTrailingComment$3(enclosingNode, comment);
23636 function handleCallExpressionComments(precedingNode, enclosingNode, comment) {
23637 if (enclosingNode && (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression") && precedingNode && enclosingNode.callee === precedingNode && enclosingNode.arguments.length > 0) {
23638 addLeadingComment$3(enclosingNode.arguments[0], comment);
23645 function handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) {
23646 if (enclosingNode && (enclosingNode.type === "UnionTypeAnnotation" || enclosingNode.type === "TSUnionType")) {
23647 if (util$1.isNodeIgnoreComment(comment)) {
23648 followingNode.prettierIgnore = true;
23649 comment.unignore = true;
23652 if (precedingNode) {
23653 addTrailingComment$3(precedingNode, comment);
23660 if (followingNode && (followingNode.type === "UnionTypeAnnotation" || followingNode.type === "TSUnionType") && util$1.isNodeIgnoreComment(comment)) {
23661 followingNode.types[0].prettierIgnore = true;
23662 comment.unignore = true;
23668 function handlePropertyComments(enclosingNode, comment) {
23669 if (enclosingNode && (enclosingNode.type === "Property" || enclosingNode.type === "ObjectProperty")) {
23670 addLeadingComment$3(enclosingNode, comment);
23677 function handleOnlyComments(enclosingNode, ast, comment, isLastComment) {
23678 // With Flow the enclosingNode is undefined so use the AST instead.
23679 if (ast && ast.body && ast.body.length === 0) {
23680 if (isLastComment) {
23681 addDanglingComment$3(ast, comment);
23683 addLeadingComment$3(ast, comment);
23687 } else if (enclosingNode && enclosingNode.type === "Program" && enclosingNode.body.length === 0 && enclosingNode.directives && enclosingNode.directives.length === 0) {
23688 if (isLastComment) {
23689 addDanglingComment$3(enclosingNode, comment);
23691 addLeadingComment$3(enclosingNode, comment);
23700 function handleForComments(enclosingNode, precedingNode, comment) {
23701 if (enclosingNode && (enclosingNode.type === "ForInStatement" || enclosingNode.type === "ForOfStatement")) {
23702 addLeadingComment$3(enclosingNode, comment);
23709 function handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) {
23710 if (precedingNode && precedingNode.type === "ImportSpecifier" && enclosingNode && enclosingNode.type === "ImportDeclaration" && util$1.hasNewline(text, options.locEnd(comment))) {
23711 addTrailingComment$3(precedingNode, comment);
23718 function handleAssignmentPatternComments(enclosingNode, comment) {
23719 if (enclosingNode && enclosingNode.type === "AssignmentPattern") {
23720 addLeadingComment$3(enclosingNode, comment);
23727 function handleTypeAliasComments(enclosingNode, followingNode, comment) {
23728 if (enclosingNode && enclosingNode.type === "TypeAlias") {
23729 addLeadingComment$3(enclosingNode, comment);
23736 function handleVariableDeclaratorComments(enclosingNode, followingNode, comment) {
23737 if (enclosingNode && (enclosingNode.type === "VariableDeclarator" || enclosingNode.type === "AssignmentExpression") && followingNode && (followingNode.type === "ObjectExpression" || followingNode.type === "ArrayExpression" || followingNode.type === "TemplateLiteral" || followingNode.type === "TaggedTemplateExpression" || isBlockComment(comment))) {
23738 addLeadingComment$3(followingNode, comment);
23745 function handleTSFunctionTrailingComments(text, enclosingNode, followingNode, comment, options) {
23746 if (!followingNode && enclosingNode && (enclosingNode.type === "TSMethodSignature" || enclosingNode.type === "TSDeclareFunction" || enclosingNode.type === "TSAbstractMethodDefinition") && util$1.getNextNonSpaceNonCommentCharacter(text, comment, options.locEnd) === ";") {
23747 addTrailingComment$3(enclosingNode, comment);
23754 function handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) {
23755 if (!enclosingNode || enclosingNode.type !== "TSMappedType") {
23759 if (followingNode && followingNode.type === "TSTypeParameter" && followingNode.name) {
23760 addLeadingComment$3(followingNode.name, comment);
23764 if (precedingNode && precedingNode.type === "TSTypeParameter" && precedingNode.constraint) {
23765 addTrailingComment$3(precedingNode.constraint, comment);
23772 function isBlockComment(comment) {
23773 return comment.type === "Block" || comment.type === "CommentBlock";
23776 function hasLeadingComment(node, fn = () => true) {
23777 if (node.leadingComments) {
23778 return node.leadingComments.some(fn);
23781 if (node.comments) {
23782 return node.comments.some(comment => comment.leading && fn(comment));
23788 function isRealFunctionLikeNode(node) {
23789 return node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression" || node.type === "FunctionDeclaration" || node.type === "ObjectMethod" || node.type === "ClassMethod" || node.type === "TSDeclareFunction" || node.type === "TSCallSignatureDeclaration" || node.type === "TSConstructSignatureDeclaration" || node.type === "TSConstructSignatureDeclaration" || node.type === "TSMethodSignature" || node.type === "TSConstructorType" || node.type === "TSFunctionType" || node.type === "TSDeclareMethod";
23792 function getGapRegex(enclosingNode) {
23793 if (enclosingNode && enclosingNode.type !== "BinaryExpression" && enclosingNode.type !== "LogicalExpression") {
23794 // Support degenerate single-element unions and intersections.
23795 // E.g.: `type A = /* 1 */ & B`
23796 return /^[\s(&|]*$/;
23800 function getCommentChildNodes(node, options) {
23801 // Prevent attaching comments to FunctionExpression in this case:
23803 // bar() // comment
23808 if ((options.parser === "typescript" || options.parser === "flow") && node.type === "MethodDefinition" && node.value && node.value.type === "FunctionExpression" && node.value.params.length === 0 && !node.value.returnType && (!node.value.typeParameters || node.value.typeParameters.length === 0) && node.value.body) {
23809 return [...(node.decorators || []), node.key, node.value.body];
23813 function isTypeCastComment(comment) {
23814 return isBlockComment(comment) && comment.value[0] === "*" && // TypeScript expects the type to be enclosed in curly brackets, however
23815 // Closure Compiler accepts types in parens and even without any delimiters at all.
23816 // That's why we just search for "@type".
23817 /@type\b/.test(comment.value);
23821 handleOwnLineComment,
23822 handleEndOfLineComment,
23823 handleRemainingComment,
23828 getCommentChildNodes
23832 isBlockComment: isBlockComment$1,
23833 hasLeadingComment: hasLeadingComment$1
23840 hardline: hardline$8,
23841 softline: softline$5,
23842 literalline: literalline$3,
23845 dedentToRoot: dedentToRoot$2
23849 stripTrailingHardline: stripTrailingHardline$2
23853 function embed$3(path, print, textToDoc, options) {
23854 const node = path.getValue();
23855 const parent = path.getParentNode();
23856 const parentParent = path.getParentNode(1);
23858 switch (node.type) {
23859 case "TemplateLiteral":
23861 const isCss = [isStyledJsx, isStyledComponents, isCssProp, isAngularComponentStyles].some(isIt => isIt(path));
23864 // Get full template literal with expressions replaced by placeholders
23865 const rawQuasis = node.quasis.map(q => q.value.raw);
23866 let placeholderID = 0;
23867 const text = rawQuasis.reduce((prevVal, currVal, idx) => {
23868 return idx === 0 ? currVal : prevVal + "@prettier-placeholder-" + placeholderID++ + "-id" + currVal;
23870 const doc = textToDoc(text, {
23873 return transformCssDoc(doc, path, print);
23876 * react-relay and graphql-tag
23878 * graphql.experimental`...`
23881 * This intentionally excludes Relay Classic tags, as Prettier does not
23882 * support Relay Classic formatting.
23886 if (isGraphQL(path)) {
23887 const expressionDocs = node.expressions ? path.map(print, "expressions") : [];
23888 const numQuasis = node.quasis.length;
23890 if (numQuasis === 1 && node.quasis[0].value.raw.trim() === "") {
23896 for (let i = 0; i < numQuasis; i++) {
23897 const templateElement = node.quasis[i];
23898 const isFirst = i === 0;
23899 const isLast = i === numQuasis - 1;
23900 const text = templateElement.value.cooked; // Bail out if any of the quasis have an invalid escape sequence
23901 // (which would make the `cooked` value be `null` or `undefined`)
23903 if (typeof text !== "string") {
23907 const lines = text.split("\n");
23908 const numLines = lines.length;
23909 const expressionDoc = expressionDocs[i];
23910 const startsWithBlankLine = numLines > 2 && lines[0].trim() === "" && lines[1].trim() === "";
23911 const endsWithBlankLine = numLines > 2 && lines[numLines - 1].trim() === "" && lines[numLines - 2].trim() === "";
23912 const commentsAndWhitespaceOnly = lines.every(line => /^\s*(?:#[^\r\n]*)?$/.test(line)); // Bail out if an interpolation occurs within a comment.
23914 if (!isLast && /#[^\r\n]*$/.test(lines[numLines - 1])) {
23920 if (commentsAndWhitespaceOnly) {
23921 doc = printGraphqlComments(lines);
23923 doc = stripTrailingHardline$2(textToDoc(text, {
23929 doc = escapeTemplateCharacters(doc, false);
23931 if (!isFirst && startsWithBlankLine) {
23937 if (!isLast && endsWithBlankLine) {
23940 } else if (!isFirst && !isLast && startsWithBlankLine) {
23944 if (expressionDoc) {
23945 parts.push(concat$b(["${", expressionDoc, "}"]));
23949 return concat$b(["`", indent$6(concat$b([hardline$8, join$7(hardline$8, parts)])), hardline$8, "`"]);
23952 const htmlParser = isHtml(path) ? "html" : isAngularComponentTemplate(path) ? "angular" : undefined;
23955 return printHtmlTemplateLiteral(path, print, textToDoc, htmlParser, options);
23961 case "TemplateElement":
23967 if (parentParent && parentParent.type === "TaggedTemplateExpression" && parent.quasis.length === 1 && parentParent.tag.type === "Identifier" && (parentParent.tag.name === "md" || parentParent.tag.name === "markdown")) {
23968 const text = parent.quasis[0].value.raw.replace(/((?:\\\\)*)\\`/g, (_, backslashes) => "\\".repeat(backslashes.length / 2) + "`");
23969 const indentation = getIndentation(text);
23970 const hasIndent = indentation !== "";
23971 return concat$b([hasIndent ? indent$6(concat$b([softline$5, printMarkdown(text.replace(new RegExp("^".concat(indentation), "gm"), ""))])) : concat$b([literalline$3, dedentToRoot$2(printMarkdown(text))]), softline$5]);
23978 function printMarkdown(text) {
23979 const doc = textToDoc(text, {
23980 parser: "markdown",
23981 __inJsTemplate: true
23983 return stripTrailingHardline$2(escapeTemplateCharacters(doc, true));
23987 function getIndentation(str) {
23988 const firstMatchedIndent = str.match(/^([^\S\n]*)\S/m);
23989 return firstMatchedIndent === null ? "" : firstMatchedIndent[1];
23992 function uncook(cookedValue) {
23993 return cookedValue.replace(/([\\`]|\$\{)/g, "\\$1");
23996 function escapeTemplateCharacters(doc, raw) {
23997 return mapDoc$3(doc, currentDoc => {
23998 if (!currentDoc.parts) {
24003 currentDoc.parts.forEach(part => {
24004 if (typeof part === "string") {
24005 parts.push(raw ? part.replace(/(\\*)`/g, "$1$1\\`") : uncook(part));
24010 return Object.assign({}, currentDoc, {
24016 function transformCssDoc(quasisDoc, path, print) {
24017 const parentNode = path.getValue();
24018 const isEmpty = parentNode.quasis.length === 1 && !parentNode.quasis[0].value.raw.trim();
24024 const expressionDocs = parentNode.expressions ? path.map(print, "expressions") : [];
24025 const newDoc = replacePlaceholders(quasisDoc, expressionDocs);
24026 /* istanbul ignore if */
24029 throw new Error("Couldn't insert all the expressions");
24032 return concat$b(["`", indent$6(concat$b([hardline$8, stripTrailingHardline$2(newDoc)])), softline$5, "`"]);
24033 } // Search all the placeholders in the quasisDoc tree
24034 // and replace them with the expression docs one by one
24035 // returns a new doc with all the placeholders replaced,
24036 // or null if it couldn't replace any expression
24039 function replacePlaceholders(quasisDoc, expressionDocs) {
24040 if (!expressionDocs || !expressionDocs.length) {
24044 const expressions = expressionDocs.slice();
24045 let replaceCounter = 0;
24046 const newDoc = mapDoc$3(quasisDoc, doc => {
24047 if (!doc || !doc.parts || !doc.parts.length) {
24054 const atIndex = parts.indexOf("@");
24055 const placeholderIndex = atIndex + 1;
24057 if (atIndex > -1 && typeof parts[placeholderIndex] === "string" && parts[placeholderIndex].startsWith("prettier-placeholder")) {
24058 // If placeholder is split, join it
24059 const at = parts[atIndex];
24060 const placeholder = parts[placeholderIndex];
24061 const rest = parts.slice(placeholderIndex + 1);
24062 parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest);
24065 const atPlaceholderIndex = parts.findIndex(part => typeof part === "string" && part.startsWith("@prettier-placeholder"));
24067 if (atPlaceholderIndex > -1) {
24068 const placeholder = parts[atPlaceholderIndex];
24069 const rest = parts.slice(atPlaceholderIndex + 1);
24070 const placeholderMatch = placeholder.match(/@prettier-placeholder-(.+)-id([\s\S]*)/);
24071 const placeholderID = placeholderMatch[1]; // When the expression has a suffix appended, like:
24072 // animation: linear ${time}s ease-out;
24074 const suffix = placeholderMatch[2];
24075 const expression = expressions[placeholderID];
24077 parts = parts.slice(0, atPlaceholderIndex).concat(["${", expression, "}" + suffix]).concat(rest);
24080 return Object.assign({}, doc, {
24084 return expressions.length === replaceCounter ? newDoc : null;
24087 function printGraphqlComments(lines) {
24089 let seenComment = false;
24090 lines.map(textLine => textLine.trim()).forEach((textLine, i, array) => {
24091 // Lines are either whitespace only, or a comment (with potential whitespace
24092 // around it). Drop whitespace-only lines.
24093 if (textLine === "") {
24097 if (array[i - 1] === "" && seenComment) {
24098 // If a non-first comment is preceded by a blank (whitespace only) line,
24099 // add in a blank line.
24100 parts.push(concat$b([hardline$8, textLine]));
24102 parts.push(textLine);
24105 seenComment = true;
24106 }); // If `lines` was whitespace only, return `null`.
24108 return parts.length === 0 ? null : join$7(hardline$8, parts);
24111 * Template literal in these contexts:
24112 * <style jsx>{`div{color:red}`}</style>
24119 function isStyledJsx(path) {
24120 const node = path.getValue();
24121 const parent = path.getParentNode();
24122 const parentParent = path.getParentNode(1);
24123 return parentParent && node.quasis && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXElement" && parentParent.openingElement.name.name === "style" && parentParent.openingElement.attributes.some(attribute => attribute.name.name === "jsx") || parent && parent.type === "TaggedTemplateExpression" && parent.tag.type === "Identifier" && parent.tag.name === "css" || parent && parent.type === "TaggedTemplateExpression" && parent.tag.type === "MemberExpression" && parent.tag.object.name === "css" && (parent.tag.property.name === "global" || parent.tag.property.name === "resolve");
24126 * Angular Components can have:
24127 * - Inline HTML template
24128 * - Inline CSS styles
24130 * ...which are both within template literals somewhere
24131 * inside of the Component decorator factory.
24135 * template: `<div>...</div>`,
24136 * styles: [`h1 { color: blue; }`]
24141 function isAngularComponentStyles(path) {
24142 return path.match(node => node.type === "TemplateLiteral", (node, name) => node.type === "ArrayExpression" && name === "elements", (node, name) => (node.type === "Property" || node.type === "ObjectProperty") && node.key.type === "Identifier" && node.key.name === "styles" && name === "value", ...angularComponentObjectExpressionPredicates);
24145 function isAngularComponentTemplate(path) {
24146 return path.match(node => node.type === "TemplateLiteral", (node, name) => (node.type === "Property" || node.type === "ObjectProperty") && node.key.type === "Identifier" && node.key.name === "template" && name === "value", ...angularComponentObjectExpressionPredicates);
24149 const angularComponentObjectExpressionPredicates = [(node, name) => node.type === "ObjectExpression" && name === "properties", (node, name) => node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "Component" && name === "arguments", (node, name) => node.type === "Decorator" && name === "expression"];
24151 * styled-components template literals
24154 function isStyledComponents(path) {
24155 const parent = path.getParentNode();
24157 if (!parent || parent.type !== "TaggedTemplateExpression") {
24165 switch (tag.type) {
24166 case "MemberExpression":
24167 return (// styled.foo``
24168 isStyledIdentifier(tag.object) || // Component.extend``
24169 isStyledExtend(tag)
24172 case "CallExpression":
24173 return (// styled(Component)``
24174 isStyledIdentifier(tag.callee) || tag.callee.type === "MemberExpression" && (tag.callee.object.type === "MemberExpression" && ( // styled.foo.attrs({})``
24175 isStyledIdentifier(tag.callee.object.object) || // Component.extend.attrs({})``
24176 isStyledExtend(tag.callee.object)) || // styled(Component).attrs({})``
24177 tag.callee.object.type === "CallExpression" && isStyledIdentifier(tag.callee.object.callee))
24182 return tag.name === "css";
24189 * JSX element with CSS prop
24193 function isCssProp(path) {
24194 const parent = path.getParentNode();
24195 const parentParent = path.getParentNode(1);
24196 return parentParent && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" && parentParent.name.type === "JSXIdentifier" && parentParent.name.name === "css";
24199 function isStyledIdentifier(node) {
24200 return node.type === "Identifier" && node.name === "styled";
24203 function isStyledExtend(node) {
24204 return /^[A-Z]/.test(node.object.name) && node.property.name === "extend";
24207 * react-relay and graphql-tag
24209 * graphql.experimental`...`
24211 * GraphQL comment block
24213 * This intentionally excludes Relay Classic tags, as Prettier does not
24214 * support Relay Classic formatting.
24218 function isGraphQL(path) {
24219 const node = path.getValue();
24220 const parent = path.getParentNode();
24221 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");
24224 function hasLanguageComment(node, languageName) {
24225 // This checks for a leading comment that is exactly `/* GraphQL */`
24226 // In order to be in line with other implementations of this comment tag
24227 // we will not trim the comment value and we will expect exactly one space on
24228 // either side of the GraphQL string
24229 // Also see ./clean.js
24230 return hasLeadingComment$1(node, comment => isBlockComment$1(comment) && comment.value === " ".concat(languageName, " "));
24234 * - HTML comment block
24238 function isHtml(path) {
24239 return hasLanguageComment(path.getValue(), "HTML") || path.match(node => node.type === "TemplateLiteral", (node, name) => node.type === "TaggedTemplateExpression" && node.tag.type === "Identifier" && node.tag.name === "html" && name === "quasi");
24240 } // The counter is needed to distinguish nested embeds.
24243 let htmlTemplateLiteralCounter = 0;
24245 function printHtmlTemplateLiteral(path, print, textToDoc, parser, options) {
24246 const node = path.getValue();
24247 const counter = htmlTemplateLiteralCounter;
24248 htmlTemplateLiteralCounter = htmlTemplateLiteralCounter + 1 >>> 0;
24250 const composePlaceholder = index => "PRETTIER_HTML_PLACEHOLDER_".concat(index, "_").concat(counter, "_IN_JS");
24252 const text = node.quasis.map((quasi, index, quasis) => index === quasis.length - 1 ? quasi.value.cooked : quasi.value.cooked + composePlaceholder(index)).join("");
24253 const expressionDocs = path.map(print, "expressions");
24255 if (expressionDocs.length === 0 && text.trim().length === 0) {
24259 const placeholderRegex = new RegExp(composePlaceholder("(\\d+)"), "g");
24260 let topLevelCount = 0;
24261 const contentDoc = mapDoc$3(stripTrailingHardline$2(textToDoc(text, {
24264 __onHtmlRoot(root) {
24265 topLevelCount = root.children.length;
24269 if (typeof doc !== "string") {
24274 const components = doc.split(placeholderRegex);
24276 for (let i = 0; i < components.length; i++) {
24277 let component = components[i];
24281 component = uncook(component);
24283 if (options.embeddedInHtml) {
24284 component = component.replace(/<\/(script)\b/gi, "<\\/$1");
24287 parts.push(component);
24293 const placeholderIndex = +component;
24294 parts.push(concat$b(["${", group$a(expressionDocs[placeholderIndex]), "}"]));
24297 return concat$b(parts);
24299 const leadingWhitespace = /^\s/.test(text) ? " " : "";
24300 const trailingWhitespace = /\s$/.test(text) ? " " : "";
24301 const linebreak = options.htmlWhitespaceSensitivity === "ignore" ? hardline$8 : leadingWhitespace && trailingWhitespace ? line$7 : null;
24304 return group$a(concat$b(["`", indent$6(concat$b([linebreak, group$a(contentDoc)])), linebreak, "`"]));
24307 return group$a(concat$b(["`", leadingWhitespace, topLevelCount > 1 ? indent$6(group$a(contentDoc)) : group$a(contentDoc), trailingWhitespace, "`"]));
24310 var embed_1$1 = embed$3;
24312 function clean$4(ast, newObj, parent) {
24313 ["range", "raw", "comments", "leadingComments", "trailingComments", "innerComments", "extra", "start", "end", "flags", "errors"].forEach(name => {
24314 delete newObj[name];
24317 if (ast.loc && ast.loc.source === null) {
24318 delete newObj.loc.source;
24321 if (ast.type === "BigIntLiteral") {
24322 newObj.value = newObj.value.toLowerCase();
24323 } // We remove extra `;` and add them when needed
24326 if (ast.type === "EmptyStatement") {
24328 } // We move text around, including whitespaces and add {" "}
24331 if (ast.type === "JSXText") {
24335 if (ast.type === "JSXExpressionContainer" && ast.expression.type === "Literal" && ast.expression.value === " ") {
24337 } // (TypeScript) Ignore `static` in `constructor(static p) {}`
24338 // and `export` in `constructor(export p) {}`
24341 if (ast.type === "TSParameterProperty" && ast.accessibility === null && !ast.readonly) {
24343 type: "Identifier",
24344 name: ast.parameter.name,
24345 typeAnnotation: newObj.parameter.typeAnnotation,
24346 decorators: newObj.decorators
24348 } // (TypeScript) ignore empty `specifiers` array
24351 if (ast.type === "TSNamespaceExportDeclaration" && ast.specifiers && ast.specifiers.length === 0) {
24352 delete newObj.specifiers;
24353 } // We convert <div></div> to <div />
24356 if (ast.type === "JSXOpeningElement") {
24357 delete newObj.selfClosing;
24360 if (ast.type === "JSXElement") {
24361 delete newObj.closingElement;
24362 } // We change {'key': value} into {key: value}
24365 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")) {
24369 if (ast.type === "OptionalMemberExpression" && ast.optional === false) {
24370 newObj.type = "MemberExpression";
24371 delete newObj.optional;
24372 } // Remove raw and cooked values from TemplateElement when it's CSS
24376 if (ast.type === "JSXElement" && ast.openingElement.name.name === "style" && ast.openingElement.attributes.some(attr => attr.name.name === "jsx")) {
24377 const templateLiterals = newObj.children.filter(child => child.type === "JSXExpressionContainer" && child.expression.type === "TemplateLiteral").map(container => container.expression);
24378 const quasis = templateLiterals.reduce((quasis, templateLiteral) => quasis.concat(templateLiteral.quasis), []);
24379 quasis.forEach(q => delete q.value);
24380 } // CSS template literals in css prop
24383 if (ast.type === "JSXAttribute" && ast.name.name === "css" && ast.value.type === "JSXExpressionContainer" && ast.value.expression.type === "TemplateLiteral") {
24384 newObj.value.expression.quasis.forEach(q => delete q.value);
24385 } // Angular Components: Inline HTML template and Inline CSS styles
24388 const expression = ast.expression || ast.callee;
24390 if (ast.type === "Decorator" && expression.type === "CallExpression" && expression.callee.name === "Component" && expression.arguments.length === 1) {
24391 const astProps = ast.expression.arguments[0].properties;
24392 newObj.expression.arguments[0].properties.forEach((prop, index) => {
24393 let templateLiteral = null;
24395 switch (astProps[index].key.name) {
24397 if (prop.value.type === "ArrayExpression") {
24398 templateLiteral = prop.value.elements[0];
24404 if (prop.value.type === "TemplateLiteral") {
24405 templateLiteral = prop.value;
24411 if (templateLiteral) {
24412 templateLiteral.quasis.forEach(q => delete q.value);
24415 } // styled-components, graphql, markdown
24418 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")) {
24419 newObj.quasi.quasis.forEach(quasi => delete quasi.value);
24422 if (ast.type === "TemplateLiteral") {
24423 // This checks for a leading comment that is exactly `/* GraphQL */`
24424 // In order to be in line with other implementations of this comment tag
24425 // we will not trim the comment value and we will expect exactly one space on
24426 // either side of the GraphQL string
24427 // Also see ./embed.js
24428 const hasLanguageComment = ast.leadingComments && ast.leadingComments.some(comment => comment.type === "CommentBlock" && ["GraphQL", "HTML"].some(languageName => comment.value === " ".concat(languageName, " ")));
24430 if (hasLanguageComment || parent.type === "CallExpression" && parent.callee.name === "graphql") {
24431 newObj.quasis.forEach(quasi => delete quasi.value);
24436 var clean_1$1 = clean$4;
24439 getLast: getLast$2,
24440 hasNewline: hasNewline$4,
24441 hasNewlineInRange: hasNewlineInRange$2,
24442 hasIgnoreComment: hasIgnoreComment$3,
24443 hasNodeIgnoreComment: hasNodeIgnoreComment$1,
24444 skipWhitespace: skipWhitespace$2
24446 const isIdentifierName = utils$1.keyword.isIdentifierNameES5; // We match any whitespace except line terminators because
24447 // Flow annotation comments cannot be split across lines. For example:
24450 // : any */).foo = 5;
24452 // is not picked up by Flow (see https://github.com/facebook/flow/issues/7050), so
24453 // removing the newline would create a type annotation that the user did not intend
24456 const NON_LINE_TERMINATING_WHITE_SPACE = "(?:(?=.)\\s)";
24457 const FLOW_SHORTHAND_ANNOTATION = new RegExp("^".concat(NON_LINE_TERMINATING_WHITE_SPACE, "*:"));
24458 const FLOW_ANNOTATION = new RegExp("^".concat(NON_LINE_TERMINATING_WHITE_SPACE, "*::"));
24460 function hasFlowShorthandAnnotationComment(node) {
24461 // https://flow.org/en/docs/types/comments/
24462 // Syntax example: const r = new (window.Request /*: Class<Request> */)("");
24463 return node.extra && node.extra.parenthesized && node.trailingComments && node.trailingComments[0].value.match(FLOW_SHORTHAND_ANNOTATION);
24466 function hasFlowAnnotationComment(comments) {
24467 return comments && comments[0].value.match(FLOW_ANNOTATION);
24470 function hasNode(node, fn) {
24471 if (!node || typeof node !== "object") {
24475 if (Array.isArray(node)) {
24476 return node.some(value => hasNode(value, fn));
24479 const result = fn(node);
24480 return typeof result === "boolean" ? result : Object.keys(node).some(key => hasNode(node[key], fn));
24483 function hasNakedLeftSide(node) {
24484 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";
24487 function getLeftSide(node) {
24488 if (node.expressions) {
24489 return node.expressions[0];
24492 return node.left || node.test || node.callee || node.object || node.tag || node.argument || node.expression;
24495 function getLeftSidePathName(path, node) {
24496 if (node.expressions) {
24497 return ["expressions", 0];
24520 if (node.argument) {
24521 return ["argument"];
24524 if (node.expression) {
24525 return ["expression"];
24528 throw new Error("Unexpected node has no left side", node);
24531 const exportDeclarationTypes = new Set(["ExportDefaultDeclaration", "ExportDefaultSpecifier", "DeclareExportDeclaration", "ExportNamedDeclaration", "ExportAllDeclaration"]);
24533 function isExportDeclaration(node) {
24534 return node && exportDeclarationTypes.has(node.type);
24537 function getParentExportDeclaration(path) {
24538 const parentNode = path.getParentNode();
24540 if (path.getName() === "declaration" && isExportDeclaration(parentNode)) {
24547 function isLiteral(node) {
24548 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";
24551 function isNumericLiteral(node) {
24552 return node.type === "NumericLiteral" || node.type === "Literal" && typeof node.value === "number";
24555 function isStringLiteral(node) {
24556 return node.type === "StringLiteral" || node.type === "Literal" && typeof node.value === "string";
24559 function isObjectType(n) {
24560 return n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral";
24563 function isFunctionOrArrowExpression(node) {
24564 return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
24567 function isFunctionOrArrowExpressionWithBody(node) {
24568 return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement";
24571 function isTemplateLiteral(node) {
24572 return node.type === "TemplateLiteral";
24573 } // `inject` is used in AngularJS 1.x, `async` in Angular 2+
24574 // example: https://docs.angularjs.org/guide/unit-testing#using-beforeall-
24577 function isAngularTestWrapper(node) {
24578 return (node.type === "CallExpression" || node.type === "OptionalCallExpression") && node.callee.type === "Identifier" && (node.callee.name === "async" || node.callee.name === "inject" || node.callee.name === "fakeAsync");
24581 function isJSXNode(node) {
24582 return node.type === "JSXElement" || node.type === "JSXFragment";
24585 function isTheOnlyJSXElementInMarkdown(options, path) {
24586 if (options.parentParser !== "markdown" && options.parentParser !== "mdx") {
24590 const node = path.getNode();
24592 if (!node.expression || !isJSXNode(node.expression)) {
24596 const parent = path.getParentNode();
24597 return parent.type === "Program" && parent.body.length === 1;
24598 } // Detect an expression node representing `{" "}`
24601 function isJSXWhitespaceExpression(node) {
24602 return node.type === "JSXExpressionContainer" && isLiteral(node.expression) && node.expression.value === " " && !node.expression.comments;
24605 function isMemberExpressionChain(node) {
24606 if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") {
24610 if (node.object.type === "Identifier") {
24614 return isMemberExpressionChain(node.object);
24617 function isGetterOrSetter(node) {
24618 return node.kind === "get" || node.kind === "set";
24621 function sameLocStart(nodeA, nodeB, options) {
24622 return options.locStart(nodeA) === options.locStart(nodeB);
24623 } // TODO: This is a bad hack and we need a better way to distinguish between
24624 // arrow functions and otherwise
24627 function isFunctionNotation(node, options) {
24628 return isGetterOrSetter(node) || sameLocStart(node, node.value, options);
24629 } // Hack to differentiate between the following two which have the same ast
24630 // type T = { method: () => void };
24631 // type T = { method(): void };
24634 function isObjectTypePropertyAFunction(node, options) {
24635 return (node.type === "ObjectTypeProperty" || node.type === "ObjectTypeInternalSlot") && node.value.type === "FunctionTypeAnnotation" && !node.static && !isFunctionNotation(node, options);
24636 } // Hack to differentiate between the following two which have the same ast
24637 // declare function f(a): void;
24638 // var f: (a) => void;
24641 function isTypeAnnotationAFunction(node, options) {
24642 return (node.type === "TypeAnnotation" || node.type === "TSTypeAnnotation") && node.typeAnnotation.type === "FunctionTypeAnnotation" && !node.static && !sameLocStart(node, node.typeAnnotation, options);
24645 const binaryishNodeTypes = new Set(["BinaryExpression", "LogicalExpression", "NGPipeExpression"]);
24647 function isBinaryish(node) {
24648 return binaryishNodeTypes.has(node.type);
24651 function isMemberish(node) {
24652 return node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "BindExpression" && node.object;
24655 function isSimpleFlowType(node) {
24656 const flowTypeAnnotations = ["AnyTypeAnnotation", "NullLiteralTypeAnnotation", "GenericTypeAnnotation", "ThisTypeAnnotation", "NumberTypeAnnotation", "VoidTypeAnnotation", "EmptyTypeAnnotation", "MixedTypeAnnotation", "BooleanTypeAnnotation", "BooleanLiteralTypeAnnotation", "StringTypeAnnotation"];
24657 return node && flowTypeAnnotations.includes(node.type) && !(node.type === "GenericTypeAnnotation" && node.typeParameters);
24660 const unitTestRe = /^(skip|[fx]?(it|describe|test))$/;
24662 function isSkipOrOnlyBlock(node) {
24663 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");
24666 function isUnitTestSetUp(n) {
24667 const unitTestSetUpRe = /^(before|after)(Each|All)$/;
24668 return n.callee.type === "Identifier" && unitTestSetUpRe.test(n.callee.name) && n.arguments.length === 1;
24669 } // eg; `describe("some string", (done) => {})`
24672 function isTestCall(n, parent) {
24673 if (n.type !== "CallExpression") {
24677 if (n.arguments.length === 1) {
24678 if (isAngularTestWrapper(n) && parent && isTestCall(parent)) {
24679 return isFunctionOrArrowExpression(n.arguments[0]);
24682 if (isUnitTestSetUp(n)) {
24683 return isAngularTestWrapper(n.arguments[0]);
24685 } else if (n.arguments.length === 2 || n.arguments.length === 3) {
24686 if ((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name) || isSkipOrOnlyBlock(n)) && (isTemplateLiteral(n.arguments[0]) || isStringLiteral(n.arguments[0]))) {
24687 // it("name", () => { ... }, 2500)
24688 if (n.arguments[2] && !isNumericLiteral(n.arguments[2])) {
24692 return (n.arguments.length === 2 ? isFunctionOrArrowExpression(n.arguments[1]) : isFunctionOrArrowExpressionWithBody(n.arguments[1]) && n.arguments[1].params.length <= 1) || isAngularTestWrapper(n.arguments[1]);
24699 function hasLeadingComment$2(node) {
24700 return node.comments && node.comments.some(comment => comment.leading);
24703 function hasTrailingComment(node) {
24704 return node.comments && node.comments.some(comment => comment.trailing);
24707 function isCallOrOptionalCallExpression(node) {
24708 return node.type === "CallExpression" || node.type === "OptionalCallExpression";
24711 function hasDanglingComments(node) {
24712 return node.comments && node.comments.some(comment => !comment.leading && !comment.trailing);
24714 /** identify if an angular expression seems to have side effects */
24717 function hasNgSideEffect(path) {
24718 return hasNode(path.getValue(), node => {
24719 switch (node.type) {
24723 case "CallExpression":
24724 case "OptionalCallExpression":
24725 case "AssignmentExpression":
24731 function isNgForOf(node, index, parentNode) {
24732 return node.type === "NGMicrosyntaxKeyedExpression" && node.key.name === "of" && index === 1 && parentNode.body[0].type === "NGMicrosyntaxLet" && parentNode.body[0].value === null;
24734 /** @param node {import("estree").TemplateLiteral} */
24737 function isSimpleTemplateLiteral(node) {
24738 if (node.expressions.length === 0) {
24742 return node.expressions.every(expr => {
24743 // Disallow comments since printDocToString can't print them here
24744 if (expr.comments) {
24746 } // Allow `x` and `this`
24749 if (expr.type === "Identifier" || expr.type === "ThisExpression") {
24751 } // Allow `a.b.c`, `a.b[c]`, and `this.x.y`
24754 if (expr.type === "MemberExpression" || expr.type === "OptionalMemberExpression") {
24757 while (head.type === "MemberExpression" || head.type === "OptionalMemberExpression") {
24758 if (head.property.type !== "Identifier" && head.property.type !== "Literal" && head.property.type !== "StringLiteral" && head.property.type !== "NumericLiteral") {
24762 head = head.object;
24764 if (head.comments) {
24769 if (head.type === "Identifier" || head.type === "ThisExpression") {
24780 function getFlowVariance(path) {
24781 if (!path.variance) {
24783 } // Babel 7.0 currently uses variance node type, and flow should
24784 // follow suit soon:
24785 // https://github.com/babel/babel/issues/4722
24788 const variance = path.variance.kind || path.variance;
24790 switch (variance) {
24798 /* istanbul ignore next */
24803 function classPropMayCauseASIProblems(path) {
24804 const node = path.getNode();
24806 if (node.type !== "ClassProperty") {
24810 const name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today
24811 // so isn't properly tested yet.
24813 if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) {
24818 function classChildNeedsASIProtection(node) {
24823 if (node.static || node.accessibility // TypeScript
24828 if (!node.computed) {
24829 const name = node.key && node.key.name;
24831 if (name === "in" || name === "instanceof") {
24836 switch (node.type) {
24837 case "ClassProperty":
24838 case "TSAbstractClassProperty":
24839 return node.computed;
24841 case "MethodDefinition": // Flow
24843 case "TSAbstractMethodDefinition": // TypeScript
24845 case "ClassMethod":
24846 case "ClassPrivateMethod":
24849 const isAsync = node.value ? node.value.async : node.async;
24850 const isGenerator = node.value ? node.value.generator : node.generator;
24852 if (isAsync || node.kind === "get" || node.kind === "set") {
24856 if (node.computed || isGenerator) {
24863 case "TSIndexSignature":
24867 /* istanbul ignore next */
24872 function getTypeScriptMappedTypeModifier(tokenNode, keyword) {
24873 if (tokenNode === "+") {
24874 return "+" + keyword;
24875 } else if (tokenNode === "-") {
24876 return "-" + keyword;
24882 function hasNewlineBetweenOrAfterDecorators(node, options) {
24883 return hasNewlineInRange$2(options.originalText, options.locStart(node.decorators[0]), options.locEnd(getLast$2(node.decorators))) || hasNewline$4(options.originalText, options.locEnd(getLast$2(node.decorators)));
24884 } // Only space, newline, carriage return, and tab are treated as whitespace
24888 const jsxWhitespaceChars = " \n\r\t";
24889 const matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)");
24890 const containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]"); // Meaningful if it contains non-whitespace characters,
24891 // or it contains whitespace without a new line.
24893 function isMeaningfulJSXText(node) {
24894 return isLiteral(node) && (containsNonJsxWhitespaceRegex.test(rawText(node)) || !/\n/.test(rawText(node)));
24897 function hasJsxIgnoreComment(path) {
24898 const node = path.getValue();
24899 const parent = path.getParentNode();
24901 if (!parent || !node || !isJSXNode(node) || !isJSXNode(parent)) {
24903 } // Lookup the previous sibling, ignoring any empty JSXText elements
24906 const index = parent.children.indexOf(node);
24907 let prevSibling = null;
24909 for (let i = index; i > 0; i--) {
24910 const candidate = parent.children[i - 1];
24912 if (candidate.type === "JSXText" && !isMeaningfulJSXText(candidate)) {
24916 prevSibling = candidate;
24920 return prevSibling && prevSibling.type === "JSXExpressionContainer" && prevSibling.expression.type === "JSXEmptyExpression" && prevSibling.expression.comments && prevSibling.expression.comments.find(comment => comment.value.trim() === "prettier-ignore");
24923 function isEmptyJSXElement(node) {
24924 if (node.children.length === 0) {
24928 if (node.children.length > 1) {
24930 } // if there is one text child and does not contain any meaningful text
24931 // we can treat the element as empty.
24934 const child = node.children[0];
24935 return isLiteral(child) && !isMeaningfulJSXText(child);
24938 function hasPrettierIgnore$4(path) {
24939 return hasIgnoreComment$3(path) || hasJsxIgnoreComment(path);
24942 function isLastStatement(path) {
24943 const parent = path.getParentNode();
24949 const node = path.getValue();
24950 const body = (parent.body || parent.consequent).filter(stmt => stmt.type !== "EmptyStatement");
24951 return body && body[body.length - 1] === node;
24954 function isFlowAnnotationComment(text, typeAnnotation, options) {
24955 const start = options.locStart(typeAnnotation);
24956 const end = skipWhitespace$2(text, options.locEnd(typeAnnotation));
24957 return text.slice(start, start + 2) === "/*" && text.slice(end, end + 2) === "*/";
24960 function hasLeadingOwnLineComment(text, node, options) {
24961 if (isJSXNode(node)) {
24962 return hasNodeIgnoreComment$1(node);
24965 const res = node.comments && node.comments.some(comment => comment.leading && hasNewline$4(text, options.locEnd(comment)));
24967 } // This recurses the return argument, looking for the first token
24968 // (the leftmost leaf node) and, if it (or its parents) has any
24969 // leadingComments, returns true (so it can be wrapped in parens).
24972 function returnArgumentHasLeadingComment(options, argument) {
24973 if (hasLeadingOwnLineComment(options.originalText, argument, options)) {
24977 if (hasNakedLeftSide(argument)) {
24978 let leftMost = argument;
24981 while (newLeftMost = getLeftSide(leftMost)) {
24982 leftMost = newLeftMost;
24984 if (hasLeadingOwnLineComment(options.originalText, leftMost, options)) {
24993 function isStringPropSafeToCoerceToIdentifier(node, options) {
24994 return isStringLiteral(node.key) && isIdentifierName(node.key.value) && options.parser !== "json" && // With `--strictPropertyInitialization`, TS treats properties with quoted names differently than unquoted ones.
24995 // See https://github.com/microsoft/TypeScript/pull/20075
24996 !((options.parser === "typescript" || options.parser === "babel-ts") && node.type === "ClassProperty");
24999 function isJestEachTemplateLiteral(node, parentNode) {
25001 * describe.each`table`(name, fn)
25002 * describe.only.each`table`(name, fn)
25003 * describe.skip.each`table`(name, fn)
25004 * test.each`table`(name, fn)
25005 * test.only.each`table`(name, fn)
25006 * test.skip.each`table`(name, fn)
25008 * Ref: https://github.com/facebook/jest/pull/6102
25010 const jestEachTriggerRegex = /^[xf]?(describe|it|test)$/;
25011 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));
25014 function templateLiteralHasNewLines(template) {
25015 return template.quasis.some(quasi => quasi.value.raw.includes("\n"));
25018 function isTemplateOnItsOwnLine(n, text, options) {
25019 return (n.type === "TemplateLiteral" && templateLiteralHasNewLines(n) || n.type === "TaggedTemplateExpression" && templateLiteralHasNewLines(n.quasi)) && !hasNewline$4(text, options.locStart(n), {
25024 function needsHardlineAfterDanglingComment(node) {
25025 if (!node.comments) {
25029 const lastDanglingComment = getLast$2(node.comments.filter(comment => !comment.leading && !comment.trailing));
25030 return lastDanglingComment && !comments$1.isBlockComment(lastDanglingComment);
25031 } // If we have nested conditional expressions, we want to print them in JSX mode
25032 // if there's at least one JSXElement somewhere in the tree.
25034 // A conditional expression chain like this should be printed in normal mode,
25035 // because there aren't JSXElements anywhere in it:
25037 // isA ? "A" : isB ? "B" : isC ? "C" : "Unknown";
25039 // But a conditional expression chain like this should be printed in JSX mode,
25040 // because there is a JSXElement in the last ConditionalExpression:
25042 // isA ? "A" : isB ? "B" : isC ? "C" : <span className="warning">Unknown</span>;
25044 // This type of ConditionalExpression chain is structured like this in the AST:
25046 // ConditionalExpression {
25048 // consequent: ...,
25049 // alternate: ConditionalExpression {
25051 // consequent: ...,
25052 // alternate: ConditionalExpression {
25054 // consequent: ...,
25060 // We want to traverse over that shape and convert it into a flat structure so
25061 // that we can find if there's a JSXElement somewhere inside.
25064 function getConditionalChainContents(node) {
25065 // Given this code:
25067 // // Using a ConditionalExpression as the consequent is uncommon, but should
25069 // A ? B : C ? D : E ? F ? G : H : I
25071 // which has this AST:
25073 // ConditionalExpression {
25074 // test: Identifier(A),
25075 // consequent: Identifier(B),
25076 // alternate: ConditionalExpression {
25077 // test: Identifier(C),
25078 // consequent: Identifier(D),
25079 // alternate: ConditionalExpression {
25080 // test: Identifier(E),
25081 // consequent: ConditionalExpression {
25082 // test: Identifier(F),
25083 // consequent: Identifier(G),
25084 // alternate: Identifier(H),
25086 // alternate: Identifier(I),
25091 // we should return this Array:
25105 // This loses the information about whether each node was the test,
25106 // consequent, or alternate, but we don't care about that here- we are only
25107 // flattening this structure to find if there's any JSXElements inside.
25108 const nonConditionalExpressions = [];
25110 function recurse(node) {
25111 if (node.type === "ConditionalExpression") {
25112 recurse(node.test);
25113 recurse(node.consequent);
25114 recurse(node.alternate);
25116 nonConditionalExpressions.push(node);
25121 return nonConditionalExpressions;
25124 function conditionalExpressionChainContainsJSX(node) {
25125 return Boolean(getConditionalChainContents(node).find(isJSXNode));
25126 } // Logic to check for args with multiple anonymous functions. For instance,
25127 // the following call should be split on multiple lines for readability:
25128 // source.pipe(map((x) => x + x), filter((x) => x % 2 === 0))
25131 function isFunctionCompositionArgs(args) {
25132 if (args.length <= 1) {
25138 for (const arg of args) {
25139 if (isFunctionOrArrowExpression(arg)) {
25145 } else if (isCallOrOptionalCallExpression(arg)) {
25146 for (const childArg of arg.arguments) {
25147 if (isFunctionOrArrowExpression(childArg)) {
25155 } // Logic to determine if a call is a “long curried function call”.
25156 // See https://github.com/prettier/prettier/issues/1420.
25158 // `connect(a, b, c)(d)`
25159 // In the above call expression, the second call is the parent node and the
25160 // first call is the current node.
25163 function isLongCurriedCallExpression(path) {
25164 const node = path.getValue();
25165 const parent = path.getParentNode();
25166 return isCallOrOptionalCallExpression(node) && isCallOrOptionalCallExpression(parent) && parent.callee === node && node.arguments.length > parent.arguments.length && parent.arguments.length > 0;
25169 * @param {import('estree').Node} node
25170 * @param {number} depth
25171 * @returns {boolean}
25175 function isSimpleCallArgument(node, depth) {
25180 const isChildSimple = child => isSimpleCallArgument(child, depth + 1);
25182 const regexpPattern = node.type === "Literal" && node.regex && node.regex.pattern || node.type === "RegExpLiteral" && node.pattern;
25184 if (regexpPattern && regexpPattern.length > 5) {
25188 if (node.type === "Literal" || node.type === "BooleanLiteral" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "StringLiteral" || node.type === "Identifier" || node.type === "ThisExpression" || node.type === "Super" || node.type === "BigIntLiteral" || node.type === "PrivateName" || node.type === "ArgumentPlaceholder" || node.type === "RegExpLiteral" || node.type === "Import") {
25192 if (node.type === "TemplateLiteral") {
25193 return node.expressions.every(isChildSimple);
25196 if (node.type === "ObjectExpression") {
25197 return node.properties.every(p => !p.computed && (p.shorthand || p.value && isChildSimple(p.value)));
25200 if (node.type === "ArrayExpression") {
25201 return node.elements.every(x => x == null || isChildSimple(x));
25204 if (node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "NewExpression") {
25205 return isSimpleCallArgument(node.callee, depth) && node.arguments.every(isChildSimple);
25208 if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
25209 return isSimpleCallArgument(node.object, depth) && isSimpleCallArgument(node.property, depth);
25212 if (node.type === "UnaryExpression" && (node.operator === "!" || node.operator === "-")) {
25213 return isSimpleCallArgument(node.argument, depth);
25216 if (node.type === "TSNonNullExpression") {
25217 return isSimpleCallArgument(node.expression, depth);
25223 function rawText(node) {
25224 return node.extra ? node.extra.raw : node.raw;
25227 function identity$1(x) {
25231 function isTSXFile(options) {
25232 return options.filepath && /\.tsx$/i.test(options.filepath);
25236 classChildNeedsASIProtection,
25237 classPropMayCauseASIProblems,
25238 conditionalExpressionChainContainsJSX,
25240 getLeftSidePathName,
25241 getParentExportDeclaration,
25242 getTypeScriptMappedTypeModifier,
25243 hasDanglingComments,
25244 hasFlowAnnotationComment,
25245 hasFlowShorthandAnnotationComment,
25246 hasLeadingComment: hasLeadingComment$2,
25247 hasLeadingOwnLineComment,
25249 hasNewlineBetweenOrAfterDecorators,
25252 hasPrettierIgnore: hasPrettierIgnore$4,
25253 hasTrailingComment,
25254 identity: identity$1,
25256 isCallOrOptionalCallExpression,
25258 isExportDeclaration,
25259 isFlowAnnotationComment,
25260 isFunctionCompositionArgs,
25261 isFunctionNotation,
25262 isFunctionOrArrowExpression,
25264 isJestEachTemplateLiteral,
25266 isJSXWhitespaceExpression,
25269 isLongCurriedCallExpression,
25270 isSimpleCallArgument,
25271 isMeaningfulJSXText,
25272 isMemberExpressionChain,
25277 isObjectTypePropertyAFunction,
25279 isSimpleTemplateLiteral,
25281 isStringPropSafeToCoerceToIdentifier,
25282 isTemplateOnItsOwnLine,
25284 isTheOnlyJSXElementInMarkdown,
25286 isTypeAnnotationAFunction,
25287 matchJsxWhitespaceRegex,
25288 needsHardlineAfterDanglingComment,
25290 returnArgumentHasLeadingComment
25294 getLeftSidePathName: getLeftSidePathName$1,
25295 hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$1,
25296 hasNakedLeftSide: hasNakedLeftSide$1,
25300 function needsParens(path, options) {
25301 const parent = path.getParentNode();
25307 const name = path.getName();
25308 const node = path.getNode(); // If the value of this path is some child of a Node and not a Node
25309 // itself, then it doesn't need parentheses. Only Node objects (in
25310 // fact, only Expression nodes) need parentheses.
25312 if (path.getValue() !== node) {
25314 } // to avoid unexpected `}}` in HTML interpolations
25317 if (options.__isInHtmlInterpolation && !options.bracketSpacing && endsWithRightBracket(node) && isFollowedByRightBracket(path)) {
25319 } // Only statements don't need parentheses.
25322 if (isStatement(node)) {
25326 if ( // Preserve parens if we have a Flow annotation comment, unless we're using the Flow
25327 // parser. The Flow parser turns Flow comments into type annotation nodes in its
25328 // AST, which we handle separately.
25329 options.parser !== "flow" && hasFlowShorthandAnnotationComment$1(path.getValue())) {
25331 } // Identifiers never need parentheses.
25334 if (node.type === "Identifier") {
25335 // ...unless those identifiers are embed placeholders. They might be substituted by complex
25336 // expressions, so the parens around them should not be dropped. Example (JS-in-HTML-in-JS):
25337 // let tpl = html`<script> f((${expr}) / 2); </script>`;
25338 // If the inner JS formatter removes the parens, the expression might change its meaning:
25339 // f((a + b) / 2) vs f(a + b / 2)
25340 if (node.extra && node.extra.parenthesized && /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(node.name)) {
25347 if (parent.type === "ParenthesizedExpression") {
25349 } // Add parens around the extends clause of a class. It is needed for almost
25350 // all expressions.
25353 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")) {
25357 if (parent.type === "ExportDefaultDeclaration") {
25358 return (// `export default function` or `export default class` can't be followed by
25359 // anything after. So an expression like `export default (function(){}).toString()`
25360 // needs to be followed by a parentheses
25361 shouldWrapFunctionForExportDefault(path, options) || // `export default (foo, bar)` also needs parentheses
25362 node.type === "SequenceExpression"
25366 if (parent.type === "Decorator" && parent.expression === node) {
25367 let hasCallExpression = false;
25368 let hasMemberExpression = false;
25369 let current = node;
25372 switch (current.type) {
25373 case "MemberExpression":
25374 hasMemberExpression = true;
25375 current = current.object;
25378 case "CallExpression":
25381 hasMemberExpression ||
25383 hasCallExpression) {
25387 hasCallExpression = true;
25388 current = current.callee;
25402 if (parent.type === "ArrowFunctionExpression" && parent.body === node && node.type !== "SequenceExpression" && // these have parens added anyway
25403 util$1.startsWithNoLookaheadToken(node,
25404 /* forbidFunctionClassAndDoExpr */
25405 false) || parent.type === "ExpressionStatement" && util$1.startsWithNoLookaheadToken(node,
25406 /* forbidFunctionClassAndDoExpr */
25411 switch (node.type) {
25412 case "SpreadElement":
25413 case "SpreadProperty":
25414 return parent.type === "MemberExpression" && name === "object" && parent.object === node;
25416 case "UpdateExpression":
25417 if (parent.type === "UnaryExpression") {
25418 return node.prefix && (node.operator === "++" && parent.operator === "+" || node.operator === "--" && parent.operator === "-");
25421 // else fallthrough
25423 case "UnaryExpression":
25424 switch (parent.type) {
25425 case "UnaryExpression":
25426 return node.operator === parent.operator && (node.operator === "+" || node.operator === "-");
25428 case "BindExpression":
25431 case "MemberExpression":
25432 case "OptionalMemberExpression":
25433 return name === "object";
25435 case "TaggedTemplateExpression":
25438 case "NewExpression":
25439 case "CallExpression":
25440 case "OptionalCallExpression":
25441 return name === "callee";
25443 case "BinaryExpression":
25444 return parent.operator === "**" && name === "left";
25446 case "TSNonNullExpression":
25453 case "BinaryExpression":
25455 if (parent.type === "UpdateExpression") {
25459 const isLeftOfAForStatement = node => {
25463 const parent = path.getParentNode(i++);
25469 if (parent.type === "ForStatement" && parent.init === node) {
25479 if (node.operator === "in" && isLeftOfAForStatement(node)) {
25485 case "TSTypeAssertion":
25486 case "TSAsExpression":
25487 case "LogicalExpression":
25488 switch (parent.type) {
25489 case "ConditionalExpression":
25490 return node.type === "TSAsExpression";
25492 case "CallExpression":
25493 case "NewExpression":
25494 case "OptionalCallExpression":
25495 return name === "callee";
25497 case "ClassExpression":
25498 case "ClassDeclaration":
25499 return name === "superClass" && parent.superClass === node;
25501 case "TSTypeAssertion":
25502 case "TaggedTemplateExpression":
25503 case "UnaryExpression":
25504 case "JSXSpreadAttribute":
25505 case "SpreadElement":
25506 case "SpreadProperty":
25507 case "BindExpression":
25508 case "AwaitExpression":
25509 case "TSAsExpression":
25510 case "TSNonNullExpression":
25511 case "UpdateExpression":
25514 case "MemberExpression":
25515 case "OptionalMemberExpression":
25516 return name === "object";
25518 case "AssignmentExpression":
25519 return parent.left === node && (node.type === "TSTypeAssertion" || node.type === "TSAsExpression");
25521 case "LogicalExpression":
25522 if (node.type === "LogicalExpression") {
25523 return parent.operator !== node.operator;
25526 // else fallthrough
25528 case "BinaryExpression":
25530 if (!node.operator && node.type !== "TSTypeAssertion") {
25534 const po = parent.operator;
25535 const pp = util$1.getPrecedence(po);
25536 const no = node.operator;
25537 const np = util$1.getPrecedence(no);
25543 if (pp === np && name === "right") {
25544 assert.strictEqual(parent.right, node);
25548 if (pp === np && !util$1.shouldFlatten(po, no)) {
25552 if (pp < np && no === "%") {
25553 return po === "+" || po === "-";
25554 } // Add parenthesis when working with bitwise operators
25555 // It's not strictly needed but helps with code understanding
25558 if (util$1.isBitwiseOperator(po)) {
25569 case "SequenceExpression":
25570 switch (parent.type) {
25571 case "ReturnStatement":
25574 case "ForStatement":
25575 // Although parentheses wouldn't hurt around sequence
25576 // expressions in the head of for loops, traditional style
25577 // dictates that e.g. i++, j++ should not be wrapped with
25581 case "ExpressionStatement":
25582 return name !== "expression";
25584 case "ArrowFunctionExpression":
25585 // We do need parentheses, but SequenceExpressions are handled
25586 // specially when printing bodies of arrow functions.
25587 return name !== "body";
25590 // Otherwise err on the side of overparenthesization, adding
25591 // explicit exceptions above if this proves overzealous.
25595 case "YieldExpression":
25596 if (parent.type === "UnaryExpression" || parent.type === "AwaitExpression" || parent.type === "TSAsExpression" || parent.type === "TSNonNullExpression") {
25600 // else fallthrough
25602 case "AwaitExpression":
25603 switch (parent.type) {
25604 case "TaggedTemplateExpression":
25605 case "UnaryExpression":
25606 case "BinaryExpression":
25607 case "LogicalExpression":
25608 case "SpreadElement":
25609 case "SpreadProperty":
25610 case "TSAsExpression":
25611 case "TSNonNullExpression":
25612 case "BindExpression":
25615 case "MemberExpression":
25616 case "OptionalMemberExpression":
25617 return name === "object";
25619 case "NewExpression":
25620 case "CallExpression":
25621 case "OptionalCallExpression":
25622 return name === "callee";
25624 case "ConditionalExpression":
25625 return parent.test === node;
25631 case "TSJSDocFunctionType":
25632 case "TSConditionalType":
25633 if (parent.type === "TSConditionalType" && node === parent.extendsType) {
25639 case "TSFunctionType":
25640 case "TSConstructorType":
25641 if (parent.type === "TSConditionalType" && node === parent.checkType) {
25647 case "TSUnionType":
25648 case "TSIntersectionType":
25649 if (parent.type === "TSUnionType" || parent.type === "TSIntersectionType") {
25655 case "TSTypeOperator":
25656 case "TSInferType":
25657 return parent.type === "TSArrayType" || parent.type === "TSOptionalType" || parent.type === "TSRestType" || parent.type === "TSIndexedAccessType" && node === parent.objectType || parent.type === "TSTypeOperator" || parent.type === "TSTypeAnnotation" && /^TSJSDoc/.test(path.getParentNode(1).type);
25659 case "ArrayTypeAnnotation":
25660 return parent.type === "NullableTypeAnnotation";
25662 case "IntersectionTypeAnnotation":
25663 case "UnionTypeAnnotation":
25664 return parent.type === "ArrayTypeAnnotation" || parent.type === "NullableTypeAnnotation" || parent.type === "IntersectionTypeAnnotation" || parent.type === "UnionTypeAnnotation";
25666 case "NullableTypeAnnotation":
25667 return parent.type === "ArrayTypeAnnotation";
25669 case "FunctionTypeAnnotation":
25671 const ancestor = parent.type === "NullableTypeAnnotation" ? path.getParentNode(1) : parent;
25672 return ancestor.type === "UnionTypeAnnotation" || ancestor.type === "IntersectionTypeAnnotation" || ancestor.type === "ArrayTypeAnnotation" || // We should check ancestor's parent to know whether the parentheses
25673 // are really needed, but since ??T doesn't make sense this check
25674 // will almost never be true.
25675 ancestor.type === "NullableTypeAnnotation";
25678 case "StringLiteral":
25679 case "NumericLiteral":
25681 if (typeof node.value === "string" && parent.type === "ExpressionStatement" && ( // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2
25682 // See corresponding workaround in printer.js case: "Literal"
25683 options.parser !== "typescript" && !parent.directive || options.parser === "typescript" && options.originalText.charAt(options.locStart(node) - 1) === "(")) {
25684 // To avoid becoming a directive
25685 const grandParent = path.getParentNode(1);
25686 return grandParent.type === "Program" || grandParent.type === "BlockStatement";
25689 return parent.type === "MemberExpression" && typeof node.value === "number" && name === "object" && parent.object === node;
25691 case "AssignmentExpression":
25693 const grandParent = path.getParentNode(1);
25695 if (parent.type === "ArrowFunctionExpression" && parent.body === node) {
25697 } else if (parent.type === "ClassProperty" && parent.key === node && parent.computed) {
25699 } else if (parent.type === "TSPropertySignature" && parent.name === node) {
25701 } else if (parent.type === "ForStatement" && (parent.init === node || parent.update === node)) {
25703 } else if (parent.type === "ExpressionStatement") {
25704 return node.left.type === "ObjectPattern";
25705 } else if (parent.type === "TSPropertySignature" && parent.key === node) {
25707 } else if (parent.type === "AssignmentExpression") {
25709 } else if (parent.type === "SequenceExpression" && grandParent && grandParent.type === "ForStatement" && (grandParent.init === parent || grandParent.update === parent)) {
25711 } else if (parent.type === "Property" && parent.value === node) {
25713 } else if (parent.type === "NGChainedExpression") {
25720 case "ConditionalExpression":
25721 switch (parent.type) {
25722 case "TaggedTemplateExpression":
25723 case "UnaryExpression":
25724 case "SpreadElement":
25725 case "SpreadProperty":
25726 case "BinaryExpression":
25727 case "LogicalExpression":
25728 case "NGPipeExpression":
25729 case "ExportDefaultDeclaration":
25730 case "AwaitExpression":
25731 case "JSXSpreadAttribute":
25732 case "TSTypeAssertion":
25733 case "TypeCastExpression":
25734 case "TSAsExpression":
25735 case "TSNonNullExpression":
25738 case "NewExpression":
25739 case "CallExpression":
25740 case "OptionalCallExpression":
25741 return name === "callee";
25743 case "ConditionalExpression":
25744 return name === "test" && parent.test === node;
25746 case "MemberExpression":
25747 case "OptionalMemberExpression":
25748 return name === "object";
25754 case "FunctionExpression":
25755 switch (parent.type) {
25756 case "NewExpression":
25757 case "CallExpression":
25758 case "OptionalCallExpression":
25759 // Not always necessary, but it's clearer to the reader if IIFEs are wrapped in parentheses.
25760 // Is necessary if it is `expression` of `ExpressionStatement`.
25761 return name === "callee";
25763 case "TaggedTemplateExpression":
25765 // This is basically a kind of IIFE.
25771 case "ArrowFunctionExpression":
25772 switch (parent.type) {
25773 case "NewExpression":
25774 case "CallExpression":
25775 case "OptionalCallExpression":
25776 return name === "callee";
25778 case "MemberExpression":
25779 case "OptionalMemberExpression":
25780 return name === "object";
25782 case "TSAsExpression":
25783 case "BindExpression":
25784 case "TaggedTemplateExpression":
25785 case "UnaryExpression":
25786 case "LogicalExpression":
25787 case "BinaryExpression":
25788 case "AwaitExpression":
25789 case "TSTypeAssertion":
25792 case "ConditionalExpression":
25793 return name === "test";
25799 case "ClassExpression":
25800 switch (parent.type) {
25801 case "NewExpression":
25802 return name === "callee" && parent.callee === node;
25808 case "OptionalMemberExpression":
25809 case "OptionalCallExpression":
25810 if (parent.type === "MemberExpression" && name === "object" || (parent.type === "CallExpression" || parent.type === "NewExpression") && name === "callee") {
25816 case "CallExpression":
25817 case "MemberExpression":
25818 case "TaggedTemplateExpression":
25819 case "TSNonNullExpression":
25820 if ((parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee") {
25824 switch (object.type) {
25825 case "CallExpression":
25826 case "OptionalCallExpression":
25829 case "MemberExpression":
25830 case "OptionalMemberExpression":
25831 case "BindExpression":
25832 object = object.object;
25834 // tagged templates are basically member expressions from a grammar perspective
25835 // see https://tc39.github.io/ecma262/#prod-MemberExpression
25837 case "TaggedTemplateExpression":
25838 object = object.tag;
25841 case "TSNonNullExpression":
25842 object = object.expression;
25853 case "BindExpression":
25854 return (parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && name === "object";
25856 case "NGPipeExpression":
25857 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") {
25863 case "JSXFragment":
25865 return name === "callee" || parent.type !== "ArrayExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "AssignmentExpression" && parent.type !== "AssignmentPattern" && parent.type !== "BinaryExpression" && parent.type !== "CallExpression" && parent.type !== "NewExpression" && parent.type !== "ConditionalExpression" && parent.type !== "ExpressionStatement" && parent.type !== "JsExpressionRoot" && parent.type !== "JSXAttribute" && parent.type !== "JSXElement" && parent.type !== "JSXExpressionContainer" && parent.type !== "JSXFragment" && parent.type !== "LogicalExpression" && parent.type !== "ObjectProperty" && parent.type !== "OptionalCallExpression" && parent.type !== "Property" && parent.type !== "ReturnStatement" && parent.type !== "ThrowStatement" && parent.type !== "TypeCastExpression" && parent.type !== "VariableDeclarator" && parent.type !== "YieldExpression";
25867 case "TypeAnnotation":
25868 return name === "returnType" && parent.type === "ArrowFunctionExpression" && includesFunctionTypeInObjectType(node);
25874 function isStatement(node) {
25875 return node.type === "BlockStatement" || node.type === "BreakStatement" || node.type === "ClassBody" || node.type === "ClassDeclaration" || node.type === "ClassMethod" || node.type === "ClassProperty" || node.type === "ClassPrivateProperty" || node.type === "ContinueStatement" || node.type === "DebuggerStatement" || node.type === "DeclareClass" || node.type === "DeclareExportAllDeclaration" || node.type === "DeclareExportDeclaration" || node.type === "DeclareFunction" || node.type === "DeclareInterface" || node.type === "DeclareModule" || node.type === "DeclareModuleExports" || node.type === "DeclareVariable" || node.type === "DoWhileStatement" || node.type === "EnumDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExpressionStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement" || node.type === "ForStatement" || node.type === "FunctionDeclaration" || node.type === "IfStatement" || node.type === "ImportDeclaration" || node.type === "InterfaceDeclaration" || node.type === "LabeledStatement" || node.type === "MethodDefinition" || node.type === "ReturnStatement" || node.type === "SwitchStatement" || node.type === "ThrowStatement" || node.type === "TryStatement" || node.type === "TSDeclareFunction" || node.type === "TSEnumDeclaration" || node.type === "TSImportEqualsDeclaration" || node.type === "TSInterfaceDeclaration" || node.type === "TSModuleDeclaration" || node.type === "TSNamespaceExportDeclaration" || node.type === "TypeAlias" || node.type === "VariableDeclaration" || node.type === "WhileStatement" || node.type === "WithStatement";
25878 function includesFunctionTypeInObjectType(node) {
25879 return hasNode$1(node, n1 => n1.type === "ObjectTypeAnnotation" && hasNode$1(n1, n2 => n2.type === "FunctionTypeAnnotation" || undefined) || undefined);
25882 function endsWithRightBracket(node) {
25883 switch (node.type) {
25884 case "ObjectExpression":
25892 function isFollowedByRightBracket(path) {
25893 const node = path.getValue();
25894 const parent = path.getParentNode();
25895 const name = path.getName();
25897 switch (parent.type) {
25898 case "NGPipeExpression":
25899 if (typeof name === "number" && parent.arguments[name] === node && parent.arguments.length - 1 === name) {
25900 return path.callParent(isFollowedByRightBracket);
25905 case "ObjectProperty":
25906 if (name === "value") {
25907 const parentParent = path.getParentNode(1);
25908 return parentParent.properties[parentParent.properties.length - 1] === parent;
25913 case "BinaryExpression":
25914 case "LogicalExpression":
25915 if (name === "right") {
25916 return path.callParent(isFollowedByRightBracket);
25921 case "ConditionalExpression":
25922 if (name === "alternate") {
25923 return path.callParent(isFollowedByRightBracket);
25928 case "UnaryExpression":
25929 if (parent.prefix) {
25930 return path.callParent(isFollowedByRightBracket);
25939 function shouldWrapFunctionForExportDefault(path, options) {
25940 const node = path.getValue();
25941 const parent = path.getParentNode();
25943 if (node.type === "FunctionExpression" || node.type === "ClassExpression") {
25944 return parent.type === "ExportDefaultDeclaration" || // in some cases the function is already wrapped
25945 // (e.g. `export default (function() {})();`)
25946 // in this case we don't need to add extra parens
25947 !needsParens(path, options);
25950 if (!hasNakedLeftSide$1(node) || parent.type !== "ExportDefaultDeclaration" && needsParens(path, options)) {
25954 return path.call(childPath => shouldWrapFunctionForExportDefault(childPath, options), ...getLeftSidePathName$1(path, node));
25957 var needsParens_1 = needsParens;
25967 function printHtmlBinding(path, options, print) {
25968 const node = path.getValue();
25970 if (options.__onHtmlBindingRoot && path.getName() === null) {
25971 options.__onHtmlBindingRoot(node, options);
25974 if (node.type !== "File") {
25978 if (options.__isVueForBindingLeft) {
25979 return path.call(functionDeclarationPath => {
25982 } = functionDeclarationPath.getValue();
25983 return concat$c([params.length > 1 ? "(" : "", join$8(concat$c([",", line$8]), functionDeclarationPath.map(print, "params")), params.length > 1 ? ")" : ""]);
25984 }, "program", "body", 0);
25987 if (options.__isVueSlotScope) {
25988 return path.call(functionDeclarationPath => join$8(concat$c([",", line$8]), functionDeclarationPath.map(print, "params")), "program", "body", 0);
25990 } // based on https://github.com/prettier/prettier/blob/master/src/language-html/syntax-vue.js isVueEventBindingExpression()
25993 function isVueEventBindingExpression$2(node) {
25994 switch (node.type) {
25995 case "MemberExpression":
25996 switch (node.property.type) {
25998 case "NumericLiteral":
25999 case "StringLiteral":
26000 return isVueEventBindingExpression$2(node.object);
26013 var htmlBinding = {
26014 isVueEventBindingExpression: isVueEventBindingExpression$2,
26018 function preprocess$1(ast, options) {
26019 switch (options.parser) {
26022 case "json-stringify":
26023 case "__js_expression":
26024 case "__vue_expression":
26025 return Object.assign({}, ast, {
26026 type: options.parser.startsWith("__") ? "JsExpressionRoot" : "JsonRoot",
26029 rootMarker: options.rootMarker
26037 var preprocess_1$1 = preprocess$1;
26040 shouldFlatten: shouldFlatten$1,
26041 getNextNonSpaceNonCommentCharacter: getNextNonSpaceNonCommentCharacter$1,
26042 hasNewline: hasNewline$5,
26043 hasNewlineInRange: hasNewlineInRange$3,
26044 getLast: getLast$3,
26045 getStringWidth: getStringWidth$3,
26046 printString: printString$2,
26047 printNumber: printNumber$2,
26048 hasIgnoreComment: hasIgnoreComment$4,
26049 hasNodeIgnoreComment: hasNodeIgnoreComment$2,
26050 getPenultimate: getPenultimate$1,
26051 startsWithNoLookaheadToken: startsWithNoLookaheadToken$1,
26052 getIndentSize: getIndentSize$2,
26053 getPreferredQuote: getPreferredQuote$1
26056 isNextLineEmpty: isNextLineEmpty$4,
26057 isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$2,
26058 getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$3
26061 insertPragma: insertPragma$7
26064 printHtmlBinding: printHtmlBinding$1,
26065 isVueEventBindingExpression: isVueEventBindingExpression$3
26068 classChildNeedsASIProtection: classChildNeedsASIProtection$1,
26069 classPropMayCauseASIProblems: classPropMayCauseASIProblems$1,
26070 conditionalExpressionChainContainsJSX: conditionalExpressionChainContainsJSX$1,
26071 getFlowVariance: getFlowVariance$1,
26072 getLeftSidePathName: getLeftSidePathName$2,
26073 getParentExportDeclaration: getParentExportDeclaration$1,
26074 getTypeScriptMappedTypeModifier: getTypeScriptMappedTypeModifier$1,
26075 hasDanglingComments: hasDanglingComments$1,
26076 hasFlowAnnotationComment: hasFlowAnnotationComment$1,
26077 hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$2,
26078 hasLeadingComment: hasLeadingComment$3,
26079 hasLeadingOwnLineComment: hasLeadingOwnLineComment$1,
26080 hasNakedLeftSide: hasNakedLeftSide$2,
26081 hasNewlineBetweenOrAfterDecorators: hasNewlineBetweenOrAfterDecorators$1,
26082 hasNgSideEffect: hasNgSideEffect$1,
26083 hasPrettierIgnore: hasPrettierIgnore$5,
26084 hasTrailingComment: hasTrailingComment$1,
26085 identity: identity$2,
26086 isBinaryish: isBinaryish$1,
26087 isCallOrOptionalCallExpression: isCallOrOptionalCallExpression$1,
26088 isEmptyJSXElement: isEmptyJSXElement$1,
26089 isExportDeclaration: isExportDeclaration$1,
26090 isFlowAnnotationComment: isFlowAnnotationComment$1,
26091 isFunctionCompositionArgs: isFunctionCompositionArgs$1,
26092 isFunctionNotation: isFunctionNotation$1,
26093 isFunctionOrArrowExpression: isFunctionOrArrowExpression$1,
26094 isGetterOrSetter: isGetterOrSetter$1,
26095 isJestEachTemplateLiteral: isJestEachTemplateLiteral$1,
26096 isJSXNode: isJSXNode$1,
26097 isJSXWhitespaceExpression: isJSXWhitespaceExpression$1,
26098 isLastStatement: isLastStatement$1,
26099 isLiteral: isLiteral$1,
26100 isLongCurriedCallExpression: isLongCurriedCallExpression$1,
26101 isMeaningfulJSXText: isMeaningfulJSXText$1,
26102 isMemberExpressionChain: isMemberExpressionChain$1,
26103 isMemberish: isMemberish$1,
26104 isNgForOf: isNgForOf$1,
26105 isNumericLiteral: isNumericLiteral$1,
26106 isObjectType: isObjectType$1,
26107 isObjectTypePropertyAFunction: isObjectTypePropertyAFunction$1,
26108 isSimpleCallArgument: isSimpleCallArgument$1,
26109 isSimpleFlowType: isSimpleFlowType$1,
26110 isSimpleTemplateLiteral: isSimpleTemplateLiteral$1,
26111 isStringLiteral: isStringLiteral$1,
26112 isStringPropSafeToCoerceToIdentifier: isStringPropSafeToCoerceToIdentifier$1,
26113 isTemplateOnItsOwnLine: isTemplateOnItsOwnLine$1,
26114 isTestCall: isTestCall$1,
26115 isTheOnlyJSXElementInMarkdown: isTheOnlyJSXElementInMarkdown$1,
26116 isTSXFile: isTSXFile$1,
26117 isTypeAnnotationAFunction: isTypeAnnotationAFunction$1,
26118 matchJsxWhitespaceRegex: matchJsxWhitespaceRegex$1,
26119 needsHardlineAfterDanglingComment: needsHardlineAfterDanglingComment$1,
26120 rawText: rawText$1,
26121 returnArgumentHasLeadingComment: returnArgumentHasLeadingComment$1
26123 const needsQuoteProps = new WeakMap();
26129 hardline: hardline$9,
26130 softline: softline$6,
26131 literalline: literalline$4,
26135 conditionalGroup: conditionalGroup$1,
26137 ifBreak: ifBreak$6,
26138 breakParent: breakParent$3,
26139 lineSuffixBoundary: lineSuffixBoundary$1,
26140 addAlignmentToDoc: addAlignmentToDoc$2,
26144 willBreak: willBreak$1,
26145 isLineNext: isLineNext$1,
26146 isEmpty: isEmpty$1,
26147 removeLines: removeLines$2
26150 printDocToString: printDocToString$2
26155 function shouldPrintComma$1(options, level) {
26156 level = level || "es5";
26158 switch (options.trailingComma) {
26160 if (level === "all") {
26167 if (level === "es5") {
26179 function genericPrint$3(path, options, printPath, args) {
26180 const node = path.getValue();
26181 let needsParens = false;
26182 const linesWithoutParens = printPathNoParens(path, options, printPath, args);
26184 if (!node || isEmpty$1(linesWithoutParens)) {
26185 return linesWithoutParens;
26188 const parentExportDecl = getParentExportDeclaration$1(path);
26189 const decorators = [];
26191 if (node.type === "ClassMethod" || node.type === "ClassPrivateMethod" || node.type === "ClassProperty" || node.type === "TSAbstractClassProperty" || node.type === "ClassPrivateProperty" || node.type === "MethodDefinition" || node.type === "TSAbstractMethodDefinition" || node.type === "TSDeclareMethod") ; else if (node.decorators && node.decorators.length > 0 && // If the parent node is an export declaration and the decorator
26192 // was written before the export, the export will be responsible
26193 // for printing the decorators.
26194 !(parentExportDecl && options.locStart(parentExportDecl, {
26195 ignoreDecorators: true
26196 }) > options.locStart(node.decorators[0]))) {
26197 const shouldBreak = node.type === "ClassExpression" || node.type === "ClassDeclaration" || hasNewlineBetweenOrAfterDecorators$1(node, options);
26198 const separator = shouldBreak ? hardline$9 : line$9;
26199 path.each(decoratorPath => {
26200 let decorator = decoratorPath.getValue();
26202 if (decorator.expression) {
26203 decorator = decorator.expression;
26205 decorator = decorator.callee;
26208 decorators.push(printPath(decoratorPath), separator);
26211 if (parentExportDecl) {
26212 decorators.unshift(hardline$9);
26214 } 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,
26215 // otherwise they are printed by the node.declaration
26216 options.locStart(node, {
26217 ignoreDecorators: true
26218 }) > options.locStart(node.declaration.decorators[0])) {
26219 // Export declarations are responsible for printing any decorators
26220 // that logically apply to node.declaration.
26221 path.each(decoratorPath => {
26222 const decorator = decoratorPath.getValue();
26223 const prefix = decorator.type === "Decorator" ? "" : "@";
26224 decorators.push(prefix, printPath(decoratorPath), hardline$9);
26225 }, "declaration", "decorators");
26227 // Nodes with decorators can't have parentheses, so we can avoid
26228 // computing pathNeedsParens() except in this case.
26229 needsParens = needsParens_1(path, options);
26235 parts.unshift("(");
26238 parts.push(linesWithoutParens);
26241 const node = path.getValue();
26243 if (hasFlowShorthandAnnotationComment$2(node)) {
26245 parts.push(node.trailingComments[0].value.trimStart());
26247 node.trailingComments[0].printed = true;
26253 if (decorators.length > 0) {
26254 return group$b(concat$d(decorators.concat(parts)));
26257 return concat$d(parts);
26260 function printDecorators(path, options, print) {
26261 const node = path.getValue();
26262 return group$b(concat$d([join$9(line$9, path.map(print, "decorators")), hasNewlineBetweenOrAfterDecorators$1(node, options) ? hardline$9 : line$9]));
26265 * The following is the shared logic for
26266 * ternary operators, namely ConditionalExpression
26267 * and TSConditionalType
26268 * @typedef {Object} OperatorOptions
26269 * @property {() => Array<string | Doc>} beforeParts - Parts to print before the `?`.
26270 * @property {(breakClosingParen: boolean) => Array<string | Doc>} afterParts - Parts to print after the conditional expression.
26271 * @property {boolean} shouldCheckJsx - Whether to check for and print in JSX mode.
26272 * @property {string} conditionalNodeType - The type of the conditional expression node, ie "ConditionalExpression" or "TSConditionalType".
26273 * @property {string} consequentNodePropertyName - The property at which the consequent node can be found on the main node, eg "consequent".
26274 * @property {string} alternateNodePropertyName - The property at which the alternate node can be found on the main node, eg "alternate".
26275 * @property {string[]} testNodePropertyNames - The properties at which the test nodes can be found on the main node, eg "test".
26276 * @param {FastPath} path - The path to the ConditionalExpression/TSConditionalType node.
26277 * @param {Options} options - Prettier options
26278 * @param {Function} print - Print function to call recursively
26279 * @param {OperatorOptions} operatorOptions
26284 function printTernaryOperator(path, options, print, operatorOptions) {
26285 const node = path.getValue();
26286 const consequentNode = node[operatorOptions.consequentNodePropertyName];
26287 const alternateNode = node[operatorOptions.alternateNodePropertyName];
26288 const parts = []; // We print a ConditionalExpression in either "JSX mode" or "normal mode".
26289 // See tests/jsx/conditional-expression.js for more info.
26291 let jsxMode = false;
26292 const parent = path.getParentNode();
26293 const isParentTest = parent.type === operatorOptions.conditionalNodeType && operatorOptions.testNodePropertyNames.some(prop => parent[prop] === node);
26294 let forceNoIndent = parent.type === operatorOptions.conditionalNodeType && !isParentTest; // Find the outermost non-ConditionalExpression parent, and the outermost
26295 // ConditionalExpression parent. We'll use these to determine if we should
26296 // print in JSX mode.
26299 let previousParent;
26303 previousParent = currentParent || node;
26304 currentParent = path.getParentNode(i);
26306 } while (currentParent && currentParent.type === operatorOptions.conditionalNodeType && operatorOptions.testNodePropertyNames.every(prop => currentParent[prop] !== previousParent));
26308 const firstNonConditionalParent = currentParent || parent;
26309 const lastConditionalParent = previousParent;
26311 if (operatorOptions.shouldCheckJsx && (isJSXNode$1(node[operatorOptions.testNodePropertyNames[0]]) || isJSXNode$1(consequentNode) || isJSXNode$1(alternateNode) || conditionalExpressionChainContainsJSX$1(lastConditionalParent))) {
26313 forceNoIndent = true; // Even though they don't need parens, we wrap (almost) everything in
26314 // parens when using ?: within JSX, because the parens are analogous to
26315 // curly braces in an if statement.
26317 const wrap = doc => concat$d([ifBreak$6("(", ""), indent$7(concat$d([softline$6, doc])), softline$6, ifBreak$6(")", "")]); // The only things we don't wrap are:
26318 // * Nested conditional expressions in alternates
26323 const isNil = node => node.type === "NullLiteral" || node.type === "Literal" && node.value === null || node.type === "Identifier" && node.name === "undefined";
26325 parts.push(" ? ", isNil(consequentNode) ? path.call(print, operatorOptions.consequentNodePropertyName) : wrap(path.call(print, operatorOptions.consequentNodePropertyName)), " : ", alternateNode.type === operatorOptions.conditionalNodeType || isNil(alternateNode) ? path.call(print, operatorOptions.alternateNodePropertyName) : wrap(path.call(print, operatorOptions.alternateNodePropertyName)));
26328 const part = concat$d([line$9, "? ", consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$6("", "(") : "", align$1(2, path.call(print, operatorOptions.consequentNodePropertyName)), consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$6("", ")") : "", line$9, ": ", alternateNode.type === operatorOptions.conditionalNodeType ? path.call(print, operatorOptions.alternateNodePropertyName) : align$1(2, path.call(print, operatorOptions.alternateNodePropertyName))]);
26329 parts.push(parent.type !== operatorOptions.conditionalNodeType || parent[operatorOptions.alternateNodePropertyName] === node || isParentTest ? part : options.useTabs ? dedent$2(indent$7(part)) : align$1(Math.max(0, options.tabWidth - 2), part));
26330 } // We want a whole chain of ConditionalExpressions to all
26331 // break if any of them break. That means we should only group around the
26332 // outer-most ConditionalExpression.
26335 const maybeGroup = doc => parent === firstNonConditionalParent ? group$b(doc) : doc; // Break the closing paren to keep the chain right after it:
26342 const breakClosingParen = !jsxMode && (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression" || parent.type === "NGPipeExpression" && parent.left === node) && !parent.computed;
26343 const result = maybeGroup(concat$d([].concat((testDoc =>
26354 parent.type === operatorOptions.conditionalNodeType && parent[operatorOptions.alternateNodePropertyName] === node ? align$1(2, testDoc) : testDoc)(concat$d(operatorOptions.beforeParts())), forceNoIndent ? concat$d(parts) : indent$7(concat$d(parts)), operatorOptions.afterParts(breakClosingParen))));
26355 return isParentTest ? group$b(concat$d([indent$7(concat$d([softline$6, result])), softline$6])) : result;
26358 function printPathNoParens(path, options, print, args) {
26359 const n = path.getValue();
26360 const semi = options.semi ? ";" : "";
26366 if (typeof n === "string") {
26370 const htmlBinding = printHtmlBinding$1(path, options, print);
26373 return htmlBinding;
26379 case "JsExpressionRoot":
26380 return path.call(print, "node");
26383 return concat$d([path.call(print, "node"), hardline$9]);
26386 // Print @babel/parser's InterpreterDirective here so that
26387 // leading comments on the `Program` node get printed after the hashbang.
26388 if (n.program && n.program.interpreter) {
26389 parts.push(path.call(programPath => programPath.call(print, "interpreter"), "program"));
26392 parts.push(path.call(print, "program"));
26393 return concat$d(parts);
26397 if (n.directives) {
26398 path.each(childPath => {
26399 parts.push(print(childPath), semi, hardline$9);
26401 if (isNextLineEmpty$4(options.originalText, childPath.getValue(), options.locEnd)) {
26402 parts.push(hardline$9);
26407 parts.push(path.call(bodyPath => {
26408 return printStatementSequence(bodyPath, options, print);
26410 parts.push(comments.printDanglingComments(path, options,
26412 true)); // Only force a trailing newline if there were any contents.
26414 if (!n.body.every(({
26416 }) => type === "EmptyStatement") || n.comments) {
26417 parts.push(hardline$9);
26420 return concat$d(parts);
26421 // Babel extension.
26423 case "EmptyStatement":
26426 case "ExpressionStatement":
26427 // Detect Flow-parsed directives
26429 return concat$d([nodeStr(n.expression, options, true), semi]);
26432 if (options.parser === "__vue_event_binding") {
26433 const parent = path.getParentNode();
26435 if (parent.type === "Program" && parent.body.length === 1 && parent.body[0] === n) {
26436 return concat$d([path.call(print, "expression"), isVueEventBindingExpression$3(n.expression) ? ";" : ""]);
26438 } // Do not append semicolon after the only JSX element in a program
26441 return concat$d([path.call(print, "expression"), isTheOnlyJSXElementInMarkdown$1(options, path) ? "" : semi]);
26442 // Babel non-standard node. Used for Closure-style type casts. See postprocess.js.
26444 case "ParenthesizedExpression":
26446 const shouldHug = !n.expression.comments;
26449 return concat$d(["(", path.call(print, "expression"), ")"]);
26452 return group$b(concat$d(["(", indent$7(concat$d([softline$6, path.call(print, "expression")])), softline$6, ")"]));
26455 case "AssignmentExpression":
26456 return printAssignment(n.left, path.call(print, "left"), concat$d([" ", n.operator]), n.right, path.call(print, "right"), options);
26458 case "BinaryExpression":
26459 case "LogicalExpression":
26460 case "NGPipeExpression":
26462 const parent = path.getParentNode();
26463 const parentParent = path.getParentNode(1);
26464 const isInsideParenthesis = n !== parent.body && (parent.type === "IfStatement" || parent.type === "WhileStatement" || parent.type === "SwitchStatement" || parent.type === "DoWhileStatement");
26465 const parts = printBinaryishExpressions(path, print, options,
26467 false, isInsideParenthesis); // if (
26468 // this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft
26471 // looks super weird, we want to break the children if the parent breaks
26474 // this.hasPlugin("dynamicImports") &&
26475 // this.lookahead().type === tt.parenLeft
26478 if (isInsideParenthesis) {
26479 return concat$d(parts);
26480 } // Break between the parens in
26481 // unaries or in a member or specific call expression, i.e.
26490 if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || parent.type === "UnaryExpression" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && !parent.computed) {
26491 return group$b(concat$d([indent$7(concat$d([softline$6, concat$d(parts)])), softline$6]));
26492 } // Avoid indenting sub-expressions in some cases where the first sub-expression is already
26493 // indented accordingly. We should indent sub-expressions where the first case isn't indented.
26496 const shouldNotIndent = parent.type === "ReturnStatement" || parent.type === "ThrowStatement" || parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" || n.operator !== "|" && parent.type === "JsExpressionRoot" || n.type !== "NGPipeExpression" && (parent.type === "NGRoot" && options.parser === "__ng_binding" || parent.type === "NGMicrosyntaxExpression" && parentParent.type === "NGMicrosyntax" && parentParent.body.length === 1) || n === parent.body && parent.type === "ArrowFunctionExpression" || n !== parent.body && parent.type === "ForStatement" || parent.type === "ConditionalExpression" && parentParent.type !== "ReturnStatement" && parentParent.type !== "ThrowStatement" && parentParent.type !== "CallExpression" && parentParent.type !== "OptionalCallExpression" || parent.type === "TemplateLiteral";
26497 const shouldIndentIfInlining = parent.type === "AssignmentExpression" || parent.type === "VariableDeclarator" || parent.type === "ClassProperty" || parent.type === "TSAbstractClassProperty" || parent.type === "ClassPrivateProperty" || parent.type === "ObjectProperty" || parent.type === "Property";
26498 const samePrecedenceSubExpression = isBinaryish$1(n.left) && shouldFlatten$1(n.operator, n.left.operator);
26500 if (shouldNotIndent || shouldInlineLogicalExpression(n) && !samePrecedenceSubExpression || !shouldInlineLogicalExpression(n) && shouldIndentIfInlining) {
26501 return group$b(concat$d(parts));
26504 if (parts.length === 0) {
26506 } // If the right part is a JSX node, we include it in a separate group to
26507 // prevent it breaking the whole chain, so we can print the expression like:
26516 const hasJSX = isJSXNode$1(n.right);
26517 const rest = concat$d(hasJSX ? parts.slice(1, -1) : parts.slice(1));
26518 const groupId = Symbol("logicalChain-" + ++uid);
26519 const chain = group$b(concat$d([// Don't include the initial expression in the indentation
26520 // level. The first item is guaranteed to be the first
26521 // left-most expression.
26522 parts.length > 0 ? parts[0] : "", indent$7(rest)]), {
26530 const jsxPart = getLast$3(parts);
26531 return group$b(concat$d([chain, ifBreak$6(indent$7(jsxPart), jsxPart, {
26536 case "AssignmentPattern":
26537 return concat$d([path.call(print, "left"), " = ", path.call(print, "right")]);
26539 case "TSTypeAssertion":
26541 const shouldBreakAfterCast = !(n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression");
26542 const castGroup = group$b(concat$d(["<", indent$7(concat$d([softline$6, path.call(print, "typeAnnotation")])), softline$6, ">"]));
26543 const exprContents = concat$d([ifBreak$6("("), indent$7(concat$d([softline$6, path.call(print, "expression")])), softline$6, ifBreak$6(")")]);
26545 if (shouldBreakAfterCast) {
26546 return conditionalGroup$1([concat$d([castGroup, path.call(print, "expression")]), concat$d([castGroup, group$b(exprContents, {
26548 })]), concat$d([castGroup, path.call(print, "expression")])]);
26551 return group$b(concat$d([castGroup, path.call(print, "expression")]));
26554 case "OptionalMemberExpression":
26555 case "MemberExpression":
26557 const parent = path.getParentNode();
26558 let firstNonMemberParent;
26562 firstNonMemberParent = path.getParentNode(i);
26564 } while (firstNonMemberParent && (firstNonMemberParent.type === "MemberExpression" || firstNonMemberParent.type === "OptionalMemberExpression" || firstNonMemberParent.type === "TSNonNullExpression"));
26566 const shouldInline = firstNonMemberParent && (firstNonMemberParent.type === "NewExpression" || firstNonMemberParent.type === "BindExpression" || firstNonMemberParent.type === "VariableDeclarator" && firstNonMemberParent.id.type !== "Identifier" || firstNonMemberParent.type === "AssignmentExpression" && firstNonMemberParent.left.type !== "Identifier") || n.computed || n.object.type === "Identifier" && n.property.type === "Identifier" && parent.type !== "MemberExpression" && parent.type !== "OptionalMemberExpression";
26567 return concat$d([path.call(print, "object"), shouldInline ? printMemberLookup(path, options, print) : group$b(indent$7(concat$d([softline$6, printMemberLookup(path, options, print)])))]);
26570 case "MetaProperty":
26571 return concat$d([path.call(print, "meta"), ".", path.call(print, "property")]);
26573 case "BindExpression":
26575 parts.push(path.call(print, "object"));
26578 parts.push(group$b(indent$7(concat$d([softline$6, printBindExpressionCallee(path, options, print)]))));
26579 return concat$d(parts);
26583 return concat$d([n.name, printOptionalToken(path), printTypeAnnotation(path, options, print)]);
26586 case "V8IntrinsicIdentifier":
26587 return concat$d(["%", n.name]);
26589 case "SpreadElement":
26590 case "SpreadElementPattern":
26591 case "SpreadProperty":
26592 case "SpreadPropertyPattern":
26593 case "RestElement":
26594 case "ObjectTypeSpreadProperty":
26595 return concat$d(["...", path.call(print, "argument"), printTypeAnnotation(path, options, print)]);
26597 case "FunctionDeclaration":
26598 case "FunctionExpression":
26599 parts.push(printFunctionDeclaration(path, print, options));
26605 return concat$d(parts);
26607 case "ArrowFunctionExpression":
26610 parts.push("async ");
26613 if (shouldPrintParamsWithoutParens(path, options)) {
26614 parts.push(path.call(print, "params", 0));
26616 parts.push(group$b(concat$d([printFunctionParams(path, print, options,
26618 args && (args.expandLastArg || args.expandFirstArg),
26619 /* printTypeParams */
26620 true), printReturnType(path, print, options)])));
26623 const dangling = comments.printDanglingComments(path, options,
26626 const nextCharacter = getNextNonSpaceNonCommentCharacterIndex$3(options.originalText, comment, options.locEnd);
26627 return options.originalText.slice(nextCharacter, nextCharacter + 2) === "=>";
26631 parts.push(" ", dangling);
26635 const body = path.call(bodyPath => print(bodyPath, args), "body"); // We want to always keep these types of nodes on the same line
26638 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")) {
26639 return group$b(concat$d([concat$d(parts), " ", body]));
26640 } // We handle sequence expressions as the body of arrows specially,
26641 // so that the required parentheses end up on their own lines.
26644 if (n.body.type === "SequenceExpression") {
26645 return group$b(concat$d([concat$d(parts), group$b(concat$d([" (", indent$7(concat$d([softline$6, body])), softline$6, ")"]))]));
26646 } // if the arrow function is expanded as last argument, we are adding a
26647 // level of indentation and need to add a softline to align the closing )
26648 // with the opening (, or if it's inside a JSXExpression (e.g. an attribute)
26649 // we should align the expression's closing } with the line with the opening {.
26652 const shouldAddSoftLine = (args && args.expandLastArg || path.getParentNode().type === "JSXExpressionContainer") && !(n.comments && n.comments.length);
26653 const printTrailingComma = args && args.expandLastArg && shouldPrintComma$1(options, "all"); // In order to avoid confusion between
26657 const shouldAddParens = n.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken$1(n.body,
26658 /* forbidFunctionAndClass */
26660 return group$b(concat$d([concat$d(parts), group$b(concat$d([indent$7(concat$d([line$9, shouldAddParens ? ifBreak$6("", "(") : "", body, shouldAddParens ? ifBreak$6("", ")") : ""])), shouldAddSoftLine ? concat$d([ifBreak$6(printTrailingComma ? "," : ""), softline$6]) : ""]))]));
26663 case "YieldExpression":
26664 parts.push("yield");
26671 parts.push(" ", path.call(print, "argument"));
26674 return concat$d(parts);
26676 case "AwaitExpression":
26678 parts.push("await ", path.call(print, "argument"));
26679 const parent = path.getParentNode();
26681 if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && parent.object === n) {
26682 return group$b(concat$d([indent$7(concat$d([softline$6, concat$d(parts)])), softline$6]));
26685 return concat$d(parts);
26688 case "ImportSpecifier":
26689 if (n.importKind) {
26690 parts.push(path.call(print, "importKind"), " ");
26693 parts.push(path.call(print, "imported"));
26695 if (n.local && n.local.name !== n.imported.name) {
26696 parts.push(" as ", path.call(print, "local"));
26699 return concat$d(parts);
26701 case "ExportSpecifier":
26702 parts.push(path.call(print, "local"));
26704 if (n.exported && n.exported.name !== n.local.name) {
26705 parts.push(" as ", path.call(print, "exported"));
26708 return concat$d(parts);
26710 case "ImportNamespaceSpecifier":
26711 parts.push("* as ");
26712 parts.push(path.call(print, "local"));
26713 return concat$d(parts);
26715 case "ImportDefaultSpecifier":
26716 return path.call(print, "local");
26718 case "TSExportAssignment":
26719 return concat$d(["export = ", path.call(print, "expression"), semi]);
26721 case "ExportDefaultDeclaration":
26722 case "ExportNamedDeclaration":
26723 return printExportDeclaration(path, options, print);
26725 case "ExportAllDeclaration":
26726 parts.push("export ");
26728 if (n.exportKind === "type") {
26729 parts.push("type ");
26735 parts.push("as ", path.call(print, "exported"), " ");
26738 parts.push("from ", path.call(print, "source"), semi);
26739 return concat$d(parts);
26741 case "ExportNamespaceSpecifier":
26742 case "ExportDefaultSpecifier":
26743 return path.call(print, "exported");
26745 case "ImportDeclaration":
26747 parts.push("import ");
26749 if (n.importKind && n.importKind !== "value") {
26750 parts.push(n.importKind + " ");
26753 const standalones = [];
26754 const grouped = [];
26756 if (n.specifiers && n.specifiers.length > 0) {
26757 path.each(specifierPath => {
26758 const value = specifierPath.getValue();
26760 if (value.type === "ImportDefaultSpecifier" || value.type === "ImportNamespaceSpecifier") {
26761 standalones.push(print(specifierPath));
26763 grouped.push(print(specifierPath));
26767 if (standalones.length > 0) {
26768 parts.push(join$9(", ", standalones));
26771 if (standalones.length > 0 && grouped.length > 0) {
26775 if (grouped.length === 1 && standalones.length === 0 && n.specifiers && !n.specifiers.some(node => node.comments)) {
26776 parts.push(concat$d(["{", options.bracketSpacing ? " " : "", concat$d(grouped), options.bracketSpacing ? " " : "", "}"]));
26777 } else if (grouped.length >= 1) {
26778 parts.push(group$b(concat$d(["{", indent$7(concat$d([options.bracketSpacing ? line$9 : softline$6, join$9(concat$d([",", line$9]), grouped)])), ifBreak$6(shouldPrintComma$1(options) ? "," : ""), options.bracketSpacing ? line$9 : softline$6, "}"])));
26781 parts.push(" from ");
26782 } else if (n.importKind && n.importKind === "type" || // import {} from 'x'
26783 /{\s*}/.test(options.originalText.slice(options.locStart(n), options.locStart(n.source)))) {
26784 parts.push("{} from ");
26787 parts.push(path.call(print, "source"), semi);
26788 return concat$d(parts);
26794 case "TSModuleBlock":
26795 case "BlockStatement":
26797 const naked = path.call(bodyPath => {
26798 return printStatementSequence(bodyPath, options, print);
26800 const hasContent = n.body.find(node => node.type !== "EmptyStatement");
26801 const hasDirectives = n.directives && n.directives.length > 0;
26802 const parent = path.getParentNode();
26803 const parentParent = path.getParentNode(1);
26805 if (!hasContent && !hasDirectives && !hasDanglingComments$1(n) && (parent.type === "ArrowFunctionExpression" || parent.type === "FunctionExpression" || parent.type === "FunctionDeclaration" || parent.type === "ObjectMethod" || parent.type === "ClassMethod" || parent.type === "ClassPrivateMethod" || parent.type === "ForStatement" || parent.type === "WhileStatement" || parent.type === "DoWhileStatement" || parent.type === "DoExpression" || parent.type === "CatchClause" && !parentParent.finalizer || parent.type === "TSModuleDeclaration")) {
26809 parts.push("{"); // Babel 6
26811 if (hasDirectives) {
26812 path.each(childPath => {
26813 parts.push(indent$7(concat$d([hardline$9, print(childPath), semi])));
26815 if (isNextLineEmpty$4(options.originalText, childPath.getValue(), options.locEnd)) {
26816 parts.push(hardline$9);
26822 parts.push(indent$7(concat$d([hardline$9, naked])));
26825 parts.push(comments.printDanglingComments(path, options));
26826 parts.push(hardline$9, "}");
26827 return concat$d(parts);
26830 case "ReturnStatement":
26831 return concat$d(["return", printReturnAndThrowArgument(path, options, print)]);
26833 case "NewExpression":
26834 case "OptionalCallExpression":
26835 case "CallExpression":
26837 const isNew = n.type === "NewExpression";
26838 const optional = printOptionalToken(path);
26840 if ( // We want to keep CommonJS- and AMD-style require calls, and AMD-style
26841 // define calls, as a unit.
26842 // e.g. `define(["some/lib", (lib) => {`
26843 !isNew && n.callee.type === "Identifier" && (n.callee.name === "require" || n.callee.name === "define") || // Template literals as single arguments
26844 n.arguments.length === 1 && isTemplateOnItsOwnLine$1(n.arguments[0], options.originalText, options) || // Keep test declarations on a single line
26845 // e.g. `it('long name', () => {`
26846 !isNew && isTestCall$1(n, path.getParentNode())) {
26847 return concat$d([isNew ? "new " : "", path.call(print, "callee"), optional, printFunctionTypeParameters(path, options, print), concat$d(["(", join$9(", ", path.map(print, "arguments")), ")"])]);
26848 } // Inline Flow annotation comments following Identifiers in Call nodes need to
26849 // stay with the Identifier. For example:
26851 // foo /*:: <SomeGeneric> */(bar);
26853 // Here, we ensure that such comments stay between the Identifier and the Callee.
26856 const isIdentifierWithFlowAnnotation = n.callee.type === "Identifier" && hasFlowAnnotationComment$1(n.callee.trailingComments);
26858 if (isIdentifierWithFlowAnnotation) {
26859 n.callee.trailingComments[0].printed = true;
26860 } // We detect calls on member lookups and possibly print them in a
26861 // special chain format. See `printMemberChain` for more info.
26864 if (!isNew && isMemberish$1(n.callee) && !path.call(path => needsParens_1(path, options), "callee")) {
26865 return printMemberChain(path, options, print);
26868 const contents = concat$d([isNew ? "new " : "", path.call(print, "callee"), optional, isIdentifierWithFlowAnnotation ? "/*:: ".concat(n.callee.trailingComments[0].value.slice(2).trim(), " */") : "", printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]); // We group here when the callee is itself a call expression.
26869 // See `isLongCurriedCallExpression` for more info.
26871 if (isCallOrOptionalCallExpression$1(n.callee)) {
26872 return group$b(contents);
26878 case "TSInterfaceDeclaration":
26880 parts.push("declare ");
26883 parts.push(n.abstract ? "abstract " : "", printTypeScriptModifiers(path, options, print), "interface ", path.call(print, "id"), n.typeParameters ? path.call(print, "typeParameters") : "", " ");
26885 if (n.extends && n.extends.length) {
26886 parts.push(group$b(indent$7(concat$d([softline$6, "extends ", (n.extends.length === 1 ? identity$2 : indent$7)(join$9(concat$d([",", line$9]), path.map(print, "extends"))), " "]))));
26889 parts.push(path.call(print, "body"));
26890 return concat$d(parts);
26892 case "ObjectTypeInternalSlot":
26893 return concat$d([n.static ? "static " : "", "[[", path.call(print, "id"), "]]", printOptionalToken(path), n.method ? "" : ": ", path.call(print, "value")]);
26895 case "ObjectExpression":
26896 case "ObjectPattern":
26897 case "ObjectTypeAnnotation":
26898 case "TSInterfaceBody":
26899 case "TSTypeLiteral":
26901 let propertiesField;
26903 if (n.type === "TSTypeLiteral") {
26904 propertiesField = "members";
26905 } else if (n.type === "TSInterfaceBody") {
26906 propertiesField = "body";
26908 propertiesField = "properties";
26911 const isTypeAnnotation = n.type === "ObjectTypeAnnotation";
26914 if (isTypeAnnotation) {
26915 fields.push("indexers", "callProperties", "internalSlots");
26918 fields.push(propertiesField);
26919 const firstProperty = fields.map(field => n[field][0]).sort((a, b) => options.locStart(a) - options.locStart(b))[0];
26920 const parent = path.getParentNode(0);
26921 const isFlowInterfaceLikeBody = isTypeAnnotation && parent && (parent.type === "InterfaceDeclaration" || parent.type === "DeclareInterface" || parent.type === "DeclareClass") && path.getName() === "body";
26922 const shouldBreak = n.type === "TSInterfaceBody" || isFlowInterfaceLikeBody || n.type === "ObjectPattern" && parent.type !== "FunctionDeclaration" && parent.type !== "FunctionExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "ObjectMethod" && parent.type !== "ClassMethod" && parent.type !== "ClassPrivateMethod" && parent.type !== "AssignmentPattern" && parent.type !== "CatchClause" && n.properties.some(property => property.value && (property.value.type === "ObjectPattern" || property.value.type === "ArrayPattern")) || n.type !== "ObjectPattern" && firstProperty && hasNewlineInRange$3(options.originalText, options.locStart(n), options.locStart(firstProperty));
26923 const separator = isFlowInterfaceLikeBody ? ";" : n.type === "TSInterfaceBody" || n.type === "TSTypeLiteral" ? ifBreak$6(semi, ";") : ",";
26924 const leftBrace = n.exact ? "{|" : "{";
26925 const rightBrace = n.exact ? "|}" : "}"; // Unfortunately, things are grouped together in the ast can be
26926 // interleaved in the source code. So we need to reorder them before
26929 const propsAndLoc = [];
26930 fields.forEach(field => {
26931 path.each(childPath => {
26932 const node = childPath.getValue();
26935 printed: print(childPath),
26936 loc: options.locStart(node)
26940 let separatorParts = [];
26941 const props = propsAndLoc.sort((a, b) => a.loc - b.loc).map(prop => {
26942 const result = concat$d(separatorParts.concat(group$b(prop.printed)));
26943 separatorParts = [separator, line$9];
26945 if ((prop.node.type === "TSPropertySignature" || prop.node.type === "TSMethodSignature" || prop.node.type === "TSConstructSignatureDeclaration") && hasNodeIgnoreComment$2(prop.node)) {
26946 separatorParts.shift();
26949 if (isNextLineEmpty$4(options.originalText, prop.node, options.locEnd)) {
26950 separatorParts.push(hardline$9);
26959 if (hasDanglingComments$1(n)) {
26960 const hasLineComments = !n.comments.every(comments$1.isBlockComment);
26961 const printedDanglingComments = comments.printDanglingComments(path, options,
26964 printed = concat$d([printedDanglingComments, hasLineComments || hasNewline$5(options.originalText, options.locEnd(n.comments[n.comments.length - 1])) ? hardline$9 : line$9, "..."]);
26969 props.push(concat$d(separatorParts.concat(printed)));
26972 const lastElem = getLast$3(n[propertiesField]);
26973 const canHaveTrailingSeparator = !(n.inexact || lastElem && (lastElem.type === "RestElement" || hasNodeIgnoreComment$2(lastElem)));
26976 if (props.length === 0) {
26977 if (!hasDanglingComments$1(n)) {
26978 return concat$d([leftBrace, rightBrace, printTypeAnnotation(path, options, print)]);
26981 content = group$b(concat$d([leftBrace, comments.printDanglingComments(path, options), softline$6, rightBrace, printOptionalToken(path), printTypeAnnotation(path, options, print)]));
26983 content = concat$d([leftBrace, indent$7(concat$d([options.bracketSpacing ? line$9 : softline$6, concat$d(props)])), ifBreak$6(canHaveTrailingSeparator && (separator !== "," || shouldPrintComma$1(options)) ? separator : ""), concat$d([options.bracketSpacing ? line$9 : softline$6, rightBrace]), printOptionalToken(path), printTypeAnnotation(path, options, print)]);
26984 } // If we inline the object as first argument of the parent, we don't want
26985 // to create another group so that the object breaks before the return
26989 if (path.match(node => node.type === "ObjectPattern" && !node.decorators, (node, name, number) => shouldHugArguments(node) && (name === "params" || name === "parameters") && number === 0) || path.match(shouldHugType, (node, name) => name === "typeAnnotation", (node, name) => name === "typeAnnotation", (node, name, number) => shouldHugArguments(node) && (name === "params" || name === "parameters") && number === 0)) {
26993 return group$b(content, {
26999 case "ObjectProperty": // Non-standard AST node type.
27002 if (n.method || n.kind === "get" || n.kind === "set") {
27003 return printMethod(path, options, print);
27007 parts.push(path.call(print, "value"));
27009 parts.push(printAssignment(n.key, printPropertyKey(path, options, print), ":", n.value, path.call(print, "value"), options));
27012 return concat$d(parts);
27015 case "ClassMethod":
27016 case "ClassPrivateMethod":
27017 case "MethodDefinition":
27018 case "TSAbstractMethodDefinition":
27019 case "TSDeclareMethod":
27020 if (n.decorators && n.decorators.length !== 0) {
27021 parts.push(printDecorators(path, options, print));
27024 if (n.accessibility) {
27025 parts.push(n.accessibility + " ");
27029 parts.push("static ");
27032 if (n.type === "TSAbstractMethodDefinition" || n.abstract) {
27033 parts.push("abstract ");
27036 parts.push(printMethod(path, options, print));
27037 return concat$d(parts);
27039 case "ObjectMethod":
27040 return printMethod(path, options, print);
27043 return concat$d(["@", path.call(print, "expression"), path.call(print, "callee")]);
27045 case "ArrayExpression":
27046 case "ArrayPattern":
27047 if (n.elements.length === 0) {
27048 if (!hasDanglingComments$1(n)) {
27051 parts.push(group$b(concat$d(["[", comments.printDanglingComments(path, options), softline$6, "]"])));
27054 const lastElem = getLast$3(n.elements);
27055 const canHaveTrailingComma = !(lastElem && lastElem.type === "RestElement"); // JavaScript allows you to have empty elements in an array which
27056 // changes its length based on the number of commas. The algorithm
27057 // is that if the last argument is null, we need to force insert
27058 // a comma to ensure JavaScript recognizes it.
27059 // [,].length === 1
27060 // [1,].length === 1
27061 // [1,,].length === 2
27063 // Note that getLast returns null if the array is empty, but
27064 // we already check for an empty array just above so we are safe
27066 const needsForcedTrailingComma = canHaveTrailingComma && lastElem === null;
27067 const shouldBreak = n.elements.length > 1 && n.elements.every((element, i, elements) => {
27068 const elementType = element && element.type;
27070 if (elementType !== "ArrayExpression" && elementType !== "ObjectExpression") {
27074 const nextElement = elements[i + 1];
27076 if (nextElement && elementType !== nextElement.type) {
27080 const itemsKey = elementType === "ArrayExpression" ? "elements" : "properties";
27081 return element[itemsKey] && element[itemsKey].length > 1;
27083 parts.push(group$b(concat$d(["[", indent$7(concat$d([softline$6, printArrayItems(path, options, "elements", print)])), needsForcedTrailingComma ? "," : "", ifBreak$6(canHaveTrailingComma && !needsForcedTrailingComma && shouldPrintComma$1(options) ? "," : ""), comments.printDanglingComments(path, options,
27085 true), softline$6, "]"]), {
27090 parts.push(printOptionalToken(path), printTypeAnnotation(path, options, print));
27091 return concat$d(parts);
27093 case "SequenceExpression":
27095 const parent = path.getParentNode(0);
27097 if (parent.type === "ExpressionStatement" || parent.type === "ForStatement") {
27098 // For ExpressionStatements and for-loop heads, which are among
27099 // the few places a SequenceExpression appears unparenthesized, we want
27100 // to indent expressions after the first.
27103 if (p.getName() === 0) {
27104 parts.push(print(p));
27106 parts.push(",", indent$7(concat$d([line$9, print(p)])));
27109 return group$b(concat$d(parts));
27112 return group$b(concat$d([join$9(concat$d([",", line$9]), path.map(print, "expressions"))]));
27115 case "ThisExpression":
27121 case "NullLiteral":
27122 // Babel 6 Literal split
27125 case "RegExpLiteral":
27126 // Babel 6 Literal split
27127 return printRegex(n);
27129 case "NumericLiteral":
27130 // Babel 6 Literal split
27131 return printNumber$2(n.extra.raw);
27133 case "BigIntLiteral":
27134 // babel: n.extra.raw, typescript: n.raw, flow: n.bigint
27135 return (n.bigint || (n.extra ? n.extra.raw : n.raw)).toLowerCase();
27137 case "BooleanLiteral": // Babel 6 Literal split
27139 case "StringLiteral": // Babel 6 Literal split
27144 return printRegex(n.regex);
27147 if (typeof n.value === "number") {
27148 return printNumber$2(n.raw);
27151 if (typeof n.value !== "string") {
27152 return "" + n.value;
27153 } // TypeScript workaround for https://github.com/JamesHenry/typescript-estree/issues/2
27154 // See corresponding workaround in needs-parens.js
27157 const grandParent = path.getParentNode(1);
27158 const isTypeScriptDirective = options.parser === "typescript" && typeof n.value === "string" && grandParent && (grandParent.type === "Program" || grandParent.type === "BlockStatement");
27159 return nodeStr(n, options, isTypeScriptDirective);
27163 return path.call(print, "value");
27166 case "DirectiveLiteral":
27167 return nodeStr(n, options);
27169 case "UnaryExpression":
27170 parts.push(n.operator);
27172 if (/[a-z]$/.test(n.operator)) {
27176 if (n.argument.comments && n.argument.comments.length > 0) {
27177 parts.push(group$b(concat$d(["(", indent$7(concat$d([softline$6, path.call(print, "argument")])), softline$6, ")"])));
27179 parts.push(path.call(print, "argument"));
27182 return concat$d(parts);
27184 case "UpdateExpression":
27185 parts.push(path.call(print, "argument"), n.operator);
27191 return concat$d(parts);
27193 case "ConditionalExpression":
27194 return printTernaryOperator(path, options, print, {
27195 beforeParts: () => [path.call(print, "test")],
27196 afterParts: breakClosingParen => [breakClosingParen ? softline$6 : ""],
27197 shouldCheckJsx: true,
27198 conditionalNodeType: "ConditionalExpression",
27199 consequentNodePropertyName: "consequent",
27200 alternateNodePropertyName: "alternate",
27201 testNodePropertyNames: ["test"]
27204 case "VariableDeclaration":
27206 const printed = path.map(childPath => {
27207 return print(childPath);
27208 }, "declarations"); // We generally want to terminate all variable declarations with a
27209 // semicolon, except when they in the () part of for loops.
27211 const parentNode = path.getParentNode();
27212 const isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement";
27213 const hasValue = n.declarations.some(decl => decl.init);
27216 if (printed.length === 1 && !n.declarations[0].comments) {
27217 firstVariable = printed[0];
27218 } else if (printed.length > 0) {
27219 // Indent first var to comply with eslint one-var rule
27220 firstVariable = indent$7(printed[0]);
27223 parts = [n.declare ? "declare " : "", n.kind, firstVariable ? concat$d([" ", firstVariable]) : "", indent$7(concat$d(printed.slice(1).map(p => concat$d([",", hasValue && !isParentForLoop ? hardline$9 : line$9, p]))))];
27225 if (!(isParentForLoop && parentNode.body !== n)) {
27229 return group$b(concat$d(parts));
27232 case "TSTypeAliasDeclaration":
27235 parts.push("declare ");
27238 const printed = printAssignmentRight(n.id, n.typeAnnotation, n.typeAnnotation && path.call(print, "typeAnnotation"), options);
27239 parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi);
27240 return group$b(concat$d(parts));
27243 case "VariableDeclarator":
27244 return printAssignment(n.id, path.call(print, "id"), " =", n.init, n.init && path.call(print, "init"), options);
27246 case "WithStatement":
27247 return group$b(concat$d(["with (", path.call(print, "object"), ")", adjustClause(n.body, path.call(print, "body"))]));
27249 case "IfStatement":
27251 const con = adjustClause(n.consequent, path.call(print, "consequent"));
27252 const opening = group$b(concat$d(["if (", group$b(concat$d([indent$7(concat$d([softline$6, path.call(print, "test")])), softline$6])), ")", con]));
27253 parts.push(opening);
27256 const commentOnOwnLine = hasTrailingComment$1(n.consequent) && n.consequent.comments.some(comment => comment.trailing && !comments$1.isBlockComment(comment)) || needsHardlineAfterDanglingComment$1(n);
27257 const elseOnSameLine = n.consequent.type === "BlockStatement" && !commentOnOwnLine;
27258 parts.push(elseOnSameLine ? " " : hardline$9);
27260 if (hasDanglingComments$1(n)) {
27261 parts.push(comments.printDanglingComments(path, options, true), commentOnOwnLine ? hardline$9 : " ");
27264 parts.push("else", group$b(adjustClause(n.alternate, path.call(print, "alternate"), n.alternate.type === "IfStatement")));
27267 return concat$d(parts);
27270 case "ForStatement":
27272 const body = adjustClause(n.body, path.call(print, "body")); // We want to keep dangling comments above the loop to stay consistent.
27273 // Any comment positioned between the for statement and the parentheses
27274 // is going to be printed before the statement.
27276 const dangling = comments.printDanglingComments(path, options,
27279 const printedComments = dangling ? concat$d([dangling, softline$6]) : "";
27281 if (!n.init && !n.test && !n.update) {
27282 return concat$d([printedComments, group$b(concat$d(["for (;;)", body]))]);
27285 return concat$d([printedComments, group$b(concat$d(["for (", group$b(concat$d([indent$7(concat$d([softline$6, path.call(print, "init"), ";", line$9, path.call(print, "test"), ";", line$9, path.call(print, "update")])), softline$6])), ")", body]))]);
27288 case "WhileStatement":
27289 return group$b(concat$d(["while (", group$b(concat$d([indent$7(concat$d([softline$6, path.call(print, "test")])), softline$6])), ")", adjustClause(n.body, path.call(print, "body"))]));
27291 case "ForInStatement":
27292 // Note: esprima can't actually parse "for each (".
27293 return group$b(concat$d([n.each ? "for each (" : "for (", path.call(print, "left"), " in ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))]));
27295 case "ForOfStatement":
27296 return group$b(concat$d(["for", n.await ? " await" : "", " (", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))]));
27298 case "DoWhileStatement":
27300 const clause = adjustClause(n.body, path.call(print, "body"));
27301 const doBody = group$b(concat$d(["do", clause]));
27304 if (n.body.type === "BlockStatement") {
27307 parts.push(hardline$9);
27310 parts.push("while (");
27311 parts.push(group$b(concat$d([indent$7(concat$d([softline$6, path.call(print, "test")])), softline$6])), ")", semi);
27312 return concat$d(parts);
27315 case "DoExpression":
27316 return concat$d(["do ", path.call(print, "body")]);
27318 case "BreakStatement":
27319 parts.push("break");
27322 parts.push(" ", path.call(print, "label"));
27326 return concat$d(parts);
27328 case "ContinueStatement":
27329 parts.push("continue");
27332 parts.push(" ", path.call(print, "label"));
27336 return concat$d(parts);
27338 case "LabeledStatement":
27339 if (n.body.type === "EmptyStatement") {
27340 return concat$d([path.call(print, "label"), ":;"]);
27343 return concat$d([path.call(print, "label"), ": ", path.call(print, "body")]);
27345 case "TryStatement":
27346 return concat$d(["try ", path.call(print, "block"), n.handler ? concat$d([" ", path.call(print, "handler")]) : "", n.finalizer ? concat$d([" finally ", path.call(print, "finalizer")]) : ""]);
27348 case "CatchClause":
27350 const hasComments = n.param.comments && n.param.comments.some(comment => !comments$1.isBlockComment(comment) || comment.leading && hasNewline$5(options.originalText, options.locEnd(comment)) || comment.trailing && hasNewline$5(options.originalText, options.locStart(comment), {
27353 const param = path.call(print, "param");
27354 return concat$d(["catch ", hasComments ? concat$d(["(", indent$7(concat$d([softline$6, param])), softline$6, ") "]) : concat$d(["(", param, ") "]), path.call(print, "body")]);
27357 return concat$d(["catch ", path.call(print, "body")]);
27359 case "ThrowStatement":
27360 return concat$d(["throw", printReturnAndThrowArgument(path, options, print)]);
27361 // Note: ignoring n.lexical because it has no printing consequences.
27363 case "SwitchStatement":
27364 return concat$d([group$b(concat$d(["switch (", indent$7(concat$d([softline$6, path.call(print, "discriminant")])), softline$6, ")"])), " {", n.cases.length > 0 ? indent$7(concat$d([hardline$9, join$9(hardline$9, path.map(casePath => {
27365 const caseNode = casePath.getValue();
27366 return concat$d([casePath.call(print), n.cases.indexOf(caseNode) !== n.cases.length - 1 && isNextLineEmpty$4(options.originalText, caseNode, options.locEnd) ? hardline$9 : ""]);
27367 }, "cases"))])) : "", hardline$9, "}"]);
27372 parts.push("case ", path.call(print, "test"), ":");
27374 parts.push("default:");
27377 const consequent = n.consequent.filter(node => node.type !== "EmptyStatement");
27379 if (consequent.length > 0) {
27380 const cons = path.call(consequentPath => {
27381 return printStatementSequence(consequentPath, options, print);
27383 parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? concat$d([" ", cons]) : indent$7(concat$d([hardline$9, cons])));
27386 return concat$d(parts);
27388 // JSX extensions below.
27390 case "DebuggerStatement":
27391 return concat$d(["debugger", semi]);
27393 case "JSXAttribute":
27394 parts.push(path.call(print, "name"));
27399 if (isStringLiteral$1(n.value)) {
27400 const raw = rawText$1(n.value); // Unescape all quotes so we get an accurate preferred quote
27402 let final = raw.replace(/'/g, "'").replace(/"/g, '"');
27403 const quote = getPreferredQuote$1(final, options.jsxSingleQuote ? "'" : '"');
27404 const escape = quote === "'" ? "'" : """;
27405 final = final.slice(1, -1).replace(new RegExp(quote, "g"), escape);
27406 res = concat$d([quote, final, quote]);
27408 res = path.call(print, "value");
27411 parts.push("=", res);
27414 return concat$d(parts);
27416 case "JSXIdentifier":
27417 return "" + n.name;
27419 case "JSXNamespacedName":
27420 return join$9(":", [path.call(print, "namespace"), path.call(print, "name")]);
27422 case "JSXMemberExpression":
27423 return join$9(".", [path.call(print, "object"), path.call(print, "property")]);
27425 case "TSQualifiedName":
27426 return join$9(".", [path.call(print, "left"), path.call(print, "right")]);
27428 case "JSXSpreadAttribute":
27429 case "JSXSpreadChild":
27431 return concat$d(["{", path.call(p => {
27432 const printed = concat$d(["...", print(p)]);
27433 const n = p.getValue();
27435 if (!n.comments || !n.comments.length) {
27439 return concat$d([indent$7(concat$d([softline$6, comments.printComments(p, () => printed, options)])), softline$6]);
27440 }, n.type === "JSXSpreadAttribute" ? "argument" : "expression"), "}"]);
27443 case "JSXExpressionContainer":
27445 const parent = path.getParentNode(0);
27446 const hasComments = n.expression.comments && n.expression.comments.length > 0;
27447 const shouldInline = n.expression.type === "JSXEmptyExpression" || !hasComments && (n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression" || n.expression.type === "ArrowFunctionExpression" || n.expression.type === "CallExpression" || n.expression.type === "OptionalCallExpression" || n.expression.type === "FunctionExpression" || n.expression.type === "TemplateLiteral" || n.expression.type === "TaggedTemplateExpression" || n.expression.type === "DoExpression" || isJSXNode$1(parent) && (n.expression.type === "ConditionalExpression" || isBinaryish$1(n.expression)));
27449 if (shouldInline) {
27450 return group$b(concat$d(["{", path.call(print, "expression"), lineSuffixBoundary$1, "}"]));
27453 return group$b(concat$d(["{", indent$7(concat$d([softline$6, path.call(print, "expression")])), softline$6, lineSuffixBoundary$1, "}"]));
27456 case "JSXFragment":
27459 const elem = comments.printComments(path, () => printJSXElement(path, options, print), options);
27460 return maybeWrapJSXElementInParens(path, elem, options);
27463 case "JSXOpeningElement":
27465 const n = path.getValue();
27466 const nameHasComments = n.name && n.name.comments && n.name.comments.length > 0 || n.typeParameters && n.typeParameters.comments && n.typeParameters.comments.length > 0; // Don't break self-closing elements with no attributes and no comments
27468 if (n.selfClosing && !n.attributes.length && !nameHasComments) {
27469 return concat$d(["<", path.call(print, "name"), path.call(print, "typeParameters"), " />"]);
27470 } // don't break up opening elements with a single long text attribute
27473 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:
27482 !nameHasComments && (!n.attributes[0].comments || !n.attributes[0].comments.length)) {
27483 return group$b(concat$d(["<", path.call(print, "name"), path.call(print, "typeParameters"), " ", concat$d(path.map(print, "attributes")), n.selfClosing ? " />" : ">"]));
27486 const lastAttrHasTrailingComments = n.attributes.length && hasTrailingComment$1(getLast$3(n.attributes));
27487 const bracketSameLine = // Simple tags (no attributes and no comment in tag name) should be
27488 // kept unbroken regardless of `jsxBracketSameLine`
27489 !n.attributes.length && !nameHasComments || options.jsxBracketSameLine && ( // We should print the bracket in a new line for the following cases:
27496 !nameHasComments || n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a
27497 // string literal with newlines
27499 const shouldBreak = n.attributes && n.attributes.some(attr => attr.value && isStringLiteral$1(attr.value) && attr.value.value.includes("\n"));
27500 return group$b(concat$d(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$d([indent$7(concat$d(path.map(attr => concat$d([line$9, print(attr)]), "attributes"))), n.selfClosing ? line$9 : bracketSameLine ? ">" : softline$6]), n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), {
27505 case "JSXClosingElement":
27506 return concat$d(["</", path.call(print, "name"), ">"]);
27508 case "JSXOpeningFragment":
27509 case "JSXClosingFragment":
27511 const hasComment = n.comments && n.comments.length;
27512 const hasOwnLineComment = hasComment && !n.comments.every(comments$1.isBlockComment);
27513 const isOpeningFragment = n.type === "JSXOpeningFragment";
27514 return concat$d([isOpeningFragment ? "<" : "</", indent$7(concat$d([hasOwnLineComment ? hardline$9 : hasComment && !isOpeningFragment ? " " : "", comments.printDanglingComments(path, options, true)])), hasOwnLineComment ? hardline$9 : "", ">"]);
27518 /* istanbul ignore next */
27519 throw new Error("JSXTest should be handled by JSXElement");
27521 case "JSXEmptyExpression":
27523 const requiresHardline = n.comments && !n.comments.every(comments$1.isBlockComment);
27524 return concat$d([comments.printDanglingComments(path, options,
27526 !requiresHardline), requiresHardline ? hardline$9 : ""]);
27530 if (!n.comments && n.body.length === 0) {
27534 return concat$d(["{", n.body.length > 0 ? indent$7(concat$d([hardline$9, path.call(bodyPath => {
27535 return printStatementSequence(bodyPath, options, print);
27536 }, "body")])) : comments.printDanglingComments(path, options), hardline$9, "}"]);
27538 case "ClassProperty":
27539 case "TSAbstractClassProperty":
27540 case "ClassPrivateProperty":
27542 if (n.decorators && n.decorators.length !== 0) {
27543 parts.push(printDecorators(path, options, print));
27546 if (n.accessibility) {
27547 parts.push(n.accessibility + " ");
27551 parts.push("declare ");
27555 parts.push("static ");
27558 if (n.type === "TSAbstractClassProperty" || n.abstract) {
27559 parts.push("abstract ");
27563 parts.push("readonly ");
27566 const variance = getFlowVariance$1(n);
27569 parts.push(variance);
27572 parts.push(printPropertyKey(path, options, print), printOptionalToken(path), printTypeAnnotation(path, options, print));
27575 parts.push(" =", printAssignmentRight(n.key, n.value, path.call(print, "value"), options));
27579 return group$b(concat$d(parts));
27582 case "ClassDeclaration":
27583 case "ClassExpression":
27585 parts.push("declare ");
27588 parts.push(concat$d(printClass(path, options, print)));
27589 return concat$d(parts);
27591 case "TSInterfaceHeritage":
27592 case "TSExpressionWithTypeArguments":
27594 parts.push(path.call(print, "expression"));
27596 if (n.typeParameters) {
27597 parts.push(path.call(print, "typeParameters"));
27600 return concat$d(parts);
27602 case "TemplateElement":
27603 return join$9(literalline$4, n.value.raw.split(/\r?\n/g));
27605 case "TemplateLiteral":
27607 let expressions = path.map(print, "expressions");
27608 const parentNode = path.getParentNode();
27610 if (isJestEachTemplateLiteral$1(n, parentNode)) {
27611 const printed = printJestEachTemplateLiteral(n, expressions, options);
27618 const isSimple = isSimpleTemplateLiteral$1(n);
27621 expressions = expressions.map(doc => printDocToString$2(doc, Object.assign({}, options, {
27622 printWidth: Infinity
27626 parts.push(lineSuffixBoundary$1, "`");
27627 path.each(childPath => {
27628 const i = childPath.getName();
27629 parts.push(print(childPath));
27631 if (i < expressions.length) {
27632 // For a template literal of the following form:
27639 // the expression is on its own line (there is a \n in the previous
27640 // quasi literal), therefore we want to indent the JavaScript
27641 // expression inside at the beginning of ${ instead of the beginning
27646 const quasi = childPath.getValue();
27647 const indentSize = getIndentSize$2(quasi.value.raw, tabWidth);
27648 let printed = expressions[i];
27651 // Breaks at the template element boundaries (${ and }) are preferred to breaking
27652 // in the middle of a MemberExpression
27653 if (n.expressions[i].comments && n.expressions[i].comments.length || n.expressions[i].type === "MemberExpression" || n.expressions[i].type === "OptionalMemberExpression" || n.expressions[i].type === "ConditionalExpression" || n.expressions[i].type === "SequenceExpression" || n.expressions[i].type === "TSAsExpression" || isBinaryish$1(n.expressions[i])) {
27654 printed = concat$d([indent$7(concat$d([softline$6, printed])), softline$6]);
27658 const aligned = indentSize === 0 && quasi.value.raw.endsWith("\n") ? align$1(-Infinity, printed) : addAlignmentToDoc$2(printed, indentSize, tabWidth);
27659 parts.push(group$b(concat$d(["${", aligned, lineSuffixBoundary$1, "}"])));
27663 return concat$d(parts);
27665 // These types are unprintable because they serve as abstract
27666 // supertypes for other (printable) types.
27668 case "TaggedTemplateExpression":
27669 return concat$d([path.call(print, "tag"), path.call(print, "typeParameters"), path.call(print, "quasi")]);
27673 case "SourceLocation":
27679 case "Declaration":
27681 case "NamedSpecifier":
27683 case "MemberTypeAnnotation": // Flow
27686 /* istanbul ignore next */
27687 throw new Error("unprintable type: " + JSON.stringify(n.type));
27688 // Type Annotations for Facebook Flow, typically stripped out or
27689 // transformed away before printing.
27691 case "TypeAnnotation":
27692 case "TSTypeAnnotation":
27693 if (n.typeAnnotation) {
27694 return path.call(print, "typeAnnotation");
27696 /* istanbul ignore next */
27701 case "TSTupleType":
27702 case "TupleTypeAnnotation":
27704 const typesField = n.type === "TSTupleType" ? "elementTypes" : "types";
27705 const hasRest = n[typesField].length > 0 && getLast$3(n[typesField]).type === "TSRestType";
27706 return group$b(concat$d(["[", indent$7(concat$d([softline$6, printArrayItems(path, options, typesField, print)])), ifBreak$6(shouldPrintComma$1(options, "all") && !hasRest ? "," : ""), comments.printDanglingComments(path, options,
27708 true), softline$6, "]"]));
27711 case "ExistsTypeAnnotation":
27714 case "EmptyTypeAnnotation":
27717 case "AnyTypeAnnotation":
27720 case "MixedTypeAnnotation":
27723 case "ArrayTypeAnnotation":
27724 return concat$d([path.call(print, "elementType"), "[]"]);
27726 case "BooleanTypeAnnotation":
27729 case "BooleanLiteralTypeAnnotation":
27730 return "" + n.value;
27732 case "DeclareClass":
27733 return printFlowDeclaration(path, printClass(path, options, print));
27735 case "TSDeclareFunction":
27736 // For TypeScript the TSDeclareFunction node shares the AST
27737 // structure with FunctionDeclaration
27738 return concat$d([n.declare ? "declare " : "", printFunctionDeclaration(path, print, options), semi]);
27740 case "DeclareFunction":
27741 return printFlowDeclaration(path, ["function ", path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), semi]);
27743 case "DeclareModule":
27744 return printFlowDeclaration(path, ["module ", path.call(print, "id"), " ", path.call(print, "body")]);
27746 case "DeclareModuleExports":
27747 return printFlowDeclaration(path, ["module.exports", ": ", path.call(print, "typeAnnotation"), semi]);
27749 case "DeclareVariable":
27750 return printFlowDeclaration(path, ["var ", path.call(print, "id"), semi]);
27752 case "DeclareExportAllDeclaration":
27753 return concat$d(["declare export * from ", path.call(print, "source")]);
27755 case "DeclareExportDeclaration":
27756 return concat$d(["declare ", printExportDeclaration(path, options, print)]);
27758 case "DeclareOpaqueType":
27761 parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters"));
27764 parts.push(": ", path.call(print, "supertype"));
27768 parts.push(" = ", path.call(print, "impltype"));
27773 if (n.type === "DeclareOpaqueType") {
27774 return printFlowDeclaration(path, parts);
27777 return concat$d(parts);
27780 case "EnumDeclaration":
27781 return concat$d(["enum ", path.call(print, "id"), " ", path.call(print, "body")]);
27783 case "EnumBooleanBody":
27784 case "EnumNumberBody":
27785 case "EnumStringBody":
27786 case "EnumSymbolBody":
27788 if (n.type === "EnumSymbolBody" || n.explicitType) {
27792 case "EnumBooleanBody":
27796 case "EnumNumberBody":
27800 case "EnumStringBody":
27804 case "EnumSymbolBody":
27809 parts.push("of ", type, " ");
27812 if (n.members.length === 0) {
27813 parts.push(group$b(concat$d(["{", comments.printDanglingComments(path, options), softline$6, "}"])));
27815 parts.push(group$b(concat$d(["{", indent$7(concat$d([hardline$9, printArrayItems(path, options, "members", print), shouldPrintComma$1(options) ? "," : ""])), comments.printDanglingComments(path, options,
27817 true), hardline$9, "}"])));
27820 return concat$d(parts);
27823 case "EnumBooleanMember":
27824 case "EnumNumberMember":
27825 case "EnumStringMember":
27826 return concat$d([path.call(print, "id"), " = ", typeof n.init === "object" ? path.call(print, "init") : String(n.init)]);
27828 case "EnumDefaultedMember":
27829 return path.call(print, "id");
27831 case "FunctionTypeAnnotation":
27832 case "TSFunctionType":
27834 // FunctionTypeAnnotation is ambiguous:
27835 // declare function foo(a: B): void; OR
27836 // var A: (a: B) => void;
27837 const parent = path.getParentNode(0);
27838 const parentParent = path.getParentNode(1);
27839 const parentParentParent = path.getParentNode(2);
27840 let isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !((parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeInternalSlot") && !getFlowVariance$1(parent) && !parent.optional && options.locStart(parent) === options.locStart(n) || parent.type === "ObjectTypeCallProperty" || parentParentParent && parentParentParent.type === "DeclareFunction");
27841 let needsColon = isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation"); // Sadly we can't put it inside of FastPath::needsColon because we are
27842 // printing ":" as part of the expression and it would put parenthesis
27845 const needsParens = needsColon && isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation") && parentParent.type === "ArrowFunctionExpression";
27847 if (isObjectTypePropertyAFunction$1(parent, options)) {
27848 isArrowFunctionTypeAnnotation = true;
27856 parts.push(printFunctionParams(path, print, options,
27859 /* printTypeParams */
27860 true)); // The returnType is not wrapped in a TypeAnnotation, so the colon
27861 // needs to be added separately.
27863 if (n.returnType || n.predicate || n.typeAnnotation) {
27864 parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType"), path.call(print, "predicate"), path.call(print, "typeAnnotation"));
27871 return group$b(concat$d(parts));
27875 return concat$d(["...", path.call(print, "typeAnnotation")]);
27877 case "TSOptionalType":
27878 return concat$d([path.call(print, "typeAnnotation"), "?"]);
27880 case "FunctionTypeParam":
27881 return concat$d([path.call(print, "name"), printOptionalToken(path), n.name ? ": " : "", path.call(print, "typeAnnotation")]);
27883 case "GenericTypeAnnotation":
27884 return concat$d([path.call(print, "id"), path.call(print, "typeParameters")]);
27886 case "DeclareInterface":
27887 case "InterfaceDeclaration":
27888 case "InterfaceTypeAnnotation":
27890 if (n.type === "DeclareInterface" || n.declare) {
27891 parts.push("declare ");
27894 parts.push("interface");
27896 if (n.type === "DeclareInterface" || n.type === "InterfaceDeclaration") {
27897 parts.push(" ", path.call(print, "id"), path.call(print, "typeParameters"));
27900 if (n.extends.length > 0) {
27901 parts.push(group$b(indent$7(concat$d([line$9, "extends ", (n.extends.length === 1 ? identity$2 : indent$7)(join$9(concat$d([",", line$9]), path.map(print, "extends")))]))));
27904 parts.push(" ", path.call(print, "body"));
27905 return group$b(concat$d(parts));
27908 case "ClassImplements":
27909 case "InterfaceExtends":
27910 return concat$d([path.call(print, "id"), path.call(print, "typeParameters")]);
27912 case "TSClassImplements":
27913 return concat$d([path.call(print, "expression"), path.call(print, "typeParameters")]);
27915 case "TSIntersectionType":
27916 case "IntersectionTypeAnnotation":
27918 const types = path.map(print, "types");
27920 let wasIndented = false;
27922 for (let i = 0; i < types.length; ++i) {
27924 result.push(types[i]);
27925 } else if (isObjectType$1(n.types[i - 1]) && isObjectType$1(n.types[i])) {
27926 // If both are objects, don't indent
27927 result.push(concat$d([" & ", wasIndented ? indent$7(types[i]) : types[i]]));
27928 } else if (!isObjectType$1(n.types[i - 1]) && !isObjectType$1(n.types[i])) {
27929 // If no object is involved, go to the next line if it breaks
27930 result.push(indent$7(concat$d([" &", line$9, types[i]])));
27932 // If you go from object to non-object or vis-versa, then inline it
27934 wasIndented = true;
27937 result.push(" & ", i > 1 ? indent$7(types[i]) : types[i]);
27941 return group$b(concat$d(result));
27944 case "TSUnionType":
27945 case "UnionTypeAnnotation":
27947 // single-line variation
27949 // multi-line variation
27953 const parent = path.getParentNode(); // If there's a leading comment, the parent is doing the indentation
27955 const shouldIndent = parent.type !== "TypeParameterInstantiation" && parent.type !== "TSTypeParameterInstantiation" && parent.type !== "GenericTypeAnnotation" && parent.type !== "TSTypeReference" && parent.type !== "TSTypeAssertion" && parent.type !== "TupleTypeAnnotation" && parent.type !== "TSTupleType" && !(parent.type === "FunctionTypeParam" && !parent.name) && !((parent.type === "TypeAlias" || parent.type === "VariableDeclarator" || parent.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment$1(options.originalText, n, options)); // {
27958 // should be inlined and not be printed in the multi-line variant
27960 const shouldHug = shouldHugType(n); // We want to align the children but without its comment, so it looks like
27965 const printed = path.map(typePath => {
27966 let printedType = typePath.call(print);
27969 printedType = align$1(2, printedType);
27972 return comments.printComments(typePath, () => printedType, options);
27976 return join$9(" | ", printed);
27979 const shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment$1(options.originalText, n, options);
27980 const code = concat$d([ifBreak$6(concat$d([shouldAddStartLine ? line$9 : "", "| "])), join$9(concat$d([line$9, "| "]), printed)]);
27982 if (needsParens_1(path, options)) {
27983 return group$b(concat$d([indent$7(code), softline$6]));
27986 if (parent.type === "TupleTypeAnnotation" && parent.types.length > 1 || parent.type === "TSTupleType" && parent.elementTypes.length > 1) {
27987 return group$b(concat$d([indent$7(concat$d([ifBreak$6(concat$d(["(", softline$6])), code])), softline$6, ifBreak$6(")")]));
27990 return group$b(shouldIndent ? indent$7(code) : code);
27993 case "NullableTypeAnnotation":
27994 return concat$d(["?", path.call(print, "typeAnnotation")]);
27996 case "TSNullKeyword":
27997 case "NullLiteralTypeAnnotation":
28000 case "ThisTypeAnnotation":
28003 case "NumberTypeAnnotation":
28006 case "SymbolTypeAnnotation":
28009 case "ObjectTypeCallProperty":
28011 parts.push("static ");
28014 parts.push(path.call(print, "value"));
28015 return concat$d(parts);
28017 case "ObjectTypeIndexer":
28019 const variance = getFlowVariance$1(n);
28020 return concat$d([variance || "", "[", path.call(print, "id"), n.id ? ": " : "", path.call(print, "key"), "]: ", path.call(print, "value")]);
28023 case "ObjectTypeProperty":
28025 const variance = getFlowVariance$1(n);
28029 modifier = "proto ";
28030 } else if (n.static) {
28031 modifier = "static ";
28034 return concat$d([modifier, isGetterOrSetter$1(n) ? n.kind + " " : "", variance || "", printPropertyKey(path, options, print), printOptionalToken(path), isFunctionNotation$1(n, options) ? "" : ": ", path.call(print, "value")]);
28037 case "QualifiedTypeIdentifier":
28038 return concat$d([path.call(print, "qualification"), ".", path.call(print, "id")]);
28040 case "StringLiteralTypeAnnotation":
28041 return nodeStr(n, options);
28043 case "NumberLiteralTypeAnnotation":
28044 assert.strictEqual(typeof n.value, "number");
28046 if (n.extra != null) {
28047 return printNumber$2(n.extra.raw);
28050 return printNumber$2(n.raw);
28052 case "StringTypeAnnotation":
28055 case "DeclareTypeAlias":
28058 if (n.type === "DeclareTypeAlias" || n.declare) {
28059 parts.push("declare ");
28062 const printed = printAssignmentRight(n.id, n.right, path.call(print, "right"), options);
28063 parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi);
28064 return group$b(concat$d(parts));
28067 case "TypeCastExpression":
28069 return concat$d(["(", path.call(print, "expression"), printTypeAnnotation(path, options, print), ")"]);
28072 case "TypeParameterDeclaration":
28073 case "TypeParameterInstantiation":
28075 const value = path.getValue();
28076 const commentStart = value.range ? options.originalText.slice(0, value.range[0]).lastIndexOf("/*") : -1; // As noted in the TypeCastExpression comments above, we're able to use a normal whitespace regex here
28077 // because we know for sure that this is a type definition.
28079 const commentSyntax = commentStart >= 0 && options.originalText.slice(commentStart).match(/^\/\*\s*::/);
28081 if (commentSyntax) {
28082 return concat$d(["/*:: ", printTypeParameters(path, options, print, "params"), " */"]);
28085 return printTypeParameters(path, options, print, "params");
28088 case "TSTypeParameterDeclaration":
28089 case "TSTypeParameterInstantiation":
28090 return printTypeParameters(path, options, print, "params");
28092 case "TSTypeParameter":
28093 case "TypeParameter":
28095 const parent = path.getParentNode();
28097 if (parent.type === "TSMappedType") {
28098 parts.push("[", path.call(print, "name"));
28100 if (n.constraint) {
28101 parts.push(" in ", path.call(print, "constraint"));
28105 return concat$d(parts);
28108 const variance = getFlowVariance$1(n);
28111 parts.push(variance);
28114 parts.push(path.call(print, "name"));
28118 parts.push(path.call(print, "bound"));
28121 if (n.constraint) {
28122 parts.push(" extends ", path.call(print, "constraint"));
28126 parts.push(" = ", path.call(print, "default"));
28127 } // Keep comma if the file extension is .tsx and
28128 // has one type parameter that isn't extend with any types.
28129 // Because, otherwise formatted result will be invalid as tsx.
28132 const grandParent = path.getNode(2);
28134 if (parent.params && parent.params.length === 1 && isTSXFile$1(options) && !n.constraint && grandParent.type === "ArrowFunctionExpression") {
28138 return concat$d(parts);
28141 case "TypeofTypeAnnotation":
28142 return concat$d(["typeof ", path.call(print, "argument")]);
28144 case "VoidTypeAnnotation":
28147 case "InferredPredicate":
28149 // Unhandled types below. If encountered, nodes of these types should
28150 // be either left alone or desugared into AST types that are fully
28151 // supported by the pretty-printer.
28153 case "DeclaredPredicate":
28154 return concat$d(["%checks(", path.call(print, "value"), ")"]);
28156 case "TSAbstractKeyword":
28159 case "TSAnyKeyword":
28162 case "TSAsyncKeyword":
28165 case "TSBooleanKeyword":
28168 case "TSBigIntKeyword":
28171 case "TSConstKeyword":
28174 case "TSDeclareKeyword":
28177 case "TSExportKeyword":
28180 case "TSNeverKeyword":
28183 case "TSNumberKeyword":
28186 case "TSObjectKeyword":
28189 case "TSProtectedKeyword":
28190 return "protected";
28192 case "TSPrivateKeyword":
28195 case "TSPublicKeyword":
28198 case "TSReadonlyKeyword":
28201 case "TSSymbolKeyword":
28204 case "TSStaticKeyword":
28207 case "TSStringKeyword":
28210 case "TSUndefinedKeyword":
28211 return "undefined";
28213 case "TSUnknownKeyword":
28216 case "TSVoidKeyword":
28219 case "TSAsExpression":
28220 return concat$d([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]);
28222 case "TSArrayType":
28223 return concat$d([path.call(print, "elementType"), "[]"]);
28225 case "TSPropertySignature":
28228 parts.push("export ");
28231 if (n.accessibility) {
28232 parts.push(n.accessibility + " ");
28236 parts.push("static ");
28240 parts.push("readonly ");
28243 parts.push(printPropertyKey(path, options, print), printOptionalToken(path));
28245 if (n.typeAnnotation) {
28247 parts.push(path.call(print, "typeAnnotation"));
28248 } // This isn't valid semantically, but it's in the AST so we can print it.
28251 if (n.initializer) {
28252 parts.push(" = ", path.call(print, "initializer"));
28255 return concat$d(parts);
28258 case "TSParameterProperty":
28259 if (n.accessibility) {
28260 parts.push(n.accessibility + " ");
28264 parts.push("export ");
28268 parts.push("static ");
28272 parts.push("readonly ");
28275 parts.push(path.call(print, "parameter"));
28276 return concat$d(parts);
28278 case "TSTypeReference":
28279 return concat$d([path.call(print, "typeName"), printTypeParameters(path, options, print, "typeParameters")]);
28281 case "TSTypeQuery":
28282 return concat$d(["typeof ", path.call(print, "exprName")]);
28284 case "TSIndexSignature":
28286 const parent = path.getParentNode(); // The typescript parser accepts multiple parameters here. If you're
28287 // using them, it makes sense to have a trailing comma. But if you
28288 // aren't, this is more like a computed property name than an array.
28289 // So we leave off the trailing comma when there's just one parameter.
28291 const trailingComma = n.parameters.length > 1 ? ifBreak$6(shouldPrintComma$1(options) ? "," : "") : "";
28292 const parametersGroup = group$b(concat$d([indent$7(concat$d([softline$6, join$9(concat$d([", ", softline$6]), path.map(print, "parameters"))])), trailingComma, softline$6]));
28293 return concat$d([n.export ? "export " : "", n.accessibility ? concat$d([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", "[", n.parameters ? parametersGroup : "", n.typeAnnotation ? "]: " : "]", n.typeAnnotation ? path.call(print, "typeAnnotation") : "", parent.type === "ClassBody" ? semi : ""]);
28296 case "TSTypePredicate":
28297 return concat$d([n.asserts ? "asserts " : "", path.call(print, "parameterName"), n.typeAnnotation ? concat$d([" is ", path.call(print, "typeAnnotation")]) : ""]);
28299 case "TSNonNullExpression":
28300 return concat$d([path.call(print, "expression"), "!"]);
28305 case "TSImportType":
28306 return concat$d([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, n.parameter ? "parameter" : "argument"), ")", !n.qualifier ? "" : concat$d([".", path.call(print, "qualifier")]), printTypeParameters(path, options, print, "typeParameters")]);
28308 case "TSLiteralType":
28309 return path.call(print, "literal");
28311 case "TSIndexedAccessType":
28312 return concat$d([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]);
28314 case "TSConstructSignatureDeclaration":
28315 case "TSCallSignatureDeclaration":
28316 case "TSConstructorType":
28318 if (n.type !== "TSCallSignatureDeclaration") {
28319 parts.push("new ");
28322 parts.push(group$b(printFunctionParams(path, print, options,
28325 /* printTypeParams */
28328 if (n.returnType || n.typeAnnotation) {
28329 const isType = n.type === "TSConstructorType";
28330 parts.push(isType ? " => " : ": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
28333 return concat$d(parts);
28336 case "TSTypeOperator":
28337 return concat$d([n.operator, " ", path.call(print, "typeAnnotation")]);
28339 case "TSMappedType":
28341 const shouldBreak = hasNewlineInRange$3(options.originalText, options.locStart(n), options.locEnd(n));
28342 return group$b(concat$d(["{", indent$7(concat$d([options.bracketSpacing ? line$9 : softline$6, n.readonly ? concat$d([getTypeScriptMappedTypeModifier$1(n.readonly, "readonly"), " "]) : "", printTypeScriptModifiers(path, options, print), path.call(print, "typeParameter"), n.optional ? getTypeScriptMappedTypeModifier$1(n.optional, "?") : "", n.typeAnnotation ? ": " : "", path.call(print, "typeAnnotation"), ifBreak$6(semi, "")])), comments.printDanglingComments(path, options,
28344 true), options.bracketSpacing ? line$9 : softline$6, "}"]), {
28349 case "TSMethodSignature":
28350 parts.push(n.accessibility ? concat$d([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,
28353 /* printTypeParams */
28356 if (n.returnType || n.typeAnnotation) {
28357 parts.push(": ", path.call(print, "returnType"), path.call(print, "typeAnnotation"));
28360 return group$b(concat$d(parts));
28362 case "TSNamespaceExportDeclaration":
28363 parts.push("export as namespace ", path.call(print, "id"));
28365 if (options.semi) {
28369 return group$b(concat$d(parts));
28371 case "TSEnumDeclaration":
28373 parts.push("declare ");
28377 parts.push(printTypeScriptModifiers(path, options, print));
28381 parts.push("const ");
28384 parts.push("enum ", path.call(print, "id"), " ");
28386 if (n.members.length === 0) {
28387 parts.push(group$b(concat$d(["{", comments.printDanglingComments(path, options), softline$6, "}"])));
28389 parts.push(group$b(concat$d(["{", indent$7(concat$d([hardline$9, printArrayItems(path, options, "members", print), shouldPrintComma$1(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options,
28391 true), hardline$9, "}"])));
28394 return concat$d(parts);
28396 case "TSEnumMember":
28397 parts.push(path.call(print, "id"));
28399 if (n.initializer) {
28400 parts.push(" = ", path.call(print, "initializer"));
28403 return concat$d(parts);
28405 case "TSImportEqualsDeclaration":
28407 parts.push("export ");
28410 parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference"));
28412 if (options.semi) {
28416 return group$b(concat$d(parts));
28418 case "TSExternalModuleReference":
28419 return concat$d(["require(", path.call(print, "expression"), ")"]);
28421 case "TSModuleDeclaration":
28423 const parent = path.getParentNode();
28424 const isExternalModule = isLiteral$1(n.id);
28425 const parentIsDeclaration = parent.type === "TSModuleDeclaration";
28426 const bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration";
28428 if (parentIsDeclaration) {
28432 parts.push("declare ");
28435 parts.push(printTypeScriptModifiers(path, options, print));
28436 const textBetweenNodeAndItsId = options.originalText.slice(options.locStart(n), options.locStart(n.id)); // Global declaration looks like this:
28437 // (declare)? global { ... }
28439 const isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId);
28441 if (!isGlobalDeclaration) {
28442 parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace ");
28446 parts.push(path.call(print, "id"));
28448 if (bodyIsDeclaration) {
28449 parts.push(path.call(print, "body"));
28450 } else if (n.body) {
28451 parts.push(" ", group$b(path.call(print, "body")));
28456 return concat$d(parts);
28459 case "PrivateName":
28460 return concat$d(["#", path.call(print, "id")]);
28461 // TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields.
28463 case "TSPrivateIdentifier":
28464 return n.escapedText;
28466 case "TSConditionalType":
28467 return printTernaryOperator(path, options, print, {
28468 beforeParts: () => [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")],
28469 afterParts: () => [],
28470 shouldCheckJsx: false,
28471 conditionalNodeType: "TSConditionalType",
28472 consequentNodePropertyName: "trueType",
28473 alternateNodePropertyName: "falseType",
28474 testNodePropertyNames: ["checkType", "extendsType"]
28477 case "TSInferType":
28478 return concat$d(["infer", " ", path.call(print, "typeParameter")]);
28480 case "InterpreterDirective":
28481 parts.push("#!", n.value, hardline$9);
28483 if (isNextLineEmpty$4(options.originalText, n, options.locEnd)) {
28484 parts.push(hardline$9);
28487 return concat$d(parts);
28490 return concat$d([].concat(path.call(print, "node"), !n.node.comments || n.node.comments.length === 0 ? [] : concat$d([" //", n.node.comments[0].value.trimEnd()])));
28492 case "NGChainedExpression":
28493 return group$b(join$9(concat$d([";", line$9]), path.map(childPath => hasNgSideEffect$1(childPath) ? print(childPath) : concat$d(["(", print(childPath), ")"]), "expressions")));
28495 case "NGEmptyExpression":
28498 case "NGQuotedExpression":
28499 return concat$d([n.prefix, ": ", n.value.trim()]);
28501 case "NGMicrosyntax":
28502 return concat$d(path.map((childPath, index) => concat$d([index === 0 ? "" : isNgForOf$1(childPath.getValue(), index, n) ? " " : concat$d([";", line$9]), print(childPath)]), "body"));
28504 case "NGMicrosyntaxKey":
28505 return /^[a-z_$][a-z0-9_$]*(-[a-z_$][a-z0-9_$])*$/i.test(n.name) ? n.name : JSON.stringify(n.name);
28507 case "NGMicrosyntaxExpression":
28508 return concat$d([path.call(print, "expression"), n.alias === null ? "" : concat$d([" as ", path.call(print, "alias")])]);
28510 case "NGMicrosyntaxKeyedExpression":
28512 const index = path.getName();
28513 const parentNode = path.getParentNode();
28514 const shouldNotPrintColon = isNgForOf$1(n, index, parentNode) || (index === 1 && (n.key.name === "then" || n.key.name === "else") || index === 2 && n.key.name === "else" && parentNode.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && parentNode.body[index - 1].key.name === "then") && parentNode.body[0].type === "NGMicrosyntaxExpression";
28515 return concat$d([path.call(print, "key"), shouldNotPrintColon ? " " : ": ", path.call(print, "expression")]);
28518 case "NGMicrosyntaxLet":
28519 return concat$d(["let ", path.call(print, "key"), n.value === null ? "" : concat$d([" = ", path.call(print, "value")])]);
28521 case "NGMicrosyntaxAs":
28522 return concat$d([path.call(print, "key"), " as ", path.call(print, "alias")]);
28524 case "ArgumentPlaceholder":
28526 // These are not valid TypeScript. Printing them just for the sake of error recovery.
28528 case "TSJSDocAllType":
28531 case "TSJSDocUnknownType":
28534 case "TSJSDocNullableType":
28535 return concat$d(["?", path.call(print, "typeAnnotation")]);
28537 case "TSJSDocNonNullableType":
28538 return concat$d(["!", path.call(print, "typeAnnotation")]);
28540 case "TSJSDocFunctionType":
28541 return concat$d(["function(", // The parameters could be here, but typescript-estree doesn't convert them anyway (throws an error).
28542 "): ", path.call(print, "typeAnnotation")]);
28545 /* istanbul ignore next */
28546 throw new Error("unknown type: " + JSON.stringify(n.type));
28550 function printStatementSequence(path, options, print) {
28551 const printed = [];
28552 const bodyNode = path.getNode();
28553 const isClass = bodyNode.type === "ClassBody";
28554 path.map((stmtPath, i) => {
28555 const stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy
28556 // "statements," it's safer simply to skip them.
28558 /* istanbul ignore if */
28562 } // Skip printing EmptyStatement nodes to avoid leaving stray
28563 // semicolons lying around.
28566 if (stmt.type === "EmptyStatement") {
28570 const stmtPrinted = print(stmtPath);
28571 const text = options.originalText;
28572 const parts = []; // in no-semi mode, prepend statement with semicolon if it might break ASI
28573 // don't prepend the only JSX element in a program with semicolon
28575 if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown$1(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options)) {
28576 if (stmt.comments && stmt.comments.some(comment => comment.leading)) {
28577 parts.push(print(stmtPath, {
28581 parts.push(";", stmtPrinted);
28584 parts.push(stmtPrinted);
28587 if (!options.semi && isClass) {
28588 if (classPropMayCauseASIProblems$1(stmtPath)) {
28590 } else if (stmt.type === "ClassProperty") {
28591 const nextChild = bodyNode.body[i + 1];
28593 if (classChildNeedsASIProtection$1(nextChild)) {
28599 if (isNextLineEmpty$4(text, stmt, options.locEnd) && !isLastStatement$1(stmtPath)) {
28600 parts.push(hardline$9);
28603 printed.push(concat$d(parts));
28605 return join$9(hardline$9, printed);
28608 function printPropertyKey(path, options, print) {
28609 const node = path.getNode();
28611 if (node.computed) {
28612 return concat$d(["[", path.call(print, "key"), "]"]);
28615 const parent = path.getParentNode();
28620 if (node.type === "ClassPrivateProperty" && // flow has `Identifier` key, and babel has `PrivateName` key
28621 key.type === "Identifier") {
28622 return concat$d(["#", path.call(print, "key")]);
28625 if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) {
28626 const objectHasStringProp = (parent.properties || parent.body || parent.members).some(prop => !prop.computed && prop.key && isStringLiteral$1(prop.key) && !isStringPropSafeToCoerceToIdentifier$1(prop, options));
28627 needsQuoteProps.set(parent, objectHasStringProp);
28630 if (key.type === "Identifier" && (options.parser === "json" || options.quoteProps === "consistent" && needsQuoteProps.get(parent))) {
28632 const prop = printString$2(JSON.stringify(key.name), options);
28633 return path.call(keyPath => comments.printComments(keyPath, () => prop, options), "key");
28636 if (isStringPropSafeToCoerceToIdentifier$1(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) {
28638 return path.call(keyPath => comments.printComments(keyPath, () => key.value, options), "key");
28641 return path.call(print, "key");
28644 function printMethod(path, options, print) {
28645 const node = path.getNode();
28649 const value = node.value || node;
28652 if (!kind || kind === "init" || kind === "method" || kind === "constructor") {
28654 parts.push("async ");
28657 if (value.generator) {
28661 assert.ok(kind === "get" || kind === "set");
28662 parts.push(kind, " ");
28665 parts.push(printPropertyKey(path, options, print), node.optional || node.key.optional ? "?" : "", node === value ? printMethodInternal(path, options, print) : path.call(path => printMethodInternal(path, options, print), "value"));
28666 return concat$d(parts);
28669 function printMethodInternal(path, options, print) {
28670 const parts = [printFunctionTypeParameters(path, options, print), group$b(concat$d([printFunctionParams(path, print, options), printReturnType(path, print, options)]))];
28672 if (path.getNode().body) {
28673 parts.push(" ", path.call(print, "body"));
28675 parts.push(options.semi ? ";" : "");
28678 return concat$d(parts);
28681 function couldGroupArg(arg) {
28682 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
28683 // https://github.com/prettier/prettier/issues/4070
28684 // export class Thing implements OtherThing {
28685 // do: (type: Type) => Provider<Prop> = memoize(
28686 // (type: ObjectType): Provider<Opts> => {}
28689 // https://github.com/prettier/prettier/issues/6099
28690 // app.get("/", (req, res): void => {
28691 // res.send("Hello World!");
28693 !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));
28696 function shouldGroupLastArg(args) {
28697 const lastArg = getLast$3(args);
28698 const penultimateArg = getPenultimate$1(args);
28699 return !hasLeadingComment$3(lastArg) && !hasTrailingComment$1(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type,
28700 // disable last element expansion.
28701 !penultimateArg || penultimateArg.type !== lastArg.type);
28704 function shouldGroupFirstArg(args) {
28705 if (args.length !== 2) {
28709 const [firstArg, secondArg] = args;
28710 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);
28713 function printJestEachTemplateLiteral(node, expressions, options) {
28716 * ${1} | ${1} | ${2}
28717 * ${1} | ${2} | ${3}
28718 * ${2} | ${1} | ${3}
28720 const headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/);
28722 if (headerNames.length > 1 || headerNames.some(headerName => headerName.length !== 0)) {
28724 const stringifiedExpressions = expressions.map(doc => "${" + printDocToString$2(doc, Object.assign({}, options, {
28725 printWidth: Infinity,
28727 })).formatted + "}");
28728 const tableBody = [{
28729 hasLineBreak: false,
28733 for (let i = 1; i < node.quasis.length; i++) {
28734 const row = tableBody[tableBody.length - 1];
28735 const correspondingExpression = stringifiedExpressions[i - 1];
28736 row.cells.push(correspondingExpression);
28738 if (correspondingExpression.includes("\n")) {
28739 row.hasLineBreak = true;
28742 if (node.quasis[i].value.raw.includes("\n")) {
28744 hasLineBreak: false,
28750 const maxColumnCount = Math.max(headerNames.length, ...tableBody.map(row => row.cells.length));
28751 const maxColumnWidths = Array.from({
28752 length: maxColumnCount
28756 }, ...tableBody.filter(row => row.cells.length !== 0)];
28760 } of table.filter(row => !row.hasLineBreak)) {
28761 cells.forEach((cell, index) => {
28762 maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$3(cell));
28766 parts.push(lineSuffixBoundary$1, "`", indent$7(concat$d([hardline$9, join$9(hardline$9, table.map(row => join$9(" | ", row.cells.map((cell, index) => row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$3(cell))))))])), hardline$9, "`");
28767 return concat$d(parts);
28771 function printArgumentsList(path, options, print) {
28772 const node = path.getValue();
28773 const args = node.arguments;
28775 if (args.length === 0) {
28776 return concat$d(["(", comments.printDanglingComments(path, options,
28779 } // useEffect(() => { ... }, [foo, bar, baz])
28782 if (args.length === 2 && args[0].type === "ArrowFunctionExpression" && args[0].params.length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && !args.find(arg => arg.comments)) {
28783 return concat$d(["(", path.call(print, "arguments", 0), ", ", path.call(print, "arguments", 1), ")"]);
28792 function shouldBreakForArrowFunctionInArguments(arg, argPath) {
28793 if (!arg || arg.type !== "ArrowFunctionExpression" || !arg.body || arg.body.type !== "BlockStatement" || !arg.params || arg.params.length < 1) {
28797 let shouldBreak = false;
28798 argPath.each(paramPath => {
28799 const printed = concat$d([print(paramPath)]);
28800 shouldBreak = shouldBreak || willBreak$1(printed);
28802 return shouldBreak;
28805 let anyArgEmptyLine = false;
28806 let shouldBreakForArrowFunction = false;
28807 let hasEmptyLineFollowingFirstArg = false;
28808 const lastArgIndex = args.length - 1;
28809 const printedArguments = path.map((argPath, index) => {
28810 const arg = argPath.getNode();
28811 const parts = [print(argPath)];
28813 if (index === lastArgIndex) ; else if (isNextLineEmpty$4(options.originalText, arg, options.locEnd)) {
28815 hasEmptyLineFollowingFirstArg = true;
28818 anyArgEmptyLine = true;
28819 parts.push(",", hardline$9, hardline$9);
28821 parts.push(",", line$9);
28824 shouldBreakForArrowFunction = shouldBreakForArrowFunctionInArguments(arg, argPath);
28825 return concat$d(parts);
28827 const maybeTrailingComma = // Dynamic imports cannot have trailing commas
28828 !(node.callee && node.callee.type === "Import") && shouldPrintComma$1(options, "all") ? "," : "";
28830 function allArgsBrokenOut() {
28831 return group$b(concat$d(["(", indent$7(concat$d([line$9, concat$d(printedArguments)])), maybeTrailingComma, line$9, ")"]), {
28836 if (path.getParentNode().type !== "Decorator" && isFunctionCompositionArgs$1(args)) {
28837 return allArgsBrokenOut();
28840 const shouldGroupFirst = shouldGroupFirstArg(args);
28841 const shouldGroupLast = shouldGroupLastArg(args);
28843 if (shouldGroupFirst || shouldGroupLast) {
28844 const shouldBreak = (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$1) : printedArguments.slice(0, -1).some(willBreak$1)) || anyArgEmptyLine || shouldBreakForArrowFunction; // We want to print the last argument with a special flag
28846 let printedExpanded;
28848 path.each(argPath => {
28849 if (shouldGroupFirst && i === 0) {
28850 printedExpanded = [concat$d([argPath.call(p => print(p, {
28851 expandFirstArg: true
28852 })), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$9 : line$9, hasEmptyLineFollowingFirstArg ? hardline$9 : ""])].concat(printedArguments.slice(1));
28855 if (shouldGroupLast && i === args.length - 1) {
28856 printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(p => print(p, {
28857 expandLastArg: true
28863 const somePrintedArgumentsWillBreak = printedArguments.some(willBreak$1);
28864 const simpleConcat = concat$d(["(", concat$d(printedExpanded), ")"]);
28865 return concat$d([somePrintedArgumentsWillBreak ? breakParent$3 : "", conditionalGroup$1([!somePrintedArgumentsWillBreak && !node.typeArguments && !node.typeParameters ? simpleConcat : ifBreak$6(allArgsBrokenOut(), simpleConcat), shouldGroupFirst ? concat$d(["(", group$b(printedExpanded[0], {
28867 }), concat$d(printedExpanded.slice(1)), ")"]) : concat$d(["(", concat$d(printedArguments.slice(0, -1)), group$b(getLast$3(printedExpanded), {
28869 }), ")"]), allArgsBrokenOut()], {
28874 const contents = concat$d(["(", indent$7(concat$d([softline$6, concat$d(printedArguments)])), ifBreak$6(maybeTrailingComma), softline$6, ")"]);
28876 if (isLongCurriedCallExpression$1(path)) {
28877 // By not wrapping the arguments in a group, the printer prioritizes
28878 // breaking up these arguments rather than the args of the parent call.
28882 return group$b(contents, {
28883 shouldBreak: printedArguments.some(willBreak$1) || anyArgEmptyLine
28887 function printTypeAnnotation(path, options, print) {
28888 const node = path.getValue();
28890 if (!node.typeAnnotation) {
28894 const parentNode = path.getParentNode();
28895 const isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite;
28896 const isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node;
28898 if (isFlowAnnotationComment$1(options.originalText, node.typeAnnotation, options)) {
28899 return concat$d([" /*: ", path.call(print, "typeAnnotation"), " */"]);
28902 return concat$d([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path.call(print, "typeAnnotation")]);
28905 function printFunctionTypeParameters(path, options, print) {
28906 const fun = path.getValue();
28908 if (fun.typeArguments) {
28909 return path.call(print, "typeArguments");
28912 if (fun.typeParameters) {
28913 return path.call(print, "typeParameters");
28919 function printFunctionParams(path, print, options, expandArg, printTypeParams) {
28920 const fun = path.getValue();
28921 const parent = path.getParentNode();
28922 const paramsField = fun.parameters ? "parameters" : "params";
28923 const isParametersInTestCall = isTestCall$1(parent);
28924 const shouldHugParameters = shouldHugArguments(fun);
28925 const shouldExpandParameters = expandArg && !(fun[paramsField] && fun[paramsField].some(n => n.comments));
28926 const typeParams = printTypeParams ? printFunctionTypeParameters(path, options, print) : "";
28929 if (fun[paramsField]) {
28930 const lastArgIndex = fun[paramsField].length - 1;
28931 printed = path.map((childPath, index) => {
28933 const param = childPath.getValue();
28934 parts.push(print(childPath));
28936 if (index === lastArgIndex) {
28938 parts.push(",", line$9);
28940 } else if (isParametersInTestCall || shouldHugParameters || shouldExpandParameters) {
28942 } else if (isNextLineEmpty$4(options.originalText, param, options.locEnd)) {
28943 parts.push(",", hardline$9, hardline$9);
28945 parts.push(",", line$9);
28948 return concat$d(parts);
28953 printed.push(concat$d(["...", path.call(print, "rest")]));
28956 if (printed.length === 0) {
28957 return concat$d([typeParams, "(", comments.printDanglingComments(path, options,
28959 true, comment => getNextNonSpaceNonCommentCharacter$1(options.originalText, comment, options.locEnd) === ")"), ")"]);
28962 const lastParam = getLast$3(fun[paramsField]); // If the parent is a call with the first/last argument expansion and this is the
28963 // params of the first/last argument, we don't want the arguments to break and instead
28964 // want the whole expression to be on a new line.
28967 // verylongcall( verylongcall((
28973 if (shouldExpandParameters) {
28974 return group$b(concat$d([removeLines$2(typeParams), "(", concat$d(printed.map(removeLines$2)), ")"]));
28975 } // Single object destructuring should hug
28984 const hasNotParameterDecorator = fun[paramsField].every(param => !param.decorators);
28986 if (shouldHugParameters && hasNotParameterDecorator) {
28987 return concat$d([typeParams, "(", concat$d(printed), ")"]);
28988 } // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})`
28991 if (isParametersInTestCall) {
28992 return concat$d([typeParams, "(", concat$d(printed), ")"]);
28995 const isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction$1(parent, options) || isTypeAnnotationAFunction$1(parent, options) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === fun) && fun[paramsField].length === 1 && fun[paramsField][0].name === null && fun[paramsField][0].typeAnnotation && fun.typeParameters === null && isSimpleFlowType$1(fun[paramsField][0].typeAnnotation) && !fun.rest;
28997 if (isFlowShorthandWithOneArg) {
28998 if (options.arrowParens === "always") {
28999 return concat$d(["(", concat$d(printed), ")"]);
29002 return concat$d(printed);
29005 const canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest;
29006 return concat$d([typeParams, "(", indent$7(concat$d([softline$6, concat$d(printed)])), ifBreak$6(canHaveTrailingComma && shouldPrintComma$1(options, "all") ? "," : ""), softline$6, ")"]);
29009 function shouldPrintParamsWithoutParens(path, options) {
29010 if (options.arrowParens === "always") {
29014 if (options.arrowParens === "avoid") {
29015 const node = path.getValue();
29016 return canPrintParamsWithoutParens(node);
29017 } // Fallback default; should be unreachable
29023 function canPrintParamsWithoutParens(node) {
29024 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;
29027 function printFunctionDeclaration(path, print, options) {
29028 const n = path.getValue();
29032 parts.push("async ");
29036 parts.push("function* ");
29038 parts.push("function ");
29042 parts.push(path.call(print, "id"));
29045 parts.push(printFunctionTypeParameters(path, options, print), group$b(concat$d([printFunctionParams(path, print, options), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body"));
29046 return concat$d(parts);
29049 function printReturnType(path, print, options) {
29050 const n = path.getValue();
29051 const returnType = path.call(print, "returnType");
29053 if (n.returnType && isFlowAnnotationComment$1(options.originalText, n.returnType, options)) {
29054 return concat$d([" /*: ", returnType, " */"]);
29057 const parts = [returnType]; // prepend colon to TypeScript type annotation
29059 if (n.returnType && n.returnType.typeAnnotation) {
29060 parts.unshift(": ");
29064 // The return type will already add the colon, but otherwise we
29065 // need to do it ourselves
29066 parts.push(n.returnType ? " " : ": ", path.call(print, "predicate"));
29069 return concat$d(parts);
29072 function printExportDeclaration(path, options, print) {
29073 const decl = path.getValue();
29074 const semi = options.semi ? ";" : "";
29075 const parts = ["export "];
29076 const isDefault = decl.default || decl.type === "ExportDefaultDeclaration";
29079 parts.push("default ");
29082 parts.push(comments.printDanglingComments(path, options,
29086 if (needsHardlineAfterDanglingComment$1(decl)) {
29087 parts.push(hardline$9);
29090 if (decl.declaration) {
29091 parts.push(path.call(print, "declaration"));
29093 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") {
29097 if (decl.specifiers && decl.specifiers.length > 0) {
29098 const specifiers = [];
29099 const defaultSpecifiers = [];
29100 const namespaceSpecifiers = [];
29101 path.each(specifierPath => {
29102 const specifierType = path.getValue().type;
29104 if (specifierType === "ExportSpecifier") {
29105 specifiers.push(print(specifierPath));
29106 } else if (specifierType === "ExportDefaultSpecifier") {
29107 defaultSpecifiers.push(print(specifierPath));
29108 } else if (specifierType === "ExportNamespaceSpecifier") {
29109 namespaceSpecifiers.push(concat$d(["* as ", print(specifierPath)]));
29112 const isNamespaceFollowed = namespaceSpecifiers.length !== 0 && specifiers.length !== 0;
29113 const isDefaultFollowed = defaultSpecifiers.length !== 0 && (namespaceSpecifiers.length !== 0 || specifiers.length !== 0);
29114 const canBreak = specifiers.length > 1 || defaultSpecifiers.length > 0 || decl.specifiers && decl.specifiers.some(node => node.comments);
29117 if (specifiers.length !== 0) {
29119 printed = group$b(concat$d(["{", indent$7(concat$d([options.bracketSpacing ? line$9 : softline$6, join$9(concat$d([",", line$9]), specifiers)])), ifBreak$6(shouldPrintComma$1(options) ? "," : ""), options.bracketSpacing ? line$9 : softline$6, "}"]));
29121 printed = concat$d(["{", options.bracketSpacing ? " " : "", concat$d(specifiers), options.bracketSpacing ? " " : "", "}"]);
29125 parts.push(decl.exportKind === "type" ? "type " : "", concat$d(defaultSpecifiers), concat$d([isDefaultFollowed ? ", " : ""]), concat$d(namespaceSpecifiers), concat$d([isNamespaceFollowed ? ", " : ""]), printed);
29131 parts.push(" from ", path.call(print, "source"));
29137 return concat$d(parts);
29140 function printFlowDeclaration(path, parts) {
29141 const parentExportDecl = getParentExportDeclaration$1(path);
29143 if (parentExportDecl) {
29144 assert.strictEqual(parentExportDecl.type, "DeclareExportDeclaration");
29146 // If the parent node has type DeclareExportDeclaration, then it
29147 // will be responsible for printing the "declare" token. Otherwise
29148 // it needs to be printed with this non-exported declaration node.
29149 parts.unshift("declare ");
29152 return concat$d(parts);
29155 function printTypeScriptModifiers(path, options, print) {
29156 const n = path.getValue();
29158 if (!n.modifiers || !n.modifiers.length) {
29162 return concat$d([join$9(" ", path.map(print, "modifiers")), " "]);
29165 function printTypeParameters(path, options, print, paramsKey) {
29166 const n = path.getValue();
29168 if (!n[paramsKey]) {
29170 } // for TypeParameterDeclaration typeParameters is a single node
29173 if (!Array.isArray(n[paramsKey])) {
29174 return path.call(print, paramsKey);
29177 const grandparent = path.getNode(2);
29178 const greatGrandParent = path.getNode(3);
29179 const greatGreatGrandParent = path.getNode(4);
29180 const isParameterInTestCall = grandparent != null && isTestCall$1(grandparent);
29181 const shouldInline = isParameterInTestCall || n[paramsKey].length === 0 || n[paramsKey].length === 1 && (shouldHugType(n[paramsKey][0]) || n[paramsKey][0].type === "GenericTypeAnnotation" && shouldHugType(n[paramsKey][0].id) || n[paramsKey][0].type === "TSTypeReference" && shouldHugType(n[paramsKey][0].typeName) || n[paramsKey][0].type === "NullableTypeAnnotation" || // See https://github.com/prettier/prettier/pull/6467 for the context.
29182 greatGreatGrandParent && greatGreatGrandParent.type === "VariableDeclarator" && grandparent.type === "TSTypeAnnotation" && greatGrandParent.type !== "ArrowFunctionExpression" && n[paramsKey][0].type !== "TSUnionType" && n[paramsKey][0].type !== "UnionTypeAnnotation" && n[paramsKey][0].type !== "TSIntersectionType" && n[paramsKey][0].type !== "IntersectionTypeAnnotation" && n[paramsKey][0].type !== "TSConditionalType" && n[paramsKey][0].type !== "TSMappedType" && n[paramsKey][0].type !== "TSTypeOperator" && n[paramsKey][0].type !== "TSIndexedAccessType" && n[paramsKey][0].type !== "TSArrayType");
29184 function printDanglingCommentsForInline(n) {
29185 if (!hasDanglingComments$1(n)) {
29189 const hasOnlyBlockComments = n.comments.every(comments$1.isBlockComment);
29190 const printed = comments.printDanglingComments(path, options,
29192 hasOnlyBlockComments);
29194 if (hasOnlyBlockComments) {
29198 return concat$d([printed, hardline$9]);
29201 if (shouldInline) {
29202 return concat$d(["<", join$9(", ", path.map(print, paramsKey)), printDanglingCommentsForInline(n), ">"]);
29205 return group$b(concat$d(["<", indent$7(concat$d([softline$6, join$9(concat$d([",", line$9]), path.map(print, paramsKey))])), ifBreak$6(options.parser !== "typescript" && options.parser !== "babel-ts" && shouldPrintComma$1(options, "all") ? "," : ""), softline$6, ">"]));
29208 function printClass(path, options, print) {
29209 const n = path.getValue();
29213 parts.push("abstract ");
29216 parts.push("class");
29219 parts.push(" ", path.call(print, "id"));
29222 parts.push(path.call(print, "typeParameters"));
29223 const partsGroup = [];
29225 if (n.superClass) {
29226 const printed = concat$d(["extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters")]); // Keep old behaviour of extends in same line
29227 // If there is only on extends and there are not comments
29229 if ((!n.implements || n.implements.length === 0) && (!n.superClass.comments || n.superClass.comments.length === 0)) {
29230 parts.push(concat$d([" ", path.call(superClass => comments.printComments(superClass, () => printed, options), "superClass")]));
29232 partsGroup.push(group$b(concat$d([line$9, path.call(superClass => comments.printComments(superClass, () => printed, options), "superClass")])));
29234 } else if (n.extends && n.extends.length > 0) {
29235 parts.push(" extends ", join$9(", ", path.map(print, "extends")));
29238 if (n.mixins && n.mixins.length > 0) {
29239 partsGroup.push(line$9, "mixins ", group$b(indent$7(join$9(concat$d([",", line$9]), path.map(print, "mixins")))));
29242 if (n.implements && n.implements.length > 0) {
29243 partsGroup.push(line$9, "implements", group$b(indent$7(concat$d([line$9, join$9(concat$d([",", line$9]), path.map(print, "implements"))]))));
29246 if (partsGroup.length > 0) {
29247 parts.push(group$b(indent$7(concat$d(partsGroup))));
29250 if (n.body && n.body.comments && hasLeadingOwnLineComment$1(options.originalText, n.body, options)) {
29251 parts.push(hardline$9);
29256 parts.push(path.call(print, "body"));
29260 function printOptionalToken(path) {
29261 const node = path.getValue();
29263 if (!node.optional || // It's an optional computed method parsed by typescript-estree.
29264 // "?" is printed in `printMethod`.
29265 node.type === "Identifier" && node === path.getParentNode().key) {
29269 if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) {
29276 function printMemberLookup(path, options, print) {
29277 const property = path.call(print, "property");
29278 const n = path.getValue();
29279 const optional = printOptionalToken(path);
29282 return concat$d([optional, ".", property]);
29285 if (!n.property || isNumericLiteral$1(n.property)) {
29286 return concat$d([optional, "[", property, "]"]);
29289 return group$b(concat$d([optional, "[", indent$7(concat$d([softline$6, property])), softline$6, "]"]));
29292 function printBindExpressionCallee(path, options, print) {
29293 return concat$d(["::", path.call(print, "callee")]);
29294 } // We detect calls on member expressions specially to format a
29295 // common pattern better. The pattern we are looking for is this:
29298 // .map(x => x + 1)
29299 // .filter(x => x > 10)
29300 // .some(x => x % 2)
29302 // The way it is structured in the AST is via a nested sequence of
29303 // MemberExpression and CallExpression. We need to traverse the AST
29304 // and make groups out of it to print it in the desired way.
29307 function printMemberChain(path, options, print) {
29308 // The first phase is to linearize the AST by traversing it down.
29311 // has the following AST structure:
29312 // CallExpression(MemberExpression(CallExpression(Identifier)))
29313 // and we transform it into
29314 // [Identifier, CallExpression, MemberExpression, CallExpression]
29315 const printedNodes = []; // Here we try to retain one typed empty line after each call expression or
29316 // the first group whether it is in parentheses or not
29318 function shouldInsertEmptyLineAfter(node) {
29322 const nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$3(originalText, node, options.locEnd);
29323 const nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty
29324 // line after that parenthesis
29326 if (nextChar === ")") {
29327 return isNextLineEmptyAfterIndex$2(originalText, nextCharIndex + 1, options.locEnd);
29330 return isNextLineEmpty$4(originalText, node, options.locEnd);
29333 function rec(path) {
29334 const node = path.getValue();
29336 if ((node.type === "CallExpression" || node.type === "OptionalCallExpression") && (isMemberish$1(node.callee) || node.callee.type === "CallExpression" || node.callee.type === "OptionalCallExpression")) {
29337 printedNodes.unshift({
29339 printed: concat$d([comments.printComments(path, () => concat$d([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)]), options), shouldInsertEmptyLineAfter(node) ? hardline$9 : ""])
29341 path.call(callee => rec(callee), "callee");
29342 } else if (isMemberish$1(node)) {
29343 printedNodes.unshift({
29345 needsParens: needsParens_1(path, options),
29346 printed: comments.printComments(path, () => node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup(path, options, print) : printBindExpressionCallee(path, options, print), options)
29348 path.call(object => rec(object), "object");
29349 } else if (node.type === "TSNonNullExpression") {
29350 printedNodes.unshift({
29352 printed: comments.printComments(path, () => "!", options)
29354 path.call(expression => rec(expression), "expression");
29356 printedNodes.unshift({
29358 printed: path.call(print)
29361 } // Note: the comments of the root node have already been printed, so we
29362 // need to extract this first call without printing them as they would
29363 // if handled inside of the recursive call.
29366 const node = path.getValue();
29367 printedNodes.unshift({
29369 printed: concat$d([printOptionalToken(path), printFunctionTypeParameters(path, options, print), printArgumentsList(path, options, print)])
29371 path.call(callee => rec(callee), "callee"); // Once we have a linear list of printed nodes, we want to create groups out
29375 // will be grouped as
29377 // [Identifier, CallExpression],
29378 // [MemberExpression, MemberExpression, CallExpression],
29379 // [MemberExpression, CallExpression],
29380 // [MemberExpression],
29382 // so that we can print it as
29387 // The first group is the first node followed by
29388 // - as many CallExpression as possible
29389 // < fn()()() >.something()
29390 // - as many array accessors as possible
29391 // < fn()[0][1][2] >.something()
29392 // - then, as many MemberExpression as possible but the last one
29393 // < this.items >.something()
29396 let currentGroup = [printedNodes[0]];
29399 for (; i < printedNodes.length; ++i) {
29400 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)) {
29401 currentGroup.push(printedNodes[i]);
29407 if (printedNodes[0].node.type !== "CallExpression" && printedNodes[0].node.type !== "OptionalCallExpression") {
29408 for (; i + 1 < printedNodes.length; ++i) {
29409 if (isMemberish$1(printedNodes[i].node) && isMemberish$1(printedNodes[i + 1].node)) {
29410 currentGroup.push(printedNodes[i]);
29417 groups.push(currentGroup);
29418 currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by
29419 // a sequence of CallExpression. To compute it, we keep adding things to the
29420 // group until we has seen a CallExpression in the past and reach a
29421 // MemberExpression
29423 let hasSeenCallExpression = false;
29425 for (; i < printedNodes.length; ++i) {
29426 if (hasSeenCallExpression && isMemberish$1(printedNodes[i].node)) {
29427 // [0] should be appended at the end of the group instead of the
29428 // beginning of the next one
29429 if (printedNodes[i].node.computed && isNumericLiteral$1(printedNodes[i].node.property)) {
29430 currentGroup.push(printedNodes[i]);
29434 groups.push(currentGroup);
29436 hasSeenCallExpression = false;
29439 if (printedNodes[i].node.type === "CallExpression" || printedNodes[i].node.type === "OptionalCallExpression") {
29440 hasSeenCallExpression = true;
29443 currentGroup.push(printedNodes[i]);
29445 if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(comment => comment.trailing)) {
29446 groups.push(currentGroup);
29448 hasSeenCallExpression = false;
29452 if (currentGroup.length > 0) {
29453 groups.push(currentGroup);
29454 } // There are cases like Object.keys(), Observable.of(), _.values() where
29455 // they are the subject of all the chained calls and therefore should
29456 // be kept on the same line:
29458 // Object.keys(items)
29462 // In order to detect those cases, we use an heuristic: if the first
29463 // node is an identifier with the name starting with a capital
29464 // letter or just a sequence of _$. The rationale is that they are
29465 // likely to be factories.
29468 function isFactory(name) {
29469 return /^[A-Z]|^[_$]+$/.test(name);
29470 } // In case the Identifier is shorter than tab width, we can keep the
29471 // first call in a single line, if it's an ExpressionStatement.
29473 // d3.scaleLinear()
29474 // .domain([0, 100])
29475 // .range([0, width]);
29479 function isShort(name) {
29480 return name.length <= options.tabWidth;
29483 function shouldNotWrap(groups) {
29484 const parent = path.getParentNode();
29485 const isExpression = parent && parent.type === "ExpressionStatement";
29486 const hasComputed = groups[1].length && groups[1][0].node.computed;
29488 if (groups[0].length === 1) {
29489 const firstNode = groups[0][0].node;
29490 return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpression && isShort(firstNode.name) || hasComputed);
29493 const lastNode = getLast$3(groups[0]).node;
29494 return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed);
29497 const shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups);
29499 function printGroup(printedGroup) {
29500 const printed = printedGroup.map(tuple => tuple.printed); // Checks if the last node (i.e. the parent node) needs parens and print
29503 if (printedGroup.length > 0 && printedGroup[printedGroup.length - 1].needsParens) {
29504 return concat$d(["(", ...printed, ")"]);
29507 return concat$d(printed);
29510 function printIndentedGroup(groups) {
29511 if (groups.length === 0) {
29515 return indent$7(group$b(concat$d([hardline$9, join$9(hardline$9, groups.map(printGroup))])));
29518 const printedGroups = groups.map(printGroup);
29519 const oneLine = concat$d(printedGroups);
29520 const cutoff = shouldMerge ? 3 : 2;
29521 const flatGroups = groups.reduce((res, group) => res.concat(group), []);
29522 const hasComment = flatGroups.slice(1, -1).some(node => hasLeadingComment$3(node.node)) || flatGroups.slice(0, -1).some(node => hasTrailingComment$1(node.node)) || groups[cutoff] && hasLeadingComment$3(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just
29523 // render everything concatenated together.
29525 if (groups.length <= cutoff && !hasComment) {
29526 if (isLongCurriedCallExpression$1(path)) {
29530 return group$b(oneLine);
29531 } // Find out the last node in the first group and check if it has an
29532 // empty line after
29535 const lastNodeBeforeIndent = getLast$3(shouldMerge ? groups.slice(1, 2)[0] : groups[0]).node;
29536 const shouldHaveEmptyLineBeforeIndent = lastNodeBeforeIndent.type !== "CallExpression" && lastNodeBeforeIndent.type !== "OptionalCallExpression" && shouldInsertEmptyLineAfter(lastNodeBeforeIndent);
29537 const expanded = concat$d([printGroup(groups[0]), shouldMerge ? concat$d(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$9 : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]);
29538 const callExpressions = printedNodes.map(({
29540 }) => node).filter(isCallOrOptionalCallExpression$1); // We don't want to print in one line if the chain has:
29542 // * Non-trivial arguments.
29543 // * Any group but the last one has a hard line.
29544 // If the last group is a function it's okay to inline if it fits.
29546 if (hasComment || callExpressions.length > 2 && callExpressions.some(expr => !expr.arguments.every(arg => isSimpleCallArgument$1(arg, 0))) || printedGroups.slice(0, -1).some(willBreak$1) ||
29548 * scopes.filter(scope => scope.value !== '').map((scope, i) => {
29549 * // multi line content
29552 ((lastGroupDoc, lastGroupNode) => isCallOrOptionalCallExpression$1(lastGroupNode) && willBreak$1(lastGroupDoc))(getLast$3(printedGroups), getLast$3(getLast$3(groups)).node) && callExpressions.slice(0, -1).some(n => n.arguments.some(isFunctionOrArrowExpression$1))) {
29553 return group$b(expanded);
29556 return concat$d([// We only need to check `oneLine` because if `expanded` is chosen
29557 // that means that the parent group has already been broken
29559 willBreak$1(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$3 : "", conditionalGroup$1([oneLine, expanded])]);
29562 function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
29563 if (isFacebookTranslationTag) {
29567 if (childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement) {
29568 return child.length === 1 ? softline$6 : hardline$9;
29574 function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) {
29575 if (isFacebookTranslationTag) {
29579 if (child.length === 1) {
29580 return childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement ? hardline$9 : softline$6;
29584 } // JSX Children are strange, mostly for two reasons:
29585 // 1. JSX reads newlines into string values, instead of skipping them like JS
29586 // 2. up to one whitespace between elements within a line is significant,
29587 // but not between lines.
29589 // Leading, trailing, and lone whitespace all need to
29590 // turn themselves into the rather ugly `{' '}` when breaking.
29592 // We print JSX using the `fill` doc primitive.
29593 // This requires that we give it an array of alternating
29594 // content and whitespace elements.
29595 // To ensure this we add dummy `""` content elements as needed.
29598 function printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag) {
29599 const n = path.getValue();
29600 const children = []; // using `map` instead of `each` because it provides `i`
29602 path.map((childPath, i) => {
29603 const child = childPath.getValue();
29605 if (isLiteral$1(child)) {
29606 const text = rawText$1(child); // Contains a non-whitespace character
29608 if (isMeaningfulJSXText$1(child)) {
29609 const words = text.split(matchJsxWhitespaceRegex$1); // Starts with whitespace
29611 if (words[0] === "") {
29615 if (/\n/.test(words[0])) {
29616 const next = n.children[i + 1];
29617 children.push(separatorWithWhitespace(isFacebookTranslationTag, words[1], child, next));
29619 children.push(jsxWhitespace);
29625 let endWhitespace; // Ends with whitespace
29627 if (getLast$3(words) === "") {
29629 endWhitespace = words.pop();
29630 } // This was whitespace only without a new line.
29633 if (words.length === 0) {
29637 words.forEach((word, i) => {
29639 children.push(line$9);
29641 children.push(word);
29645 if (endWhitespace !== undefined) {
29646 if (/\n/.test(endWhitespace)) {
29647 const next = n.children[i + 1];
29648 children.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$3(children), child, next));
29650 children.push(jsxWhitespace);
29653 const next = n.children[i + 1];
29654 children.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$3(children), child, next));
29656 } else if (/\n/.test(text)) {
29657 // Keep (up to one) blank line between tags/expressions/text.
29658 // Note: We don't keep blank lines between text elements.
29659 if (text.match(/\n/g).length > 1) {
29661 children.push(hardline$9);
29665 children.push(jsxWhitespace);
29668 const printedChild = print(childPath);
29669 children.push(printedChild);
29670 const next = n.children[i + 1];
29671 const directlyFollowedByMeaningfulText = next && isMeaningfulJSXText$1(next);
29673 if (directlyFollowedByMeaningfulText) {
29674 const firstWord = rawText$1(next).trim().split(matchJsxWhitespaceRegex$1)[0];
29675 children.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord, child, next));
29677 children.push(hardline$9);
29682 } // JSX expands children from the inside-out, instead of the outside-in.
29683 // This is both to break children before attributes,
29684 // and to ensure that when children break, their parents do as well.
29686 // Any element that is written without any newlines and fits on a single line
29687 // is left that way.
29688 // Not only that, any user-written-line containing multiple JSX siblings
29689 // should also be kept on one line if possible,
29690 // so each user-written-line is wrapped in its own group.
29692 // Elements that contain newlines or don't fit on a single line (recursively)
29693 // are fully-split, using hardline and shouldBreak: true.
29695 // To support that case properly, all leading and trailing spaces
29696 // are stripped from the list of children, and replaced with a single hardline.
29699 function printJSXElement(path, options, print) {
29700 const n = path.getValue();
29702 if (n.type === "JSXElement" && isEmptyJSXElement$1(n)) {
29703 return concat$d([path.call(print, "openingElement"), path.call(print, "closingElement")]);
29706 const openingLines = n.type === "JSXElement" ? path.call(print, "openingElement") : path.call(print, "openingFragment");
29707 const closingLines = n.type === "JSXElement" ? path.call(print, "closingElement") : path.call(print, "closingFragment");
29709 if (n.children.length === 1 && n.children[0].type === "JSXExpressionContainer" && (n.children[0].expression.type === "TemplateLiteral" || n.children[0].expression.type === "TaggedTemplateExpression")) {
29710 return concat$d([openingLines, concat$d(path.map(print, "children")), closingLines]);
29711 } // Convert `{" "}` to text nodes containing a space.
29712 // This makes it easy to turn them into `jsxWhitespace` which
29713 // can then print as either a space or `{" "}` when breaking.
29716 n.children = n.children.map(child => {
29717 if (isJSXWhitespaceExpression$1(child)) {
29727 const containsTag = n.children.filter(isJSXNode$1).length > 0;
29728 const containsMultipleExpressions = n.children.filter(child => child.type === "JSXExpressionContainer").length > 1;
29729 const containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true.
29731 let forcedBreak = willBreak$1(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions;
29732 const isMdxBlock = path.getParentNode().rootMarker === "mdx";
29733 const rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}';
29734 const jsxWhitespace = isMdxBlock ? concat$d([" "]) : ifBreak$6(concat$d([rawJsxWhitespace, softline$6]), " ");
29735 const isFacebookTranslationTag = n.openingElement && n.openingElement.name && n.openingElement.name.name === "fbt";
29736 const children = printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag);
29737 const containsText = n.children.some(child => isMeaningfulJSXText$1(child)); // We can end up we multiple whitespace elements with empty string
29738 // content between them.
29739 // We need to remove empty whitespace and softlines before JSX whitespace
29740 // to get the correct output.
29742 for (let i = children.length - 2; i >= 0; i--) {
29743 const isPairOfEmptyStrings = children[i] === "" && children[i + 1] === "";
29744 const isPairOfHardlines = children[i] === hardline$9 && children[i + 1] === "" && children[i + 2] === hardline$9;
29745 const isLineFollowedByJSXWhitespace = (children[i] === softline$6 || children[i] === hardline$9) && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
29746 const isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$6 || children[i + 2] === hardline$9);
29747 const isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace;
29748 const isPairOfHardOrSoftLines = children[i] === softline$6 && children[i + 1] === "" && children[i + 2] === hardline$9 || children[i] === hardline$9 && children[i + 1] === "" && children[i + 2] === softline$6;
29750 if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace || isPairOfHardOrSoftLines) {
29751 children.splice(i, 2);
29752 } else if (isJSXWhitespaceFollowedByLine) {
29753 children.splice(i + 1, 2);
29755 } // Trim trailing lines (or empty strings)
29758 while (children.length && (isLineNext$1(getLast$3(children)) || isEmpty$1(getLast$3(children)))) {
29760 } // Trim leading lines (or empty strings)
29763 while (children.length && (isLineNext$1(children[0]) || isEmpty$1(children[0])) && (isLineNext$1(children[1]) || isEmpty$1(children[1]))) {
29766 } // Tweak how we format children if outputting this element over multiple lines.
29767 // Also detect whether we will force this element to output over multiple lines.
29770 const multilineChildren = [];
29771 children.forEach((child, i) => {
29772 // There are a number of situations where we need to ensure we display
29773 // whitespace as `{" "}` when outputting this element over multiple lines.
29774 if (child === jsxWhitespace) {
29775 if (i === 1 && children[i - 1] === "") {
29776 if (children.length === 2) {
29777 // Solitary whitespace
29778 multilineChildren.push(rawJsxWhitespace);
29780 } // Leading whitespace
29783 multilineChildren.push(concat$d([rawJsxWhitespace, hardline$9]));
29785 } else if (i === children.length - 1) {
29786 // Trailing whitespace
29787 multilineChildren.push(rawJsxWhitespace);
29789 } else if (children[i - 1] === "" && children[i - 2] === hardline$9) {
29790 // Whitespace after line break
29791 multilineChildren.push(rawJsxWhitespace);
29796 multilineChildren.push(child);
29798 if (willBreak$1(child)) {
29799 forcedBreak = true;
29801 }); // If there is text we use `fill` to fit as much onto each line as possible.
29802 // When there is no text (just tags and expressions) we use `group`
29803 // to output each on a separate line.
29805 const content = containsText ? fill$4(multilineChildren) : group$b(concat$d(multilineChildren), {
29813 const multiLineElem = group$b(concat$d([openingLines, indent$7(concat$d([hardline$9, content])), hardline$9, closingLines]));
29816 return multiLineElem;
29819 return conditionalGroup$1([group$b(concat$d([openingLines, concat$d(children), closingLines])), multiLineElem]);
29822 function maybeWrapJSXElementInParens(path, elem, options) {
29823 const parent = path.getParentNode();
29829 const NO_WRAP_PARENTS = {
29830 ArrayExpression: true,
29831 JSXAttribute: true,
29833 JSXExpressionContainer: true,
29835 ExpressionStatement: true,
29836 CallExpression: true,
29837 OptionalCallExpression: true,
29838 ConditionalExpression: true,
29839 JsExpressionRoot: true
29842 if (NO_WRAP_PARENTS[parent.type]) {
29846 const shouldBreak = path.match(undefined, node => node.type === "ArrowFunctionExpression", isCallOrOptionalCallExpression$1, node => node.type === "JSXExpressionContainer");
29847 const needsParens = needsParens_1(path, options);
29848 return group$b(concat$d([needsParens ? "" : ifBreak$6("("), indent$7(concat$d([softline$6, elem])), softline$6, needsParens ? "" : ifBreak$6(")")]), {
29853 function shouldInlineLogicalExpression(node) {
29854 if (node.type !== "LogicalExpression") {
29858 if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) {
29862 if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) {
29866 if (isJSXNode$1(node.right)) {
29871 } // For binary expressions to be consistent, we need to group
29872 // subsequent operators with the same precedence level under a single
29873 // group. Otherwise they will be nested such that some of them break
29874 // onto new lines but not all. Operators with the same precedence
29875 // level should either all break or not. Because we group them by
29876 // precedence level and the AST is structured based on precedence
29877 // level, things are naturally broken up correctly, i.e. `&&` is
29878 // broken before `+`.
29881 function printBinaryishExpressions(path, print, options, isNested, isInsideParenthesis) {
29883 const node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same.
29885 if (isBinaryish$1(node)) {
29886 // Put all operators with the same precedence level in the same
29887 // group. The reason we only need to do this with the `left`
29888 // expression is because given an expression like `1 + 2 - 3`, it
29889 // is always parsed like `((1 + 2) - 3)`, meaning the `left` side
29890 // is where the rest of the expression will exist. Binary
29891 // expressions on the right side mean they have a difference
29892 // precedence level and should be treated as a separate group, so
29893 // print them normally. (This doesn't hold for the `**` operator,
29894 // which is unique in that it is right-associative.)
29895 if (shouldFlatten$1(node.operator, node.left.operator)) {
29896 // Flatten them out by recursively calling this function.
29897 parts = parts.concat(path.call(left => printBinaryishExpressions(left, print, options,
29899 true, isInsideParenthesis), "left"));
29901 parts.push(path.call(print, "left"));
29904 const shouldInline = shouldInlineLogicalExpression(node);
29905 const lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment$1(options.originalText, node.right, options);
29906 const operator = node.type === "NGPipeExpression" ? "|" : node.operator;
29907 const rightSuffix = node.type === "NGPipeExpression" && node.arguments.length !== 0 ? group$b(indent$7(concat$d([softline$6, ": ", join$9(concat$d([softline$6, ":", ifBreak$6(" ")]), path.map(print, "arguments").map(arg => align$1(2, group$b(arg))))]))) : "";
29908 const right = shouldInline ? concat$d([operator, " ", path.call(print, "right"), rightSuffix]) : concat$d([lineBeforeOperator ? softline$6 : "", operator, lineBeforeOperator ? " " : line$9, path.call(print, "right"), rightSuffix]); // If there's only a single binary expression, we want to create a group
29909 // in order to avoid having a small right part like -1 be on its own line.
29911 const parent = path.getParentNode();
29912 const shouldGroup = !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type;
29913 parts.push(" ", shouldGroup ? group$b(right) : right); // The root comments are already printed, but we need to manually print
29914 // the other ones since we don't call the normal print on BinaryExpression,
29915 // only for the left and right parts
29917 if (isNested && node.comments) {
29918 parts = comments.printComments(path, () => concat$d(parts), options);
29921 // Our stopping case. Simply print the node normally.
29922 parts.push(path.call(print));
29928 function printAssignmentRight(leftNode, rightNode, printedRight, options) {
29929 if (hasLeadingOwnLineComment$1(options.originalText, rightNode, options)) {
29930 return indent$7(concat$d([line$9, printedRight]));
29933 const canBreak = isBinaryish$1(rightNode) && !shouldInlineLogicalExpression(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish$1(rightNode.test) && !shouldInlineLogicalExpression(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || rightNode.type === "ClassExpression" && rightNode.decorators && rightNode.decorators.length || (leftNode.type === "Identifier" || isStringLiteral$1(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral$1(rightNode) || isMemberExpressionChain$1(rightNode)) && // do not put values on a separate line from the key in json
29934 options.parser !== "json" && options.parser !== "json5" || rightNode.type === "SequenceExpression";
29937 return group$b(indent$7(concat$d([line$9, printedRight])));
29940 return concat$d([" ", printedRight]);
29943 function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) {
29945 return printedLeft;
29948 const printed = printAssignmentRight(leftNode, rightNode, printedRight, options);
29949 return group$b(concat$d([printedLeft, operator, printed]));
29952 function adjustClause(node, clause, forceSpace) {
29953 if (node.type === "EmptyStatement") {
29957 if (node.type === "BlockStatement" || forceSpace) {
29958 return concat$d([" ", clause]);
29961 return indent$7(concat$d([line$9, clause]));
29964 function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) {
29965 const raw = rawText$1(node);
29966 const isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral";
29967 return printString$2(raw, options, isDirectiveLiteral);
29970 function printRegex(node) {
29971 const flags = node.flags.split("").sort().join("");
29972 return "/".concat(node.pattern, "/").concat(flags);
29975 function exprNeedsASIProtection(path, options) {
29976 const node = path.getValue();
29977 const maybeASIProblem = needsParens_1(path, options) || node.type === "ParenthesizedExpression" || node.type === "TypeCastExpression" || node.type === "ArrowFunctionExpression" && !shouldPrintParamsWithoutParens(path, options) || node.type === "ArrayExpression" || node.type === "ArrayPattern" || node.type === "UnaryExpression" && node.prefix && (node.operator === "+" || node.operator === "-") || node.type === "TemplateLiteral" || node.type === "TemplateElement" || isJSXNode$1(node) || node.type === "BindExpression" && !node.object || node.type === "RegExpLiteral" || node.type === "Literal" && node.pattern || node.type === "Literal" && node.regex;
29979 if (maybeASIProblem) {
29983 if (!hasNakedLeftSide$2(node)) {
29987 return path.call(childPath => exprNeedsASIProtection(childPath, options), ...getLeftSidePathName$2(path, node));
29990 function stmtNeedsASIProtection(path, options) {
29991 const node = path.getNode();
29993 if (node.type !== "ExpressionStatement") {
29997 return path.call(childPath => exprNeedsASIProtection(childPath, options), "expression");
30000 function shouldHugType(node) {
30001 if (isSimpleFlowType$1(node) || isObjectType$1(node)) {
30005 if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") {
30006 const voidCount = node.types.filter(n => n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword").length;
30007 const hasObject = node.types.some(n => n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}>
30008 n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference");
30010 if (node.types.length - 1 === voidCount && hasObject) {
30018 function shouldHugArguments(fun) {
30019 if (!fun || fun.rest) {
30023 const params = fun.params || fun.parameters;
30025 if (!params || params.length !== 1) {
30029 const param = params[0];
30030 return !param.comments && (param.type === "ObjectPattern" || param.type === "ArrayPattern" || param.type === "Identifier" && param.typeAnnotation && (param.typeAnnotation.type === "TypeAnnotation" || param.typeAnnotation.type === "TSTypeAnnotation") && isObjectType$1(param.typeAnnotation.typeAnnotation) || param.type === "FunctionTypeParam" && isObjectType$1(param.typeAnnotation) || param.type === "AssignmentPattern" && (param.left.type === "ObjectPattern" || param.left.type === "ArrayPattern") && (param.right.type === "Identifier" || param.right.type === "ObjectExpression" && param.right.properties.length === 0 || param.right.type === "ArrayExpression" && param.right.elements.length === 0));
30033 function printArrayItems(path, options, printPath, print) {
30034 const printedElements = [];
30035 let separatorParts = [];
30036 path.each(childPath => {
30037 printedElements.push(concat$d(separatorParts));
30038 printedElements.push(group$b(print(childPath)));
30039 separatorParts = [",", line$9];
30041 if (childPath.getValue() && isNextLineEmpty$4(options.originalText, childPath.getValue(), options.locEnd)) {
30042 separatorParts.push(softline$6);
30045 return concat$d(printedElements);
30048 function printReturnAndThrowArgument(path, options, print) {
30049 const node = path.getValue();
30050 const semi = options.semi ? ";" : "";
30053 if (node.argument) {
30054 if (returnArgumentHasLeadingComment$1(options, node.argument)) {
30055 parts.push(concat$d([" (", indent$7(concat$d([hardline$9, path.call(print, "argument")])), hardline$9, ")"]));
30056 } else if (isBinaryish$1(node.argument) || node.argument.type === "SequenceExpression") {
30057 parts.push(group$b(concat$d([ifBreak$6(" (", " "), indent$7(concat$d([softline$6, path.call(print, "argument")])), softline$6, ifBreak$6(")")])));
30059 parts.push(" ", path.call(print, "argument"));
30063 const lastComment = Array.isArray(node.comments) && node.comments[node.comments.length - 1];
30064 const isLastCommentLine = lastComment && (lastComment.type === "CommentLine" || lastComment.type === "Line");
30066 if (isLastCommentLine) {
30070 if (hasDanglingComments$1(node)) {
30071 parts.push(" ", comments.printDanglingComments(path, options,
30076 if (!isLastCommentLine) {
30080 return concat$d(parts);
30083 function willPrintOwnComments(path
30086 const node = path.getValue();
30087 const parent = path.getParentNode();
30088 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$4(path) || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType");
30091 function canAttachComment$1(node) {
30092 return node.type && node.type !== "CommentBlock" && node.type !== "CommentLine" && node.type !== "Line" && node.type !== "Block" && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import";
30095 function printComment$2(commentPath, options) {
30096 const comment = commentPath.getValue();
30098 switch (comment.type) {
30099 case "CommentBlock":
30102 if (isIndentableBlockComment(comment)) {
30103 const printed = printIndentableBlockComment(comment); // We need to prevent an edge case of a previous trailing comment
30104 // printed as a `lineSuffix` which causes the comments to be
30105 // interleaved. See https://github.com/prettier/prettier/issues/4412
30107 if (comment.trailing && !hasNewline$5(options.originalText, options.locStart(comment), {
30110 return concat$d([hardline$9, printed]);
30116 const commentEnd = options.locEnd(comment);
30117 const isInsideFlowComment = options.originalText.slice(commentEnd - 3, commentEnd) === "*-/";
30118 return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/");
30121 case "CommentLine":
30123 // Print shebangs with the proper comment characters
30124 if (options.originalText.slice(options.locStart(comment)).startsWith("#!")) {
30125 return "#!" + comment.value.trimEnd();
30128 return "//" + comment.value.trimEnd();
30131 throw new Error("Not a comment: " + JSON.stringify(comment));
30135 function isIndentableBlockComment(comment) {
30136 // If the comment has multiple lines and every line starts with a star
30137 // we can fix the indentation of each line. The stars in the `/*` and
30138 // `*/` delimiters are not included in the comment value, so add them
30140 const lines = "*".concat(comment.value, "*").split("\n");
30141 return lines.length > 1 && lines.every(line => line.trim()[0] === "*");
30144 function printIndentableBlockComment(comment) {
30145 const lines = comment.value.split("\n");
30146 return concat$d(["/*", join$9(hardline$9, lines.map((line, index) => index === 0 ? line.trimEnd() : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()))), "*/"]);
30149 var printerEstree = {
30150 preprocess: preprocess_1$1,
30151 print: genericPrint$3,
30153 insertPragma: insertPragma$7,
30154 massageAstNode: clean_1$1,
30155 hasPrettierIgnore: hasPrettierIgnore$5,
30156 willPrintOwnComments,
30157 canAttachComment: canAttachComment$1,
30158 printComment: printComment$2,
30159 isBlockComment: comments$1.isBlockComment,
30161 ownLine: comments$1.handleOwnLineComment,
30162 endOfLine: comments$1.handleEndOfLineComment,
30163 remaining: comments$1.handleRemainingComment
30165 getGapRegex: comments$1.getGapRegex,
30166 getCommentChildNodes: comments$1.getCommentChildNodes
30171 hardline: hardline$a,
30174 } = document.builders;
30176 function genericPrint$4(path, options, print) {
30177 const node = path.getValue();
30179 switch (node.type) {
30181 return concat$e([path.call(print, "node"), hardline$a]);
30183 case "ArrayExpression":
30184 return node.elements.length === 0 ? "[]" : concat$e(["[", indent$8(concat$e([hardline$a, join$a(concat$e([",", hardline$a]), path.map(print, "elements"))])), hardline$a, "]"]);
30186 case "ObjectExpression":
30187 return node.properties.length === 0 ? "{}" : concat$e(["{", indent$8(concat$e([hardline$a, join$a(concat$e([",", hardline$a]), path.map(print, "properties"))])), hardline$a, "}"]);
30189 case "ObjectProperty":
30190 return concat$e([path.call(print, "key"), ": ", path.call(print, "value")]);
30192 case "UnaryExpression":
30193 return concat$e([node.operator === "+" ? "" : node.operator, path.call(print, "argument")]);
30195 case "NullLiteral":
30198 case "BooleanLiteral":
30199 return node.value ? "true" : "false";
30201 case "StringLiteral":
30202 case "NumericLiteral":
30203 return JSON.stringify(node.value);
30206 return JSON.stringify(node.name);
30209 /* istanbul ignore next */
30210 throw new Error("unknown type: " + JSON.stringify(node.type));
30214 function clean$5(node, newNode
30217 delete newNode.start;
30218 delete newNode.end;
30219 delete newNode.extra;
30220 delete newNode.loc;
30221 delete newNode.comments;
30222 delete newNode.errors;
30224 if (node.type === "Identifier") {
30226 type: "StringLiteral",
30231 if (node.type === "UnaryExpression" && node.operator === "+") {
30232 return newNode.argument;
30236 var printerEstreeJson = {
30237 preprocess: preprocess_1$1,
30238 print: genericPrint$4,
30239 massageAstNode: clean$5
30242 const CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
30247 category: CATEGORY_JAVASCRIPT,
30256 description: "Include parentheses around a sole arrow function parameter.",
30259 description: "Always include parens. Example: `(x) => x`"
30262 description: "Omit parens when possible. Example: `x => x`"
30265 bracketSpacing: commonOptions.bracketSpacing,
30266 jsxBracketSameLine: {
30268 category: CATEGORY_JAVASCRIPT,
30271 description: "Put > on the last line instead of at a new line."
30275 category: CATEGORY_JAVASCRIPT,
30278 description: "Print semicolons.",
30279 oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them."
30281 singleQuote: commonOptions.singleQuote,
30284 category: CATEGORY_JAVASCRIPT,
30287 description: "Use single quotes in JSX."
30291 category: CATEGORY_JAVASCRIPT,
30293 default: "as-needed",
30294 description: "Change when properties in objects are quoted.",
30296 value: "as-needed",
30297 description: "Only add quotes around object properties where required."
30299 value: "consistent",
30300 description: "If at least one property in an object requires quotes, quote all properties."
30303 description: "Respect the input use of quotes in object properties."
30308 category: CATEGORY_JAVASCRIPT,
30320 description: "Print trailing commas wherever possible when multi-line.",
30323 description: "Trailing commas where valid in ES5 (objects, arrays, etc.)"
30326 description: "No trailing commas."
30329 description: "Trailing commas wherever possible (including function arguments)."
30334 var name$9 = "JavaScript";
30335 var type$8 = "programming";
30336 var tmScope$8 = "source.js";
30337 var aceMode$8 = "javascript";
30338 var codemirrorMode$4 = "javascript";
30339 var codemirrorMimeType$4 = "text/javascript";
30340 var color$3 = "#f1e05a";
30345 var extensions$8 = [
30371 var interpreters = [
30382 var languageId$8 = 183;
30386 tmScope: tmScope$8,
30387 aceMode: aceMode$8,
30388 codemirrorMode: codemirrorMode$4,
30389 codemirrorMimeType: codemirrorMimeType$4,
30391 aliases: aliases$2,
30392 extensions: extensions$8,
30393 filenames: filenames,
30394 interpreters: interpreters,
30395 languageId: languageId$8
30398 var JavaScript$1 = /*#__PURE__*/Object.freeze({
30402 tmScope: tmScope$8,
30403 aceMode: aceMode$8,
30404 codemirrorMode: codemirrorMode$4,
30405 codemirrorMimeType: codemirrorMimeType$4,
30407 aliases: aliases$2,
30408 extensions: extensions$8,
30409 filenames: filenames,
30410 interpreters: interpreters,
30411 languageId: languageId$8,
30412 'default': JavaScript
30415 var name$a = "JSX";
30416 var type$9 = "programming";
30417 var group$c = "JavaScript";
30418 var extensions$9 = [
30421 var tmScope$9 = "source.js.jsx";
30422 var aceMode$9 = "javascript";
30423 var codemirrorMode$5 = "jsx";
30424 var codemirrorMimeType$5 = "text/jsx";
30425 var languageId$9 = 178;
30430 extensions: extensions$9,
30431 tmScope: tmScope$9,
30432 aceMode: aceMode$9,
30433 codemirrorMode: codemirrorMode$5,
30434 codemirrorMimeType: codemirrorMimeType$5,
30435 languageId: languageId$9
30438 var JSX$1 = /*#__PURE__*/Object.freeze({
30443 extensions: extensions$9,
30444 tmScope: tmScope$9,
30445 aceMode: aceMode$9,
30446 codemirrorMode: codemirrorMode$5,
30447 codemirrorMimeType: codemirrorMimeType$5,
30448 languageId: languageId$9,
30452 var name$b = "TypeScript";
30453 var type$a = "programming";
30454 var color$4 = "#2b7489";
30458 var interpreters$1 = [
30462 var extensions$a = [
30465 var tmScope$a = "source.ts";
30466 var aceMode$a = "typescript";
30467 var codemirrorMode$6 = "javascript";
30468 var codemirrorMimeType$6 = "application/typescript";
30469 var languageId$a = 378;
30474 aliases: aliases$3,
30475 interpreters: interpreters$1,
30476 extensions: extensions$a,
30477 tmScope: tmScope$a,
30478 aceMode: aceMode$a,
30479 codemirrorMode: codemirrorMode$6,
30480 codemirrorMimeType: codemirrorMimeType$6,
30481 languageId: languageId$a
30484 var TypeScript$1 = /*#__PURE__*/Object.freeze({
30489 aliases: aliases$3,
30490 interpreters: interpreters$1,
30491 extensions: extensions$a,
30492 tmScope: tmScope$a,
30493 aceMode: aceMode$a,
30494 codemirrorMode: codemirrorMode$6,
30495 codemirrorMimeType: codemirrorMimeType$6,
30496 languageId: languageId$a,
30497 'default': TypeScript
30500 var name$c = "TSX";
30501 var type$b = "programming";
30502 var group$d = "TypeScript";
30503 var extensions$b = [
30506 var tmScope$b = "source.tsx";
30507 var aceMode$b = "javascript";
30508 var codemirrorMode$7 = "jsx";
30509 var codemirrorMimeType$7 = "text/jsx";
30510 var languageId$b = 94901924;
30515 extensions: extensions$b,
30516 tmScope: tmScope$b,
30517 aceMode: aceMode$b,
30518 codemirrorMode: codemirrorMode$7,
30519 codemirrorMimeType: codemirrorMimeType$7,
30520 languageId: languageId$b
30523 var TSX$1 = /*#__PURE__*/Object.freeze({
30528 extensions: extensions$b,
30529 tmScope: tmScope$b,
30530 aceMode: aceMode$b,
30531 codemirrorMode: codemirrorMode$7,
30532 codemirrorMimeType: codemirrorMimeType$7,
30533 languageId: languageId$b,
30537 var name$d = "JSON";
30538 var type$c = "data";
30539 var tmScope$c = "source.json";
30540 var aceMode$c = "json";
30541 var codemirrorMode$8 = "javascript";
30542 var codemirrorMimeType$8 = "application/json";
30543 var searchable = false;
30544 var extensions$c = [
30551 ".JSON-tmLanguage",
30562 var filenames$1 = [
30571 var languageId$c = 174;
30575 tmScope: tmScope$c,
30576 aceMode: aceMode$c,
30577 codemirrorMode: codemirrorMode$8,
30578 codemirrorMimeType: codemirrorMimeType$8,
30579 searchable: searchable,
30580 extensions: extensions$c,
30581 filenames: filenames$1,
30582 languageId: languageId$c
30585 var _JSON$1 = /*#__PURE__*/Object.freeze({
30589 tmScope: tmScope$c,
30590 aceMode: aceMode$c,
30591 codemirrorMode: codemirrorMode$8,
30592 codemirrorMimeType: codemirrorMimeType$8,
30593 searchable: searchable,
30594 extensions: extensions$c,
30595 filenames: filenames$1,
30596 languageId: languageId$c,
30600 var name$e = "JSON with Comments";
30601 var type$d = "data";
30602 var group$e = "JSON";
30603 var tmScope$d = "source.js";
30604 var aceMode$d = "javascript";
30605 var codemirrorMode$9 = "javascript";
30606 var codemirrorMimeType$9 = "text/javascript";
30610 var extensions$d = [
30613 ".sublime-commands",
30614 ".sublime-completions",
30618 ".sublime-mousemap",
30619 ".sublime-project",
30620 ".sublime-settings",
30622 ".sublime-workspace",
30623 ".sublime_metrics",
30626 var filenames$2 = [
30633 "language-configuration.json",
30636 var languageId$d = 423;
30637 var JSON_with_Comments = {
30641 tmScope: tmScope$d,
30642 aceMode: aceMode$d,
30643 codemirrorMode: codemirrorMode$9,
30644 codemirrorMimeType: codemirrorMimeType$9,
30645 aliases: aliases$4,
30646 extensions: extensions$d,
30647 filenames: filenames$2,
30648 languageId: languageId$d
30651 var JSON_with_Comments$1 = /*#__PURE__*/Object.freeze({
30656 tmScope: tmScope$d,
30657 aceMode: aceMode$d,
30658 codemirrorMode: codemirrorMode$9,
30659 codemirrorMimeType: codemirrorMimeType$9,
30660 aliases: aliases$4,
30661 extensions: extensions$d,
30662 filenames: filenames$2,
30663 languageId: languageId$d,
30664 'default': JSON_with_Comments
30667 var name$f = "JSON5";
30668 var type$e = "data";
30669 var extensions$e = [
30672 var tmScope$e = "source.js";
30673 var aceMode$e = "javascript";
30674 var codemirrorMode$a = "javascript";
30675 var codemirrorMimeType$a = "application/json";
30676 var languageId$e = 175;
30680 extensions: extensions$e,
30681 tmScope: tmScope$e,
30682 aceMode: aceMode$e,
30683 codemirrorMode: codemirrorMode$a,
30684 codemirrorMimeType: codemirrorMimeType$a,
30685 languageId: languageId$e
30688 var JSON5$1 = /*#__PURE__*/Object.freeze({
30692 extensions: extensions$e,
30693 tmScope: tmScope$e,
30694 aceMode: aceMode$e,
30695 codemirrorMode: codemirrorMode$a,
30696 codemirrorMimeType: codemirrorMimeType$a,
30697 languageId: languageId$e,
30701 var require$$0$6 = getCjsExportFromNamespace(JavaScript$1);
30703 var require$$1$2 = getCjsExportFromNamespace(JSX$1);
30705 var require$$2$1 = getCjsExportFromNamespace(TypeScript$1);
30707 var require$$3$1 = getCjsExportFromNamespace(TSX$1);
30709 var require$$4 = getCjsExportFromNamespace(_JSON$1);
30711 var require$$5 = getCjsExportFromNamespace(JSON_with_Comments$1);
30713 var require$$6 = getCjsExportFromNamespace(JSON5$1);
30715 const languages$4 = [createLanguage(require$$0$6, data => ({
30717 parsers: ["babel", "flow"],
30718 vscodeLanguageIds: ["javascript", "mongo"],
30719 interpreters: data.interpreters.concat(["nodejs"])
30720 })), createLanguage(require$$0$6, () => ({
30723 parsers: ["babel", "flow"],
30724 vscodeLanguageIds: ["javascript"],
30727 extensions: [".js.flow"]
30728 })), createLanguage(require$$1$2, () => ({
30730 parsers: ["babel", "flow"],
30731 vscodeLanguageIds: ["javascriptreact"]
30732 })), createLanguage(require$$2$1, () => ({
30734 parsers: ["typescript", "babel-ts"],
30735 vscodeLanguageIds: ["typescript"]
30736 })), createLanguage(require$$3$1, () => ({
30738 parsers: ["typescript", "babel-ts"],
30739 vscodeLanguageIds: ["typescriptreact"]
30740 })), createLanguage(require$$4, () => ({
30741 name: "JSON.stringify",
30743 parsers: ["json-stringify"],
30744 vscodeLanguageIds: ["json"],
30746 // .json file defaults to json instead of json-stringify
30747 filenames: ["package.json", "package-lock.json", "composer.json"]
30748 })), createLanguage(require$$4, data => ({
30751 vscodeLanguageIds: ["json"],
30752 filenames: data.filenames.concat([".prettierrc"])
30753 })), createLanguage(require$$5, data => ({
30756 vscodeLanguageIds: ["jsonc"],
30757 filenames: data.filenames.concat([".eslintrc"])
30758 })), createLanguage(require$$6, () => ({
30760 parsers: ["json5"],
30761 vscodeLanguageIds: ["json5"]
30763 const printers$4 = {
30764 estree: printerEstree,
30765 "estree-json": printerEstreeJson
30768 languages: languages$4,
30769 options: options$5,
30770 printers: printers$4
30774 "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]",
30775 "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]",
30776 "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]"
30787 const INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"];
30788 const INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]);
30789 const kRegex = new RegExp(kPattern);
30790 const punctuationRegex = new RegExp(punctuationPattern);
30792 * split text into whitespaces and words
30793 * @param {string} text
30794 * @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>}
30797 function splitText(text, options) {
30798 const KIND_NON_CJK = "non-cjk";
30799 const KIND_CJ_LETTER = "cj-letter";
30800 const KIND_K_LETTER = "k-letter";
30801 const KIND_CJK_PUNCTUATION = "cjk-punctuation";
30803 (options.proseWrap === "preserve" ? text : text.replace(new RegExp("(".concat(cjkPattern, ")\n(").concat(cjkPattern, ")"), "g"), "$1$2")).split(/([ \t\n]+)/).forEach((token, index, tokens) => {
30805 if (index % 2 === 1) {
30807 type: "whitespace",
30808 value: /\n/.test(token) ? "\n" : " "
30811 } // word separated by whitespace
30814 if ((index === 0 || index === tokens.length - 1) && token === "") {
30818 token.split(new RegExp("(".concat(cjkPattern, ")"))).forEach((innerToken, innerIndex, innerTokens) => {
30819 if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") {
30824 if (innerIndex % 2 === 0) {
30825 if (innerToken !== "") {
30829 kind: KIND_NON_CJK,
30830 hasLeadingPunctuation: punctuationRegex.test(innerToken[0]),
30831 hasTrailingPunctuation: punctuationRegex.test(getLast$4(innerToken))
30839 appendNode(punctuationRegex.test(innerToken) ? {
30842 kind: KIND_CJK_PUNCTUATION,
30843 hasLeadingPunctuation: true,
30844 hasTrailingPunctuation: true
30848 kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER,
30849 hasLeadingPunctuation: false,
30850 hasTrailingPunctuation: false
30856 function appendNode(node) {
30857 const lastNode = getLast$4(nodes);
30859 if (lastNode && lastNode.type === "word") {
30860 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) {
30862 type: "whitespace",
30865 } else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace
30866 ![lastNode.value, node.value].some(value => /\u3000/.test(value))) {
30868 type: "whitespace",
30876 function isBetween(kind1, kind2) {
30877 return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1;
30882 function getOrderedListItemInfo(orderListItem, originalText) {
30883 const [, numberText, marker, leadingSpaces] = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/);
30891 function hasGitDiffFriendlyOrderedList(node, options) {
30892 if (!node.ordered) {
30896 if (node.children.length < 2) {
30900 const firstNumber = Number(getOrderedListItemInfo(node.children[0], options.originalText).numberText);
30901 const secondNumber = Number(getOrderedListItemInfo(node.children[1], options.originalText).numberText);
30903 if (firstNumber === 0 && node.children.length > 2) {
30904 const thirdNumber = Number(getOrderedListItemInfo(node.children[2], options.originalText).numberText);
30905 return secondNumber === 1 && thirdNumber === 1;
30908 return secondNumber === 1;
30909 } // workaround for https://github.com/remarkjs/remark/issues/351
30910 // leading and trailing newlines are stripped by remark
30913 function getFencedCodeBlockValue(node, originalText) {
30914 const text = originalText.slice(node.position.start.offset, node.position.end.offset);
30915 const leadingSpaceCount = text.match(/^\s*/)[0].length;
30916 const replaceRegex = new RegExp("^\\s{0,".concat(leadingSpaceCount, "}"));
30917 const lineContents = text.split("\n");
30918 const markerStyle = text[leadingSpaceCount]; // ` or ~
30920 const marker = text.slice(leadingSpaceCount).match(new RegExp("^[".concat(markerStyle, "]+")))[0]; // https://spec.commonmark.org/0.28/#example-104: Closing fences may be indented by 0-3 spaces
30921 // https://spec.commonmark.org/0.28/#example-93: The closing code fence must be at least as long as the opening fence
30923 const hasEndMarker = new RegExp("^\\s{0,3}".concat(marker)).test(lineContents[lineContents.length - 1].slice(getIndent(lineContents.length - 1)));
30924 return lineContents.slice(1, hasEndMarker ? -1 : undefined).map((x, i) => x.slice(getIndent(i + 1)).replace(replaceRegex, "")).join("\n");
30926 function getIndent(lineIndex) {
30927 return node.position.indent[lineIndex - 1] - 1;
30931 function mapAst(ast, handler) {
30932 return function preorder(node, index, parentStack) {
30933 parentStack = parentStack || [];
30934 const newNode = Object.assign({}, handler(node, index, parentStack));
30936 if (newNode.children) {
30937 newNode.children = newNode.children.map((child, index) => {
30938 return preorder(child, index, [newNode].concat(parentStack));
30943 }(ast, null, null);
30949 punctuationPattern,
30950 getFencedCodeBlockValue,
30951 getOrderedListItemInfo,
30952 hasGitDiffFriendlyOrderedList,
30954 INLINE_NODE_WRAPPER_TYPES
30959 hardline: hardline$b,
30960 literalline: literalline$5,
30962 markAsRoot: markAsRoot$3
30969 getFencedCodeBlockValue: getFencedCodeBlockValue$1
30972 function embed$4(path, print, textToDoc, options) {
30973 const node = path.getValue();
30975 if (node.type === "code" && node.lang !== null) {
30976 // only look for the first string so as to support [markdown-preview-enhanced](https://shd101wyy.github.io/markdown-preview-enhanced/#/code-chunk)
30977 const langMatch = node.lang.match(/^[A-Za-z0-9_-]+/);
30978 const lang = langMatch ? langMatch[0] : "";
30979 const parser = getParserName(lang);
30982 const styleUnit = options.__inJsTemplate ? "~" : "`";
30983 const style = styleUnit.repeat(Math.max(3, util$1.getMaxContinuousCount(node.value, styleUnit) + 1));
30984 const doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), {
30987 return markAsRoot$3(concat$f([style, node.lang, hardline$b, replaceNewlinesWithLiterallines(doc), style]));
30991 if (node.type === "yaml") {
30992 return markAsRoot$3(concat$f(["---", hardline$b, node.value && node.value.trim() ? replaceNewlinesWithLiterallines(textToDoc(node.value, {
30994 })) : "", "---"]));
30998 switch (node.type) {
30999 case "importExport":
31000 return textToDoc(node.value, {
31005 return textToDoc("<$>".concat(node.value, "</$>"), {
31006 parser: "__js_expression",
31013 function getParserName(lang) {
31014 const supportInfo = support.getSupportInfo({
31015 plugins: options.plugins
31017 const language = supportInfo.languages.find(language => language.name.toLowerCase() === lang || language.aliases && language.aliases.includes(lang) || language.extensions && language.extensions.find(ext => ext === ".".concat(lang)));
31020 return language.parsers[0];
31026 function replaceNewlinesWithLiterallines(doc) {
31027 return mapDoc$4(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$f(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$5)) : currentDoc);
31031 var embed_1$2 = embed$4;
31033 const pragmas = ["format", "prettier"];
31035 function startWithPragma(text) {
31036 const pragma = "@(".concat(pragmas.join("|"), ")");
31037 const regex = new RegExp(["<!--\\s*".concat(pragma, "\\s*-->"), "<!--.*\r?\n[\\s\\S]*(^|\n)[^\\S\n]*".concat(pragma, "[^\\S\n]*($|\n)[\\s\\S]*\n.*-->")].join("|"), "m");
31038 const matched = text.match(regex);
31039 return matched && matched.index === 0;
31044 hasPragma: text => startWithPragma(frontMatter(text).content.trimStart()),
31045 insertPragma: text => {
31046 const extracted = frontMatter(text);
31047 const pragma = "<!-- @".concat(pragmas[0], " -->");
31048 return extracted.frontMatter ? "".concat(extracted.frontMatter.raw, "\n\n").concat(pragma, "\n\n").concat(extracted.content) : "".concat(pragma, "\n\n").concat(extracted.content);
31053 getOrderedListItemInfo: getOrderedListItemInfo$1,
31055 splitText: splitText$1
31056 } = utils$6; // 0x0 ~ 0x10ffff
31057 // eslint-disable-next-line no-control-regex
31059 const isSingleCharRegex = /^([\u0000-\uffff]|[\ud800-\udbff][\udc00-\udfff])$/;
31061 function preprocess$2(ast, options) {
31062 ast = restoreUnescapedCharacter(ast, options);
31063 ast = mergeContinuousTexts(ast);
31064 ast = transformInlineCode(ast);
31065 ast = transformIndentedCodeblockAndMarkItsParentList(ast, options);
31066 ast = markAlignedList(ast, options);
31067 ast = splitTextIntoSentences(ast, options);
31068 ast = transformImportExport(ast);
31069 ast = mergeContinuousImportExport(ast);
31073 function transformImportExport(ast) {
31074 return mapAst$1(ast, node => {
31075 if (node.type !== "import" && node.type !== "export") {
31079 return Object.assign({}, node, {
31080 type: "importExport"
31085 function transformInlineCode(ast) {
31086 return mapAst$1(ast, node => {
31087 if (node.type !== "inlineCode") {
31091 return Object.assign({}, node, {
31092 value: node.value.replace(/\s+/g, " ")
31097 function restoreUnescapedCharacter(ast, options) {
31098 return mapAst$1(ast, node => {
31099 return node.type !== "text" ? node : Object.assign({}, node, {
31100 value: node.value !== "*" && node.value !== "_" && node.value !== "$" && // handle these cases in printer
31101 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
31106 function mergeContinuousImportExport(ast) {
31107 return mergeChildren(ast, (prevNode, node) => prevNode.type === "importExport" && node.type === "importExport", (prevNode, node) => ({
31108 type: "importExport",
31109 value: prevNode.value + "\n\n" + node.value,
31111 start: prevNode.position.start,
31112 end: node.position.end
31117 function mergeChildren(ast, shouldMerge, mergeNode) {
31118 return mapAst$1(ast, node => {
31119 if (!node.children) {
31123 const children = node.children.reduce((current, child) => {
31124 const lastChild = current[current.length - 1];
31126 if (lastChild && shouldMerge(lastChild, child)) {
31127 current.splice(-1, 1, mergeNode(lastChild, child));
31129 current.push(child);
31134 return Object.assign({}, node, {
31140 function mergeContinuousTexts(ast) {
31141 return mergeChildren(ast, (prevNode, node) => prevNode.type === "text" && node.type === "text", (prevNode, node) => ({
31143 value: prevNode.value + node.value,
31145 start: prevNode.position.start,
31146 end: node.position.end
31151 function splitTextIntoSentences(ast, options) {
31152 return mapAst$1(ast, (node, index, [parentNode]) => {
31153 if (node.type !== "text") {
31161 if (parentNode.type === "paragraph") {
31163 value = value.trimStart();
31166 if (index === parentNode.children.length - 1) {
31167 value = value.trimEnd();
31173 position: node.position,
31174 children: splitText$1(value, options)
31179 function transformIndentedCodeblockAndMarkItsParentList(ast, options) {
31180 return mapAst$1(ast, (node, index, parentStack) => {
31181 if (node.type === "code") {
31182 // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it
31183 const isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset));
31184 node.isIndented = isIndented;
31187 for (let i = 0; i < parentStack.length; i++) {
31188 const parent = parentStack[i]; // no need to check checked items
31190 if (parent.hasIndentedCodeblock) {
31194 if (parent.type === "list") {
31195 parent.hasIndentedCodeblock = true;
31205 function markAlignedList(ast, options) {
31206 return mapAst$1(ast, (node, index, parentStack) => {
31207 if (node.type === "list" && node.children.length !== 0) {
31208 // if one of its parents is not aligned, it's not possible to be aligned in sub-lists
31209 for (let i = 0; i < parentStack.length; i++) {
31210 const parent = parentStack[i];
31212 if (parent.type === "list" && !parent.isAligned) {
31213 node.isAligned = false;
31218 node.isAligned = isAligned(node);
31224 function getListItemStart(listItem) {
31225 return listItem.children.length === 0 ? -1 : listItem.children[0].position.start.column - 1;
31228 function isAligned(list) {
31229 if (!list.ordered) {
31237 const [firstItem, secondItem] = list.children;
31238 const firstInfo = getOrderedListItemInfo$1(firstItem, options.originalText);
31240 if (firstInfo.leadingSpaces.length > 1) {
31250 const firstStart = getListItemStart(firstItem);
31252 if (firstStart === -1) {
31262 if (list.children.length === 1) {
31272 return firstStart % options.tabWidth === 0;
31275 const secondStart = getListItemStart(secondItem);
31277 if (firstStart !== secondStart) {
31288 if (firstStart % options.tabWidth === 0) {
31308 const secondInfo = getOrderedListItemInfo$1(secondItem, options.originalText);
31309 return secondInfo.leadingSpaces.length > 1;
31313 var preprocess_1$2 = preprocess$2;
31317 breakParent: breakParent$4,
31321 literalline: literalline$6,
31322 markAsRoot: markAsRoot$4,
31323 hardline: hardline$c,
31324 softline: softline$7,
31325 ifBreak: ifBreak$7,
31335 printDocToString: printDocToString$3
31339 getFencedCodeBlockValue: getFencedCodeBlockValue$2,
31340 hasGitDiffFriendlyOrderedList: hasGitDiffFriendlyOrderedList$1,
31341 splitText: splitText$2,
31342 punctuationPattern: punctuationPattern$1,
31343 INLINE_NODE_TYPES: INLINE_NODE_TYPES$1,
31344 INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES$1
31347 replaceEndOfLineWith: replaceEndOfLineWith$2
31349 const TRAILING_HARDLINE_NODES = ["importExport"];
31350 const SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"];
31351 const SIBLING_NODE_TYPES = ["listItem", "definition", "footnoteDefinition"];
31353 function genericPrint$5(path, options, print) {
31354 const node = path.getValue();
31356 if (shouldRemainTheSameContent(path)) {
31357 return concat$g(splitText$2(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(node => node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options)));
31360 switch (node.type) {
31362 if (node.children.length === 0) {
31366 return concat$g([normalizeDoc(printRoot(path, options, print)), !TRAILING_HARDLINE_NODES.includes(getLastDescendantNode(node).type) ? hardline$c : ""]);
31369 return printChildren$2(path, options, print, {
31370 postprocessor: fill$5
31374 return printChildren$2(path, options, print);
31377 return node.value.replace(/[*$]/g, "\\$&") // escape all `*` and `$` (math)
31378 .replace(new RegExp(["(^|".concat(punctuationPattern$1, ")(_+)"), "(_+)(".concat(punctuationPattern$1, "|$)")].join("|"), "g"), (_, text1, underscore1, underscore2, text2) => (underscore1 ? "".concat(text1).concat(underscore1) : "".concat(underscore2).concat(text2)).replace(/_/g, "\\_"));
31379 // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
31383 const parentNode = path.getParentNode();
31384 const index = parentNode.children.indexOf(node);
31385 const nextNode = parentNode.children[index + 1];
31386 const proseWrap = // leading char that may cause different syntax
31387 nextNode && /^>|^([-+*]|#{1,6}|[0-9]+[.)])$/.test(nextNode.value) ? "never" : options.proseWrap;
31388 return printLine(path, node.value, {
31395 const parentNode = path.getParentNode();
31396 const index = parentNode.children.indexOf(node);
31397 const prevNode = parentNode.children[index - 1];
31398 const nextNode = parentNode.children[index + 1];
31399 const hasPrevOrNextWord = // `1*2*3` is considered emphasis but `1_2_3` is not
31400 prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && util$1.getLast(prevNode.children).type === "word" && !util$1.getLast(prevNode.children).hasTrailingPunctuation || nextNode && nextNode.type === "sentence" && nextNode.children.length > 0 && nextNode.children[0].type === "word" && !nextNode.children[0].hasLeadingPunctuation;
31401 const style = hasPrevOrNextWord || getAncestorNode$2(path, "emphasis") ? "*" : "_";
31402 return concat$g([style, printChildren$2(path, options, print), style]);
31406 return concat$g(["**", printChildren$2(path, options, print), "**"]);
31409 return concat$g(["~~", printChildren$2(path, options, print), "~~"]);
31413 const backtickCount = util$1.getMinNotPresentContinuousCount(node.value, "`");
31414 const style = "`".repeat(backtickCount || 1);
31415 const gap = backtickCount ? " " : "";
31416 return concat$g([style, gap, node.value, gap, style]);
31420 switch (options.originalText[node.position.start.offset]) {
31423 const mailto = "mailto:";
31424 const url = // <hello@example.com> is parsed as { url: "mailto:hello@example.com" }
31425 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;
31426 return concat$g(["<", url, ">"]);
31430 return concat$g(["[", printChildren$2(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
31433 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
31437 return concat$g(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]);
31440 return concat$g(["> ", align$2("> ", printChildren$2(path, options, print))]);
31443 return concat$g(["#".repeat(node.depth) + " ", printChildren$2(path, options, print)]);
31447 if (node.isIndented) {
31448 // indented code block
31449 const alignment = " ".repeat(4);
31450 return align$2(alignment, concat$g([alignment, concat$g(replaceEndOfLineWith$2(node.value, hardline$c))]));
31451 } // fenced code block
31454 const styleUnit = options.__inJsTemplate ? "~" : "`";
31455 const style = styleUnit.repeat(Math.max(3, util$1.getMaxContinuousCount(node.value, styleUnit) + 1));
31456 return concat$g([style, node.lang || "", hardline$c, concat$g(replaceEndOfLineWith$2(getFencedCodeBlockValue$2(node, options.originalText), hardline$c)), hardline$c, style]);
31461 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
31465 const parentNode = path.getParentNode();
31466 const value = parentNode.type === "root" && util$1.getLast(parentNode.children) === node ? node.value.trimEnd() : node.value;
31467 const isHtmlComment = /^<!--[\s\S]*-->$/.test(value);
31468 return concat$g(replaceEndOfLineWith$2(value, isHtmlComment ? hardline$c : markAsRoot$4(literalline$6)));
31473 const nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode());
31474 const isGitDiffFriendlyOrderedList = hasGitDiffFriendlyOrderedList$1(node, options);
31475 return printChildren$2(path, options, print, {
31476 processor: (childPath, index) => {
31477 const prefix = getPrefix();
31478 const childNode = childPath.getValue();
31480 if (childNode.children.length === 2 && childNode.children[1].type === "html" && childNode.children[0].position.start.column !== childNode.children[1].position.start.column) {
31481 return concat$g([prefix, printListItem(childPath, options, print, prefix)]);
31484 return concat$g([prefix, align$2(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]);
31486 function getPrefix() {
31487 const rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* ";
31488 return node.isAligned ||
31489 /* workaround for https://github.com/remarkjs/remark/issues/315 */
31490 node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix;
31496 case "thematicBreak":
31498 const counter = getAncestorCounter$1(path, "list");
31500 if (counter === -1) {
31504 const nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1));
31505 return nthSiblingIndex % 2 === 0 ? "***" : "---";
31508 case "linkReference":
31509 return concat$g(["[", printChildren$2(path, options, print), "]", node.referenceType === "full" ? concat$g(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]);
31511 case "imageReference":
31512 switch (node.referenceType) {
31514 return concat$g(["![", node.alt || "", "][", node.identifier, "]"]);
31517 return concat$g(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]);
31522 const lineOrSpace = options.proseWrap === "always" ? line$a : " ";
31523 return group$f(concat$g([concat$g(["[", node.identifier, "]:"]), indent$9(concat$g([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$g([lineOrSpace, printTitle(node.title, options, false)])]))]));
31527 return concat$g(["[^", printChildren$2(path, options, print), "]"]);
31529 case "footnoteReference":
31530 return concat$g(["[^", node.identifier, "]"]);
31532 case "footnoteDefinition":
31534 const nextNode = path.getParentNode().children[path.getName() + 1];
31535 const shouldInlineFootnote = node.children.length === 1 && node.children[0].type === "paragraph" && (options.proseWrap === "never" || options.proseWrap === "preserve" && node.children[0].position.start.line === node.children[0].position.end.line);
31536 return concat$g(["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$2(path, options, print) : group$f(concat$g([align$2(" ".repeat(options.tabWidth), printChildren$2(path, options, print, {
31537 processor: (childPath, index) => {
31538 return index === 0 ? group$f(concat$g([softline$7, childPath.call(print)])) : childPath.call(print);
31540 })), nextNode && nextNode.type === "footnoteDefinition" ? softline$7 : ""]))]);
31544 return printTable(path, options, print);
31547 return printChildren$2(path, options, print);
31550 return /\s/.test(options.originalText[node.position.start.offset]) ? concat$g([" ", markAsRoot$4(literalline$6)]) : concat$g(["\\", hardline$c]);
31553 return concat$g(replaceEndOfLineWith$2(node.value, hardline$c));
31556 case "importExport":
31559 // fallback to the original text if multiparser failed
31562 return concat$g(["$$", hardline$c, node.value ? concat$g([concat$g(replaceEndOfLineWith$2(node.value, hardline$c)), hardline$c]) : "", "$$"]);
31566 // remark-math trims content but we don't want to remove whitespaces
31567 // since it's very possible that it's recognized as math accidentally
31568 return options.originalText.slice(options.locStart(node), options.locEnd(node));
31571 case "tableRow": // handled in "table"
31573 case "listItem": // handled in "list"
31576 throw new Error("Unknown markdown type ".concat(JSON.stringify(node.type)));
31580 function printListItem(path, options, print, listPrefix) {
31581 const node = path.getValue();
31582 const prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] ";
31583 return concat$g([prefix, printChildren$2(path, options, print, {
31584 processor: (childPath, index) => {
31585 if (index === 0 && childPath.getValue().type !== "list") {
31586 return align$2(" ".repeat(prefix.length), childPath.call(print));
31589 const alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block
31591 return concat$g([alignment, align$2(alignment, childPath.call(print))]);
31596 function alignListPrefix(prefix, options) {
31597 const additionalSpaces = getAdditionalSpaces();
31598 return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block
31601 function getAdditionalSpaces() {
31602 const restSpaces = prefix.length % options.tabWidth;
31603 return restSpaces === 0 ? 0 : options.tabWidth - restSpaces;
31607 function getNthListSiblingIndex(node, parentNode) {
31608 return getNthSiblingIndex(node, parentNode, siblingNode => siblingNode.ordered === node.ordered);
31611 function getNthSiblingIndex(node, parentNode, condition) {
31612 condition = condition || (() => true);
31616 for (const childNode of parentNode.children) {
31617 if (childNode.type === node.type && condition(childNode)) {
31623 if (childNode === node) {
31629 function getAncestorCounter$1(path, typeOrTypes) {
31630 const types = [].concat(typeOrTypes);
31634 while (ancestorNode = path.getParentNode(++counter)) {
31635 if (types.includes(ancestorNode.type)) {
31643 function getAncestorNode$2(path, typeOrTypes) {
31644 const counter = getAncestorCounter$1(path, typeOrTypes);
31645 return counter === -1 ? null : path.getParentNode(counter);
31648 function printLine(path, value, options) {
31649 if (options.proseWrap === "preserve" && value === "\n") {
31653 const isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES);
31654 return value !== "" ? isBreakable ? line$a : " " : isBreakable ? softline$7 : "";
31657 function printTable(path, options, print) {
31658 const hardlineWithoutBreakParent = hardline$c.parts[0];
31659 const node = path.getValue();
31660 const contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } }
31662 path.map(rowPath => {
31663 const rowContents = [];
31664 rowPath.map(cellPath => {
31665 rowContents.push(printDocToString$3(cellPath.call(print), options).formatted);
31667 contents.push(rowContents);
31668 }, "children"); // Get the width of each column
31670 const columnMaxWidths = contents.reduce((currentWidths, rowContents) => currentWidths.map((width, columnIndex) => Math.max(width, util$1.getStringWidth(rowContents[columnIndex]))), contents[0].map(() => 3) // minimum width = 3 (---, :--, :-:, --:)
31672 const alignedTable = join$b(hardlineWithoutBreakParent, [printRow(contents[0]), printSeparator(), join$b(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents)))]);
31674 if (options.proseWrap !== "never") {
31675 return concat$g([breakParent$4, alignedTable]);
31676 } // Only if the --prose-wrap never is set and it exceeds the print width.
31679 const compactTable = join$b(hardlineWithoutBreakParent, [printRow(contents[0],
31681 true), printSeparator(
31683 true), join$b(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents,
31686 return concat$g([breakParent$4, group$f(ifBreak$7(compactTable, alignedTable))]);
31688 function printSeparator(isCompact) {
31689 return concat$g(["| ", join$b(" | ", columnMaxWidths.map((width, index) => {
31690 const spaces = isCompact ? 3 : width;
31692 switch (node.align[index]) {
31694 return ":" + "-".repeat(spaces - 1);
31697 return "-".repeat(spaces - 1) + ":";
31700 return ":" + "-".repeat(spaces - 2) + ":";
31703 return "-".repeat(spaces);
31708 function printRow(rowContents, isCompact) {
31709 return concat$g(["| ", join$b(" | ", isCompact ? rowContents : rowContents.map((rowContent, columnIndex) => {
31710 switch (node.align[columnIndex]) {
31712 return alignRight(rowContent, columnMaxWidths[columnIndex]);
31715 return alignCenter(rowContent, columnMaxWidths[columnIndex]);
31718 return alignLeft(rowContent, columnMaxWidths[columnIndex]);
31723 function alignLeft(text, width) {
31724 const spaces = width - util$1.getStringWidth(text);
31725 return concat$g([text, " ".repeat(spaces)]);
31728 function alignRight(text, width) {
31729 const spaces = width - util$1.getStringWidth(text);
31730 return concat$g([" ".repeat(spaces), text]);
31733 function alignCenter(text, width) {
31734 const spaces = width - util$1.getStringWidth(text);
31735 const left = Math.floor(spaces / 2);
31736 const right = spaces - left;
31737 return concat$g([" ".repeat(left), text, " ".repeat(right)]);
31741 function printRoot(path, options, print) {
31742 /** @typedef {{ index: number, offset: number }} IgnorePosition */
31744 /** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */
31745 const ignoreRanges = [];
31746 /** @type {IgnorePosition | null} */
31748 let ignoreStart = null;
31751 } = path.getValue();
31752 children.forEach((childNode, index) => {
31753 switch (isPrettierIgnore$1(childNode)) {
31755 if (ignoreStart === null) {
31758 offset: childNode.position.end.offset
31765 if (ignoreStart !== null) {
31766 ignoreRanges.push({
31767 start: ignoreStart,
31770 offset: childNode.position.start.offset
31773 ignoreStart = null;
31779 return printChildren$2(path, options, print, {
31780 processor: (childPath, index) => {
31781 if (ignoreRanges.length !== 0) {
31782 const ignoreRange = ignoreRanges[0];
31784 if (index === ignoreRange.start.index) {
31785 return concat$g([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]);
31788 if (ignoreRange.start.index < index && index < ignoreRange.end.index) {
31792 if (index === ignoreRange.end.index) {
31793 ignoreRanges.shift();
31798 return childPath.call(print);
31803 function printChildren$2(path, options, print, events) {
31804 events = events || {};
31805 const postprocessor = events.postprocessor || concat$g;
31807 const processor = events.processor || (childPath => childPath.call(print));
31809 const node = path.getValue();
31812 path.map((childPath, index) => {
31813 const childNode = childPath.getValue();
31814 const result = processor(childPath, index);
31816 if (result !== false) {
31819 prevNode: lastChildNode,
31824 if (!shouldNotPrePrintHardline(childNode, data)) {
31825 parts.push(hardline$c);
31827 if (lastChildNode && TRAILING_HARDLINE_NODES.includes(lastChildNode.type)) {
31828 if (shouldPrePrintTripleHardline(childNode, data)) {
31829 parts.push(hardline$c);
31832 if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) {
31833 parts.push(hardline$c);
31836 if (shouldPrePrintTripleHardline(childNode, data)) {
31837 parts.push(hardline$c);
31842 parts.push(result);
31843 lastChildNode = childNode;
31846 return postprocessor(parts);
31849 function getLastDescendantNode(node) {
31850 let current = node;
31852 while (current.children && current.children.length !== 0) {
31853 current = current.children[current.children.length - 1];
31858 /** @return {false | 'next' | 'start' | 'end'} */
31861 function isPrettierIgnore$1(node) {
31862 if (node.type !== "html") {
31866 const match = node.value.match(/^<!--\s*prettier-ignore(?:-(start|end))?\s*-->$/);
31867 return match === null ? false : match[1] ? match[1] : "next";
31870 function shouldNotPrePrintHardline(node, data) {
31871 const isFirstNode = data.parts.length === 0;
31872 const isInlineNode = INLINE_NODE_TYPES$1.includes(node.type);
31873 const isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES$1.includes(data.parentNode.type);
31874 return isFirstNode || isInlineNode || isInlineHTML;
31877 function shouldPrePrintDoubleHardline(node, data) {
31878 const isSequence = (data.prevNode && data.prevNode.type) === node.type;
31879 const isSiblingNode = isSequence && SIBLING_NODE_TYPES.includes(node.type);
31880 const isInTightListItem = data.parentNode.type === "listItem" && !data.parentNode.loose;
31881 const isPrevNodeLooseListItem = data.prevNode && data.prevNode.type === "listItem" && data.prevNode.loose;
31882 const isPrevNodePrettierIgnore = isPrettierIgnore$1(data.prevNode) === "next";
31883 const isBlockHtmlWithoutBlankLineBetweenPrevHtml = node.type === "html" && data.prevNode && data.prevNode.type === "html" && data.prevNode.position.end.line + 1 === node.position.start.line;
31884 const isHtmlDirectAfterListItem = node.type === "html" && data.parentNode.type === "listItem" && data.prevNode && data.prevNode.type === "paragraph" && data.prevNode.position.end.line + 1 === node.position.start.line;
31885 return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml || isHtmlDirectAfterListItem);
31888 function shouldPrePrintTripleHardline(node, data) {
31889 const isPrevNodeList = data.prevNode && data.prevNode.type === "list";
31890 const isIndentedCode = node.type === "code" && node.isIndented;
31891 return isPrevNodeList && isIndentedCode;
31894 function shouldRemainTheSameContent(path) {
31895 const ancestorNode = getAncestorNode$2(path, ["linkReference", "imageReference"]);
31896 return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full");
31899 function normalizeDoc(doc) {
31900 return mapDoc$5(doc, currentDoc => {
31901 if (!currentDoc.parts) {
31905 if (currentDoc.type === "concat" && currentDoc.parts.length === 1) {
31906 return currentDoc.parts[0];
31909 const parts = currentDoc.parts.reduce((parts, part) => {
31910 if (part.type === "concat") {
31911 parts.push(...part.parts);
31912 } else if (part !== "") {
31918 return Object.assign({}, currentDoc, {
31919 parts: normalizeParts$2(parts)
31924 function printUrl(url, dangerousCharOrChars) {
31925 const dangerousChars = [" "].concat(dangerousCharOrChars || []);
31926 return new RegExp(dangerousChars.map(x => "\\".concat(x)).join("|")).test(url) ? "<".concat(url, ">") : url;
31929 function printTitle(title, options, printSpace) {
31930 if (printSpace == null) {
31939 return " " + printTitle(title, options, false);
31942 if (title.includes('"') && title.includes("'") && !title.includes(")")) {
31943 return "(".concat(title, ")"); // avoid escaped quotes
31944 } // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split
31947 const singleCount = title.split("'").length - 1;
31948 const doubleCount = title.split('"').length - 1;
31949 const quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"';
31950 title = title.replace(new RegExp("(".concat(quote, ")"), "g"), "\\$1");
31951 return "".concat(quote).concat(title).concat(quote);
31954 function normalizeParts$2(parts) {
31955 return parts.reduce((current, part) => {
31956 const lastPart = util$1.getLast(current);
31958 if (typeof lastPart === "string" && typeof part === "string") {
31959 current.splice(-1, 1, lastPart + part);
31961 current.push(part);
31968 function clamp(value, min, max) {
31969 return value < min ? min : value > max ? max : value;
31972 function clean$6(ast, newObj, parent) {
31973 delete newObj.position;
31974 delete newObj.raw; // front-matter
31977 if (ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") {
31978 delete newObj.value;
31981 if (ast.type === "list") {
31982 delete newObj.isAligned;
31983 } // texts can be splitted or merged
31986 if (ast.type === "text") {
31990 if (ast.type === "inlineCode") {
31991 newObj.value = ast.value.replace(/[ \t\n]+/g, " ");
31992 } // for insert pragma
31995 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$4.startWithPragma(ast.value)) {
32000 function hasPrettierIgnore$6(path) {
32001 const index = +path.getName();
32007 const prevNode = path.getParentNode().children[index - 1];
32008 return isPrettierIgnore$1(prevNode) === "next";
32011 var printerMarkdown = {
32012 preprocess: preprocess_1$2,
32013 print: genericPrint$5,
32015 massageAstNode: clean$6,
32016 hasPrettierIgnore: hasPrettierIgnore$6,
32017 insertPragma: pragma$4.insertPragma
32021 proseWrap: commonOptions.proseWrap,
32022 singleQuote: commonOptions.singleQuote
32025 var name$g = "Markdown";
32026 var type$f = "prose";
32030 var aceMode$f = "markdown";
32031 var codemirrorMode$b = "gfm";
32032 var codemirrorMimeType$b = "text/x-gfm";
32034 var extensions$f = [
32046 var filenames$3 = [
32049 var tmScope$f = "source.gfm";
32050 var languageId$f = 222;
32054 aliases: aliases$5,
32055 aceMode: aceMode$f,
32056 codemirrorMode: codemirrorMode$b,
32057 codemirrorMimeType: codemirrorMimeType$b,
32059 extensions: extensions$f,
32060 filenames: filenames$3,
32061 tmScope: tmScope$f,
32062 languageId: languageId$f
32065 var Markdown$1 = /*#__PURE__*/Object.freeze({
32069 aliases: aliases$5,
32070 aceMode: aceMode$f,
32071 codemirrorMode: codemirrorMode$b,
32072 codemirrorMimeType: codemirrorMimeType$b,
32074 extensions: extensions$f,
32075 filenames: filenames$3,
32076 tmScope: tmScope$f,
32077 languageId: languageId$f,
32078 'default': Markdown
32081 var require$$0$7 = getCjsExportFromNamespace(Markdown$1);
32083 const languages$5 = [createLanguage(require$$0$7, data => ({
32085 parsers: ["markdown"],
32086 vscodeLanguageIds: ["markdown"],
32087 filenames: data.filenames.concat(["README"]),
32088 extensions: data.extensions.filter(extension => extension !== ".mdx")
32089 })), createLanguage(require$$0$7, () => ({
32093 vscodeLanguageIds: ["mdx"],
32095 extensions: [".mdx"]
32097 const printers$5 = {
32098 mdast: printerMarkdown
32100 var languageMarkdown = {
32101 languages: languages$5,
32102 options: options$6,
32103 printers: printers$5
32106 function isPragma(text) {
32107 return /^\s*@(prettier|format)\s*$/.test(text);
32110 function hasPragma$4(text) {
32111 return /^\s*#[^\n\S]*@(prettier|format)\s*?(\n|$)/.test(text);
32114 function insertPragma$8(text) {
32115 return "# @format\n\n".concat(text);
32120 hasPragma: hasPragma$4,
32121 insertPragma: insertPragma$8
32128 function getAncestorCount(path, filter) {
32130 const pathStackLength = path.stack.length - 1;
32132 for (let i = 0; i < pathStackLength; i++) {
32133 const value = path.stack[i];
32135 if (isNode(value) && filter(value)) {
32143 * @param {any} value
32144 * @param {string[]=} types
32148 function isNode(value, types) {
32149 return value && typeof value.type === "string" && (!types || types.includes(value.type));
32152 function mapNode(node, callback, parent) {
32153 return callback("children" in node ? Object.assign({}, node, {
32154 children: node.children.map(childNode => mapNode(childNode, callback, node))
32155 }) : node, parent);
32158 function defineShortcut(x, key, getter) {
32159 Object.defineProperty(x, key, {
32165 function isNextLineEmpty$5(node, text) {
32166 let newlineCount = 0;
32167 const textLength = text.length;
32169 for (let i = node.position.end.offset - 1; i < textLength; i++) {
32170 const char = text[i];
32172 if (char === "\n") {
32176 if (newlineCount === 1 && /\S/.test(char)) {
32180 if (newlineCount === 2) {
32188 function isLastDescendantNode(path) {
32189 const node = path.getValue();
32191 switch (node.type) {
32198 const pathStackLength = path.stack.length;
32200 for (let i = 1; i < pathStackLength; i++) {
32201 const item = path.stack[i];
32202 const parentItem = path.stack[i - 1];
32204 if (Array.isArray(parentItem) && typeof item === "number" && item !== parentItem.length - 1) {
32212 function getLastDescendantNode$1(node) {
32213 return "children" in node && node.children.length !== 0 ? getLastDescendantNode$1(getLast$5(node.children)) : node;
32216 function isPrettierIgnore$2(comment) {
32217 return comment.value.trim() === "prettier-ignore";
32220 function hasPrettierIgnore$7(path) {
32221 const node = path.getValue();
32223 if (node.type === "documentBody") {
32224 const document = path.getParentNode();
32225 return hasEndComments(document.head) && isPrettierIgnore$2(getLast$5(document.head.endComments));
32228 return hasLeadingComments(node) && isPrettierIgnore$2(getLast$5(node.leadingComments));
32231 function isEmptyNode(node) {
32232 return (!node.children || node.children.length === 0) && !hasComments(node);
32235 function hasComments(node) {
32236 return hasLeadingComments(node) || hasMiddleComments(node) || hasIndicatorComment(node) || hasTrailingComment$2(node) || hasEndComments(node);
32239 function hasLeadingComments(node) {
32240 return node && node.leadingComments && node.leadingComments.length !== 0;
32243 function hasMiddleComments(node) {
32244 return node && node.middleComments && node.middleComments.length !== 0;
32247 function hasIndicatorComment(node) {
32248 return node && node.indicatorComment;
32251 function hasTrailingComment$2(node) {
32252 return node && node.trailingComment;
32255 function hasEndComments(node) {
32256 return node && node.endComments && node.endComments.length !== 0;
32259 * " a b c d e f " -> [" a b", "c d", "e f "]
32263 function splitWithSingleSpace(text) {
32265 let lastPart = undefined;
32267 for (const part of text.split(/( +)/g)) {
32268 if (part !== " ") {
32269 if (lastPart === " ") {
32272 parts.push((parts.pop() || "") + part);
32274 } else if (lastPart === undefined) {
32281 if (lastPart === " ") {
32282 parts.push((parts.pop() || "") + " ");
32285 if (parts[0] === "") {
32287 parts.unshift(" " + (parts.shift() || ""));
32293 function getFlowScalarLineContents(nodeType, content, options) {
32294 const rawLineContents = content.split("\n").map((lineContent, index, lineContents) => index === 0 && index === lineContents.length - 1 ? lineContent : index !== 0 && index !== lineContents.length - 1 ? lineContent.trim() : index === 0 ? lineContent.trimEnd() : lineContent.trimStart());
32296 if (options.proseWrap === "preserve") {
32297 return rawLineContents.map(lineContent => lineContent.length === 0 ? [] : [lineContent]);
32300 return rawLineContents.map(lineContent => lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent)).reduce((reduced, lineContentWords, index) => index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !( // trailing backslash in quoteDouble should be preserved
32301 nodeType === "quoteDouble" && getLast$5(getLast$5(reduced)).endsWith("\\")) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]), []).map(lineContentWords => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords);
32304 function getBlockValueLineContents(node, {
32309 const content = node.position.start.line === node.position.end.line ? "" : options.originalText.slice(node.position.start.offset, node.position.end.offset) // exclude open line `>` or `|`
32310 .match(/^[^\n]*?\n([\s\S]*)$/)[1];
32311 const leadingSpaceCount = node.indent === null ? (match => match ? match[1].length : Infinity)(content.match(/^( *)\S/m)) : node.indent - 1 + parentIndent;
32312 const rawLineContents = content.split("\n").map(lineContent => lineContent.slice(leadingSpaceCount));
32314 if (options.proseWrap === "preserve" || node.type === "blockLiteral") {
32315 return removeUnnecessaryTrailingNewlines(rawLineContents.map(lineContent => lineContent.length === 0 ? [] : [lineContent]));
32318 return removeUnnecessaryTrailingNewlines(rawLineContents.map(lineContent => lineContent.length === 0 ? [] : splitWithSingleSpace(lineContent)).reduce((reduced, lineContentWords, index) => index !== 0 && rawLineContents[index - 1].length !== 0 && lineContentWords.length !== 0 && !/^\s/.test(lineContentWords[0]) && !/^\s|\s$/.test(getLast$5(reduced)) ? reduced.concat([reduced.pop().concat(lineContentWords)]) : reduced.concat([lineContentWords]), []).map(lineContentWords => lineContentWords.reduce((reduced, word) => // disallow trailing spaces
32319 reduced.length !== 0 && /\s$/.test(getLast$5(reduced)) ? reduced.concat(reduced.pop() + " " + word) : reduced.concat(word), [])).map(lineContentWords => options.proseWrap === "never" ? [lineContentWords.join(" ")] : lineContentWords));
32321 function removeUnnecessaryTrailingNewlines(lineContents) {
32322 if (node.chomping === "keep") {
32323 return getLast$5(lineContents).length === 0 ? lineContents.slice(0, -1) : lineContents;
32326 let trailingNewlineCount = 0;
32328 for (let i = lineContents.length - 1; i >= 0; i--) {
32329 if (lineContents[i].length === 0) {
32330 trailingNewlineCount++;
32336 return trailingNewlineCount === 0 ? lineContents : trailingNewlineCount >= 2 && !isLastDescendant ? // next empty line
32337 lineContents.slice(0, -(trailingNewlineCount - 1)) : lineContents.slice(0, -trailingNewlineCount);
32342 getLast: getLast$5,
32348 isNextLineEmpty: isNextLineEmpty$5,
32349 isLastDescendantNode,
32350 getBlockValueLineContents,
32351 getFlowScalarLineContents,
32352 getLastDescendantNode: getLastDescendantNode$1,
32353 hasPrettierIgnore: hasPrettierIgnore$7,
32354 hasLeadingComments,
32356 hasIndicatorComment,
32357 hasTrailingComment: hasTrailingComment$2,
32362 insertPragma: insertPragma$9,
32363 isPragma: isPragma$1
32366 getAncestorCount: getAncestorCount$1,
32367 getBlockValueLineContents: getBlockValueLineContents$1,
32368 getFlowScalarLineContents: getFlowScalarLineContents$1,
32369 getLast: getLast$6,
32370 getLastDescendantNode: getLastDescendantNode$2,
32371 hasLeadingComments: hasLeadingComments$1,
32372 hasMiddleComments: hasMiddleComments$1,
32373 hasIndicatorComment: hasIndicatorComment$1,
32374 hasTrailingComment: hasTrailingComment$3,
32375 hasEndComments: hasEndComments$1,
32376 hasPrettierIgnore: hasPrettierIgnore$8,
32377 isLastDescendantNode: isLastDescendantNode$1,
32378 isNextLineEmpty: isNextLineEmpty$6,
32380 isEmptyNode: isEmptyNode$1,
32381 defineShortcut: defineShortcut$1,
32384 const docBuilders$2 = document.builders;
32386 conditionalGroup: conditionalGroup$2,
32387 breakParent: breakParent$5,
32390 dedentToRoot: dedentToRoot$3,
32393 hardline: hardline$d,
32394 ifBreak: ifBreak$8,
32397 lineSuffix: lineSuffix$2,
32398 literalline: literalline$7,
32399 markAsRoot: markAsRoot$5,
32400 softline: softline$8
32403 replaceEndOfLineWith: replaceEndOfLineWith$3
32406 function preprocess$3(ast) {
32407 return mapNode$1(ast, defineShortcuts);
32410 function defineShortcuts(node) {
32411 switch (node.type) {
32413 defineShortcut$1(node, "head", () => node.children[0]);
32414 defineShortcut$1(node, "body", () => node.children[1]);
32417 case "documentBody":
32418 case "sequenceItem":
32419 case "flowSequenceItem":
32421 case "mappingValue":
32422 defineShortcut$1(node, "content", () => node.children[0]);
32425 case "mappingItem":
32426 case "flowMappingItem":
32427 defineShortcut$1(node, "key", () => node.children[0]);
32428 defineShortcut$1(node, "value", () => node.children[1]);
32435 function genericPrint$6(path, options, print) {
32436 const node = path.getValue();
32437 const parentNode = path.getParentNode();
32438 const tag = !node.tag ? "" : path.call(print, "tag");
32439 const anchor = !node.anchor ? "" : path.call(print, "anchor");
32440 const nextEmptyLine = isNode$1(node, ["mapping", "sequence", "comment", "directive", "mappingItem", "sequenceItem"]) && !isLastDescendantNode$1(path) ? printNextEmptyLine(path, options.originalText) : "";
32441 return concat$h([node.type !== "mappingValue" && hasLeadingComments$1(node) ? concat$h([join$c(hardline$d, path.map(print, "leadingComments")), hardline$d]) : "", tag, tag && anchor ? " " : "", anchor, tag || anchor ? isNode$1(node, ["sequence", "mapping"]) && !hasMiddleComments$1(node) ? hardline$d : " " : "", hasMiddleComments$1(node) ? concat$h([node.middleComments.length === 1 ? "" : hardline$d, join$c(hardline$d, path.map(print, "middleComments")), hardline$d]) : "", hasPrettierIgnore$8(path) ? concat$h(replaceEndOfLineWith$3(options.originalText.slice(node.position.start.offset, node.position.end.offset), literalline$7)) : group$g(_print(node, parentNode, path, options, print)), hasTrailingComment$3(node) && !isNode$1(node, ["document", "documentHead"]) ? lineSuffix$2(concat$h([node.type === "mappingValue" && !node.content ? "" : " ", parentNode.type === "mappingKey" && path.getParentNode(2).type === "mapping" && isInlineNode(node) ? "" : breakParent$5, path.call(print, "trailingComment")])) : "", nextEmptyLine, hasEndComments$1(node) && !isNode$1(node, ["documentHead", "documentBody"]) ? align$3(node.type === "sequenceItem" ? 2 : 0, concat$h([hardline$d, join$c(hardline$d, path.map(print, "endComments"))])) : ""]);
32444 function _print(node, parentNode, path, options, print) {
32445 switch (node.type) {
32447 return concat$h([join$c(hardline$d, path.map((childPath, index) => {
32448 const document = node.children[index];
32449 const nextDocument = node.children[index + 1];
32450 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, "---"])]);
32451 }, "children")), node.children.length === 0 || (lastDescendantNode => isNode$1(lastDescendantNode, ["blockLiteral", "blockFolded"]) && lastDescendantNode.chomping === "keep")(getLastDescendantNode$2(node)) ? "" : hardline$d]);
32455 const nextDocument = parentNode.children[path.getName() + 1];
32456 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));
32459 case "documentHead":
32460 return join$c(hardline$d, [].concat(path.map(print, "children"), path.map(print, "endComments")));
32462 case "documentBody":
32464 const children = join$c(hardline$d, path.map(print, "children")).parts;
32465 const endComments = join$c(hardline$d, path.map(print, "endComments")).parts;
32466 const separator = children.length === 0 || endComments.length === 0 ? "" : (lastDescendantNode => isNode$1(lastDescendantNode, ["blockFolded", "blockLiteral"]) ? lastDescendantNode.chomping === "keep" ? // there's already a newline printed at the end of blockValue (chomping=keep, lastDescendant=true)
32467 "" : // an extra newline for better readability
32468 concat$h([hardline$d, hardline$d]) : hardline$d)(getLastDescendantNode$2(node));
32469 return concat$h([].concat(children, separator, endComments));
32473 return concat$h(["%", join$c(" ", [node.name].concat(node.parameters))]);
32476 return concat$h(["#", node.value]);
32479 return concat$h(["*", node.value]);
32482 return options.originalText.slice(node.position.start.offset, node.position.end.offset);
32485 return concat$h(["&", node.value]);
32488 return printFlowScalarContent(node.type, options.originalText.slice(node.position.start.offset, node.position.end.offset), options);
32490 case "quoteDouble":
32491 case "quoteSingle":
32493 const singleQuote = "'";
32494 const doubleQuote = '"';
32495 const raw = options.originalText.slice(node.position.start.offset + 1, node.position.end.offset - 1);
32497 if (node.type === "quoteSingle" && raw.includes("\\") || node.type === "quoteDouble" && /\\[^"]/.test(raw)) {
32498 // only quoteDouble can use escape chars
32499 // and quoteSingle do not need to escape backslashes
32500 const originalQuote = node.type === "quoteDouble" ? doubleQuote : singleQuote;
32501 return concat$h([originalQuote, printFlowScalarContent(node.type, raw, options), originalQuote]);
32502 } else if (raw.includes(doubleQuote)) {
32503 return concat$h([singleQuote, printFlowScalarContent(node.type, node.type === "quoteDouble" ? raw // double quote needs to be escaped by backslash in quoteDouble
32504 .replace(/\\"/g, doubleQuote).replace(/'/g, singleQuote.repeat(2)) : raw, options), singleQuote]);
32507 if (raw.includes(singleQuote)) {
32508 return concat$h([doubleQuote, printFlowScalarContent(node.type, node.type === "quoteSingle" ? // single quote needs to be escaped by 2 single quotes in quoteSingle
32509 raw.replace(/''/g, singleQuote) : raw, options), doubleQuote]);
32512 const quote = options.singleQuote ? singleQuote : doubleQuote;
32513 return concat$h([quote, printFlowScalarContent(node.type, raw, options), quote]);
32516 case "blockFolded":
32517 case "blockLiteral":
32519 const parentIndent = getAncestorCount$1(path, ancestorNode => isNode$1(ancestorNode, ["sequence", "mapping"]));
32520 const isLastDescendant = isLastDescendantNode$1(path);
32521 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, {
32525 }).reduce((reduced, lineWords, index, lineContents) => reduced.concat(index === 0 ? hardline$d : "", fill$6(join$c(line$b, lineWords).parts), index !== lineContents.length - 1 ? lineWords.length === 0 ? hardline$d : markAsRoot$5(literalline$7) : node.chomping === "keep" && isLastDescendant ? lineWords.length === 0 ? dedentToRoot$3(hardline$d) : dedentToRoot$3(literalline$7) : ""), []))))]);
32529 return join$c(hardline$d, path.map(print, "children"));
32531 case "sequenceItem":
32532 return concat$h(["- ", align$3(2, !node.content ? "" : path.call(print, "content"))]);
32535 return !node.content ? "" : path.call(print, "content");
32537 case "mappingValue":
32538 return !node.content ? "" : path.call(print, "content");
32541 return join$c(hardline$d, path.map(print, "children"));
32543 case "mappingItem":
32544 case "flowMappingItem":
32546 const isEmptyMappingKey = isEmptyNode$1(node.key);
32547 const isEmptyMappingValue = isEmptyNode$1(node.value);
32549 if (isEmptyMappingKey && isEmptyMappingValue) {
32550 return concat$h([": "]);
32553 const key = path.call(print, "key");
32554 const value = path.call(print, "value");
32556 if (isEmptyMappingValue) {
32557 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)]);
32560 if (isEmptyMappingKey) {
32561 return concat$h([": ", align$3(2, value)]);
32564 const groupId = Symbol("mappingKey");
32565 const forceExplicitKey = hasLeadingComments$1(node.value) || !isInlineNode(node.key.content);
32566 return forceExplicitKey ? concat$h(["? ", align$3(2, key), hardline$d, join$c("", path.map(print, "value", "leadingComments").map(comment => concat$h([comment, hardline$d]))), ": ", align$3(2, value)]) : // force singleline
32567 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), {
32569 })])), ifBreak$8(concat$h([hardline$d, ": ", align$3(2, value)]), indent(concat$h([needsSpaceInFrontOfMappingValue(node) ? " " : "", ":", hasLeadingComments$1(node.value.content) || hasEndComments$1(node.value) && node.value.content && !isNode$1(node.value.content, ["mapping", "sequence"]) || parentNode.type === "mapping" && hasTrailingComment$3(node.key.content) && isInlineNode(node.value.content) || isNode$1(node.value.content, ["mapping", "sequence"]) && node.value.content.tag === null && node.value.content.anchor === null ? hardline$d : !node.value.content ? "" : line$b, value])), {
32574 case "flowMapping":
32575 case "flowSequence":
32577 const openMarker = node.type === "flowMapping" ? "{" : "[";
32578 const closeMarker = node.type === "flowMapping" ? "}" : "]";
32579 const bracketSpacing = node.type === "flowMapping" && node.children.length !== 0 && options.bracketSpacing ? line$b : softline$8;
32581 const isLastItemEmptyMappingItem = node.children.length !== 0 && (lastItem => lastItem.type === "flowMappingItem" && isEmptyNode$1(lastItem.key) && isEmptyNode$1(lastItem.value))(getLast$6(node.children));
32583 return concat$h([openMarker, indent(concat$h([bracketSpacing, concat$h(path.map((childPath, index) => concat$h([print(childPath), index === node.children.length - 1 ? "" : concat$h([",", line$b, node.children[index].position.start.line !== node.children[index + 1].position.start.line ? printNextEmptyLine(childPath, options.originalText) : ""])]), "children")), ifBreak$8(",", "")])), isLastItemEmptyMappingItem ? "" : bracketSpacing, closeMarker]);
32586 case "flowSequenceItem":
32587 return path.call(print, "content");
32588 // istanbul ignore next
32591 throw new Error("Unexpected node type ".concat(node.type));
32594 function indent(doc) {
32595 return docBuilders$2.align(" ".repeat(options.tabWidth), doc);
32599 function align$3(n, doc) {
32600 return typeof n === "number" && n > 0 ? docBuilders$2.align(" ".repeat(n), doc) : docBuilders$2.align(n, doc);
32603 function isInlineNode(node) {
32608 switch (node.type) {
32610 case "quoteDouble":
32611 case "quoteSingle":
32613 case "flowMapping":
32614 case "flowSequence":
32622 function isSingleLineNode(node) {
32627 switch (node.type) {
32629 case "quoteDouble":
32630 case "quoteSingle":
32631 return node.position.start.line === node.position.end.line;
32641 function shouldPrintDocumentBody(document) {
32642 return document.body.children.length !== 0 || hasEndComments$1(document.body);
32645 function shouldPrintDocumentEndMarker(document, nextDocument) {
32648 *... # trailingComment
32650 hasTrailingComment$3(document) || nextDocument && (
32656 nextDocument.head.children.length !== 0 ||
32662 hasEndComments$1(nextDocument.head))
32666 function shouldPrintDocumentHeadEndMarker(document, nextDocument, root, options) {
32670 * preserve the first document head end marker
32672 root.children[0] === document && /---(\s|$)/.test(options.originalText.slice(options.locStart(document), options.locStart(document) + 4)) ||
32677 document.head.children.length !== 0 ||
32682 hasEndComments$1(document.head) ||
32684 * --- # trailing comment
32686 hasTrailingComment$3(document.head)) {
32690 if (shouldPrintDocumentEndMarker(document, nextDocument)) {
32694 return nextDocument ? "root" : false;
32697 function isAbsolutelyPrintedAsSingleLineNode(node, options) {
32702 switch (node.type) {
32704 case "quoteSingle":
32705 case "quoteDouble":
32715 if (options.proseWrap === "preserve") {
32716 return node.position.start.line === node.position.end.line;
32719 if ( // backslash-newline
32720 /\\$/m.test(options.originalText.slice(node.position.start.offset, node.position.end.offset))) {
32724 switch (options.proseWrap) {
32726 return !node.value.includes("\n");
32729 return !/[\n ]/.test(node.value);
32730 // istanbul ignore next
32737 function needsSpaceInFrontOfMappingValue(node) {
32738 return node.key.content && node.key.content.type === "alias";
32741 function printNextEmptyLine(path, originalText) {
32742 const node = path.getValue();
32743 const root = path.stack[0];
32744 root.isNextEmptyLinePrintedChecklist = root.isNextEmptyLinePrintedChecklist || [];
32746 if (!root.isNextEmptyLinePrintedChecklist[node.position.end.line]) {
32747 if (isNextLineEmpty$6(node, originalText)) {
32748 root.isNextEmptyLinePrintedChecklist[node.position.end.line] = true;
32756 function printFlowScalarContent(nodeType, content, options) {
32757 const lineContents = getFlowScalarLineContents$1(nodeType, content, options);
32758 return join$c(hardline$d, lineContents.map(lineContentWords => fill$6(join$c(line$b, lineContentWords).parts)));
32761 function clean$7(node, newNode
32764 if (isNode$1(newNode)) {
32765 delete newNode.position;
32767 switch (newNode.type) {
32770 if (isPragma$1(newNode.value)) {
32776 case "quoteDouble":
32777 case "quoteSingle":
32778 newNode.type = "quote";
32784 var printerYaml = {
32785 preprocess: preprocess$3,
32786 print: genericPrint$6,
32787 massageAstNode: clean$7,
32788 insertPragma: insertPragma$9
32792 bracketSpacing: commonOptions.bracketSpacing,
32793 singleQuote: commonOptions.singleQuote,
32794 proseWrap: commonOptions.proseWrap
32797 var name$h = "YAML";
32798 var type$g = "data";
32799 var tmScope$g = "source.yaml";
32803 var extensions$g = [
32811 ".yaml-tmlanguage",
32815 var filenames$4 = [
32822 var aceMode$g = "yaml";
32823 var codemirrorMode$c = "yaml";
32824 var codemirrorMimeType$c = "text/x-yaml";
32825 var languageId$g = 407;
32829 tmScope: tmScope$g,
32830 aliases: aliases$6,
32831 extensions: extensions$g,
32832 filenames: filenames$4,
32833 aceMode: aceMode$g,
32834 codemirrorMode: codemirrorMode$c,
32835 codemirrorMimeType: codemirrorMimeType$c,
32836 languageId: languageId$g
32839 var YAML$1 = /*#__PURE__*/Object.freeze({
32843 tmScope: tmScope$g,
32844 aliases: aliases$6,
32845 extensions: extensions$g,
32846 filenames: filenames$4,
32847 aceMode: aceMode$g,
32848 codemirrorMode: codemirrorMode$c,
32849 codemirrorMimeType: codemirrorMimeType$c,
32850 languageId: languageId$g,
32854 var require$$0$8 = getCjsExportFromNamespace(YAML$1);
32856 const languages$6 = [createLanguage(require$$0$8, data => ({
32859 vscodeLanguageIds: ["yaml"],
32860 // yarn.lock is not YAML: https://github.com/yarnpkg/yarn/issues/5629
32861 filenames: data.filenames.filter(filename => filename !== "yarn.lock")
32863 var languageYaml = {
32864 languages: languages$6,
32875 getSupportInfo: getSupportInfo$2
32877 const internalPlugins = [languageCss, languageGraphql, languageHandlebars, languageHtml, languageJs, languageMarkdown, languageYaml];
32879 function withPlugins(fn, optsArgIdx = 1 // Usually `opts` is the 2nd argument
32881 return (...args) => {
32882 const opts = args[optsArgIdx] || {};
32883 const plugins = opts.plugins || [];
32884 args[optsArgIdx] = Object.assign({}, opts, {
32885 plugins: [...internalPlugins, ...(Array.isArray(plugins) ? plugins : Object.values(plugins))]
32887 return fn(...args);
32891 const formatWithCursor = withPlugins(core.formatWithCursor);
32895 format(text, opts) {
32896 return formatWithCursor(text, opts).formatted;
32899 check(text, opts) {
32902 } = formatWithCursor(text, opts);
32903 return formatted === text;
32907 getSupportInfo: withPlugins(getSupportInfo$2, 0),
32908 version: version$2,
32911 parse: withPlugins(core.parse),
32912 formatAST: withPlugins(core.formatAST),
32913 formatDoc: withPlugins(core.formatDoc),
32914 printToDoc: withPlugins(core.printToDoc),
32915 printDocToString: withPlugins(core.printDocToString)
32919 var standalone$1 = standalone;
32921 return standalone$1;