4 var path = require('path');
5 var fs$2 = require('fs');
6 var readline = require('readline');
7 var os = require('os');
8 var tty = require('tty');
9 var util$2 = require('util');
10 var stream_1 = require('stream');
11 var events_1 = require('events');
13 function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
15 var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
16 var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$2);
17 var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline);
18 var os__default = /*#__PURE__*/_interopDefaultLegacy(os);
19 var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty);
20 var util__default = /*#__PURE__*/_interopDefaultLegacy(util$2);
21 var stream_1__default = /*#__PURE__*/_interopDefaultLegacy(stream_1);
22 var events_1__default = /*#__PURE__*/_interopDefaultLegacy(events_1);
24 var semverCompare = function cmp(a, b) {
25 var pa = a.split('.');
26 var pb = b.split('.');
28 for (var i = 0; i < 3; i++) {
29 var na = Number(pa[i]);
30 var nb = Number(pb[i]);
31 if (na > nb) return 1;
32 if (nb > na) return -1;
33 if (!isNaN(na) && isNaN(nb)) return 1;
34 if (isNaN(na) && !isNaN(nb)) return -1;
40 var pleaseUpgradeNode = function pleaseUpgradeNode(pkg, opts) {
41 var opts = opts || {};
42 var requiredVersion = pkg.engines.node.replace('>=', '');
43 var currentVersion = process.version.replace('v', '');
45 if (semverCompare(currentVersion, requiredVersion) === -1) {
47 console.error(opts.message(requiredVersion));
49 console.error(pkg.name + ' requires at least version ' + requiredVersion + ' of Node, please upgrade');
52 if (opts.hasOwnProperty('exitCode')) {
53 process.exit(opts.exitCode);
60 var name = "prettier";
61 var version = "2.2.1";
62 var description = "Prettier is an opinionated code formatter";
63 var bin = "./bin/prettier.js";
64 var repository = "prettier/prettier";
65 var homepage = "https://prettier.io";
66 var author = "James Long";
68 var main = "./index.js";
69 var browser = "./standalone.js";
70 var unpkg = "./standalone.js";
81 "@angular/compiler": "10.2.3",
82 "@babel/code-frame": "7.10.4",
83 "@babel/parser": "7.12.5",
84 "@glimmer/syntax": "0.66.0",
85 "@iarna/toml": "2.2.5",
86 "@typescript-eslint/typescript-estree": "4.8.1",
87 "angular-estree-parser": "2.2.1",
88 "angular-html-parser": "1.7.1",
91 "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540",
96 editorconfig: "0.15.3",
97 "editorconfig-to-prettier": "0.2.0",
98 "escape-string-regexp": "4.0.0",
101 "fast-glob": "3.2.4",
102 "fast-json-stable-stringify": "2.1.0",
103 "find-parent-dir": "0.3.0",
104 "flow-parser": "0.138.0",
105 "get-stdin": "8.0.0",
108 "html-element-attributes": "2.3.0",
109 "html-styles": "1.0.0",
110 "html-tag-names": "1.1.5",
111 "html-void-elements": "1.0.5",
113 "jest-docblock": "26.0.0",
116 "lines-and-columns": "1.1.6",
117 "linguist-languages": "7.12.1",
123 "n-readlines": "1.0.1",
125 "parse-srcset": "ikatyang/parse-srcset#54eb9c1cb21db5c62b4d0e275d7249516df6f0ee",
126 "please-upgrade-node": "3.2.0",
127 "postcss-less": "3.1.4",
128 "postcss-media-query-parser": "0.2.3",
129 "postcss-scss": "2.1.1",
130 "postcss-selector-parser": "2.2.3",
131 "postcss-values-parser": "2.0.1",
132 "regexp-util": "1.2.2",
133 "remark-footnotes": "2.0.0",
134 "remark-math": "3.0.1",
135 "remark-parse": "8.0.3",
138 "string-width": "4.2.0",
140 "unicode-regex": "3.0.0",
143 "yaml-unist-parser": "1.3.1"
145 var devDependencies = {
146 "@babel/core": "7.12.3",
147 "@babel/preset-env": "7.12.1",
148 "@babel/types": "7.12.6",
149 "@glimmer/reference": "0.66.0",
150 "@rollup/plugin-alias": "3.1.1",
151 "@rollup/plugin-babel": "5.2.1",
152 "@rollup/plugin-commonjs": "16.0.0",
153 "@rollup/plugin-json": "4.1.0",
154 "@rollup/plugin-node-resolve": "10.0.0",
155 "@rollup/plugin-replace": "2.3.4",
156 "@types/estree": "0.0.45",
157 "@types/node": "14.14.0",
158 "@typescript-eslint/types": "4.8.1",
159 "babel-jest": "26.6.3",
160 "babel-loader": "8.2.1",
162 "builtin-modules": "3.1.0",
163 "cross-env": "7.0.2",
166 "eslint-config-prettier": "6.15.0",
167 "eslint-formatter-friendly": "7.0.0",
168 "eslint-plugin-import": "2.22.1",
169 "eslint-plugin-jest": "24.1.3",
170 "eslint-plugin-prettier-internal-rules": "file:scripts/tools/eslint-plugin-prettier-internal-rules",
171 "eslint-plugin-react": "7.21.5",
172 "eslint-plugin-unicorn": "23.0.0",
175 "jest-snapshot-serializer-ansi": "1.0.0",
176 "jest-snapshot-serializer-raw": "1.1.0",
177 "jest-watch-typeahead": "0.6.1",
178 "npm-run-all": "4.1.5",
179 "path-browserify": "1.0.1",
183 "rollup-plugin-node-globals": "1.4.0",
184 "rollup-plugin-terser": "7.0.2",
186 "snapshot-diff": "0.8.1",
187 "strip-ansi": "6.0.0",
188 "synchronous-promise": "2.0.15",
190 "terser-webpack-plugin": "5.0.3",
194 prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1",
195 "prepare-release": "yarn && yarn build && yarn test:dist",
197 "test:dev-package": "cross-env INSTALL_PACKAGE=1 jest",
198 "test:dist": "cross-env NODE_ENV=production jest",
199 "test:dist-standalone": "cross-env NODE_ENV=production TEST_STANDALONE=1 jest",
200 "test:integration": "jest tests_integration",
201 "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",
202 "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",
203 "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",
204 lint: "run-p lint:*",
205 "lint:typecheck": "tsc",
206 "lint:eslint": "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly",
207 "lint:changelog": "node ./scripts/lint-changelog.js",
208 "lint:prettier": "prettier . \"!test*\" --check",
209 "lint:dist": "eslint --no-eslintrc --no-ignore --env=es6,browser --parser-options=ecmaVersion:2018 \"dist/!(bin-prettier|index|third-party).js\"",
210 "lint:spellcheck": "cspell \"**/*\" \".github/**/*\"",
211 "lint:deps": "node ./scripts/check-deps.js",
212 fix: "run-s fix:eslint fix:prettier",
213 "fix:eslint": "yarn lint:eslint --fix",
214 "fix:prettier": "yarn lint:prettier --write",
215 build: "node --max-old-space-size=3072 ./scripts/build/build.js",
216 "build-docs": "node ./scripts/build-docs.js"
221 description: description,
223 repository: repository,
232 dependencies: dependencies,
233 devDependencies: devDependencies,
237 var fastJsonStableStringify = function (data, opts) {
238 if (!opts) opts = {};
239 if (typeof opts === 'function') opts = {
242 var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false;
244 var cmp = opts.cmp && function (f) {
245 return function (node) {
246 return function (a, b) {
255 return f(aobj, bobj);
261 return function stringify(node) {
262 if (node && node.toJSON && typeof node.toJSON === 'function') {
263 node = node.toJSON();
266 if (node === undefined) return;
267 if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
268 if (typeof node !== 'object') return JSON.stringify(node);
271 if (Array.isArray(node)) {
274 for (i = 0; i < node.length; i++) {
276 out += stringify(node[i]) || 'null';
282 if (node === null) return 'null';
284 if (seen.indexOf(node) !== -1) {
285 if (cycles) return JSON.stringify('__cycle__');
286 throw new TypeError('Converting circular structure to JSON');
289 var seenIndex = seen.push(node) - 1;
290 var keys = Object.keys(node).sort(cmp && cmp(node));
293 for (i = 0; i < keys.length; i++) {
295 var value = stringify(node[key]);
296 if (!value) continue;
298 out += JSON.stringify(key) + ':' + value;
301 seen.splice(seenIndex, 1);
302 return '{' + out + '}';
306 var src = require("./index");
308 const preserveCamelCase = (string, locale) => {
309 let isLastCharLower = false;
310 let isLastCharUpper = false;
311 let isLastLastCharUpper = false;
313 for (let i = 0; i < string.length; i++) {
314 const character = string[i];
316 if (isLastCharLower && /[\p{Lu}]/u.test(character)) {
317 string = string.slice(0, i) + '-' + string.slice(i);
318 isLastCharLower = false;
319 isLastLastCharUpper = isLastCharUpper;
320 isLastCharUpper = true;
322 } else if (isLastCharUpper && isLastLastCharUpper && /[\p{Ll}]/u.test(character)) {
323 string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
324 isLastLastCharUpper = isLastCharUpper;
325 isLastCharUpper = false;
326 isLastCharLower = true;
328 isLastCharLower = character.toLocaleLowerCase(locale) === character && character.toLocaleUpperCase(locale) !== character;
329 isLastLastCharUpper = isLastCharUpper;
330 isLastCharUpper = character.toLocaleUpperCase(locale) === character && character.toLocaleLowerCase(locale) !== character;
337 const preserveConsecutiveUppercase = input => {
338 return input.replace(/^[\p{Lu}](?![\p{Lu}])/gu, m1 => m1.toLowerCase());
341 const postProcess = (input, options) => {
342 return input.replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) => p1.toLocaleUpperCase(options.locale)).replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, m => m.toLocaleUpperCase(options.locale));
345 const camelCase = (input, options) => {
346 if (!(typeof input === 'string' || Array.isArray(input))) {
347 throw new TypeError('Expected the input to be `string | string[]`');
350 options = Object.assign({
352 preserveConsecutiveUppercase: false
355 if (Array.isArray(input)) {
356 input = input.map(x => x.trim()).filter(x => x.length).join('-');
358 input = input.trim();
361 if (input.length === 0) {
365 if (input.length === 1) {
366 return options.pascalCase ? input.toLocaleUpperCase(options.locale) : input.toLocaleLowerCase(options.locale);
369 const hasUpperCase = input !== input.toLocaleLowerCase(options.locale);
372 input = preserveCamelCase(input, options.locale);
375 input = input.replace(/^[_.\- ]+/, '');
377 if (options.preserveConsecutiveUppercase) {
378 input = preserveConsecutiveUppercase(input);
380 input = input.toLocaleLowerCase();
383 if (options.pascalCase) {
384 input = input.charAt(0).toLocaleUpperCase(options.locale) + input.slice(1);
387 return postProcess(input, options);
390 var camelcase = camelCase; // TODO: Remove this for the next major release
392 var _default = camelCase;
393 camelcase.default = _default;
396 * dashify <https://github.com/jonschlinkert/dashify>
398 * Copyright (c) 2015-2017, Jon Schlinkert.
399 * Released under the MIT License.
402 var dashify = (str, options) => {
403 if (typeof str !== 'string') throw new TypeError('expected a string');
404 return str.trim().replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\W/g, m => /[À-ž]/.test(m) ? m : '-').replace(/^-+|-+$/g, '').replace(/-{2,}/g, m => options && options.condense ? '-' : m).toLowerCase();
407 function createCommonjsModule(fn, basedir, module) {
411 require: function (path, base) {
412 return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
414 }, fn(module, module.exports), module.exports;
417 function commonjsRequire () {
418 throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
422 "aliceblue": [240, 248, 255],
423 "antiquewhite": [250, 235, 215],
424 "aqua": [0, 255, 255],
425 "aquamarine": [127, 255, 212],
426 "azure": [240, 255, 255],
427 "beige": [245, 245, 220],
428 "bisque": [255, 228, 196],
430 "blanchedalmond": [255, 235, 205],
432 "blueviolet": [138, 43, 226],
433 "brown": [165, 42, 42],
434 "burlywood": [222, 184, 135],
435 "cadetblue": [95, 158, 160],
436 "chartreuse": [127, 255, 0],
437 "chocolate": [210, 105, 30],
438 "coral": [255, 127, 80],
439 "cornflowerblue": [100, 149, 237],
440 "cornsilk": [255, 248, 220],
441 "crimson": [220, 20, 60],
442 "cyan": [0, 255, 255],
443 "darkblue": [0, 0, 139],
444 "darkcyan": [0, 139, 139],
445 "darkgoldenrod": [184, 134, 11],
446 "darkgray": [169, 169, 169],
447 "darkgreen": [0, 100, 0],
448 "darkgrey": [169, 169, 169],
449 "darkkhaki": [189, 183, 107],
450 "darkmagenta": [139, 0, 139],
451 "darkolivegreen": [85, 107, 47],
452 "darkorange": [255, 140, 0],
453 "darkorchid": [153, 50, 204],
454 "darkred": [139, 0, 0],
455 "darksalmon": [233, 150, 122],
456 "darkseagreen": [143, 188, 143],
457 "darkslateblue": [72, 61, 139],
458 "darkslategray": [47, 79, 79],
459 "darkslategrey": [47, 79, 79],
460 "darkturquoise": [0, 206, 209],
461 "darkviolet": [148, 0, 211],
462 "deeppink": [255, 20, 147],
463 "deepskyblue": [0, 191, 255],
464 "dimgray": [105, 105, 105],
465 "dimgrey": [105, 105, 105],
466 "dodgerblue": [30, 144, 255],
467 "firebrick": [178, 34, 34],
468 "floralwhite": [255, 250, 240],
469 "forestgreen": [34, 139, 34],
470 "fuchsia": [255, 0, 255],
471 "gainsboro": [220, 220, 220],
472 "ghostwhite": [248, 248, 255],
473 "gold": [255, 215, 0],
474 "goldenrod": [218, 165, 32],
475 "gray": [128, 128, 128],
476 "green": [0, 128, 0],
477 "greenyellow": [173, 255, 47],
478 "grey": [128, 128, 128],
479 "honeydew": [240, 255, 240],
480 "hotpink": [255, 105, 180],
481 "indianred": [205, 92, 92],
482 "indigo": [75, 0, 130],
483 "ivory": [255, 255, 240],
484 "khaki": [240, 230, 140],
485 "lavender": [230, 230, 250],
486 "lavenderblush": [255, 240, 245],
487 "lawngreen": [124, 252, 0],
488 "lemonchiffon": [255, 250, 205],
489 "lightblue": [173, 216, 230],
490 "lightcoral": [240, 128, 128],
491 "lightcyan": [224, 255, 255],
492 "lightgoldenrodyellow": [250, 250, 210],
493 "lightgray": [211, 211, 211],
494 "lightgreen": [144, 238, 144],
495 "lightgrey": [211, 211, 211],
496 "lightpink": [255, 182, 193],
497 "lightsalmon": [255, 160, 122],
498 "lightseagreen": [32, 178, 170],
499 "lightskyblue": [135, 206, 250],
500 "lightslategray": [119, 136, 153],
501 "lightslategrey": [119, 136, 153],
502 "lightsteelblue": [176, 196, 222],
503 "lightyellow": [255, 255, 224],
505 "limegreen": [50, 205, 50],
506 "linen": [250, 240, 230],
507 "magenta": [255, 0, 255],
508 "maroon": [128, 0, 0],
509 "mediumaquamarine": [102, 205, 170],
510 "mediumblue": [0, 0, 205],
511 "mediumorchid": [186, 85, 211],
512 "mediumpurple": [147, 112, 219],
513 "mediumseagreen": [60, 179, 113],
514 "mediumslateblue": [123, 104, 238],
515 "mediumspringgreen": [0, 250, 154],
516 "mediumturquoise": [72, 209, 204],
517 "mediumvioletred": [199, 21, 133],
518 "midnightblue": [25, 25, 112],
519 "mintcream": [245, 255, 250],
520 "mistyrose": [255, 228, 225],
521 "moccasin": [255, 228, 181],
522 "navajowhite": [255, 222, 173],
524 "oldlace": [253, 245, 230],
525 "olive": [128, 128, 0],
526 "olivedrab": [107, 142, 35],
527 "orange": [255, 165, 0],
528 "orangered": [255, 69, 0],
529 "orchid": [218, 112, 214],
530 "palegoldenrod": [238, 232, 170],
531 "palegreen": [152, 251, 152],
532 "paleturquoise": [175, 238, 238],
533 "palevioletred": [219, 112, 147],
534 "papayawhip": [255, 239, 213],
535 "peachpuff": [255, 218, 185],
536 "peru": [205, 133, 63],
537 "pink": [255, 192, 203],
538 "plum": [221, 160, 221],
539 "powderblue": [176, 224, 230],
540 "purple": [128, 0, 128],
541 "rebeccapurple": [102, 51, 153],
543 "rosybrown": [188, 143, 143],
544 "royalblue": [65, 105, 225],
545 "saddlebrown": [139, 69, 19],
546 "salmon": [250, 128, 114],
547 "sandybrown": [244, 164, 96],
548 "seagreen": [46, 139, 87],
549 "seashell": [255, 245, 238],
550 "sienna": [160, 82, 45],
551 "silver": [192, 192, 192],
552 "skyblue": [135, 206, 235],
553 "slateblue": [106, 90, 205],
554 "slategray": [112, 128, 144],
555 "slategrey": [112, 128, 144],
556 "snow": [255, 250, 250],
557 "springgreen": [0, 255, 127],
558 "steelblue": [70, 130, 180],
559 "tan": [210, 180, 140],
560 "teal": [0, 128, 128],
561 "thistle": [216, 191, 216],
562 "tomato": [255, 99, 71],
563 "turquoise": [64, 224, 208],
564 "violet": [238, 130, 238],
565 "wheat": [245, 222, 179],
566 "white": [255, 255, 255],
567 "whitesmoke": [245, 245, 245],
568 "yellow": [255, 255, 0],
569 "yellowgreen": [154, 205, 50]
574 /* eslint-disable no-mixed-operators */
575 // NOTE: conversions should only return primitive values (i.e. arrays, or
576 // values that give correct `typeof` results).
577 // do not use box values types (i.e. Number(), String(), etc.)
579 const reverseKeywords = {};
581 for (const key of Object.keys(colorName)) {
582 reverseKeywords[colorName[key]] = key;
636 labels: ['h', 'c', 'g']
640 labels: ['r16', 'g16', 'b16']
647 var conversions = convert; // Hide .channels and .labels properties
649 for (const model of Object.keys(convert)) {
650 if (!('channels' in convert[model])) {
651 throw new Error('missing channels property: ' + model);
654 if (!('labels' in convert[model])) {
655 throw new Error('missing channel labels property: ' + model);
658 if (convert[model].labels.length !== convert[model].channels) {
659 throw new Error('channel and label counts mismatch: ' + model);
666 delete convert[model].channels;
667 delete convert[model].labels;
668 Object.defineProperty(convert[model], 'channels', {
671 Object.defineProperty(convert[model], 'labels', {
676 convert.rgb.hsl = function (rgb) {
677 const r = rgb[0] / 255;
678 const g = rgb[1] / 255;
679 const b = rgb[2] / 255;
680 const min = Math.min(r, g, b);
681 const max = Math.max(r, g, b);
682 const delta = max - min;
688 } else if (r === max) {
690 } else if (g === max) {
691 h = 2 + (b - r) / delta;
692 } else if (b === max) {
693 h = 4 + (r - g) / delta;
696 h = Math.min(h * 60, 360);
702 const l = (min + max) / 2;
706 } else if (l <= 0.5) {
707 s = delta / (max + min);
709 s = delta / (2 - max - min);
712 return [h, s * 100, l * 100];
715 convert.rgb.hsv = function (rgb) {
721 const r = rgb[0] / 255;
722 const g = rgb[1] / 255;
723 const b = rgb[2] / 255;
724 const v = Math.max(r, g, b);
725 const diff = v - Math.min(r, g, b);
727 const diffc = function (c) {
728 return (v - c) / 6 / diff + 1 / 2;
742 } else if (g === v) {
743 h = 1 / 3 + rdif - bdif;
744 } else if (b === v) {
745 h = 2 / 3 + gdif - rdif;
755 return [h * 360, s * 100, v * 100];
758 convert.rgb.hwb = function (rgb) {
762 const h = convert.rgb.hsl(rgb)[0];
763 const w = 1 / 255 * Math.min(r, Math.min(g, b));
764 b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
765 return [h, w * 100, b * 100];
768 convert.rgb.cmyk = function (rgb) {
769 const r = rgb[0] / 255;
770 const g = rgb[1] / 255;
771 const b = rgb[2] / 255;
772 const k = Math.min(1 - r, 1 - g, 1 - b);
773 const c = (1 - r - k) / (1 - k) || 0;
774 const m = (1 - g - k) / (1 - k) || 0;
775 const y = (1 - b - k) / (1 - k) || 0;
776 return [c * 100, m * 100, y * 100, k * 100];
779 function comparativeDistance(x, y) {
781 See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
783 return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2;
786 convert.rgb.keyword = function (rgb) {
787 const reversed = reverseKeywords[rgb];
793 let currentClosestDistance = Infinity;
794 let currentClosestKeyword;
796 for (const keyword of Object.keys(colorName)) {
797 const value = colorName[keyword]; // Compute comparative distance
799 const distance = comparativeDistance(rgb, value); // Check if its less, if so set as closest
801 if (distance < currentClosestDistance) {
802 currentClosestDistance = distance;
803 currentClosestKeyword = keyword;
807 return currentClosestKeyword;
810 convert.keyword.rgb = function (keyword) {
811 return colorName[keyword];
814 convert.rgb.xyz = function (rgb) {
815 let r = rgb[0] / 255;
816 let g = rgb[1] / 255;
817 let b = rgb[2] / 255; // Assume sRGB
819 r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92;
820 g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92;
821 b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92;
822 const x = r * 0.4124 + g * 0.3576 + b * 0.1805;
823 const y = r * 0.2126 + g * 0.7152 + b * 0.0722;
824 const z = r * 0.0193 + g * 0.1192 + b * 0.9505;
825 return [x * 100, y * 100, z * 100];
828 convert.rgb.lab = function (rgb) {
829 const xyz = convert.rgb.xyz(rgb);
836 x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
837 y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
838 z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
839 const l = 116 * y - 16;
840 const a = 500 * (x - y);
841 const b = 200 * (y - z);
845 convert.hsl.rgb = function (hsl) {
846 const h = hsl[0] / 360;
847 const s = hsl[1] / 100;
848 const l = hsl[2] / 100;
855 return [val, val, val];
864 const t1 = 2 * l - t2;
865 const rgb = [0, 0, 0];
867 for (let i = 0; i < 3; i++) {
868 t3 = h + 1 / 3 * -(i - 1);
879 val = t1 + (t2 - t1) * 6 * t3;
880 } else if (2 * t3 < 1) {
882 } else if (3 * t3 < 2) {
883 val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
894 convert.hsl.hsv = function (hsl) {
896 let s = hsl[1] / 100;
897 let l = hsl[2] / 100;
899 const lmin = Math.max(l, 0.01);
901 s *= l <= 1 ? l : 2 - l;
902 smin *= lmin <= 1 ? lmin : 2 - lmin;
903 const v = (l + s) / 2;
904 const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
905 return [h, sv * 100, v * 100];
908 convert.hsv.rgb = function (hsv) {
909 const h = hsv[0] / 60;
910 const s = hsv[1] / 100;
911 let v = hsv[2] / 100;
912 const hi = Math.floor(h) % 6;
913 const f = h - Math.floor(h);
914 const p = 255 * v * (1 - s);
915 const q = 255 * v * (1 - s * f);
916 const t = 255 * v * (1 - s * (1 - f));
940 convert.hsv.hsl = function (hsv) {
942 const s = hsv[1] / 100;
943 const v = hsv[2] / 100;
944 const vmin = Math.max(v, 0.01);
948 const lmin = (2 - s) * vmin;
950 sl /= lmin <= 1 ? lmin : 2 - lmin;
953 return [h, sl * 100, l * 100];
954 }; // http://dev.w3.org/csswg/css-color/#hwb-to-rgb
957 convert.hwb.rgb = function (hwb) {
958 const h = hwb[0] / 360;
959 let wh = hwb[1] / 100;
960 let bl = hwb[2] / 100;
961 const ratio = wh + bl;
962 let f; // Wh + bl cant be > 1
969 const i = Math.floor(6 * h);
973 if ((i & 0x01) !== 0) {
977 const n = wh + f * (v - wh); // Linear interpolation
982 /* eslint-disable max-statements-per-line,no-multi-spaces */
1023 /* eslint-enable max-statements-per-line,no-multi-spaces */
1026 return [r * 255, g * 255, b * 255];
1029 convert.cmyk.rgb = function (cmyk) {
1030 const c = cmyk[0] / 100;
1031 const m = cmyk[1] / 100;
1032 const y = cmyk[2] / 100;
1033 const k = cmyk[3] / 100;
1034 const r = 1 - Math.min(1, c * (1 - k) + k);
1035 const g = 1 - Math.min(1, m * (1 - k) + k);
1036 const b = 1 - Math.min(1, y * (1 - k) + k);
1037 return [r * 255, g * 255, b * 255];
1040 convert.xyz.rgb = function (xyz) {
1041 const x = xyz[0] / 100;
1042 const y = xyz[1] / 100;
1043 const z = xyz[2] / 100;
1047 r = x * 3.2406 + y * -1.5372 + z * -0.4986;
1048 g = x * -0.9689 + y * 1.8758 + z * 0.0415;
1049 b = x * 0.0557 + y * -0.2040 + z * 1.0570; // Assume sRGB
1051 r = r > 0.0031308 ? 1.055 * r ** (1.0 / 2.4) - 0.055 : r * 12.92;
1052 g = g > 0.0031308 ? 1.055 * g ** (1.0 / 2.4) - 0.055 : g * 12.92;
1053 b = b > 0.0031308 ? 1.055 * b ** (1.0 / 2.4) - 0.055 : b * 12.92;
1054 r = Math.min(Math.max(0, r), 1);
1055 g = Math.min(Math.max(0, g), 1);
1056 b = Math.min(Math.max(0, b), 1);
1057 return [r * 255, g * 255, b * 255];
1060 convert.xyz.lab = function (xyz) {
1067 x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
1068 y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
1069 z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
1070 const l = 116 * y - 16;
1071 const a = 500 * (x - y);
1072 const b = 200 * (y - z);
1076 convert.lab.xyz = function (lab) {
1089 y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
1090 x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
1091 z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
1098 convert.lab.lch = function (lab) {
1103 const hr = Math.atan2(b, a);
1104 h = hr * 360 / 2 / Math.PI;
1110 const c = Math.sqrt(a * a + b * b);
1114 convert.lch.lab = function (lch) {
1118 const hr = h / 360 * 2 * Math.PI;
1119 const a = c * Math.cos(hr);
1120 const b = c * Math.sin(hr);
1124 convert.rgb.ansi16 = function (args, saturation = null) {
1125 const [r, g, b] = args;
1126 let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
1128 value = Math.round(value / 50);
1134 let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
1143 convert.hsv.ansi16 = function (args) {
1144 // Optimization here; we already know the value and don't need to get
1145 // it converted for us.
1146 return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
1149 convert.rgb.ansi256 = function (args) {
1152 const b = args[2]; // We use the extended greyscale palette here, with the exception of
1153 // black and white. normal palette only has 4 greyscale shades.
1155 if (r === g && g === b) {
1164 return Math.round((r - 8) / 247 * 24) + 232;
1167 const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
1171 convert.ansi16.rgb = function (args) {
1172 let color = args % 10; // Handle greyscale
1174 if (color === 0 || color === 7) {
1179 color = color / 10.5 * 255;
1180 return [color, color, color];
1183 const mult = (~~(args > 50) + 1) * 0.5;
1184 const r = (color & 1) * mult * 255;
1185 const g = (color >> 1 & 1) * mult * 255;
1186 const b = (color >> 2 & 1) * mult * 255;
1190 convert.ansi256.rgb = function (args) {
1193 const c = (args - 232) * 10 + 8;
1199 const r = Math.floor(args / 36) / 5 * 255;
1200 const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
1201 const b = rem % 6 / 5 * 255;
1205 convert.rgb.hex = function (args) {
1206 const integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF);
1207 const string = integer.toString(16).toUpperCase();
1208 return '000000'.substring(string.length) + string;
1211 convert.hex.rgb = function (args) {
1212 const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
1218 let colorString = match[0];
1220 if (match[0].length === 3) {
1221 colorString = colorString.split('').map(char => {
1226 const integer = parseInt(colorString, 16);
1227 const r = integer >> 16 & 0xFF;
1228 const g = integer >> 8 & 0xFF;
1229 const b = integer & 0xFF;
1233 convert.rgb.hcg = function (rgb) {
1234 const r = rgb[0] / 255;
1235 const g = rgb[1] / 255;
1236 const b = rgb[2] / 255;
1237 const max = Math.max(Math.max(r, g), b);
1238 const min = Math.min(Math.min(r, g), b);
1239 const chroma = max - min;
1244 grayscale = min / (1 - chroma);
1251 } else if (max === r) {
1252 hue = (g - b) / chroma % 6;
1253 } else if (max === g) {
1254 hue = 2 + (b - r) / chroma;
1256 hue = 4 + (r - g) / chroma;
1261 return [hue * 360, chroma * 100, grayscale * 100];
1264 convert.hsl.hcg = function (hsl) {
1265 const s = hsl[1] / 100;
1266 const l = hsl[2] / 100;
1267 const c = l < 0.5 ? 2.0 * s * l : 2.0 * s * (1.0 - l);
1271 f = (l - 0.5 * c) / (1.0 - c);
1274 return [hsl[0], c * 100, f * 100];
1277 convert.hsv.hcg = function (hsv) {
1278 const s = hsv[1] / 100;
1279 const v = hsv[2] / 100;
1284 f = (v - c) / (1 - c);
1287 return [hsv[0], c * 100, f * 100];
1290 convert.hcg.rgb = function (hcg) {
1291 const h = hcg[0] / 360;
1292 const c = hcg[1] / 100;
1293 const g = hcg[2] / 100;
1296 return [g * 255, g * 255, g * 255];
1299 const pure = [0, 0, 0];
1300 const hi = h % 1 * 6;
1304 /* eslint-disable max-statements-per-line */
1306 switch (Math.floor(hi)) {
1342 /* eslint-enable max-statements-per-line */
1346 return [(c * pure[0] + mg) * 255, (c * pure[1] + mg) * 255, (c * pure[2] + mg) * 255];
1349 convert.hcg.hsv = function (hcg) {
1350 const c = hcg[1] / 100;
1351 const g = hcg[2] / 100;
1352 const v = c + g * (1.0 - c);
1359 return [hcg[0], f * 100, v * 100];
1362 convert.hcg.hsl = function (hcg) {
1363 const c = hcg[1] / 100;
1364 const g = hcg[2] / 100;
1365 const l = g * (1.0 - c) + 0.5 * c;
1368 if (l > 0.0 && l < 0.5) {
1370 } else if (l >= 0.5 && l < 1.0) {
1371 s = c / (2 * (1 - l));
1374 return [hcg[0], s * 100, l * 100];
1377 convert.hcg.hwb = function (hcg) {
1378 const c = hcg[1] / 100;
1379 const g = hcg[2] / 100;
1380 const v = c + g * (1.0 - c);
1381 return [hcg[0], (v - c) * 100, (1 - v) * 100];
1384 convert.hwb.hcg = function (hwb) {
1385 const w = hwb[1] / 100;
1386 const b = hwb[2] / 100;
1392 g = (v - c) / (1 - c);
1395 return [hwb[0], c * 100, g * 100];
1398 convert.apple.rgb = function (apple) {
1399 return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255];
1402 convert.rgb.apple = function (rgb) {
1403 return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535];
1406 convert.gray.rgb = function (args) {
1407 return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
1410 convert.gray.hsl = function (args) {
1411 return [0, 0, args[0]];
1414 convert.gray.hsv = convert.gray.hsl;
1416 convert.gray.hwb = function (gray) {
1417 return [0, 100, gray[0]];
1420 convert.gray.cmyk = function (gray) {
1421 return [0, 0, 0, gray[0]];
1424 convert.gray.lab = function (gray) {
1425 return [gray[0], 0, 0];
1428 convert.gray.hex = function (gray) {
1429 const val = Math.round(gray[0] / 100 * 255) & 0xFF;
1430 const integer = (val << 16) + (val << 8) + val;
1431 const string = integer.toString(16).toUpperCase();
1432 return '000000'.substring(string.length) + string;
1435 convert.rgb.gray = function (rgb) {
1436 const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
1437 return [val / 255 * 100];
1441 This function routes a model to all other models.
1443 all functions that are routed have a property `.conversion` attached
1444 to the returned synthetic function. This property is an array
1445 of strings, each with the steps in between the 'from' and 'to'
1446 color models (inclusive).
1448 conversions that are not possible simply are not included.
1451 function buildGraph() {
1452 const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3
1454 const models = Object.keys(conversions);
1456 for (let len = models.length, i = 0; i < len; i++) {
1457 graph[models[i]] = {
1458 // http://jsperf.com/1-vs-infinity
1459 // micro-opt, but this is simple.
1466 } // https://en.wikipedia.org/wiki/Breadth-first_search
1469 function deriveBFS(fromModel) {
1470 const graph = buildGraph();
1471 const queue = [fromModel]; // Unshift -> queue -> pop
1473 graph[fromModel].distance = 0;
1475 while (queue.length) {
1476 const current = queue.pop();
1477 const adjacents = Object.keys(conversions[current]);
1479 for (let len = adjacents.length, i = 0; i < len; i++) {
1480 const adjacent = adjacents[i];
1481 const node = graph[adjacent];
1483 if (node.distance === -1) {
1484 node.distance = graph[current].distance + 1;
1485 node.parent = current;
1486 queue.unshift(adjacent);
1494 function link(from, to) {
1495 return function (args) {
1496 return to(from(args));
1500 function wrapConversion(toModel, graph) {
1501 const path = [graph[toModel].parent, toModel];
1502 let fn = conversions[graph[toModel].parent][toModel];
1503 let cur = graph[toModel].parent;
1505 while (graph[cur].parent) {
1506 path.unshift(graph[cur].parent);
1507 fn = link(conversions[graph[cur].parent][cur], fn);
1508 cur = graph[cur].parent;
1511 fn.conversion = path;
1515 var route = function (fromModel) {
1516 const graph = deriveBFS(fromModel);
1517 const conversion = {};
1518 const models = Object.keys(graph);
1520 for (let len = models.length, i = 0; i < len; i++) {
1521 const toModel = models[i];
1522 const node = graph[toModel];
1524 if (node.parent === null) {
1525 // No possible conversion, or this node is the source model.
1529 conversion[toModel] = wrapConversion(toModel, graph);
1535 const convert$1 = {};
1536 const models = Object.keys(conversions);
1538 function wrapRaw(fn) {
1539 const wrappedFn = function (...args) {
1540 const arg0 = args[0];
1542 if (arg0 === undefined || arg0 === null) {
1546 if (arg0.length > 1) {
1551 }; // Preserve .conversion property if there is one
1554 if ('conversion' in fn) {
1555 wrappedFn.conversion = fn.conversion;
1561 function wrapRounded(fn) {
1562 const wrappedFn = function (...args) {
1563 const arg0 = args[0];
1565 if (arg0 === undefined || arg0 === null) {
1569 if (arg0.length > 1) {
1573 const result = fn(args); // We're assuming the result is an array here.
1574 // see notice in conversions.js; don't use box types
1575 // in conversion functions.
1577 if (typeof result === 'object') {
1578 for (let len = result.length, i = 0; i < len; i++) {
1579 result[i] = Math.round(result[i]);
1584 }; // Preserve .conversion property if there is one
1587 if ('conversion' in fn) {
1588 wrappedFn.conversion = fn.conversion;
1594 models.forEach(fromModel => {
1595 convert$1[fromModel] = {};
1596 Object.defineProperty(convert$1[fromModel], 'channels', {
1597 value: conversions[fromModel].channels
1599 Object.defineProperty(convert$1[fromModel], 'labels', {
1600 value: conversions[fromModel].labels
1602 const routes = route(fromModel);
1603 const routeModels = Object.keys(routes);
1604 routeModels.forEach(toModel => {
1605 const fn = routes[toModel];
1606 convert$1[fromModel][toModel] = wrapRounded(fn);
1607 convert$1[fromModel][toModel].raw = wrapRaw(fn);
1610 var colorConvert = convert$1;
1612 var ansiStyles = createCommonjsModule(function (module) {
1614 const wrapAnsi16 = (fn, offset) => (...args) => {
1615 const code = fn(...args);
1616 return `\u001B[${code + offset}m`;
1619 const wrapAnsi256 = (fn, offset) => (...args) => {
1620 const code = fn(...args);
1621 return `\u001B[${38 + offset};5;${code}m`;
1624 const wrapAnsi16m = (fn, offset) => (...args) => {
1625 const rgb = fn(...args);
1626 return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
1629 const ansi2ansi = n => n;
1631 const rgb2rgb = (r, g, b) => [r, g, b];
1633 const setLazyProperty = (object, property, get) => {
1634 Object.defineProperty(object, property, {
1636 const value = get();
1637 Object.defineProperty(object, property, {
1648 /** @type {typeof import('color-convert')} */
1653 const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
1654 if (colorConvert$1 === undefined) {
1655 colorConvert$1 = colorConvert;
1658 const offset = isBackground ? 10 : 0;
1661 for (const [sourceSpace, suite] of Object.entries(colorConvert$1)) {
1662 const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
1664 if (sourceSpace === targetSpace) {
1665 styles[name] = wrap(identity, offset);
1666 } else if (typeof suite === 'object') {
1667 styles[name] = wrap(suite[targetSpace], offset);
1674 function assembleStyles() {
1675 const codes = new Map();
1679 // 21 isn't widely supported and 22 does the same thing
1686 strikethrough: [9, 29]
1698 blackBright: [90, 39],
1699 redBright: [91, 39],
1700 greenBright: [92, 39],
1701 yellowBright: [93, 39],
1702 blueBright: [94, 39],
1703 magentaBright: [95, 39],
1704 cyanBright: [96, 39],
1705 whiteBright: [97, 39]
1713 bgMagenta: [45, 49],
1717 bgBlackBright: [100, 49],
1718 bgRedBright: [101, 49],
1719 bgGreenBright: [102, 49],
1720 bgYellowBright: [103, 49],
1721 bgBlueBright: [104, 49],
1722 bgMagentaBright: [105, 49],
1723 bgCyanBright: [106, 49],
1724 bgWhiteBright: [107, 49]
1726 }; // Alias bright black as gray (and grey)
1728 styles.color.gray = styles.color.blackBright;
1729 styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
1730 styles.color.grey = styles.color.blackBright;
1731 styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
1733 for (const [groupName, group] of Object.entries(styles)) {
1734 for (const [styleName, style] of Object.entries(group)) {
1735 styles[styleName] = {
1736 open: `\u001B[${style[0]}m`,
1737 close: `\u001B[${style[1]}m`
1739 group[styleName] = styles[styleName];
1740 codes.set(style[0], style[1]);
1743 Object.defineProperty(styles, groupName, {
1749 Object.defineProperty(styles, 'codes', {
1753 styles.color.close = '\u001B[39m';
1754 styles.bgColor.close = '\u001B[49m';
1755 setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
1756 setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
1757 setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
1758 setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
1759 setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
1760 setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
1762 } // Make the export immutable
1765 Object.defineProperty(module, 'exports', {
1771 var hasFlag = (flag, argv = process.argv) => {
1772 const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
1773 const position = argv.indexOf(prefix + flag);
1774 const terminatorPosition = argv.indexOf('--');
1775 return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
1783 if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never')) {
1785 } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
1789 if ('FORCE_COLOR' in env) {
1790 if (env.FORCE_COLOR === 'true') {
1792 } else if (env.FORCE_COLOR === 'false') {
1795 forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
1799 function translateLevel(level) {
1812 function supportsColor(haveStream, streamIsTTY) {
1813 if (forceColor === 0) {
1817 if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
1821 if (hasFlag('color=256')) {
1825 if (haveStream && !streamIsTTY && forceColor === undefined) {
1829 const min = forceColor || 0;
1831 if (env.TERM === 'dumb') {
1835 if (process.platform === 'win32') {
1836 // Windows 10 build 10586 is the first Windows release that supports 256 colors.
1837 // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
1838 const osRelease = os__default['default'].release().split('.');
1840 if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
1841 return Number(osRelease[2]) >= 14931 ? 3 : 2;
1848 if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
1855 if ('TEAMCITY_VERSION' in env) {
1856 return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
1859 if ('GITHUB_ACTIONS' in env) {
1863 if (env.COLORTERM === 'truecolor') {
1867 if ('TERM_PROGRAM' in env) {
1868 const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
1870 switch (env.TERM_PROGRAM) {
1872 return version >= 3 ? 3 : 2;
1874 case 'Apple_Terminal':
1880 if (/-256(color)?$/i.test(env.TERM)) {
1884 if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
1888 if ('COLORTERM' in env) {
1895 function getSupportLevel(stream) {
1896 const level = supportsColor(stream, stream && stream.isTTY);
1897 return translateLevel(level);
1900 var supportsColor_1 = {
1901 supportsColor: getSupportLevel,
1902 stdout: translateLevel(supportsColor(true, tty__default['default'].isatty(1))),
1903 stderr: translateLevel(supportsColor(true, tty__default['default'].isatty(2)))
1906 const stringReplaceAll = (string, substring, replacer) => {
1907 let index = string.indexOf(substring);
1913 const substringLength = substring.length;
1915 let returnValue = '';
1918 returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
1919 endIndex = index + substringLength;
1920 index = string.indexOf(substring, endIndex);
1921 } while (index !== -1);
1923 returnValue += string.substr(endIndex);
1927 const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
1929 let returnValue = '';
1932 const gotCR = string[index - 1] === '\r';
1933 returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
1934 endIndex = index + 1;
1935 index = string.indexOf('\n', endIndex);
1936 } while (index !== -1);
1938 returnValue += string.substr(endIndex);
1944 stringEncaseCRLFWithFirstIndex
1947 const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
1948 const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
1949 const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
1950 const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
1951 const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]);
1953 function unescape(c) {
1954 const u = c[0] === 'u';
1955 const bracket = c[1] === '{';
1957 if (u && !bracket && c.length === 5 || c[0] === 'x' && c.length === 3) {
1958 return String.fromCharCode(parseInt(c.slice(1), 16));
1962 return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
1965 return ESCAPES.get(c) || c;
1968 function parseArguments(name, arguments_) {
1970 const chunks = arguments_.trim().split(/\s*,\s*/g);
1973 for (const chunk of chunks) {
1974 const number = Number(chunk);
1976 if (!Number.isNaN(number)) {
1977 results.push(number);
1978 } else if (matches = chunk.match(STRING_REGEX)) {
1979 results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
1981 throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
1988 function parseStyle(style) {
1989 STYLE_REGEX.lastIndex = 0;
1993 while ((matches = STYLE_REGEX.exec(style)) !== null) {
1994 const name = matches[1];
1997 const args = parseArguments(name, matches[2]);
1998 results.push([name].concat(args));
2000 results.push([name]);
2007 function buildStyle(chalk, styles) {
2010 for (const layer of styles) {
2011 for (const style of layer.styles) {
2012 enabled[style[0]] = layer.inverse ? null : style.slice(1);
2016 let current = chalk;
2018 for (const [styleName, styles] of Object.entries(enabled)) {
2019 if (!Array.isArray(styles)) {
2023 if (!(styleName in current)) {
2024 throw new Error(`Unknown Chalk style: ${styleName}`);
2027 current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
2033 var templates = (chalk, temporary) => {
2036 let chunk = []; // eslint-disable-next-line max-params
2038 temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
2039 if (escapeCharacter) {
2040 chunk.push(unescape(escapeCharacter));
2042 const string = chunk.join('');
2044 chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
2047 styles: parseStyle(style)
2050 if (styles.length === 0) {
2051 throw new Error('Found extraneous } in Chalk template literal');
2054 chunks.push(buildStyle(chalk, styles)(chunk.join('')));
2058 chunk.push(character);
2061 chunks.push(chunk.join(''));
2063 if (styles.length > 0) {
2064 const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
2065 throw new Error(errMessage);
2068 return chunks.join('');
2072 stdout: stdoutColor,
2074 } = supportsColor_1;
2076 stringReplaceAll: stringReplaceAll$1,
2077 stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1
2081 } = Array; // `supportsColor.level` → `ansiStyles.color[name]` mapping
2083 const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
2084 const styles = Object.create(null);
2086 const applyOptions = (object, options = {}) => {
2087 if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
2088 throw new Error('The `level` option should be an integer from 0 to 3');
2089 } // Detect level if not set manually
2092 const colorLevel = stdoutColor ? stdoutColor.level : 0;
2093 object.level = options.level === undefined ? colorLevel : options.level;
2097 constructor(options) {
2098 // eslint-disable-next-line no-constructor-return
2099 return chalkFactory(options);
2104 const chalkFactory = options => {
2106 applyOptions(chalk, options);
2108 chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
2110 Object.setPrototypeOf(chalk, Chalk.prototype);
2111 Object.setPrototypeOf(chalk.template, chalk);
2113 chalk.template.constructor = () => {
2114 throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
2117 chalk.template.Instance = ChalkClass;
2118 return chalk.template;
2121 function Chalk(options) {
2122 return chalkFactory(options);
2125 for (const [styleName, style] of Object.entries(ansiStyles)) {
2126 styles[styleName] = {
2128 const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
2129 Object.defineProperty(this, styleName, {
2140 const builder = createBuilder(this, this._styler, true);
2141 Object.defineProperty(this, 'visible', {
2148 const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
2150 for (const model of usedModels) {
2156 return function (...arguments_) {
2157 const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
2158 return createBuilder(this, styler, this._isEmpty);
2165 for (const model of usedModels) {
2166 const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
2172 return function (...arguments_) {
2173 const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
2174 return createBuilder(this, styler, this._isEmpty);
2181 const proto = Object.defineProperties(() => {}, Object.assign({}, styles, {
2186 return this._generator.level;
2190 this._generator.level = level;
2196 const createStyler = (open, close, parent) => {
2200 if (parent === undefined) {
2204 openAll = parent.openAll + open;
2205 closeAll = close + parent.closeAll;
2217 const createBuilder = (self, _styler, _isEmpty) => {
2218 const builder = (...arguments_) => {
2219 if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) {
2220 // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
2221 return applyStyle(builder, chalkTag(builder, ...arguments_));
2222 } // Single argument is hot path, implicit coercion is faster than anything
2223 // eslint-disable-next-line no-implicit-coercion
2226 return applyStyle(builder, arguments_.length === 1 ? '' + arguments_[0] : arguments_.join(' '));
2227 }; // We alter the prototype because we must return a function, but there is
2228 // no way to create a function with a different prototype
2231 Object.setPrototypeOf(builder, proto);
2232 builder._generator = self;
2233 builder._styler = _styler;
2234 builder._isEmpty = _isEmpty;
2238 const applyStyle = (self, string) => {
2239 if (self.level <= 0 || !string) {
2240 return self._isEmpty ? '' : string;
2243 let styler = self._styler;
2245 if (styler === undefined) {
2254 if (string.indexOf('\u001B') !== -1) {
2255 while (styler !== undefined) {
2256 // Replace any instances already present with a re-opening code
2257 // otherwise only the part of the string until said closing code
2258 // will be colored, and the rest will simply be 'plain'.
2259 string = stringReplaceAll$1(string, styler.close, styler.open);
2260 styler = styler.parent;
2262 } // We can move both next actions out of loop, because remaining actions in loop won't have
2263 // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
2264 // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
2267 const lfIndex = string.indexOf('\n');
2269 if (lfIndex !== -1) {
2270 string = stringEncaseCRLFWithFirstIndex$1(string, closeAll, openAll, lfIndex);
2273 return openAll + string + closeAll;
2278 const chalkTag = (chalk, ...strings) => {
2279 const [firstString] = strings;
2281 if (!isArray(firstString) || !isArray(firstString.raw)) {
2282 // If chalk() was called by itself or with a string,
2283 // return the string itself as a string.
2284 return strings.join(' ');
2287 const arguments_ = strings.slice(1);
2288 const parts = [firstString.raw[0]];
2290 for (let i = 1; i < firstString.length; i++) {
2291 parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]));
2294 if (template === undefined) {
2295 template = templates;
2298 return template(chalk, parts.join(''));
2301 Object.defineProperties(Chalk.prototype, styles);
2302 const chalk = Chalk(); // eslint-disable-line new-cap
2304 chalk.supportsColor = stdoutColor;
2305 chalk.stderr = Chalk({
2306 level: stderrColor ? stderrColor.level : 0
2307 }); // eslint-disable-line new-cap
2309 chalk.stderr.supportsColor = stderrColor;
2313 * The inverse of `_.toPairs`; this method returns an object composed
2314 * from key-value `pairs`.
2320 * @param {Array} pairs The key-value pairs.
2321 * @returns {Object} Returns the new object.
2324 * _.fromPairs([['a', 1], ['b', 2]]);
2325 * // => { 'a': 1, 'b': 2 }
2327 function fromPairs(pairs) {
2329 length = pairs == null ? 0 : pairs.length,
2332 while (++index < length) {
2333 var pair = pairs[index];
2334 result[pair[0]] = pair[1];
2340 var fromPairs_1 = fromPairs;
2343 * Checks if `value` is classified as an `Array` object.
2349 * @param {*} value The value to check.
2350 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
2353 * _.isArray([1, 2, 3]);
2356 * _.isArray(document.body.children);
2362 * _.isArray(_.noop);
2365 var isArray$1 = Array.isArray;
2366 var isArray_1 = isArray$1;
2368 /** Detect free variable `global` from Node.js. */
2369 var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
2370 var _freeGlobal = freeGlobal;
2372 /** Detect free variable `self`. */
2374 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
2375 /** Used as a reference to the global object. */
2377 var root = _freeGlobal || freeSelf || Function('return this')();
2380 /** Built-in value references. */
2382 var Symbol$1 = _root.Symbol;
2383 var _Symbol = Symbol$1;
2385 /** Used for built-in method references. */
2387 var objectProto = Object.prototype;
2388 /** Used to check objects for own properties. */
2390 var hasOwnProperty = objectProto.hasOwnProperty;
2392 * Used to resolve the
2393 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
2397 var nativeObjectToString = objectProto.toString;
2398 /** Built-in value references. */
2400 var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined;
2402 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
2405 * @param {*} value The value to query.
2406 * @returns {string} Returns the raw `toStringTag`.
2409 function getRawTag(value) {
2410 var isOwn = hasOwnProperty.call(value, symToStringTag),
2411 tag = value[symToStringTag];
2414 value[symToStringTag] = undefined;
2415 var unmasked = true;
2418 var result = nativeObjectToString.call(value);
2422 value[symToStringTag] = tag;
2424 delete value[symToStringTag];
2431 var _getRawTag = getRawTag;
2433 /** Used for built-in method references. */
2434 var objectProto$1 = Object.prototype;
2436 * Used to resolve the
2437 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
2441 var nativeObjectToString$1 = objectProto$1.toString;
2443 * Converts `value` to a string using `Object.prototype.toString`.
2446 * @param {*} value The value to convert.
2447 * @returns {string} Returns the converted string.
2450 function objectToString(value) {
2451 return nativeObjectToString$1.call(value);
2454 var _objectToString = objectToString;
2456 /** `Object#toString` result references. */
2458 var nullTag = '[object Null]',
2459 undefinedTag = '[object Undefined]';
2460 /** Built-in value references. */
2462 var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined;
2464 * The base implementation of `getTag` without fallbacks for buggy environments.
2467 * @param {*} value The value to query.
2468 * @returns {string} Returns the `toStringTag`.
2471 function baseGetTag(value) {
2472 if (value == null) {
2473 return value === undefined ? undefinedTag : nullTag;
2476 return symToStringTag$1 && symToStringTag$1 in Object(value) ? _getRawTag(value) : _objectToString(value);
2479 var _baseGetTag = baseGetTag;
2482 * Checks if `value` is object-like. A value is object-like if it's not `null`
2483 * and has a `typeof` result of "object".
2489 * @param {*} value The value to check.
2490 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
2493 * _.isObjectLike({});
2496 * _.isObjectLike([1, 2, 3]);
2499 * _.isObjectLike(_.noop);
2502 * _.isObjectLike(null);
2505 function isObjectLike(value) {
2506 return value != null && typeof value == 'object';
2509 var isObjectLike_1 = isObjectLike;
2511 /** `Object#toString` result references. */
2513 var symbolTag = '[object Symbol]';
2515 * Checks if `value` is classified as a `Symbol` primitive or object.
2521 * @param {*} value The value to check.
2522 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
2525 * _.isSymbol(Symbol.iterator);
2528 * _.isSymbol('abc');
2532 function isSymbol(value) {
2533 return typeof value == 'symbol' || isObjectLike_1(value) && _baseGetTag(value) == symbolTag;
2536 var isSymbol_1 = isSymbol;
2538 /** Used to match property names within property paths. */
2540 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
2541 reIsPlainProp = /^\w*$/;
2543 * Checks if `value` is a property name and not a property path.
2546 * @param {*} value The value to check.
2547 * @param {Object} [object] The object to query keys on.
2548 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
2551 function isKey(value, object) {
2552 if (isArray_1(value)) {
2556 var type = typeof value;
2558 if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) {
2562 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
2568 * Checks if `value` is the
2569 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
2570 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
2576 * @param {*} value The value to check.
2577 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
2583 * _.isObject([1, 2, 3]);
2586 * _.isObject(_.noop);
2592 function isObject(value) {
2593 var type = typeof value;
2594 return value != null && (type == 'object' || type == 'function');
2597 var isObject_1 = isObject;
2599 /** `Object#toString` result references. */
2601 var asyncTag = '[object AsyncFunction]',
2602 funcTag = '[object Function]',
2603 genTag = '[object GeneratorFunction]',
2604 proxyTag = '[object Proxy]';
2606 * Checks if `value` is classified as a `Function` object.
2612 * @param {*} value The value to check.
2613 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
2619 * _.isFunction(/abc/);
2623 function isFunction(value) {
2624 if (!isObject_1(value)) {
2626 } // The use of `Object#toString` avoids issues with the `typeof` operator
2627 // in Safari 9 which returns 'object' for typed arrays and other constructors.
2630 var tag = _baseGetTag(value);
2631 return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
2634 var isFunction_1 = isFunction;
2636 /** Used to detect overreaching core-js shims. */
2638 var coreJsData = _root['__core-js_shared__'];
2639 var _coreJsData = coreJsData;
2641 /** Used to detect methods masquerading as native. */
2643 var maskSrcKey = function () {
2644 var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || '');
2645 return uid ? 'Symbol(src)_1.' + uid : '';
2648 * Checks if `func` has its source masked.
2651 * @param {Function} func The function to check.
2652 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
2656 function isMasked(func) {
2657 return !!maskSrcKey && maskSrcKey in func;
2660 var _isMasked = isMasked;
2662 /** Used for built-in method references. */
2663 var funcProto = Function.prototype;
2664 /** Used to resolve the decompiled source of functions. */
2666 var funcToString = funcProto.toString;
2668 * Converts `func` to its source code.
2671 * @param {Function} func The function to convert.
2672 * @returns {string} Returns the source code.
2675 function toSource(func) {
2678 return funcToString.call(func);
2689 var _toSource = toSource;
2692 * Used to match `RegExp`
2693 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
2696 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
2697 /** Used to detect host constructors (Safari). */
2699 var reIsHostCtor = /^\[object .+?Constructor\]$/;
2700 /** Used for built-in method references. */
2702 var funcProto$1 = Function.prototype,
2703 objectProto$2 = Object.prototype;
2704 /** Used to resolve the decompiled source of functions. */
2706 var funcToString$1 = funcProto$1.toString;
2707 /** Used to check objects for own properties. */
2709 var hasOwnProperty$1 = objectProto$2.hasOwnProperty;
2710 /** Used to detect if a method is native. */
2712 var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$1).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$');
2714 * The base implementation of `_.isNative` without bad shim checks.
2717 * @param {*} value The value to check.
2718 * @returns {boolean} Returns `true` if `value` is a native function,
2722 function baseIsNative(value) {
2723 if (!isObject_1(value) || _isMasked(value)) {
2727 var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor;
2728 return pattern.test(_toSource(value));
2731 var _baseIsNative = baseIsNative;
2734 * Gets the value at `key` of `object`.
2737 * @param {Object} [object] The object to query.
2738 * @param {string} key The key of the property to get.
2739 * @returns {*} Returns the property value.
2741 function getValue(object, key) {
2742 return object == null ? undefined : object[key];
2745 var _getValue = getValue;
2748 * Gets the native function at `key` of `object`.
2751 * @param {Object} object The object to query.
2752 * @param {string} key The key of the method to get.
2753 * @returns {*} Returns the function if it's native, else `undefined`.
2756 function getNative(object, key) {
2757 var value = _getValue(object, key);
2758 return _baseIsNative(value) ? value : undefined;
2761 var _getNative = getNative;
2763 /* Built-in method references that are verified to be native. */
2765 var nativeCreate = _getNative(Object, 'create');
2766 var _nativeCreate = nativeCreate;
2769 * Removes all key-value entries from the hash.
2776 function hashClear() {
2777 this.__data__ = _nativeCreate ? _nativeCreate(null) : {};
2781 var _hashClear = hashClear;
2784 * Removes `key` and its value from the hash.
2789 * @param {Object} hash The hash to modify.
2790 * @param {string} key The key of the value to remove.
2791 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
2793 function hashDelete(key) {
2794 var result = this.has(key) && delete this.__data__[key];
2795 this.size -= result ? 1 : 0;
2799 var _hashDelete = hashDelete;
2801 /** Used to stand-in for `undefined` hash values. */
2803 var HASH_UNDEFINED = '__lodash_hash_undefined__';
2804 /** Used for built-in method references. */
2806 var objectProto$3 = Object.prototype;
2807 /** Used to check objects for own properties. */
2809 var hasOwnProperty$2 = objectProto$3.hasOwnProperty;
2811 * Gets the hash value for `key`.
2816 * @param {string} key The key of the value to get.
2817 * @returns {*} Returns the entry value.
2820 function hashGet(key) {
2821 var data = this.__data__;
2823 if (_nativeCreate) {
2824 var result = data[key];
2825 return result === HASH_UNDEFINED ? undefined : result;
2828 return hasOwnProperty$2.call(data, key) ? data[key] : undefined;
2831 var _hashGet = hashGet;
2833 /** Used for built-in method references. */
2835 var objectProto$4 = Object.prototype;
2836 /** Used to check objects for own properties. */
2838 var hasOwnProperty$3 = objectProto$4.hasOwnProperty;
2840 * Checks if a hash value for `key` exists.
2845 * @param {string} key The key of the entry to check.
2846 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
2849 function hashHas(key) {
2850 var data = this.__data__;
2851 return _nativeCreate ? data[key] !== undefined : hasOwnProperty$3.call(data, key);
2854 var _hashHas = hashHas;
2856 /** Used to stand-in for `undefined` hash values. */
2858 var HASH_UNDEFINED$1 = '__lodash_hash_undefined__';
2860 * Sets the hash `key` to `value`.
2865 * @param {string} key The key of the value to set.
2866 * @param {*} value The value to set.
2867 * @returns {Object} Returns the hash instance.
2870 function hashSet(key, value) {
2871 var data = this.__data__;
2872 this.size += this.has(key) ? 0 : 1;
2873 data[key] = _nativeCreate && value === undefined ? HASH_UNDEFINED$1 : value;
2877 var _hashSet = hashSet;
2880 * Creates a hash object.
2884 * @param {Array} [entries] The key-value pairs to cache.
2887 function Hash(entries) {
2889 length = entries == null ? 0 : entries.length;
2892 while (++index < length) {
2893 var entry = entries[index];
2894 this.set(entry[0], entry[1]);
2896 } // Add methods to `Hash`.
2899 Hash.prototype.clear = _hashClear;
2900 Hash.prototype['delete'] = _hashDelete;
2901 Hash.prototype.get = _hashGet;
2902 Hash.prototype.has = _hashHas;
2903 Hash.prototype.set = _hashSet;
2907 * Removes all key-value entries from the list cache.
2911 * @memberOf ListCache
2913 function listCacheClear() {
2918 var _listCacheClear = listCacheClear;
2922 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
2923 * comparison between two values to determine if they are equivalent.
2929 * @param {*} value The value to compare.
2930 * @param {*} other The other value to compare.
2931 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
2934 * var object = { 'a': 1 };
2935 * var other = { 'a': 1 };
2937 * _.eq(object, object);
2940 * _.eq(object, other);
2946 * _.eq('a', Object('a'));
2952 function eq(value, other) {
2953 return value === other || value !== value && other !== other;
2959 * Gets the index at which the `key` is found in `array` of key-value pairs.
2962 * @param {Array} array The array to inspect.
2963 * @param {*} key The key to search for.
2964 * @returns {number} Returns the index of the matched value, else `-1`.
2967 function assocIndexOf(array, key) {
2968 var length = array.length;
2971 if (eq_1(array[length][0], key)) {
2979 var _assocIndexOf = assocIndexOf;
2981 /** Used for built-in method references. */
2983 var arrayProto = Array.prototype;
2984 /** Built-in value references. */
2986 var splice = arrayProto.splice;
2988 * Removes `key` and its value from the list cache.
2992 * @memberOf ListCache
2993 * @param {string} key The key of the value to remove.
2994 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
2997 function listCacheDelete(key) {
2998 var data = this.__data__,
2999 index = _assocIndexOf(data, key);
3005 var lastIndex = data.length - 1;
3007 if (index == lastIndex) {
3010 splice.call(data, index, 1);
3017 var _listCacheDelete = listCacheDelete;
3020 * Gets the list cache value for `key`.
3024 * @memberOf ListCache
3025 * @param {string} key The key of the value to get.
3026 * @returns {*} Returns the entry value.
3029 function listCacheGet(key) {
3030 var data = this.__data__,
3031 index = _assocIndexOf(data, key);
3032 return index < 0 ? undefined : data[index][1];
3035 var _listCacheGet = listCacheGet;
3038 * Checks if a list cache value for `key` exists.
3042 * @memberOf ListCache
3043 * @param {string} key The key of the entry to check.
3044 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
3047 function listCacheHas(key) {
3048 return _assocIndexOf(this.__data__, key) > -1;
3051 var _listCacheHas = listCacheHas;
3054 * Sets the list cache `key` to `value`.
3058 * @memberOf ListCache
3059 * @param {string} key The key of the value to set.
3060 * @param {*} value The value to set.
3061 * @returns {Object} Returns the list cache instance.
3064 function listCacheSet(key, value) {
3065 var data = this.__data__,
3066 index = _assocIndexOf(data, key);
3070 data.push([key, value]);
3072 data[index][1] = value;
3078 var _listCacheSet = listCacheSet;
3081 * Creates an list cache object.
3085 * @param {Array} [entries] The key-value pairs to cache.
3088 function ListCache(entries) {
3090 length = entries == null ? 0 : entries.length;
3093 while (++index < length) {
3094 var entry = entries[index];
3095 this.set(entry[0], entry[1]);
3097 } // Add methods to `ListCache`.
3100 ListCache.prototype.clear = _listCacheClear;
3101 ListCache.prototype['delete'] = _listCacheDelete;
3102 ListCache.prototype.get = _listCacheGet;
3103 ListCache.prototype.has = _listCacheHas;
3104 ListCache.prototype.set = _listCacheSet;
3105 var _ListCache = ListCache;
3107 /* Built-in method references that are verified to be native. */
3109 var Map$1 = _getNative(_root, 'Map');
3113 * Removes all key-value entries from the map.
3117 * @memberOf MapCache
3120 function mapCacheClear() {
3123 'hash': new _Hash(),
3124 'map': new (_Map || _ListCache)(),
3125 'string': new _Hash()
3129 var _mapCacheClear = mapCacheClear;
3132 * Checks if `value` is suitable for use as unique object key.
3135 * @param {*} value The value to check.
3136 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
3138 function isKeyable(value) {
3139 var type = typeof value;
3140 return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null;
3143 var _isKeyable = isKeyable;
3146 * Gets the data for `map`.
3149 * @param {Object} map The map to query.
3150 * @param {string} key The reference key.
3151 * @returns {*} Returns the map data.
3154 function getMapData(map, key) {
3155 var data = map.__data__;
3156 return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map;
3159 var _getMapData = getMapData;
3162 * Removes `key` and its value from the map.
3166 * @memberOf MapCache
3167 * @param {string} key The key of the value to remove.
3168 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
3171 function mapCacheDelete(key) {
3172 var result = _getMapData(this, key)['delete'](key);
3173 this.size -= result ? 1 : 0;
3177 var _mapCacheDelete = mapCacheDelete;
3180 * Gets the map value for `key`.
3184 * @memberOf MapCache
3185 * @param {string} key The key of the value to get.
3186 * @returns {*} Returns the entry value.
3189 function mapCacheGet(key) {
3190 return _getMapData(this, key).get(key);
3193 var _mapCacheGet = mapCacheGet;
3196 * Checks if a map value for `key` exists.
3200 * @memberOf MapCache
3201 * @param {string} key The key of the entry to check.
3202 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
3205 function mapCacheHas(key) {
3206 return _getMapData(this, key).has(key);
3209 var _mapCacheHas = mapCacheHas;
3212 * Sets the map `key` to `value`.
3216 * @memberOf MapCache
3217 * @param {string} key The key of the value to set.
3218 * @param {*} value The value to set.
3219 * @returns {Object} Returns the map cache instance.
3222 function mapCacheSet(key, value) {
3223 var data = _getMapData(this, key),
3225 data.set(key, value);
3226 this.size += data.size == size ? 0 : 1;
3230 var _mapCacheSet = mapCacheSet;
3233 * Creates a map cache object to store key-value pairs.
3237 * @param {Array} [entries] The key-value pairs to cache.
3240 function MapCache(entries) {
3242 length = entries == null ? 0 : entries.length;
3245 while (++index < length) {
3246 var entry = entries[index];
3247 this.set(entry[0], entry[1]);
3249 } // Add methods to `MapCache`.
3252 MapCache.prototype.clear = _mapCacheClear;
3253 MapCache.prototype['delete'] = _mapCacheDelete;
3254 MapCache.prototype.get = _mapCacheGet;
3255 MapCache.prototype.has = _mapCacheHas;
3256 MapCache.prototype.set = _mapCacheSet;
3257 var _MapCache = MapCache;
3259 /** Error message constants. */
3261 var FUNC_ERROR_TEXT = 'Expected a function';
3263 * Creates a function that memoizes the result of `func`. If `resolver` is
3264 * provided, it determines the cache key for storing the result based on the
3265 * arguments provided to the memoized function. By default, the first argument
3266 * provided to the memoized function is used as the map cache key. The `func`
3267 * is invoked with the `this` binding of the memoized function.
3269 * **Note:** The cache is exposed as the `cache` property on the memoized
3270 * function. Its creation may be customized by replacing the `_.memoize.Cache`
3271 * constructor with one whose instances implement the
3272 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
3273 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
3278 * @category Function
3279 * @param {Function} func The function to have its output memoized.
3280 * @param {Function} [resolver] The function to resolve the cache key.
3281 * @returns {Function} Returns the new memoized function.
3284 * var object = { 'a': 1, 'b': 2 };
3285 * var other = { 'c': 3, 'd': 4 };
3287 * var values = _.memoize(_.values);
3298 * // Modify the result cache.
3299 * values.cache.set(object, ['a', 'b']);
3303 * // Replace `_.memoize.Cache`.
3304 * _.memoize.Cache = WeakMap;
3307 function memoize(func, resolver) {
3308 if (typeof func != 'function' || resolver != null && typeof resolver != 'function') {
3309 throw new TypeError(FUNC_ERROR_TEXT);
3312 var memoized = function () {
3313 var args = arguments,
3314 key = resolver ? resolver.apply(this, args) : args[0],
3315 cache = memoized.cache;
3317 if (cache.has(key)) {
3318 return cache.get(key);
3321 var result = func.apply(this, args);
3322 memoized.cache = cache.set(key, result) || cache;
3326 memoized.cache = new (memoize.Cache || _MapCache)();
3328 } // Expose `MapCache`.
3331 memoize.Cache = _MapCache;
3332 var memoize_1 = memoize;
3334 /** Used as the maximum memoize cache size. */
3336 var MAX_MEMOIZE_SIZE = 500;
3338 * A specialized version of `_.memoize` which clears the memoized function's
3339 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
3342 * @param {Function} func The function to have its output memoized.
3343 * @returns {Function} Returns the new memoized function.
3346 function memoizeCapped(func) {
3347 var result = memoize_1(func, function (key) {
3348 if (cache.size === MAX_MEMOIZE_SIZE) {
3354 var cache = result.cache;
3358 var _memoizeCapped = memoizeCapped;
3360 /** Used to match property names within property paths. */
3362 var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
3363 /** Used to match backslashes in property paths. */
3365 var reEscapeChar = /\\(\\)?/g;
3367 * Converts `string` to a property path array.
3370 * @param {string} string The string to convert.
3371 * @returns {Array} Returns the property path array.
3374 var stringToPath = _memoizeCapped(function (string) {
3377 if (string.charCodeAt(0) === 46
3383 string.replace(rePropName, function (match, number, quote, subString) {
3384 result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
3388 var _stringToPath = stringToPath;
3391 * A specialized version of `_.map` for arrays without support for iteratee
3395 * @param {Array} [array] The array to iterate over.
3396 * @param {Function} iteratee The function invoked per iteration.
3397 * @returns {Array} Returns the new mapped array.
3399 function arrayMap(array, iteratee) {
3401 length = array == null ? 0 : array.length,
3402 result = Array(length);
3404 while (++index < length) {
3405 result[index] = iteratee(array[index], index, array);
3411 var _arrayMap = arrayMap;
3413 /** Used as references for various `Number` constants. */
3415 var INFINITY = 1 / 0;
3416 /** Used to convert symbols to primitives and strings. */
3418 var symbolProto = _Symbol ? _Symbol.prototype : undefined,
3419 symbolToString = symbolProto ? symbolProto.toString : undefined;
3421 * The base implementation of `_.toString` which doesn't convert nullish
3422 * values to empty strings.
3425 * @param {*} value The value to process.
3426 * @returns {string} Returns the string.
3429 function baseToString(value) {
3430 // Exit early for strings to avoid a performance hit in some environments.
3431 if (typeof value == 'string') {
3435 if (isArray_1(value)) {
3436 // Recursively convert values (susceptible to call stack limits).
3437 return _arrayMap(value, baseToString) + '';
3440 if (isSymbol_1(value)) {
3441 return symbolToString ? symbolToString.call(value) : '';
3444 var result = value + '';
3445 return result == '0' && 1 / value == -INFINITY ? '-0' : result;
3448 var _baseToString = baseToString;
3451 * Converts `value` to a string. An empty string is returned for `null`
3452 * and `undefined` values. The sign of `-0` is preserved.
3458 * @param {*} value The value to convert.
3459 * @returns {string} Returns the converted string.
3468 * _.toString([1, 2, 3]);
3472 function toString(value) {
3473 return value == null ? '' : _baseToString(value);
3476 var toString_1 = toString;
3479 * Casts `value` to a path array if it's not one.
3482 * @param {*} value The value to inspect.
3483 * @param {Object} [object] The object to query keys on.
3484 * @returns {Array} Returns the cast property path array.
3487 function castPath(value, object) {
3488 if (isArray_1(value)) {
3492 return _isKey(value, object) ? [value] : _stringToPath(toString_1(value));
3495 var _castPath = castPath;
3497 /** Used as references for various `Number` constants. */
3499 var INFINITY$1 = 1 / 0;
3501 * Converts `value` to a string key if it's not a string or symbol.
3504 * @param {*} value The value to inspect.
3505 * @returns {string|symbol} Returns the key.
3508 function toKey(value) {
3509 if (typeof value == 'string' || isSymbol_1(value)) {
3513 var result = value + '';
3514 return result == '0' && 1 / value == -INFINITY$1 ? '-0' : result;
3520 * The base implementation of `_.get` without support for default values.
3523 * @param {Object} object The object to query.
3524 * @param {Array|string} path The path of the property to get.
3525 * @returns {*} Returns the resolved value.
3528 function baseGet(object, path) {
3529 path = _castPath(path, object);
3531 length = path.length;
3533 while (object != null && index < length) {
3534 object = object[_toKey(path[index++])];
3537 return index && index == length ? object : undefined;
3540 var _baseGet = baseGet;
3542 var defineProperty = function () {
3544 var func = _getNative(Object, 'defineProperty');
3550 var _defineProperty = defineProperty;
3553 * The base implementation of `assignValue` and `assignMergeValue` without
3557 * @param {Object} object The object to modify.
3558 * @param {string} key The key of the property to assign.
3559 * @param {*} value The value to assign.
3562 function baseAssignValue(object, key, value) {
3563 if (key == '__proto__' && _defineProperty) {
3564 _defineProperty(object, key, {
3565 'configurable': true,
3571 object[key] = value;
3575 var _baseAssignValue = baseAssignValue;
3577 /** Used for built-in method references. */
3579 var objectProto$5 = Object.prototype;
3580 /** Used to check objects for own properties. */
3582 var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
3584 * Assigns `value` to `key` of `object` if the existing value is not equivalent
3585 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
3586 * for equality comparisons.
3589 * @param {Object} object The object to modify.
3590 * @param {string} key The key of the property to assign.
3591 * @param {*} value The value to assign.
3594 function assignValue(object, key, value) {
3595 var objValue = object[key];
3597 if (!(hasOwnProperty$4.call(object, key) && eq_1(objValue, value)) || value === undefined && !(key in object)) {
3598 _baseAssignValue(object, key, value);
3602 var _assignValue = assignValue;
3604 /** Used as references for various `Number` constants. */
3605 var MAX_SAFE_INTEGER = 9007199254740991;
3606 /** Used to detect unsigned integer values. */
3608 var reIsUint = /^(?:0|[1-9]\d*)$/;
3610 * Checks if `value` is a valid array-like index.
3613 * @param {*} value The value to check.
3614 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
3615 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
3618 function isIndex(value, length) {
3619 var type = typeof value;
3620 length = length == null ? MAX_SAFE_INTEGER : length;
3621 return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
3624 var _isIndex = isIndex;
3627 * The base implementation of `_.set`.
3630 * @param {Object} object The object to modify.
3631 * @param {Array|string} path The path of the property to set.
3632 * @param {*} value The value to set.
3633 * @param {Function} [customizer] The function to customize path creation.
3634 * @returns {Object} Returns `object`.
3637 function baseSet(object, path, value, customizer) {
3638 if (!isObject_1(object)) {
3642 path = _castPath(path, object);
3644 length = path.length,
3645 lastIndex = length - 1,
3648 while (nested != null && ++index < length) {
3649 var key = _toKey(path[index]),
3652 if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
3656 if (index != lastIndex) {
3657 var objValue = nested[key];
3658 newValue = customizer ? customizer(objValue, key, nested) : undefined;
3660 if (newValue === undefined) {
3661 newValue = isObject_1(objValue) ? objValue : _isIndex(path[index + 1]) ? [] : {};
3665 _assignValue(nested, key, newValue);
3666 nested = nested[key];
3672 var _baseSet = baseSet;
3675 * The base implementation of `_.pickBy` without support for iteratee shorthands.
3678 * @param {Object} object The source object.
3679 * @param {string[]} paths The property paths to pick.
3680 * @param {Function} predicate The function invoked per property.
3681 * @returns {Object} Returns the new object.
3684 function basePickBy(object, paths, predicate) {
3686 length = paths.length,
3689 while (++index < length) {
3690 var path = paths[index],
3691 value = _baseGet(object, path);
3693 if (predicate(value, path)) {
3694 _baseSet(result, _castPath(path, object), value);
3701 var _basePickBy = basePickBy;
3704 * The base implementation of `_.hasIn` without support for deep paths.
3707 * @param {Object} [object] The object to query.
3708 * @param {Array|string} key The key to check.
3709 * @returns {boolean} Returns `true` if `key` exists, else `false`.
3711 function baseHasIn(object, key) {
3712 return object != null && key in Object(object);
3715 var _baseHasIn = baseHasIn;
3717 /** `Object#toString` result references. */
3719 var argsTag = '[object Arguments]';
3721 * The base implementation of `_.isArguments`.
3724 * @param {*} value The value to check.
3725 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
3728 function baseIsArguments(value) {
3729 return isObjectLike_1(value) && _baseGetTag(value) == argsTag;
3732 var _baseIsArguments = baseIsArguments;
3734 /** Used for built-in method references. */
3736 var objectProto$6 = Object.prototype;
3737 /** Used to check objects for own properties. */
3739 var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
3740 /** Built-in value references. */
3742 var propertyIsEnumerable = objectProto$6.propertyIsEnumerable;
3744 * Checks if `value` is likely an `arguments` object.
3750 * @param {*} value The value to check.
3751 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
3755 * _.isArguments(function() { return arguments; }());
3758 * _.isArguments([1, 2, 3]);
3762 var isArguments = _baseIsArguments(function () {
3764 }()) ? _baseIsArguments : function (value) {
3765 return isObjectLike_1(value) && hasOwnProperty$5.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
3767 var isArguments_1 = isArguments;
3769 /** Used as references for various `Number` constants. */
3770 var MAX_SAFE_INTEGER$1 = 9007199254740991;
3772 * Checks if `value` is a valid array-like length.
3774 * **Note:** This method is loosely based on
3775 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
3781 * @param {*} value The value to check.
3782 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
3788 * _.isLength(Number.MIN_VALUE);
3791 * _.isLength(Infinity);
3798 function isLength(value) {
3799 return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1;
3802 var isLength_1 = isLength;
3805 * Checks if `path` exists on `object`.
3808 * @param {Object} object The object to query.
3809 * @param {Array|string} path The path to check.
3810 * @param {Function} hasFunc The function to check properties.
3811 * @returns {boolean} Returns `true` if `path` exists, else `false`.
3814 function hasPath(object, path, hasFunc) {
3815 path = _castPath(path, object);
3817 length = path.length,
3820 while (++index < length) {
3821 var key = _toKey(path[index]);
3823 if (!(result = object != null && hasFunc(object, key))) {
3827 object = object[key];
3830 if (result || ++index != length) {
3834 length = object == null ? 0 : object.length;
3835 return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object));
3838 var _hasPath = hasPath;
3841 * Checks if `path` is a direct or inherited property of `object`.
3847 * @param {Object} object The object to query.
3848 * @param {Array|string} path The path to check.
3849 * @returns {boolean} Returns `true` if `path` exists, else `false`.
3852 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
3854 * _.hasIn(object, 'a');
3857 * _.hasIn(object, 'a.b');
3860 * _.hasIn(object, ['a', 'b']);
3863 * _.hasIn(object, 'b');
3867 function hasIn(object, path) {
3868 return object != null && _hasPath(object, path, _baseHasIn);
3871 var hasIn_1 = hasIn;
3874 * The base implementation of `_.pick` without support for individual
3875 * property identifiers.
3878 * @param {Object} object The source object.
3879 * @param {string[]} paths The property paths to pick.
3880 * @returns {Object} Returns the new object.
3883 function basePick(object, paths) {
3884 return _basePickBy(object, paths, function (value, path) {
3885 return hasIn_1(object, path);
3889 var _basePick = basePick;
3892 * Appends the elements of `values` to `array`.
3895 * @param {Array} array The array to modify.
3896 * @param {Array} values The values to append.
3897 * @returns {Array} Returns `array`.
3899 function arrayPush(array, values) {
3901 length = values.length,
3902 offset = array.length;
3904 while (++index < length) {
3905 array[offset + index] = values[index];
3911 var _arrayPush = arrayPush;
3913 /** Built-in value references. */
3915 var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined;
3917 * Checks if `value` is a flattenable `arguments` object or array.
3920 * @param {*} value The value to check.
3921 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
3924 function isFlattenable(value) {
3925 return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
3928 var _isFlattenable = isFlattenable;
3931 * The base implementation of `_.flatten` with support for restricting flattening.
3934 * @param {Array} array The array to flatten.
3935 * @param {number} depth The maximum recursion depth.
3936 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
3937 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
3938 * @param {Array} [result=[]] The initial result value.
3939 * @returns {Array} Returns the new flattened array.
3942 function baseFlatten(array, depth, predicate, isStrict, result) {
3944 length = array.length;
3945 predicate || (predicate = _isFlattenable);
3946 result || (result = []);
3948 while (++index < length) {
3949 var value = array[index];
3951 if (depth > 0 && predicate(value)) {
3953 // Recursively flatten arrays (susceptible to call stack limits).
3954 baseFlatten(value, depth - 1, predicate, isStrict, result);
3956 _arrayPush(result, value);
3958 } else if (!isStrict) {
3959 result[result.length] = value;
3966 var _baseFlatten = baseFlatten;
3969 * Flattens `array` a single level deep.
3975 * @param {Array} array The array to flatten.
3976 * @returns {Array} Returns the new flattened array.
3979 * _.flatten([1, [2, [3, [4]], 5]]);
3980 * // => [1, 2, [3, [4]], 5]
3983 function flatten(array) {
3984 var length = array == null ? 0 : array.length;
3985 return length ? _baseFlatten(array, 1) : [];
3988 var flatten_1 = flatten;
3991 * A faster alternative to `Function#apply`, this function invokes `func`
3992 * with the `this` binding of `thisArg` and the arguments of `args`.
3995 * @param {Function} func The function to invoke.
3996 * @param {*} thisArg The `this` binding of `func`.
3997 * @param {Array} args The arguments to invoke `func` with.
3998 * @returns {*} Returns the result of `func`.
4000 function apply(func, thisArg, args) {
4001 switch (args.length) {
4003 return func.call(thisArg);
4006 return func.call(thisArg, args[0]);
4009 return func.call(thisArg, args[0], args[1]);
4012 return func.call(thisArg, args[0], args[1], args[2]);
4015 return func.apply(thisArg, args);
4020 /* Built-in method references for those with the same name as other `lodash` methods. */
4022 var nativeMax = Math.max;
4024 * A specialized version of `baseRest` which transforms the rest array.
4027 * @param {Function} func The function to apply a rest parameter to.
4028 * @param {number} [start=func.length-1] The start position of the rest parameter.
4029 * @param {Function} transform The rest array transform.
4030 * @returns {Function} Returns the new function.
4033 function overRest(func, start, transform) {
4034 start = nativeMax(start === undefined ? func.length - 1 : start, 0);
4035 return function () {
4036 var args = arguments,
4038 length = nativeMax(args.length - start, 0),
4039 array = Array(length);
4041 while (++index < length) {
4042 array[index] = args[start + index];
4046 var otherArgs = Array(start + 1);
4048 while (++index < start) {
4049 otherArgs[index] = args[index];
4052 otherArgs[start] = transform(array);
4053 return _apply(func, this, otherArgs);
4057 var _overRest = overRest;
4060 * Creates a function that returns `value`.
4066 * @param {*} value The value to return from the new function.
4067 * @returns {Function} Returns the new constant function.
4070 * var objects = _.times(2, _.constant({ 'a': 1 }));
4072 * console.log(objects);
4073 * // => [{ 'a': 1 }, { 'a': 1 }]
4075 * console.log(objects[0] === objects[1]);
4078 function constant(value) {
4079 return function () {
4084 var constant_1 = constant;
4087 * This method returns the first argument it receives.
4093 * @param {*} value Any value.
4094 * @returns {*} Returns `value`.
4097 * var object = { 'a': 1 };
4099 * console.log(_.identity(object) === object);
4102 function identity(value) {
4106 var identity_1 = identity;
4109 * The base implementation of `setToString` without support for hot loop shorting.
4112 * @param {Function} func The function to modify.
4113 * @param {Function} string The `toString` result.
4114 * @returns {Function} Returns `func`.
4117 var baseSetToString = !_defineProperty ? identity_1 : function (func, string) {
4118 return _defineProperty(func, 'toString', {
4119 'configurable': true,
4120 'enumerable': false,
4121 'value': constant_1(string),
4125 var _baseSetToString = baseSetToString;
4127 /** Used to detect hot functions by number of calls within a span of milliseconds. */
4128 var HOT_COUNT = 800,
4130 /* Built-in method references for those with the same name as other `lodash` methods. */
4132 var nativeNow = Date.now;
4134 * Creates a function that'll short out and invoke `identity` instead
4135 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
4139 * @param {Function} func The function to restrict.
4140 * @returns {Function} Returns the new shortable function.
4143 function shortOut(func) {
4146 return function () {
4147 var stamp = nativeNow(),
4148 remaining = HOT_SPAN - (stamp - lastCalled);
4151 if (remaining > 0) {
4152 if (++count >= HOT_COUNT) {
4153 return arguments[0];
4159 return func.apply(undefined, arguments);
4163 var _shortOut = shortOut;
4166 * Sets the `toString` method of `func` to return `string`.
4169 * @param {Function} func The function to modify.
4170 * @param {Function} string The `toString` result.
4171 * @returns {Function} Returns `func`.
4174 var setToString = _shortOut(_baseSetToString);
4175 var _setToString = setToString;
4178 * A specialized version of `baseRest` which flattens the rest array.
4181 * @param {Function} func The function to apply a rest parameter to.
4182 * @returns {Function} Returns the new function.
4185 function flatRest(func) {
4186 return _setToString(_overRest(func, undefined, flatten_1), func + '');
4189 var _flatRest = flatRest;
4192 * Creates an object composed of the picked `object` properties.
4198 * @param {Object} object The source object.
4199 * @param {...(string|string[])} [paths] The property paths to pick.
4200 * @returns {Object} Returns the new object.
4203 * var object = { 'a': 1, 'b': '2', 'c': 3 };
4205 * _.pick(object, ['a', 'c']);
4206 * // => { 'a': 1, 'c': 3 }
4209 var pick = _flatRest(function (object, paths) {
4210 return object == null ? {} : _basePick(object, paths);
4215 * A specialized version of `baseAggregator` for arrays.
4218 * @param {Array} [array] The array to iterate over.
4219 * @param {Function} setter The function to set `accumulator` values.
4220 * @param {Function} iteratee The iteratee to transform keys.
4221 * @param {Object} accumulator The initial aggregated object.
4222 * @returns {Function} Returns `accumulator`.
4224 function arrayAggregator(array, setter, iteratee, accumulator) {
4226 length = array == null ? 0 : array.length;
4228 while (++index < length) {
4229 var value = array[index];
4230 setter(accumulator, value, iteratee(value), array);
4236 var _arrayAggregator = arrayAggregator;
4239 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
4242 * @param {boolean} [fromRight] Specify iterating from right to left.
4243 * @returns {Function} Returns the new base function.
4245 function createBaseFor(fromRight) {
4246 return function (object, iteratee, keysFunc) {
4248 iterable = Object(object),
4249 props = keysFunc(object),
4250 length = props.length;
4253 var key = props[fromRight ? length : ++index];
4255 if (iteratee(iterable[key], key, iterable) === false) {
4264 var _createBaseFor = createBaseFor;
4267 * The base implementation of `baseForOwn` which iterates over `object`
4268 * properties returned by `keysFunc` and invokes `iteratee` for each property.
4269 * Iteratee functions may exit iteration early by explicitly returning `false`.
4272 * @param {Object} object The object to iterate over.
4273 * @param {Function} iteratee The function invoked per iteration.
4274 * @param {Function} keysFunc The function to get the keys of `object`.
4275 * @returns {Object} Returns `object`.
4278 var baseFor = _createBaseFor();
4279 var _baseFor = baseFor;
4282 * The base implementation of `_.times` without support for iteratee shorthands
4283 * or max array length checks.
4286 * @param {number} n The number of times to invoke `iteratee`.
4287 * @param {Function} iteratee The function invoked per iteration.
4288 * @returns {Array} Returns the array of results.
4290 function baseTimes(n, iteratee) {
4294 while (++index < n) {
4295 result[index] = iteratee(index);
4301 var _baseTimes = baseTimes;
4304 * This method returns `false`.
4310 * @returns {boolean} Returns `false`.
4313 * _.times(2, _.stubFalse);
4314 * // => [false, false]
4316 function stubFalse() {
4320 var stubFalse_1 = stubFalse;
4322 var isBuffer_1 = createCommonjsModule(function (module, exports) {
4323 /** Detect free variable `exports`. */
4324 var freeExports = exports && !exports.nodeType && exports;
4325 /** Detect free variable `module`. */
4327 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
4328 /** Detect the popular CommonJS extension `module.exports`. */
4330 var moduleExports = freeModule && freeModule.exports === freeExports;
4331 /** Built-in value references. */
4333 var Buffer = moduleExports ? _root.Buffer : undefined;
4334 /* Built-in method references for those with the same name as other `lodash` methods. */
4336 var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;
4338 * Checks if `value` is a buffer.
4344 * @param {*} value The value to check.
4345 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
4348 * _.isBuffer(new Buffer(2));
4351 * _.isBuffer(new Uint8Array(2));
4355 var isBuffer = nativeIsBuffer || stubFalse_1;
4356 module.exports = isBuffer;
4359 /** `Object#toString` result references. */
4361 var argsTag$1 = '[object Arguments]',
4362 arrayTag = '[object Array]',
4363 boolTag = '[object Boolean]',
4364 dateTag = '[object Date]',
4365 errorTag = '[object Error]',
4366 funcTag$1 = '[object Function]',
4367 mapTag = '[object Map]',
4368 numberTag = '[object Number]',
4369 objectTag = '[object Object]',
4370 regexpTag = '[object RegExp]',
4371 setTag = '[object Set]',
4372 stringTag = '[object String]',
4373 weakMapTag = '[object WeakMap]';
4374 var arrayBufferTag = '[object ArrayBuffer]',
4375 dataViewTag = '[object DataView]',
4376 float32Tag = '[object Float32Array]',
4377 float64Tag = '[object Float64Array]',
4378 int8Tag = '[object Int8Array]',
4379 int16Tag = '[object Int16Array]',
4380 int32Tag = '[object Int32Array]',
4381 uint8Tag = '[object Uint8Array]',
4382 uint8ClampedTag = '[object Uint8ClampedArray]',
4383 uint16Tag = '[object Uint16Array]',
4384 uint32Tag = '[object Uint32Array]';
4385 /** Used to identify `toStringTag` values of typed arrays. */
4387 var typedArrayTags = {};
4388 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
4389 typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
4391 * The base implementation of `_.isTypedArray` without Node.js optimizations.
4394 * @param {*} value The value to check.
4395 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
4398 function baseIsTypedArray(value) {
4399 return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)];
4402 var _baseIsTypedArray = baseIsTypedArray;
4405 * The base implementation of `_.unary` without support for storing metadata.
4408 * @param {Function} func The function to cap arguments for.
4409 * @returns {Function} Returns the new capped function.
4411 function baseUnary(func) {
4412 return function (value) {
4417 var _baseUnary = baseUnary;
4419 var _nodeUtil = createCommonjsModule(function (module, exports) {
4420 /** Detect free variable `exports`. */
4421 var freeExports = exports && !exports.nodeType && exports;
4422 /** Detect free variable `module`. */
4424 var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
4425 /** Detect the popular CommonJS extension `module.exports`. */
4427 var moduleExports = freeModule && freeModule.exports === freeExports;
4428 /** Detect free variable `process` from Node.js. */
4430 var freeProcess = moduleExports && _freeGlobal.process;
4431 /** Used to access faster Node.js helpers. */
4433 var nodeUtil = function () {
4435 // Use `util.types` for Node.js 10+.
4436 var types = freeModule && freeModule.require && freeModule.require('util').types;
4440 } // Legacy `process.binding('util')` for Node.js < 10.
4443 return freeProcess && freeProcess.binding && freeProcess.binding('util');
4447 module.exports = nodeUtil;
4450 /* Node.js helper references. */
4452 var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray;
4454 * Checks if `value` is classified as a typed array.
4460 * @param {*} value The value to check.
4461 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
4464 * _.isTypedArray(new Uint8Array);
4467 * _.isTypedArray([]);
4471 var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray;
4472 var isTypedArray_1 = isTypedArray;
4474 /** Used for built-in method references. */
4476 var objectProto$7 = Object.prototype;
4477 /** Used to check objects for own properties. */
4479 var hasOwnProperty$6 = objectProto$7.hasOwnProperty;
4481 * Creates an array of the enumerable property names of the array-like `value`.
4484 * @param {*} value The value to query.
4485 * @param {boolean} inherited Specify returning inherited property names.
4486 * @returns {Array} Returns the array of property names.
4489 function arrayLikeKeys(value, inherited) {
4490 var isArr = isArray_1(value),
4491 isArg = !isArr && isArguments_1(value),
4492 isBuff = !isArr && !isArg && isBuffer_1(value),
4493 isType = !isArr && !isArg && !isBuff && isTypedArray_1(value),
4494 skipIndexes = isArr || isArg || isBuff || isType,
4495 result = skipIndexes ? _baseTimes(value.length, String) : [],
4496 length = result.length;
4498 for (var key in value) {
4499 if ((inherited || hasOwnProperty$6.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode.
4500 key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers.
4501 isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays.
4502 isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties.
4503 _isIndex(key, length)))) {
4511 var _arrayLikeKeys = arrayLikeKeys;
4513 /** Used for built-in method references. */
4514 var objectProto$8 = Object.prototype;
4516 * Checks if `value` is likely a prototype object.
4519 * @param {*} value The value to check.
4520 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
4523 function isPrototype(value) {
4524 var Ctor = value && value.constructor,
4525 proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$8;
4526 return value === proto;
4529 var _isPrototype = isPrototype;
4532 * Creates a unary function that invokes `func` with its argument transformed.
4535 * @param {Function} func The function to wrap.
4536 * @param {Function} transform The argument transform.
4537 * @returns {Function} Returns the new function.
4539 function overArg(func, transform) {
4540 return function (arg) {
4541 return func(transform(arg));
4545 var _overArg = overArg;
4547 /* Built-in method references for those with the same name as other `lodash` methods. */
4549 var nativeKeys = _overArg(Object.keys, Object);
4550 var _nativeKeys = nativeKeys;
4552 /** Used for built-in method references. */
4554 var objectProto$9 = Object.prototype;
4555 /** Used to check objects for own properties. */
4557 var hasOwnProperty$7 = objectProto$9.hasOwnProperty;
4559 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
4562 * @param {Object} object The object to query.
4563 * @returns {Array} Returns the array of property names.
4566 function baseKeys(object) {
4567 if (!_isPrototype(object)) {
4568 return _nativeKeys(object);
4573 for (var key in Object(object)) {
4574 if (hasOwnProperty$7.call(object, key) && key != 'constructor') {
4582 var _baseKeys = baseKeys;
4585 * Checks if `value` is array-like. A value is considered array-like if it's
4586 * not a function and has a `value.length` that's an integer greater than or
4587 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
4593 * @param {*} value The value to check.
4594 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
4597 * _.isArrayLike([1, 2, 3]);
4600 * _.isArrayLike(document.body.children);
4603 * _.isArrayLike('abc');
4606 * _.isArrayLike(_.noop);
4610 function isArrayLike(value) {
4611 return value != null && isLength_1(value.length) && !isFunction_1(value);
4614 var isArrayLike_1 = isArrayLike;
4617 * Creates an array of the own enumerable property names of `object`.
4619 * **Note:** Non-object values are coerced to objects. See the
4620 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
4627 * @param {Object} object The object to query.
4628 * @returns {Array} Returns the array of property names.
4636 * Foo.prototype.c = 3;
4639 * // => ['a', 'b'] (iteration order is not guaranteed)
4645 function keys(object) {
4646 return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object);
4652 * The base implementation of `_.forOwn` without support for iteratee shorthands.
4655 * @param {Object} object The object to iterate over.
4656 * @param {Function} iteratee The function invoked per iteration.
4657 * @returns {Object} Returns `object`.
4660 function baseForOwn(object, iteratee) {
4661 return object && _baseFor(object, iteratee, keys_1);
4664 var _baseForOwn = baseForOwn;
4667 * Creates a `baseEach` or `baseEachRight` function.
4670 * @param {Function} eachFunc The function to iterate over a collection.
4671 * @param {boolean} [fromRight] Specify iterating from right to left.
4672 * @returns {Function} Returns the new base function.
4675 function createBaseEach(eachFunc, fromRight) {
4676 return function (collection, iteratee) {
4677 if (collection == null) {
4681 if (!isArrayLike_1(collection)) {
4682 return eachFunc(collection, iteratee);
4685 var length = collection.length,
4686 index = fromRight ? length : -1,
4687 iterable = Object(collection);
4689 while (fromRight ? index-- : ++index < length) {
4690 if (iteratee(iterable[index], index, iterable) === false) {
4699 var _createBaseEach = createBaseEach;
4702 * The base implementation of `_.forEach` without support for iteratee shorthands.
4705 * @param {Array|Object} collection The collection to iterate over.
4706 * @param {Function} iteratee The function invoked per iteration.
4707 * @returns {Array|Object} Returns `collection`.
4710 var baseEach = _createBaseEach(_baseForOwn);
4711 var _baseEach = baseEach;
4714 * Aggregates elements of `collection` on `accumulator` with keys transformed
4715 * by `iteratee` and values set by `setter`.
4718 * @param {Array|Object} collection The collection to iterate over.
4719 * @param {Function} setter The function to set `accumulator` values.
4720 * @param {Function} iteratee The iteratee to transform keys.
4721 * @param {Object} accumulator The initial aggregated object.
4722 * @returns {Function} Returns `accumulator`.
4725 function baseAggregator(collection, setter, iteratee, accumulator) {
4726 _baseEach(collection, function (value, key, collection) {
4727 setter(accumulator, value, iteratee(value), collection);
4732 var _baseAggregator = baseAggregator;
4735 * Removes all key-value entries from the stack.
4742 function stackClear() {
4743 this.__data__ = new _ListCache();
4747 var _stackClear = stackClear;
4750 * Removes `key` and its value from the stack.
4755 * @param {string} key The key of the value to remove.
4756 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
4758 function stackDelete(key) {
4759 var data = this.__data__,
4760 result = data['delete'](key);
4761 this.size = data.size;
4765 var _stackDelete = stackDelete;
4768 * Gets the stack value for `key`.
4773 * @param {string} key The key of the value to get.
4774 * @returns {*} Returns the entry value.
4776 function stackGet(key) {
4777 return this.__data__.get(key);
4780 var _stackGet = stackGet;
4783 * Checks if a stack value for `key` exists.
4788 * @param {string} key The key of the entry to check.
4789 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
4791 function stackHas(key) {
4792 return this.__data__.has(key);
4795 var _stackHas = stackHas;
4797 /** Used as the size to enable large array optimizations. */
4799 var LARGE_ARRAY_SIZE = 200;
4801 * Sets the stack `key` to `value`.
4806 * @param {string} key The key of the value to set.
4807 * @param {*} value The value to set.
4808 * @returns {Object} Returns the stack cache instance.
4811 function stackSet(key, value) {
4812 var data = this.__data__;
4814 if (data instanceof _ListCache) {
4815 var pairs = data.__data__;
4817 if (!_Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
4818 pairs.push([key, value]);
4819 this.size = ++data.size;
4823 data = this.__data__ = new _MapCache(pairs);
4826 data.set(key, value);
4827 this.size = data.size;
4831 var _stackSet = stackSet;
4834 * Creates a stack cache object to store key-value pairs.
4838 * @param {Array} [entries] The key-value pairs to cache.
4841 function Stack(entries) {
4842 var data = this.__data__ = new _ListCache(entries);
4843 this.size = data.size;
4844 } // Add methods to `Stack`.
4847 Stack.prototype.clear = _stackClear;
4848 Stack.prototype['delete'] = _stackDelete;
4849 Stack.prototype.get = _stackGet;
4850 Stack.prototype.has = _stackHas;
4851 Stack.prototype.set = _stackSet;
4854 /** Used to stand-in for `undefined` hash values. */
4855 var HASH_UNDEFINED$2 = '__lodash_hash_undefined__';
4857 * Adds `value` to the array cache.
4861 * @memberOf SetCache
4863 * @param {*} value The value to cache.
4864 * @returns {Object} Returns the cache instance.
4867 function setCacheAdd(value) {
4868 this.__data__.set(value, HASH_UNDEFINED$2);
4873 var _setCacheAdd = setCacheAdd;
4876 * Checks if `value` is in the array cache.
4880 * @memberOf SetCache
4881 * @param {*} value The value to search for.
4882 * @returns {number} Returns `true` if `value` is found, else `false`.
4884 function setCacheHas(value) {
4885 return this.__data__.has(value);
4888 var _setCacheHas = setCacheHas;
4892 * Creates an array cache object to store unique values.
4896 * @param {Array} [values] The values to cache.
4899 function SetCache(values) {
4901 length = values == null ? 0 : values.length;
4902 this.__data__ = new _MapCache();
4904 while (++index < length) {
4905 this.add(values[index]);
4907 } // Add methods to `SetCache`.
4910 SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd;
4911 SetCache.prototype.has = _setCacheHas;
4912 var _SetCache = SetCache;
4915 * A specialized version of `_.some` for arrays without support for iteratee
4919 * @param {Array} [array] The array to iterate over.
4920 * @param {Function} predicate The function invoked per iteration.
4921 * @returns {boolean} Returns `true` if any element passes the predicate check,
4924 function arraySome(array, predicate) {
4926 length = array == null ? 0 : array.length;
4928 while (++index < length) {
4929 if (predicate(array[index], index, array)) {
4937 var _arraySome = arraySome;
4940 * Checks if a `cache` value for `key` exists.
4943 * @param {Object} cache The cache to query.
4944 * @param {string} key The key of the entry to check.
4945 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
4947 function cacheHas(cache, key) {
4948 return cache.has(key);
4951 var _cacheHas = cacheHas;
4953 /** Used to compose bitmasks for value comparisons. */
4955 var COMPARE_PARTIAL_FLAG = 1,
4956 COMPARE_UNORDERED_FLAG = 2;
4958 * A specialized version of `baseIsEqualDeep` for arrays with support for
4959 * partial deep comparisons.
4962 * @param {Array} array The array to compare.
4963 * @param {Array} other The other array to compare.
4964 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
4965 * @param {Function} customizer The function to customize comparisons.
4966 * @param {Function} equalFunc The function to determine equivalents of values.
4967 * @param {Object} stack Tracks traversed `array` and `other` objects.
4968 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
4971 function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
4972 var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
4973 arrLength = array.length,
4974 othLength = other.length;
4976 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
4978 } // Check that cyclic values are equal.
4981 var arrStacked = stack.get(array);
4982 var othStacked = stack.get(other);
4984 if (arrStacked && othStacked) {
4985 return arrStacked == other && othStacked == array;
4990 seen = bitmask & COMPARE_UNORDERED_FLAG ? new _SetCache() : undefined;
4991 stack.set(array, other);
4992 stack.set(other, array); // Ignore non-index properties.
4994 while (++index < arrLength) {
4995 var arrValue = array[index],
4996 othValue = other[index];
4999 var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
5002 if (compared !== undefined) {
5009 } // Recursively compare arrays (susceptible to call stack limits).
5013 if (!_arraySome(other, function (othValue, othIndex) {
5014 if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
5015 return seen.push(othIndex);
5021 } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
5027 stack['delete'](array);
5028 stack['delete'](other);
5032 var _equalArrays = equalArrays;
5034 /** Built-in value references. */
5036 var Uint8Array = _root.Uint8Array;
5037 var _Uint8Array = Uint8Array;
5040 * Converts `map` to its key-value pairs.
5043 * @param {Object} map The map to convert.
5044 * @returns {Array} Returns the key-value pairs.
5046 function mapToArray(map) {
5048 result = Array(map.size);
5049 map.forEach(function (value, key) {
5050 result[++index] = [key, value];
5055 var _mapToArray = mapToArray;
5058 * Converts `set` to an array of its values.
5061 * @param {Object} set The set to convert.
5062 * @returns {Array} Returns the values.
5064 function setToArray(set) {
5066 result = Array(set.size);
5067 set.forEach(function (value) {
5068 result[++index] = value;
5073 var _setToArray = setToArray;
5075 /** Used to compose bitmasks for value comparisons. */
5077 var COMPARE_PARTIAL_FLAG$1 = 1,
5078 COMPARE_UNORDERED_FLAG$1 = 2;
5079 /** `Object#toString` result references. */
5081 var boolTag$1 = '[object Boolean]',
5082 dateTag$1 = '[object Date]',
5083 errorTag$1 = '[object Error]',
5084 mapTag$1 = '[object Map]',
5085 numberTag$1 = '[object Number]',
5086 regexpTag$1 = '[object RegExp]',
5087 setTag$1 = '[object Set]',
5088 stringTag$1 = '[object String]',
5089 symbolTag$1 = '[object Symbol]';
5090 var arrayBufferTag$1 = '[object ArrayBuffer]',
5091 dataViewTag$1 = '[object DataView]';
5092 /** Used to convert symbols to primitives and strings. */
5094 var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined,
5095 symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined;
5097 * A specialized version of `baseIsEqualDeep` for comparing objects of
5098 * the same `toStringTag`.
5100 * **Note:** This function only supports comparing values with tags of
5101 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
5104 * @param {Object} object The object to compare.
5105 * @param {Object} other The other object to compare.
5106 * @param {string} tag The `toStringTag` of the objects to compare.
5107 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
5108 * @param {Function} customizer The function to customize comparisons.
5109 * @param {Function} equalFunc The function to determine equivalents of values.
5110 * @param {Object} stack Tracks traversed `object` and `other` objects.
5111 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
5114 function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
5117 if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
5121 object = object.buffer;
5122 other = other.buffer;
5124 case arrayBufferTag$1:
5125 if (object.byteLength != other.byteLength || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) {
5134 // Coerce booleans to `1` or `0` and dates to milliseconds.
5135 // Invalid dates are coerced to `NaN`.
5136 return eq_1(+object, +other);
5139 return object.name == other.name && object.message == other.message;
5143 // Coerce regexes to strings and treat strings, primitives and objects,
5144 // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
5145 // for more details.
5146 return object == other + '';
5149 var convert = _mapToArray;
5152 var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1;
5153 convert || (convert = _setToArray);
5155 if (object.size != other.size && !isPartial) {
5157 } // Assume cyclic values are equal.
5160 var stacked = stack.get(object);
5163 return stacked == other;
5166 bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits).
5168 stack.set(object, other);
5169 var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
5170 stack['delete'](object);
5174 if (symbolValueOf) {
5175 return symbolValueOf.call(object) == symbolValueOf.call(other);
5183 var _equalByTag = equalByTag;
5186 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
5187 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
5188 * symbols of `object`.
5191 * @param {Object} object The object to query.
5192 * @param {Function} keysFunc The function to get the keys of `object`.
5193 * @param {Function} symbolsFunc The function to get the symbols of `object`.
5194 * @returns {Array} Returns the array of property names and symbols.
5197 function baseGetAllKeys(object, keysFunc, symbolsFunc) {
5198 var result = keysFunc(object);
5199 return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object));
5202 var _baseGetAllKeys = baseGetAllKeys;
5205 * A specialized version of `_.filter` for arrays without support for
5206 * iteratee shorthands.
5209 * @param {Array} [array] The array to iterate over.
5210 * @param {Function} predicate The function invoked per iteration.
5211 * @returns {Array} Returns the new filtered array.
5213 function arrayFilter(array, predicate) {
5215 length = array == null ? 0 : array.length,
5219 while (++index < length) {
5220 var value = array[index];
5222 if (predicate(value, index, array)) {
5223 result[resIndex++] = value;
5230 var _arrayFilter = arrayFilter;
5233 * This method returns a new empty array.
5239 * @returns {Array} Returns the new empty array.
5242 * var arrays = _.times(2, _.stubArray);
5244 * console.log(arrays);
5247 * console.log(arrays[0] === arrays[1]);
5250 function stubArray() {
5254 var stubArray_1 = stubArray;
5256 /** Used for built-in method references. */
5258 var objectProto$a = Object.prototype;
5259 /** Built-in value references. */
5261 var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable;
5262 /* Built-in method references for those with the same name as other `lodash` methods. */
5264 var nativeGetSymbols = Object.getOwnPropertySymbols;
5266 * Creates an array of the own enumerable symbols of `object`.
5269 * @param {Object} object The object to query.
5270 * @returns {Array} Returns the array of symbols.
5273 var getSymbols = !nativeGetSymbols ? stubArray_1 : function (object) {
5274 if (object == null) {
5278 object = Object(object);
5279 return _arrayFilter(nativeGetSymbols(object), function (symbol) {
5280 return propertyIsEnumerable$1.call(object, symbol);
5283 var _getSymbols = getSymbols;
5286 * Creates an array of own enumerable property names and symbols of `object`.
5289 * @param {Object} object The object to query.
5290 * @returns {Array} Returns the array of property names and symbols.
5293 function getAllKeys(object) {
5294 return _baseGetAllKeys(object, keys_1, _getSymbols);
5297 var _getAllKeys = getAllKeys;
5299 /** Used to compose bitmasks for value comparisons. */
5301 var COMPARE_PARTIAL_FLAG$2 = 1;
5302 /** Used for built-in method references. */
5304 var objectProto$b = Object.prototype;
5305 /** Used to check objects for own properties. */
5307 var hasOwnProperty$8 = objectProto$b.hasOwnProperty;
5309 * A specialized version of `baseIsEqualDeep` for objects with support for
5310 * partial deep comparisons.
5313 * @param {Object} object The object to compare.
5314 * @param {Object} other The other object to compare.
5315 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
5316 * @param {Function} customizer The function to customize comparisons.
5317 * @param {Function} equalFunc The function to determine equivalents of values.
5318 * @param {Object} stack Tracks traversed `object` and `other` objects.
5319 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
5322 function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
5323 var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2,
5324 objProps = _getAllKeys(object),
5325 objLength = objProps.length,
5326 othProps = _getAllKeys(other),
5327 othLength = othProps.length;
5329 if (objLength != othLength && !isPartial) {
5333 var index = objLength;
5336 var key = objProps[index];
5338 if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) {
5341 } // Check that cyclic values are equal.
5344 var objStacked = stack.get(object);
5345 var othStacked = stack.get(other);
5347 if (objStacked && othStacked) {
5348 return objStacked == other && othStacked == object;
5352 stack.set(object, other);
5353 stack.set(other, object);
5354 var skipCtor = isPartial;
5356 while (++index < objLength) {
5357 key = objProps[index];
5358 var objValue = object[key],
5359 othValue = other[key];
5362 var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
5363 } // Recursively compare objects (susceptible to call stack limits).
5366 if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
5371 skipCtor || (skipCtor = key == 'constructor');
5374 if (result && !skipCtor) {
5375 var objCtor = object.constructor,
5376 othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal.
5378 if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {
5383 stack['delete'](object);
5384 stack['delete'](other);
5388 var _equalObjects = equalObjects;
5390 /* Built-in method references that are verified to be native. */
5392 var DataView = _getNative(_root, 'DataView');
5393 var _DataView = DataView;
5395 /* Built-in method references that are verified to be native. */
5397 var Promise$1 = _getNative(_root, 'Promise');
5398 var _Promise = Promise$1;
5400 /* Built-in method references that are verified to be native. */
5402 var Set$1 = _getNative(_root, 'Set');
5405 /* Built-in method references that are verified to be native. */
5407 var WeakMap$1 = _getNative(_root, 'WeakMap');
5408 var _WeakMap = WeakMap$1;
5410 /** `Object#toString` result references. */
5412 var mapTag$2 = '[object Map]',
5413 objectTag$1 = '[object Object]',
5414 promiseTag = '[object Promise]',
5415 setTag$2 = '[object Set]',
5416 weakMapTag$1 = '[object WeakMap]';
5417 var dataViewTag$2 = '[object DataView]';
5418 /** Used to detect maps, sets, and weakmaps. */
5420 var dataViewCtorString = _toSource(_DataView),
5421 mapCtorString = _toSource(_Map),
5422 promiseCtorString = _toSource(_Promise),
5423 setCtorString = _toSource(_Set),
5424 weakMapCtorString = _toSource(_WeakMap);
5426 * Gets the `toStringTag` of `value`.
5429 * @param {*} value The value to query.
5430 * @returns {string} Returns the `toStringTag`.
5433 var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
5435 if (_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2 || _Map && getTag(new _Map()) != mapTag$2 || _Promise && getTag(_Promise.resolve()) != promiseTag || _Set && getTag(new _Set()) != setTag$2 || _WeakMap && getTag(new _WeakMap()) != weakMapTag$1) {
5436 getTag = function (value) {
5437 var result = _baseGetTag(value),
5438 Ctor = result == objectTag$1 ? value.constructor : undefined,
5439 ctorString = Ctor ? _toSource(Ctor) : '';
5442 switch (ctorString) {
5443 case dataViewCtorString:
5444 return dataViewTag$2;
5449 case promiseCtorString:
5455 case weakMapCtorString:
5456 return weakMapTag$1;
5464 var _getTag = getTag;
5466 /** Used to compose bitmasks for value comparisons. */
5468 var COMPARE_PARTIAL_FLAG$3 = 1;
5469 /** `Object#toString` result references. */
5471 var argsTag$2 = '[object Arguments]',
5472 arrayTag$1 = '[object Array]',
5473 objectTag$2 = '[object Object]';
5474 /** Used for built-in method references. */
5476 var objectProto$c = Object.prototype;
5477 /** Used to check objects for own properties. */
5479 var hasOwnProperty$9 = objectProto$c.hasOwnProperty;
5481 * A specialized version of `baseIsEqual` for arrays and objects which performs
5482 * deep comparisons and tracks traversed objects enabling objects with circular
5483 * references to be compared.
5486 * @param {Object} object The object to compare.
5487 * @param {Object} other The other object to compare.
5488 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
5489 * @param {Function} customizer The function to customize comparisons.
5490 * @param {Function} equalFunc The function to determine equivalents of values.
5491 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
5492 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
5495 function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
5496 var objIsArr = isArray_1(object),
5497 othIsArr = isArray_1(other),
5498 objTag = objIsArr ? arrayTag$1 : _getTag(object),
5499 othTag = othIsArr ? arrayTag$1 : _getTag(other);
5500 objTag = objTag == argsTag$2 ? objectTag$2 : objTag;
5501 othTag = othTag == argsTag$2 ? objectTag$2 : othTag;
5502 var objIsObj = objTag == objectTag$2,
5503 othIsObj = othTag == objectTag$2,
5504 isSameTag = objTag == othTag;
5506 if (isSameTag && isBuffer_1(object)) {
5507 if (!isBuffer_1(other)) {
5515 if (isSameTag && !objIsObj) {
5516 stack || (stack = new _Stack());
5517 return objIsArr || isTypedArray_1(object) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
5520 if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) {
5521 var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'),
5522 othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__');
5524 if (objIsWrapped || othIsWrapped) {
5525 var objUnwrapped = objIsWrapped ? object.value() : object,
5526 othUnwrapped = othIsWrapped ? other.value() : other;
5527 stack || (stack = new _Stack());
5528 return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
5536 stack || (stack = new _Stack());
5537 return _equalObjects(object, other, bitmask, customizer, equalFunc, stack);
5540 var _baseIsEqualDeep = baseIsEqualDeep;
5543 * The base implementation of `_.isEqual` which supports partial comparisons
5544 * and tracks traversed objects.
5547 * @param {*} value The value to compare.
5548 * @param {*} other The other value to compare.
5549 * @param {boolean} bitmask The bitmask flags.
5550 * 1 - Unordered comparison
5551 * 2 - Partial comparison
5552 * @param {Function} [customizer] The function to customize comparisons.
5553 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
5554 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
5557 function baseIsEqual(value, other, bitmask, customizer, stack) {
5558 if (value === other) {
5562 if (value == null || other == null || !isObjectLike_1(value) && !isObjectLike_1(other)) {
5563 return value !== value && other !== other;
5566 return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
5569 var _baseIsEqual = baseIsEqual;
5571 /** Used to compose bitmasks for value comparisons. */
5573 var COMPARE_PARTIAL_FLAG$4 = 1,
5574 COMPARE_UNORDERED_FLAG$2 = 2;
5576 * The base implementation of `_.isMatch` without support for iteratee shorthands.
5579 * @param {Object} object The object to inspect.
5580 * @param {Object} source The object of property values to match.
5581 * @param {Array} matchData The property names, values, and compare flags to match.
5582 * @param {Function} [customizer] The function to customize comparisons.
5583 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
5586 function baseIsMatch(object, source, matchData, customizer) {
5587 var index = matchData.length,
5589 noCustomizer = !customizer;
5591 if (object == null) {
5595 object = Object(object);
5598 var data = matchData[index];
5600 if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
5605 while (++index < length) {
5606 data = matchData[index];
5608 objValue = object[key],
5611 if (noCustomizer && data[2]) {
5612 if (objValue === undefined && !(key in object)) {
5616 var stack = new _Stack();
5619 var result = customizer(objValue, srcValue, key, object, source, stack);
5622 if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result)) {
5631 var _baseIsMatch = baseIsMatch;
5634 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
5637 * @param {*} value The value to check.
5638 * @returns {boolean} Returns `true` if `value` if suitable for strict
5639 * equality comparisons, else `false`.
5642 function isStrictComparable(value) {
5643 return value === value && !isObject_1(value);
5646 var _isStrictComparable = isStrictComparable;
5649 * Gets the property names, values, and compare flags of `object`.
5652 * @param {Object} object The object to query.
5653 * @returns {Array} Returns the match data of `object`.
5656 function getMatchData(object) {
5657 var result = keys_1(object),
5658 length = result.length;
5661 var key = result[length],
5662 value = object[key];
5663 result[length] = [key, value, _isStrictComparable(value)];
5669 var _getMatchData = getMatchData;
5672 * A specialized version of `matchesProperty` for source values suitable
5673 * for strict equality comparisons, i.e. `===`.
5676 * @param {string} key The key of the property to get.
5677 * @param {*} srcValue The value to match.
5678 * @returns {Function} Returns the new spec function.
5680 function matchesStrictComparable(key, srcValue) {
5681 return function (object) {
5682 if (object == null) {
5686 return object[key] === srcValue && (srcValue !== undefined || key in Object(object));
5690 var _matchesStrictComparable = matchesStrictComparable;
5693 * The base implementation of `_.matches` which doesn't clone `source`.
5696 * @param {Object} source The object of property values to match.
5697 * @returns {Function} Returns the new spec function.
5700 function baseMatches(source) {
5701 var matchData = _getMatchData(source);
5703 if (matchData.length == 1 && matchData[0][2]) {
5704 return _matchesStrictComparable(matchData[0][0], matchData[0][1]);
5707 return function (object) {
5708 return object === source || _baseIsMatch(object, source, matchData);
5712 var _baseMatches = baseMatches;
5715 * Gets the value at `path` of `object`. If the resolved value is
5716 * `undefined`, the `defaultValue` is returned in its place.
5722 * @param {Object} object The object to query.
5723 * @param {Array|string} path The path of the property to get.
5724 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
5725 * @returns {*} Returns the resolved value.
5728 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
5730 * _.get(object, 'a[0].b.c');
5733 * _.get(object, ['a', '0', 'b', 'c']);
5736 * _.get(object, 'a.b.c', 'default');
5740 function get(object, path, defaultValue) {
5741 var result = object == null ? undefined : _baseGet(object, path);
5742 return result === undefined ? defaultValue : result;
5747 /** Used to compose bitmasks for value comparisons. */
5749 var COMPARE_PARTIAL_FLAG$5 = 1,
5750 COMPARE_UNORDERED_FLAG$3 = 2;
5752 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
5755 * @param {string} path The path of the property to get.
5756 * @param {*} srcValue The value to match.
5757 * @returns {Function} Returns the new spec function.
5760 function baseMatchesProperty(path, srcValue) {
5761 if (_isKey(path) && _isStrictComparable(srcValue)) {
5762 return _matchesStrictComparable(_toKey(path), srcValue);
5765 return function (object) {
5766 var objValue = get_1(object, path);
5767 return objValue === undefined && objValue === srcValue ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3);
5771 var _baseMatchesProperty = baseMatchesProperty;
5774 * The base implementation of `_.property` without support for deep paths.
5777 * @param {string} key The key of the property to get.
5778 * @returns {Function} Returns the new accessor function.
5780 function baseProperty(key) {
5781 return function (object) {
5782 return object == null ? undefined : object[key];
5786 var _baseProperty = baseProperty;
5789 * A specialized version of `baseProperty` which supports deep paths.
5792 * @param {Array|string} path The path of the property to get.
5793 * @returns {Function} Returns the new accessor function.
5796 function basePropertyDeep(path) {
5797 return function (object) {
5798 return _baseGet(object, path);
5802 var _basePropertyDeep = basePropertyDeep;
5805 * Creates a function that returns the value at `path` of a given object.
5811 * @param {Array|string} path The path of the property to get.
5812 * @returns {Function} Returns the new accessor function.
5816 * { 'a': { 'b': 2 } },
5817 * { 'a': { 'b': 1 } }
5820 * _.map(objects, _.property('a.b'));
5823 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
5827 function property(path) {
5828 return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path);
5831 var property_1 = property;
5834 * The base implementation of `_.iteratee`.
5837 * @param {*} [value=_.identity] The value to convert to an iteratee.
5838 * @returns {Function} Returns the iteratee.
5841 function baseIteratee(value) {
5842 // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
5843 // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
5844 if (typeof value == 'function') {
5848 if (value == null) {
5852 if (typeof value == 'object') {
5853 return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value);
5856 return property_1(value);
5859 var _baseIteratee = baseIteratee;
5862 * Creates a function like `_.groupBy`.
5865 * @param {Function} setter The function to set accumulator values.
5866 * @param {Function} [initializer] The accumulator object initializer.
5867 * @returns {Function} Returns the new aggregator function.
5870 function createAggregator(setter, initializer) {
5871 return function (collection, iteratee) {
5872 var func = isArray_1(collection) ? _arrayAggregator : _baseAggregator,
5873 accumulator = initializer ? initializer() : {};
5874 return func(collection, setter, _baseIteratee(iteratee), accumulator);
5878 var _createAggregator = createAggregator;
5880 /** Used for built-in method references. */
5882 var objectProto$d = Object.prototype;
5883 /** Used to check objects for own properties. */
5885 var hasOwnProperty$a = objectProto$d.hasOwnProperty;
5887 * Creates an object composed of keys generated from the results of running
5888 * each element of `collection` thru `iteratee`. The order of grouped values
5889 * is determined by the order they occur in `collection`. The corresponding
5890 * value of each key is an array of elements responsible for generating the
5891 * key. The iteratee is invoked with one argument: (value).
5896 * @category Collection
5897 * @param {Array|Object} collection The collection to iterate over.
5898 * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
5899 * @returns {Object} Returns the composed aggregate object.
5902 * _.groupBy([6.1, 4.2, 6.3], Math.floor);
5903 * // => { '4': [4.2], '6': [6.1, 6.3] }
5905 * // The `_.property` iteratee shorthand.
5906 * _.groupBy(['one', 'two', 'three'], 'length');
5907 * // => { '3': ['one', 'two'], '5': ['three'] }
5910 var groupBy = _createAggregator(function (result, value, key) {
5911 if (hasOwnProperty$a.call(result, key)) {
5912 result[key].push(value);
5914 _baseAssignValue(result, key, [value]);
5917 var groupBy_1 = groupBy;
5920 * Creates an array of elements split into two groups, the first of which
5921 * contains elements `predicate` returns truthy for, the second of which
5922 * contains elements `predicate` returns falsey for. The predicate is
5923 * invoked with one argument: (value).
5928 * @category Collection
5929 * @param {Array|Object} collection The collection to iterate over.
5930 * @param {Function} [predicate=_.identity] The function invoked per iteration.
5931 * @returns {Array} Returns the array of grouped elements.
5935 * { 'user': 'barney', 'age': 36, 'active': false },
5936 * { 'user': 'fred', 'age': 40, 'active': true },
5937 * { 'user': 'pebbles', 'age': 1, 'active': false }
5940 * _.partition(users, function(o) { return o.active; });
5941 * // => objects for [['fred'], ['barney', 'pebbles']]
5943 * // The `_.matches` iteratee shorthand.
5944 * _.partition(users, { 'age': 1, 'active': false });
5945 * // => objects for [['pebbles'], ['barney', 'fred']]
5947 * // The `_.matchesProperty` iteratee shorthand.
5948 * _.partition(users, ['active', false]);
5949 * // => objects for [['barney', 'pebbles'], ['fred']]
5951 * // The `_.property` iteratee shorthand.
5952 * _.partition(users, 'active');
5953 * // => objects for [['fred'], ['barney', 'pebbles']]
5956 var partition = _createAggregator(function (result, value, key) {
5957 result[key ? 0 : 1].push(value);
5961 var partition_1 = partition;
5963 var thirdParty = require("./third-party");
5965 var prettierInternal = src.__internal;
5967 var minimist = function (args, opts) {
5968 if (!opts) opts = {};
5975 if (typeof opts['unknown'] === 'function') {
5976 flags.unknownFn = opts['unknown'];
5979 if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
5980 flags.allBools = true;
5982 [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
5983 flags.bools[key] = true;
5988 Object.keys(opts.alias || {}).forEach(function (key) {
5989 aliases[key] = [].concat(opts.alias[key]);
5990 aliases[key].forEach(function (x) {
5991 aliases[x] = [key].concat(aliases[key].filter(function (y) {
5996 [].concat(opts.string).filter(Boolean).forEach(function (key) {
5997 flags.strings[key] = true;
6000 flags.strings[aliases[key]] = true;
6003 var defaults = opts['default'] || {};
6007 Object.keys(flags.bools).forEach(function (key) {
6008 setArg(key, defaults[key] === undefined ? false : defaults[key]);
6012 if (args.indexOf('--') !== -1) {
6013 notFlags = args.slice(args.indexOf('--') + 1);
6014 args = args.slice(0, args.indexOf('--'));
6017 function argDefined(key, arg) {
6018 return flags.allBools && /^--[^=]+$/.test(arg) || flags.strings[key] || flags.bools[key] || aliases[key];
6021 function setArg(key, val, arg) {
6022 if (arg && flags.unknownFn && !argDefined(key, arg)) {
6023 if (flags.unknownFn(arg) === false) return;
6026 var value = !flags.strings[key] && isNumber(val) ? Number(val) : val;
6027 setKey(argv, key.split('.'), value);
6028 (aliases[key] || []).forEach(function (x) {
6029 setKey(argv, x.split('.'), value);
6033 function setKey(obj, keys, value) {
6036 for (var i = 0; i < keys.length - 1; i++) {
6038 if (key === '__proto__') return;
6039 if (o[key] === undefined) o[key] = {};
6040 if (o[key] === Object.prototype || o[key] === Number.prototype || o[key] === String.prototype) o[key] = {};
6041 if (o[key] === Array.prototype) o[key] = [];
6045 var key = keys[keys.length - 1];
6046 if (key === '__proto__') return;
6047 if (o === Object.prototype || o === Number.prototype || o === String.prototype) o = {};
6048 if (o === Array.prototype) o = [];
6050 if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
6052 } else if (Array.isArray(o[key])) {
6055 o[key] = [o[key], value];
6059 function aliasIsBoolean(key) {
6060 return aliases[key].some(function (x) {
6061 return flags.bools[x];
6065 for (var i = 0; i < args.length; i++) {
6068 if (/^--.+=/.test(arg)) {
6069 // Using [\s\S] instead of . because js doesn't support the
6070 // 'dotall' regex modifier. See:
6071 // http://stackoverflow.com/a/1068308/13216
6072 var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
6076 if (flags.bools[key]) {
6077 value = value !== 'false';
6080 setArg(key, value, arg);
6081 } else if (/^--no-.+/.test(arg)) {
6082 var key = arg.match(/^--no-(.+)/)[1];
6083 setArg(key, false, arg);
6084 } else if (/^--.+/.test(arg)) {
6085 var key = arg.match(/^--(.+)/)[1];
6086 var next = args[i + 1];
6088 if (next !== undefined && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) {
6089 setArg(key, next, arg);
6091 } else if (/^(true|false)$/.test(next)) {
6092 setArg(key, next === 'true', arg);
6095 setArg(key, flags.strings[key] ? '' : true, arg);
6097 } else if (/^-[^-]+/.test(arg)) {
6098 var letters = arg.slice(1, -1).split('');
6101 for (var j = 0; j < letters.length; j++) {
6102 var next = arg.slice(j + 2);
6105 setArg(letters[j], next, arg);
6109 if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
6110 setArg(letters[j], next.split('=')[1], arg);
6115 if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
6116 setArg(letters[j], next, arg);
6121 if (letters[j + 1] && letters[j + 1].match(/\W/)) {
6122 setArg(letters[j], arg.slice(j + 2), arg);
6126 setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
6130 var key = arg.slice(-1)[0];
6132 if (!broken && key !== '-') {
6133 if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) {
6134 setArg(key, args[i + 1], arg);
6136 } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) {
6137 setArg(key, args[i + 1] === 'true', arg);
6140 setArg(key, flags.strings[key] ? '' : true, arg);
6144 if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
6145 argv._.push(flags.strings['_'] || !isNumber(arg) ? arg : Number(arg));
6148 if (opts.stopEarly) {
6149 argv._.push.apply(argv._, args.slice(i + 1));
6156 Object.keys(defaults).forEach(function (key) {
6157 if (!hasKey(argv, key.split('.'))) {
6158 setKey(argv, key.split('.'), defaults[key]);
6159 (aliases[key] || []).forEach(function (x) {
6160 setKey(argv, x.split('.'), defaults[key]);
6166 argv['--'] = new Array();
6167 notFlags.forEach(function (key) {
6168 argv['--'].push(key);
6171 notFlags.forEach(function (key) {
6179 function hasKey(obj, keys) {
6181 keys.slice(0, -1).forEach(function (key) {
6184 var key = keys[keys.length - 1];
6188 function isNumber(x) {
6189 if (typeof x === 'number') return true;
6190 if (/^0x[0-9a-f]+$/i.test(x)) return true;
6191 return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
6194 const PLACEHOLDER = null;
6196 * unspecified boolean flag without default value is parsed as `undefined` instead of `false`
6199 var minimist_1 = function (args, options) {
6200 const boolean = options.boolean || [];
6201 const defaults = options.default || {};
6202 const booleanWithoutDefault = boolean.filter(key => !(key in defaults));
6203 const newDefaults = Object.assign({}, defaults, fromPairs_1(booleanWithoutDefault.map(key => [key, PLACEHOLDER])));
6204 const parsed = minimist(args, Object.assign({}, options, {
6205 default: newDefaults
6207 return fromPairs_1(Object.entries(parsed).filter(([, value]) => value !== PLACEHOLDER));
6210 var array = createCommonjsModule(function (module, exports) {
6212 Object.defineProperty(exports, "__esModule", {
6215 exports.splitWhen = exports.flatten = void 0;
6217 function flatten(items) {
6218 return items.reduce((collection, item) => [].concat(collection, item), []);
6221 exports.flatten = flatten;
6223 function splitWhen(items, predicate) {
6224 const result = [[]];
6227 for (const item of items) {
6228 if (predicate(item)) {
6230 result[groupIndex] = [];
6232 result[groupIndex].push(item);
6239 exports.splitWhen = splitWhen;
6242 var errno = createCommonjsModule(function (module, exports) {
6244 Object.defineProperty(exports, "__esModule", {
6247 exports.isEnoentCodeError = void 0;
6249 function isEnoentCodeError(error) {
6250 return error.code === 'ENOENT';
6253 exports.isEnoentCodeError = isEnoentCodeError;
6256 var fs = createCommonjsModule(function (module, exports) {
6258 Object.defineProperty(exports, "__esModule", {
6261 exports.createDirentFromStats = void 0;
6263 class DirentFromStats {
6264 constructor(name, stats) {
6266 this.isBlockDevice = stats.isBlockDevice.bind(stats);
6267 this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
6268 this.isDirectory = stats.isDirectory.bind(stats);
6269 this.isFIFO = stats.isFIFO.bind(stats);
6270 this.isFile = stats.isFile.bind(stats);
6271 this.isSocket = stats.isSocket.bind(stats);
6272 this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
6277 function createDirentFromStats(name, stats) {
6278 return new DirentFromStats(name, stats);
6281 exports.createDirentFromStats = createDirentFromStats;
6284 var path_1 = createCommonjsModule(function (module, exports) {
6286 Object.defineProperty(exports, "__esModule", {
6289 exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0;
6290 const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\
6292 const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g;
6294 * Designed to work only with simple paths: `dir\\file`.
\r
6297 function unixify(filepath) {
6298 return filepath.replace(/\\/g, '/');
6301 exports.unixify = unixify;
6303 function makeAbsolute(cwd, filepath) {
6304 return path__default['default'].resolve(cwd, filepath);
6307 exports.makeAbsolute = makeAbsolute;
6309 function escape(pattern) {
6310 return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2');
6313 exports.escape = escape;
6315 function removeLeadingDotSegment(entry) {
6316 // We do not use `startsWith` because this is 10x slower than current implementation for some cases.
6317 // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
6318 if (entry.charAt(0) === '.') {
6319 const secondCharactery = entry.charAt(1);
6321 if (secondCharactery === '/' || secondCharactery === '\\') {
6322 return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT);
6329 exports.removeLeadingDotSegment = removeLeadingDotSegment;
6333 * is-extglob <https://github.com/jonschlinkert/is-extglob>
6335 * Copyright (c) 2014-2016, Jon Schlinkert.
6336 * Licensed under the MIT License.
6338 var isExtglob = function isExtglob(str) {
6339 if (typeof str !== 'string' || str === '') {
6345 while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) {
6346 if (match[2]) return true;
6347 str = str.slice(match.index + match[0].length);
6354 * is-glob <https://github.com/jonschlinkert/is-glob>
6356 * Copyright (c) 2014-2017, Jon Schlinkert.
6357 * Released under the MIT License.
6365 var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/;
6366 var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/;
6368 var isGlob = function isGlob(str, options) {
6369 if (typeof str !== 'string' || str === '') {
6373 if (isExtglob(str)) {
6377 var regex = strictRegex;
6378 var match; // optionally relax regex
6380 if (options && options.strict === false) {
6381 regex = relaxedRegex;
6384 while (match = regex.exec(str)) {
6385 if (match[2]) return true;
6386 var idx = match.index + match[0].length; // if an open bracket/brace/paren is escaped,
6387 // set the index to the next closing character
6389 var open = match[1];
6390 var close = open ? chars[open] : null;
6392 if (open && close) {
6393 var n = str.indexOf(close, idx);
6400 str = str.slice(idx);
6406 var pathPosixDirname = path__default['default'].posix.dirname;
6407 var isWin32 = os__default['default'].platform() === 'win32';
6409 var backslash = /\\/g;
6410 var enclosure = /[\{\[].*[\/]*.*[\}\]]$/;
6411 var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
6412 var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
6414 * @param {string} str
6415 * @param {Object} opts
6416 * @param {boolean} [opts.flipBackslashes=true]
6419 var globParent = function globParent(str, opts) {
6420 var options = Object.assign({
6421 flipBackslashes: true
6422 }, opts); // flip windows path separators
6424 if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
6425 str = str.replace(backslash, slash);
6426 } // special case for strings ending in enclosure containing path separator
6429 if (enclosure.test(str)) {
6431 } // preserves full path in case of trailing path separator
6434 str += 'a'; // remove path parts that are globby
6437 str = pathPosixDirname(str);
6438 } while (isGlob(str) || globby.test(str)); // remove escape chars and return result
6441 return str.replace(escaped, '$1');
6444 var utils = createCommonjsModule(function (module, exports) {
6446 exports.isInteger = num => {
6447 if (typeof num === 'number') {
6448 return Number.isInteger(num);
6451 if (typeof num === 'string' && num.trim() !== '') {
6452 return Number.isInteger(Number(num));
6458 * Find a node of the given type
6462 exports.find = (node, type) => node.nodes.find(node => node.type === type);
6464 * Find a node of the given type
6468 exports.exceedsLimit = (min, max, step = 1, limit) => {
6469 if (limit === false) return false;
6470 if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
6471 return (Number(max) - Number(min)) / Number(step) >= limit;
6474 * Escape the given node with '\\' before node.value
6478 exports.escapeNode = (block, n = 0, type) => {
6479 let node = block.nodes[n];
6482 if (type && node.type === type || node.type === 'open' || node.type === 'close') {
6483 if (node.escaped !== true) {
6484 node.value = '\\' + node.value;
6485 node.escaped = true;
6490 * Returns true if the given brace node should be enclosed in literal braces
6494 exports.encloseBrace = node => {
6495 if (node.type !== 'brace') return false;
6497 if (node.commas >> 0 + node.ranges >> 0 === 0) {
6498 node.invalid = true;
6505 * Returns true if a brace node is invalid.
6509 exports.isInvalidBrace = block => {
6510 if (block.type !== 'brace') return false;
6511 if (block.invalid === true || block.dollar) return true;
6513 if (block.commas >> 0 + block.ranges >> 0 === 0) {
6514 block.invalid = true;
6518 if (block.open !== true || block.close !== true) {
6519 block.invalid = true;
6526 * Returns true if a node is an open or close node
6530 exports.isOpenOrClose = node => {
6531 if (node.type === 'open' || node.type === 'close') {
6535 return node.open === true || node.close === true;
6538 * Reduce an array of text nodes.
6542 exports.reduce = nodes => nodes.reduce((acc, node) => {
6543 if (node.type === 'text') acc.push(node.value);
6544 if (node.type === 'range') node.type = 'text';
6552 exports.flatten = (...args) => {
6555 const flat = arr => {
6556 for (let i = 0; i < arr.length; i++) {
6558 Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
6569 var stringify = (ast, options = {}) => {
6570 let stringify = (node, parent = {}) => {
6571 let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
6572 let invalidNode = node.invalid === true && options.escapeInvalid === true;
6576 if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) {
6577 return '\\' + node.value;
6588 for (let child of node.nodes) {
6589 output += stringify(child);
6596 return stringify(ast);
6600 * is-number <https://github.com/jonschlinkert/is-number>
6602 * Copyright (c) 2014-present, Jon Schlinkert.
6603 * Released under the MIT License.
6606 var isNumber$1 = function (num) {
6607 if (typeof num === 'number') {
6608 return num - num === 0;
6611 if (typeof num === 'string' && num.trim() !== '') {
6612 return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
6618 const toRegexRange = (min, max, options) => {
6619 if (isNumber$1(min) === false) {
6620 throw new TypeError('toRegexRange: expected the first argument to be a number');
6623 if (max === void 0 || min === max) {
6627 if (isNumber$1(max) === false) {
6628 throw new TypeError('toRegexRange: expected the second argument to be a number.');
6631 let opts = Object.assign({
6635 if (typeof opts.strictZeros === 'boolean') {
6636 opts.relaxZeros = opts.strictZeros === false;
6639 let relax = String(opts.relaxZeros);
6640 let shorthand = String(opts.shorthand);
6641 let capture = String(opts.capture);
6642 let wrap = String(opts.wrap);
6643 let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
6645 if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
6646 return toRegexRange.cache[cacheKey].result;
6649 let a = Math.min(min, max);
6650 let b = Math.max(min, max);
6652 if (Math.abs(a - b) === 1) {
6653 let result = min + '|' + max;
6656 return `(${result})`;
6659 if (opts.wrap === false) {
6663 return `(?:${result})`;
6666 let isPadded = hasPadding(min) || hasPadding(max);
6677 state.isPadded = isPadded;
6678 state.maxLen = String(state.max).length;
6682 let newMin = b < 0 ? Math.abs(b) : 1;
6683 negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
6688 positives = splitToPatterns(a, b, state, opts);
6691 state.negatives = negatives;
6692 state.positives = positives;
6693 state.result = collatePatterns(negatives, positives);
6695 if (opts.capture === true) {
6696 state.result = `(${state.result})`;
6697 } else if (opts.wrap !== false && positives.length + negatives.length > 1) {
6698 state.result = `(?:${state.result})`;
6701 toRegexRange.cache[cacheKey] = state;
6702 return state.result;
6705 function collatePatterns(neg, pos, options) {
6706 let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
6707 let onlyPositive = filterPatterns(pos, neg, '', false) || [];
6708 let intersected = filterPatterns(neg, pos, '-?', true) || [];
6709 let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
6710 return subpatterns.join('|');
6713 function splitToRanges(min, max) {
6716 let stop = countNines(min, nines);
6717 let stops = new Set([max]);
6719 while (min <= stop && stop <= max) {
6722 stop = countNines(min, nines);
6725 stop = countZeros(max + 1, zeros) - 1;
6727 while (min < stop && stop <= max) {
6730 stop = countZeros(max + 1, zeros) - 1;
6734 stops.sort(compare);
6738 * Convert a range to a regex pattern
6739 * @param {Number} `start`
6740 * @param {Number} `stop`
6745 function rangeToPattern(start, stop, options) {
6746 if (start === stop) {
6754 let zipped = zip(start, stop);
6755 let digits = zipped.length;
6759 for (let i = 0; i < digits; i++) {
6760 let [startDigit, stopDigit] = zipped[i];
6762 if (startDigit === stopDigit) {
6763 pattern += startDigit;
6764 } else if (startDigit !== '0' || stopDigit !== '9') {
6765 pattern += toCharacterClass(startDigit, stopDigit);
6772 pattern += options.shorthand === true ? '\\d' : '[0-9]';
6782 function splitToPatterns(min, max, tok, options) {
6783 let ranges = splitToRanges(min, max);
6788 for (let i = 0; i < ranges.length; i++) {
6789 let max = ranges[i];
6790 let obj = rangeToPattern(String(start), String(max), options);
6793 if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
6794 if (prev.count.length > 1) {
6798 prev.count.push(obj.count[0]);
6799 prev.string = prev.pattern + toQuantifier(prev.count);
6805 zeros = padZeros(max, tok, options);
6808 obj.string = zeros + obj.pattern + toQuantifier(obj.count);
6817 function filterPatterns(arr, comparison, prefix, intersection, options) {
6820 for (let ele of arr) {
6823 } = ele; // only push if _both_ are negative...
6825 if (!intersection && !contains(comparison, 'string', string)) {
6826 result.push(prefix + string);
6827 } // or _both_ are positive
6830 if (intersection && contains(comparison, 'string', string)) {
6831 result.push(prefix + string);
6842 function zip(a, b) {
6845 for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
6850 function compare(a, b) {
6851 return a > b ? 1 : b > a ? -1 : 0;
6854 function contains(arr, key, val) {
6855 return arr.some(ele => ele[key] === val);
6858 function countNines(min, len) {
6859 return Number(String(min).slice(0, -len) + '9'.repeat(len));
6862 function countZeros(integer, zeros) {
6863 return integer - integer % Math.pow(10, zeros);
6866 function toQuantifier(digits) {
6867 let [start = 0, stop = ''] = digits;
6869 if (stop || start > 1) {
6870 return `{${start + (stop ? ',' + stop : '')}}`;
6876 function toCharacterClass(a, b, options) {
6877 return `[${a}${b - a === 1 ? '' : '-'}${b}]`;
6880 function hasPadding(str) {
6881 return /^-?(0+)\d/.test(str);
6884 function padZeros(value, tok, options) {
6885 if (!tok.isPadded) {
6889 let diff = Math.abs(tok.maxLen - String(value).length);
6890 let relax = options.relaxZeros !== false;
6897 return relax ? '0?' : '0';
6900 return relax ? '0{0,2}' : '00';
6904 return relax ? `0{0,${diff}}` : `0{${diff}}`;
6913 toRegexRange.cache = {};
6915 toRegexRange.clearCache = () => toRegexRange.cache = {};
6917 * Expose `toRegexRange`
6921 var toRegexRange_1 = toRegexRange;
6923 const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
6925 const transform = toNumber => {
6926 return value => toNumber === true ? Number(value) : String(value);
6929 const isValidValue = value => {
6930 return typeof value === 'number' || typeof value === 'string' && value !== '';
6933 const isNumber$2 = num => Number.isInteger(+num);
6935 const zeros = input => {
6936 let value = `${input}`;
6938 if (value[0] === '-') value = value.slice(1);
6939 if (value === '0') return false;
6941 while (value[++index] === '0');
6946 const stringify$1 = (start, end, options) => {
6947 if (typeof start === 'string' || typeof end === 'string') {
6951 return options.stringify === true;
6954 const pad = (input, maxLength, toNumber) => {
6955 if (maxLength > 0) {
6956 let dash = input[0] === '-' ? '-' : '';
6957 if (dash) input = input.slice(1);
6958 input = dash + input.padStart(dash ? maxLength - 1 : maxLength, '0');
6961 if (toNumber === false) {
6962 return String(input);
6968 const toMaxLen = (input, maxLength) => {
6969 let negative = input[0] === '-' ? '-' : '';
6972 input = input.slice(1);
6976 while (input.length < maxLength) input = '0' + input;
6978 return negative ? '-' + input : input;
6981 const toSequence = (parts, options) => {
6982 parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
6983 parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
6984 let prefix = options.capture ? '' : '?:';
6989 if (parts.positives.length) {
6990 positives = parts.positives.join('|');
6993 if (parts.negatives.length) {
6994 negatives = `-(${prefix}${parts.negatives.join('|')})`;
6997 if (positives && negatives) {
6998 result = `${positives}|${negatives}`;
7000 result = positives || negatives;
7004 return `(${prefix}${result})`;
7010 const toRange = (a, b, isNumbers, options) => {
7012 return toRegexRange_1(a, b, Object.assign({
7017 let start = String.fromCharCode(a);
7018 if (a === b) return start;
7019 let stop = String.fromCharCode(b);
7020 return `[${start}-${stop}]`;
7023 const toRegex = (start, end, options) => {
7024 if (Array.isArray(start)) {
7025 let wrap = options.wrap === true;
7026 let prefix = options.capture ? '' : '?:';
7027 return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
7030 return toRegexRange_1(start, end, options);
7033 const rangeError = (...args) => {
7034 return new RangeError('Invalid range arguments: ' + util__default['default'].inspect(...args));
7037 const invalidRange = (start, end, options) => {
7038 if (options.strictRanges === true) throw rangeError([start, end]);
7042 const invalidStep = (step, options) => {
7043 if (options.strictRanges === true) {
7044 throw new TypeError(`Expected step "${step}" to be a number`);
7050 const fillNumbers = (start, end, step = 1, options = {}) => {
7051 let a = Number(start);
7052 let b = Number(end);
7054 if (!Number.isInteger(a) || !Number.isInteger(b)) {
7055 if (options.strictRanges === true) throw rangeError([start, end]);
7057 } // fix negative zero
7062 let descending = a > b;
7063 let startString = String(start);
7064 let endString = String(end);
7065 let stepString = String(step);
7066 step = Math.max(Math.abs(step), 1);
7067 let padded = zeros(startString) || zeros(endString) || zeros(stepString);
7068 let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
7069 let toNumber = padded === false && stringify$1(start, end, options) === false;
7070 let format = options.transform || transform(toNumber);
7072 if (options.toRegex && step === 1) {
7073 return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
7081 let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
7086 while (descending ? a >= b : a <= b) {
7087 if (options.toRegex === true && step > 1) {
7090 range.push(pad(format(a, index), maxLen, toNumber));
7093 a = descending ? a - step : a + step;
7097 if (options.toRegex === true) {
7098 return step > 1 ? toSequence(parts, options) : toRegex(range, null, Object.assign({
7106 const fillLetters = (start, end, step = 1, options = {}) => {
7107 if (!isNumber$2(start) && start.length > 1 || !isNumber$2(end) && end.length > 1) {
7108 return invalidRange(start, end, options);
7111 let format = options.transform || (val => String.fromCharCode(val));
7113 let a = `${start}`.charCodeAt(0);
7114 let b = `${end}`.charCodeAt(0);
7115 let descending = a > b;
7116 let min = Math.min(a, b);
7117 let max = Math.max(a, b);
7119 if (options.toRegex && step === 1) {
7120 return toRange(min, max, false, options);
7126 while (descending ? a >= b : a <= b) {
7127 range.push(format(a, index));
7128 a = descending ? a - step : a + step;
7132 if (options.toRegex === true) {
7133 return toRegex(range, null, {
7142 const fill = (start, end, step, options = {}) => {
7143 if (end == null && isValidValue(start)) {
7147 if (!isValidValue(start) || !isValidValue(end)) {
7148 return invalidRange(start, end, options);
7151 if (typeof step === 'function') {
7152 return fill(start, end, 1, {
7157 if (isObject$1(step)) {
7158 return fill(start, end, 0, step);
7161 let opts = Object.assign({}, options);
7162 if (opts.capture === true) opts.wrap = true;
7163 step = step || opts.step || 1;
7165 if (!isNumber$2(step)) {
7166 if (step != null && !isObject$1(step)) return invalidStep(step, opts);
7167 return fill(start, end, 1, step);
7170 if (isNumber$2(start) && isNumber$2(end)) {
7171 return fillNumbers(start, end, step, opts);
7174 return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
7177 var fillRange = fill;
7179 const compile = (ast, options = {}) => {
7180 let walk = (node, parent = {}) => {
7181 let invalidBlock = utils.isInvalidBrace(parent);
7182 let invalidNode = node.invalid === true && options.escapeInvalid === true;
7183 let invalid = invalidBlock === true || invalidNode === true;
7184 let prefix = options.escapeInvalid === true ? '\\' : '';
7187 if (node.isOpen === true) {
7188 return prefix + node.value;
7191 if (node.isClose === true) {
7192 return prefix + node.value;
7195 if (node.type === 'open') {
7196 return invalid ? prefix + node.value : '(';
7199 if (node.type === 'close') {
7200 return invalid ? prefix + node.value : ')';
7203 if (node.type === 'comma') {
7204 return node.prev.type === 'comma' ? '' : invalid ? node.value : '|';
7211 if (node.nodes && node.ranges > 0) {
7212 let args = utils.reduce(node.nodes);
7213 let range = fillRange(...args, Object.assign({}, options, {
7218 if (range.length !== 0) {
7219 return args.length > 1 && range.length > 1 ? `(${range})` : range;
7224 for (let child of node.nodes) {
7225 output += walk(child, node);
7235 var compile_1 = compile;
7237 const append = (queue = '', stash = '', enclose = false) => {
7239 queue = [].concat(queue);
7240 stash = [].concat(stash);
7241 if (!stash.length) return queue;
7243 if (!queue.length) {
7244 return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
7247 for (let item of queue) {
7248 if (Array.isArray(item)) {
7249 for (let value of item) {
7250 result.push(append(value, stash, enclose));
7253 for (let ele of stash) {
7254 if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
7255 result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
7260 return utils.flatten(result);
7263 const expand = (ast, options = {}) => {
7264 let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
7266 let walk = (node, parent = {}) => {
7269 let q = parent.queue;
7271 while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
7276 if (node.invalid || node.dollar) {
7277 q.push(append(q.pop(), stringify(node, options)));
7281 if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
7282 q.push(append(q.pop(), ['{}']));
7286 if (node.nodes && node.ranges > 0) {
7287 let args = utils.reduce(node.nodes);
7289 if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
7290 throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
7293 let range = fillRange(...args, options);
7295 if (range.length === 0) {
7296 range = stringify(node, options);
7299 q.push(append(q.pop(), range));
7304 let enclose = utils.encloseBrace(node);
7305 let queue = node.queue;
7308 while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
7309 block = block.parent;
7310 queue = block.queue;
7313 for (let i = 0; i < node.nodes.length; i++) {
7314 let child = node.nodes[i];
7316 if (child.type === 'comma' && node.type === 'brace') {
7317 if (i === 1) queue.push('');
7322 if (child.type === 'close') {
7323 q.push(append(q.pop(), queue, enclose));
7327 if (child.value && child.type !== 'open') {
7328 queue.push(append(queue.pop(), child.value));
7340 return utils.flatten(walk(ast));
7343 var expand_1 = expand;
7346 MAX_LENGTH: 1024 * 64,
7355 CHAR_UPPERCASE_A: 'A',
7358 CHAR_LOWERCASE_A: 'a',
7361 CHAR_UPPERCASE_Z: 'Z',
7364 CHAR_LOWERCASE_Z: 'z',
7367 CHAR_LEFT_PARENTHESES: '(',
7370 CHAR_RIGHT_PARENTHESES: ')',
7376 // Non-alphabetic chars.
7377 CHAR_AMPERSAND: '&',
7383 CHAR_BACKSLASH: '\\',
7389 CHAR_CARRIAGE_RETURN: '\r',
7392 CHAR_CIRCUMFLEX_ACCENT: '^',
7407 CHAR_DOUBLE_QUOTE: '"',
7413 CHAR_EXCLAMATION_MARK: '!',
7416 CHAR_FORM_FEED: '\f',
7419 CHAR_FORWARD_SLASH: '/',
7425 CHAR_HYPHEN_MINUS: '-',
7428 CHAR_LEFT_ANGLE_BRACKET: '<',
7431 CHAR_LEFT_CURLY_BRACE: '{',
7434 CHAR_LEFT_SQUARE_BRACKET: '[',
7437 CHAR_LINE_FEED: '\n',
7440 CHAR_NO_BREAK_SPACE: '\u00A0',
7449 CHAR_QUESTION_MARK: '?',
7452 CHAR_RIGHT_ANGLE_BRACKET: '>',
7455 CHAR_RIGHT_CURLY_BRACE: '}',
7458 CHAR_RIGHT_SQUARE_BRACKET: ']',
7461 CHAR_SEMICOLON: ';',
7464 CHAR_SINGLE_QUOTE: '\'',
7473 CHAR_UNDERSCORE: '_',
7476 CHAR_VERTICAL_LINE: '|',
7479 CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF'
7503 CHAR_LEFT_PARENTHESES,
7506 CHAR_RIGHT_PARENTHESES,
7509 CHAR_LEFT_CURLY_BRACE,
7512 CHAR_RIGHT_CURLY_BRACE,
7515 CHAR_LEFT_SQUARE_BRACKET,
7518 CHAR_RIGHT_SQUARE_BRACKET,
7527 CHAR_NO_BREAK_SPACE,
7528 CHAR_ZERO_WIDTH_NOBREAK_SPACE
7534 const parse = (input, options = {}) => {
7535 if (typeof input !== 'string') {
7536 throw new TypeError('Expected a string');
7539 let opts = options || {};
7540 let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
7542 if (input.length > max) {
7543 throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
7555 let length = input.length;
7563 const advance = () => input[index++];
7565 const push = node => {
7566 if (node.type === 'text' && prev.type === 'dot') {
7570 if (prev && prev.type === 'text' && node.type === 'text') {
7571 prev.value += node.value;
7575 block.nodes.push(node);
7576 node.parent = block;
7586 while (index < length) {
7587 block = stack[stack.length - 1];
7593 if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
7601 if (value === CHAR_BACKSLASH) {
7604 value: (options.keepEscaping ? value : '') + advance()
7609 * Right square bracket (literal): ']'
7613 if (value === CHAR_RIGHT_SQUARE_BRACKET) {
7621 * Left square bracket: '['
7625 if (value === CHAR_LEFT_SQUARE_BRACKET) {
7629 while (index < length && (next = advance())) {
7632 if (next === CHAR_LEFT_SQUARE_BRACKET) {
7637 if (next === CHAR_BACKSLASH) {
7642 if (next === CHAR_RIGHT_SQUARE_BRACKET) {
7645 if (brackets === 0) {
7662 if (value === CHAR_LEFT_PARENTHESES) {
7675 if (value === CHAR_RIGHT_PARENTHESES) {
7676 if (block.type !== 'paren') {
7684 block = stack.pop();
7689 block = stack[stack.length - 1];
7697 if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
7701 if (options.keepQuotes !== true) {
7705 while (index < length && (next = advance())) {
7706 if (next === CHAR_BACKSLASH) {
7707 value += next + advance();
7711 if (next === open) {
7712 if (options.keepQuotes === true) value += next;
7726 * Left curly brace: '{'
7730 if (value === CHAR_LEFT_CURLY_BRACE) {
7732 let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
7743 block = push(brace);
7752 * Right curly brace: '}'
7756 if (value === CHAR_RIGHT_CURLY_BRACE) {
7757 if (block.type !== 'brace') {
7766 block = stack.pop();
7773 block = stack[stack.length - 1];
7781 if (value === CHAR_COMMA && depth > 0) {
7782 if (block.ranges > 0) {
7784 let open = block.nodes.shift();
7785 block.nodes = [open, {
7787 value: stringify(block)
7803 if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
7804 let siblings = block.nodes;
7806 if (depth === 0 || siblings.length === 0) {
7814 if (prev.type === 'dot') {
7816 prev.value += value;
7817 prev.type = 'range';
7819 if (block.nodes.length !== 3 && block.nodes.length !== 5) {
7820 block.invalid = true;
7831 if (prev.type === 'range') {
7833 let before = siblings[siblings.length - 1];
7834 before.value += prev.value + value;
7855 } // Mark imbalanced braces and brackets as invalid
7859 block = stack.pop();
7861 if (block.type !== 'root') {
7862 block.nodes.forEach(node => {
7864 if (node.type === 'open') node.isOpen = true;
7865 if (node.type === 'close') node.isClose = true;
7866 if (!node.nodes) node.type = 'text';
7867 node.invalid = true;
7869 }); // get the location of the block on parent.nodes (block's siblings)
7871 let parent = stack[stack.length - 1];
7872 let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes
7874 parent.nodes.splice(index, 1, ...block.nodes);
7876 } while (stack.length > 0);
7884 var parse_1 = parse;
7887 * Expand the given pattern or create a regex-compatible string.
7890 * const braces = require('braces');
7891 * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
7892 * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
7894 * @param {String} `str`
7895 * @param {Object} `options`
7901 const braces = (input, options = {}) => {
7904 if (Array.isArray(input)) {
7905 for (let pattern of input) {
7906 let result = braces.create(pattern, options);
7908 if (Array.isArray(result)) {
7909 output.push(...result);
7911 output.push(result);
7915 output = [].concat(braces.create(input, options));
7918 if (options && options.expand === true && options.nodupes === true) {
7919 output = [...new Set(output)];
7925 * Parse the given `str` with the given `options`.
7928 * // braces.parse(pattern, [, options]);
7929 * const ast = braces.parse('a/{b,c}/d');
7932 * @param {String} pattern Brace pattern to parse
7933 * @param {Object} options
7934 * @return {Object} Returns an AST
7939 braces.parse = (input, options = {}) => parse_1(input, options);
7941 * Creates a braces string from an AST, or an AST node.
7944 * const braces = require('braces');
7945 * let ast = braces.parse('foo/{a,b}/bar');
7946 * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
7948 * @param {String} `input` Brace pattern or AST.
7949 * @param {Object} `options`
7950 * @return {Array} Returns an array of expanded values.
7955 braces.stringify = (input, options = {}) => {
7956 if (typeof input === 'string') {
7957 return stringify(braces.parse(input, options), options);
7960 return stringify(input, options);
7963 * Compiles a brace pattern into a regex-compatible, optimized string.
7964 * This method is called by the main [braces](#braces) function by default.
7967 * const braces = require('braces');
7968 * console.log(braces.compile('a/{b,c}/d'));
7969 * //=> ['a/(b|c)/d']
7971 * @param {String} `input` Brace pattern or AST.
7972 * @param {Object} `options`
7973 * @return {Array} Returns an array of expanded values.
7978 braces.compile = (input, options = {}) => {
7979 if (typeof input === 'string') {
7980 input = braces.parse(input, options);
7983 return compile_1(input, options);
7986 * Expands a brace pattern into an array. This method is called by the
7987 * main [braces](#braces) function when `options.expand` is true. Before
7988 * using this method it's recommended that you read the [performance notes](#performance))
7989 * and advantages of using [.compile](#compile) instead.
7992 * const braces = require('braces');
7993 * console.log(braces.expand('a/{b,c}/d'));
7994 * //=> ['a/b/d', 'a/c/d'];
7996 * @param {String} `pattern` Brace pattern
7997 * @param {Object} `options`
7998 * @return {Array} Returns an array of expanded values.
8003 braces.expand = (input, options = {}) => {
8004 if (typeof input === 'string') {
8005 input = braces.parse(input, options);
8008 let result = expand_1(input, options); // filter out empty strings if specified
8010 if (options.noempty === true) {
8011 result = result.filter(Boolean);
8012 } // filter out duplicates if specified
8015 if (options.nodupes === true) {
8016 result = [...new Set(result)];
8022 * Processes a brace pattern and returns either an expanded array
8023 * (if `options.expand` is true), a highly optimized regex-compatible string.
8024 * This method is called by the main [braces](#braces) function.
8027 * const braces = require('braces');
8028 * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
8029 * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
8031 * @param {String} `pattern` Brace pattern
8032 * @param {Object} `options`
8033 * @return {Array} Returns an array of expanded values.
8038 braces.create = (input, options = {}) => {
8039 if (input === '' || input.length < 3) {
8043 return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options);
8050 var braces_1 = braces;
8052 const WIN_SLASH = '\\\\/';
8053 const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
8058 const DOT_LITERAL = '\\.';
8059 const PLUS_LITERAL = '\\+';
8060 const QMARK_LITERAL = '\\?';
8061 const SLASH_LITERAL = '\\/';
8062 const ONE_CHAR = '(?=.)';
8063 const QMARK = '[^/]';
8064 const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
8065 const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
8066 const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
8067 const NO_DOT = `(?!${DOT_LITERAL})`;
8068 const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
8069 const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
8070 const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
8071 const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
8072 const STAR = `${QMARK}*?`;
8073 const POSIX_CHARS = {
8091 * Windows glob regex
8094 const WINDOWS_CHARS = Object.assign({}, POSIX_CHARS, {
8095 SLASH_LITERAL: `[${WIN_SLASH}]`,
8096 QMARK: WIN_NO_SLASH,
8097 STAR: `${WIN_NO_SLASH}*?`,
8098 DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
8099 NO_DOT: `(?!${DOT_LITERAL})`,
8100 NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
8101 NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
8102 NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
8103 QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
8104 START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
8105 END_ANCHOR: `(?:[${WIN_SLASH}]|$)`
8108 * POSIX Bracket Regex
8111 const POSIX_REGEX_SOURCE = {
8114 ascii: '\\x00-\\x7F',
8116 cntrl: '\\x00-\\x1F\\x7F',
8118 graph: '\\x21-\\x7E',
8120 print: '\\x20-\\x7E ',
8121 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
8122 space: ' \\t\\r\\n\\v\\f',
8128 MAX_LENGTH: 1024 * 64,
8130 // regular expressions
8131 REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
8132 REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
8133 REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
8134 REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
8135 REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
8136 REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
8137 // Replace globs with equivalent patterns to reduce parsing time.
8151 CHAR_UPPERCASE_A: 65,
8154 CHAR_LOWERCASE_A: 97,
8157 CHAR_UPPERCASE_Z: 90,
8160 CHAR_LOWERCASE_Z: 122,
8163 CHAR_LEFT_PARENTHESES: 40,
8166 CHAR_RIGHT_PARENTHESES: 41,
8172 // Non-alphabetic chars.
8179 CHAR_BACKWARD_SLASH: 92,
8182 CHAR_CARRIAGE_RETURN: 13,
8185 CHAR_CIRCUMFLEX_ACCENT: 94,
8197 CHAR_DOUBLE_QUOTE: 34,
8203 CHAR_EXCLAMATION_MARK: 33,
8209 CHAR_FORWARD_SLASH: 47,
8212 CHAR_GRAVE_ACCENT: 96,
8218 CHAR_HYPHEN_MINUS: 45,
8221 CHAR_LEFT_ANGLE_BRACKET: 60,
8224 CHAR_LEFT_CURLY_BRACE: 123,
8227 CHAR_LEFT_SQUARE_BRACKET: 91,
8233 CHAR_NO_BREAK_SPACE: 160,
8242 CHAR_QUESTION_MARK: 63,
8245 CHAR_RIGHT_ANGLE_BRACKET: 62,
8248 CHAR_RIGHT_CURLY_BRACE: 125,
8251 CHAR_RIGHT_SQUARE_BRACKET: 93,
8257 CHAR_SINGLE_QUOTE: 39,
8266 CHAR_UNDERSCORE: 95,
8269 CHAR_VERTICAL_LINE: 124,
8272 CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
8275 SEP: path__default['default'].sep,
8278 * Create EXTGLOB_CHARS
8280 extglobChars(chars) {
8285 close: `))${chars.STAR})`
8314 return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
8319 var utils$1 = createCommonjsModule(function (module, exports) {
8321 const win32 = process.platform === 'win32';
8324 REGEX_REMOVE_BACKSLASH,
8325 REGEX_SPECIAL_CHARS,
8326 REGEX_SPECIAL_CHARS_GLOBAL
8329 exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
8331 exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
8333 exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
8335 exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
8337 exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
8339 exports.removeBackslashes = str => {
8340 return str.replace(REGEX_REMOVE_BACKSLASH, match => {
8341 return match === '\\' ? '' : match;
8345 exports.supportsLookbehinds = () => {
8346 const segs = process.version.slice(1).split('.').map(Number);
8348 if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) {
8355 exports.isWindows = options => {
8356 if (options && typeof options.windows === 'boolean') {
8357 return options.windows;
8360 return win32 === true || path__default['default'].sep === '\\';
8363 exports.escapeLast = (input, char, lastIdx) => {
8364 const idx = input.lastIndexOf(char, lastIdx);
8365 if (idx === -1) return input;
8366 if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
8367 return `${input.slice(0, idx)}\\${input.slice(idx)}`;
8370 exports.removePrefix = (input, state = {}) => {
8373 if (output.startsWith('./')) {
8374 output = output.slice(2);
8375 state.prefix = './';
8381 exports.wrapOutput = (input, state = {}, options = {}) => {
8382 const prepend = options.contains ? '' : '^';
8383 const append = options.contains ? '' : '$';
8384 let output = `${prepend}(?:${input})${append}`;
8386 if (state.negated === true) {
8387 output = `(?:^(?!${output}).*$)`;
8401 CHAR_BACKWARD_SLASH,
8404 CHAR_COMMA: CHAR_COMMA$1,
8407 CHAR_DOT: CHAR_DOT$1,
8410 CHAR_EXCLAMATION_MARK,
8416 CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1,
8419 CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1,
8422 CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1,
8431 CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1,
8434 CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1,
8437 CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1
8442 const isPathSeparator = code => {
8443 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
8446 const depth = token => {
8447 if (token.isPrefix !== true) {
8448 token.depth = token.isGlobstar ? Infinity : 1;
8452 * Quickly scans a glob pattern and returns an object with a handful of
8453 * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
8454 * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
8457 * const pm = require('picomatch');
8458 * console.log(pm.scan('foo/bar/*.js'));
8459 * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
8461 * @param {String} `str`
8462 * @param {Object} `options`
8463 * @return {Object} Returns an object with tokens and regex source string.
8468 const scan = (input, options) => {
8469 const opts = options || {};
8470 const length = input.length - 1;
8471 const scanToEnd = opts.parts === true || opts.scanToEnd === true;
8479 let isBrace = false;
8480 let isBracket = false;
8482 let isExtglob = false;
8483 let isGlobstar = false;
8484 let braceEscaped = false;
8485 let backslashes = false;
8486 let negated = false;
8487 let finished = false;
8497 const eos = () => index >= length;
8499 const peek = () => str.charCodeAt(index + 1);
8501 const advance = () => {
8503 return str.charCodeAt(++index);
8506 while (index < length) {
8510 if (code === CHAR_BACKWARD_SLASH) {
8511 backslashes = token.backslashes = true;
8514 if (code === CHAR_LEFT_CURLY_BRACE$1) {
8515 braceEscaped = true;
8521 if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
8524 while (eos() !== true && (code = advance())) {
8525 if (code === CHAR_BACKWARD_SLASH) {
8526 backslashes = token.backslashes = true;
8531 if (code === CHAR_LEFT_CURLY_BRACE$1) {
8536 if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) {
8537 isBrace = token.isBrace = true;
8538 isGlob = token.isGlob = true;
8541 if (scanToEnd === true) {
8548 if (braceEscaped !== true && code === CHAR_COMMA$1) {
8549 isBrace = token.isBrace = true;
8550 isGlob = token.isGlob = true;
8553 if (scanToEnd === true) {
8560 if (code === CHAR_RIGHT_CURLY_BRACE$1) {
8564 braceEscaped = false;
8565 isBrace = token.isBrace = true;
8572 if (scanToEnd === true) {
8579 if (code === CHAR_FORWARD_SLASH) {
8580 slashes.push(index);
8587 if (finished === true) continue;
8589 if (prev === CHAR_DOT$1 && index === start + 1) {
8594 lastIndex = index + 1;
8598 if (opts.noext !== true) {
8599 const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
8601 if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) {
8602 isGlob = token.isGlob = true;
8603 isExtglob = token.isExtglob = true;
8606 if (scanToEnd === true) {
8607 while (eos() !== true && (code = advance())) {
8608 if (code === CHAR_BACKWARD_SLASH) {
8609 backslashes = token.backslashes = true;
8614 if (code === CHAR_RIGHT_PARENTHESES$1) {
8615 isGlob = token.isGlob = true;
8628 if (code === CHAR_ASTERISK) {
8629 if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
8630 isGlob = token.isGlob = true;
8633 if (scanToEnd === true) {
8640 if (code === CHAR_QUESTION_MARK) {
8641 isGlob = token.isGlob = true;
8644 if (scanToEnd === true) {
8651 if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
8652 while (eos() !== true && (next = advance())) {
8653 if (next === CHAR_BACKWARD_SLASH) {
8654 backslashes = token.backslashes = true;
8659 if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
8660 isBracket = token.isBracket = true;
8661 isGlob = token.isGlob = true;
8664 if (scanToEnd === true) {
8673 if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
8674 negated = token.negated = true;
8679 if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) {
8680 isGlob = token.isGlob = true;
8682 if (scanToEnd === true) {
8683 while (eos() !== true && (code = advance())) {
8684 if (code === CHAR_LEFT_PARENTHESES$1) {
8685 backslashes = token.backslashes = true;
8690 if (code === CHAR_RIGHT_PARENTHESES$1) {
8702 if (isGlob === true) {
8705 if (scanToEnd === true) {
8713 if (opts.noext === true) {
8723 prefix = str.slice(0, start);
8724 str = str.slice(start);
8728 if (base && isGlob === true && lastIndex > 0) {
8729 base = str.slice(0, lastIndex);
8730 glob = str.slice(lastIndex);
8731 } else if (isGlob === true) {
8738 if (base && base !== '' && base !== '/' && base !== str) {
8739 if (isPathSeparator(base.charCodeAt(base.length - 1))) {
8740 base = base.slice(0, -1);
8744 if (opts.unescape === true) {
8745 if (glob) glob = utils$1.removeBackslashes(glob);
8747 if (base && backslashes === true) {
8748 base = utils$1.removeBackslashes(base);
8766 if (opts.tokens === true) {
8769 if (!isPathSeparator(code)) {
8773 state.tokens = tokens;
8776 if (opts.parts === true || opts.tokens === true) {
8779 for (let idx = 0; idx < slashes.length; idx++) {
8780 const n = prevIndex ? prevIndex + 1 : start;
8781 const i = slashes[idx];
8782 const value = input.slice(n, i);
8785 if (idx === 0 && start !== 0) {
8786 tokens[idx].isPrefix = true;
8787 tokens[idx].value = prefix;
8789 tokens[idx].value = value;
8793 state.maxDepth += tokens[idx].depth;
8796 if (idx !== 0 || value !== '') {
8803 if (prevIndex && prevIndex + 1 < input.length) {
8804 const value = input.slice(prevIndex + 1);
8808 tokens[tokens.length - 1].value = value;
8809 depth(tokens[tokens.length - 1]);
8810 state.maxDepth += tokens[tokens.length - 1].depth;
8814 state.slashes = slashes;
8815 state.parts = parts;
8829 MAX_LENGTH: MAX_LENGTH$1,
8830 POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
8831 REGEX_NON_SPECIAL_CHARS,
8832 REGEX_SPECIAL_CHARS_BACKREF,
8839 const expandRange = (args, options) => {
8840 if (typeof options.expandRange === 'function') {
8841 return options.expandRange(...args, options);
8845 const value = `[${args.join('-')}]`;
8848 /* eslint-disable-next-line no-new */
8851 return args.map(v => utils$1.escapeRegex(v)).join('..');
8857 * Create the message for a syntax error
8861 const syntaxError = (type, char) => {
8862 return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
8865 * Parse the given input string.
8866 * @param {String} input
8867 * @param {Object} options
8872 const parse$1 = (input, options) => {
8873 if (typeof input !== 'string') {
8874 throw new TypeError('Expected a string');
8877 input = REPLACEMENTS[input] || input;
8878 const opts = Object.assign({}, options);
8879 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
8880 let len = input.length;
8883 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
8889 output: opts.prepend || ''
8891 const tokens = [bos];
8892 const capture = opts.capture ? '' : '?:';
8893 const win32 = utils$1.isWindows(options); // create constants based on platform, for windows or posix
8895 const PLATFORM_CHARS = constants$1.globChars(win32);
8896 const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
8912 const globstar = opts => {
8913 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
8916 const nodot = opts.dot ? '' : NO_DOT;
8917 const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
8918 let star = opts.bash === true ? globstar(opts) : STAR;
8922 } // minimatch options support
8925 if (typeof opts.noext === 'boolean') {
8926 opts.noextglob = opts.noext;
8933 dot: opts.dot === true,
8946 input = utils$1.removePrefix(input, state);
8948 const extglobs = [];
8954 * Tokenizing helpers
8957 const eos = () => state.index === len - 1;
8959 const peek = state.peek = (n = 1) => input[state.index + n];
8961 const advance = state.advance = () => input[++state.index];
8963 const remaining = () => input.slice(state.index + 1);
8965 const consume = (value = '', num = 0) => {
8966 state.consumed += value;
8970 const append = token => {
8971 state.output += token.output != null ? token.output : token.value;
8972 consume(token.value);
8975 const negate = () => {
8978 while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
8984 if (count % 2 === 0) {
8988 state.negated = true;
8993 const increment = type => {
8998 const decrement = type => {
9003 * Push tokens onto the tokens array. This helper speeds up
9004 * tokenizing by 1) helping us avoid backtracking as much as possible,
9005 * and 2) helping us avoid creating extra tokens when consecutive
9006 * characters are plain text. This improves performance and simplifies
9011 const push = tok => {
9012 if (prev.type === 'globstar') {
9013 const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
9014 const isExtglob = tok.extglob === true || extglobs.length && (tok.type === 'pipe' || tok.type === 'paren');
9016 if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
9017 state.output = state.output.slice(0, -prev.output.length);
9021 state.output += prev.output;
9025 if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
9026 extglobs[extglobs.length - 1].inner += tok.value;
9029 if (tok.value || tok.output) append(tok);
9031 if (prev && prev.type === 'text' && tok.type === 'text') {
9032 prev.value += tok.value;
9033 prev.output = (prev.output || '') + tok.value;
9042 const extglobOpen = (type, value) => {
9043 const token = Object.assign({}, EXTGLOB_CHARS[value], {
9048 token.parens = state.parens;
9049 token.output = state.output;
9050 const output = (opts.capture ? '(' : '') + token.open;
9051 increment('parens');
9055 output: state.output ? '' : ONE_CHAR
9063 extglobs.push(token);
9066 const extglobClose = token => {
9067 let output = token.close + (opts.capture ? ')' : '');
9069 if (token.type === 'negate') {
9070 let extglobStar = star;
9072 if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
9073 extglobStar = globstar(opts);
9076 if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
9077 output = token.close = `)$))${extglobStar}`;
9080 if (token.prev.type === 'bos' && eos()) {
9081 state.negatedExtglob = true;
9091 decrement('parens');
9098 if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
9099 let backslashes = false;
9100 let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
9101 if (first === '\\') {
9106 if (first === '?') {
9108 return esc + first + (rest ? QMARK.repeat(rest.length) : '');
9112 return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
9115 return QMARK.repeat(chars.length);
9118 if (first === '.') {
9119 return DOT_LITERAL.repeat(chars.length);
9122 if (first === '*') {
9124 return esc + first + (rest ? star : '');
9130 return esc ? m : `\\${m}`;
9133 if (backslashes === true) {
9134 if (opts.unescape === true) {
9135 output = output.replace(/\\/g, '');
9137 output = output.replace(/\\+/g, m => {
9138 return m.length % 2 === 0 ? '\\\\' : m ? '\\' : '';
9143 if (output === input && opts.contains === true) {
9144 state.output = input;
9148 state.output = utils$1.wrapOutput(output, state, options);
9152 * Tokenize input until we reach end-of-string
9159 if (value === '\u0000') {
9163 * Escaped characters
9167 if (value === '\\') {
9168 const next = peek();
9170 if (next === '/' && opts.bash !== true) {
9174 if (next === '.' || next === ';') {
9185 } // collapse slashes to reduce potential for exploits
9188 const match = /^\\+/.exec(remaining());
9191 if (match && match[0].length > 2) {
9192 slashes = match[0].length;
9193 state.index += slashes;
9195 if (slashes % 2 !== 0) {
9200 if (opts.unescape === true) {
9201 value = advance() || '';
9203 value += advance() || '';
9206 if (state.brackets === 0) {
9215 * If we're inside a regex character class, continue
9216 * until we reach the closing bracket.
9220 if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
9221 if (opts.posix !== false && value === ':') {
9222 const inner = prev.value.slice(1);
9224 if (inner.includes('[')) {
9227 if (inner.includes(':')) {
9228 const idx = prev.value.lastIndexOf('[');
9229 const pre = prev.value.slice(0, idx);
9230 const rest = prev.value.slice(idx + 2);
9231 const posix = POSIX_REGEX_SOURCE$1[rest];
9234 prev.value = pre + posix;
9235 state.backtrack = true;
9238 if (!bos.output && tokens.indexOf(prev) === 1) {
9239 bos.output = ONE_CHAR;
9248 if (value === '[' && peek() !== ':' || value === '-' && peek() === ']') {
9249 value = `\\${value}`;
9252 if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
9253 value = `\\${value}`;
9256 if (opts.posix === true && value === '!' && prev.value === '[') {
9260 prev.value += value;
9267 * If we're inside a quoted string, continue
9268 * until we reach the closing double quote.
9272 if (state.quotes === 1 && value !== '"') {
9273 value = utils$1.escapeRegex(value);
9274 prev.value += value;
9285 if (value === '"') {
9286 state.quotes = state.quotes === 1 ? 0 : 1;
9288 if (opts.keepQuotes === true) {
9302 if (value === '(') {
9303 increment('parens');
9311 if (value === ')') {
9312 if (state.parens === 0 && opts.strictBrackets === true) {
9313 throw new SyntaxError(syntaxError('opening', '('));
9316 const extglob = extglobs[extglobs.length - 1];
9318 if (extglob && state.parens === extglob.parens + 1) {
9319 extglobClose(extglobs.pop());
9326 output: state.parens ? ')' : '\\)'
9328 decrement('parens');
9336 if (value === '[') {
9337 if (opts.nobracket === true || !remaining().includes(']')) {
9338 if (opts.nobracket !== true && opts.strictBrackets === true) {
9339 throw new SyntaxError(syntaxError('closing', ']'));
9342 value = `\\${value}`;
9344 increment('brackets');
9354 if (value === ']') {
9355 if (opts.nobracket === true || prev && prev.type === 'bracket' && prev.value.length === 1) {
9359 output: `\\${value}`
9364 if (state.brackets === 0) {
9365 if (opts.strictBrackets === true) {
9366 throw new SyntaxError(syntaxError('opening', '['));
9372 output: `\\${value}`
9377 decrement('brackets');
9378 const prevValue = prev.value.slice(1);
9380 if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
9381 value = `/${value}`;
9384 prev.value += value;
9387 }); // when literal brackets are explicitly disabled
9388 // assume we should match with a regex character class
9390 if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) {
9394 const escaped = utils$1.escapeRegex(prev.value);
9395 state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled
9396 // assume we should escape the brackets to match literal characters
9398 if (opts.literalBrackets === true) {
9399 state.output += escaped;
9400 prev.value = escaped;
9402 } // when the user specifies nothing, try to match both
9405 prev.value = `(${capture}${escaped}|${prev.value})`;
9406 state.output += prev.value;
9414 if (value === '{' && opts.nobrace !== true) {
9415 increment('braces');
9420 outputIndex: state.output.length,
9421 tokensIndex: state.tokens.length
9428 if (value === '}') {
9429 const brace = braces[braces.length - 1];
9431 if (opts.nobrace === true || !brace) {
9442 if (brace.dots === true) {
9443 const arr = tokens.slice();
9446 for (let i = arr.length - 1; i >= 0; i--) {
9449 if (arr[i].type === 'brace') {
9453 if (arr[i].type !== 'dots') {
9454 range.unshift(arr[i].value);
9458 output = expandRange(range, opts);
9459 state.backtrack = true;
9462 if (brace.comma !== true && brace.dots !== true) {
9463 const out = state.output.slice(0, brace.outputIndex);
9464 const toks = state.tokens.slice(brace.tokensIndex);
9465 brace.value = brace.output = '\\{';
9466 value = output = '\\}';
9469 for (const t of toks) {
9470 state.output += t.output || t.value;
9479 decrement('braces');
9488 if (value === '|') {
9489 if (extglobs.length > 0) {
9490 extglobs[extglobs.length - 1].conditions++;
9504 if (value === ',') {
9506 const brace = braces[braces.length - 1];
9508 if (brace && stack[stack.length - 1] === 'braces') {
9525 if (value === '/') {
9526 // if the beginning of the glob is "./", advance the start
9527 // to the current index, and don't add the "./" characters
9528 // to the state. This greatly simplifies lookbehinds when
9529 // checking for BOS characters like "!" and "." (not "./")
9530 if (prev.type === 'dot' && state.index === state.start + 1) {
9531 state.start = state.index + 1;
9532 state.consumed = '';
9535 prev = bos; // reset "prev" to the first token
9543 output: SLASH_LITERAL
9552 if (value === '.') {
9553 if (state.braces > 0 && prev.type === 'dot') {
9554 if (prev.value === '.') prev.output = DOT_LITERAL;
9555 const brace = braces[braces.length - 1];
9557 prev.output += value;
9558 prev.value += value;
9563 if (state.braces + state.parens === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
9584 if (value === '?') {
9585 const isGroup = prev && prev.value === '(';
9587 if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
9588 extglobOpen('qmark', value);
9592 if (prev && prev.type === 'paren') {
9593 const next = peek();
9596 if (next === '<' && !utils$1.supportsLookbehinds()) {
9597 throw new Error('Node.js v10 or higher is required for regex lookbehinds');
9600 if (prev.value === '(' && !/[!=<:]/.test(next) || next === '<' && !/<([!=]|\w+>)/.test(remaining())) {
9601 output = `\\${value}`;
9612 if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
9616 output: QMARK_NO_DOT
9633 if (value === '!') {
9634 if (opts.noextglob !== true && peek() === '(') {
9635 if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
9636 extglobOpen('negate', value);
9641 if (opts.nonegate !== true && state.index === 0) {
9651 if (value === '+') {
9652 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
9653 extglobOpen('plus', value);
9657 if (prev && prev.value === '(' || opts.regex === false) {
9661 output: PLUS_LITERAL
9666 if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace') || state.parens > 0) {
9685 if (value === '@') {
9686 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
9707 if (value !== '*') {
9708 if (value === '$' || value === '^') {
9709 value = `\\${value}`;
9712 const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
9716 state.index += match[0].length;
9730 if (prev && (prev.type === 'globstar' || prev.star === true)) {
9733 prev.value += value;
9735 state.backtrack = true;
9736 state.globstar = true;
9741 let rest = remaining();
9743 if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
9744 extglobOpen('star', value);
9748 if (prev.type === 'star') {
9749 if (opts.noglobstar === true) {
9754 const prior = prev.prev;
9755 const before = prior.prev;
9756 const isStart = prior.type === 'slash' || prior.type === 'bos';
9757 const afterStar = before && (before.type === 'star' || before.type === 'globstar');
9759 if (opts.bash === true && (!isStart || rest[0] && rest[0] !== '/')) {
9768 const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
9769 const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
9771 if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
9778 } // strip consecutive `/**/`
9781 while (rest.slice(0, 3) === '/**') {
9782 const after = input[state.index + 4];
9784 if (after && after !== '/') {
9788 rest = rest.slice(3);
9792 if (prior.type === 'bos' && eos()) {
9793 prev.type = 'globstar';
9794 prev.value += value;
9795 prev.output = globstar(opts);
9796 state.output = prev.output;
9797 state.globstar = true;
9802 if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
9803 state.output = state.output.slice(0, -(prior.output + prev.output).length);
9804 prior.output = `(?:${prior.output}`;
9805 prev.type = 'globstar';
9806 prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
9807 prev.value += value;
9808 state.globstar = true;
9809 state.output += prior.output + prev.output;
9814 if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
9815 const end = rest[1] !== void 0 ? '|$' : '';
9816 state.output = state.output.slice(0, -(prior.output + prev.output).length);
9817 prior.output = `(?:${prior.output}`;
9818 prev.type = 'globstar';
9819 prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
9820 prev.value += value;
9821 state.output += prior.output + prev.output;
9822 state.globstar = true;
9823 consume(value + advance());
9832 if (prior.type === 'bos' && rest[0] === '/') {
9833 prev.type = 'globstar';
9834 prev.value += value;
9835 prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
9836 state.output = prev.output;
9837 state.globstar = true;
9838 consume(value + advance());
9845 } // remove single star from output
9848 state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar
9850 prev.type = 'globstar';
9851 prev.output = globstar(opts);
9852 prev.value += value; // reset output with globstar
9854 state.output += prev.output;
9855 state.globstar = true;
9866 if (opts.bash === true) {
9867 token.output = '.*?';
9869 if (prev.type === 'bos' || prev.type === 'slash') {
9870 token.output = nodot + token.output;
9877 if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
9878 token.output = value;
9883 if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
9884 if (prev.type === 'dot') {
9885 state.output += NO_DOT_SLASH;
9886 prev.output += NO_DOT_SLASH;
9887 } else if (opts.dot === true) {
9888 state.output += NO_DOTS_SLASH;
9889 prev.output += NO_DOTS_SLASH;
9891 state.output += nodot;
9892 prev.output += nodot;
9895 if (peek() !== '*') {
9896 state.output += ONE_CHAR;
9897 prev.output += ONE_CHAR;
9904 while (state.brackets > 0) {
9905 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
9906 state.output = utils$1.escapeLast(state.output, '[');
9907 decrement('brackets');
9910 while (state.parens > 0) {
9911 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
9912 state.output = utils$1.escapeLast(state.output, '(');
9913 decrement('parens');
9916 while (state.braces > 0) {
9917 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
9918 state.output = utils$1.escapeLast(state.output, '{');
9919 decrement('braces');
9922 if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
9924 type: 'maybe_slash',
9926 output: `${SLASH_LITERAL}?`
9928 } // rebuild the output if we had to backtrack at any point
9931 if (state.backtrack === true) {
9934 for (const token of state.tokens) {
9935 state.output += token.output != null ? token.output : token.value;
9938 state.output += token.suffix;
9946 * Fast paths for creating regular expressions for common glob patterns.
9947 * This can significantly speed up processing and has very little downside
9948 * impact when none of the fast paths match.
9952 parse$1.fastpaths = (input, options) => {
9953 const opts = Object.assign({}, options);
9954 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
9955 const len = input.length;
9958 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
9961 input = REPLACEMENTS[input] || input;
9962 const win32 = utils$1.isWindows(options); // create constants based on platform, for windows or posix
9974 } = constants$1.globChars(win32);
9975 const nodot = opts.dot ? NO_DOTS : NO_DOT;
9976 const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
9977 const capture = opts.capture ? '' : '?:';
9982 let star = opts.bash === true ? '.*?' : STAR;
9988 const globstar = opts => {
9989 if (opts.noglobstar === true) return star;
9990 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
9993 const create = str => {
9996 return `${nodot}${ONE_CHAR}${star}`;
9999 return `${DOT_LITERAL}${ONE_CHAR}${star}`;
10002 return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
10005 return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
10008 return nodot + globstar(opts);
10011 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
10014 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
10017 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
10021 const match = /^(.*?)\.(\w+)$/.exec(str);
10022 if (!match) return;
10023 const source = create(match[1]);
10024 if (!source) return;
10025 return source + DOT_LITERAL + match[2];
10030 const output = utils$1.removePrefix(input, state);
10031 let source = create(output);
10033 if (source && opts.strictSlashes !== true) {
10034 source += `${SLASH_LITERAL}?`;
10040 var parse_1$1 = parse$1;
10042 const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val);
10044 * Creates a matcher function from one or more glob patterns. The
10045 * returned function takes a string to match as its first argument,
10046 * and returns true if the string is a match. The returned matcher
10047 * function also takes a boolean as the second argument that, when true,
10048 * returns an object with additional information.
10051 * const picomatch = require('picomatch');
10052 * // picomatch(glob[, options]);
10054 * const isMatch = picomatch('*.!(*a)');
10055 * console.log(isMatch('a.a')); //=> false
10056 * console.log(isMatch('a.b')); //=> true
10059 * @param {String|Array} `globs` One or more glob patterns.
10060 * @param {Object=} `options`
10061 * @return {Function=} Returns a matcher function.
10066 const picomatch = (glob, options, returnState = false) => {
10067 if (Array.isArray(glob)) {
10068 const fns = glob.map(input => picomatch(input, options, returnState));
10070 const arrayMatcher = str => {
10071 for (const isMatch of fns) {
10072 const state = isMatch(str);
10073 if (state) return state;
10079 return arrayMatcher;
10082 const isState = isObject$2(glob) && glob.tokens && glob.input;
10084 if (glob === '' || typeof glob !== 'string' && !isState) {
10085 throw new TypeError('Expected pattern to be a non-empty string');
10088 const opts = options || {};
10089 const posix = utils$1.isWindows(options);
10090 const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true);
10091 const state = regex.state;
10092 delete regex.state;
10094 let isIgnored = () => false;
10097 const ignoreOpts = Object.assign({}, options, {
10102 isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
10105 const matcher = (input, returnObject = false) => {
10110 } = picomatch.test(input, regex, options, {
10125 if (typeof opts.onResult === 'function') {
10126 opts.onResult(result);
10129 if (isMatch === false) {
10130 result.isMatch = false;
10131 return returnObject ? result : false;
10134 if (isIgnored(input)) {
10135 if (typeof opts.onIgnore === 'function') {
10136 opts.onIgnore(result);
10139 result.isMatch = false;
10140 return returnObject ? result : false;
10143 if (typeof opts.onMatch === 'function') {
10144 opts.onMatch(result);
10147 return returnObject ? result : true;
10151 matcher.state = state;
10157 * Test `input` with the given `regex`. This is used by the main
10158 * `picomatch()` function to test the input string.
10161 * const picomatch = require('picomatch');
10162 * // picomatch.test(input, regex[, options]);
10164 * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
10165 * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
10167 * @param {String} `input` String to test.
10168 * @param {RegExp} `regex`
10169 * @return {Object} Returns an object with matching info.
10174 picomatch.test = (input, regex, options, {
10178 if (typeof input !== 'string') {
10179 throw new TypeError('Expected input to be a string');
10182 if (input === '') {
10189 const opts = options || {};
10190 const format = opts.format || (posix ? utils$1.toPosixSlashes : null);
10191 let match = input === glob;
10192 let output = match && format ? format(input) : input;
10194 if (match === false) {
10195 output = format ? format(input) : input;
10196 match = output === glob;
10199 if (match === false || opts.capture === true) {
10200 if (opts.matchBase === true || opts.basename === true) {
10201 match = picomatch.matchBase(input, regex, options, posix);
10203 match = regex.exec(output);
10208 isMatch: Boolean(match),
10214 * Match the basename of a filepath.
10217 * const picomatch = require('picomatch');
10218 * // picomatch.matchBase(input, glob[, options]);
10219 * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
10221 * @param {String} `input` String to test.
10222 * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
10223 * @return {Boolean}
10228 picomatch.matchBase = (input, glob, options, posix = utils$1.isWindows(options)) => {
10229 const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
10230 return regex.test(path__default['default'].basename(input));
10233 * Returns true if **any** of the given glob `patterns` match the specified `string`.
10236 * const picomatch = require('picomatch');
10237 * // picomatch.isMatch(string, patterns[, options]);
10239 * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
10240 * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
10242 * @param {String|Array} str The string to test.
10243 * @param {String|Array} patterns One or more glob patterns to use for matching.
10244 * @param {Object} [options] See available [options](#options).
10245 * @return {Boolean} Returns true if any patterns match `str`
10250 picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
10252 * Parse a glob pattern to create the source string for a regular
10256 * const picomatch = require('picomatch');
10257 * const result = picomatch.parse(pattern[, options]);
10259 * @param {String} `pattern`
10260 * @param {Object} `options`
10261 * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
10266 picomatch.parse = (pattern, options) => {
10267 if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
10268 return parse_1$1(pattern, Object.assign({}, options, {
10273 * Scan a glob pattern to separate the pattern into segments.
10276 * const picomatch = require('picomatch');
10277 * // picomatch.scan(input[, options]);
10279 * const result = picomatch.scan('!./foo/*.js');
10280 * console.log(result);
10282 * input: '!./foo/*.js',
10287 * isBracket: false,
10289 * isExtglob: false,
10290 * isGlobstar: false,
10293 * @param {String} `input` Glob pattern to scan.
10294 * @param {Object} `options`
10295 * @return {Object} Returns an object with
10300 picomatch.scan = (input, options) => scan_1(input, options);
10302 * Create a regular expression from a parsed glob pattern.
10305 * const picomatch = require('picomatch');
10306 * const state = picomatch.parse('*.js');
10307 * // picomatch.compileRe(state[, options]);
10309 * console.log(picomatch.compileRe(state));
10310 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
10312 * @param {String} `state` The object returned from the `.parse` method.
10313 * @param {Object} `options`
10314 * @return {RegExp} Returns a regex created from the given pattern.
10319 picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => {
10320 if (returnOutput === true) {
10321 return parsed.output;
10324 const opts = options || {};
10325 const prepend = opts.contains ? '' : '^';
10326 const append = opts.contains ? '' : '$';
10327 let source = `${prepend}(?:${parsed.output})${append}`;
10329 if (parsed && parsed.negated === true) {
10330 source = `^(?!${source}).*$`;
10333 const regex = picomatch.toRegex(source, options);
10335 if (returnState === true) {
10336 regex.state = parsed;
10342 picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
10343 if (!input || typeof input !== 'string') {
10344 throw new TypeError('Expected a non-empty string');
10347 const opts = options || {};
10355 if (input.startsWith('./')) {
10356 input = input.slice(2);
10357 prefix = parsed.prefix = './';
10360 if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
10361 output = parse_1$1.fastpaths(input, options);
10364 if (output === undefined) {
10365 parsed = parse_1$1(input, options);
10366 parsed.prefix = prefix + (parsed.prefix || '');
10368 parsed.output = output;
10371 return picomatch.compileRe(parsed, options, returnOutput, returnState);
10374 * Create a regular expression from the given regex source string.
10377 * const picomatch = require('picomatch');
10378 * // picomatch.toRegex(source[, options]);
10380 * const { output } = picomatch.parse('*.js');
10381 * console.log(picomatch.toRegex(output));
10382 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
10384 * @param {String} `source` Regular expression source string.
10385 * @param {Object} `options`
10391 picomatch.toRegex = (source, options) => {
10393 const opts = options || {};
10394 return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
10396 if (options && options.debug === true) throw err;
10401 * Picomatch constants.
10406 picomatch.constants = constants$1;
10408 * Expose "picomatch"
10411 var picomatch_1 = picomatch;
10413 var picomatch$1 = picomatch_1;
10415 const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');
10417 * Returns an array of strings that match one or more glob patterns.
10420 * const mm = require('micromatch');
10421 * // mm(list, patterns[, options]);
10423 * console.log(mm(['a.js', 'a.txt'], ['*.js']));
10426 * @param {String|Array<string>} list List of strings to match.
10427 * @param {String|Array<string>} patterns One or more glob patterns to use for matching.
10428 * @param {Object} options See available [options](#options)
10429 * @return {Array} Returns an array of matches
10435 const micromatch = (list, patterns, options) => {
10436 patterns = [].concat(patterns);
10437 list = [].concat(list);
10438 let omit = new Set();
10439 let keep = new Set();
10440 let items = new Set();
10443 let onResult = state => {
10444 items.add(state.output);
10446 if (options && options.onResult) {
10447 options.onResult(state);
10451 for (let i = 0; i < patterns.length; i++) {
10452 let isMatch = picomatch$1(String(patterns[i]), Object.assign({}, options, {
10455 let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
10456 if (negated) negatives++;
10458 for (let item of list) {
10459 let matched = isMatch(item, true);
10460 let match = negated ? !matched.isMatch : matched.isMatch;
10461 if (!match) continue;
10464 omit.add(matched.output);
10466 omit.delete(matched.output);
10467 keep.add(matched.output);
10472 let result = negatives === patterns.length ? [...items] : [...keep];
10473 let matches = result.filter(item => !omit.has(item));
10475 if (options && matches.length === 0) {
10476 if (options.failglob === true) {
10477 throw new Error(`No matches found for "${patterns.join(', ')}"`);
10480 if (options.nonull === true || options.nullglob === true) {
10481 return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
10488 * Backwards compatibility
10492 micromatch.match = micromatch;
10494 * Returns a matcher function from the given glob `pattern` and `options`.
10495 * The returned function takes a string to match as its only argument and returns
10496 * true if the string is a match.
10499 * const mm = require('micromatch');
10500 * // mm.matcher(pattern[, options]);
10502 * const isMatch = mm.matcher('*.!(*a)');
10503 * console.log(isMatch('a.a')); //=> false
10504 * console.log(isMatch('a.b')); //=> true
10506 * @param {String} `pattern` Glob pattern
10507 * @param {Object} `options`
10508 * @return {Function} Returns a matcher function.
10512 micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);
10514 * Returns true if **any** of the given glob `patterns` match the specified `string`.
10517 * const mm = require('micromatch');
10518 * // mm.isMatch(string, patterns[, options]);
10520 * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
10521 * console.log(mm.isMatch('a.a', 'b.*')); //=> false
10523 * @param {String} str The string to test.
10524 * @param {String|Array} patterns One or more glob patterns to use for matching.
10525 * @param {Object} [options] See available [options](#options).
10526 * @return {Boolean} Returns true if any patterns match `str`
10531 micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
10533 * Backwards compatibility
10537 micromatch.any = micromatch.isMatch;
10539 * Returns a list of strings that _**do not match any**_ of the given `patterns`.
10542 * const mm = require('micromatch');
10543 * // mm.not(list, patterns[, options]);
10545 * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
10546 * //=> ['b.b', 'c.c']
10548 * @param {Array} `list` Array of strings to match.
10549 * @param {String|Array} `patterns` One or more glob pattern to use for matching.
10550 * @param {Object} `options` See available [options](#options) for changing how matches are performed
10551 * @return {Array} Returns an array of strings that **do not match** the given patterns.
10555 micromatch.not = (list, patterns, options = {}) => {
10556 patterns = [].concat(patterns).map(String);
10557 let result = new Set();
10560 let onResult = state => {
10561 if (options.onResult) options.onResult(state);
10562 items.push(state.output);
10565 let matches = micromatch(list, patterns, Object.assign({}, options, {
10569 for (let item of items) {
10570 if (!matches.includes(item)) {
10575 return [...result];
10578 * Returns true if the given `string` contains the given pattern. Similar
10579 * to [.isMatch](#isMatch) but the pattern can match any part of the string.
10582 * var mm = require('micromatch');
10583 * // mm.contains(string, pattern[, options]);
10585 * console.log(mm.contains('aa/bb/cc', '*b'));
10587 * console.log(mm.contains('aa/bb/cc', '*d'));
10590 * @param {String} `str` The string to match.
10591 * @param {String|Array} `patterns` Glob pattern to use for matching.
10592 * @param {Object} `options` See available [options](#options) for changing how matches are performed
10593 * @return {Boolean} Returns true if the patter matches any part of `str`.
10598 micromatch.contains = (str, pattern, options) => {
10599 if (typeof str !== 'string') {
10600 throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`);
10603 if (Array.isArray(pattern)) {
10604 return pattern.some(p => micromatch.contains(str, p, options));
10607 if (typeof pattern === 'string') {
10608 if (isEmptyString(str) || isEmptyString(pattern)) {
10612 if (str.includes(pattern) || str.startsWith('./') && str.slice(2).includes(pattern)) {
10617 return micromatch.isMatch(str, pattern, Object.assign({}, options, {
10622 * Filter the keys of the given object with the given `glob` pattern
10623 * and `options`. Does not attempt to match nested keys. If you need this feature,
10624 * use [glob-object][] instead.
10627 * const mm = require('micromatch');
10628 * // mm.matchKeys(object, patterns[, options]);
10630 * const obj = { aa: 'a', ab: 'b', ac: 'c' };
10631 * console.log(mm.matchKeys(obj, '*b'));
10634 * @param {Object} `object` The object with keys to filter.
10635 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
10636 * @param {Object} `options` See available [options](#options) for changing how matches are performed
10637 * @return {Object} Returns an object with only keys that match the given patterns.
10642 micromatch.matchKeys = (obj, patterns, options) => {
10643 if (!utils$1.isObject(obj)) {
10644 throw new TypeError('Expected the first argument to be an object');
10647 let keys = micromatch(Object.keys(obj), patterns, options);
10650 for (let key of keys) res[key] = obj[key];
10655 * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
10658 * const mm = require('micromatch');
10659 * // mm.some(list, patterns[, options]);
10661 * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
10663 * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
10666 * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
10667 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
10668 * @param {Object} `options` See available [options](#options) for changing how matches are performed
10669 * @return {Boolean} Returns true if any patterns match `str`
10674 micromatch.some = (list, patterns, options) => {
10675 let items = [].concat(list);
10677 for (let pattern of [].concat(patterns)) {
10678 let isMatch = picomatch$1(String(pattern), options);
10680 if (items.some(item => isMatch(item))) {
10688 * Returns true if every string in the given `list` matches
10689 * any of the given glob `patterns`.
10692 * const mm = require('micromatch');
10693 * // mm.every(list, patterns[, options]);
10695 * console.log(mm.every('foo.js', ['foo.js']));
10697 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
10699 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
10701 * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
10704 * @param {String|Array} `list` The string or array of strings to test.
10705 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
10706 * @param {Object} `options` See available [options](#options) for changing how matches are performed
10707 * @return {Boolean} Returns true if any patterns match `str`
10712 micromatch.every = (list, patterns, options) => {
10713 let items = [].concat(list);
10715 for (let pattern of [].concat(patterns)) {
10716 let isMatch = picomatch$1(String(pattern), options);
10718 if (!items.every(item => isMatch(item))) {
10726 * Returns true if **all** of the given `patterns` match
10727 * the specified string.
10730 * const mm = require('micromatch');
10731 * // mm.all(string, patterns[, options]);
10733 * console.log(mm.all('foo.js', ['foo.js']));
10736 * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
10739 * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
10742 * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
10745 * @param {String|Array} `str` The string to test.
10746 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
10747 * @param {Object} `options` See available [options](#options) for changing how matches are performed
10748 * @return {Boolean} Returns true if any patterns match `str`
10753 micromatch.all = (str, patterns, options) => {
10754 if (typeof str !== 'string') {
10755 throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`);
10758 return [].concat(patterns).every(p => picomatch$1(p, options)(str));
10761 * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
10764 * const mm = require('micromatch');
10765 * // mm.capture(pattern, string[, options]);
10767 * console.log(mm.capture('test/*.js', 'test/foo.js'));
10769 * console.log(mm.capture('test/*.js', 'foo/bar.css'));
10772 * @param {String} `glob` Glob pattern to use for matching.
10773 * @param {String} `input` String to match
10774 * @param {Object} `options` See available [options](#options) for changing how matches are performed
10775 * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
10780 micromatch.capture = (glob, input, options) => {
10781 let posix = utils$1.isWindows(options);
10782 let regex = picomatch$1.makeRe(String(glob), Object.assign({}, options, {
10785 let match = regex.exec(posix ? utils$1.toPosixSlashes(input) : input);
10788 return match.slice(1).map(v => v === void 0 ? '' : v);
10792 * Create a regular expression from the given glob `pattern`.
10795 * const mm = require('micromatch');
10796 * // mm.makeRe(pattern[, options]);
10798 * console.log(mm.makeRe('*.js'));
10799 * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
10801 * @param {String} `pattern` A glob pattern to convert to regex.
10802 * @param {Object} `options`
10803 * @return {RegExp} Returns a regex created from the given pattern.
10808 micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);
10810 * Scan a glob pattern to separate the pattern into segments. Used
10811 * by the [split](#split) method.
10814 * const mm = require('micromatch');
10815 * const state = mm.scan(pattern[, options]);
10817 * @param {String} `pattern`
10818 * @param {Object} `options`
10819 * @return {Object} Returns an object with
10824 micromatch.scan = (...args) => picomatch$1.scan(...args);
10826 * Parse a glob pattern to create the source string for a regular
10830 * const mm = require('micromatch');
10831 * const state = mm(pattern[, options]);
10833 * @param {String} `glob`
10834 * @param {Object} `options`
10835 * @return {Object} Returns an object with useful properties and output to be used as regex source string.
10840 micromatch.parse = (patterns, options) => {
10843 for (let pattern of [].concat(patterns || [])) {
10844 for (let str of braces_1(String(pattern), options)) {
10845 res.push(picomatch$1.parse(str, options));
10852 * Process the given brace `pattern`.
10855 * const { braces } = require('micromatch');
10856 * console.log(braces('foo/{a,b,c}/bar'));
10857 * //=> [ 'foo/(a|b|c)/bar' ]
10859 * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
10860 * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
10862 * @param {String} `pattern` String with brace pattern to process.
10863 * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
10869 micromatch.braces = (pattern, options) => {
10870 if (typeof pattern !== 'string') throw new TypeError('Expected a string');
10872 if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) {
10876 return braces_1(pattern, options);
10883 micromatch.braceExpand = (pattern, options) => {
10884 if (typeof pattern !== 'string') throw new TypeError('Expected a string');
10885 return micromatch.braces(pattern, Object.assign({}, options, {
10890 * Expose micromatch
10894 var micromatch_1 = micromatch;
10896 var pattern = createCommonjsModule(function (module, exports) {
10898 Object.defineProperty(exports, "__esModule", {
10901 exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0;
10902 const GLOBSTAR = '**';
10903 const ESCAPE_SYMBOL = '\\';
10904 const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/;
10905 const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/;
10906 const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/;
10907 const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/;
10908 const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/;
10910 function isStaticPattern(pattern, options = {}) {
10911 return !isDynamicPattern(pattern, options);
10914 exports.isStaticPattern = isStaticPattern;
10916 function isDynamicPattern(pattern, options = {}) {
10918 * A special case with an empty string is necessary for matching patterns that start with a forward slash.
\r
10919 * An empty string cannot be a dynamic pattern.
\r
10920 * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'.
\r
10922 if (pattern === '') {
10926 * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check
\r
10927 * filepath directly (without read directory).
\r
10931 if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) {
10935 if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) {
10939 if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) {
10943 if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) {
10950 exports.isDynamicPattern = isDynamicPattern;
10952 function convertToPositivePattern(pattern) {
10953 return isNegativePattern(pattern) ? pattern.slice(1) : pattern;
10956 exports.convertToPositivePattern = convertToPositivePattern;
10958 function convertToNegativePattern(pattern) {
10959 return '!' + pattern;
10962 exports.convertToNegativePattern = convertToNegativePattern;
10964 function isNegativePattern(pattern) {
10965 return pattern.startsWith('!') && pattern[1] !== '(';
10968 exports.isNegativePattern = isNegativePattern;
10970 function isPositivePattern(pattern) {
10971 return !isNegativePattern(pattern);
10974 exports.isPositivePattern = isPositivePattern;
10976 function getNegativePatterns(patterns) {
10977 return patterns.filter(isNegativePattern);
10980 exports.getNegativePatterns = getNegativePatterns;
10982 function getPositivePatterns(patterns) {
10983 return patterns.filter(isPositivePattern);
10986 exports.getPositivePatterns = getPositivePatterns;
10988 function getBaseDirectory(pattern) {
10989 return globParent(pattern, {
10990 flipBackslashes: false
10994 exports.getBaseDirectory = getBaseDirectory;
10996 function hasGlobStar(pattern) {
10997 return pattern.includes(GLOBSTAR);
11000 exports.hasGlobStar = hasGlobStar;
11002 function endsWithSlashGlobStar(pattern) {
11003 return pattern.endsWith('/' + GLOBSTAR);
11006 exports.endsWithSlashGlobStar = endsWithSlashGlobStar;
11008 function isAffectDepthOfReadingPattern(pattern) {
11009 const basename = path__default['default'].basename(pattern);
11010 return endsWithSlashGlobStar(pattern) || isStaticPattern(basename);
11013 exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
11015 function expandPatternsWithBraceExpansion(patterns) {
11016 return patterns.reduce((collection, pattern) => {
11017 return collection.concat(expandBraceExpansion(pattern));
11021 exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion;
11023 function expandBraceExpansion(pattern) {
11024 return micromatch_1.braces(pattern, {
11030 exports.expandBraceExpansion = expandBraceExpansion;
11032 function getPatternParts(pattern, options) {
11035 } = picomatch$1.scan(pattern, Object.assign(Object.assign({}, options), {
11039 * The scan method returns an empty array in some cases.
\r
11040 * See micromatch/picomatch#58 for more details.
\r
11043 if (parts.length === 0) {
11047 * The scan method does not return an empty part for the pattern with a forward slash.
\r
11048 * This is another part of micromatch/picomatch#58.
\r
11052 if (parts[0].startsWith('/')) {
11053 parts[0] = parts[0].slice(1);
11060 exports.getPatternParts = getPatternParts;
11062 function makeRe(pattern, options) {
11063 return micromatch_1.makeRe(pattern, options);
11066 exports.makeRe = makeRe;
11068 function convertPatternsToRe(patterns, options) {
11069 return patterns.map(pattern => makeRe(pattern, options));
11072 exports.convertPatternsToRe = convertPatternsToRe;
11074 function matchAny(entry, patternsRe) {
11075 return patternsRe.some(patternRe => patternRe.test(entry));
11078 exports.matchAny = matchAny;
11083 * https://github.com/teambition/merge2
11085 * Copyright (c) 2014-2020 Teambition
11086 * Licensed under the MIT license.
11090 const PassThrough = stream_1__default['default'].PassThrough;
11091 const slice = Array.prototype.slice;
11092 var merge2_1 = merge2;
11094 function merge2() {
11095 const streamsQueue = [];
11096 const args = slice.call(arguments);
11097 let merging = false;
11098 let options = args[args.length - 1];
11100 if (options && !Array.isArray(options) && options.pipe == null) {
11106 const doEnd = options.end !== false;
11107 const doPipeError = options.pipeError === true;
11109 if (options.objectMode == null) {
11110 options.objectMode = true;
11113 if (options.highWaterMark == null) {
11114 options.highWaterMark = 64 * 1024;
11117 const mergedStream = PassThrough(options);
11119 function addStream() {
11120 for (let i = 0, len = arguments.length; i < len; i++) {
11121 streamsQueue.push(pauseStreams(arguments[i], options));
11128 function mergeStream() {
11134 let streams = streamsQueue.shift();
11137 process.nextTick(endStream);
11141 if (!Array.isArray(streams)) {
11142 streams = [streams];
11145 let pipesCount = streams.length + 1;
11148 if (--pipesCount > 0) {
11156 function pipe(stream) {
11158 stream.removeListener('merge2UnpipeEnd', onend);
11159 stream.removeListener('end', onend);
11162 stream.removeListener('error', onerror);
11168 function onerror(err) {
11169 mergedStream.emit('error', err);
11170 } // skip ended stream
11173 if (stream._readableState.endEmitted) {
11177 stream.on('merge2UnpipeEnd', onend);
11178 stream.on('end', onend);
11181 stream.on('error', onerror);
11184 stream.pipe(mergedStream, {
11186 }); // compatible for old stream
11191 for (let i = 0; i < streams.length; i++) {
11198 function endStream() {
11199 merging = false; // emit 'queueDrain' when all streams merged.
11201 mergedStream.emit('queueDrain');
11204 mergedStream.end();
11208 mergedStream.setMaxListeners(0);
11209 mergedStream.add = addStream;
11210 mergedStream.on('unpipe', function (stream) {
11211 stream.emit('merge2UnpipeEnd');
11215 addStream.apply(null, args);
11218 return mergedStream;
11219 } // check and pause streams for pipe.
11222 function pauseStreams(streams, options) {
11223 if (!Array.isArray(streams)) {
11224 // Backwards-compat with old-style streams
11225 if (!streams._readableState && streams.pipe) {
11226 streams = streams.pipe(PassThrough(options));
11229 if (!streams._readableState || !streams.pause || !streams.pipe) {
11230 throw new Error('Only readable stream can be merged.');
11235 for (let i = 0, len = streams.length; i < len; i++) {
11236 streams[i] = pauseStreams(streams[i], options);
11243 var stream = createCommonjsModule(function (module, exports) {
11245 Object.defineProperty(exports, "__esModule", {
11248 exports.merge = void 0;
11250 function merge(streams) {
11251 const mergedStream = merge2_1(streams);
11252 streams.forEach(stream => {
11253 stream.once('error', error => mergedStream.emit('error', error));
11255 mergedStream.once('close', () => propagateCloseEventToSources(streams));
11256 mergedStream.once('end', () => propagateCloseEventToSources(streams));
11257 return mergedStream;
11260 exports.merge = merge;
11262 function propagateCloseEventToSources(streams) {
11263 streams.forEach(stream => stream.emit('close'));
11267 var string = createCommonjsModule(function (module, exports) {
11269 Object.defineProperty(exports, "__esModule", {
11272 exports.isEmpty = exports.isString = void 0;
11274 function isString(input) {
11275 return typeof input === 'string';
11278 exports.isString = isString;
11280 function isEmpty(input) {
11281 return input === '';
11284 exports.isEmpty = isEmpty;
11287 var utils$2 = createCommonjsModule(function (module, exports) {
11289 Object.defineProperty(exports, "__esModule", {
11292 exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0;
11293 exports.array = array;
11294 exports.errno = errno;
11296 exports.path = path_1;
11297 exports.pattern = pattern;
11298 exports.stream = stream;
11299 exports.string = string;
11302 var tasks = createCommonjsModule(function (module, exports) {
11304 Object.defineProperty(exports, "__esModule", {
11307 exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0;
11309 function generate(patterns, settings) {
11310 const positivePatterns = getPositivePatterns(patterns);
11311 const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore);
11312 const staticPatterns = positivePatterns.filter(pattern => utils$2.pattern.isStaticPattern(pattern, settings));
11313 const dynamicPatterns = positivePatterns.filter(pattern => utils$2.pattern.isDynamicPattern(pattern, settings));
11314 const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns,
11317 const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns,
11320 return staticTasks.concat(dynamicTasks);
11323 exports.generate = generate;
11325 function convertPatternsToTasks(positive, negative, dynamic) {
11326 const positivePatternsGroup = groupPatternsByBaseDirectory(positive); // When we have a global group – there is no reason to divide the patterns into independent tasks.
11327 // In this case, the global task covers the rest.
11329 if ('.' in positivePatternsGroup) {
11330 const task = convertPatternGroupToTask('.', positive, negative, dynamic);
11334 return convertPatternGroupsToTasks(positivePatternsGroup, negative, dynamic);
11337 exports.convertPatternsToTasks = convertPatternsToTasks;
11339 function getPositivePatterns(patterns) {
11340 return utils$2.pattern.getPositivePatterns(patterns);
11343 exports.getPositivePatterns = getPositivePatterns;
11345 function getNegativePatternsAsPositive(patterns, ignore) {
11346 const negative = utils$2.pattern.getNegativePatterns(patterns).concat(ignore);
11347 const positive = negative.map(utils$2.pattern.convertToPositivePattern);
11351 exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive;
11353 function groupPatternsByBaseDirectory(patterns) {
11355 return patterns.reduce((collection, pattern) => {
11356 const base = utils$2.pattern.getBaseDirectory(pattern);
11358 if (base in collection) {
11359 collection[base].push(pattern);
11361 collection[base] = [pattern];
11368 exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory;
11370 function convertPatternGroupsToTasks(positive, negative, dynamic) {
11371 return Object.keys(positive).map(base => {
11372 return convertPatternGroupToTask(base, positive[base], negative, dynamic);
11376 exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks;
11378 function convertPatternGroupToTask(base, positive, negative, dynamic) {
11384 patterns: [].concat(positive, negative.map(utils$2.pattern.convertToNegativePattern))
11388 exports.convertPatternGroupToTask = convertPatternGroupToTask;
11391 var async = createCommonjsModule(function (module, exports) {
11393 Object.defineProperty(exports, "__esModule", {
11397 function read(path, settings, callback) {
11398 settings.fs.lstat(path, (lstatError, lstat) => {
11399 if (lstatError !== null) {
11400 return callFailureCallback(callback, lstatError);
11403 if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
11404 return callSuccessCallback(callback, lstat);
11407 settings.fs.stat(path, (statError, stat) => {
11408 if (statError !== null) {
11409 if (settings.throwErrorOnBrokenSymbolicLink) {
11410 return callFailureCallback(callback, statError);
11413 return callSuccessCallback(callback, lstat);
11416 if (settings.markSymbolicLink) {
11417 stat.isSymbolicLink = () => true;
11420 callSuccessCallback(callback, stat);
11425 exports.read = read;
11427 function callFailureCallback(callback, error) {
11431 function callSuccessCallback(callback, result) {
11432 callback(null, result);
11436 var sync = createCommonjsModule(function (module, exports) {
11438 Object.defineProperty(exports, "__esModule", {
11442 function read(path, settings) {
11443 const lstat = settings.fs.lstatSync(path);
11445 if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) {
11450 const stat = settings.fs.statSync(path);
11452 if (settings.markSymbolicLink) {
11453 stat.isSymbolicLink = () => true;
11458 if (!settings.throwErrorOnBrokenSymbolicLink) {
11466 exports.read = read;
11469 var fs_1 = createCommonjsModule(function (module, exports) {
11471 Object.defineProperty(exports, "__esModule", {
11474 exports.FILE_SYSTEM_ADAPTER = {
11475 lstat: fs__default['default'].lstat,
11476 stat: fs__default['default'].stat,
11477 lstatSync: fs__default['default'].lstatSync,
11478 statSync: fs__default['default'].statSync
11481 function createFileSystemAdapter(fsMethods) {
11482 if (fsMethods === undefined) {
11483 return exports.FILE_SYSTEM_ADAPTER;
11486 return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
11489 exports.createFileSystemAdapter = createFileSystemAdapter;
11492 var settings = createCommonjsModule(function (module, exports) {
11494 Object.defineProperty(exports, "__esModule", {
11499 constructor(_options = {}) {
11500 this._options = _options;
11501 this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true);
11502 this.fs = fs_1.createFileSystemAdapter(this._options.fs);
11503 this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false);
11504 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
11507 _getValue(option, value) {
11508 return option === undefined ? value : option;
11513 exports.default = Settings;
11516 var out = createCommonjsModule(function (module, exports) {
11518 Object.defineProperty(exports, "__esModule", {
11521 exports.Settings = settings.default;
11523 function stat(path, optionsOrSettingsOrCallback, callback) {
11524 if (typeof optionsOrSettingsOrCallback === 'function') {
11525 return async.read(path, getSettings(), optionsOrSettingsOrCallback);
11528 async.read(path, getSettings(optionsOrSettingsOrCallback), callback);
11531 exports.stat = stat;
11533 function statSync(path, optionsOrSettings) {
11534 const settings = getSettings(optionsOrSettings);
11535 return sync.read(path, settings);
11538 exports.statSync = statSync;
11540 function getSettings(settingsOrOptions = {}) {
11541 if (settingsOrOptions instanceof settings.default) {
11542 return settingsOrOptions;
11545 return new settings.default(settingsOrOptions);
11549 var runParallel_1 = runParallel;
11551 function runParallel(tasks, cb) {
11552 var results, pending, keys;
11555 if (Array.isArray(tasks)) {
11557 pending = tasks.length;
11559 keys = Object.keys(tasks);
11561 pending = keys.length;
11564 function done(err) {
11566 if (cb) cb(err, results);
11570 if (isSync) process.nextTick(end);else end();
11573 function each(i, err, result) {
11574 results[i] = result;
11576 if (--pending === 0 || err) {
11586 keys.forEach(function (key) {
11587 tasks[key](function (err, result) {
11588 each(key, err, result);
11593 tasks.forEach(function (task, i) {
11594 task(function (err, result) {
11595 each(i, err, result);
11603 var constants$2 = createCommonjsModule(function (module, exports) {
11605 Object.defineProperty(exports, "__esModule", {
11608 const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.');
11609 const MAJOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[0], 10);
11610 const MINOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[1], 10);
11611 const SUPPORTED_MAJOR_VERSION = 10;
11612 const SUPPORTED_MINOR_VERSION = 10;
11613 const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION;
11614 const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION;
11616 * IS `true` for Node.js 10.10 and greater.
\r
11619 exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR;
11622 var fs$1 = createCommonjsModule(function (module, exports) {
11624 Object.defineProperty(exports, "__esModule", {
11628 class DirentFromStats {
11629 constructor(name, stats) {
11631 this.isBlockDevice = stats.isBlockDevice.bind(stats);
11632 this.isCharacterDevice = stats.isCharacterDevice.bind(stats);
11633 this.isDirectory = stats.isDirectory.bind(stats);
11634 this.isFIFO = stats.isFIFO.bind(stats);
11635 this.isFile = stats.isFile.bind(stats);
11636 this.isSocket = stats.isSocket.bind(stats);
11637 this.isSymbolicLink = stats.isSymbolicLink.bind(stats);
11642 function createDirentFromStats(name, stats) {
11643 return new DirentFromStats(name, stats);
11646 exports.createDirentFromStats = createDirentFromStats;
11649 var utils$3 = createCommonjsModule(function (module, exports) {
11651 Object.defineProperty(exports, "__esModule", {
11657 var async$1 = createCommonjsModule(function (module, exports) {
11659 Object.defineProperty(exports, "__esModule", {
11663 function read(directory, settings, callback) {
11664 if (!settings.stats && constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
11665 return readdirWithFileTypes(directory, settings, callback);
11668 return readdir(directory, settings, callback);
11671 exports.read = read;
11673 function readdirWithFileTypes(directory, settings, callback) {
11674 settings.fs.readdir(directory, {
11675 withFileTypes: true
11676 }, (readdirError, dirents) => {
11677 if (readdirError !== null) {
11678 return callFailureCallback(callback, readdirError);
11681 const entries = dirents.map(dirent => ({
11684 path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
11687 if (!settings.followSymbolicLinks) {
11688 return callSuccessCallback(callback, entries);
11691 const tasks = entries.map(entry => makeRplTaskEntry(entry, settings));
11692 runParallel_1(tasks, (rplError, rplEntries) => {
11693 if (rplError !== null) {
11694 return callFailureCallback(callback, rplError);
11697 callSuccessCallback(callback, rplEntries);
11702 exports.readdirWithFileTypes = readdirWithFileTypes;
11704 function makeRplTaskEntry(entry, settings) {
11706 if (!entry.dirent.isSymbolicLink()) {
11707 return done(null, entry);
11710 settings.fs.stat(entry.path, (statError, stats) => {
11711 if (statError !== null) {
11712 if (settings.throwErrorOnBrokenSymbolicLink) {
11713 return done(statError);
11716 return done(null, entry);
11719 entry.dirent = utils$3.fs.createDirentFromStats(entry.name, stats);
11720 return done(null, entry);
11725 function readdir(directory, settings, callback) {
11726 settings.fs.readdir(directory, (readdirError, names) => {
11727 if (readdirError !== null) {
11728 return callFailureCallback(callback, readdirError);
11731 const filepaths = names.map(name => `${directory}${settings.pathSegmentSeparator}${name}`);
11732 const tasks = filepaths.map(filepath => {
11733 return done => out.stat(filepath, settings.fsStatSettings, done);
11735 runParallel_1(tasks, (rplError, results) => {
11736 if (rplError !== null) {
11737 return callFailureCallback(callback, rplError);
11740 const entries = [];
11741 names.forEach((name, index) => {
11742 const stats = results[index];
11745 path: filepaths[index],
11746 dirent: utils$3.fs.createDirentFromStats(name, stats)
11749 if (settings.stats) {
11750 entry.stats = stats;
11753 entries.push(entry);
11755 callSuccessCallback(callback, entries);
11760 exports.readdir = readdir;
11762 function callFailureCallback(callback, error) {
11766 function callSuccessCallback(callback, result) {
11767 callback(null, result);
11771 var sync$1 = createCommonjsModule(function (module, exports) {
11773 Object.defineProperty(exports, "__esModule", {
11777 function read(directory, settings) {
11778 if (!settings.stats && constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES) {
11779 return readdirWithFileTypes(directory, settings);
11782 return readdir(directory, settings);
11785 exports.read = read;
11787 function readdirWithFileTypes(directory, settings) {
11788 const dirents = settings.fs.readdirSync(directory, {
11789 withFileTypes: true
11791 return dirents.map(dirent => {
11795 path: `${directory}${settings.pathSegmentSeparator}${dirent.name}`
11798 if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) {
11800 const stats = settings.fs.statSync(entry.path);
11801 entry.dirent = utils$3.fs.createDirentFromStats(entry.name, stats);
11803 if (settings.throwErrorOnBrokenSymbolicLink) {
11813 exports.readdirWithFileTypes = readdirWithFileTypes;
11815 function readdir(directory, settings) {
11816 const names = settings.fs.readdirSync(directory);
11817 return names.map(name => {
11818 const entryPath = `${directory}${settings.pathSegmentSeparator}${name}`;
11819 const stats = out.statSync(entryPath, settings.fsStatSettings);
11823 dirent: utils$3.fs.createDirentFromStats(name, stats)
11826 if (settings.stats) {
11827 entry.stats = stats;
11834 exports.readdir = readdir;
11837 var fs_1$1 = createCommonjsModule(function (module, exports) {
11839 Object.defineProperty(exports, "__esModule", {
11842 exports.FILE_SYSTEM_ADAPTER = {
11843 lstat: fs__default['default'].lstat,
11844 stat: fs__default['default'].stat,
11845 lstatSync: fs__default['default'].lstatSync,
11846 statSync: fs__default['default'].statSync,
11847 readdir: fs__default['default'].readdir,
11848 readdirSync: fs__default['default'].readdirSync
11851 function createFileSystemAdapter(fsMethods) {
11852 if (fsMethods === undefined) {
11853 return exports.FILE_SYSTEM_ADAPTER;
11856 return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods);
11859 exports.createFileSystemAdapter = createFileSystemAdapter;
11862 var settings$1 = createCommonjsModule(function (module, exports) {
11864 Object.defineProperty(exports, "__esModule", {
11869 constructor(_options = {}) {
11870 this._options = _options;
11871 this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false);
11872 this.fs = fs_1$1.createFileSystemAdapter(this._options.fs);
11873 this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep);
11874 this.stats = this._getValue(this._options.stats, false);
11875 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true);
11876 this.fsStatSettings = new out.Settings({
11877 followSymbolicLink: this.followSymbolicLinks,
11879 throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink
11883 _getValue(option, value) {
11884 return option === undefined ? value : option;
11889 exports.default = Settings;
11892 var out$1 = createCommonjsModule(function (module, exports) {
11894 Object.defineProperty(exports, "__esModule", {
11897 exports.Settings = settings$1.default;
11899 function scandir(path, optionsOrSettingsOrCallback, callback) {
11900 if (typeof optionsOrSettingsOrCallback === 'function') {
11901 return async$1.read(path, getSettings(), optionsOrSettingsOrCallback);
11904 async$1.read(path, getSettings(optionsOrSettingsOrCallback), callback);
11907 exports.scandir = scandir;
11909 function scandirSync(path, optionsOrSettings) {
11910 const settings = getSettings(optionsOrSettings);
11911 return sync$1.read(path, settings);
11914 exports.scandirSync = scandirSync;
11916 function getSettings(settingsOrOptions = {}) {
11917 if (settingsOrOptions instanceof settings$1.default) {
11918 return settingsOrOptions;
11921 return new settings$1.default(settingsOrOptions);
11925 function reusify(Constructor) {
11926 var head = new Constructor();
11930 var current = head;
11932 if (current.next) {
11933 head = current.next;
11935 head = new Constructor();
11939 current.next = null;
11943 function release(obj) {
11954 var reusify_1 = reusify;
11956 function fastqueue(context, worker, concurrency) {
11957 if (typeof context === 'function') {
11958 concurrency = worker;
11963 var cache = reusify_1(Task);
11964 var queueHead = null;
11965 var queueTail = null;
11973 concurrency: concurrency,
11978 getQueue: getQueue,
11982 killAndDrain: killAndDrain
11986 function running() {
11991 self.paused = true;
11994 function length() {
11995 var current = queueHead;
11999 current = current.next;
12006 function getQueue() {
12007 var current = queueHead;
12011 tasks.push(current.value);
12012 current = current.next;
12018 function resume() {
12019 if (!self.paused) return;
12020 self.paused = false;
12022 for (var i = 0; i < self.concurrency; i++) {
12029 return _running === 0 && self.length() === 0;
12032 function push(value, done) {
12033 var current = cache.get();
12034 current.context = context;
12035 current.release = release;
12036 current.value = value;
12037 current.callback = done || noop;
12039 if (_running === self.concurrency || self.paused) {
12041 queueTail.next = current;
12042 queueTail = current;
12044 queueHead = current;
12045 queueTail = current;
12050 worker.call(context, current.value, current.worked);
12054 function unshift(value, done) {
12055 var current = cache.get();
12056 current.context = context;
12057 current.release = release;
12058 current.value = value;
12059 current.callback = done || noop;
12061 if (_running === self.concurrency || self.paused) {
12063 current.next = queueHead;
12064 queueHead = current;
12066 queueHead = current;
12067 queueTail = current;
12072 worker.call(context, current.value, current.worked);
12076 function release(holder) {
12078 cache.release(holder);
12081 var next = queueHead;
12084 if (!self.paused) {
12085 if (queueTail === queueHead) {
12089 queueHead = next.next;
12091 worker.call(context, next.value, next.worked);
12093 if (queueTail === null) {
12099 } else if (--_running === 0) {
12110 function killAndDrain() {
12122 this.callback = noop;
12124 this.release = noop;
12125 this.context = null;
12128 this.worked = function worked(err, result) {
12129 var callback = self.callback;
12131 self.callback = noop;
12132 callback.call(self.context, err, result);
12133 self.release(self);
12137 var queue = fastqueue;
12139 var common = createCommonjsModule(function (module, exports) {
12141 Object.defineProperty(exports, "__esModule", {
12145 function isFatalError(settings, error) {
12146 if (settings.errorFilter === null) {
12150 return !settings.errorFilter(error);
12153 exports.isFatalError = isFatalError;
12155 function isAppliedFilter(filter, value) {
12156 return filter === null || filter(value);
12159 exports.isAppliedFilter = isAppliedFilter;
12161 function replacePathSegmentSeparator(filepath, separator) {
12162 return filepath.split(/[\\/]/).join(separator);
12165 exports.replacePathSegmentSeparator = replacePathSegmentSeparator;
12167 function joinPathSegments(a, b, separator) {
12172 return a + separator + b;
12175 exports.joinPathSegments = joinPathSegments;
12178 var reader = createCommonjsModule(function (module, exports) {
12180 Object.defineProperty(exports, "__esModule", {
12185 constructor(_root, _settings) {
12186 this._root = _root;
12187 this._settings = _settings;
12188 this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator);
12193 exports.default = Reader;
12196 var async$2 = createCommonjsModule(function (module, exports) {
12198 Object.defineProperty(exports, "__esModule", {
12202 class AsyncReader extends reader.default {
12203 constructor(_root, _settings) {
12204 super(_root, _settings);
12205 this._settings = _settings;
12206 this._scandir = out$1.scandir;
12207 this._emitter = new events_1__default['default'].EventEmitter();
12208 this._queue = queue(this._worker.bind(this), this._settings.concurrency);
12209 this._isFatalError = false;
12210 this._isDestroyed = false;
12212 this._queue.drain = () => {
12213 if (!this._isFatalError) {
12214 this._emitter.emit('end');
12220 this._isFatalError = false;
12221 this._isDestroyed = false;
12222 setImmediate(() => {
12223 this._pushToQueue(this._root, this._settings.basePath);
12225 return this._emitter;
12229 if (this._isDestroyed) {
12230 throw new Error('The reader is already destroyed');
12233 this._isDestroyed = true;
12235 this._queue.killAndDrain();
12238 onEntry(callback) {
12239 this._emitter.on('entry', callback);
12242 onError(callback) {
12243 this._emitter.once('error', callback);
12247 this._emitter.once('end', callback);
12250 _pushToQueue(directory, base) {
12251 const queueItem = {
12256 this._queue.push(queueItem, error => {
12257 if (error !== null) {
12258 this._handleError(error);
12263 _worker(item, done) {
12264 this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => {
12265 if (error !== null) {
12266 return done(error, undefined);
12269 for (const entry of entries) {
12270 this._handleEntry(entry, item.base);
12273 done(null, undefined);
12277 _handleError(error) {
12278 if (!common.isFatalError(this._settings, error)) {
12282 this._isFatalError = true;
12283 this._isDestroyed = true;
12285 this._emitter.emit('error', error);
12288 _handleEntry(entry, base) {
12289 if (this._isDestroyed || this._isFatalError) {
12293 const fullpath = entry.path;
12295 if (base !== undefined) {
12296 entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
12299 if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
12300 this._emitEntry(entry);
12303 if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
12304 this._pushToQueue(fullpath, entry.path);
12308 _emitEntry(entry) {
12309 this._emitter.emit('entry', entry);
12314 exports.default = AsyncReader;
12317 var async$3 = createCommonjsModule(function (module, exports) {
12319 Object.defineProperty(exports, "__esModule", {
12323 class AsyncProvider {
12324 constructor(_root, _settings) {
12325 this._root = _root;
12326 this._settings = _settings;
12327 this._reader = new async$2.default(this._root, this._settings);
12328 this._storage = new Set();
12332 this._reader.onError(error => {
12333 callFailureCallback(callback, error);
12336 this._reader.onEntry(entry => {
12337 this._storage.add(entry);
12340 this._reader.onEnd(() => {
12341 callSuccessCallback(callback, [...this._storage]);
12344 this._reader.read();
12349 exports.default = AsyncProvider;
12351 function callFailureCallback(callback, error) {
12355 function callSuccessCallback(callback, entries) {
12356 callback(null, entries);
12360 var stream$1 = createCommonjsModule(function (module, exports) {
12362 Object.defineProperty(exports, "__esModule", {
12366 class StreamProvider {
12367 constructor(_root, _settings) {
12368 this._root = _root;
12369 this._settings = _settings;
12370 this._reader = new async$2.default(this._root, this._settings);
12371 this._stream = new stream_1__default['default'].Readable({
12374 destroy: this._reader.destroy.bind(this._reader)
12379 this._reader.onError(error => {
12380 this._stream.emit('error', error);
12383 this._reader.onEntry(entry => {
12384 this._stream.push(entry);
12387 this._reader.onEnd(() => {
12388 this._stream.push(null);
12391 this._reader.read();
12393 return this._stream;
12398 exports.default = StreamProvider;
12401 var sync$2 = createCommonjsModule(function (module, exports) {
12403 Object.defineProperty(exports, "__esModule", {
12407 class SyncReader extends reader.default {
12409 super(...arguments);
12410 this._scandir = out$1.scandirSync;
12411 this._storage = new Set();
12412 this._queue = new Set();
12416 this._pushToQueue(this._root, this._settings.basePath);
12418 this._handleQueue();
12420 return [...this._storage];
12423 _pushToQueue(directory, base) {
12431 for (const item of this._queue.values()) {
12432 this._handleDirectory(item.directory, item.base);
12436 _handleDirectory(directory, base) {
12438 const entries = this._scandir(directory, this._settings.fsScandirSettings);
12440 for (const entry of entries) {
12441 this._handleEntry(entry, base);
12444 this._handleError(error);
12448 _handleError(error) {
12449 if (!common.isFatalError(this._settings, error)) {
12456 _handleEntry(entry, base) {
12457 const fullpath = entry.path;
12459 if (base !== undefined) {
12460 entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator);
12463 if (common.isAppliedFilter(this._settings.entryFilter, entry)) {
12464 this._pushToStorage(entry);
12467 if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) {
12468 this._pushToQueue(fullpath, entry.path);
12472 _pushToStorage(entry) {
12473 this._storage.add(entry);
12478 exports.default = SyncReader;
12481 var sync$3 = createCommonjsModule(function (module, exports) {
12483 Object.defineProperty(exports, "__esModule", {
12487 class SyncProvider {
12488 constructor(_root, _settings) {
12489 this._root = _root;
12490 this._settings = _settings;
12491 this._reader = new sync$2.default(this._root, this._settings);
12495 return this._reader.read();
12500 exports.default = SyncProvider;
12503 var settings$2 = createCommonjsModule(function (module, exports) {
12505 Object.defineProperty(exports, "__esModule", {
12510 constructor(_options = {}) {
12511 this._options = _options;
12512 this.basePath = this._getValue(this._options.basePath, undefined);
12513 this.concurrency = this._getValue(this._options.concurrency, Infinity);
12514 this.deepFilter = this._getValue(this._options.deepFilter, null);
12515 this.entryFilter = this._getValue(this._options.entryFilter, null);
12516 this.errorFilter = this._getValue(this._options.errorFilter, null);
12517 this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep);
12518 this.fsScandirSettings = new out$1.Settings({
12519 followSymbolicLinks: this._options.followSymbolicLinks,
12520 fs: this._options.fs,
12521 pathSegmentSeparator: this._options.pathSegmentSeparator,
12522 stats: this._options.stats,
12523 throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink
12527 _getValue(option, value) {
12528 return option === undefined ? value : option;
12533 exports.default = Settings;
12536 var out$2 = createCommonjsModule(function (module, exports) {
12538 Object.defineProperty(exports, "__esModule", {
12541 exports.Settings = settings$2.default;
12543 function walk(directory, optionsOrSettingsOrCallback, callback) {
12544 if (typeof optionsOrSettingsOrCallback === 'function') {
12545 return new async$3.default(directory, getSettings()).read(optionsOrSettingsOrCallback);
12548 new async$3.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback);
12551 exports.walk = walk;
12553 function walkSync(directory, optionsOrSettings) {
12554 const settings = getSettings(optionsOrSettings);
12555 const provider = new sync$3.default(directory, settings);
12556 return provider.read();
12559 exports.walkSync = walkSync;
12561 function walkStream(directory, optionsOrSettings) {
12562 const settings = getSettings(optionsOrSettings);
12563 const provider = new stream$1.default(directory, settings);
12564 return provider.read();
12567 exports.walkStream = walkStream;
12569 function getSettings(settingsOrOptions = {}) {
12570 if (settingsOrOptions instanceof settings$2.default) {
12571 return settingsOrOptions;
12574 return new settings$2.default(settingsOrOptions);
12578 var reader$1 = createCommonjsModule(function (module, exports) {
12580 Object.defineProperty(exports, "__esModule", {
12585 constructor(_settings) {
12586 this._settings = _settings;
12587 this._fsStatSettings = new out.Settings({
12588 followSymbolicLink: this._settings.followSymbolicLinks,
12589 fs: this._settings.fs,
12590 throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks
12594 _getFullEntryPath(filepath) {
12595 return path__default['default'].resolve(this._settings.cwd, filepath);
12598 _makeEntry(stats, pattern) {
12602 dirent: utils$2.fs.createDirentFromStats(pattern, stats)
12605 if (this._settings.stats) {
12606 entry.stats = stats;
12612 _isFatalError(error) {
12613 return !utils$2.errno.isEnoentCodeError(error) && !this._settings.suppressErrors;
12618 exports.default = Reader;
12621 var stream$2 = createCommonjsModule(function (module, exports) {
12623 Object.defineProperty(exports, "__esModule", {
12627 class ReaderStream extends reader$1.default {
12629 super(...arguments);
12630 this._walkStream = out$2.walkStream;
12631 this._stat = out.stat;
12634 dynamic(root, options) {
12635 return this._walkStream(root, options);
12638 static(patterns, options) {
12639 const filepaths = patterns.map(this._getFullEntryPath, this);
12640 const stream = new stream_1__default['default'].PassThrough({
12644 stream._write = (index, _enc, done) => {
12645 return this._getEntry(filepaths[index], patterns[index], options).then(entry => {
12646 if (entry !== null && options.entryFilter(entry)) {
12647 stream.push(entry);
12650 if (index === filepaths.length - 1) {
12658 for (let i = 0; i < filepaths.length; i++) {
12665 _getEntry(filepath, pattern, options) {
12666 return this._getStat(filepath).then(stats => this._makeEntry(stats, pattern)).catch(error => {
12667 if (options.errorFilter(error)) {
12675 _getStat(filepath) {
12676 return new Promise((resolve, reject) => {
12677 this._stat(filepath, this._fsStatSettings, (error, stats) => {
12678 return error === null ? resolve(stats) : reject(error);
12685 exports.default = ReaderStream;
12688 var matcher = createCommonjsModule(function (module, exports) {
12690 Object.defineProperty(exports, "__esModule", {
12695 constructor(_patterns, _settings, _micromatchOptions) {
12696 this._patterns = _patterns;
12697 this._settings = _settings;
12698 this._micromatchOptions = _micromatchOptions;
12699 this._storage = [];
12701 this._fillStorage();
12706 * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level).
\r
12707 * So, before expand patterns with brace expansion into separated patterns.
\r
12709 const patterns = utils$2.pattern.expandPatternsWithBraceExpansion(this._patterns);
12711 for (const pattern of patterns) {
12712 const segments = this._getPatternSegments(pattern);
12714 const sections = this._splitSegmentsIntoSections(segments);
12716 this._storage.push({
12717 complete: sections.length <= 1,
12725 _getPatternSegments(pattern) {
12726 const parts = utils$2.pattern.getPatternParts(pattern, this._micromatchOptions);
12727 return parts.map(part => {
12728 const dynamic = utils$2.pattern.isDynamicPattern(part, this._settings);
12740 patternRe: utils$2.pattern.makeRe(part, this._micromatchOptions)
12745 _splitSegmentsIntoSections(segments) {
12746 return utils$2.array.splitWhen(segments, segment => segment.dynamic && utils$2.pattern.hasGlobStar(segment.pattern));
12751 exports.default = Matcher;
12754 var partial = createCommonjsModule(function (module, exports) {
12756 Object.defineProperty(exports, "__esModule", {
12760 class PartialMatcher extends matcher.default {
12762 const parts = filepath.split('/');
12763 const levels = parts.length;
12765 const patterns = this._storage.filter(info => !info.complete || info.segments.length > levels);
12767 for (const pattern of patterns) {
12768 const section = pattern.sections[0];
12770 * In this case, the pattern has a globstar and we must read all directories unconditionally,
\r
12771 * but only if the level has reached the end of the first group.
\r
12773 * fixtures/{a,b}/**
\r
12774 * ^ true/false ^ always true
\r
12777 if (!pattern.complete && levels > section.length) {
12781 const match = parts.every((part, index) => {
12782 const segment = pattern.segments[index];
12784 if (segment.dynamic && segment.patternRe.test(part)) {
12788 if (!segment.dynamic && segment.pattern === part) {
12805 exports.default = PartialMatcher;
12808 var deep = createCommonjsModule(function (module, exports) {
12810 Object.defineProperty(exports, "__esModule", {
12815 constructor(_settings, _micromatchOptions) {
12816 this._settings = _settings;
12817 this._micromatchOptions = _micromatchOptions;
12820 getFilter(basePath, positive, negative) {
12821 const matcher = this._getMatcher(positive);
12823 const negativeRe = this._getNegativePatternsRe(negative);
12825 return entry => this._filter(basePath, entry, matcher, negativeRe);
12828 _getMatcher(patterns) {
12829 return new partial.default(patterns, this._settings, this._micromatchOptions);
12832 _getNegativePatternsRe(patterns) {
12833 const affectDepthOfReadingPatterns = patterns.filter(utils$2.pattern.isAffectDepthOfReadingPattern);
12834 return utils$2.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions);
12837 _filter(basePath, entry, matcher, negativeRe) {
12838 if (this._isSkippedByDeep(basePath, entry.path)) {
12842 if (this._isSkippedSymbolicLink(entry)) {
12846 const filepath = utils$2.path.removeLeadingDotSegment(entry.path);
12848 if (this._isSkippedByPositivePatterns(filepath, matcher)) {
12852 return this._isSkippedByNegativePatterns(filepath, negativeRe);
12855 _isSkippedByDeep(basePath, entryPath) {
12857 * Avoid unnecessary depth calculations when it doesn't matter.
\r
12859 if (this._settings.deep === Infinity) {
12863 return this._getEntryLevel(basePath, entryPath) >= this._settings.deep;
12866 _getEntryLevel(basePath, entryPath) {
12867 const entryPathDepth = entryPath.split('/').length;
12869 if (basePath === '') {
12870 return entryPathDepth;
12873 const basePathDepth = basePath.split('/').length;
12874 return entryPathDepth - basePathDepth;
12877 _isSkippedSymbolicLink(entry) {
12878 return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink();
12881 _isSkippedByPositivePatterns(entryPath, matcher) {
12882 return !this._settings.baseNameMatch && !matcher.match(entryPath);
12885 _isSkippedByNegativePatterns(entryPath, patternsRe) {
12886 return !utils$2.pattern.matchAny(entryPath, patternsRe);
12891 exports.default = DeepFilter;
12894 var entry = createCommonjsModule(function (module, exports) {
12896 Object.defineProperty(exports, "__esModule", {
12900 class EntryFilter {
12901 constructor(_settings, _micromatchOptions) {
12902 this._settings = _settings;
12903 this._micromatchOptions = _micromatchOptions;
12904 this.index = new Map();
12907 getFilter(positive, negative) {
12908 const positiveRe = utils$2.pattern.convertPatternsToRe(positive, this._micromatchOptions);
12909 const negativeRe = utils$2.pattern.convertPatternsToRe(negative, this._micromatchOptions);
12910 return entry => this._filter(entry, positiveRe, negativeRe);
12913 _filter(entry, positiveRe, negativeRe) {
12914 if (this._settings.unique && this._isDuplicateEntry(entry)) {
12918 if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) {
12922 if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) {
12926 const filepath = this._settings.baseNameMatch ? entry.name : entry.path;
12927 const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe);
12929 if (this._settings.unique && isMatched) {
12930 this._createIndexRecord(entry);
12936 _isDuplicateEntry(entry) {
12937 return this.index.has(entry.path);
12940 _createIndexRecord(entry) {
12941 this.index.set(entry.path, undefined);
12944 _onlyFileFilter(entry) {
12945 return this._settings.onlyFiles && !entry.dirent.isFile();
12948 _onlyDirectoryFilter(entry) {
12949 return this._settings.onlyDirectories && !entry.dirent.isDirectory();
12952 _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) {
12953 if (!this._settings.absolute) {
12957 const fullpath = utils$2.path.makeAbsolute(this._settings.cwd, entryPath);
12958 return utils$2.pattern.matchAny(fullpath, patternsRe);
12961 _isMatchToPatterns(entryPath, patternsRe) {
12962 const filepath = utils$2.path.removeLeadingDotSegment(entryPath);
12963 return utils$2.pattern.matchAny(filepath, patternsRe);
12968 exports.default = EntryFilter;
12971 var error = createCommonjsModule(function (module, exports) {
12973 Object.defineProperty(exports, "__esModule", {
12977 class ErrorFilter {
12978 constructor(_settings) {
12979 this._settings = _settings;
12983 return error => this._isNonFatalError(error);
12986 _isNonFatalError(error) {
12987 return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors;
12992 exports.default = ErrorFilter;
12995 var entry$1 = createCommonjsModule(function (module, exports) {
12997 Object.defineProperty(exports, "__esModule", {
13001 class EntryTransformer {
13002 constructor(_settings) {
13003 this._settings = _settings;
13007 return entry => this._transform(entry);
13010 _transform(entry) {
13011 let filepath = entry.path;
13013 if (this._settings.absolute) {
13014 filepath = utils$2.path.makeAbsolute(this._settings.cwd, filepath);
13015 filepath = utils$2.path.unixify(filepath);
13018 if (this._settings.markDirectories && entry.dirent.isDirectory()) {
13022 if (!this._settings.objectMode) {
13026 return Object.assign(Object.assign({}, entry), {
13033 exports.default = EntryTransformer;
13036 var provider = createCommonjsModule(function (module, exports) {
13038 Object.defineProperty(exports, "__esModule", {
13043 constructor(_settings) {
13044 this._settings = _settings;
13045 this.errorFilter = new error.default(this._settings);
13046 this.entryFilter = new entry.default(this._settings, this._getMicromatchOptions());
13047 this.deepFilter = new deep.default(this._settings, this._getMicromatchOptions());
13048 this.entryTransformer = new entry$1.default(this._settings);
13051 _getRootDirectory(task) {
13052 return path__default['default'].resolve(this._settings.cwd, task.base);
13055 _getReaderOptions(task) {
13056 const basePath = task.base === '.' ? '' : task.base;
13059 pathSegmentSeparator: '/',
13060 concurrency: this._settings.concurrency,
13061 deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative),
13062 entryFilter: this.entryFilter.getFilter(task.positive, task.negative),
13063 errorFilter: this.errorFilter.getFilter(),
13064 followSymbolicLinks: this._settings.followSymbolicLinks,
13065 fs: this._settings.fs,
13066 stats: this._settings.stats,
13067 throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink,
13068 transform: this.entryTransformer.getTransformer()
13072 _getMicromatchOptions() {
13074 dot: this._settings.dot,
13075 matchBase: this._settings.baseNameMatch,
13076 nobrace: !this._settings.braceExpansion,
13077 nocase: !this._settings.caseSensitiveMatch,
13078 noext: !this._settings.extglob,
13079 noglobstar: !this._settings.globstar,
13081 strictSlashes: false
13087 exports.default = Provider;
13090 var async$4 = createCommonjsModule(function (module, exports) {
13092 Object.defineProperty(exports, "__esModule", {
13096 class ProviderAsync extends provider.default {
13098 super(...arguments);
13099 this._reader = new stream$2.default(this._settings);
13103 const root = this._getRootDirectory(task);
13105 const options = this._getReaderOptions(task);
13107 const entries = [];
13108 return new Promise((resolve, reject) => {
13109 const stream = this.api(root, task, options);
13110 stream.once('error', reject);
13111 stream.on('data', entry => entries.push(options.transform(entry)));
13112 stream.once('end', () => resolve(entries));
13116 api(root, task, options) {
13117 if (task.dynamic) {
13118 return this._reader.dynamic(root, options);
13121 return this._reader.static(task.patterns, options);
13126 exports.default = ProviderAsync;
13129 var stream$3 = createCommonjsModule(function (module, exports) {
13131 Object.defineProperty(exports, "__esModule", {
13135 class ProviderStream extends provider.default {
13137 super(...arguments);
13138 this._reader = new stream$2.default(this._settings);
13142 const root = this._getRootDirectory(task);
13144 const options = this._getReaderOptions(task);
13146 const source = this.api(root, task, options);
13147 const destination = new stream_1__default['default'].Readable({
13151 source.once('error', error => destination.emit('error', error)).on('data', entry => destination.emit('data', options.transform(entry))).once('end', () => destination.emit('end'));
13152 destination.once('close', () => source.destroy());
13153 return destination;
13156 api(root, task, options) {
13157 if (task.dynamic) {
13158 return this._reader.dynamic(root, options);
13161 return this._reader.static(task.patterns, options);
13166 exports.default = ProviderStream;
13169 var sync$4 = createCommonjsModule(function (module, exports) {
13171 Object.defineProperty(exports, "__esModule", {
13175 class ReaderSync extends reader$1.default {
13177 super(...arguments);
13178 this._walkSync = out$2.walkSync;
13179 this._statSync = out.statSync;
13182 dynamic(root, options) {
13183 return this._walkSync(root, options);
13186 static(patterns, options) {
13187 const entries = [];
13189 for (const pattern of patterns) {
13190 const filepath = this._getFullEntryPath(pattern);
13192 const entry = this._getEntry(filepath, pattern, options);
13194 if (entry === null || !options.entryFilter(entry)) {
13198 entries.push(entry);
13204 _getEntry(filepath, pattern, options) {
13206 const stats = this._getStat(filepath);
13208 return this._makeEntry(stats, pattern);
13210 if (options.errorFilter(error)) {
13218 _getStat(filepath) {
13219 return this._statSync(filepath, this._fsStatSettings);
13224 exports.default = ReaderSync;
13227 var sync$5 = createCommonjsModule(function (module, exports) {
13229 Object.defineProperty(exports, "__esModule", {
13233 class ProviderSync extends provider.default {
13235 super(...arguments);
13236 this._reader = new sync$4.default(this._settings);
13240 const root = this._getRootDirectory(task);
13242 const options = this._getReaderOptions(task);
13244 const entries = this.api(root, task, options);
13245 return entries.map(options.transform);
13248 api(root, task, options) {
13249 if (task.dynamic) {
13250 return this._reader.dynamic(root, options);
13253 return this._reader.static(task.patterns, options);
13258 exports.default = ProviderSync;
13261 var settings$3 = createCommonjsModule(function (module, exports) {
13263 Object.defineProperty(exports, "__esModule", {
13266 exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0;
13267 const CPU_COUNT = os__default['default'].cpus().length;
13268 exports.DEFAULT_FILE_SYSTEM_ADAPTER = {
13269 lstat: fs__default['default'].lstat,
13270 lstatSync: fs__default['default'].lstatSync,
13271 stat: fs__default['default'].stat,
13272 statSync: fs__default['default'].statSync,
13273 readdir: fs__default['default'].readdir,
13274 readdirSync: fs__default['default'].readdirSync
13278 constructor(_options = {}) {
13279 this._options = _options;
13280 this.absolute = this._getValue(this._options.absolute, false);
13281 this.baseNameMatch = this._getValue(this._options.baseNameMatch, false);
13282 this.braceExpansion = this._getValue(this._options.braceExpansion, true);
13283 this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true);
13284 this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT);
13285 this.cwd = this._getValue(this._options.cwd, process.cwd());
13286 this.deep = this._getValue(this._options.deep, Infinity);
13287 this.dot = this._getValue(this._options.dot, false);
13288 this.extglob = this._getValue(this._options.extglob, true);
13289 this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true);
13290 this.fs = this._getFileSystemMethods(this._options.fs);
13291 this.globstar = this._getValue(this._options.globstar, true);
13292 this.ignore = this._getValue(this._options.ignore, []);
13293 this.markDirectories = this._getValue(this._options.markDirectories, false);
13294 this.objectMode = this._getValue(this._options.objectMode, false);
13295 this.onlyDirectories = this._getValue(this._options.onlyDirectories, false);
13296 this.onlyFiles = this._getValue(this._options.onlyFiles, true);
13297 this.stats = this._getValue(this._options.stats, false);
13298 this.suppressErrors = this._getValue(this._options.suppressErrors, false);
13299 this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false);
13300 this.unique = this._getValue(this._options.unique, true);
13302 if (this.onlyDirectories) {
13303 this.onlyFiles = false;
13307 this.objectMode = true;
13311 _getValue(option, value) {
13312 return option === undefined ? value : option;
13315 _getFileSystemMethods(methods = {}) {
13316 return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods);
13321 exports.default = Settings;
13324 async function FastGlob(source, options) {
13325 assertPatternsInput(source);
13326 const works = getWorks(source, async$4.default, options);
13327 const result = await Promise.all(works);
13328 return utils$2.array.flatten(result);
13329 } // https://github.com/typescript-eslint/typescript-eslint/issues/60
13330 // eslint-disable-next-line no-redeclare
13333 (function (FastGlob) {
13334 function sync(source, options) {
13335 assertPatternsInput(source);
13336 const works = getWorks(source, sync$5.default, options);
13337 return utils$2.array.flatten(works);
13340 FastGlob.sync = sync;
13342 function stream(source, options) {
13343 assertPatternsInput(source);
13344 const works = getWorks(source, stream$3.default, options);
13346 * The stream returned by the provider cannot work with an asynchronous iterator.
\r
13347 * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams.
\r
13348 * This affects performance (+25%). I don't see best solution right now.
\r
13351 return utils$2.stream.merge(works);
13354 FastGlob.stream = stream;
13356 function generateTasks(source, options) {
13357 assertPatternsInput(source);
13358 const patterns = [].concat(source);
13359 const settings = new settings$3.default(options);
13360 return tasks.generate(patterns, settings);
13363 FastGlob.generateTasks = generateTasks;
13365 function isDynamicPattern(source, options) {
13366 assertPatternsInput(source);
13367 const settings = new settings$3.default(options);
13368 return utils$2.pattern.isDynamicPattern(source, settings);
13371 FastGlob.isDynamicPattern = isDynamicPattern;
13373 function escapePath(source) {
13374 assertPatternsInput(source);
13375 return utils$2.path.escape(source);
13378 FastGlob.escapePath = escapePath;
13379 })(FastGlob || (FastGlob = {}));
13381 function getWorks(source, _Provider, options) {
13382 const patterns = [].concat(source);
13383 const settings = new settings$3.default(options);
13384 const tasks$1 = tasks.generate(patterns, settings);
13385 const provider = new _Provider(settings);
13386 return tasks$1.map(provider.read, provider);
13389 function assertPatternsInput(input) {
13390 const source = [].concat(input);
13391 const isValidSource = source.every(item => utils$2.string.isString(item) && !utils$2.string.isEmpty(item));
13393 if (!isValidSource) {
13394 throw new TypeError('Patterns must be a string (non empty) or an array of strings');
13398 var out$3 = FastGlob;
13400 /** @typedef {import('./util').Context} Context */
13403 * @param {Context} context
13407 function* expandPatterns(context) {
13408 const cwd = process.cwd();
13409 const seen = new Set();
13410 let noResults = true;
13412 for (const pathOrError of expandPatternsInternal(context)) {
13415 if (typeof pathOrError !== "string") {
13420 const relativePath = path__default['default'].relative(cwd, pathOrError); // filter out duplicates
13422 if (seen.has(relativePath)) {
13426 seen.add(relativePath);
13427 yield relativePath;
13431 // If there was no files and no other errors, let's yield a general error.
13433 error: `No matching files. Patterns: ${context.filePatterns.join(" ")}`
13438 * @param {Context} context
13442 function* expandPatternsInternal(context) {
13443 // Ignores files in version control systems directories and `node_modules`
13444 const silentlyIgnoredDirs = {
13448 node_modules: context.argv["with-node-modules"] !== true
13450 const globOptions = {
13452 ignore: Object.keys(silentlyIgnoredDirs).filter(dir => silentlyIgnoredDirs[dir]).map(dir => "**/" + dir)
13454 let supportedFilesGlob;
13455 const cwd = process.cwd();
13456 /** @type {Array<{ type: 'file' | 'dir' | 'glob'; glob: string; input: string; }>} */
13458 const entries = [];
13460 for (const pattern of context.filePatterns) {
13461 const absolutePath = path__default['default'].resolve(cwd, pattern);
13463 if (containsIgnoredPathSegment(absolutePath, cwd, silentlyIgnoredDirs)) {
13467 const stat = statSafeSync(absolutePath);
13470 if (stat.isFile()) {
13473 glob: escapePathForGlob(fixWindowsSlashes(pattern)),
13476 } else if (stat.isDirectory()) {
13479 glob: escapePathForGlob(fixWindowsSlashes(pattern)) + "/" + getSupportedFilesGlob(),
13483 } else if (pattern[0] === "!") {
13484 // convert negative patterns to `ignore` entries
13485 globOptions.ignore.push(fixWindowsSlashes(pattern.slice(1)));
13489 glob: fixWindowsSlashes(pattern),
13503 result = out$3.sync(glob, globOptions);
13507 /* istanbul ignore next */
13509 error: `${errorMessages.globError[type]}: ${input}\n${message}`
13511 /* istanbul ignore next */
13516 if (result.length === 0) {
13518 error: `${errorMessages.emptyResults[type]}: "${input}".`
13521 yield* sortPaths(result);
13525 function getSupportedFilesGlob() {
13526 if (!supportedFilesGlob) {
13527 const extensions = flatten_1(context.languages.map(lang => lang.extensions || []));
13528 const filenames = flatten_1(context.languages.map(lang => lang.filenames || []));
13529 supportedFilesGlob = `**/{${extensions.map(ext => "*" + (ext[0] === "." ? ext : "." + ext)).concat(filenames)}}`;
13532 return supportedFilesGlob;
13536 const errorMessages = {
13538 file: "Unable to resolve file",
13539 dir: "Unable to expand directory",
13540 glob: "Unable to expand glob pattern"
13543 file: "Explicitly specified file was ignored due to negative glob patterns",
13544 dir: "No supported files were found in the directory",
13545 glob: "No files matching the pattern were found"
13549 * @param {string} absolutePath
13550 * @param {string} cwd
13551 * @param {Record<string, boolean>} ignoredDirectories
13554 function containsIgnoredPathSegment(absolutePath, cwd, ignoredDirectories) {
13555 return path__default['default'].relative(cwd, absolutePath).split(path__default['default'].sep).some(dir => ignoredDirectories[dir]);
13558 * @param {string[]} paths
13562 function sortPaths(paths) {
13563 return paths.sort((a, b) => a.localeCompare(b));
13566 * Get stats of a given path.
13567 * @param {string} filePath The path to target file.
13568 * @returns {fs.Stats | undefined} The stats.
13572 function statSafeSync(filePath) {
13574 return fs__default['default'].statSync(filePath);
13576 /* istanbul ignore next */
13577 if (error.code !== "ENOENT") {
13583 * This function should be replaced with `fastGlob.escapePath` when these issues are fixed:
13584 * - https://github.com/mrmlnc/fast-glob/issues/261
13585 * - https://github.com/mrmlnc/fast-glob/issues/262
13586 * @param {string} path
13590 function escapePathForGlob(path) {
13591 return out$3.escapePath(path.replace(/\\/g, "\0") // Workaround for fast-glob#262 (part 1)
13592 ).replace(/\\!/g, "@(!)") // Workaround for fast-glob#261
13593 .replace(/\0/g, "@(\\\\)"); // Workaround for fast-glob#262 (part 2)
13596 const isWindows = path__default['default'].sep === "\\";
13598 * Using backslashes in globs is probably not okay, but not accepting
13599 * backslashes as path separators on Windows is even more not okay.
13600 * https://github.com/prettier/prettier/pull/6776#discussion_r380723717
13601 * https://github.com/mrmlnc/fast-glob#how-to-write-patterns-on-windows
13602 * @param {string} pattern
13605 function fixWindowsSlashes(pattern) {
13606 return isWindows ? pattern.replace(/\\/g, "/") : pattern;
13609 var expandPatterns_1 = {
13614 var lib = createCommonjsModule(function (module, exports) {
13616 Object.defineProperty(exports, "__esModule", {
13618 }); // In the absence of a WeakSet or WeakMap implementation, don't break, but don't cache either.
13623 for (var _i = 0; _i < arguments.length; _i++) {
13624 args[_i] = arguments[_i];
13628 function createWeakMap() {
13629 if (typeof WeakMap !== 'undefined') {
13630 return new WeakMap();
13632 return fakeSetOrMap();
13636 * Creates and returns a no-op implementation of a WeakMap / WeakSet that never stores anything.
13640 function fakeSetOrMap() {
13646 has: function (k) {
13650 } // Safe hasOwnProperty
13653 var hop = Object.prototype.hasOwnProperty;
13655 var has = function (obj, prop) {
13656 return hop.call(obj, prop);
13657 }; // Copy all own enumerable properties from source to target
13660 function extend(target, source) {
13661 for (var prop in source) {
13662 if (has(source, prop)) {
13663 target[prop] = source[prop];
13670 var reLeadingNewline = /^[ \t]*(?:\r\n|\r|\n)/;
13671 var reTrailingNewline = /(?:\r\n|\r|\n)[ \t]*$/;
13672 var reStartsWithNewlineOrIsEmpty = /^(?:[\r\n]|$)/;
13673 var reDetectIndentation = /(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/;
13674 var reOnlyWhitespaceWithAtLeastOneNewline = /^[ \t]*[\r\n][ \t\r\n]*$/;
13676 function _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options) {
13677 // If first interpolated value is a reference to outdent,
13678 // determine indentation level from the indentation of the interpolated value.
13679 var indentationLevel = 0;
13680 var match = strings[0].match(reDetectIndentation);
13683 indentationLevel = match[1].length;
13686 var reSource = "(\\r\\n|\\r|\\n).{0," + indentationLevel + "}";
13687 var reMatchIndent = new RegExp(reSource, 'g');
13689 if (firstInterpolatedValueSetsIndentationLevel) {
13690 strings = strings.slice(1);
13693 var newline = options.newline,
13694 trimLeadingNewline = options.trimLeadingNewline,
13695 trimTrailingNewline = options.trimTrailingNewline;
13696 var normalizeNewlines = typeof newline === 'string';
13697 var l = strings.length;
13698 var outdentedStrings = strings.map(function (v, i) {
13699 // Remove leading indentation from all lines
13700 v = v.replace(reMatchIndent, '$1'); // Trim a leading newline from the first string
13702 if (i === 0 && trimLeadingNewline) {
13703 v = v.replace(reLeadingNewline, '');
13704 } // Trim a trailing newline from the last string
13707 if (i === l - 1 && trimTrailingNewline) {
13708 v = v.replace(reTrailingNewline, '');
13709 } // Normalize newlines
13712 if (normalizeNewlines) {
13713 v = v.replace(/\r\n|\n|\r/g, function (_) {
13720 return outdentedStrings;
13723 function concatStringsAndValues(strings, values) {
13726 for (var i = 0, l = strings.length; i < l; i++) {
13737 function isTemplateStringsArray(v) {
13738 return has(v, 'raw') && has(v, 'length');
13741 * It is assumed that opts will not change. If this is a problem, clone your options object and pass the clone to
13744 * @return {outdent}
13748 function createInstance(options) {
13749 /** Cache of pre-processed template literal arrays */
13750 var arrayAutoIndentCache = createWeakMap();
13752 * Cache of pre-processed template literal arrays, where first interpolated value is a reference to outdent,
13753 * before interpolated values are injected.
13756 var arrayFirstInterpSetsIndentCache = createWeakMap();
13758 function outdent(stringsOrOptions) {
13761 for (var _i = 1; _i < arguments.length; _i++) {
13762 values[_i - 1] = arguments[_i];
13764 /* tslint:enable:no-shadowed-variable */
13767 if (isTemplateStringsArray(stringsOrOptions)) {
13768 var strings = stringsOrOptions; // Is first interpolated value a reference to outdent, alone on its own line, without any preceding non-whitespace?
13770 var firstInterpolatedValueSetsIndentationLevel = (values[0] === outdent || values[0] === defaultOutdent) && reOnlyWhitespaceWithAtLeastOneNewline.test(strings[0]) && reStartsWithNewlineOrIsEmpty.test(strings[1]); // Perform outdentation
13772 var cache = firstInterpolatedValueSetsIndentationLevel ? arrayFirstInterpSetsIndentCache : arrayAutoIndentCache;
13773 var renderedArray = cache.get(strings);
13775 if (!renderedArray) {
13776 renderedArray = _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options);
13777 cache.set(strings, renderedArray);
13779 /** If no interpolated values, skip concatenation step */
13782 if (values.length === 0) {
13783 return renderedArray[0];
13785 /** Concatenate string literals with interpolated values */
13788 var rendered = concatStringsAndValues(renderedArray, firstInterpolatedValueSetsIndentationLevel ? values.slice(1) : values);
13791 // Create and return a new instance of outdent with the given options
13792 return createInstance(extend(extend({}, options), stringsOrOptions || {}));
13796 var fullOutdent = extend(outdent, {
13797 string: function (str) {
13798 return _outdentArray([str], false, options)[0];
13801 return fullOutdent;
13804 var defaultOutdent = createInstance({
13805 trimLeadingNewline: true,
13806 trimTrailingNewline: true
13808 exports.outdent = defaultOutdent; // Named exports. Simple and preferred.
13809 // import outdent from 'outdent';
13811 exports.default = defaultOutdent;
13814 // In webpack harmony-modules environments, module.exports is read-only,
13815 // so we fail gracefully.
13817 module.exports = defaultOutdent;
13818 Object.defineProperty(defaultOutdent, '__esModule', {
13821 defaultOutdent.default = defaultOutdent;
13822 defaultOutdent.outdent = defaultOutdent;
13832 } = prettierInternal;
13833 const categoryOrder = [coreOptions.CATEGORY_OUTPUT, coreOptions.CATEGORY_FORMAT, coreOptions.CATEGORY_CONFIG, coreOptions.CATEGORY_EDITOR, coreOptions.CATEGORY_OTHER];
13837 * // The type of the option. For 'choice', see also `choices` below.
13838 * // When passing a type other than the ones listed below, the option is
13839 * // treated as taking any string as argument, and `--option <${type}>` will
13840 * // be displayed in --help.
13841 * type: "boolean" | "choice" | "int" | string;
13843 * // Default value to be passed to the minimist option `default`.
13846 * // Alias name to be passed to the minimist option `alias`.
13849 * // For grouping options by category in --help.
13850 * category?: string;
13852 * // Description to be displayed in --help. If omitted, the option won't be
13853 * // shown at all in --help (but see also `oppositeDescription` below).
13854 * description?: string;
13856 * // Description for `--no-${name}` to be displayed in --help. If omitted,
13857 * // `--no-${name}` won't be shown.
13858 * oppositeDescription?: string;
13860 * // Indicate if this option is simply passed to the API.
13861 * // true: use camelified name as the API option name.
13862 * // string: use this value as the API option name.
13863 * forwardToApi?: boolean | string;
13865 * // Indicate that a CLI flag should be an array when forwarded to the API.
13868 * // Specify available choices for validation. They will also be displayed
13869 * // in --help as <a|b|c>.
13870 * // Use an object instead of a string if a choice is deprecated and should
13871 * // be treated as `redirect` instead, or if you'd like to add description for
13875 * | { value: string, description?: string, deprecated?: boolean, redirect?: string }
13878 * // If the option has a value that is an exception to the regular value
13879 * // constraints, indicate that value here (or use a function for more
13881 * exception?: ((value: any) => boolean);
13883 * // Indicate that the option is deprecated. Use a string to add an extra
13884 * // message to --help for the option, for example to suggest a replacement
13886 * deprecated?: true | string;
13890 * Note: The options below are sorted alphabetically.
13896 category: coreOptions.CATEGORY_OUTPUT,
13898 description: outdent`
13899 Check if the given files are formatted, print a human-friendly summary
13900 message and paths to unformatted files (see also --list-different).
13904 // The supports-color package (a sub sub dependency) looks directly at
13905 // `process.argv` for `--no-color` and such-like options. The reason it is
13906 // listed here is to avoid "Ignored unknown option: --no-color" warnings.
13907 // See https://github.com/chalk/supports-color/#info for more information.
13910 description: "Colorize error messages.",
13911 oppositeDescription: "Do not colorize error messages."
13915 category: coreOptions.CATEGORY_CONFIG,
13916 description: "Path to a Prettier configuration file (.prettierrc, package.json, prettier.config.js).",
13917 oppositeDescription: "Do not look for a configuration file.",
13918 exception: value => value === false
13920 "config-precedence": {
13922 category: coreOptions.CATEGORY_CONFIG,
13923 default: "cli-override",
13925 value: "cli-override",
13926 description: "CLI options take precedence over config file"
13928 value: "file-override",
13929 description: "Config file take precedence over CLI options"
13931 value: "prefer-file",
13932 description: outdent`
13933 If a config file is found will evaluate it and ignore other CLI options.
13934 If no config file is found CLI options will evaluate as normal.
13937 description: "Define in which order config files and CLI options should be evaluated."
13939 "debug-benchmark": {
13940 // Run the formatting benchmarks. Requires 'benchmark' module to be installed.
13944 // Run the formatting once again on the formatted output, throw if different.
13947 "debug-print-doc": {
13951 // Repeat the formatting a few times and measure the average duration.
13957 category: coreOptions.CATEGORY_CONFIG,
13958 description: "Take .editorconfig into account when parsing configuration.",
13959 oppositeDescription: "Don't take .editorconfig into account when parsing configuration.",
13962 "find-config-path": {
13964 category: coreOptions.CATEGORY_CONFIG,
13965 description: "Find and print the path to a configuration file for the given input file."
13969 description: outdent`
13970 Extract the following info (as JSON) for a given file path. Reported fields:
13971 * ignored (boolean) - true if file path is filtered by --ignore-path
13972 * inferredParser (string | null) - name of parser inferred from file path
13978 description: outdent`
13979 Show CLI usage, or details about the given flag.
13980 Example: --help write
13982 exception: value => value === ""
13986 category: coreOptions.CATEGORY_CONFIG,
13987 default: ".prettierignore",
13988 description: "Path to a file with patterns describing files to ignore."
13990 "ignore-unknown": {
13993 description: "Ignore unknown files."
13995 "list-different": {
13997 category: coreOptions.CATEGORY_OUTPUT,
13999 description: "Print the names of files that are different from Prettier's formatting (see also --check)."
14003 description: "What level of logs to report.",
14005 choices: ["silent", "error", "warn", "log", "debug"]
14009 description: "Print support information as JSON."
14014 description: "Print Prettier version."
14016 "with-node-modules": {
14018 category: coreOptions.CATEGORY_CONFIG,
14019 description: "Process files inside 'node_modules' directory."
14024 category: coreOptions.CATEGORY_OUTPUT,
14025 description: "Edit files in-place. (Beware!)"
14028 const usageSummary = outdent`
14029 Usage: prettier [options] [file/dir/glob ...]
14031 By default, output is written to stdout.
14032 Stdin is read if it is piped to Prettier and no files are given.
14042 } = thirdParty; // Some CI pipelines incorrectly report process.stdout.isTTY status,
14043 // which causes unwanted lines in the output. An additional check for isCI() helps.
14044 // See https://github.com/prettier/prettier/issues/5801
14046 var isTty = function isTTY() {
14047 return process.stdout.isTTY && !isCI();
14053 diff: function diff(oldString, newString) {
14054 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
14055 var callback = options.callback;
14057 if (typeof options === 'function') {
14058 callback = options;
14062 this.options = options;
14065 function done(value) {
14067 setTimeout(function () {
14068 callback(undefined, value);
14074 } // Allow subclasses to massage the input prior to running
14077 oldString = this.castInput(oldString);
14078 newString = this.castInput(newString);
14079 oldString = this.removeEmpty(this.tokenize(oldString));
14080 newString = this.removeEmpty(this.tokenize(newString));
14081 var newLen = newString.length,
14082 oldLen = oldString.length;
14083 var editLength = 1;
14084 var maxEditLength = newLen + oldLen;
14088 }]; // Seed editLength = 0, i.e. the content starts with the same values
14090 var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
14092 if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
14093 // Identity per the equality and tokenizer
14095 value: this.join(newString),
14096 count: newString.length
14098 } // Main worker method. checks all permutations of a given edit length for acceptance.
14101 function execEditLength() {
14102 for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
14103 var basePath = void 0;
14105 var addPath = bestPath[diagonalPath - 1],
14106 removePath = bestPath[diagonalPath + 1],
14107 _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
14110 // No one else is going to attempt to use this value, clear it
14111 bestPath[diagonalPath - 1] = undefined;
14114 var canAdd = addPath && addPath.newPos + 1 < newLen,
14115 canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;
14117 if (!canAdd && !canRemove) {
14118 // If this path is a terminal then prune
14119 bestPath[diagonalPath] = undefined;
14121 } // Select the diagonal that we want to branch from. We select the prior
14122 // path whose position in the new string is the farthest from the origin
14123 // and does not pass the bounds of the diff graph
14126 if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {
14127 basePath = clonePath(removePath);
14128 self.pushComponent(basePath.components, undefined, true);
14130 basePath = addPath; // No need to clone, we've pulled it from the list
14133 self.pushComponent(basePath.components, true, undefined);
14136 _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done
14138 if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {
14139 return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));
14141 // Otherwise track this path as a potential candidate and continue.
14142 bestPath[diagonalPath] = basePath;
14147 } // Performs the length of edit iteration. Is a bit fugly as this has to support the
14148 // sync and async mode which is never fun. Loops over execEditLength until a value
14154 setTimeout(function () {
14155 // This should not happen, but we want to be safe.
14157 /* istanbul ignore next */
14158 if (editLength > maxEditLength) {
14162 if (!execEditLength()) {
14168 while (editLength <= maxEditLength) {
14169 var ret = execEditLength();
14177 pushComponent: function pushComponent(components, added, removed) {
14178 var last = components[components.length - 1];
14180 if (last && last.added === added && last.removed === removed) {
14181 // We need to clone here as the component clone operation is just
14182 // as shallow array clone
14183 components[components.length - 1] = {
14184 count: last.count + 1,
14196 extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {
14197 var newLen = newString.length,
14198 oldLen = oldString.length,
14199 newPos = basePath.newPos,
14200 oldPos = newPos - diagonalPath,
14203 while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
14210 basePath.components.push({
14215 basePath.newPos = newPos;
14218 equals: function equals(left, right) {
14219 if (this.options.comparator) {
14220 return this.options.comparator(left, right);
14222 return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();
14225 removeEmpty: function removeEmpty(array) {
14228 for (var i = 0; i < array.length; i++) {
14230 ret.push(array[i]);
14236 castInput: function castInput(value) {
14239 tokenize: function tokenize(value) {
14240 return value.split('');
14242 join: function join(chars) {
14243 return chars.join('');
14247 function buildValues(diff, components, newString, oldString, useLongestToken) {
14248 var componentPos = 0,
14249 componentLen = components.length,
14253 for (; componentPos < componentLen; componentPos++) {
14254 var component = components[componentPos];
14256 if (!component.removed) {
14257 if (!component.added && useLongestToken) {
14258 var value = newString.slice(newPos, newPos + component.count);
14259 value = value.map(function (value, i) {
14260 var oldValue = oldString[oldPos + i];
14261 return oldValue.length > value.length ? oldValue : value;
14263 component.value = diff.join(value);
14265 component.value = diff.join(newString.slice(newPos, newPos + component.count));
14268 newPos += component.count; // Common case
14270 if (!component.added) {
14271 oldPos += component.count;
14274 component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));
14275 oldPos += component.count; // Reverse add and remove so removes are output first to match common convention
14276 // The diffing algorithm is tied to add then remove output and this is the simplest
14277 // route to get the desired output with minimal overhead.
14279 if (componentPos && components[componentPos - 1].added) {
14280 var tmp = components[componentPos - 1];
14281 components[componentPos - 1] = components[componentPos];
14282 components[componentPos] = tmp;
14285 } // Special case handle for when one terminal is ignored (i.e. whitespace).
14286 // For this case we merge the terminal into the prior string and drop the change.
14287 // This is only available for string mode.
14290 var lastComponent = components[componentLen - 1];
14292 if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {
14293 components[componentLen - 2].value += lastComponent.value;
14300 function clonePath(path) {
14302 newPos: path.newPos,
14303 components: path.components.slice(0)
14307 var characterDiff = new Diff();
14309 function diffChars(oldStr, newStr, options) {
14310 return characterDiff.diff(oldStr, newStr, options);
14313 function generateOptions(options, defaults) {
14314 if (typeof options === 'function') {
14315 defaults.callback = options;
14316 } else if (options) {
14317 for (var name in options) {
14318 /* istanbul ignore else */
14319 if (options.hasOwnProperty(name)) {
14320 defaults[name] = options[name];
14327 // Ranges and exceptions:
14328 // Latin-1 Supplement, 0080–00FF
14329 // - U+00D7 × Multiplication sign
14330 // - U+00F7 ÷ Division sign
14331 // Latin Extended-A, 0100–017F
14332 // Latin Extended-B, 0180–024F
14333 // IPA Extensions, 0250–02AF
14334 // Spacing Modifier Letters, 02B0–02FF
14335 // - U+02C7 ˇ ˇ Caron
14336 // - U+02D8 ˘ ˘ Breve
14337 // - U+02D9 ˙ ˙ Dot Above
14338 // - U+02DA ˚ ˚ Ring Above
14339 // - U+02DB ˛ ˛ Ogonek
14340 // - U+02DC ˜ ˜ Small Tilde
14341 // - U+02DD ˝ ˝ Double Acute Accent
14342 // Latin Extended Additional, 1E00–1EFF
14345 var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/;
14346 var reWhitespace = /\S/;
14347 var wordDiff = new Diff();
14349 wordDiff.equals = function (left, right) {
14350 if (this.options.ignoreCase) {
14351 left = left.toLowerCase();
14352 right = right.toLowerCase();
14355 return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);
14358 wordDiff.tokenize = function (value) {
14359 // All whitespace symbols except newline group into one token, each newline - in separate token
14360 var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.
14362 for (var i = 0; i < tokens.length - 1; i++) {
14363 // If we have an empty string in the next field and we have only word chars before and after, merge
14364 if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {
14365 tokens[i] += tokens[i + 2];
14366 tokens.splice(i + 1, 2);
14374 function diffWords(oldStr, newStr, options) {
14375 options = generateOptions(options, {
14376 ignoreWhitespace: true
14378 return wordDiff.diff(oldStr, newStr, options);
14381 function diffWordsWithSpace(oldStr, newStr, options) {
14382 return wordDiff.diff(oldStr, newStr, options);
14385 var lineDiff = new Diff();
14387 lineDiff.tokenize = function (value) {
14389 linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line
14391 if (!linesAndNewlines[linesAndNewlines.length - 1]) {
14392 linesAndNewlines.pop();
14393 } // Merge the content and line separators into single tokens
14396 for (var i = 0; i < linesAndNewlines.length; i++) {
14397 var line = linesAndNewlines[i];
14399 if (i % 2 && !this.options.newlineIsToken) {
14400 retLines[retLines.length - 1] += line;
14402 if (this.options.ignoreWhitespace) {
14403 line = line.trim();
14406 retLines.push(line);
14413 function diffLines(oldStr, newStr, callback) {
14414 return lineDiff.diff(oldStr, newStr, callback);
14417 function diffTrimmedLines(oldStr, newStr, callback) {
14418 var options = generateOptions(callback, {
14419 ignoreWhitespace: true
14421 return lineDiff.diff(oldStr, newStr, options);
14424 var sentenceDiff = new Diff();
14426 sentenceDiff.tokenize = function (value) {
14427 return value.split(/(\S.+?[.!?])(?=\s+|$)/);
14430 function diffSentences(oldStr, newStr, callback) {
14431 return sentenceDiff.diff(oldStr, newStr, callback);
14434 var cssDiff = new Diff();
14436 cssDiff.tokenize = function (value) {
14437 return value.split(/([{}:;,]|\s+)/);
14440 function diffCss(oldStr, newStr, callback) {
14441 return cssDiff.diff(oldStr, newStr, callback);
14444 function _typeof(obj) {
14445 "@babel/helpers - typeof";
14447 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
14448 _typeof = function (obj) {
14452 _typeof = function (obj) {
14453 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
14457 return _typeof(obj);
14460 function _toConsumableArray(arr) {
14461 return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
14464 function _arrayWithoutHoles(arr) {
14465 if (Array.isArray(arr)) return _arrayLikeToArray(arr);
14468 function _iterableToArray(iter) {
14469 if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
14472 function _unsupportedIterableToArray(o, minLen) {
14474 if (typeof o === "string") return _arrayLikeToArray(o, minLen);
14475 var n = Object.prototype.toString.call(o).slice(8, -1);
14476 if (n === "Object" && o.constructor) n = o.constructor.name;
14477 if (n === "Map" || n === "Set") return Array.from(o);
14478 if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
14481 function _arrayLikeToArray(arr, len) {
14482 if (len == null || len > arr.length) len = arr.length;
14484 for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
14489 function _nonIterableSpread() {
14490 throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
14493 var objectPrototypeToString = Object.prototype.toString;
14494 var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
14495 // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
14497 jsonDiff.useLongestToken = true;
14498 jsonDiff.tokenize = lineDiff.tokenize;
14500 jsonDiff.castInput = function (value) {
14501 var _this$options = this.options,
14502 undefinedReplacement = _this$options.undefinedReplacement,
14503 _this$options$stringi = _this$options.stringifyReplacer,
14504 stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {
14505 return typeof v === 'undefined' ? undefinedReplacement : v;
14506 } : _this$options$stringi;
14507 return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');
14510 jsonDiff.equals = function (left, right) {
14511 return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
14514 function diffJson(oldObj, newObj, options) {
14515 return jsonDiff.diff(oldObj, newObj, options);
14516 } // This function handles the presence of circular references by bailing out when encountering an
14517 // object that is already on the "stack" of items being processed. Accepts an optional replacer
14520 function canonicalize(obj, stack, replacementStack, replacer, key) {
14521 stack = stack || [];
14522 replacementStack = replacementStack || [];
14525 obj = replacer(key, obj);
14530 for (i = 0; i < stack.length; i += 1) {
14531 if (stack[i] === obj) {
14532 return replacementStack[i];
14536 var canonicalizedObj;
14538 if ('[object Array]' === objectPrototypeToString.call(obj)) {
14540 canonicalizedObj = new Array(obj.length);
14541 replacementStack.push(canonicalizedObj);
14543 for (i = 0; i < obj.length; i += 1) {
14544 canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);
14548 replacementStack.pop();
14549 return canonicalizedObj;
14552 if (obj && obj.toJSON) {
14553 obj = obj.toJSON();
14556 if (_typeof(obj) === 'object' && obj !== null) {
14558 canonicalizedObj = {};
14559 replacementStack.push(canonicalizedObj);
14561 var sortedKeys = [],
14564 for (_key in obj) {
14565 /* istanbul ignore else */
14566 if (obj.hasOwnProperty(_key)) {
14567 sortedKeys.push(_key);
14573 for (i = 0; i < sortedKeys.length; i += 1) {
14574 _key = sortedKeys[i];
14575 canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);
14579 replacementStack.pop();
14581 canonicalizedObj = obj;
14584 return canonicalizedObj;
14587 var arrayDiff = new Diff();
14589 arrayDiff.tokenize = function (value) {
14590 return value.slice();
14593 arrayDiff.join = arrayDiff.removeEmpty = function (value) {
14597 function diffArrays(oldArr, newArr, callback) {
14598 return arrayDiff.diff(oldArr, newArr, callback);
14601 function parsePatch(uniDiff) {
14602 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
14603 var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/),
14604 delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [],
14608 function parseIndex() {
14610 list.push(index); // Parse diff metadata
14612 while (i < diffstr.length) {
14613 var line = diffstr[i]; // File header found, end parsing diff metadata
14615 if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) {
14620 var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line);
14623 index.index = header[1];
14627 } // Parse file headers if they are defined. Unified diff requires them, but
14628 // there's no technical issues to have an isolated hunk without file header
14631 parseFileHeader(index);
14632 parseFileHeader(index); // Parse hunks
14636 while (i < diffstr.length) {
14637 var _line = diffstr[i];
14639 if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) {
14641 } else if (/^@@/.test(_line)) {
14642 index.hunks.push(parseHunk());
14643 } else if (_line && options.strict) {
14644 // Ignore unexpected content unless in strict mode
14645 throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));
14650 } // Parses the --- and +++ headers, if none are found, no lines
14654 function parseFileHeader(index) {
14655 var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]);
14658 var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';
14659 var data = fileHeader[2].split('\t', 2);
14660 var fileName = data[0].replace(/\\\\/g, '\\');
14662 if (/^".*"$/.test(fileName)) {
14663 fileName = fileName.substr(1, fileName.length - 2);
14666 index[keyPrefix + 'FileName'] = fileName;
14667 index[keyPrefix + 'Header'] = (data[1] || '').trim();
14671 // This assumes that we are at the start of a hunk.
14674 function parseHunk() {
14675 var chunkHeaderIndex = i,
14676 chunkHeaderLine = diffstr[i++],
14677 chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
14679 oldStart: +chunkHeader[1],
14680 oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2],
14681 newStart: +chunkHeader[3],
14682 newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4],
14685 }; // Unified Diff Format quirk: If the chunk size is 0,
14686 // the first number is one lower than one would expect.
14687 // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
14689 if (hunk.oldLines === 0) {
14690 hunk.oldStart += 1;
14693 if (hunk.newLines === 0) {
14694 hunk.newStart += 1;
14700 for (; i < diffstr.length; i++) {
14701 // Lines starting with '---' could be mistaken for the "remove line" operation
14702 // But they could be the header for the next file. Therefore prune such cases out.
14703 if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {
14707 var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];
14709 if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') {
14710 hunk.lines.push(diffstr[i]);
14711 hunk.linedelimiters.push(delimiters[i] || '\n');
14713 if (operation === '+') {
14715 } else if (operation === '-') {
14717 } else if (operation === ' ') {
14724 } // Handle the empty block count case
14727 if (!addCount && hunk.newLines === 1) {
14731 if (!removeCount && hunk.oldLines === 1) {
14733 } // Perform optional sanity checking
14736 if (options.strict) {
14737 if (addCount !== hunk.newLines) {
14738 throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
14741 if (removeCount !== hunk.oldLines) {
14742 throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));
14749 while (i < diffstr.length) {
14754 } // Iterator that traverses in the range of [min, max], stepping
14755 // by distance from a given start position. I.e. for [0, 4], with
14756 // start of 2, this will iterate 2, 3, 1, 4, 0.
14759 function distanceIterator(start, minLine, maxLine) {
14760 var wantForward = true,
14761 backwardExhausted = false,
14762 forwardExhausted = false,
14764 return function iterator() {
14765 if (wantForward && !forwardExhausted) {
14766 if (backwardExhausted) {
14769 wantForward = false;
14770 } // Check if trying to fit beyond text length, and if not, check it fits
14771 // after offset location (or desired location on first iteration)
14774 if (start + localOffset <= maxLine) {
14775 return localOffset;
14778 forwardExhausted = true;
14781 if (!backwardExhausted) {
14782 if (!forwardExhausted) {
14783 wantForward = true;
14784 } // Check if trying to fit before text beginning, and if not, check it fits
14785 // before offset location
14788 if (minLine <= start - localOffset) {
14789 return -localOffset++;
14792 backwardExhausted = true;
14794 } // We tried to fit hunk before text beginning and beyond text length, then
14795 // hunk can't fit on the text. Return undefined
14800 function applyPatch(source, uniDiff) {
14801 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
14803 if (typeof uniDiff === 'string') {
14804 uniDiff = parsePatch(uniDiff);
14807 if (Array.isArray(uniDiff)) {
14808 if (uniDiff.length > 1) {
14809 throw new Error('applyPatch only works with a single input.');
14812 uniDiff = uniDiff[0];
14813 } // Apply the diff to the input
14816 var lines = source.split(/\r\n|[\n\v\f\r\x85]/),
14817 delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [],
14818 hunks = uniDiff.hunks,
14819 compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {
14820 return line === patchContent;
14823 fuzzFactor = options.fuzzFactor || 0,
14829 * Checks if the hunk exactly fits on the provided location
14833 function hunkFits(hunk, toPos) {
14834 for (var j = 0; j < hunk.lines.length; j++) {
14835 var line = hunk.lines[j],
14836 operation = line.length > 0 ? line[0] : ' ',
14837 content = line.length > 0 ? line.substr(1) : line;
14839 if (operation === ' ' || operation === '-') {
14840 // Context sanity check
14841 if (!compareLine(toPos + 1, lines[toPos], operation, content)) {
14844 if (errorCount > fuzzFactor) {
14854 } // Search best fit offsets for each hunk based on the previous ones
14857 for (var i = 0; i < hunks.length; i++) {
14858 var hunk = hunks[i],
14859 maxLine = lines.length - hunk.oldLines,
14861 toPos = offset + hunk.oldStart - 1;
14862 var iterator = distanceIterator(toPos, minLine, maxLine);
14864 for (; localOffset !== undefined; localOffset = iterator()) {
14865 if (hunkFits(hunk, toPos + localOffset)) {
14866 hunk.offset = offset += localOffset;
14871 if (localOffset === undefined) {
14873 } // Set lower text limit to end of the current hunk, so next ones don't try
14874 // to fit over already patched text
14877 minLine = hunk.offset + hunk.oldStart + hunk.oldLines;
14878 } // Apply patch hunks
14881 var diffOffset = 0;
14883 for (var _i = 0; _i < hunks.length; _i++) {
14884 var _hunk = hunks[_i],
14885 _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;
14887 diffOffset += _hunk.newLines - _hunk.oldLines;
14889 for (var j = 0; j < _hunk.lines.length; j++) {
14890 var line = _hunk.lines[j],
14891 operation = line.length > 0 ? line[0] : ' ',
14892 content = line.length > 0 ? line.substr(1) : line,
14893 delimiter = _hunk.linedelimiters[j];
14895 if (operation === ' ') {
14897 } else if (operation === '-') {
14898 lines.splice(_toPos, 1);
14899 delimiters.splice(_toPos, 1);
14900 /* istanbul ignore else */
14901 } else if (operation === '+') {
14902 lines.splice(_toPos, 0, content);
14903 delimiters.splice(_toPos, 0, delimiter);
14905 } else if (operation === '\\') {
14906 var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;
14908 if (previousOperation === '+') {
14909 removeEOFNL = true;
14910 } else if (previousOperation === '-') {
14915 } // Handle EOFNL insertion/removal
14919 while (!lines[lines.length - 1]) {
14923 } else if (addEOFNL) {
14925 delimiters.push('\n');
14928 for (var _k = 0; _k < lines.length - 1; _k++) {
14929 lines[_k] = lines[_k] + delimiters[_k];
14932 return lines.join('');
14933 } // Wrapper that supports multiple file patches via callbacks.
14936 function applyPatches(uniDiff, options) {
14937 if (typeof uniDiff === 'string') {
14938 uniDiff = parsePatch(uniDiff);
14941 var currentIndex = 0;
14943 function processIndex() {
14944 var index = uniDiff[currentIndex++];
14947 return options.complete();
14950 options.loadFile(index, function (err, data) {
14952 return options.complete(err);
14955 var updatedContent = applyPatch(data, index, options);
14956 options.patched(index, updatedContent, function (err) {
14958 return options.complete(err);
14969 function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
14974 if (typeof options.context === 'undefined') {
14975 options.context = 4;
14978 var diff = diffLines(oldStr, newStr, options);
14982 }); // Append an empty value to make cleanup easier
14984 function contextLines(lines) {
14985 return lines.map(function (entry) {
14986 return ' ' + entry;
14991 var oldRangeStart = 0,
14997 var _loop = function _loop(i) {
14998 var current = diff[i],
14999 lines = current.lines || current.value.replace(/\n$/, '').split('\n');
15000 current.lines = lines;
15002 if (current.added || current.removed) {
15003 var _curRange; // If we have previous context, start with that
15006 if (!oldRangeStart) {
15007 var prev = diff[i - 1];
15008 oldRangeStart = oldLine;
15009 newRangeStart = newLine;
15012 curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];
15013 oldRangeStart -= curRange.length;
15014 newRangeStart -= curRange.length;
15016 } // Output our changes
15019 (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {
15020 return (current.added ? '+' : '-') + entry;
15021 }))); // Track the updated file position
15024 if (current.added) {
15025 newLine += lines.length;
15027 oldLine += lines.length;
15030 // Identical context lines. Track line changes
15031 if (oldRangeStart) {
15032 // Close out any changes that have been output (or join overlapping)
15033 if (lines.length <= options.context * 2 && i < diff.length - 2) {
15034 var _curRange2; // Overlapping
15037 (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));
15039 var _curRange3; // end the range and output
15042 var contextSize = Math.min(lines.length, options.context);
15044 (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));
15047 oldStart: oldRangeStart,
15048 oldLines: oldLine - oldRangeStart + contextSize,
15049 newStart: newRangeStart,
15050 newLines: newLine - newRangeStart + contextSize,
15054 if (i >= diff.length - 2 && lines.length <= options.context) {
15055 // EOF is inside this hunk
15056 var oldEOFNewline = /\n$/.test(oldStr);
15057 var newEOFNewline = /\n$/.test(newStr);
15058 var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;
15060 if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) {
15061 // special case: old has no eol and no trailing context; no-nl can end up before adds
15062 // however, if the old file is empty, do not output the no-nl line
15063 curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file');
15066 if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {
15067 curRange.push('\\ No newline at end of file');
15078 oldLine += lines.length;
15079 newLine += lines.length;
15083 for (var i = 0; i < diff.length; i++) {
15088 oldFileName: oldFileName,
15089 newFileName: newFileName,
15090 oldHeader: oldHeader,
15091 newHeader: newHeader,
15096 function formatPatch(diff) {
15099 if (diff.oldFileName == diff.newFileName) {
15100 ret.push('Index: ' + diff.oldFileName);
15103 ret.push('===================================================================');
15104 ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader));
15105 ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader));
15107 for (var i = 0; i < diff.hunks.length; i++) {
15108 var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0,
15109 // the first number is one lower than one would expect.
15110 // https://www.artima.com/weblogs/viewpost.jsp?thread=164293
15112 if (hunk.oldLines === 0) {
15113 hunk.oldStart -= 1;
15116 if (hunk.newLines === 0) {
15117 hunk.newStart -= 1;
15120 ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');
15121 ret.push.apply(ret, hunk.lines);
15124 return ret.join('\n') + '\n';
15127 function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {
15128 return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options));
15131 function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {
15132 return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);
15135 function arrayEqual(a, b) {
15136 if (a.length !== b.length) {
15140 return arrayStartsWith(a, b);
15143 function arrayStartsWith(array, start) {
15144 if (start.length > array.length) {
15148 for (var i = 0; i < start.length; i++) {
15149 if (start[i] !== array[i]) {
15157 function calcLineCount(hunk) {
15158 var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),
15159 oldLines = _calcOldNewLineCount.oldLines,
15160 newLines = _calcOldNewLineCount.newLines;
15162 if (oldLines !== undefined) {
15163 hunk.oldLines = oldLines;
15165 delete hunk.oldLines;
15168 if (newLines !== undefined) {
15169 hunk.newLines = newLines;
15171 delete hunk.newLines;
15175 function merge(mine, theirs, base) {
15176 mine = loadPatch(mine, base);
15177 theirs = loadPatch(theirs, base);
15178 var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.
15179 // Leaving sanity checks on this to the API consumer that may know more about the
15180 // meaning in their own context.
15182 if (mine.index || theirs.index) {
15183 ret.index = mine.index || theirs.index;
15186 if (mine.newFileName || theirs.newFileName) {
15187 if (!fileNameChanged(mine)) {
15188 // No header or no change in ours, use theirs (and ours if theirs does not exist)
15189 ret.oldFileName = theirs.oldFileName || mine.oldFileName;
15190 ret.newFileName = theirs.newFileName || mine.newFileName;
15191 ret.oldHeader = theirs.oldHeader || mine.oldHeader;
15192 ret.newHeader = theirs.newHeader || mine.newHeader;
15193 } else if (!fileNameChanged(theirs)) {
15194 // No header or no change in theirs, use ours
15195 ret.oldFileName = mine.oldFileName;
15196 ret.newFileName = mine.newFileName;
15197 ret.oldHeader = mine.oldHeader;
15198 ret.newHeader = mine.newHeader;
15200 // Both changed... figure it out
15201 ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);
15202 ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);
15203 ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);
15204 ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);
15214 while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {
15215 var mineCurrent = mine.hunks[mineIndex] || {
15218 theirsCurrent = theirs.hunks[theirsIndex] || {
15222 if (hunkBefore(mineCurrent, theirsCurrent)) {
15223 // This patch does not overlap with any of the others, yay.
15224 ret.hunks.push(cloneHunk(mineCurrent, mineOffset));
15226 theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;
15227 } else if (hunkBefore(theirsCurrent, mineCurrent)) {
15228 // This patch does not overlap with any of the others, yay.
15229 ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));
15231 mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;
15233 // Overlap, merge as best we can
15235 oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),
15237 newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),
15241 mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);
15244 ret.hunks.push(mergedHunk);
15251 function loadPatch(param, base) {
15252 if (typeof param === 'string') {
15253 if (/^@@/m.test(param) || /^Index:/m.test(param)) {
15254 return parsePatch(param)[0];
15258 throw new Error('Must provide a base reference or pass in a patch');
15261 return structuredPatch(undefined, undefined, base, param);
15267 function fileNameChanged(patch) {
15268 return patch.newFileName && patch.newFileName !== patch.oldFileName;
15271 function selectField(index, mine, theirs) {
15272 if (mine === theirs) {
15275 index.conflict = true;
15283 function hunkBefore(test, check) {
15284 return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;
15287 function cloneHunk(hunk, offset) {
15289 oldStart: hunk.oldStart,
15290 oldLines: hunk.oldLines,
15291 newStart: hunk.newStart + offset,
15292 newLines: hunk.newLines,
15297 function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {
15298 // This will generally result in a conflicted hunk, but there are cases where the context
15299 // is the only overlap where we can successfully merge the content here.
15301 offset: mineOffset,
15306 offset: theirOffset,
15309 }; // Handle any leading content
15311 insertLeading(hunk, mine, their);
15312 insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.
15314 while (mine.index < mine.lines.length && their.index < their.lines.length) {
15315 var mineCurrent = mine.lines[mine.index],
15316 theirCurrent = their.lines[their.index];
15318 if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {
15319 // Both modified ...
15320 mutualChange(hunk, mine, their);
15321 } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {
15322 var _hunk$lines; // Mine inserted
15325 (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));
15326 } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {
15327 var _hunk$lines2; // Theirs inserted
15330 (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));
15331 } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {
15332 // Mine removed or edited
15333 removal(hunk, mine, their);
15334 } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {
15335 // Their removed or edited
15336 removal(hunk, their, mine, true);
15337 } else if (mineCurrent === theirCurrent) {
15338 // Context identity
15339 hunk.lines.push(mineCurrent);
15343 // Context mismatch
15344 conflict(hunk, collectChange(mine), collectChange(their));
15346 } // Now push anything that may be remaining
15349 insertTrailing(hunk, mine);
15350 insertTrailing(hunk, their);
15351 calcLineCount(hunk);
15354 function mutualChange(hunk, mine, their) {
15355 var myChanges = collectChange(mine),
15356 theirChanges = collectChange(their);
15358 if (allRemoves(myChanges) && allRemoves(theirChanges)) {
15359 // Special case for remove changes that are supersets of one another
15360 if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {
15363 (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));
15366 } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {
15369 (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));
15373 } else if (arrayEqual(myChanges, theirChanges)) {
15376 (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));
15381 conflict(hunk, myChanges, theirChanges);
15384 function removal(hunk, mine, their, swap) {
15385 var myChanges = collectChange(mine),
15386 theirChanges = collectContext(their, myChanges);
15388 if (theirChanges.merged) {
15391 (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));
15393 conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);
15397 function conflict(hunk, mine, their) {
15398 hunk.conflict = true;
15406 function insertLeading(hunk, insert, their) {
15407 while (insert.offset < their.offset && insert.index < insert.lines.length) {
15408 var line = insert.lines[insert.index++];
15409 hunk.lines.push(line);
15414 function insertTrailing(hunk, insert) {
15415 while (insert.index < insert.lines.length) {
15416 var line = insert.lines[insert.index++];
15417 hunk.lines.push(line);
15421 function collectChange(state) {
15423 operation = state.lines[state.index][0];
15425 while (state.index < state.lines.length) {
15426 var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change.
15428 if (operation === '-' && line[0] === '+') {
15432 if (operation === line[0]) {
15443 function collectContext(state, matchChanges) {
15447 contextChanges = false,
15448 conflicted = false;
15450 while (matchIndex < matchChanges.length && state.index < state.lines.length) {
15451 var change = state.lines[state.index],
15452 match = matchChanges[matchIndex]; // Once we've hit our add, then we are done
15454 if (match[0] === '+') {
15458 contextChanges = contextChanges || change[0] !== ' ';
15459 merged.push(match);
15460 matchIndex++; // Consume any additions in the other block as a conflict to attempt
15461 // to pull in the remaining context after this
15463 if (change[0] === '+') {
15466 while (change[0] === '+') {
15467 changes.push(change);
15468 change = state.lines[++state.index];
15472 if (match.substr(1) === change.substr(1)) {
15473 changes.push(change);
15480 if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {
15488 while (matchIndex < matchChanges.length) {
15489 merged.push(matchChanges[matchIndex++]);
15498 function allRemoves(changes) {
15499 return changes.reduce(function (prev, change) {
15500 return prev && change[0] === '-';
15504 function skipRemoveSuperset(state, removeChanges, delta) {
15505 for (var i = 0; i < delta; i++) {
15506 var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);
15508 if (state.lines[state.index + i] !== ' ' + changeContent) {
15513 state.index += delta;
15517 function calcOldNewLineCount(lines) {
15520 lines.forEach(function (line) {
15521 if (typeof line !== 'string') {
15522 var myCount = calcOldNewLineCount(line.mine);
15523 var theirCount = calcOldNewLineCount(line.theirs);
15525 if (oldLines !== undefined) {
15526 if (myCount.oldLines === theirCount.oldLines) {
15527 oldLines += myCount.oldLines;
15529 oldLines = undefined;
15533 if (newLines !== undefined) {
15534 if (myCount.newLines === theirCount.newLines) {
15535 newLines += myCount.newLines;
15537 newLines = undefined;
15541 if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {
15545 if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {
15551 oldLines: oldLines,
15554 } // See: http://code.google.com/p/google-diff-match-patch/wiki/API
15557 function convertChangesToDMP(changes) {
15562 for (var i = 0; i < changes.length; i++) {
15563 change = changes[i];
15565 if (change.added) {
15567 } else if (change.removed) {
15573 ret.push([operation, change.value]);
15579 function convertChangesToXML(changes) {
15582 for (var i = 0; i < changes.length; i++) {
15583 var change = changes[i];
15585 if (change.added) {
15587 } else if (change.removed) {
15591 ret.push(escapeHTML(change.value));
15593 if (change.added) {
15594 ret.push('</ins>');
15595 } else if (change.removed) {
15596 ret.push('</del>');
15600 return ret.join('');
15603 function escapeHTML(s) {
15605 n = n.replace(/&/g, '&');
15606 n = n.replace(/</g, '<');
15607 n = n.replace(/>/g, '>');
15608 n = n.replace(/"/g, '"');
15612 var index_es6 = /*#__PURE__*/Object.freeze({
15615 applyPatch: applyPatch,
15616 applyPatches: applyPatches,
15617 canonicalize: canonicalize,
15618 convertChangesToDMP: convertChangesToDMP,
15619 convertChangesToXML: convertChangesToXML,
15620 createPatch: createPatch,
15621 createTwoFilesPatch: createTwoFilesPatch,
15622 diffArrays: diffArrays,
15623 diffChars: diffChars,
15625 diffJson: diffJson,
15626 diffLines: diffLines,
15627 diffSentences: diffSentences,
15628 diffTrimmedLines: diffTrimmedLines,
15629 diffWords: diffWords,
15630 diffWordsWithSpace: diffWordsWithSpace,
15632 parsePatch: parsePatch,
15633 structuredPatch: structuredPatch
15636 // eslint-disable-next-line no-restricted-modules
15645 coreOptions: coreOptions$1,
15651 } = prettierInternal;
15653 expandPatterns: expandPatterns$1,
15654 fixWindowsSlashes: fixWindowsSlashes$1
15655 } = expandPatterns_1;
15656 const OPTION_USAGE_THRESHOLD = 25;
15657 const CHOICE_USAGE_MARGIN = 3;
15658 const CHOICE_USAGE_INDENTATION = 2;
15660 function getOptions(argv, detailedOptions) {
15661 return fromPairs_1(detailedOptions.filter(({
15663 }) => forwardToApi).map(({
15666 }) => [forwardToApi, argv[name]]));
15669 function cliifyOptions(object, apiDetailedOptionMap) {
15670 return Object.keys(object || {}).reduce((output, key) => {
15671 const apiOption = apiDetailedOptionMap[key];
15672 const cliKey = apiOption ? apiOption.name : key;
15673 output[dashify(cliKey)] = object[key];
15678 function diff(a, b) {
15679 return index_es6.createTwoFilesPatch("", "", a, b, "", "", {
15684 function handleError(context, filename, error) {
15685 if (error instanceof errors.UndefinedParserError) {
15686 // Can't test on CI, `isTTY()` is always false, see ./is-tty.js
15688 /* istanbul ignore next */
15689 if ((context.argv.write || context.argv["ignore-unknown"]) && isTty()) {
15690 readline__default['default'].clearLine(process.stdout, 0);
15691 readline__default['default'].cursorTo(process.stdout, 0, null);
15694 if (context.argv["ignore-unknown"]) {
15698 if (!context.argv.check && !context.argv["list-different"]) {
15699 process.exitCode = 2;
15702 context.logger.error(error.message);
15706 if (context.argv.write) {
15707 // Add newline to split errors from filename line.
15708 process.stdout.write("\n");
15711 const isParseError = Boolean(error && error.loc);
15712 const isValidationError = /^Invalid \S+ value\./.test(error && error.message);
15714 if (isParseError) {
15715 // `invalid.js: SyntaxError: Unexpected token (1:1)`.
15716 context.logger.error(`${filename}: ${String(error)}`);
15717 } else if (isValidationError || error instanceof errors.ConfigError) {
15718 // `Invalid printWidth value. Expected an integer, but received 0.5.`
15719 context.logger.error(error.message); // If validation fails for one file, it will fail for all of them.
15722 } else if (error instanceof errors.DebugError) {
15723 // `invalid.js: Some debug error message`
15724 context.logger.error(`${filename}: ${error.message}`);
15726 // `invalid.js: Error: Some unexpected error\n[stack trace]`
15728 /* istanbul ignore next */
15729 context.logger.error(filename + ": " + (error.stack || error));
15730 } // Don't exit the process if one file failed
15733 process.exitCode = 2;
15736 function logResolvedConfigPathOrDie(context) {
15737 const configFile = src.resolveConfigFile.sync(context.argv["find-config-path"]);
15740 context.logger.log(path__default['default'].relative(process.cwd(), configFile));
15746 function logFileInfoOrDie(context) {
15748 ignorePath: context.argv["ignore-path"],
15749 withNodeModules: context.argv["with-node-modules"],
15750 plugins: context.argv.plugin,
15751 pluginSearchDirs: context.argv["plugin-search-dir"],
15752 resolveConfig: context.argv.config !== false
15754 context.logger.log(src.format(fastJsonStableStringify(src.getFileInfo.sync(context.argv["file-info"], options)), {
15759 function writeOutput(context, result, options) {
15760 // Don't use `console.log` here since it adds an extra newline at the end.
15761 process.stdout.write(context.argv["debug-check"] ? result.filepath : result.formatted);
15763 if (options && options.cursorOffset >= 0) {
15764 process.stderr.write(result.cursorOffset + "\n");
15768 function listDifferent(context, input, options, filename) {
15769 if (!context.argv.check && !context.argv["list-different"]) {
15774 if (!options.filepath && !options.parser) {
15775 throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
15778 if (!src.check(input, options)) {
15779 if (!context.argv.write) {
15780 context.logger.log(filename);
15781 process.exitCode = 1;
15785 context.logger.error(error.message);
15791 function format(context, input, opt) {
15792 if (!opt.parser && !opt.filepath) {
15793 throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser.");
15796 if (context.argv["debug-print-doc"]) {
15797 const doc = src.__debug.printToDoc(input, opt);
15800 formatted: src.__debug.formatDoc(doc)
15804 if (context.argv["debug-check"]) {
15805 const pp = src.format(input, opt);
15806 const pppp = src.format(pp, opt);
15809 throw new errors.DebugError("prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp));
15811 const stringify = obj => JSON.stringify(obj, null, 2);
15813 const ast = stringify(src.__debug.parse(input, opt,
15816 const past = stringify(src.__debug.parse(pp, opt,
15819 /* istanbul ignore next */
15821 if (ast !== past) {
15822 const MAX_AST_SIZE = 2097152; // 2MB
15824 const astDiff = ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE ? "AST diff too large to render" : diff(ast, past);
15825 throw new errors.DebugError("ast(input) !== ast(prettier(input))\n" + astDiff + "\n" + diff(input, pp));
15831 filepath: opt.filepath || "(stdin)\n"
15834 /* istanbul ignore next */
15837 if (context.argv["debug-benchmark"]) {
15841 benchmark = require("benchmark");
15843 context.logger.debug("'--debug-benchmark' requires the 'benchmark' package to be installed.");
15847 context.logger.debug("'--debug-benchmark' option found, measuring formatWithCursor with 'benchmark' module.");
15848 const suite = new benchmark.Suite();
15849 suite.add("format", () => {
15850 src.formatWithCursor(input, opt);
15851 }).on("cycle", event => {
15853 benchmark: String(event.target),
15854 hz: event.target.hz,
15855 ms: event.target.times.cycle * 1000
15857 context.logger.debug("'--debug-benchmark' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
15861 } else if (context.argv["debug-repeat"] > 0) {
15862 const repeat = context.argv["debug-repeat"];
15863 context.logger.debug("'--debug-repeat' option found, running formatWithCursor " + repeat + " times."); // should be using `performance.now()`, but only `Date` is cross-platform enough
15865 const now = Date.now ? () => Date.now() : () => +new Date();
15868 for (let i = 0; i < repeat; ++i) {
15869 const startMs = now();
15870 src.formatWithCursor(input, opt);
15871 totalMs += now() - startMs;
15874 const averageMs = totalMs / repeat;
15877 hz: 1000 / averageMs,
15880 context.logger.debug("'--debug-repeat' measurements for formatWithCursor: " + JSON.stringify(results, null, 2));
15883 return src.formatWithCursor(input, opt);
15886 function getOptionsOrDie(context, filePath) {
15888 if (context.argv.config === false) {
15889 context.logger.debug("'--no-config' option found, skip loading config file.");
15893 context.logger.debug(context.argv.config ? `load config file from '${context.argv.config}'` : `resolve config from '${filePath}'`);
15894 const options = src.resolveConfig.sync(filePath, {
15895 editorconfig: context.argv.editorconfig,
15896 config: context.argv.config
15898 context.logger.debug("loaded options `" + JSON.stringify(options) + "`");
15901 context.logger.error(`Invalid configuration file \`${filePath}\`: ` + error.message);
15906 function getOptionsForFile(context, filepath) {
15907 const options = getOptionsOrDie(context, filepath);
15908 const hasPlugins = options && options.plugins;
15911 pushContextPlugins(context, options.plugins);
15914 const appliedOptions = Object.assign({
15916 }, applyConfigPrecedence(context, options && optionsNormalizer.normalizeApiOptions(options, context.supportOptions, {
15917 logger: context.logger
15919 context.logger.debug(`applied config-precedence (${context.argv["config-precedence"]}): ` + `${JSON.stringify(appliedOptions)}`);
15922 popContextPlugins(context);
15925 return appliedOptions;
15928 function parseArgsToOptions(context, overrideDefaults) {
15929 const minimistOptions = createMinimistOptions(context.detailedOptions);
15930 const apiDetailedOptionMap = createApiDetailedOptionMap(context.detailedOptions);
15931 return getOptions(optionsNormalizer.normalizeCliOptions(minimist_1(context.args, {
15932 string: minimistOptions.string,
15933 boolean: minimistOptions.boolean,
15934 default: cliifyOptions(overrideDefaults, apiDetailedOptionMap)
15935 }), context.detailedOptions, {
15937 }), context.detailedOptions);
15940 function applyConfigPrecedence(context, options) {
15942 switch (context.argv["config-precedence"]) {
15943 case "cli-override":
15944 return parseArgsToOptions(context, options);
15946 case "file-override":
15947 return Object.assign({}, parseArgsToOptions(context), options);
15949 case "prefer-file":
15950 return options || parseArgsToOptions(context);
15953 /* istanbul ignore next */
15954 context.logger.error(error.toString());
15955 /* istanbul ignore next */
15961 function formatStdin(context) {
15962 const filepath = context.argv["stdin-filepath"] ? path__default['default'].resolve(process.cwd(), context.argv["stdin-filepath"]) : process.cwd();
15963 const ignorer = createIgnorerFromContextOrDie(context); // If there's an ignore-path set, the filename must be relative to the
15964 // ignore path, not the current working directory.
15966 const relativeFilepath = context.argv["ignore-path"] ? path__default['default'].relative(path__default['default'].dirname(context.argv["ignore-path"]), filepath) : path__default['default'].relative(process.cwd(), filepath);
15967 getStdin().then(input => {
15968 if (relativeFilepath && ignorer.ignores(fixWindowsSlashes$1(relativeFilepath))) {
15969 writeOutput(context, {
15975 const options = getOptionsForFile(context, filepath);
15977 if (listDifferent(context, input, options, "(stdin)")) {
15981 writeOutput(context, format(context, input, options), options);
15982 }).catch(error => {
15983 handleError(context, relativeFilepath || "stdin", error);
15987 function createIgnorerFromContextOrDie(context) {
15989 return createIgnorer.sync(context.argv["ignore-path"], context.argv["with-node-modules"]);
15991 context.logger.error(e.message);
15996 function formatFiles(context) {
15997 // The ignorer will be used to filter file paths after the glob is checked,
15998 // before any files are actually written
15999 const ignorer = createIgnorerFromContextOrDie(context);
16000 let numberOfUnformattedFilesFound = 0;
16002 if (context.argv.check) {
16003 context.logger.log("Checking formatting...");
16006 for (const pathOrError of expandPatterns$1(context)) {
16007 if (typeof pathOrError === "object") {
16008 context.logger.error(pathOrError.error); // Don't exit, but set the exit code to 2
16010 process.exitCode = 2;
16014 const filename = pathOrError; // If there's an ignore-path set, the filename must be relative to the
16015 // ignore path, not the current working directory.
16017 const ignoreFilename = context.argv["ignore-path"] ? path__default['default'].relative(path__default['default'].dirname(context.argv["ignore-path"]), filename) : filename;
16018 const fileIgnored = ignorer.ignores(fixWindowsSlashes$1(ignoreFilename));
16020 if (fileIgnored && (context.argv["debug-check"] || context.argv.write || context.argv.check || context.argv["list-different"])) {
16024 const options = Object.assign({}, getOptionsForFile(context, filename), {
16029 context.logger.log(filename, {
16037 input = fs__default['default'].readFileSync(filename, "utf8");
16039 // Add newline to split errors from filename line.
16041 /* istanbul ignore next */
16042 context.logger.log("");
16043 /* istanbul ignore next */
16045 context.logger.error(`Unable to read file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
16047 /* istanbul ignore next */
16049 process.exitCode = 2;
16050 /* istanbul ignore next */
16056 writeOutput(context, {
16062 const start = Date.now();
16067 result = format(context, input, options);
16068 output = result.formatted;
16070 handleError(context, filename, error);
16074 const isDifferent = output !== input;
16077 // Remove previously printed filename to log it with duration.
16078 readline__default['default'].clearLine(process.stdout, 0);
16079 readline__default['default'].cursorTo(process.stdout, 0, null);
16082 if (context.argv.write) {
16083 // Don't write the file if it won't change in order not to invalidate
16084 // mtime based caches.
16086 if (!context.argv.check && !context.argv["list-different"]) {
16087 context.logger.log(`${filename} ${Date.now() - start}ms`);
16091 fs__default['default'].writeFileSync(filename, output, "utf8");
16093 /* istanbul ignore next */
16094 context.logger.error(`Unable to write file: ${filename}\n${error.message}`); // Don't exit the process if one file failed
16096 /* istanbul ignore next */
16098 process.exitCode = 2;
16100 } else if (!context.argv.check && !context.argv["list-different"]) {
16101 context.logger.log(`${source.grey(filename)} ${Date.now() - start}ms`);
16103 } else if (context.argv["debug-check"]) {
16104 /* istanbul ignore else */
16105 if (result.filepath) {
16106 context.logger.log(result.filepath);
16108 process.exitCode = 2;
16110 } else if (!context.argv.check && !context.argv["list-different"]) {
16111 writeOutput(context, result, options);
16115 if (context.argv.check) {
16116 context.logger.warn(filename);
16117 } else if (context.argv["list-different"]) {
16118 context.logger.log(filename);
16121 numberOfUnformattedFilesFound += 1;
16123 } // Print check summary based on expected exit code
16126 if (context.argv.check) {
16127 if (numberOfUnformattedFilesFound === 0) {
16128 context.logger.log("All matched files use Prettier code style!");
16130 context.logger.warn(context.argv.write ? "Code style issues fixed in the above file(s)." : "Code style issues found in the above file(s). Forgot to run Prettier?");
16132 } // Ensure non-zero exitCode when using --check/list-different is not combined with --write
16135 if ((context.argv.check || context.argv["list-different"]) && numberOfUnformattedFilesFound > 0 && !process.exitCode && !context.argv.write) {
16136 process.exitCode = 1;
16140 function getOptionsWithOpposites(options) {
16141 // Add --no-foo after --foo.
16142 const optionsWithOpposites = options.map(option => [option.description ? option : null, option.oppositeDescription ? Object.assign({}, option, {
16143 name: `no-${option.name}`,
16145 description: option.oppositeDescription
16147 return flatten_1(optionsWithOpposites).filter(Boolean);
16150 function createUsage(context) {
16151 const options = getOptionsWithOpposites(context.detailedOptions).filter( // remove unnecessary option (e.g. `semi`, `color`, etc.), which is only used for --help <flag>
16152 option => !(option.type === "boolean" && option.oppositeDescription && !option.name.startsWith("no-")));
16153 const groupedOptions = groupBy_1(options, option => option.category);
16154 const firstCategories = constant$1.categoryOrder.slice(0, -1);
16155 const lastCategories = constant$1.categoryOrder.slice(-1);
16156 const restCategories = Object.keys(groupedOptions).filter(category => !constant$1.categoryOrder.includes(category));
16157 const allCategories = [...firstCategories, ...restCategories, ...lastCategories];
16158 const optionsUsage = allCategories.map(category => {
16159 const categoryOptions = groupedOptions[category].map(option => createOptionUsage(context, option, OPTION_USAGE_THRESHOLD)).join("\n");
16160 return `${category} options:\n\n${indent(categoryOptions, 2)}`;
16162 return [constant$1.usageSummary].concat(optionsUsage, [""]).join("\n\n");
16165 function createOptionUsage(context, option, threshold) {
16166 const header = createOptionUsageHeader(option);
16167 const optionDefaultValue = getOptionDefaultValue(context, option.name);
16168 return createOptionUsageRow(header, `${option.description}${optionDefaultValue === undefined ? "" : `\nDefaults to ${createDefaultValueDisplay(optionDefaultValue)}.`}`, threshold);
16171 function createDefaultValueDisplay(value) {
16172 return Array.isArray(value) ? `[${value.map(createDefaultValueDisplay).join(", ")}]` : value;
16175 function createOptionUsageHeader(option) {
16176 const name = `--${option.name}`;
16177 const alias = option.alias ? `-${option.alias},` : null;
16178 const type = createOptionUsageType(option);
16179 return [alias, name, type].filter(Boolean).join(" ");
16182 function createOptionUsageRow(header, content, threshold) {
16183 const separator = header.length >= threshold ? `\n${" ".repeat(threshold)}` : " ".repeat(threshold - header.length);
16184 const description = content.replace(/\n/g, `\n${" ".repeat(threshold)}`);
16185 return `${header}${separator}${description}`;
16188 function createOptionUsageType(option) {
16189 switch (option.type) {
16194 return `<${option.choices.filter(choice => !choice.deprecated && choice.since !== null).map(choice => choice.value).join("|")}>`;
16197 return `<${option.type}>`;
16201 function createChoiceUsages(choices, margin, indentation) {
16202 const activeChoices = choices.filter(choice => !choice.deprecated && choice.since !== null);
16203 const threshold = activeChoices.map(choice => choice.value.length).reduce((current, length) => Math.max(current, length), 0) + margin;
16204 return activeChoices.map(choice => indent(createOptionUsageRow(choice.value, choice.description, threshold), indentation));
16207 function createDetailedUsage(context, flag) {
16208 const option = getOptionsWithOpposites(context.detailedOptions).find(option => option.name === flag || option.alias === flag);
16209 const header = createOptionUsageHeader(option);
16210 const description = `\n\n${indent(option.description, 2)}`;
16211 const choices = option.type !== "choice" ? "" : `\n\nValid options:\n\n${createChoiceUsages(option.choices, CHOICE_USAGE_MARGIN, CHOICE_USAGE_INDENTATION).join("\n")}`;
16212 const optionDefaultValue = getOptionDefaultValue(context, option.name);
16213 const defaults = optionDefaultValue !== undefined ? `\n\nDefault: ${createDefaultValueDisplay(optionDefaultValue)}` : "";
16214 const pluginDefaults = option.pluginDefaults && Object.keys(option.pluginDefaults).length ? `\nPlugin defaults:${Object.keys(option.pluginDefaults).map(key => `\n* ${key}: ${createDefaultValueDisplay(option.pluginDefaults[key])}`)}` : "";
16215 return `${header}${description}${choices}${defaults}${pluginDefaults}`;
16218 function getOptionDefaultValue(context, optionName) {
16220 if (!(optionName in context.detailedOptionMap)) {
16224 const option = context.detailedOptionMap[optionName];
16226 if (option.default !== undefined) {
16227 return option.default;
16230 const optionCamelName = camelcase(optionName);
16232 if (optionCamelName in context.apiDefaultOptions) {
16233 return context.apiDefaultOptions[optionCamelName];
16237 function indent(str, spaces) {
16238 return str.replace(/^/gm, " ".repeat(spaces));
16241 function createLogger(logLevel) {
16243 warn: createLogFunc("warn", "yellow"),
16244 error: createLogFunc("error", "red"),
16245 debug: createLogFunc("debug", "blue"),
16246 log: createLogFunc("log")
16249 function createLogFunc(loggerName, color) {
16250 if (!shouldLog(loggerName)) {
16254 const prefix = color ? `[${source[color](loggerName)}] ` : "";
16255 return function (message, opts) {
16256 opts = Object.assign({
16259 const stream = process[loggerName === "log" ? "stdout" : "stderr"];
16260 stream.write(message.replace(/^/gm, prefix) + (opts.newline ? "\n" : ""));
16264 function shouldLog(loggerName) {
16265 switch (logLevel) {
16270 if (loggerName === "debug") {
16277 if (loggerName === "log") {
16284 if (loggerName === "warn") {
16291 return loggerName === "error";
16296 function normalizeDetailedOption(name, option) {
16297 return Object.assign({
16298 category: coreOptions$1.CATEGORY_OTHER
16300 choices: option.choices && option.choices.map(choice => {
16301 const newChoice = Object.assign({
16304 }, typeof choice === "object" ? choice : {
16307 /* istanbul ignore next */
16309 if (newChoice.value === true) {
16310 newChoice.value = ""; // backward compatibility for original boolean option
16318 function normalizeDetailedOptionMap(detailedOptionMap) {
16319 return fromPairs_1(Object.entries(detailedOptionMap).sort(([leftName], [rightName]) => leftName.localeCompare(rightName)).map(([name, option]) => [name, normalizeDetailedOption(name, option)]));
16322 function createMinimistOptions(detailedOptions) {
16323 const [boolean, string] = partition_1(detailedOptions, ({
16325 }) => type === "boolean").map(detailedOptions => flatten_1(detailedOptions.map(({
16328 }) => alias ? [name, alias] : [name])));
16329 const defaults = fromPairs_1(detailedOptions.filter(option => !option.deprecated && (!option.forwardToApi || option.name === "plugin" || option.name === "plugin-search-dir") && option.default !== undefined).map(option => [option.name, option.default]));
16331 // we use vnopts' AliasSchema to handle aliases for better error messages
16339 function createApiDetailedOptionMap(detailedOptions) {
16340 return fromPairs_1(detailedOptions.filter(option => option.forwardToApi && option.forwardToApi !== option.name).map(option => [option.forwardToApi, option]));
16343 function createDetailedOptionMap(supportOptions) {
16344 return fromPairs_1(supportOptions.map(option => {
16345 const newOption = Object.assign({}, option, {
16346 name: option.cliName || dashify(option.name),
16347 description: option.cliDescription || option.description,
16348 category: option.cliCategory || coreOptions$1.CATEGORY_FORMAT,
16349 forwardToApi: option.name
16351 /* istanbul ignore next */
16353 if (option.deprecated) {
16354 delete newOption.forwardToApi;
16355 delete newOption.description;
16356 delete newOption.oppositeDescription;
16357 newOption.deprecated = true;
16360 return [newOption.name, newOption];
16362 } //-----------------------------context-util-start-------------------------------
16365 * @typedef {Object} Context
16367 * @property {string[]} args
16369 * @property {string[]} filePatterns
16370 * @property {any[]} supportOptions
16371 * @property detailedOptions
16372 * @property detailedOptionMap
16373 * @property apiDefaultOptions
16374 * @property languages
16375 * @property {Partial<Context>[]} stack
16378 /** @returns {Context} */
16381 function createContext(args) {
16386 updateContextArgv(context);
16387 normalizeContextArgv(context, ["loglevel", "plugin", "plugin-search-dir"]);
16388 context.logger = createLogger(context.argv.loglevel);
16389 updateContextArgv(context, context.argv.plugin, context.argv["plugin-search-dir"]);
16391 /** @type {Context} */
16396 function initContext(context) {
16397 // split into 2 step so that we could wrap this in a `try..catch` in cli/index.js
16398 normalizeContextArgv(context);
16401 * @param {Context} context
16402 * @param {string[]} plugins
16403 * @param {string[]=} pluginSearchDirs
16407 function updateContextOptions(context, plugins, pluginSearchDirs) {
16409 options: supportOptions,
16411 } = src.getSupportInfo({
16412 showDeprecated: true,
16413 showUnreleased: true,
16414 showInternal: true,
16418 const detailedOptionMap = normalizeDetailedOptionMap(Object.assign({}, createDetailedOptionMap(supportOptions), constant$1.options));
16419 const detailedOptions = arrayify(detailedOptionMap, "name");
16420 const apiDefaultOptions = Object.assign({}, optionsModule.hiddenDefaults, fromPairs_1(supportOptions.filter(({
16422 }) => !deprecated).map(option => [option.name, option.default])));
16423 Object.assign(context, {
16432 * @param {Context} context
16433 * @param {string[]} plugins
16434 * @param {string[]=} pluginSearchDirs
16438 function pushContextPlugins(context, plugins, pluginSearchDirs) {
16439 context.stack.push(pick_1(context, ["supportOptions", "detailedOptions", "detailedOptionMap", "apiDefaultOptions", "languages"]));
16440 updateContextOptions(context, plugins, pluginSearchDirs);
16443 * @param {Context} context
16447 function popContextPlugins(context) {
16448 Object.assign(context, context.stack.pop());
16451 function updateContextArgv(context, plugins, pluginSearchDirs) {
16452 pushContextPlugins(context, plugins, pluginSearchDirs);
16453 const minimistOptions = createMinimistOptions(context.detailedOptions);
16454 const argv = minimist_1(context.args, minimistOptions);
16455 context.argv = argv;
16456 context.filePatterns = argv._.map(file => String(file));
16459 function normalizeContextArgv(context, keys) {
16460 const detailedOptions = !keys ? context.detailedOptions : context.detailedOptions.filter(option => keys.includes(option.name));
16461 const argv = !keys ? context.argv : pick_1(context.argv, keys);
16462 context.argv = optionsNormalizer.normalizeCliOptions(argv, detailedOptions, {
16463 logger: context.logger
16465 } //------------------------------context-util-end--------------------------------
16470 createDetailedOptionMap,
16471 createDetailedUsage,
16477 logResolvedConfigPathOrDie,
16479 normalizeDetailedOptionMap
16482 pleaseUpgradeNode(require$$1); // eslint-disable-next-line no-restricted-modules
16484 function run(args) {
16485 const context = util$1.createContext(args);
16488 util$1.initContext(context);
16489 context.logger.debug(`normalized argv: ${JSON.stringify(context.argv)}`);
16491 if (context.argv.check && context.argv["list-different"]) {
16492 context.logger.error("Cannot use --check and --list-different together.");
16496 if (context.argv.write && context.argv["debug-check"]) {
16497 context.logger.error("Cannot use --write and --debug-check together.");
16501 if (context.argv["find-config-path"] && context.filePatterns.length) {
16502 context.logger.error("Cannot use --find-config-path with multiple files");
16506 if (context.argv["file-info"] && context.filePatterns.length) {
16507 context.logger.error("Cannot use --file-info with multiple files");
16511 if (context.argv.version) {
16512 context.logger.log(src.version);
16516 if (context.argv.help !== undefined) {
16517 context.logger.log(typeof context.argv.help === "string" && context.argv.help !== "" ? util$1.createDetailedUsage(context, context.argv.help) : util$1.createUsage(context));
16521 if (context.argv["support-info"]) {
16522 context.logger.log(src.format(fastJsonStableStringify(src.getSupportInfo()), {
16528 const hasFilePatterns = context.filePatterns.length !== 0;
16529 const useStdin = !hasFilePatterns && (!process.stdin.isTTY || context.args["stdin-filepath"]);
16531 if (context.argv["find-config-path"]) {
16532 util$1.logResolvedConfigPathOrDie(context);
16533 } else if (context.argv["file-info"]) {
16534 util$1.logFileInfoOrDie(context);
16535 } else if (useStdin) {
16536 util$1.formatStdin(context);
16537 } else if (hasFilePatterns) {
16538 util$1.formatFiles(context);
16540 context.logger.log(util$1.createUsage(context));
16544 context.logger.error(error.message);
16553 cli.run(process.argv.slice(2));
16556 module.exports = prettier;