source: node_modules/vite/dist/node-cjs/publicUtils.cjs

Last change on this file was 57e58a3, checked in by ste08 <sjovanoska@…>, 4 months ago

Initial commit

  • Property mode set to 100644
File size: 164.6 KB
RevLine 
[57e58a3]1'use strict';
2
3var path$1 = require('node:path');
4var node_url = require('node:url');
5var fs$1 = require('node:fs');
6var esbuild = require('esbuild');
7var node_child_process = require('node:child_process');
8var node_module = require('node:module');
9var require$$0 = require('tty');
10var require$$1 = require('util');
11var require$$1$1 = require('path');
12var require$$0$1 = require('crypto');
13var require$$1$2 = require('fs');
14var readline = require('node:readline');
15var require$$2 = require('os');
16
17var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
18const { version: version$2 } = JSON.parse(
19 fs$1.readFileSync(new URL("../../package.json", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))).toString()
20);
21const VERSION = version$2;
22const DEFAULT_MAIN_FIELDS = [
23 "browser",
24 "module",
25 "jsnext:main",
26 // moment still uses this...
27 "jsnext"
28];
29const DEFAULT_CLIENT_MAIN_FIELDS = Object.freeze(DEFAULT_MAIN_FIELDS);
30const DEFAULT_SERVER_MAIN_FIELDS = Object.freeze(
31 DEFAULT_MAIN_FIELDS.filter((f) => f !== "browser")
32);
33const DEV_PROD_CONDITION = `development|production`;
34const DEFAULT_CONDITIONS = ["module", "browser", "node", DEV_PROD_CONDITION];
35const DEFAULT_CLIENT_CONDITIONS = Object.freeze(
36 DEFAULT_CONDITIONS.filter((c) => c !== "node")
37);
38const DEFAULT_SERVER_CONDITIONS = Object.freeze(
39 DEFAULT_CONDITIONS.filter((c) => c !== "browser")
40);
41const FS_PREFIX = `/@fs/`;
42const VITE_PACKAGE_DIR = path$1.resolve(
43 // import.meta.url is `dist/node/constants.js` after bundle
44 node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))),
45 "../../.."
46);
47const CLIENT_ENTRY = path$1.resolve(VITE_PACKAGE_DIR, "dist/client/client.mjs");
48path$1.resolve(VITE_PACKAGE_DIR, "dist/client/env.mjs");
49path$1.dirname(CLIENT_ENTRY);
50const defaultAllowedOrigins = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/;
51
52const comma = ','.charCodeAt(0);
53const semicolon = ';'.charCodeAt(0);
54const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
55const intToChar = new Uint8Array(64); // 64 possible chars.
56const charToInt = new Uint8Array(128); // z is 122 in ASCII
57for (let i = 0; i < chars.length; i++) {
58 const c = chars.charCodeAt(i);
59 intToChar[i] = c;
60 charToInt[c] = i;
61}
62function encodeInteger(builder, num, relative) {
63 let delta = num - relative;
64 delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;
65 do {
66 let clamped = delta & 0b011111;
67 delta >>>= 5;
68 if (delta > 0)
69 clamped |= 0b100000;
70 builder.write(intToChar[clamped]);
71 } while (delta > 0);
72 return num;
73}
74
75const bufLength = 1024 * 16;
76// Provide a fallback for older environments.
77const td = typeof TextDecoder !== 'undefined'
78 ? /* #__PURE__ */ new TextDecoder()
79 : typeof Buffer !== 'undefined'
80 ? {
81 decode(buf) {
82 const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
83 return out.toString();
84 },
85 }
86 : {
87 decode(buf) {
88 let out = '';
89 for (let i = 0; i < buf.length; i++) {
90 out += String.fromCharCode(buf[i]);
91 }
92 return out;
93 },
94 };
95class StringWriter {
96 constructor() {
97 this.pos = 0;
98 this.out = '';
99 this.buffer = new Uint8Array(bufLength);
100 }
101 write(v) {
102 const { buffer } = this;
103 buffer[this.pos++] = v;
104 if (this.pos === bufLength) {
105 this.out += td.decode(buffer);
106 this.pos = 0;
107 }
108 }
109 flush() {
110 const { buffer, out, pos } = this;
111 return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
112 }
113}
114function encode(decoded) {
115 const writer = new StringWriter();
116 let sourcesIndex = 0;
117 let sourceLine = 0;
118 let sourceColumn = 0;
119 let namesIndex = 0;
120 for (let i = 0; i < decoded.length; i++) {
121 const line = decoded[i];
122 if (i > 0)
123 writer.write(semicolon);
124 if (line.length === 0)
125 continue;
126 let genColumn = 0;
127 for (let j = 0; j < line.length; j++) {
128 const segment = line[j];
129 if (j > 0)
130 writer.write(comma);
131 genColumn = encodeInteger(writer, segment[0], genColumn);
132 if (segment.length === 1)
133 continue;
134 sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
135 sourceLine = encodeInteger(writer, segment[2], sourceLine);
136 sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
137 if (segment.length === 4)
138 continue;
139 namesIndex = encodeInteger(writer, segment[4], namesIndex);
140 }
141 }
142 return writer.flush();
143}
144
145function getDefaultExportFromCjs (x) {
146 return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
147}
148
149var picocolors = {exports: {}};
150
151let p = process || {}, argv = p.argv || [], env = p.env || {};
152let isColorSupported =
153 !(!!env.NO_COLOR || argv.includes("--no-color")) &&
154 (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI);
155
156let formatter = (open, close, replace = open) =>
157 input => {
158 let string = "" + input, index = string.indexOf(close, open.length);
159 return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close
160 };
161
162let replaceClose = (string, close, replace, index) => {
163 let result = "", cursor = 0;
164 do {
165 result += string.substring(cursor, index) + replace;
166 cursor = index + close.length;
167 index = string.indexOf(close, cursor);
168 } while (~index)
169 return result + string.substring(cursor)
170};
171
172let createColors = (enabled = isColorSupported) => {
173 let f = enabled ? formatter : () => String;
174 return {
175 isColorSupported: enabled,
176 reset: f("\x1b[0m", "\x1b[0m"),
177 bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
178 dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
179 italic: f("\x1b[3m", "\x1b[23m"),
180 underline: f("\x1b[4m", "\x1b[24m"),
181 inverse: f("\x1b[7m", "\x1b[27m"),
182 hidden: f("\x1b[8m", "\x1b[28m"),
183 strikethrough: f("\x1b[9m", "\x1b[29m"),
184
185 black: f("\x1b[30m", "\x1b[39m"),
186 red: f("\x1b[31m", "\x1b[39m"),
187 green: f("\x1b[32m", "\x1b[39m"),
188 yellow: f("\x1b[33m", "\x1b[39m"),
189 blue: f("\x1b[34m", "\x1b[39m"),
190 magenta: f("\x1b[35m", "\x1b[39m"),
191 cyan: f("\x1b[36m", "\x1b[39m"),
192 white: f("\x1b[37m", "\x1b[39m"),
193 gray: f("\x1b[90m", "\x1b[39m"),
194
195 bgBlack: f("\x1b[40m", "\x1b[49m"),
196 bgRed: f("\x1b[41m", "\x1b[49m"),
197 bgGreen: f("\x1b[42m", "\x1b[49m"),
198 bgYellow: f("\x1b[43m", "\x1b[49m"),
199 bgBlue: f("\x1b[44m", "\x1b[49m"),
200 bgMagenta: f("\x1b[45m", "\x1b[49m"),
201 bgCyan: f("\x1b[46m", "\x1b[49m"),
202 bgWhite: f("\x1b[47m", "\x1b[49m"),
203
204 blackBright: f("\x1b[90m", "\x1b[39m"),
205 redBright: f("\x1b[91m", "\x1b[39m"),
206 greenBright: f("\x1b[92m", "\x1b[39m"),
207 yellowBright: f("\x1b[93m", "\x1b[39m"),
208 blueBright: f("\x1b[94m", "\x1b[39m"),
209 magentaBright: f("\x1b[95m", "\x1b[39m"),
210 cyanBright: f("\x1b[96m", "\x1b[39m"),
211 whiteBright: f("\x1b[97m", "\x1b[39m"),
212
213 bgBlackBright: f("\x1b[100m", "\x1b[49m"),
214 bgRedBright: f("\x1b[101m", "\x1b[49m"),
215 bgGreenBright: f("\x1b[102m", "\x1b[49m"),
216 bgYellowBright: f("\x1b[103m", "\x1b[49m"),
217 bgBlueBright: f("\x1b[104m", "\x1b[49m"),
218 bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
219 bgCyanBright: f("\x1b[106m", "\x1b[49m"),
220 bgWhiteBright: f("\x1b[107m", "\x1b[49m"),
221 }
222};
223
224picocolors.exports = createColors();
225picocolors.exports.createColors = createColors;
226
227var picocolorsExports = picocolors.exports;
228var colors = /*@__PURE__*/getDefaultExportFromCjs(picocolorsExports);
229
230var src = {exports: {}};
231
232var browser$1 = {exports: {}};
233
234/**
235 * Helpers.
236 */
237
238var ms;
239var hasRequiredMs;
240
241function requireMs () {
242 if (hasRequiredMs) return ms;
243 hasRequiredMs = 1;
244 var s = 1000;
245 var m = s * 60;
246 var h = m * 60;
247 var d = h * 24;
248 var w = d * 7;
249 var y = d * 365.25;
250
251 /**
252 * Parse or format the given `val`.
253 *
254 * Options:
255 *
256 * - `long` verbose formatting [false]
257 *
258 * @param {String|Number} val
259 * @param {Object} [options]
260 * @throws {Error} throw an error if val is not a non-empty string or a number
261 * @return {String|Number}
262 * @api public
263 */
264
265 ms = function (val, options) {
266 options = options || {};
267 var type = typeof val;
268 if (type === 'string' && val.length > 0) {
269 return parse(val);
270 } else if (type === 'number' && isFinite(val)) {
271 return options.long ? fmtLong(val) : fmtShort(val);
272 }
273 throw new Error(
274 'val is not a non-empty string or a valid number. val=' +
275 JSON.stringify(val)
276 );
277 };
278
279 /**
280 * Parse the given `str` and return milliseconds.
281 *
282 * @param {String} str
283 * @return {Number}
284 * @api private
285 */
286
287 function parse(str) {
288 str = String(str);
289 if (str.length > 100) {
290 return;
291 }
292 var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
293 str
294 );
295 if (!match) {
296 return;
297 }
298 var n = parseFloat(match[1]);
299 var type = (match[2] || 'ms').toLowerCase();
300 switch (type) {
301 case 'years':
302 case 'year':
303 case 'yrs':
304 case 'yr':
305 case 'y':
306 return n * y;
307 case 'weeks':
308 case 'week':
309 case 'w':
310 return n * w;
311 case 'days':
312 case 'day':
313 case 'd':
314 return n * d;
315 case 'hours':
316 case 'hour':
317 case 'hrs':
318 case 'hr':
319 case 'h':
320 return n * h;
321 case 'minutes':
322 case 'minute':
323 case 'mins':
324 case 'min':
325 case 'm':
326 return n * m;
327 case 'seconds':
328 case 'second':
329 case 'secs':
330 case 'sec':
331 case 's':
332 return n * s;
333 case 'milliseconds':
334 case 'millisecond':
335 case 'msecs':
336 case 'msec':
337 case 'ms':
338 return n;
339 default:
340 return undefined;
341 }
342 }
343
344 /**
345 * Short format for `ms`.
346 *
347 * @param {Number} ms
348 * @return {String}
349 * @api private
350 */
351
352 function fmtShort(ms) {
353 var msAbs = Math.abs(ms);
354 if (msAbs >= d) {
355 return Math.round(ms / d) + 'd';
356 }
357 if (msAbs >= h) {
358 return Math.round(ms / h) + 'h';
359 }
360 if (msAbs >= m) {
361 return Math.round(ms / m) + 'm';
362 }
363 if (msAbs >= s) {
364 return Math.round(ms / s) + 's';
365 }
366 return ms + 'ms';
367 }
368
369 /**
370 * Long format for `ms`.
371 *
372 * @param {Number} ms
373 * @return {String}
374 * @api private
375 */
376
377 function fmtLong(ms) {
378 var msAbs = Math.abs(ms);
379 if (msAbs >= d) {
380 return plural(ms, msAbs, d, 'day');
381 }
382 if (msAbs >= h) {
383 return plural(ms, msAbs, h, 'hour');
384 }
385 if (msAbs >= m) {
386 return plural(ms, msAbs, m, 'minute');
387 }
388 if (msAbs >= s) {
389 return plural(ms, msAbs, s, 'second');
390 }
391 return ms + ' ms';
392 }
393
394 /**
395 * Pluralization helper.
396 */
397
398 function plural(ms, msAbs, n, name) {
399 var isPlural = msAbs >= n * 1.5;
400 return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
401 }
402 return ms;
403}
404
405var common;
406var hasRequiredCommon;
407
408function requireCommon () {
409 if (hasRequiredCommon) return common;
410 hasRequiredCommon = 1;
411 /**
412 * This is the common logic for both the Node.js and web browser
413 * implementations of `debug()`.
414 */
415
416 function setup(env) {
417 createDebug.debug = createDebug;
418 createDebug.default = createDebug;
419 createDebug.coerce = coerce;
420 createDebug.disable = disable;
421 createDebug.enable = enable;
422 createDebug.enabled = enabled;
423 createDebug.humanize = requireMs();
424 createDebug.destroy = destroy;
425
426 Object.keys(env).forEach(key => {
427 createDebug[key] = env[key];
428 });
429
430 /**
431 * The currently active debug mode names, and names to skip.
432 */
433
434 createDebug.names = [];
435 createDebug.skips = [];
436
437 /**
438 * Map of special "%n" handling functions, for the debug "format" argument.
439 *
440 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
441 */
442 createDebug.formatters = {};
443
444 /**
445 * Selects a color for a debug namespace
446 * @param {String} namespace The namespace string for the debug instance to be colored
447 * @return {Number|String} An ANSI color code for the given namespace
448 * @api private
449 */
450 function selectColor(namespace) {
451 let hash = 0;
452
453 for (let i = 0; i < namespace.length; i++) {
454 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
455 hash |= 0; // Convert to 32bit integer
456 }
457
458 return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
459 }
460 createDebug.selectColor = selectColor;
461
462 /**
463 * Create a debugger with the given `namespace`.
464 *
465 * @param {String} namespace
466 * @return {Function}
467 * @api public
468 */
469 function createDebug(namespace) {
470 let prevTime;
471 let enableOverride = null;
472 let namespacesCache;
473 let enabledCache;
474
475 function debug(...args) {
476 // Disabled?
477 if (!debug.enabled) {
478 return;
479 }
480
481 const self = debug;
482
483 // Set `diff` timestamp
484 const curr = Number(new Date());
485 const ms = curr - (prevTime || curr);
486 self.diff = ms;
487 self.prev = prevTime;
488 self.curr = curr;
489 prevTime = curr;
490
491 args[0] = createDebug.coerce(args[0]);
492
493 if (typeof args[0] !== 'string') {
494 // Anything else let's inspect with %O
495 args.unshift('%O');
496 }
497
498 // Apply any `formatters` transformations
499 let index = 0;
500 args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
501 // If we encounter an escaped % then don't increase the array index
502 if (match === '%%') {
503 return '%';
504 }
505 index++;
506 const formatter = createDebug.formatters[format];
507 if (typeof formatter === 'function') {
508 const val = args[index];
509 match = formatter.call(self, val);
510
511 // Now we need to remove `args[index]` since it's inlined in the `format`
512 args.splice(index, 1);
513 index--;
514 }
515 return match;
516 });
517
518 // Apply env-specific formatting (colors, etc.)
519 createDebug.formatArgs.call(self, args);
520
521 const logFn = self.log || createDebug.log;
522 logFn.apply(self, args);
523 }
524
525 debug.namespace = namespace;
526 debug.useColors = createDebug.useColors();
527 debug.color = createDebug.selectColor(namespace);
528 debug.extend = extend;
529 debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
530
531 Object.defineProperty(debug, 'enabled', {
532 enumerable: true,
533 configurable: false,
534 get: () => {
535 if (enableOverride !== null) {
536 return enableOverride;
537 }
538 if (namespacesCache !== createDebug.namespaces) {
539 namespacesCache = createDebug.namespaces;
540 enabledCache = createDebug.enabled(namespace);
541 }
542
543 return enabledCache;
544 },
545 set: v => {
546 enableOverride = v;
547 }
548 });
549
550 // Env-specific initialization logic for debug instances
551 if (typeof createDebug.init === 'function') {
552 createDebug.init(debug);
553 }
554
555 return debug;
556 }
557
558 function extend(namespace, delimiter) {
559 const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
560 newDebug.log = this.log;
561 return newDebug;
562 }
563
564 /**
565 * Enables a debug mode by namespaces. This can include modes
566 * separated by a colon and wildcards.
567 *
568 * @param {String} namespaces
569 * @api public
570 */
571 function enable(namespaces) {
572 createDebug.save(namespaces);
573 createDebug.namespaces = namespaces;
574
575 createDebug.names = [];
576 createDebug.skips = [];
577
578 const split = (typeof namespaces === 'string' ? namespaces : '')
579 .trim()
580 .replace(' ', ',')
581 .split(',')
582 .filter(Boolean);
583
584 for (const ns of split) {
585 if (ns[0] === '-') {
586 createDebug.skips.push(ns.slice(1));
587 } else {
588 createDebug.names.push(ns);
589 }
590 }
591 }
592
593 /**
594 * Checks if the given string matches a namespace template, honoring
595 * asterisks as wildcards.
596 *
597 * @param {String} search
598 * @param {String} template
599 * @return {Boolean}
600 */
601 function matchesTemplate(search, template) {
602 let searchIndex = 0;
603 let templateIndex = 0;
604 let starIndex = -1;
605 let matchIndex = 0;
606
607 while (searchIndex < search.length) {
608 if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {
609 // Match character or proceed with wildcard
610 if (template[templateIndex] === '*') {
611 starIndex = templateIndex;
612 matchIndex = searchIndex;
613 templateIndex++; // Skip the '*'
614 } else {
615 searchIndex++;
616 templateIndex++;
617 }
618 } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition
619 // Backtrack to the last '*' and try to match more characters
620 templateIndex = starIndex + 1;
621 matchIndex++;
622 searchIndex = matchIndex;
623 } else {
624 return false; // No match
625 }
626 }
627
628 // Handle trailing '*' in template
629 while (templateIndex < template.length && template[templateIndex] === '*') {
630 templateIndex++;
631 }
632
633 return templateIndex === template.length;
634 }
635
636 /**
637 * Disable debug output.
638 *
639 * @return {String} namespaces
640 * @api public
641 */
642 function disable() {
643 const namespaces = [
644 ...createDebug.names,
645 ...createDebug.skips.map(namespace => '-' + namespace)
646 ].join(',');
647 createDebug.enable('');
648 return namespaces;
649 }
650
651 /**
652 * Returns true if the given mode name is enabled, false otherwise.
653 *
654 * @param {String} name
655 * @return {Boolean}
656 * @api public
657 */
658 function enabled(name) {
659 for (const skip of createDebug.skips) {
660 if (matchesTemplate(name, skip)) {
661 return false;
662 }
663 }
664
665 for (const ns of createDebug.names) {
666 if (matchesTemplate(name, ns)) {
667 return true;
668 }
669 }
670
671 return false;
672 }
673
674 /**
675 * Coerce `val`.
676 *
677 * @param {Mixed} val
678 * @return {Mixed}
679 * @api private
680 */
681 function coerce(val) {
682 if (val instanceof Error) {
683 return val.stack || val.message;
684 }
685 return val;
686 }
687
688 /**
689 * XXX DO NOT USE. This is a temporary stub function.
690 * XXX It WILL be removed in the next major release.
691 */
692 function destroy() {
693 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
694 }
695
696 createDebug.enable(createDebug.load());
697
698 return createDebug;
699 }
700
701 common = setup;
702 return common;
703}
704
705/* eslint-env browser */
706
707var hasRequiredBrowser;
708
709function requireBrowser () {
710 if (hasRequiredBrowser) return browser$1.exports;
711 hasRequiredBrowser = 1;
712 (function (module, exports) {
713 /**
714 * This is the web browser implementation of `debug()`.
715 */
716
717 exports.formatArgs = formatArgs;
718 exports.save = save;
719 exports.load = load;
720 exports.useColors = useColors;
721 exports.storage = localstorage();
722 exports.destroy = (() => {
723 let warned = false;
724
725 return () => {
726 if (!warned) {
727 warned = true;
728 console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
729 }
730 };
731 })();
732
733 /**
734 * Colors.
735 */
736
737 exports.colors = [
738 '#0000CC',
739 '#0000FF',
740 '#0033CC',
741 '#0033FF',
742 '#0066CC',
743 '#0066FF',
744 '#0099CC',
745 '#0099FF',
746 '#00CC00',
747 '#00CC33',
748 '#00CC66',
749 '#00CC99',
750 '#00CCCC',
751 '#00CCFF',
752 '#3300CC',
753 '#3300FF',
754 '#3333CC',
755 '#3333FF',
756 '#3366CC',
757 '#3366FF',
758 '#3399CC',
759 '#3399FF',
760 '#33CC00',
761 '#33CC33',
762 '#33CC66',
763 '#33CC99',
764 '#33CCCC',
765 '#33CCFF',
766 '#6600CC',
767 '#6600FF',
768 '#6633CC',
769 '#6633FF',
770 '#66CC00',
771 '#66CC33',
772 '#9900CC',
773 '#9900FF',
774 '#9933CC',
775 '#9933FF',
776 '#99CC00',
777 '#99CC33',
778 '#CC0000',
779 '#CC0033',
780 '#CC0066',
781 '#CC0099',
782 '#CC00CC',
783 '#CC00FF',
784 '#CC3300',
785 '#CC3333',
786 '#CC3366',
787 '#CC3399',
788 '#CC33CC',
789 '#CC33FF',
790 '#CC6600',
791 '#CC6633',
792 '#CC9900',
793 '#CC9933',
794 '#CCCC00',
795 '#CCCC33',
796 '#FF0000',
797 '#FF0033',
798 '#FF0066',
799 '#FF0099',
800 '#FF00CC',
801 '#FF00FF',
802 '#FF3300',
803 '#FF3333',
804 '#FF3366',
805 '#FF3399',
806 '#FF33CC',
807 '#FF33FF',
808 '#FF6600',
809 '#FF6633',
810 '#FF9900',
811 '#FF9933',
812 '#FFCC00',
813 '#FFCC33'
814 ];
815
816 /**
817 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
818 * and the Firebug extension (any Firefox version) are known
819 * to support "%c" CSS customizations.
820 *
821 * TODO: add a `localStorage` variable to explicitly enable/disable colors
822 */
823
824 // eslint-disable-next-line complexity
825 function useColors() {
826 // NB: In an Electron preload script, document will be defined but not fully
827 // initialized. Since we know we're in Chrome, we'll just detect this case
828 // explicitly
829 if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
830 return true;
831 }
832
833 // Internet Explorer and Edge do not support colors.
834 if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
835 return false;
836 }
837
838 let m;
839
840 // Is webkit? http://stackoverflow.com/a/16459606/376773
841 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
842 // eslint-disable-next-line no-return-assign
843 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
844 // Is firebug? http://stackoverflow.com/a/398120/376773
845 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
846 // Is firefox >= v31?
847 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
848 (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) ||
849 // Double check webkit in userAgent just in case we are in a worker
850 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
851 }
852
853 /**
854 * Colorize log arguments if enabled.
855 *
856 * @api public
857 */
858
859 function formatArgs(args) {
860 args[0] = (this.useColors ? '%c' : '') +
861 this.namespace +
862 (this.useColors ? ' %c' : ' ') +
863 args[0] +
864 (this.useColors ? '%c ' : ' ') +
865 '+' + module.exports.humanize(this.diff);
866
867 if (!this.useColors) {
868 return;
869 }
870
871 const c = 'color: ' + this.color;
872 args.splice(1, 0, c, 'color: inherit');
873
874 // The final "%c" is somewhat tricky, because there could be other
875 // arguments passed either before or after the %c, so we need to
876 // figure out the correct index to insert the CSS into
877 let index = 0;
878 let lastC = 0;
879 args[0].replace(/%[a-zA-Z%]/g, match => {
880 if (match === '%%') {
881 return;
882 }
883 index++;
884 if (match === '%c') {
885 // We only are interested in the *last* %c
886 // (the user may have provided their own)
887 lastC = index;
888 }
889 });
890
891 args.splice(lastC, 0, c);
892 }
893
894 /**
895 * Invokes `console.debug()` when available.
896 * No-op when `console.debug` is not a "function".
897 * If `console.debug` is not available, falls back
898 * to `console.log`.
899 *
900 * @api public
901 */
902 exports.log = console.debug || console.log || (() => {});
903
904 /**
905 * Save `namespaces`.
906 *
907 * @param {String} namespaces
908 * @api private
909 */
910 function save(namespaces) {
911 try {
912 if (namespaces) {
913 exports.storage.setItem('debug', namespaces);
914 } else {
915 exports.storage.removeItem('debug');
916 }
917 } catch (error) {
918 // Swallow
919 // XXX (@Qix-) should we be logging these?
920 }
921 }
922
923 /**
924 * Load `namespaces`.
925 *
926 * @return {String} returns the previously persisted debug modes
927 * @api private
928 */
929 function load() {
930 let r;
931 try {
932 r = exports.storage.getItem('debug');
933 } catch (error) {
934 // Swallow
935 // XXX (@Qix-) should we be logging these?
936 }
937
938 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
939 if (!r && typeof process !== 'undefined' && 'env' in process) {
940 r = process.env.DEBUG;
941 }
942
943 return r;
944 }
945
946 /**
947 * Localstorage attempts to return the localstorage.
948 *
949 * This is necessary because safari throws
950 * when a user disables cookies/localstorage
951 * and you attempt to access it.
952 *
953 * @return {LocalStorage}
954 * @api private
955 */
956
957 function localstorage() {
958 try {
959 // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
960 // The Browser also has localStorage in the global context.
961 return localStorage;
962 } catch (error) {
963 // Swallow
964 // XXX (@Qix-) should we be logging these?
965 }
966 }
967
968 module.exports = requireCommon()(exports);
969
970 const {formatters} = module.exports;
971
972 /**
973 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
974 */
975
976 formatters.j = function (v) {
977 try {
978 return JSON.stringify(v);
979 } catch (error) {
980 return '[UnexpectedJSONParseError]: ' + error.message;
981 }
982 };
983 } (browser$1, browser$1.exports));
984 return browser$1.exports;
985}
986
987var node = {exports: {}};
988
989/**
990 * Module dependencies.
991 */
992
993var hasRequiredNode;
994
995function requireNode () {
996 if (hasRequiredNode) return node.exports;
997 hasRequiredNode = 1;
998 (function (module, exports) {
999 const tty = require$$0;
1000 const util = require$$1;
1001
1002 /**
1003 * This is the Node.js implementation of `debug()`.
1004 */
1005
1006 exports.init = init;
1007 exports.log = log;
1008 exports.formatArgs = formatArgs;
1009 exports.save = save;
1010 exports.load = load;
1011 exports.useColors = useColors;
1012 exports.destroy = util.deprecate(
1013 () => {},
1014 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
1015 );
1016
1017 /**
1018 * Colors.
1019 */
1020
1021 exports.colors = [6, 2, 3, 4, 5, 1];
1022
1023 try {
1024 // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
1025 // eslint-disable-next-line import/no-extraneous-dependencies
1026 const supportsColor = require('supports-color');
1027
1028 if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
1029 exports.colors = [
1030 20,
1031 21,
1032 26,
1033 27,
1034 32,
1035 33,
1036 38,
1037 39,
1038 40,
1039 41,
1040 42,
1041 43,
1042 44,
1043 45,
1044 56,
1045 57,
1046 62,
1047 63,
1048 68,
1049 69,
1050 74,
1051 75,
1052 76,
1053 77,
1054 78,
1055 79,
1056 80,
1057 81,
1058 92,
1059 93,
1060 98,
1061 99,
1062 112,
1063 113,
1064 128,
1065 129,
1066 134,
1067 135,
1068 148,
1069 149,
1070 160,
1071 161,
1072 162,
1073 163,
1074 164,
1075 165,
1076 166,
1077 167,
1078 168,
1079 169,
1080 170,
1081 171,
1082 172,
1083 173,
1084 178,
1085 179,
1086 184,
1087 185,
1088 196,
1089 197,
1090 198,
1091 199,
1092 200,
1093 201,
1094 202,
1095 203,
1096 204,
1097 205,
1098 206,
1099 207,
1100 208,
1101 209,
1102 214,
1103 215,
1104 220,
1105 221
1106 ];
1107 }
1108 } catch (error) {
1109 // Swallow - we only care if `supports-color` is available; it doesn't have to be.
1110 }
1111
1112 /**
1113 * Build up the default `inspectOpts` object from the environment variables.
1114 *
1115 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
1116 */
1117
1118 exports.inspectOpts = Object.keys(process.env).filter(key => {
1119 return /^debug_/i.test(key);
1120 }).reduce((obj, key) => {
1121 // Camel-case
1122 const prop = key
1123 .substring(6)
1124 .toLowerCase()
1125 .replace(/_([a-z])/g, (_, k) => {
1126 return k.toUpperCase();
1127 });
1128
1129 // Coerce string value into JS value
1130 let val = process.env[key];
1131 if (/^(yes|on|true|enabled)$/i.test(val)) {
1132 val = true;
1133 } else if (/^(no|off|false|disabled)$/i.test(val)) {
1134 val = false;
1135 } else if (val === 'null') {
1136 val = null;
1137 } else {
1138 val = Number(val);
1139 }
1140
1141 obj[prop] = val;
1142 return obj;
1143 }, {});
1144
1145 /**
1146 * Is stdout a TTY? Colored output is enabled when `true`.
1147 */
1148
1149 function useColors() {
1150 return 'colors' in exports.inspectOpts ?
1151 Boolean(exports.inspectOpts.colors) :
1152 tty.isatty(process.stderr.fd);
1153 }
1154
1155 /**
1156 * Adds ANSI color escape codes if enabled.
1157 *
1158 * @api public
1159 */
1160
1161 function formatArgs(args) {
1162 const {namespace: name, useColors} = this;
1163
1164 if (useColors) {
1165 const c = this.color;
1166 const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
1167 const prefix = ` ${colorCode};1m${name} \u001B[0m`;
1168
1169 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
1170 args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
1171 } else {
1172 args[0] = getDate() + name + ' ' + args[0];
1173 }
1174 }
1175
1176 function getDate() {
1177 if (exports.inspectOpts.hideDate) {
1178 return '';
1179 }
1180 return new Date().toISOString() + ' ';
1181 }
1182
1183 /**
1184 * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.
1185 */
1186
1187 function log(...args) {
1188 return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n');
1189 }
1190
1191 /**
1192 * Save `namespaces`.
1193 *
1194 * @param {String} namespaces
1195 * @api private
1196 */
1197 function save(namespaces) {
1198 if (namespaces) {
1199 process.env.DEBUG = namespaces;
1200 } else {
1201 // If you set a process.env field to null or undefined, it gets cast to the
1202 // string 'null' or 'undefined'. Just delete instead.
1203 delete process.env.DEBUG;
1204 }
1205 }
1206
1207 /**
1208 * Load `namespaces`.
1209 *
1210 * @return {String} returns the previously persisted debug modes
1211 * @api private
1212 */
1213
1214 function load() {
1215 return process.env.DEBUG;
1216 }
1217
1218 /**
1219 * Init logic for `debug` instances.
1220 *
1221 * Create a new `inspectOpts` object in case `useColors` is set
1222 * differently for a particular `debug` instance.
1223 */
1224
1225 function init(debug) {
1226 debug.inspectOpts = {};
1227
1228 const keys = Object.keys(exports.inspectOpts);
1229 for (let i = 0; i < keys.length; i++) {
1230 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
1231 }
1232 }
1233
1234 module.exports = requireCommon()(exports);
1235
1236 const {formatters} = module.exports;
1237
1238 /**
1239 * Map %o to `util.inspect()`, all on a single line.
1240 */
1241
1242 formatters.o = function (v) {
1243 this.inspectOpts.colors = this.useColors;
1244 return util.inspect(v, this.inspectOpts)
1245 .split('\n')
1246 .map(str => str.trim())
1247 .join(' ');
1248 };
1249
1250 /**
1251 * Map %O to `util.inspect()`, allowing multiple lines if needed.
1252 */
1253
1254 formatters.O = function (v) {
1255 this.inspectOpts.colors = this.useColors;
1256 return util.inspect(v, this.inspectOpts);
1257 };
1258 } (node, node.exports));
1259 return node.exports;
1260}
1261
1262/**
1263 * Detect Electron renderer / nwjs process, which is node, but we should
1264 * treat as a browser.
1265 */
1266
1267if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
1268 src.exports = requireBrowser();
1269} else {
1270 src.exports = requireNode();
1271}
1272
1273var srcExports = src.exports;
1274var debug$2 = /*@__PURE__*/getDefaultExportFromCjs(srcExports);
1275
1276var utils$4 = {};
1277
1278const WIN_SLASH = '\\\\/';
1279const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
1280
1281/**
1282 * Posix glob regex
1283 */
1284
1285const DOT_LITERAL = '\\.';
1286const PLUS_LITERAL = '\\+';
1287const QMARK_LITERAL = '\\?';
1288const SLASH_LITERAL = '\\/';
1289const ONE_CHAR = '(?=.)';
1290const QMARK = '[^/]';
1291const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
1292const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
1293const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
1294const NO_DOT = `(?!${DOT_LITERAL})`;
1295const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
1296const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
1297const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
1298const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
1299const STAR = `${QMARK}*?`;
1300const SEP = '/';
1301
1302const POSIX_CHARS = {
1303 DOT_LITERAL,
1304 PLUS_LITERAL,
1305 QMARK_LITERAL,
1306 SLASH_LITERAL,
1307 ONE_CHAR,
1308 QMARK,
1309 END_ANCHOR,
1310 DOTS_SLASH,
1311 NO_DOT,
1312 NO_DOTS,
1313 NO_DOT_SLASH,
1314 NO_DOTS_SLASH,
1315 QMARK_NO_DOT,
1316 STAR,
1317 START_ANCHOR,
1318 SEP
1319};
1320
1321/**
1322 * Windows glob regex
1323 */
1324
1325const WINDOWS_CHARS = {
1326 ...POSIX_CHARS,
1327
1328 SLASH_LITERAL: `[${WIN_SLASH}]`,
1329 QMARK: WIN_NO_SLASH,
1330 STAR: `${WIN_NO_SLASH}*?`,
1331 DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
1332 NO_DOT: `(?!${DOT_LITERAL})`,
1333 NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
1334 NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
1335 NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
1336 QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
1337 START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
1338 END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
1339 SEP: '\\'
1340};
1341
1342/**
1343 * POSIX Bracket Regex
1344 */
1345
1346const POSIX_REGEX_SOURCE$1 = {
1347 alnum: 'a-zA-Z0-9',
1348 alpha: 'a-zA-Z',
1349 ascii: '\\x00-\\x7F',
1350 blank: ' \\t',
1351 cntrl: '\\x00-\\x1F\\x7F',
1352 digit: '0-9',
1353 graph: '\\x21-\\x7E',
1354 lower: 'a-z',
1355 print: '\\x20-\\x7E ',
1356 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
1357 space: ' \\t\\r\\n\\v\\f',
1358 upper: 'A-Z',
1359 word: 'A-Za-z0-9_',
1360 xdigit: 'A-Fa-f0-9'
1361};
1362
1363var constants$2 = {
1364 MAX_LENGTH: 1024 * 64,
1365 POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
1366
1367 // regular expressions
1368 REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
1369 REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
1370 REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
1371 REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
1372 REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
1373 REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
1374
1375 // Replace globs with equivalent patterns to reduce parsing time.
1376 REPLACEMENTS: {
1377 '***': '*',
1378 '**/**': '**',
1379 '**/**/**': '**'
1380 },
1381
1382 // Digits
1383 CHAR_0: 48, /* 0 */
1384 CHAR_9: 57, /* 9 */
1385
1386 // Alphabet chars.
1387 CHAR_UPPERCASE_A: 65, /* A */
1388 CHAR_LOWERCASE_A: 97, /* a */
1389 CHAR_UPPERCASE_Z: 90, /* Z */
1390 CHAR_LOWERCASE_Z: 122, /* z */
1391
1392 CHAR_LEFT_PARENTHESES: 40, /* ( */
1393 CHAR_RIGHT_PARENTHESES: 41, /* ) */
1394
1395 CHAR_ASTERISK: 42, /* * */
1396
1397 // Non-alphabetic chars.
1398 CHAR_AMPERSAND: 38, /* & */
1399 CHAR_AT: 64, /* @ */
1400 CHAR_BACKWARD_SLASH: 92, /* \ */
1401 CHAR_CARRIAGE_RETURN: 13, /* \r */
1402 CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
1403 CHAR_COLON: 58, /* : */
1404 CHAR_COMMA: 44, /* , */
1405 CHAR_DOT: 46, /* . */
1406 CHAR_DOUBLE_QUOTE: 34, /* " */
1407 CHAR_EQUAL: 61, /* = */
1408 CHAR_EXCLAMATION_MARK: 33, /* ! */
1409 CHAR_FORM_FEED: 12, /* \f */
1410 CHAR_FORWARD_SLASH: 47, /* / */
1411 CHAR_GRAVE_ACCENT: 96, /* ` */
1412 CHAR_HASH: 35, /* # */
1413 CHAR_HYPHEN_MINUS: 45, /* - */
1414 CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
1415 CHAR_LEFT_CURLY_BRACE: 123, /* { */
1416 CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
1417 CHAR_LINE_FEED: 10, /* \n */
1418 CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
1419 CHAR_PERCENT: 37, /* % */
1420 CHAR_PLUS: 43, /* + */
1421 CHAR_QUESTION_MARK: 63, /* ? */
1422 CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
1423 CHAR_RIGHT_CURLY_BRACE: 125, /* } */
1424 CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
1425 CHAR_SEMICOLON: 59, /* ; */
1426 CHAR_SINGLE_QUOTE: 39, /* ' */
1427 CHAR_SPACE: 32, /* */
1428 CHAR_TAB: 9, /* \t */
1429 CHAR_UNDERSCORE: 95, /* _ */
1430 CHAR_VERTICAL_LINE: 124, /* | */
1431 CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
1432
1433 /**
1434 * Create EXTGLOB_CHARS
1435 */
1436
1437 extglobChars(chars) {
1438 return {
1439 '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
1440 '?': { type: 'qmark', open: '(?:', close: ')?' },
1441 '+': { type: 'plus', open: '(?:', close: ')+' },
1442 '*': { type: 'star', open: '(?:', close: ')*' },
1443 '@': { type: 'at', open: '(?:', close: ')' }
1444 };
1445 },
1446
1447 /**
1448 * Create GLOB_CHARS
1449 */
1450
1451 globChars(win32) {
1452 return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
1453 }
1454};
1455
1456/*global navigator*/
1457
1458(function (exports) {
1459
1460 const {
1461 REGEX_BACKSLASH,
1462 REGEX_REMOVE_BACKSLASH,
1463 REGEX_SPECIAL_CHARS,
1464 REGEX_SPECIAL_CHARS_GLOBAL
1465 } = constants$2;
1466
1467 exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
1468 exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
1469 exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
1470 exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
1471 exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
1472
1473 exports.isWindows = () => {
1474 if (typeof navigator !== 'undefined' && navigator.platform) {
1475 const platform = navigator.platform.toLowerCase();
1476 return platform === 'win32' || platform === 'windows';
1477 }
1478
1479 if (typeof process !== 'undefined' && process.platform) {
1480 return process.platform === 'win32';
1481 }
1482
1483 return false;
1484 };
1485
1486 exports.removeBackslashes = str => {
1487 return str.replace(REGEX_REMOVE_BACKSLASH, match => {
1488 return match === '\\' ? '' : match;
1489 });
1490 };
1491
1492 exports.escapeLast = (input, char, lastIdx) => {
1493 const idx = input.lastIndexOf(char, lastIdx);
1494 if (idx === -1) return input;
1495 if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
1496 return `${input.slice(0, idx)}\\${input.slice(idx)}`;
1497 };
1498
1499 exports.removePrefix = (input, state = {}) => {
1500 let output = input;
1501 if (output.startsWith('./')) {
1502 output = output.slice(2);
1503 state.prefix = './';
1504 }
1505 return output;
1506 };
1507
1508 exports.wrapOutput = (input, state = {}, options = {}) => {
1509 const prepend = options.contains ? '' : '^';
1510 const append = options.contains ? '' : '$';
1511
1512 let output = `${prepend}(?:${input})${append}`;
1513 if (state.negated === true) {
1514 output = `(?:^(?!${output}).*$)`;
1515 }
1516 return output;
1517 };
1518
1519 exports.basename = (path, { windows } = {}) => {
1520 const segs = path.split(windows ? /[\\/]/ : '/');
1521 const last = segs[segs.length - 1];
1522
1523 if (last === '') {
1524 return segs[segs.length - 2];
1525 }
1526
1527 return last;
1528 };
1529} (utils$4));
1530
1531const utils$3 = utils$4;
1532const {
1533 CHAR_ASTERISK, /* * */
1534 CHAR_AT, /* @ */
1535 CHAR_BACKWARD_SLASH, /* \ */
1536 CHAR_COMMA, /* , */
1537 CHAR_DOT, /* . */
1538 CHAR_EXCLAMATION_MARK, /* ! */
1539 CHAR_FORWARD_SLASH, /* / */
1540 CHAR_LEFT_CURLY_BRACE, /* { */
1541 CHAR_LEFT_PARENTHESES, /* ( */
1542 CHAR_LEFT_SQUARE_BRACKET, /* [ */
1543 CHAR_PLUS, /* + */
1544 CHAR_QUESTION_MARK, /* ? */
1545 CHAR_RIGHT_CURLY_BRACE, /* } */
1546 CHAR_RIGHT_PARENTHESES, /* ) */
1547 CHAR_RIGHT_SQUARE_BRACKET /* ] */
1548} = constants$2;
1549
1550const isPathSeparator = code => {
1551 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
1552};
1553
1554const depth = token => {
1555 if (token.isPrefix !== true) {
1556 token.depth = token.isGlobstar ? Infinity : 1;
1557 }
1558};
1559
1560/**
1561 * Quickly scans a glob pattern and returns an object with a handful of
1562 * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
1563 * `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
1564 * with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
1565 *
1566 * ```js
1567 * const pm = require('picomatch');
1568 * console.log(pm.scan('foo/bar/*.js'));
1569 * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
1570 * ```
1571 * @param {String} `str`
1572 * @param {Object} `options`
1573 * @return {Object} Returns an object with tokens and regex source string.
1574 * @api public
1575 */
1576
1577const scan$1 = (input, options) => {
1578 const opts = options || {};
1579
1580 const length = input.length - 1;
1581 const scanToEnd = opts.parts === true || opts.scanToEnd === true;
1582 const slashes = [];
1583 const tokens = [];
1584 const parts = [];
1585
1586 let str = input;
1587 let index = -1;
1588 let start = 0;
1589 let lastIndex = 0;
1590 let isBrace = false;
1591 let isBracket = false;
1592 let isGlob = false;
1593 let isExtglob = false;
1594 let isGlobstar = false;
1595 let braceEscaped = false;
1596 let backslashes = false;
1597 let negated = false;
1598 let negatedExtglob = false;
1599 let finished = false;
1600 let braces = 0;
1601 let prev;
1602 let code;
1603 let token = { value: '', depth: 0, isGlob: false };
1604
1605 const eos = () => index >= length;
1606 const peek = () => str.charCodeAt(index + 1);
1607 const advance = () => {
1608 prev = code;
1609 return str.charCodeAt(++index);
1610 };
1611
1612 while (index < length) {
1613 code = advance();
1614 let next;
1615
1616 if (code === CHAR_BACKWARD_SLASH) {
1617 backslashes = token.backslashes = true;
1618 code = advance();
1619
1620 if (code === CHAR_LEFT_CURLY_BRACE) {
1621 braceEscaped = true;
1622 }
1623 continue;
1624 }
1625
1626 if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
1627 braces++;
1628
1629 while (eos() !== true && (code = advance())) {
1630 if (code === CHAR_BACKWARD_SLASH) {
1631 backslashes = token.backslashes = true;
1632 advance();
1633 continue;
1634 }
1635
1636 if (code === CHAR_LEFT_CURLY_BRACE) {
1637 braces++;
1638 continue;
1639 }
1640
1641 if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
1642 isBrace = token.isBrace = true;
1643 isGlob = token.isGlob = true;
1644 finished = true;
1645
1646 if (scanToEnd === true) {
1647 continue;
1648 }
1649
1650 break;
1651 }
1652
1653 if (braceEscaped !== true && code === CHAR_COMMA) {
1654 isBrace = token.isBrace = true;
1655 isGlob = token.isGlob = true;
1656 finished = true;
1657
1658 if (scanToEnd === true) {
1659 continue;
1660 }
1661
1662 break;
1663 }
1664
1665 if (code === CHAR_RIGHT_CURLY_BRACE) {
1666 braces--;
1667
1668 if (braces === 0) {
1669 braceEscaped = false;
1670 isBrace = token.isBrace = true;
1671 finished = true;
1672 break;
1673 }
1674 }
1675 }
1676
1677 if (scanToEnd === true) {
1678 continue;
1679 }
1680
1681 break;
1682 }
1683
1684 if (code === CHAR_FORWARD_SLASH) {
1685 slashes.push(index);
1686 tokens.push(token);
1687 token = { value: '', depth: 0, isGlob: false };
1688
1689 if (finished === true) continue;
1690 if (prev === CHAR_DOT && index === (start + 1)) {
1691 start += 2;
1692 continue;
1693 }
1694
1695 lastIndex = index + 1;
1696 continue;
1697 }
1698
1699 if (opts.noext !== true) {
1700 const isExtglobChar = code === CHAR_PLUS
1701 || code === CHAR_AT
1702 || code === CHAR_ASTERISK
1703 || code === CHAR_QUESTION_MARK
1704 || code === CHAR_EXCLAMATION_MARK;
1705
1706 if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
1707 isGlob = token.isGlob = true;
1708 isExtglob = token.isExtglob = true;
1709 finished = true;
1710 if (code === CHAR_EXCLAMATION_MARK && index === start) {
1711 negatedExtglob = true;
1712 }
1713
1714 if (scanToEnd === true) {
1715 while (eos() !== true && (code = advance())) {
1716 if (code === CHAR_BACKWARD_SLASH) {
1717 backslashes = token.backslashes = true;
1718 code = advance();
1719 continue;
1720 }
1721
1722 if (code === CHAR_RIGHT_PARENTHESES) {
1723 isGlob = token.isGlob = true;
1724 finished = true;
1725 break;
1726 }
1727 }
1728 continue;
1729 }
1730 break;
1731 }
1732 }
1733
1734 if (code === CHAR_ASTERISK) {
1735 if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
1736 isGlob = token.isGlob = true;
1737 finished = true;
1738
1739 if (scanToEnd === true) {
1740 continue;
1741 }
1742 break;
1743 }
1744
1745 if (code === CHAR_QUESTION_MARK) {
1746 isGlob = token.isGlob = true;
1747 finished = true;
1748
1749 if (scanToEnd === true) {
1750 continue;
1751 }
1752 break;
1753 }
1754
1755 if (code === CHAR_LEFT_SQUARE_BRACKET) {
1756 while (eos() !== true && (next = advance())) {
1757 if (next === CHAR_BACKWARD_SLASH) {
1758 backslashes = token.backslashes = true;
1759 advance();
1760 continue;
1761 }
1762
1763 if (next === CHAR_RIGHT_SQUARE_BRACKET) {
1764 isBracket = token.isBracket = true;
1765 isGlob = token.isGlob = true;
1766 finished = true;
1767 break;
1768 }
1769 }
1770
1771 if (scanToEnd === true) {
1772 continue;
1773 }
1774
1775 break;
1776 }
1777
1778 if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
1779 negated = token.negated = true;
1780 start++;
1781 continue;
1782 }
1783
1784 if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
1785 isGlob = token.isGlob = true;
1786
1787 if (scanToEnd === true) {
1788 while (eos() !== true && (code = advance())) {
1789 if (code === CHAR_LEFT_PARENTHESES) {
1790 backslashes = token.backslashes = true;
1791 code = advance();
1792 continue;
1793 }
1794
1795 if (code === CHAR_RIGHT_PARENTHESES) {
1796 finished = true;
1797 break;
1798 }
1799 }
1800 continue;
1801 }
1802 break;
1803 }
1804
1805 if (isGlob === true) {
1806 finished = true;
1807
1808 if (scanToEnd === true) {
1809 continue;
1810 }
1811
1812 break;
1813 }
1814 }
1815
1816 if (opts.noext === true) {
1817 isExtglob = false;
1818 isGlob = false;
1819 }
1820
1821 let base = str;
1822 let prefix = '';
1823 let glob = '';
1824
1825 if (start > 0) {
1826 prefix = str.slice(0, start);
1827 str = str.slice(start);
1828 lastIndex -= start;
1829 }
1830
1831 if (base && isGlob === true && lastIndex > 0) {
1832 base = str.slice(0, lastIndex);
1833 glob = str.slice(lastIndex);
1834 } else if (isGlob === true) {
1835 base = '';
1836 glob = str;
1837 } else {
1838 base = str;
1839 }
1840
1841 if (base && base !== '' && base !== '/' && base !== str) {
1842 if (isPathSeparator(base.charCodeAt(base.length - 1))) {
1843 base = base.slice(0, -1);
1844 }
1845 }
1846
1847 if (opts.unescape === true) {
1848 if (glob) glob = utils$3.removeBackslashes(glob);
1849
1850 if (base && backslashes === true) {
1851 base = utils$3.removeBackslashes(base);
1852 }
1853 }
1854
1855 const state = {
1856 prefix,
1857 input,
1858 start,
1859 base,
1860 glob,
1861 isBrace,
1862 isBracket,
1863 isGlob,
1864 isExtglob,
1865 isGlobstar,
1866 negated,
1867 negatedExtglob
1868 };
1869
1870 if (opts.tokens === true) {
1871 state.maxDepth = 0;
1872 if (!isPathSeparator(code)) {
1873 tokens.push(token);
1874 }
1875 state.tokens = tokens;
1876 }
1877
1878 if (opts.parts === true || opts.tokens === true) {
1879 let prevIndex;
1880
1881 for (let idx = 0; idx < slashes.length; idx++) {
1882 const n = prevIndex ? prevIndex + 1 : start;
1883 const i = slashes[idx];
1884 const value = input.slice(n, i);
1885 if (opts.tokens) {
1886 if (idx === 0 && start !== 0) {
1887 tokens[idx].isPrefix = true;
1888 tokens[idx].value = prefix;
1889 } else {
1890 tokens[idx].value = value;
1891 }
1892 depth(tokens[idx]);
1893 state.maxDepth += tokens[idx].depth;
1894 }
1895 if (idx !== 0 || value !== '') {
1896 parts.push(value);
1897 }
1898 prevIndex = i;
1899 }
1900
1901 if (prevIndex && prevIndex + 1 < input.length) {
1902 const value = input.slice(prevIndex + 1);
1903 parts.push(value);
1904
1905 if (opts.tokens) {
1906 tokens[tokens.length - 1].value = value;
1907 depth(tokens[tokens.length - 1]);
1908 state.maxDepth += tokens[tokens.length - 1].depth;
1909 }
1910 }
1911
1912 state.slashes = slashes;
1913 state.parts = parts;
1914 }
1915
1916 return state;
1917};
1918
1919var scan_1 = scan$1;
1920
1921const constants$1 = constants$2;
1922const utils$2 = utils$4;
1923
1924/**
1925 * Constants
1926 */
1927
1928const {
1929 MAX_LENGTH,
1930 POSIX_REGEX_SOURCE,
1931 REGEX_NON_SPECIAL_CHARS,
1932 REGEX_SPECIAL_CHARS_BACKREF,
1933 REPLACEMENTS
1934} = constants$1;
1935
1936/**
1937 * Helpers
1938 */
1939
1940const expandRange = (args, options) => {
1941 if (typeof options.expandRange === 'function') {
1942 return options.expandRange(...args, options);
1943 }
1944
1945 args.sort();
1946 const value = `[${args.join('-')}]`;
1947
1948 return value;
1949};
1950
1951/**
1952 * Create the message for a syntax error
1953 */
1954
1955const syntaxError = (type, char) => {
1956 return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
1957};
1958
1959/**
1960 * Parse the given input string.
1961 * @param {String} input
1962 * @param {Object} options
1963 * @return {Object}
1964 */
1965
1966const parse$2 = (input, options) => {
1967 if (typeof input !== 'string') {
1968 throw new TypeError('Expected a string');
1969 }
1970
1971 input = REPLACEMENTS[input] || input;
1972
1973 const opts = { ...options };
1974 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
1975
1976 let len = input.length;
1977 if (len > max) {
1978 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
1979 }
1980
1981 const bos = { type: 'bos', value: '', output: opts.prepend || '' };
1982 const tokens = [bos];
1983
1984 const capture = opts.capture ? '' : '?:';
1985
1986 // create constants based on platform, for windows or posix
1987 const PLATFORM_CHARS = constants$1.globChars(opts.windows);
1988 const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
1989
1990 const {
1991 DOT_LITERAL,
1992 PLUS_LITERAL,
1993 SLASH_LITERAL,
1994 ONE_CHAR,
1995 DOTS_SLASH,
1996 NO_DOT,
1997 NO_DOT_SLASH,
1998 NO_DOTS_SLASH,
1999 QMARK,
2000 QMARK_NO_DOT,
2001 STAR,
2002 START_ANCHOR
2003 } = PLATFORM_CHARS;
2004
2005 const globstar = opts => {
2006 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
2007 };
2008
2009 const nodot = opts.dot ? '' : NO_DOT;
2010 const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
2011 let star = opts.bash === true ? globstar(opts) : STAR;
2012
2013 if (opts.capture) {
2014 star = `(${star})`;
2015 }
2016
2017 // minimatch options support
2018 if (typeof opts.noext === 'boolean') {
2019 opts.noextglob = opts.noext;
2020 }
2021
2022 const state = {
2023 input,
2024 index: -1,
2025 start: 0,
2026 dot: opts.dot === true,
2027 consumed: '',
2028 output: '',
2029 prefix: '',
2030 backtrack: false,
2031 negated: false,
2032 brackets: 0,
2033 braces: 0,
2034 parens: 0,
2035 quotes: 0,
2036 globstar: false,
2037 tokens
2038 };
2039
2040 input = utils$2.removePrefix(input, state);
2041 len = input.length;
2042
2043 const extglobs = [];
2044 const braces = [];
2045 const stack = [];
2046 let prev = bos;
2047 let value;
2048
2049 /**
2050 * Tokenizing helpers
2051 */
2052
2053 const eos = () => state.index === len - 1;
2054 const peek = state.peek = (n = 1) => input[state.index + n];
2055 const advance = state.advance = () => input[++state.index] || '';
2056 const remaining = () => input.slice(state.index + 1);
2057 const consume = (value = '', num = 0) => {
2058 state.consumed += value;
2059 state.index += num;
2060 };
2061
2062 const append = token => {
2063 state.output += token.output != null ? token.output : token.value;
2064 consume(token.value);
2065 };
2066
2067 const negate = () => {
2068 let count = 1;
2069
2070 while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) {
2071 advance();
2072 state.start++;
2073 count++;
2074 }
2075
2076 if (count % 2 === 0) {
2077 return false;
2078 }
2079
2080 state.negated = true;
2081 state.start++;
2082 return true;
2083 };
2084
2085 const increment = type => {
2086 state[type]++;
2087 stack.push(type);
2088 };
2089
2090 const decrement = type => {
2091 state[type]--;
2092 stack.pop();
2093 };
2094
2095 /**
2096 * Push tokens onto the tokens array. This helper speeds up
2097 * tokenizing by 1) helping us avoid backtracking as much as possible,
2098 * and 2) helping us avoid creating extra tokens when consecutive
2099 * characters are plain text. This improves performance and simplifies
2100 * lookbehinds.
2101 */
2102
2103 const push = tok => {
2104 if (prev.type === 'globstar') {
2105 const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
2106 const isExtglob = tok.extglob === true || (extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'));
2107
2108 if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
2109 state.output = state.output.slice(0, -prev.output.length);
2110 prev.type = 'star';
2111 prev.value = '*';
2112 prev.output = star;
2113 state.output += prev.output;
2114 }
2115 }
2116
2117 if (extglobs.length && tok.type !== 'paren') {
2118 extglobs[extglobs.length - 1].inner += tok.value;
2119 }
2120
2121 if (tok.value || tok.output) append(tok);
2122 if (prev && prev.type === 'text' && tok.type === 'text') {
2123 prev.output = (prev.output || prev.value) + tok.value;
2124 prev.value += tok.value;
2125 return;
2126 }
2127
2128 tok.prev = prev;
2129 tokens.push(tok);
2130 prev = tok;
2131 };
2132
2133 const extglobOpen = (type, value) => {
2134 const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' };
2135
2136 token.prev = prev;
2137 token.parens = state.parens;
2138 token.output = state.output;
2139 const output = (opts.capture ? '(' : '') + token.open;
2140
2141 increment('parens');
2142 push({ type, value, output: state.output ? '' : ONE_CHAR });
2143 push({ type: 'paren', extglob: true, value: advance(), output });
2144 extglobs.push(token);
2145 };
2146
2147 const extglobClose = token => {
2148 let output = token.close + (opts.capture ? ')' : '');
2149 let rest;
2150
2151 if (token.type === 'negate') {
2152 let extglobStar = star;
2153
2154 if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
2155 extglobStar = globstar(opts);
2156 }
2157
2158 if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) {
2159 output = token.close = `)$))${extglobStar}`;
2160 }
2161
2162 if (token.inner.includes('*') && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
2163 // Any non-magical string (`.ts`) or even nested expression (`.{ts,tsx}`) can follow after the closing parenthesis.
2164 // In this case, we need to parse the string and use it in the output of the original pattern.
2165 // Suitable patterns: `/!(*.d).ts`, `/!(*.d).{ts,tsx}`, `**/!(*-dbg).@(js)`.
2166 //
2167 // Disabling the `fastpaths` option due to a problem with parsing strings as `.ts` in the pattern like `**/!(*.d).ts`.
2168 const expression = parse$2(rest, { ...options, fastpaths: false }).output;
2169
2170 output = token.close = `)${expression})${extglobStar})`;
2171 }
2172
2173 if (token.prev.type === 'bos') {
2174 state.negatedExtglob = true;
2175 }
2176 }
2177
2178 push({ type: 'paren', extglob: true, value, output });
2179 decrement('parens');
2180 };
2181
2182 /**
2183 * Fast paths
2184 */
2185
2186 if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
2187 let backslashes = false;
2188
2189 let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
2190 if (first === '\\') {
2191 backslashes = true;
2192 return m;
2193 }
2194
2195 if (first === '?') {
2196 if (esc) {
2197 return esc + first + (rest ? QMARK.repeat(rest.length) : '');
2198 }
2199 if (index === 0) {
2200 return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
2201 }
2202 return QMARK.repeat(chars.length);
2203 }
2204
2205 if (first === '.') {
2206 return DOT_LITERAL.repeat(chars.length);
2207 }
2208
2209 if (first === '*') {
2210 if (esc) {
2211 return esc + first + (rest ? star : '');
2212 }
2213 return star;
2214 }
2215 return esc ? m : `\\${m}`;
2216 });
2217
2218 if (backslashes === true) {
2219 if (opts.unescape === true) {
2220 output = output.replace(/\\/g, '');
2221 } else {
2222 output = output.replace(/\\+/g, m => {
2223 return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
2224 });
2225 }
2226 }
2227
2228 if (output === input && opts.contains === true) {
2229 state.output = input;
2230 return state;
2231 }
2232
2233 state.output = utils$2.wrapOutput(output, state, options);
2234 return state;
2235 }
2236
2237 /**
2238 * Tokenize input until we reach end-of-string
2239 */
2240
2241 while (!eos()) {
2242 value = advance();
2243
2244 if (value === '\u0000') {
2245 continue;
2246 }
2247
2248 /**
2249 * Escaped characters
2250 */
2251
2252 if (value === '\\') {
2253 const next = peek();
2254
2255 if (next === '/' && opts.bash !== true) {
2256 continue;
2257 }
2258
2259 if (next === '.' || next === ';') {
2260 continue;
2261 }
2262
2263 if (!next) {
2264 value += '\\';
2265 push({ type: 'text', value });
2266 continue;
2267 }
2268
2269 // collapse slashes to reduce potential for exploits
2270 const match = /^\\+/.exec(remaining());
2271 let slashes = 0;
2272
2273 if (match && match[0].length > 2) {
2274 slashes = match[0].length;
2275 state.index += slashes;
2276 if (slashes % 2 !== 0) {
2277 value += '\\';
2278 }
2279 }
2280
2281 if (opts.unescape === true) {
2282 value = advance();
2283 } else {
2284 value += advance();
2285 }
2286
2287 if (state.brackets === 0) {
2288 push({ type: 'text', value });
2289 continue;
2290 }
2291 }
2292
2293 /**
2294 * If we're inside a regex character class, continue
2295 * until we reach the closing bracket.
2296 */
2297
2298 if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
2299 if (opts.posix !== false && value === ':') {
2300 const inner = prev.value.slice(1);
2301 if (inner.includes('[')) {
2302 prev.posix = true;
2303
2304 if (inner.includes(':')) {
2305 const idx = prev.value.lastIndexOf('[');
2306 const pre = prev.value.slice(0, idx);
2307 const rest = prev.value.slice(idx + 2);
2308 const posix = POSIX_REGEX_SOURCE[rest];
2309 if (posix) {
2310 prev.value = pre + posix;
2311 state.backtrack = true;
2312 advance();
2313
2314 if (!bos.output && tokens.indexOf(prev) === 1) {
2315 bos.output = ONE_CHAR;
2316 }
2317 continue;
2318 }
2319 }
2320 }
2321 }
2322
2323 if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
2324 value = `\\${value}`;
2325 }
2326
2327 if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
2328 value = `\\${value}`;
2329 }
2330
2331 if (opts.posix === true && value === '!' && prev.value === '[') {
2332 value = '^';
2333 }
2334
2335 prev.value += value;
2336 append({ value });
2337 continue;
2338 }
2339
2340 /**
2341 * If we're inside a quoted string, continue
2342 * until we reach the closing double quote.
2343 */
2344
2345 if (state.quotes === 1 && value !== '"') {
2346 value = utils$2.escapeRegex(value);
2347 prev.value += value;
2348 append({ value });
2349 continue;
2350 }
2351
2352 /**
2353 * Double quotes
2354 */
2355
2356 if (value === '"') {
2357 state.quotes = state.quotes === 1 ? 0 : 1;
2358 if (opts.keepQuotes === true) {
2359 push({ type: 'text', value });
2360 }
2361 continue;
2362 }
2363
2364 /**
2365 * Parentheses
2366 */
2367
2368 if (value === '(') {
2369 increment('parens');
2370 push({ type: 'paren', value });
2371 continue;
2372 }
2373
2374 if (value === ')') {
2375 if (state.parens === 0 && opts.strictBrackets === true) {
2376 throw new SyntaxError(syntaxError('opening', '('));
2377 }
2378
2379 const extglob = extglobs[extglobs.length - 1];
2380 if (extglob && state.parens === extglob.parens + 1) {
2381 extglobClose(extglobs.pop());
2382 continue;
2383 }
2384
2385 push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
2386 decrement('parens');
2387 continue;
2388 }
2389
2390 /**
2391 * Square brackets
2392 */
2393
2394 if (value === '[') {
2395 if (opts.nobracket === true || !remaining().includes(']')) {
2396 if (opts.nobracket !== true && opts.strictBrackets === true) {
2397 throw new SyntaxError(syntaxError('closing', ']'));
2398 }
2399
2400 value = `\\${value}`;
2401 } else {
2402 increment('brackets');
2403 }
2404
2405 push({ type: 'bracket', value });
2406 continue;
2407 }
2408
2409 if (value === ']') {
2410 if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
2411 push({ type: 'text', value, output: `\\${value}` });
2412 continue;
2413 }
2414
2415 if (state.brackets === 0) {
2416 if (opts.strictBrackets === true) {
2417 throw new SyntaxError(syntaxError('opening', '['));
2418 }
2419
2420 push({ type: 'text', value, output: `\\${value}` });
2421 continue;
2422 }
2423
2424 decrement('brackets');
2425
2426 const prevValue = prev.value.slice(1);
2427 if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
2428 value = `/${value}`;
2429 }
2430
2431 prev.value += value;
2432 append({ value });
2433
2434 // when literal brackets are explicitly disabled
2435 // assume we should match with a regex character class
2436 if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) {
2437 continue;
2438 }
2439
2440 const escaped = utils$2.escapeRegex(prev.value);
2441 state.output = state.output.slice(0, -prev.value.length);
2442
2443 // when literal brackets are explicitly enabled
2444 // assume we should escape the brackets to match literal characters
2445 if (opts.literalBrackets === true) {
2446 state.output += escaped;
2447 prev.value = escaped;
2448 continue;
2449 }
2450
2451 // when the user specifies nothing, try to match both
2452 prev.value = `(${capture}${escaped}|${prev.value})`;
2453 state.output += prev.value;
2454 continue;
2455 }
2456
2457 /**
2458 * Braces
2459 */
2460
2461 if (value === '{' && opts.nobrace !== true) {
2462 increment('braces');
2463
2464 const open = {
2465 type: 'brace',
2466 value,
2467 output: '(',
2468 outputIndex: state.output.length,
2469 tokensIndex: state.tokens.length
2470 };
2471
2472 braces.push(open);
2473 push(open);
2474 continue;
2475 }
2476
2477 if (value === '}') {
2478 const brace = braces[braces.length - 1];
2479
2480 if (opts.nobrace === true || !brace) {
2481 push({ type: 'text', value, output: value });
2482 continue;
2483 }
2484
2485 let output = ')';
2486
2487 if (brace.dots === true) {
2488 const arr = tokens.slice();
2489 const range = [];
2490
2491 for (let i = arr.length - 1; i >= 0; i--) {
2492 tokens.pop();
2493 if (arr[i].type === 'brace') {
2494 break;
2495 }
2496 if (arr[i].type !== 'dots') {
2497 range.unshift(arr[i].value);
2498 }
2499 }
2500
2501 output = expandRange(range, opts);
2502 state.backtrack = true;
2503 }
2504
2505 if (brace.comma !== true && brace.dots !== true) {
2506 const out = state.output.slice(0, brace.outputIndex);
2507 const toks = state.tokens.slice(brace.tokensIndex);
2508 brace.value = brace.output = '\\{';
2509 value = output = '\\}';
2510 state.output = out;
2511 for (const t of toks) {
2512 state.output += (t.output || t.value);
2513 }
2514 }
2515
2516 push({ type: 'brace', value, output });
2517 decrement('braces');
2518 braces.pop();
2519 continue;
2520 }
2521
2522 /**
2523 * Pipes
2524 */
2525
2526 if (value === '|') {
2527 if (extglobs.length > 0) {
2528 extglobs[extglobs.length - 1].conditions++;
2529 }
2530 push({ type: 'text', value });
2531 continue;
2532 }
2533
2534 /**
2535 * Commas
2536 */
2537
2538 if (value === ',') {
2539 let output = value;
2540
2541 const brace = braces[braces.length - 1];
2542 if (brace && stack[stack.length - 1] === 'braces') {
2543 brace.comma = true;
2544 output = '|';
2545 }
2546
2547 push({ type: 'comma', value, output });
2548 continue;
2549 }
2550
2551 /**
2552 * Slashes
2553 */
2554
2555 if (value === '/') {
2556 // if the beginning of the glob is "./", advance the start
2557 // to the current index, and don't add the "./" characters
2558 // to the state. This greatly simplifies lookbehinds when
2559 // checking for BOS characters like "!" and "." (not "./")
2560 if (prev.type === 'dot' && state.index === state.start + 1) {
2561 state.start = state.index + 1;
2562 state.consumed = '';
2563 state.output = '';
2564 tokens.pop();
2565 prev = bos; // reset "prev" to the first token
2566 continue;
2567 }
2568
2569 push({ type: 'slash', value, output: SLASH_LITERAL });
2570 continue;
2571 }
2572
2573 /**
2574 * Dots
2575 */
2576
2577 if (value === '.') {
2578 if (state.braces > 0 && prev.type === 'dot') {
2579 if (prev.value === '.') prev.output = DOT_LITERAL;
2580 const brace = braces[braces.length - 1];
2581 prev.type = 'dots';
2582 prev.output += value;
2583 prev.value += value;
2584 brace.dots = true;
2585 continue;
2586 }
2587
2588 if ((state.braces + state.parens) === 0 && prev.type !== 'bos' && prev.type !== 'slash') {
2589 push({ type: 'text', value, output: DOT_LITERAL });
2590 continue;
2591 }
2592
2593 push({ type: 'dot', value, output: DOT_LITERAL });
2594 continue;
2595 }
2596
2597 /**
2598 * Question marks
2599 */
2600
2601 if (value === '?') {
2602 const isGroup = prev && prev.value === '(';
2603 if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
2604 extglobOpen('qmark', value);
2605 continue;
2606 }
2607
2608 if (prev && prev.type === 'paren') {
2609 const next = peek();
2610 let output = value;
2611
2612 if ((prev.value === '(' && !/[!=<:]/.test(next)) || (next === '<' && !/<([!=]|\w+>)/.test(remaining()))) {
2613 output = `\\${value}`;
2614 }
2615
2616 push({ type: 'text', value, output });
2617 continue;
2618 }
2619
2620 if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
2621 push({ type: 'qmark', value, output: QMARK_NO_DOT });
2622 continue;
2623 }
2624
2625 push({ type: 'qmark', value, output: QMARK });
2626 continue;
2627 }
2628
2629 /**
2630 * Exclamation
2631 */
2632
2633 if (value === '!') {
2634 if (opts.noextglob !== true && peek() === '(') {
2635 if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
2636 extglobOpen('negate', value);
2637 continue;
2638 }
2639 }
2640
2641 if (opts.nonegate !== true && state.index === 0) {
2642 negate();
2643 continue;
2644 }
2645 }
2646
2647 /**
2648 * Plus
2649 */
2650
2651 if (value === '+') {
2652 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
2653 extglobOpen('plus', value);
2654 continue;
2655 }
2656
2657 if ((prev && prev.value === '(') || opts.regex === false) {
2658 push({ type: 'plus', value, output: PLUS_LITERAL });
2659 continue;
2660 }
2661
2662 if ((prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) || state.parens > 0) {
2663 push({ type: 'plus', value });
2664 continue;
2665 }
2666
2667 push({ type: 'plus', value: PLUS_LITERAL });
2668 continue;
2669 }
2670
2671 /**
2672 * Plain text
2673 */
2674
2675 if (value === '@') {
2676 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
2677 push({ type: 'at', extglob: true, value, output: '' });
2678 continue;
2679 }
2680
2681 push({ type: 'text', value });
2682 continue;
2683 }
2684
2685 /**
2686 * Plain text
2687 */
2688
2689 if (value !== '*') {
2690 if (value === '$' || value === '^') {
2691 value = `\\${value}`;
2692 }
2693
2694 const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
2695 if (match) {
2696 value += match[0];
2697 state.index += match[0].length;
2698 }
2699
2700 push({ type: 'text', value });
2701 continue;
2702 }
2703
2704 /**
2705 * Stars
2706 */
2707
2708 if (prev && (prev.type === 'globstar' || prev.star === true)) {
2709 prev.type = 'star';
2710 prev.star = true;
2711 prev.value += value;
2712 prev.output = star;
2713 state.backtrack = true;
2714 state.globstar = true;
2715 consume(value);
2716 continue;
2717 }
2718
2719 let rest = remaining();
2720 if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
2721 extglobOpen('star', value);
2722 continue;
2723 }
2724
2725 if (prev.type === 'star') {
2726 if (opts.noglobstar === true) {
2727 consume(value);
2728 continue;
2729 }
2730
2731 const prior = prev.prev;
2732 const before = prior.prev;
2733 const isStart = prior.type === 'slash' || prior.type === 'bos';
2734 const afterStar = before && (before.type === 'star' || before.type === 'globstar');
2735
2736 if (opts.bash === true && (!isStart || (rest[0] && rest[0] !== '/'))) {
2737 push({ type: 'star', value, output: '' });
2738 continue;
2739 }
2740
2741 const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
2742 const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
2743 if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
2744 push({ type: 'star', value, output: '' });
2745 continue;
2746 }
2747
2748 // strip consecutive `/**/`
2749 while (rest.slice(0, 3) === '/**') {
2750 const after = input[state.index + 4];
2751 if (after && after !== '/') {
2752 break;
2753 }
2754 rest = rest.slice(3);
2755 consume('/**', 3);
2756 }
2757
2758 if (prior.type === 'bos' && eos()) {
2759 prev.type = 'globstar';
2760 prev.value += value;
2761 prev.output = globstar(opts);
2762 state.output = prev.output;
2763 state.globstar = true;
2764 consume(value);
2765 continue;
2766 }
2767
2768 if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
2769 state.output = state.output.slice(0, -(prior.output + prev.output).length);
2770 prior.output = `(?:${prior.output}`;
2771
2772 prev.type = 'globstar';
2773 prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)');
2774 prev.value += value;
2775 state.globstar = true;
2776 state.output += prior.output + prev.output;
2777 consume(value);
2778 continue;
2779 }
2780
2781 if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') {
2782 const end = rest[1] !== undefined ? '|$' : '';
2783
2784 state.output = state.output.slice(0, -(prior.output + prev.output).length);
2785 prior.output = `(?:${prior.output}`;
2786
2787 prev.type = 'globstar';
2788 prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
2789 prev.value += value;
2790
2791 state.output += prior.output + prev.output;
2792 state.globstar = true;
2793
2794 consume(value + advance());
2795
2796 push({ type: 'slash', value: '/', output: '' });
2797 continue;
2798 }
2799
2800 if (prior.type === 'bos' && rest[0] === '/') {
2801 prev.type = 'globstar';
2802 prev.value += value;
2803 prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
2804 state.output = prev.output;
2805 state.globstar = true;
2806 consume(value + advance());
2807 push({ type: 'slash', value: '/', output: '' });
2808 continue;
2809 }
2810
2811 // remove single star from output
2812 state.output = state.output.slice(0, -prev.output.length);
2813
2814 // reset previous token to globstar
2815 prev.type = 'globstar';
2816 prev.output = globstar(opts);
2817 prev.value += value;
2818
2819 // reset output with globstar
2820 state.output += prev.output;
2821 state.globstar = true;
2822 consume(value);
2823 continue;
2824 }
2825
2826 const token = { type: 'star', value, output: star };
2827
2828 if (opts.bash === true) {
2829 token.output = '.*?';
2830 if (prev.type === 'bos' || prev.type === 'slash') {
2831 token.output = nodot + token.output;
2832 }
2833 push(token);
2834 continue;
2835 }
2836
2837 if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
2838 token.output = value;
2839 push(token);
2840 continue;
2841 }
2842
2843 if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
2844 if (prev.type === 'dot') {
2845 state.output += NO_DOT_SLASH;
2846 prev.output += NO_DOT_SLASH;
2847
2848 } else if (opts.dot === true) {
2849 state.output += NO_DOTS_SLASH;
2850 prev.output += NO_DOTS_SLASH;
2851
2852 } else {
2853 state.output += nodot;
2854 prev.output += nodot;
2855 }
2856
2857 if (peek() !== '*') {
2858 state.output += ONE_CHAR;
2859 prev.output += ONE_CHAR;
2860 }
2861 }
2862
2863 push(token);
2864 }
2865
2866 while (state.brackets > 0) {
2867 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']'));
2868 state.output = utils$2.escapeLast(state.output, '[');
2869 decrement('brackets');
2870 }
2871
2872 while (state.parens > 0) {
2873 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')'));
2874 state.output = utils$2.escapeLast(state.output, '(');
2875 decrement('parens');
2876 }
2877
2878 while (state.braces > 0) {
2879 if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}'));
2880 state.output = utils$2.escapeLast(state.output, '{');
2881 decrement('braces');
2882 }
2883
2884 if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
2885 push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
2886 }
2887
2888 // rebuild the output if we had to backtrack at any point
2889 if (state.backtrack === true) {
2890 state.output = '';
2891
2892 for (const token of state.tokens) {
2893 state.output += token.output != null ? token.output : token.value;
2894
2895 if (token.suffix) {
2896 state.output += token.suffix;
2897 }
2898 }
2899 }
2900
2901 return state;
2902};
2903
2904/**
2905 * Fast paths for creating regular expressions for common glob patterns.
2906 * This can significantly speed up processing and has very little downside
2907 * impact when none of the fast paths match.
2908 */
2909
2910parse$2.fastpaths = (input, options) => {
2911 const opts = { ...options };
2912 const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
2913 const len = input.length;
2914 if (len > max) {
2915 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
2916 }
2917
2918 input = REPLACEMENTS[input] || input;
2919
2920 // create constants based on platform, for windows or posix
2921 const {
2922 DOT_LITERAL,
2923 SLASH_LITERAL,
2924 ONE_CHAR,
2925 DOTS_SLASH,
2926 NO_DOT,
2927 NO_DOTS,
2928 NO_DOTS_SLASH,
2929 STAR,
2930 START_ANCHOR
2931 } = constants$1.globChars(opts.windows);
2932
2933 const nodot = opts.dot ? NO_DOTS : NO_DOT;
2934 const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
2935 const capture = opts.capture ? '' : '?:';
2936 const state = { negated: false, prefix: '' };
2937 let star = opts.bash === true ? '.*?' : STAR;
2938
2939 if (opts.capture) {
2940 star = `(${star})`;
2941 }
2942
2943 const globstar = opts => {
2944 if (opts.noglobstar === true) return star;
2945 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
2946 };
2947
2948 const create = str => {
2949 switch (str) {
2950 case '*':
2951 return `${nodot}${ONE_CHAR}${star}`;
2952
2953 case '.*':
2954 return `${DOT_LITERAL}${ONE_CHAR}${star}`;
2955
2956 case '*.*':
2957 return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
2958
2959 case '*/*':
2960 return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
2961
2962 case '**':
2963 return nodot + globstar(opts);
2964
2965 case '**/*':
2966 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
2967
2968 case '**/*.*':
2969 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
2970
2971 case '**/.*':
2972 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
2973
2974 default: {
2975 const match = /^(.*?)\.(\w+)$/.exec(str);
2976 if (!match) return;
2977
2978 const source = create(match[1]);
2979 if (!source) return;
2980
2981 return source + DOT_LITERAL + match[2];
2982 }
2983 }
2984 };
2985
2986 const output = utils$2.removePrefix(input, state);
2987 let source = create(output);
2988
2989 if (source && opts.strictSlashes !== true) {
2990 source += `${SLASH_LITERAL}?`;
2991 }
2992
2993 return source;
2994};
2995
2996var parse_1$1 = parse$2;
2997
2998const scan = scan_1;
2999const parse$1 = parse_1$1;
3000const utils$1 = utils$4;
3001const constants = constants$2;
3002const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val);
3003
3004/**
3005 * Creates a matcher function from one or more glob patterns. The
3006 * returned function takes a string to match as its first argument,
3007 * and returns true if the string is a match. The returned matcher
3008 * function also takes a boolean as the second argument that, when true,
3009 * returns an object with additional information.
3010 *
3011 * ```js
3012 * const picomatch = require('picomatch');
3013 * // picomatch(glob[, options]);
3014 *
3015 * const isMatch = picomatch('*.!(*a)');
3016 * console.log(isMatch('a.a')); //=> false
3017 * console.log(isMatch('a.b')); //=> true
3018 * ```
3019 * @name picomatch
3020 * @param {String|Array} `globs` One or more glob patterns.
3021 * @param {Object=} `options`
3022 * @return {Function=} Returns a matcher function.
3023 * @api public
3024 */
3025
3026const picomatch$1 = (glob, options, returnState = false) => {
3027 if (Array.isArray(glob)) {
3028 const fns = glob.map(input => picomatch$1(input, options, returnState));
3029 const arrayMatcher = str => {
3030 for (const isMatch of fns) {
3031 const state = isMatch(str);
3032 if (state) return state;
3033 }
3034 return false;
3035 };
3036 return arrayMatcher;
3037 }
3038
3039 const isState = isObject$2(glob) && glob.tokens && glob.input;
3040
3041 if (glob === '' || (typeof glob !== 'string' && !isState)) {
3042 throw new TypeError('Expected pattern to be a non-empty string');
3043 }
3044
3045 const opts = options || {};
3046 const posix = opts.windows;
3047 const regex = isState
3048 ? picomatch$1.compileRe(glob, options)
3049 : picomatch$1.makeRe(glob, options, false, true);
3050
3051 const state = regex.state;
3052 delete regex.state;
3053
3054 let isIgnored = () => false;
3055 if (opts.ignore) {
3056 const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
3057 isIgnored = picomatch$1(opts.ignore, ignoreOpts, returnState);
3058 }
3059
3060 const matcher = (input, returnObject = false) => {
3061 const { isMatch, match, output } = picomatch$1.test(input, regex, options, { glob, posix });
3062 const result = { glob, state, regex, posix, input, output, match, isMatch };
3063
3064 if (typeof opts.onResult === 'function') {
3065 opts.onResult(result);
3066 }
3067
3068 if (isMatch === false) {
3069 result.isMatch = false;
3070 return returnObject ? result : false;
3071 }
3072
3073 if (isIgnored(input)) {
3074 if (typeof opts.onIgnore === 'function') {
3075 opts.onIgnore(result);
3076 }
3077 result.isMatch = false;
3078 return returnObject ? result : false;
3079 }
3080
3081 if (typeof opts.onMatch === 'function') {
3082 opts.onMatch(result);
3083 }
3084 return returnObject ? result : true;
3085 };
3086
3087 if (returnState) {
3088 matcher.state = state;
3089 }
3090
3091 return matcher;
3092};
3093
3094/**
3095 * Test `input` with the given `regex`. This is used by the main
3096 * `picomatch()` function to test the input string.
3097 *
3098 * ```js
3099 * const picomatch = require('picomatch');
3100 * // picomatch.test(input, regex[, options]);
3101 *
3102 * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
3103 * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
3104 * ```
3105 * @param {String} `input` String to test.
3106 * @param {RegExp} `regex`
3107 * @return {Object} Returns an object with matching info.
3108 * @api public
3109 */
3110
3111picomatch$1.test = (input, regex, options, { glob, posix } = {}) => {
3112 if (typeof input !== 'string') {
3113 throw new TypeError('Expected input to be a string');
3114 }
3115
3116 if (input === '') {
3117 return { isMatch: false, output: '' };
3118 }
3119
3120 const opts = options || {};
3121 const format = opts.format || (posix ? utils$1.toPosixSlashes : null);
3122 let match = input === glob;
3123 let output = (match && format) ? format(input) : input;
3124
3125 if (match === false) {
3126 output = format ? format(input) : input;
3127 match = output === glob;
3128 }
3129
3130 if (match === false || opts.capture === true) {
3131 if (opts.matchBase === true || opts.basename === true) {
3132 match = picomatch$1.matchBase(input, regex, options, posix);
3133 } else {
3134 match = regex.exec(output);
3135 }
3136 }
3137
3138 return { isMatch: Boolean(match), match, output };
3139};
3140
3141/**
3142 * Match the basename of a filepath.
3143 *
3144 * ```js
3145 * const picomatch = require('picomatch');
3146 * // picomatch.matchBase(input, glob[, options]);
3147 * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
3148 * ```
3149 * @param {String} `input` String to test.
3150 * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
3151 * @return {Boolean}
3152 * @api public
3153 */
3154
3155picomatch$1.matchBase = (input, glob, options) => {
3156 const regex = glob instanceof RegExp ? glob : picomatch$1.makeRe(glob, options);
3157 return regex.test(utils$1.basename(input));
3158};
3159
3160/**
3161 * Returns true if **any** of the given glob `patterns` match the specified `string`.
3162 *
3163 * ```js
3164 * const picomatch = require('picomatch');
3165 * // picomatch.isMatch(string, patterns[, options]);
3166 *
3167 * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
3168 * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
3169 * ```
3170 * @param {String|Array} str The string to test.
3171 * @param {String|Array} patterns One or more glob patterns to use for matching.
3172 * @param {Object} [options] See available [options](#options).
3173 * @return {Boolean} Returns true if any patterns match `str`
3174 * @api public
3175 */
3176
3177picomatch$1.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
3178
3179/**
3180 * Parse a glob pattern to create the source string for a regular
3181 * expression.
3182 *
3183 * ```js
3184 * const picomatch = require('picomatch');
3185 * const result = picomatch.parse(pattern[, options]);
3186 * ```
3187 * @param {String} `pattern`
3188 * @param {Object} `options`
3189 * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
3190 * @api public
3191 */
3192
3193picomatch$1.parse = (pattern, options) => {
3194 if (Array.isArray(pattern)) return pattern.map(p => picomatch$1.parse(p, options));
3195 return parse$1(pattern, { ...options, fastpaths: false });
3196};
3197
3198/**
3199 * Scan a glob pattern to separate the pattern into segments.
3200 *
3201 * ```js
3202 * const picomatch = require('picomatch');
3203 * // picomatch.scan(input[, options]);
3204 *
3205 * const result = picomatch.scan('!./foo/*.js');
3206 * console.log(result);
3207 * { prefix: '!./',
3208 * input: '!./foo/*.js',
3209 * start: 3,
3210 * base: 'foo',
3211 * glob: '*.js',
3212 * isBrace: false,
3213 * isBracket: false,
3214 * isGlob: true,
3215 * isExtglob: false,
3216 * isGlobstar: false,
3217 * negated: true }
3218 * ```
3219 * @param {String} `input` Glob pattern to scan.
3220 * @param {Object} `options`
3221 * @return {Object} Returns an object with
3222 * @api public
3223 */
3224
3225picomatch$1.scan = (input, options) => scan(input, options);
3226
3227/**
3228 * Compile a regular expression from the `state` object returned by the
3229 * [parse()](#parse) method.
3230 *
3231 * @param {Object} `state`
3232 * @param {Object} `options`
3233 * @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
3234 * @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
3235 * @return {RegExp}
3236 * @api public
3237 */
3238
3239picomatch$1.compileRe = (state, options, returnOutput = false, returnState = false) => {
3240 if (returnOutput === true) {
3241 return state.output;
3242 }
3243
3244 const opts = options || {};
3245 const prepend = opts.contains ? '' : '^';
3246 const append = opts.contains ? '' : '$';
3247
3248 let source = `${prepend}(?:${state.output})${append}`;
3249 if (state && state.negated === true) {
3250 source = `^(?!${source}).*$`;
3251 }
3252
3253 const regex = picomatch$1.toRegex(source, options);
3254 if (returnState === true) {
3255 regex.state = state;
3256 }
3257
3258 return regex;
3259};
3260
3261/**
3262 * Create a regular expression from a parsed glob pattern.
3263 *
3264 * ```js
3265 * const picomatch = require('picomatch');
3266 * const state = picomatch.parse('*.js');
3267 * // picomatch.compileRe(state[, options]);
3268 *
3269 * console.log(picomatch.compileRe(state));
3270 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
3271 * ```
3272 * @param {String} `state` The object returned from the `.parse` method.
3273 * @param {Object} `options`
3274 * @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
3275 * @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
3276 * @return {RegExp} Returns a regex created from the given pattern.
3277 * @api public
3278 */
3279
3280picomatch$1.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
3281 if (!input || typeof input !== 'string') {
3282 throw new TypeError('Expected a non-empty string');
3283 }
3284
3285 let parsed = { negated: false, fastpaths: true };
3286
3287 if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
3288 parsed.output = parse$1.fastpaths(input, options);
3289 }
3290
3291 if (!parsed.output) {
3292 parsed = parse$1(input, options);
3293 }
3294
3295 return picomatch$1.compileRe(parsed, options, returnOutput, returnState);
3296};
3297
3298/**
3299 * Create a regular expression from the given regex source string.
3300 *
3301 * ```js
3302 * const picomatch = require('picomatch');
3303 * // picomatch.toRegex(source[, options]);
3304 *
3305 * const { output } = picomatch.parse('*.js');
3306 * console.log(picomatch.toRegex(output));
3307 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
3308 * ```
3309 * @param {String} `source` Regular expression source string.
3310 * @param {Object} `options`
3311 * @return {RegExp}
3312 * @api public
3313 */
3314
3315picomatch$1.toRegex = (source, options) => {
3316 try {
3317 const opts = options || {};
3318 return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
3319 } catch (err) {
3320 if (options && options.debug === true) throw err;
3321 return /$^/;
3322 }
3323};
3324
3325/**
3326 * Picomatch constants.
3327 * @return {Object}
3328 */
3329
3330picomatch$1.constants = constants;
3331
3332/**
3333 * Expose "picomatch"
3334 */
3335
3336var picomatch_1$1 = picomatch$1;
3337
3338const pico = picomatch_1$1;
3339const utils = utils$4;
3340
3341function picomatch(glob, options, returnState = false) {
3342 // default to os.platform()
3343 if (options && (options.windows === null || options.windows === undefined)) {
3344 // don't mutate the original options object
3345 options = { ...options, windows: utils.isWindows() };
3346 }
3347
3348 return pico(glob, options, returnState);
3349}
3350
3351Object.assign(picomatch, pico);
3352var picomatch_1 = picomatch;
3353
3354var pm = /*@__PURE__*/getDefaultExportFromCjs(picomatch_1);
3355
3356// Helper since Typescript can't detect readonly arrays with Array.isArray
3357function isArray(arg) {
3358 return Array.isArray(arg);
3359}
3360function ensureArray(thing) {
3361 if (isArray(thing))
3362 return thing;
3363 if (thing == null)
3364 return [];
3365 return [thing];
3366}
3367
3368const normalizePathRegExp = new RegExp(`\\${require$$1$1.win32.sep}`, 'g');
3369const normalizePath$1 = function normalizePath(filename) {
3370 return filename.replace(normalizePathRegExp, require$$1$1.posix.sep);
3371};
3372
3373function getMatcherString(id, resolutionBase) {
3374 if (resolutionBase === false || require$$1$1.isAbsolute(id) || id.startsWith('**')) {
3375 return normalizePath$1(id);
3376 }
3377 // resolve('') is valid and will default to process.cwd()
3378 const basePath = normalizePath$1(require$$1$1.resolve(resolutionBase || ''))
3379 // escape all possible (posix + win) path characters that might interfere with regex
3380 .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
3381 // Note that we use posix.join because:
3382 // 1. the basePath has been normalized to use /
3383 // 2. the incoming glob (id) matcher, also uses /
3384 // otherwise Node will force backslash (\) on windows
3385 return require$$1$1.posix.join(basePath, normalizePath$1(id));
3386}
3387const createFilter$1 = function createFilter(include, exclude, options) {
3388 const resolutionBase = options && options.resolve;
3389 const getMatcher = (id) => id instanceof RegExp
3390 ? id
3391 : {
3392 test: (what) => {
3393 // this refactor is a tad overly verbose but makes for easy debugging
3394 const pattern = getMatcherString(id, resolutionBase);
3395 const fn = pm(pattern, { dot: true });
3396 const result = fn(what);
3397 return result;
3398 }
3399 };
3400 const includeMatchers = ensureArray(include).map(getMatcher);
3401 const excludeMatchers = ensureArray(exclude).map(getMatcher);
3402 if (!includeMatchers.length && !excludeMatchers.length)
3403 return (id) => typeof id === 'string' && !id.includes('\0');
3404 return function result(id) {
3405 if (typeof id !== 'string')
3406 return false;
3407 if (id.includes('\0'))
3408 return false;
3409 const pathId = normalizePath$1(id);
3410 for (let i = 0; i < excludeMatchers.length; ++i) {
3411 const matcher = excludeMatchers[i];
3412 if (matcher instanceof RegExp) {
3413 matcher.lastIndex = 0;
3414 }
3415 if (matcher.test(pathId))
3416 return false;
3417 }
3418 for (let i = 0; i < includeMatchers.length; ++i) {
3419 const matcher = includeMatchers[i];
3420 if (matcher instanceof RegExp) {
3421 matcher.lastIndex = 0;
3422 }
3423 if (matcher.test(pathId))
3424 return true;
3425 }
3426 return !includeMatchers.length;
3427 };
3428};
3429
3430const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
3431const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
3432const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
3433forbiddenIdentifiers.add('');
3434
3435const isWindows = typeof process !== "undefined" && process.platform === "win32";
3436const windowsSlashRE = /\\/g;
3437function slash(p) {
3438 return p.replace(windowsSlashRE, "/");
3439}
3440const postfixRE = /[?#].*$/;
3441function cleanUrl(url) {
3442 return url.replace(postfixRE, "");
3443}
3444function withTrailingSlash(path) {
3445 if (path[path.length - 1] !== "/") {
3446 return `${path}/`;
3447 }
3448 return path;
3449}
3450
3451let pnp;
3452if (process.versions.pnp) {
3453 try {
3454 pnp = node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)))("pnpapi");
3455 } catch {
3456 }
3457}
3458function resolvePackageData(pkgName, basedir, preserveSymlinks = false, packageCache) {
3459 if (pnp) {
3460 try {
3461 const pkg = pnp.resolveToUnqualified(pkgName, basedir, {
3462 considerBuiltins: false
3463 });
3464 if (!pkg) return null;
3465 const pkgData = loadPackageData(path$1.join(pkg, "package.json"));
3466 return pkgData;
3467 } catch {
3468 return null;
3469 }
3470 }
3471 while (basedir) {
3472 const pkg = path$1.join(basedir, "node_modules", pkgName, "package.json");
3473 try {
3474 if (fs$1.existsSync(pkg)) {
3475 const pkgPath = preserveSymlinks ? pkg : safeRealpathSync(pkg);
3476 const pkgData = loadPackageData(pkgPath);
3477 return pkgData;
3478 }
3479 } catch {
3480 }
3481 const nextBasedir = path$1.dirname(basedir);
3482 if (nextBasedir === basedir) break;
3483 basedir = nextBasedir;
3484 }
3485 return null;
3486}
3487function loadPackageData(pkgPath) {
3488 const data = JSON.parse(stripBomTag(fs$1.readFileSync(pkgPath, "utf-8")));
3489 const pkgDir = normalizePath(path$1.dirname(pkgPath));
3490 const { sideEffects } = data;
3491 let hasSideEffects;
3492 if (typeof sideEffects === "boolean") {
3493 hasSideEffects = () => sideEffects;
3494 } else if (Array.isArray(sideEffects)) {
3495 if (sideEffects.length <= 0) {
3496 hasSideEffects = () => false;
3497 } else {
3498 const finalPackageSideEffects = sideEffects.map((sideEffect) => {
3499 if (sideEffect.includes("/")) {
3500 return sideEffect;
3501 }
3502 return `**/${sideEffect}`;
3503 });
3504 hasSideEffects = createFilter(finalPackageSideEffects, null, {
3505 resolve: pkgDir
3506 });
3507 }
3508 } else {
3509 hasSideEffects = () => null;
3510 }
3511 const resolvedCache = {};
3512 const pkg = {
3513 dir: pkgDir,
3514 data,
3515 hasSideEffects,
3516 setResolvedCache(key, entry, options) {
3517 resolvedCache[getResolveCacheKey(key, options)] = entry;
3518 },
3519 getResolvedCache(key, options) {
3520 return resolvedCache[getResolveCacheKey(key, options)];
3521 }
3522 };
3523 return pkg;
3524}
3525function getResolveCacheKey(key, options) {
3526 return [
3527 key,
3528 options.isRequire ? "1" : "0",
3529 options.conditions.join("_"),
3530 options.extensions.join("_"),
3531 options.mainFields.join("_")
3532 ].join("|");
3533}
3534
3535const createFilter = createFilter$1;
3536node_module.builtinModules.filter((id) => !id.includes(":"));
3537function isInNodeModules(id) {
3538 return id.includes("node_modules");
3539}
3540node_module.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href)));
3541const _dirname = path$1.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('node-cjs/publicUtils.cjs', document.baseURI).href))));
3542const rollupVersion = resolvePackageData("rollup", _dirname, true)?.data.version ?? "";
3543const filter = process.env.VITE_DEBUG_FILTER;
3544const DEBUG = process.env.DEBUG;
3545function createDebugger(namespace, options = {}) {
3546 const log = debug$2(namespace);
3547 const { onlyWhenFocused, depth } = options;
3548 if (depth && log.inspectOpts && log.inspectOpts.depth == null) {
3549 log.inspectOpts.depth = options.depth;
3550 }
3551 let enabled = log.enabled;
3552 if (enabled && onlyWhenFocused) {
3553 const ns = typeof onlyWhenFocused === "string" ? onlyWhenFocused : namespace;
3554 enabled = !!DEBUG?.includes(ns);
3555 }
3556 if (enabled) {
3557 return (...args) => {
3558 if (!filter || args.some((a) => a?.includes?.(filter))) {
3559 log(...args);
3560 }
3561 };
3562 }
3563}
3564function testCaseInsensitiveFS() {
3565 if (!CLIENT_ENTRY.endsWith("client.mjs")) {
3566 throw new Error(
3567 `cannot test case insensitive FS, CLIENT_ENTRY const doesn't contain client.mjs`
3568 );
3569 }
3570 if (!fs$1.existsSync(CLIENT_ENTRY)) {
3571 throw new Error(
3572 "cannot test case insensitive FS, CLIENT_ENTRY does not point to an existing file: " + CLIENT_ENTRY
3573 );
3574 }
3575 return fs$1.existsSync(CLIENT_ENTRY.replace("client.mjs", "cLiEnT.mjs"));
3576}
3577const isCaseInsensitiveFS = testCaseInsensitiveFS();
3578const VOLUME_RE = /^[A-Z]:/i;
3579function normalizePath(id) {
3580 return path$1.posix.normalize(isWindows ? slash(id) : id);
3581}
3582function fsPathFromId(id) {
3583 const fsPath = normalizePath(
3584 id.startsWith(FS_PREFIX) ? id.slice(FS_PREFIX.length) : id
3585 );
3586 return fsPath[0] === "/" || VOLUME_RE.test(fsPath) ? fsPath : `/${fsPath}`;
3587}
3588function fsPathFromUrl(url) {
3589 return fsPathFromId(cleanUrl(url));
3590}
3591function isParentDirectory(dir, file) {
3592 dir = withTrailingSlash(dir);
3593 return file.startsWith(dir) || isCaseInsensitiveFS && file.toLowerCase().startsWith(dir.toLowerCase());
3594}
3595function isSameFileUri(file1, file2) {
3596 return file1 === file2 || isCaseInsensitiveFS && file1.toLowerCase() === file2.toLowerCase();
3597}
3598const trailingSeparatorRE = /[?&]$/;
3599const timestampRE = /\bt=\d{13}&?\b/;
3600function removeTimestampQuery(url) {
3601 return url.replace(timestampRE, "").replace(trailingSeparatorRE, "");
3602}
3603function isObject$1(value) {
3604 return Object.prototype.toString.call(value) === "[object Object]";
3605}
3606function tryStatSync(file) {
3607 try {
3608 return fs$1.statSync(file, { throwIfNoEntry: false });
3609 } catch {
3610 }
3611}
3612function isFileReadable(filename) {
3613 if (!tryStatSync(filename)) {
3614 return false;
3615 }
3616 try {
3617 fs$1.accessSync(filename, fs$1.constants.R_OK);
3618 return true;
3619 } catch {
3620 return false;
3621 }
3622}
3623let safeRealpathSync = isWindows ? windowsSafeRealPathSync : fs$1.realpathSync.native;
3624const windowsNetworkMap = /* @__PURE__ */ new Map();
3625function windowsMappedRealpathSync(path2) {
3626 const realPath = fs$1.realpathSync.native(path2);
3627 if (realPath.startsWith("\\\\")) {
3628 for (const [network, volume] of windowsNetworkMap) {
3629 if (realPath.startsWith(network)) return realPath.replace(network, volume);
3630 }
3631 }
3632 return realPath;
3633}
3634const parseNetUseRE = /^\w* +(\w:) +([^ ]+)\s/;
3635let firstSafeRealPathSyncRun = false;
3636function windowsSafeRealPathSync(path2) {
3637 if (!firstSafeRealPathSyncRun) {
3638 optimizeSafeRealPathSync();
3639 firstSafeRealPathSyncRun = true;
3640 }
3641 return fs$1.realpathSync(path2);
3642}
3643function optimizeSafeRealPathSync() {
3644 const nodeVersion = process.versions.node.split(".").map(Number);
3645 if (nodeVersion[0] < 18 || nodeVersion[0] === 18 && nodeVersion[1] < 10) {
3646 safeRealpathSync = fs$1.realpathSync;
3647 return;
3648 }
3649 try {
3650 fs$1.realpathSync.native(path$1.resolve("./"));
3651 } catch (error) {
3652 if (error.message.includes("EISDIR: illegal operation on a directory")) {
3653 safeRealpathSync = fs$1.realpathSync;
3654 return;
3655 }
3656 }
3657 node_child_process.exec("net use", (error, stdout) => {
3658 if (error) return;
3659 const lines = stdout.split("\n");
3660 for (const line of lines) {
3661 const m = parseNetUseRE.exec(line);
3662 if (m) windowsNetworkMap.set(m[2], m[1]);
3663 }
3664 if (windowsNetworkMap.size === 0) {
3665 safeRealpathSync = fs$1.realpathSync.native;
3666 } else {
3667 safeRealpathSync = windowsMappedRealpathSync;
3668 }
3669 });
3670}
3671function arraify(target) {
3672 return Array.isArray(target) ? target : [target];
3673}
3674function backwardCompatibleWorkerPlugins(plugins) {
3675 if (Array.isArray(plugins)) {
3676 return plugins;
3677 }
3678 if (typeof plugins === "function") {
3679 return plugins();
3680 }
3681 return [];
3682}
3683function mergeConfigRecursively(defaults, overrides, rootPath) {
3684 const merged = { ...defaults };
3685 for (const key in overrides) {
3686 const value = overrides[key];
3687 if (value == null) {
3688 continue;
3689 }
3690 const existing = merged[key];
3691 if (existing == null) {
3692 merged[key] = value;
3693 continue;
3694 }
3695 if (key === "alias" && (rootPath === "resolve" || rootPath === "")) {
3696 merged[key] = mergeAlias(existing, value);
3697 continue;
3698 } else if (key === "assetsInclude" && rootPath === "") {
3699 merged[key] = [].concat(existing, value);
3700 continue;
3701 } else if (key === "noExternal" && (rootPath === "ssr" || rootPath === "resolve") && (existing === true || value === true)) {
3702 merged[key] = true;
3703 continue;
3704 } else if (key === "plugins" && rootPath === "worker") {
3705 merged[key] = () => [
3706 ...backwardCompatibleWorkerPlugins(existing),
3707 ...backwardCompatibleWorkerPlugins(value)
3708 ];
3709 continue;
3710 } else if (key === "server" && rootPath === "server.hmr") {
3711 merged[key] = value;
3712 continue;
3713 }
3714 if (Array.isArray(existing) || Array.isArray(value)) {
3715 merged[key] = [...arraify(existing), ...arraify(value)];
3716 continue;
3717 }
3718 if (isObject$1(existing) && isObject$1(value)) {
3719 merged[key] = mergeConfigRecursively(
3720 existing,
3721 value,
3722 rootPath ? `${rootPath}.${key}` : key
3723 );
3724 continue;
3725 }
3726 merged[key] = value;
3727 }
3728 return merged;
3729}
3730function mergeConfig(defaults, overrides, isRoot = true) {
3731 if (typeof defaults === "function" || typeof overrides === "function") {
3732 throw new Error(`Cannot merge config in form of callback`);
3733 }
3734 return mergeConfigRecursively(defaults, overrides, isRoot ? "" : ".");
3735}
3736function mergeAlias(a, b) {
3737 if (!a) return b;
3738 if (!b) return a;
3739 if (isObject$1(a) && isObject$1(b)) {
3740 return { ...a, ...b };
3741 }
3742 return [...normalizeAlias(b), ...normalizeAlias(a)];
3743}
3744function normalizeAlias(o = []) {
3745 return Array.isArray(o) ? o.map(normalizeSingleAlias) : Object.keys(o).map(
3746 (find) => normalizeSingleAlias({
3747 find,
3748 replacement: o[find]
3749 })
3750 );
3751}
3752function normalizeSingleAlias({
3753 find,
3754 replacement,
3755 customResolver
3756}) {
3757 if (typeof find === "string" && find[find.length - 1] === "/" && replacement[replacement.length - 1] === "/") {
3758 find = find.slice(0, find.length - 1);
3759 replacement = replacement.slice(0, replacement.length - 1);
3760 }
3761 const alias = {
3762 find,
3763 replacement
3764 };
3765 if (customResolver) {
3766 alias.customResolver = customResolver;
3767 }
3768 return alias;
3769}
3770function stripBomTag(content) {
3771 if (content.charCodeAt(0) === 65279) {
3772 return content.slice(1);
3773 }
3774 return content;
3775}
3776
3777const CSS_LANGS_RE = (
3778 // eslint-disable-next-line regexp/no-unused-capturing-group
3779 /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/
3780);
3781const isCSSRequest = (request) => CSS_LANGS_RE.test(request);
3782class SplitVendorChunkCache {
3783 cache;
3784 constructor() {
3785 this.cache = /* @__PURE__ */ new Map();
3786 }
3787 reset() {
3788 this.cache = /* @__PURE__ */ new Map();
3789 }
3790}
3791function splitVendorChunk(options = {}) {
3792 const cache = options.cache ?? new SplitVendorChunkCache();
3793 return (id, { getModuleInfo }) => {
3794 if (isInNodeModules(id) && !isCSSRequest(id) && staticImportedByEntry(id, getModuleInfo, cache.cache)) {
3795 return "vendor";
3796 }
3797 };
3798}
3799function staticImportedByEntry(id, getModuleInfo, cache, importStack = []) {
3800 if (cache.has(id)) {
3801 return cache.get(id);
3802 }
3803 if (importStack.includes(id)) {
3804 cache.set(id, false);
3805 return false;
3806 }
3807 const mod = getModuleInfo(id);
3808 if (!mod) {
3809 cache.set(id, false);
3810 return false;
3811 }
3812 if (mod.isEntry) {
3813 cache.set(id, true);
3814 return true;
3815 }
3816 const someImporterIs = mod.importers.some(
3817 (importer) => staticImportedByEntry(
3818 importer,
3819 getModuleInfo,
3820 cache,
3821 importStack.concat(id)
3822 )
3823 );
3824 cache.set(id, someImporterIs);
3825 return someImporterIs;
3826}
3827function splitVendorChunkPlugin() {
3828 const caches = [];
3829 function createSplitVendorChunk(output, config) {
3830 const cache = new SplitVendorChunkCache();
3831 caches.push(cache);
3832 const build = config.build ?? {};
3833 const format = output.format;
3834 if (!build.ssr && !build.lib && format !== "umd" && format !== "iife") {
3835 return splitVendorChunk({ cache });
3836 }
3837 }
3838 return {
3839 name: "vite:split-vendor-chunk",
3840 config(config) {
3841 let outputs = config.build?.rollupOptions?.output;
3842 if (outputs) {
3843 outputs = arraify(outputs);
3844 for (const output of outputs) {
3845 const viteManualChunks = createSplitVendorChunk(output, config);
3846 if (viteManualChunks) {
3847 if (output.manualChunks) {
3848 if (typeof output.manualChunks === "function") {
3849 const userManualChunks = output.manualChunks;
3850 output.manualChunks = (id, api) => {
3851 return userManualChunks(id, api) ?? viteManualChunks(id, api);
3852 };
3853 } else {
3854 console.warn(
3855 "(!) the `splitVendorChunk` plugin doesn't have any effect when using the object form of `build.rollupOptions.output.manualChunks`. Consider using the function form instead."
3856 );
3857 }
3858 } else {
3859 output.manualChunks = viteManualChunks;
3860 }
3861 }
3862 }
3863 } else {
3864 return {
3865 build: {
3866 rollupOptions: {
3867 output: {
3868 manualChunks: createSplitVendorChunk({}, config)
3869 }
3870 }
3871 }
3872 };
3873 }
3874 },
3875 buildStart() {
3876 caches.forEach((cache) => cache.reset());
3877 }
3878 };
3879}
3880
3881function perEnvironmentPlugin(name, applyToEnvironment) {
3882 return {
3883 name,
3884 applyToEnvironment
3885 };
3886}
3887
3888function perEnvironmentState(initial) {
3889 const stateMap = /* @__PURE__ */ new WeakMap();
3890 return function(context) {
3891 const { environment } = context;
3892 let state = stateMap.get(environment);
3893 if (!state) {
3894 state = initial(environment);
3895 stateMap.set(environment, state);
3896 }
3897 return state;
3898 };
3899}
3900
3901var convertSourceMap$1 = {};
3902
3903(function (exports) {
3904
3905 Object.defineProperty(exports, 'commentRegex', {
3906 get: function getCommentRegex () {
3907 // Groups: 1: media type, 2: MIME type, 3: charset, 4: encoding, 5: data.
3908 return /^\s*?\/[\/\*][@#]\s+?sourceMappingURL=data:(((?:application|text)\/json)(?:;charset=([^;,]+?)?)?)?(?:;(base64))?,(.*?)$/mg;
3909 }
3910 });
3911
3912
3913 Object.defineProperty(exports, 'mapFileCommentRegex', {
3914 get: function getMapFileCommentRegex () {
3915 // Matches sourceMappingURL in either // or /* comment styles.
3916 return /(?:\/\/[@#][ \t]+?sourceMappingURL=([^\s'"`]+?)[ \t]*?$)|(?:\/\*[@#][ \t]+sourceMappingURL=([^*]+?)[ \t]*?(?:\*\/){1}[ \t]*?$)/mg;
3917 }
3918 });
3919
3920 var decodeBase64;
3921 if (typeof Buffer !== 'undefined') {
3922 if (typeof Buffer.from === 'function') {
3923 decodeBase64 = decodeBase64WithBufferFrom;
3924 } else {
3925 decodeBase64 = decodeBase64WithNewBuffer;
3926 }
3927 } else {
3928 decodeBase64 = decodeBase64WithAtob;
3929 }
3930
3931 function decodeBase64WithBufferFrom(base64) {
3932 return Buffer.from(base64, 'base64').toString();
3933 }
3934
3935 function decodeBase64WithNewBuffer(base64) {
3936 if (typeof value === 'number') {
3937 throw new TypeError('The value to decode must not be of type number.');
3938 }
3939 return new Buffer(base64, 'base64').toString();
3940 }
3941
3942 function decodeBase64WithAtob(base64) {
3943 return decodeURIComponent(escape(atob(base64)));
3944 }
3945
3946 function stripComment(sm) {
3947 return sm.split(',').pop();
3948 }
3949
3950 function readFromFileMap(sm, read) {
3951 var r = exports.mapFileCommentRegex.exec(sm);
3952 // for some odd reason //# .. captures in 1 and /* .. */ in 2
3953 var filename = r[1] || r[2];
3954
3955 try {
3956 var sm = read(filename);
3957 if (sm != null && typeof sm.catch === 'function') {
3958 return sm.catch(throwError);
3959 } else {
3960 return sm;
3961 }
3962 } catch (e) {
3963 throwError(e);
3964 }
3965
3966 function throwError(e) {
3967 throw new Error('An error occurred while trying to read the map file at ' + filename + '\n' + e.stack);
3968 }
3969 }
3970
3971 function Converter (sm, opts) {
3972 opts = opts || {};
3973
3974 if (opts.hasComment) {
3975 sm = stripComment(sm);
3976 }
3977
3978 if (opts.encoding === 'base64') {
3979 sm = decodeBase64(sm);
3980 } else if (opts.encoding === 'uri') {
3981 sm = decodeURIComponent(sm);
3982 }
3983
3984 if (opts.isJSON || opts.encoding) {
3985 sm = JSON.parse(sm);
3986 }
3987
3988 this.sourcemap = sm;
3989 }
3990
3991 Converter.prototype.toJSON = function (space) {
3992 return JSON.stringify(this.sourcemap, null, space);
3993 };
3994
3995 if (typeof Buffer !== 'undefined') {
3996 if (typeof Buffer.from === 'function') {
3997 Converter.prototype.toBase64 = encodeBase64WithBufferFrom;
3998 } else {
3999 Converter.prototype.toBase64 = encodeBase64WithNewBuffer;
4000 }
4001 } else {
4002 Converter.prototype.toBase64 = encodeBase64WithBtoa;
4003 }
4004
4005 function encodeBase64WithBufferFrom() {
4006 var json = this.toJSON();
4007 return Buffer.from(json, 'utf8').toString('base64');
4008 }
4009
4010 function encodeBase64WithNewBuffer() {
4011 var json = this.toJSON();
4012 if (typeof json === 'number') {
4013 throw new TypeError('The json to encode must not be of type number.');
4014 }
4015 return new Buffer(json, 'utf8').toString('base64');
4016 }
4017
4018 function encodeBase64WithBtoa() {
4019 var json = this.toJSON();
4020 return btoa(unescape(encodeURIComponent(json)));
4021 }
4022
4023 Converter.prototype.toURI = function () {
4024 var json = this.toJSON();
4025 return encodeURIComponent(json);
4026 };
4027
4028 Converter.prototype.toComment = function (options) {
4029 var encoding, content, data;
4030 if (options != null && options.encoding === 'uri') {
4031 encoding = '';
4032 content = this.toURI();
4033 } else {
4034 encoding = ';base64';
4035 content = this.toBase64();
4036 }
4037 data = 'sourceMappingURL=data:application/json;charset=utf-8' + encoding + ',' + content;
4038 return options != null && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
4039 };
4040
4041 // returns copy instead of original
4042 Converter.prototype.toObject = function () {
4043 return JSON.parse(this.toJSON());
4044 };
4045
4046 Converter.prototype.addProperty = function (key, value) {
4047 if (this.sourcemap.hasOwnProperty(key)) throw new Error('property "' + key + '" already exists on the sourcemap, use set property instead');
4048 return this.setProperty(key, value);
4049 };
4050
4051 Converter.prototype.setProperty = function (key, value) {
4052 this.sourcemap[key] = value;
4053 return this;
4054 };
4055
4056 Converter.prototype.getProperty = function (key) {
4057 return this.sourcemap[key];
4058 };
4059
4060 exports.fromObject = function (obj) {
4061 return new Converter(obj);
4062 };
4063
4064 exports.fromJSON = function (json) {
4065 return new Converter(json, { isJSON: true });
4066 };
4067
4068 exports.fromURI = function (uri) {
4069 return new Converter(uri, { encoding: 'uri' });
4070 };
4071
4072 exports.fromBase64 = function (base64) {
4073 return new Converter(base64, { encoding: 'base64' });
4074 };
4075
4076 exports.fromComment = function (comment) {
4077 var m, encoding;
4078 comment = comment
4079 .replace(/^\/\*/g, '//')
4080 .replace(/\*\/$/g, '');
4081 m = exports.commentRegex.exec(comment);
4082 encoding = m && m[4] || 'uri';
4083 return new Converter(comment, { encoding: encoding, hasComment: true });
4084 };
4085
4086 function makeConverter(sm) {
4087 return new Converter(sm, { isJSON: true });
4088 }
4089
4090 exports.fromMapFileComment = function (comment, read) {
4091 if (typeof read === 'string') {
4092 throw new Error(
4093 'String directory paths are no longer supported with `fromMapFileComment`\n' +
4094 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
4095 )
4096 }
4097
4098 var sm = readFromFileMap(comment, read);
4099 if (sm != null && typeof sm.then === 'function') {
4100 return sm.then(makeConverter);
4101 } else {
4102 return makeConverter(sm);
4103 }
4104 };
4105
4106 // Finds last sourcemap comment in file or returns null if none was found
4107 exports.fromSource = function (content) {
4108 var m = content.match(exports.commentRegex);
4109 return m ? exports.fromComment(m.pop()) : null;
4110 };
4111
4112 // Finds last sourcemap comment in file or returns null if none was found
4113 exports.fromMapFileSource = function (content, read) {
4114 if (typeof read === 'string') {
4115 throw new Error(
4116 'String directory paths are no longer supported with `fromMapFileSource`\n' +
4117 'Please review the Upgrading documentation at https://github.com/thlorenz/convert-source-map#upgrading'
4118 )
4119 }
4120 var m = content.match(exports.mapFileCommentRegex);
4121 return m ? exports.fromMapFileComment(m.pop(), read) : null;
4122 };
4123
4124 exports.removeComments = function (src) {
4125 return src.replace(exports.commentRegex, '');
4126 };
4127
4128 exports.removeMapFileComments = function (src) {
4129 return src.replace(exports.mapFileCommentRegex, '');
4130 };
4131
4132 exports.generateMapFileComment = function (file, options) {
4133 var data = 'sourceMappingURL=' + file;
4134 return options && options.multiline ? '/*# ' + data + ' */' : '//# ' + data;
4135 };
4136} (convertSourceMap$1));
4137
4138var convertSourceMap = /*@__PURE__*/getDefaultExportFromCjs(convertSourceMap$1);
4139
4140/*!
4141 * etag
4142 * Copyright(c) 2014-2016 Douglas Christopher Wilson
4143 * MIT Licensed
4144 */
4145
4146/**
4147 * Module exports.
4148 * @public
4149 */
4150
4151var etag_1 = etag;
4152
4153/**
4154 * Module dependencies.
4155 * @private
4156 */
4157
4158var crypto$1 = require$$0$1;
4159var Stats = require$$1$2.Stats;
4160
4161/**
4162 * Module variables.
4163 * @private
4164 */
4165
4166var toString$1 = Object.prototype.toString;
4167
4168/**
4169 * Generate an entity tag.
4170 *
4171 * @param {Buffer|string} entity
4172 * @return {string}
4173 * @private
4174 */
4175
4176function entitytag (entity) {
4177 if (entity.length === 0) {
4178 // fast-path empty
4179 return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
4180 }
4181
4182 // compute hash of entity
4183 var hash = crypto$1
4184 .createHash('sha1')
4185 .update(entity, 'utf8')
4186 .digest('base64')
4187 .substring(0, 27);
4188
4189 // compute length of entity
4190 var len = typeof entity === 'string'
4191 ? Buffer.byteLength(entity, 'utf8')
4192 : entity.length;
4193
4194 return '"' + len.toString(16) + '-' + hash + '"'
4195}
4196
4197/**
4198 * Create a simple ETag.
4199 *
4200 * @param {string|Buffer|Stats} entity
4201 * @param {object} [options]
4202 * @param {boolean} [options.weak]
4203 * @return {String}
4204 * @public
4205 */
4206
4207function etag (entity, options) {
4208 if (entity == null) {
4209 throw new TypeError('argument entity is required')
4210 }
4211
4212 // support fs.Stats object
4213 var isStats = isstats(entity);
4214 var weak = options && typeof options.weak === 'boolean'
4215 ? options.weak
4216 : isStats;
4217
4218 // validate argument
4219 if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) {
4220 throw new TypeError('argument entity must be string, Buffer, or fs.Stats')
4221 }
4222
4223 // generate entity tag
4224 var tag = isStats
4225 ? stattag(entity)
4226 : entitytag(entity);
4227
4228 return weak
4229 ? 'W/' + tag
4230 : tag
4231}
4232
4233/**
4234 * Determine if object is a Stats object.
4235 *
4236 * @param {object} obj
4237 * @return {boolean}
4238 * @api private
4239 */
4240
4241function isstats (obj) {
4242 // genuine fs.Stats
4243 if (typeof Stats === 'function' && obj instanceof Stats) {
4244 return true
4245 }
4246
4247 // quack quack
4248 return obj && typeof obj === 'object' &&
4249 'ctime' in obj && toString$1.call(obj.ctime) === '[object Date]' &&
4250 'mtime' in obj && toString$1.call(obj.mtime) === '[object Date]' &&
4251 'ino' in obj && typeof obj.ino === 'number' &&
4252 'size' in obj && typeof obj.size === 'number'
4253}
4254
4255/**
4256 * Generate a tag for a stat.
4257 *
4258 * @param {object} stat
4259 * @return {string}
4260 * @private
4261 */
4262
4263function stattag (stat) {
4264 var mtime = stat.mtime.getTime().toString(16);
4265 var size = stat.size.toString(16);
4266
4267 return '"' + size + '-' + mtime + '"'
4268}
4269
4270var getEtag = /*@__PURE__*/getDefaultExportFromCjs(etag_1);
4271
4272class BitSet {
4273 constructor(arg) {
4274 this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
4275 }
4276
4277 add(n) {
4278 this.bits[n >> 5] |= 1 << (n & 31);
4279 }
4280
4281 has(n) {
4282 return !!(this.bits[n >> 5] & (1 << (n & 31)));
4283 }
4284}
4285
4286class Chunk {
4287 constructor(start, end, content) {
4288 this.start = start;
4289 this.end = end;
4290 this.original = content;
4291
4292 this.intro = '';
4293 this.outro = '';
4294
4295 this.content = content;
4296 this.storeName = false;
4297 this.edited = false;
4298
4299 {
4300 this.previous = null;
4301 this.next = null;
4302 }
4303 }
4304
4305 appendLeft(content) {
4306 this.outro += content;
4307 }
4308
4309 appendRight(content) {
4310 this.intro = this.intro + content;
4311 }
4312
4313 clone() {
4314 const chunk = new Chunk(this.start, this.end, this.original);
4315
4316 chunk.intro = this.intro;
4317 chunk.outro = this.outro;
4318 chunk.content = this.content;
4319 chunk.storeName = this.storeName;
4320 chunk.edited = this.edited;
4321
4322 return chunk;
4323 }
4324
4325 contains(index) {
4326 return this.start < index && index < this.end;
4327 }
4328
4329 eachNext(fn) {
4330 let chunk = this;
4331 while (chunk) {
4332 fn(chunk);
4333 chunk = chunk.next;
4334 }
4335 }
4336
4337 eachPrevious(fn) {
4338 let chunk = this;
4339 while (chunk) {
4340 fn(chunk);
4341 chunk = chunk.previous;
4342 }
4343 }
4344
4345 edit(content, storeName, contentOnly) {
4346 this.content = content;
4347 if (!contentOnly) {
4348 this.intro = '';
4349 this.outro = '';
4350 }
4351 this.storeName = storeName;
4352
4353 this.edited = true;
4354
4355 return this;
4356 }
4357
4358 prependLeft(content) {
4359 this.outro = content + this.outro;
4360 }
4361
4362 prependRight(content) {
4363 this.intro = content + this.intro;
4364 }
4365
4366 reset() {
4367 this.intro = '';
4368 this.outro = '';
4369 if (this.edited) {
4370 this.content = this.original;
4371 this.storeName = false;
4372 this.edited = false;
4373 }
4374 }
4375
4376 split(index) {
4377 const sliceIndex = index - this.start;
4378
4379 const originalBefore = this.original.slice(0, sliceIndex);
4380 const originalAfter = this.original.slice(sliceIndex);
4381
4382 this.original = originalBefore;
4383
4384 const newChunk = new Chunk(index, this.end, originalAfter);
4385 newChunk.outro = this.outro;
4386 this.outro = '';
4387
4388 this.end = index;
4389
4390 if (this.edited) {
4391 // after split we should save the edit content record into the correct chunk
4392 // to make sure sourcemap correct
4393 // For example:
4394 // ' test'.trim()
4395 // split -> ' ' + 'test'
4396 // ✔️ edit -> '' + 'test'
4397 // ✖️ edit -> 'test' + ''
4398 // TODO is this block necessary?...
4399 newChunk.edit('', false);
4400 this.content = '';
4401 } else {
4402 this.content = originalBefore;
4403 }
4404
4405 newChunk.next = this.next;
4406 if (newChunk.next) newChunk.next.previous = newChunk;
4407 newChunk.previous = this;
4408 this.next = newChunk;
4409
4410 return newChunk;
4411 }
4412
4413 toString() {
4414 return this.intro + this.content + this.outro;
4415 }
4416
4417 trimEnd(rx) {
4418 this.outro = this.outro.replace(rx, '');
4419 if (this.outro.length) return true;
4420
4421 const trimmed = this.content.replace(rx, '');
4422
4423 if (trimmed.length) {
4424 if (trimmed !== this.content) {
4425 this.split(this.start + trimmed.length).edit('', undefined, true);
4426 if (this.edited) {
4427 // save the change, if it has been edited
4428 this.edit(trimmed, this.storeName, true);
4429 }
4430 }
4431 return true;
4432 } else {
4433 this.edit('', undefined, true);
4434
4435 this.intro = this.intro.replace(rx, '');
4436 if (this.intro.length) return true;
4437 }
4438 }
4439
4440 trimStart(rx) {
4441 this.intro = this.intro.replace(rx, '');
4442 if (this.intro.length) return true;
4443
4444 const trimmed = this.content.replace(rx, '');
4445
4446 if (trimmed.length) {
4447 if (trimmed !== this.content) {
4448 const newChunk = this.split(this.end - trimmed.length);
4449 if (this.edited) {
4450 // save the change, if it has been edited
4451 newChunk.edit(trimmed, this.storeName, true);
4452 }
4453 this.edit('', undefined, true);
4454 }
4455 return true;
4456 } else {
4457 this.edit('', undefined, true);
4458
4459 this.outro = this.outro.replace(rx, '');
4460 if (this.outro.length) return true;
4461 }
4462 }
4463}
4464
4465function getBtoa() {
4466 if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
4467 return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
4468 } else if (typeof Buffer === 'function') {
4469 return (str) => Buffer.from(str, 'utf-8').toString('base64');
4470 } else {
4471 return () => {
4472 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
4473 };
4474 }
4475}
4476
4477const btoa$1 = /*#__PURE__*/ getBtoa();
4478
4479class SourceMap {
4480 constructor(properties) {
4481 this.version = 3;
4482 this.file = properties.file;
4483 this.sources = properties.sources;
4484 this.sourcesContent = properties.sourcesContent;
4485 this.names = properties.names;
4486 this.mappings = encode(properties.mappings);
4487 if (typeof properties.x_google_ignoreList !== 'undefined') {
4488 this.x_google_ignoreList = properties.x_google_ignoreList;
4489 }
4490 if (typeof properties.debugId !== 'undefined') {
4491 this.debugId = properties.debugId;
4492 }
4493 }
4494
4495 toString() {
4496 return JSON.stringify(this);
4497 }
4498
4499 toUrl() {
4500 return 'data:application/json;charset=utf-8;base64,' + btoa$1(this.toString());
4501 }
4502}
4503
4504function guessIndent(code) {
4505 const lines = code.split('\n');
4506
4507 const tabbed = lines.filter((line) => /^\t+/.test(line));
4508 const spaced = lines.filter((line) => /^ {2,}/.test(line));
4509
4510 if (tabbed.length === 0 && spaced.length === 0) {
4511 return null;
4512 }
4513
4514 // More lines tabbed than spaced? Assume tabs, and
4515 // default to tabs in the case of a tie (or nothing
4516 // to go on)
4517 if (tabbed.length >= spaced.length) {
4518 return '\t';
4519 }
4520
4521 // Otherwise, we need to guess the multiple
4522 const min = spaced.reduce((previous, current) => {
4523 const numSpaces = /^ +/.exec(current)[0].length;
4524 return Math.min(numSpaces, previous);
4525 }, Infinity);
4526
4527 return new Array(min + 1).join(' ');
4528}
4529
4530function getRelativePath(from, to) {
4531 const fromParts = from.split(/[/\\]/);
4532 const toParts = to.split(/[/\\]/);
4533
4534 fromParts.pop(); // get dirname
4535
4536 while (fromParts[0] === toParts[0]) {
4537 fromParts.shift();
4538 toParts.shift();
4539 }
4540
4541 if (fromParts.length) {
4542 let i = fromParts.length;
4543 while (i--) fromParts[i] = '..';
4544 }
4545
4546 return fromParts.concat(toParts).join('/');
4547}
4548
4549const toString = Object.prototype.toString;
4550
4551function isObject(thing) {
4552 return toString.call(thing) === '[object Object]';
4553}
4554
4555function getLocator(source) {
4556 const originalLines = source.split('\n');
4557 const lineOffsets = [];
4558
4559 for (let i = 0, pos = 0; i < originalLines.length; i++) {
4560 lineOffsets.push(pos);
4561 pos += originalLines[i].length + 1;
4562 }
4563
4564 return function locate(index) {
4565 let i = 0;
4566 let j = lineOffsets.length;
4567 while (i < j) {
4568 const m = (i + j) >> 1;
4569 if (index < lineOffsets[m]) {
4570 j = m;
4571 } else {
4572 i = m + 1;
4573 }
4574 }
4575 const line = i - 1;
4576 const column = index - lineOffsets[line];
4577 return { line, column };
4578 };
4579}
4580
4581const wordRegex = /\w/;
4582
4583class Mappings {
4584 constructor(hires) {
4585 this.hires = hires;
4586 this.generatedCodeLine = 0;
4587 this.generatedCodeColumn = 0;
4588 this.raw = [];
4589 this.rawSegments = this.raw[this.generatedCodeLine] = [];
4590 this.pending = null;
4591 }
4592
4593 addEdit(sourceIndex, content, loc, nameIndex) {
4594 if (content.length) {
4595 const contentLengthMinusOne = content.length - 1;
4596 let contentLineEnd = content.indexOf('\n', 0);
4597 let previousContentLineEnd = -1;
4598 // Loop through each line in the content and add a segment, but stop if the last line is empty,
4599 // else code afterwards would fill one line too many
4600 while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
4601 const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
4602 if (nameIndex >= 0) {
4603 segment.push(nameIndex);
4604 }
4605 this.rawSegments.push(segment);
4606
4607 this.generatedCodeLine += 1;
4608 this.raw[this.generatedCodeLine] = this.rawSegments = [];
4609 this.generatedCodeColumn = 0;
4610
4611 previousContentLineEnd = contentLineEnd;
4612 contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
4613 }
4614
4615 const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
4616 if (nameIndex >= 0) {
4617 segment.push(nameIndex);
4618 }
4619 this.rawSegments.push(segment);
4620
4621 this.advance(content.slice(previousContentLineEnd + 1));
4622 } else if (this.pending) {
4623 this.rawSegments.push(this.pending);
4624 this.advance(content);
4625 }
4626
4627 this.pending = null;
4628 }
4629
4630 addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
4631 let originalCharIndex = chunk.start;
4632 let first = true;
4633 // when iterating each char, check if it's in a word boundary
4634 let charInHiresBoundary = false;
4635
4636 while (originalCharIndex < chunk.end) {
4637 if (original[originalCharIndex] === '\n') {
4638 loc.line += 1;
4639 loc.column = 0;
4640 this.generatedCodeLine += 1;
4641 this.raw[this.generatedCodeLine] = this.rawSegments = [];
4642 this.generatedCodeColumn = 0;
4643 first = true;
4644 charInHiresBoundary = false;
4645 } else {
4646 if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
4647 const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
4648
4649 if (this.hires === 'boundary') {
4650 // in hires "boundary", group segments per word boundary than per char
4651 if (wordRegex.test(original[originalCharIndex])) {
4652 // for first char in the boundary found, start the boundary by pushing a segment
4653 if (!charInHiresBoundary) {
4654 this.rawSegments.push(segment);
4655 charInHiresBoundary = true;
4656 }
4657 } else {
4658 // for non-word char, end the boundary by pushing a segment
4659 this.rawSegments.push(segment);
4660 charInHiresBoundary = false;
4661 }
4662 } else {
4663 this.rawSegments.push(segment);
4664 }
4665 }
4666
4667 loc.column += 1;
4668 this.generatedCodeColumn += 1;
4669 first = false;
4670 }
4671
4672 originalCharIndex += 1;
4673 }
4674
4675 this.pending = null;
4676 }
4677
4678 advance(str) {
4679 if (!str) return;
4680
4681 const lines = str.split('\n');
4682
4683 if (lines.length > 1) {
4684 for (let i = 0; i < lines.length - 1; i++) {
4685 this.generatedCodeLine++;
4686 this.raw[this.generatedCodeLine] = this.rawSegments = [];
4687 }
4688 this.generatedCodeColumn = 0;
4689 }
4690
4691 this.generatedCodeColumn += lines[lines.length - 1].length;
4692 }
4693}
4694
4695const n = '\n';
4696
4697const warned = {
4698 insertLeft: false,
4699 insertRight: false,
4700 storeName: false,
4701};
4702
4703class MagicString {
4704 constructor(string, options = {}) {
4705 const chunk = new Chunk(0, string.length, string);
4706
4707 Object.defineProperties(this, {
4708 original: { writable: true, value: string },
4709 outro: { writable: true, value: '' },
4710 intro: { writable: true, value: '' },
4711 firstChunk: { writable: true, value: chunk },
4712 lastChunk: { writable: true, value: chunk },
4713 lastSearchedChunk: { writable: true, value: chunk },
4714 byStart: { writable: true, value: {} },
4715 byEnd: { writable: true, value: {} },
4716 filename: { writable: true, value: options.filename },
4717 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
4718 sourcemapLocations: { writable: true, value: new BitSet() },
4719 storedNames: { writable: true, value: {} },
4720 indentStr: { writable: true, value: undefined },
4721 ignoreList: { writable: true, value: options.ignoreList },
4722 offset: { writable: true, value: options.offset || 0 },
4723 });
4724
4725 this.byStart[0] = chunk;
4726 this.byEnd[string.length] = chunk;
4727 }
4728
4729 addSourcemapLocation(char) {
4730 this.sourcemapLocations.add(char);
4731 }
4732
4733 append(content) {
4734 if (typeof content !== 'string') throw new TypeError('outro content must be a string');
4735
4736 this.outro += content;
4737 return this;
4738 }
4739
4740 appendLeft(index, content) {
4741 index = index + this.offset;
4742
4743 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
4744
4745 this._split(index);
4746
4747 const chunk = this.byEnd[index];
4748
4749 if (chunk) {
4750 chunk.appendLeft(content);
4751 } else {
4752 this.intro += content;
4753 }
4754 return this;
4755 }
4756
4757 appendRight(index, content) {
4758 index = index + this.offset;
4759
4760 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
4761
4762 this._split(index);
4763
4764 const chunk = this.byStart[index];
4765
4766 if (chunk) {
4767 chunk.appendRight(content);
4768 } else {
4769 this.outro += content;
4770 }
4771 return this;
4772 }
4773
4774 clone() {
4775 const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
4776
4777 let originalChunk = this.firstChunk;
4778 let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
4779
4780 while (originalChunk) {
4781 cloned.byStart[clonedChunk.start] = clonedChunk;
4782 cloned.byEnd[clonedChunk.end] = clonedChunk;
4783
4784 const nextOriginalChunk = originalChunk.next;
4785 const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
4786
4787 if (nextClonedChunk) {
4788 clonedChunk.next = nextClonedChunk;
4789 nextClonedChunk.previous = clonedChunk;
4790
4791 clonedChunk = nextClonedChunk;
4792 }
4793
4794 originalChunk = nextOriginalChunk;
4795 }
4796
4797 cloned.lastChunk = clonedChunk;
4798
4799 if (this.indentExclusionRanges) {
4800 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
4801 }
4802
4803 cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
4804
4805 cloned.intro = this.intro;
4806 cloned.outro = this.outro;
4807
4808 return cloned;
4809 }
4810
4811 generateDecodedMap(options) {
4812 options = options || {};
4813
4814 const sourceIndex = 0;
4815 const names = Object.keys(this.storedNames);
4816 const mappings = new Mappings(options.hires);
4817
4818 const locate = getLocator(this.original);
4819
4820 if (this.intro) {
4821 mappings.advance(this.intro);
4822 }
4823
4824 this.firstChunk.eachNext((chunk) => {
4825 const loc = locate(chunk.start);
4826
4827 if (chunk.intro.length) mappings.advance(chunk.intro);
4828
4829 if (chunk.edited) {
4830 mappings.addEdit(
4831 sourceIndex,
4832 chunk.content,
4833 loc,
4834 chunk.storeName ? names.indexOf(chunk.original) : -1,
4835 );
4836 } else {
4837 mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
4838 }
4839
4840 if (chunk.outro.length) mappings.advance(chunk.outro);
4841 });
4842
4843 return {
4844 file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
4845 sources: [
4846 options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
4847 ],
4848 sourcesContent: options.includeContent ? [this.original] : undefined,
4849 names,
4850 mappings: mappings.raw,
4851 x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
4852 };
4853 }
4854
4855 generateMap(options) {
4856 return new SourceMap(this.generateDecodedMap(options));
4857 }
4858
4859 _ensureindentStr() {
4860 if (this.indentStr === undefined) {
4861 this.indentStr = guessIndent(this.original);
4862 }
4863 }
4864
4865 _getRawIndentString() {
4866 this._ensureindentStr();
4867 return this.indentStr;
4868 }
4869
4870 getIndentString() {
4871 this._ensureindentStr();
4872 return this.indentStr === null ? '\t' : this.indentStr;
4873 }
4874
4875 indent(indentStr, options) {
4876 const pattern = /^[^\r\n]/gm;
4877
4878 if (isObject(indentStr)) {
4879 options = indentStr;
4880 indentStr = undefined;
4881 }
4882
4883 if (indentStr === undefined) {
4884 this._ensureindentStr();
4885 indentStr = this.indentStr || '\t';
4886 }
4887
4888 if (indentStr === '') return this; // noop
4889
4890 options = options || {};
4891
4892 // Process exclusion ranges
4893 const isExcluded = {};
4894
4895 if (options.exclude) {
4896 const exclusions =
4897 typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
4898 exclusions.forEach((exclusion) => {
4899 for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
4900 isExcluded[i] = true;
4901 }
4902 });
4903 }
4904
4905 let shouldIndentNextCharacter = options.indentStart !== false;
4906 const replacer = (match) => {
4907 if (shouldIndentNextCharacter) return `${indentStr}${match}`;
4908 shouldIndentNextCharacter = true;
4909 return match;
4910 };
4911
4912 this.intro = this.intro.replace(pattern, replacer);
4913
4914 let charIndex = 0;
4915 let chunk = this.firstChunk;
4916
4917 while (chunk) {
4918 const end = chunk.end;
4919
4920 if (chunk.edited) {
4921 if (!isExcluded[charIndex]) {
4922 chunk.content = chunk.content.replace(pattern, replacer);
4923
4924 if (chunk.content.length) {
4925 shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
4926 }
4927 }
4928 } else {
4929 charIndex = chunk.start;
4930
4931 while (charIndex < end) {
4932 if (!isExcluded[charIndex]) {
4933 const char = this.original[charIndex];
4934
4935 if (char === '\n') {
4936 shouldIndentNextCharacter = true;
4937 } else if (char !== '\r' && shouldIndentNextCharacter) {
4938 shouldIndentNextCharacter = false;
4939
4940 if (charIndex === chunk.start) {
4941 chunk.prependRight(indentStr);
4942 } else {
4943 this._splitChunk(chunk, charIndex);
4944 chunk = chunk.next;
4945 chunk.prependRight(indentStr);
4946 }
4947 }
4948 }
4949
4950 charIndex += 1;
4951 }
4952 }
4953
4954 charIndex = chunk.end;
4955 chunk = chunk.next;
4956 }
4957
4958 this.outro = this.outro.replace(pattern, replacer);
4959
4960 return this;
4961 }
4962
4963 insert() {
4964 throw new Error(
4965 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
4966 );
4967 }
4968
4969 insertLeft(index, content) {
4970 if (!warned.insertLeft) {
4971 console.warn(
4972 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
4973 );
4974 warned.insertLeft = true;
4975 }
4976
4977 return this.appendLeft(index, content);
4978 }
4979
4980 insertRight(index, content) {
4981 if (!warned.insertRight) {
4982 console.warn(
4983 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
4984 );
4985 warned.insertRight = true;
4986 }
4987
4988 return this.prependRight(index, content);
4989 }
4990
4991 move(start, end, index) {
4992 start = start + this.offset;
4993 end = end + this.offset;
4994 index = index + this.offset;
4995
4996 if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
4997
4998 this._split(start);
4999 this._split(end);
5000 this._split(index);
5001
5002 const first = this.byStart[start];
5003 const last = this.byEnd[end];
5004
5005 const oldLeft = first.previous;
5006 const oldRight = last.next;
5007
5008 const newRight = this.byStart[index];
5009 if (!newRight && last === this.lastChunk) return this;
5010 const newLeft = newRight ? newRight.previous : this.lastChunk;
5011
5012 if (oldLeft) oldLeft.next = oldRight;
5013 if (oldRight) oldRight.previous = oldLeft;
5014
5015 if (newLeft) newLeft.next = first;
5016 if (newRight) newRight.previous = last;
5017
5018 if (!first.previous) this.firstChunk = last.next;
5019 if (!last.next) {
5020 this.lastChunk = first.previous;
5021 this.lastChunk.next = null;
5022 }
5023
5024 first.previous = newLeft;
5025 last.next = newRight || null;
5026
5027 if (!newLeft) this.firstChunk = first;
5028 if (!newRight) this.lastChunk = last;
5029 return this;
5030 }
5031
5032 overwrite(start, end, content, options) {
5033 options = options || {};
5034 return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
5035 }
5036
5037 update(start, end, content, options) {
5038 start = start + this.offset;
5039 end = end + this.offset;
5040
5041 if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
5042
5043 if (this.original.length !== 0) {
5044 while (start < 0) start += this.original.length;
5045 while (end < 0) end += this.original.length;
5046 }
5047
5048 if (end > this.original.length) throw new Error('end is out of bounds');
5049 if (start === end)
5050 throw new Error(
5051 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
5052 );
5053
5054 this._split(start);
5055 this._split(end);
5056
5057 if (options === true) {
5058 if (!warned.storeName) {
5059 console.warn(
5060 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
5061 );
5062 warned.storeName = true;
5063 }
5064
5065 options = { storeName: true };
5066 }
5067 const storeName = options !== undefined ? options.storeName : false;
5068 const overwrite = options !== undefined ? options.overwrite : false;
5069
5070 if (storeName) {
5071 const original = this.original.slice(start, end);
5072 Object.defineProperty(this.storedNames, original, {
5073 writable: true,
5074 value: true,
5075 enumerable: true,
5076 });
5077 }
5078
5079 const first = this.byStart[start];
5080 const last = this.byEnd[end];
5081
5082 if (first) {
5083 let chunk = first;
5084 while (chunk !== last) {
5085 if (chunk.next !== this.byStart[chunk.end]) {
5086 throw new Error('Cannot overwrite across a split point');
5087 }
5088 chunk = chunk.next;
5089 chunk.edit('', false);
5090 }
5091
5092 first.edit(content, storeName, !overwrite);
5093 } else {
5094 // must be inserting at the end
5095 const newChunk = new Chunk(start, end, '').edit(content, storeName);
5096
5097 // TODO last chunk in the array may not be the last chunk, if it's moved...
5098 last.next = newChunk;
5099 newChunk.previous = last;
5100 }
5101 return this;
5102 }
5103
5104 prepend(content) {
5105 if (typeof content !== 'string') throw new TypeError('outro content must be a string');
5106
5107 this.intro = content + this.intro;
5108 return this;
5109 }
5110
5111 prependLeft(index, content) {
5112 index = index + this.offset;
5113
5114 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
5115
5116 this._split(index);
5117
5118 const chunk = this.byEnd[index];
5119
5120 if (chunk) {
5121 chunk.prependLeft(content);
5122 } else {
5123 this.intro = content + this.intro;
5124 }
5125 return this;
5126 }
5127
5128 prependRight(index, content) {
5129 index = index + this.offset;
5130
5131 if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
5132
5133 this._split(index);
5134
5135 const chunk = this.byStart[index];
5136
5137 if (chunk) {
5138 chunk.prependRight(content);
5139 } else {
5140 this.outro = content + this.outro;
5141 }
5142 return this;
5143 }
5144
5145 remove(start, end) {
5146 start = start + this.offset;
5147 end = end + this.offset;
5148
5149 if (this.original.length !== 0) {
5150 while (start < 0) start += this.original.length;
5151 while (end < 0) end += this.original.length;
5152 }
5153
5154 if (start === end) return this;
5155
5156 if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
5157 if (start > end) throw new Error('end must be greater than start');
5158
5159 this._split(start);
5160 this._split(end);
5161
5162 let chunk = this.byStart[start];
5163
5164 while (chunk) {
5165 chunk.intro = '';
5166 chunk.outro = '';
5167 chunk.edit('');
5168
5169 chunk = end > chunk.end ? this.byStart[chunk.end] : null;
5170 }
5171 return this;
5172 }
5173
5174 reset(start, end) {
5175 start = start + this.offset;
5176 end = end + this.offset;
5177
5178 if (this.original.length !== 0) {
5179 while (start < 0) start += this.original.length;
5180 while (end < 0) end += this.original.length;
5181 }
5182
5183 if (start === end) return this;
5184
5185 if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
5186 if (start > end) throw new Error('end must be greater than start');
5187
5188 this._split(start);
5189 this._split(end);
5190
5191 let chunk = this.byStart[start];
5192
5193 while (chunk) {
5194 chunk.reset();
5195
5196 chunk = end > chunk.end ? this.byStart[chunk.end] : null;
5197 }
5198 return this;
5199 }
5200
5201 lastChar() {
5202 if (this.outro.length) return this.outro[this.outro.length - 1];
5203 let chunk = this.lastChunk;
5204 do {
5205 if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
5206 if (chunk.content.length) return chunk.content[chunk.content.length - 1];
5207 if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
5208 } while ((chunk = chunk.previous));
5209 if (this.intro.length) return this.intro[this.intro.length - 1];
5210 return '';
5211 }
5212
5213 lastLine() {
5214 let lineIndex = this.outro.lastIndexOf(n);
5215 if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
5216 let lineStr = this.outro;
5217 let chunk = this.lastChunk;
5218 do {
5219 if (chunk.outro.length > 0) {
5220 lineIndex = chunk.outro.lastIndexOf(n);
5221 if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
5222 lineStr = chunk.outro + lineStr;
5223 }
5224
5225 if (chunk.content.length > 0) {
5226 lineIndex = chunk.content.lastIndexOf(n);
5227 if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
5228 lineStr = chunk.content + lineStr;
5229 }
5230
5231 if (chunk.intro.length > 0) {
5232 lineIndex = chunk.intro.lastIndexOf(n);
5233 if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
5234 lineStr = chunk.intro + lineStr;
5235 }
5236 } while ((chunk = chunk.previous));
5237 lineIndex = this.intro.lastIndexOf(n);
5238 if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
5239 return this.intro + lineStr;
5240 }
5241
5242 slice(start = 0, end = this.original.length - this.offset) {
5243 start = start + this.offset;
5244 end = end + this.offset;
5245
5246 if (this.original.length !== 0) {
5247 while (start < 0) start += this.original.length;
5248 while (end < 0) end += this.original.length;
5249 }
5250
5251 let result = '';
5252
5253 // find start chunk
5254 let chunk = this.firstChunk;
5255 while (chunk && (chunk.start > start || chunk.end <= start)) {
5256 // found end chunk before start
5257 if (chunk.start < end && chunk.end >= end) {
5258 return result;
5259 }
5260
5261 chunk = chunk.next;
5262 }
5263
5264 if (chunk && chunk.edited && chunk.start !== start)
5265 throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
5266
5267 const startChunk = chunk;
5268 while (chunk) {
5269 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
5270 result += chunk.intro;
5271 }
5272
5273 const containsEnd = chunk.start < end && chunk.end >= end;
5274 if (containsEnd && chunk.edited && chunk.end !== end)
5275 throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
5276
5277 const sliceStart = startChunk === chunk ? start - chunk.start : 0;
5278 const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
5279
5280 result += chunk.content.slice(sliceStart, sliceEnd);
5281
5282 if (chunk.outro && (!containsEnd || chunk.end === end)) {
5283 result += chunk.outro;
5284 }
5285
5286 if (containsEnd) {
5287 break;
5288 }
5289
5290 chunk = chunk.next;
5291 }
5292
5293 return result;
5294 }
5295
5296 // TODO deprecate this? not really very useful
5297 snip(start, end) {
5298 const clone = this.clone();
5299 clone.remove(0, start);
5300 clone.remove(end, clone.original.length);
5301
5302 return clone;
5303 }
5304
5305 _split(index) {
5306 if (this.byStart[index] || this.byEnd[index]) return;
5307
5308 let chunk = this.lastSearchedChunk;
5309 const searchForward = index > chunk.end;
5310
5311 while (chunk) {
5312 if (chunk.contains(index)) return this._splitChunk(chunk, index);
5313
5314 chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
5315 }
5316 }
5317
5318 _splitChunk(chunk, index) {
5319 if (chunk.edited && chunk.content.length) {
5320 // zero-length edited chunks are a special case (overlapping replacements)
5321 const loc = getLocator(this.original)(index);
5322 throw new Error(
5323 `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
5324 );
5325 }
5326
5327 const newChunk = chunk.split(index);
5328
5329 this.byEnd[index] = chunk;
5330 this.byStart[index] = newChunk;
5331 this.byEnd[newChunk.end] = newChunk;
5332
5333 if (chunk === this.lastChunk) this.lastChunk = newChunk;
5334
5335 this.lastSearchedChunk = chunk;
5336 return true;
5337 }
5338
5339 toString() {
5340 let str = this.intro;
5341
5342 let chunk = this.firstChunk;
5343 while (chunk) {
5344 str += chunk.toString();
5345 chunk = chunk.next;
5346 }
5347
5348 return str + this.outro;
5349 }
5350
5351 isEmpty() {
5352 let chunk = this.firstChunk;
5353 do {
5354 if (
5355 (chunk.intro.length && chunk.intro.trim()) ||
5356 (chunk.content.length && chunk.content.trim()) ||
5357 (chunk.outro.length && chunk.outro.trim())
5358 )
5359 return false;
5360 } while ((chunk = chunk.next));
5361 return true;
5362 }
5363
5364 length() {
5365 let chunk = this.firstChunk;
5366 let length = 0;
5367 do {
5368 length += chunk.intro.length + chunk.content.length + chunk.outro.length;
5369 } while ((chunk = chunk.next));
5370 return length;
5371 }
5372
5373 trimLines() {
5374 return this.trim('[\\r\\n]');
5375 }
5376
5377 trim(charType) {
5378 return this.trimStart(charType).trimEnd(charType);
5379 }
5380
5381 trimEndAborted(charType) {
5382 const rx = new RegExp((charType || '\\s') + '+$');
5383
5384 this.outro = this.outro.replace(rx, '');
5385 if (this.outro.length) return true;
5386
5387 let chunk = this.lastChunk;
5388
5389 do {
5390 const end = chunk.end;
5391 const aborted = chunk.trimEnd(rx);
5392
5393 // if chunk was trimmed, we have a new lastChunk
5394 if (chunk.end !== end) {
5395 if (this.lastChunk === chunk) {
5396 this.lastChunk = chunk.next;
5397 }
5398
5399 this.byEnd[chunk.end] = chunk;
5400 this.byStart[chunk.next.start] = chunk.next;
5401 this.byEnd[chunk.next.end] = chunk.next;
5402 }
5403
5404 if (aborted) return true;
5405 chunk = chunk.previous;
5406 } while (chunk);
5407
5408 return false;
5409 }
5410
5411 trimEnd(charType) {
5412 this.trimEndAborted(charType);
5413 return this;
5414 }
5415 trimStartAborted(charType) {
5416 const rx = new RegExp('^' + (charType || '\\s') + '+');
5417
5418 this.intro = this.intro.replace(rx, '');
5419 if (this.intro.length) return true;
5420
5421 let chunk = this.firstChunk;
5422
5423 do {
5424 const end = chunk.end;
5425 const aborted = chunk.trimStart(rx);
5426
5427 if (chunk.end !== end) {
5428 // special case...
5429 if (chunk === this.lastChunk) this.lastChunk = chunk.next;
5430
5431 this.byEnd[chunk.end] = chunk;
5432 this.byStart[chunk.next.start] = chunk.next;
5433 this.byEnd[chunk.next.end] = chunk.next;
5434 }
5435
5436 if (aborted) return true;
5437 chunk = chunk.next;
5438 } while (chunk);
5439
5440 return false;
5441 }
5442
5443 trimStart(charType) {
5444 this.trimStartAborted(charType);
5445 return this;
5446 }
5447
5448 hasChanged() {
5449 return this.original !== this.toString();
5450 }
5451
5452 _replaceRegexp(searchValue, replacement) {
5453 function getReplacement(match, str) {
5454 if (typeof replacement === 'string') {
5455 return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
5456 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
5457 if (i === '$') return '$';
5458 if (i === '&') return match[0];
5459 const num = +i;
5460 if (num < match.length) return match[+i];
5461 return `$${i}`;
5462 });
5463 } else {
5464 return replacement(...match, match.index, str, match.groups);
5465 }
5466 }
5467 function matchAll(re, str) {
5468 let match;
5469 const matches = [];
5470 while ((match = re.exec(str))) {
5471 matches.push(match);
5472 }
5473 return matches;
5474 }
5475 if (searchValue.global) {
5476 const matches = matchAll(searchValue, this.original);
5477 matches.forEach((match) => {
5478 if (match.index != null) {
5479 const replacement = getReplacement(match, this.original);
5480 if (replacement !== match[0]) {
5481 this.overwrite(match.index, match.index + match[0].length, replacement);
5482 }
5483 }
5484 });
5485 } else {
5486 const match = this.original.match(searchValue);
5487 if (match && match.index != null) {
5488 const replacement = getReplacement(match, this.original);
5489 if (replacement !== match[0]) {
5490 this.overwrite(match.index, match.index + match[0].length, replacement);
5491 }
5492 }
5493 }
5494 return this;
5495 }
5496
5497 _replaceString(string, replacement) {
5498 const { original } = this;
5499 const index = original.indexOf(string);
5500
5501 if (index !== -1) {
5502 this.overwrite(index, index + string.length, replacement);
5503 }
5504
5505 return this;
5506 }
5507
5508 replace(searchValue, replacement) {
5509 if (typeof searchValue === 'string') {
5510 return this._replaceString(searchValue, replacement);
5511 }
5512
5513 return this._replaceRegexp(searchValue, replacement);
5514 }
5515
5516 _replaceAllString(string, replacement) {
5517 const { original } = this;
5518 const stringLength = string.length;
5519 for (
5520 let index = original.indexOf(string);
5521 index !== -1;
5522 index = original.indexOf(string, index + stringLength)
5523 ) {
5524 const previous = original.slice(index, index + stringLength);
5525 if (previous !== replacement) this.overwrite(index, index + stringLength, replacement);
5526 }
5527
5528 return this;
5529 }
5530
5531 replaceAll(searchValue, replacement) {
5532 if (typeof searchValue === 'string') {
5533 return this._replaceAllString(searchValue, replacement);
5534 }
5535
5536 if (!searchValue.global) {
5537 throw new TypeError(
5538 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
5539 );
5540 }
5541
5542 return this._replaceRegexp(searchValue, replacement);
5543 }
5544}
5545
5546const debug$1 = createDebugger("vite:sourcemap", {
5547 onlyWhenFocused: true
5548});
5549function genSourceMapUrl(map) {
5550 if (typeof map !== "string") {
5551 map = JSON.stringify(map);
5552 }
5553 return `data:application/json;base64,${Buffer.from(map).toString("base64")}`;
5554}
5555function getCodeWithSourcemap(type, code, map) {
5556 if (debug$1) {
5557 code += `
5558/*${JSON.stringify(map, null, 2).replace(/\*\//g, "*\\/")}*/
5559`;
5560 }
5561 if (type === "js") {
5562 code += `
5563//# sourceMappingURL=${genSourceMapUrl(map)}`;
5564 } else if (type === "css") {
5565 code += `
5566/*# sourceMappingURL=${genSourceMapUrl(map)} */`;
5567 }
5568 return code;
5569}
5570
5571const debug = createDebugger("vite:send", {
5572 onlyWhenFocused: true
5573});
5574const alias = {
5575 js: "text/javascript",
5576 css: "text/css",
5577 html: "text/html",
5578 json: "application/json"
5579};
5580function send(req, res, content, type, options) {
5581 const {
5582 etag = getEtag(content, { weak: true }),
5583 cacheControl = "no-cache",
5584 headers,
5585 map
5586 } = options;
5587 if (res.writableEnded) {
5588 return;
5589 }
5590 if (req.headers["if-none-match"] === etag) {
5591 res.statusCode = 304;
5592 res.end();
5593 return;
5594 }
5595 res.setHeader("Content-Type", alias[type] || type);
5596 res.setHeader("Cache-Control", cacheControl);
5597 res.setHeader("Etag", etag);
5598 if (headers) {
5599 for (const name in headers) {
5600 res.setHeader(name, headers[name]);
5601 }
5602 }
5603 if (map && "version" in map && map.mappings) {
5604 if (type === "js" || type === "css") {
5605 content = getCodeWithSourcemap(type, content.toString(), map);
5606 }
5607 } else if (type === "js" && (!map || map.mappings !== "")) {
5608 const code = content.toString();
5609 if (convertSourceMap.mapFileCommentRegex.test(code)) {
5610 debug?.(`Skipped injecting fallback sourcemap for ${req.url}`);
5611 } else {
5612 const urlWithoutTimestamp = removeTimestampQuery(req.url);
5613 const ms = new MagicString(code);
5614 content = getCodeWithSourcemap(
5615 type,
5616 code,
5617 ms.generateMap({
5618 source: path$1.basename(urlWithoutTimestamp),
5619 hires: "boundary",
5620 includeContent: true
5621 })
5622 );
5623 }
5624 }
5625 res.statusCode = 200;
5626 res.end(content);
5627 return;
5628}
5629
5630const LogLevels = {
5631 silent: 0,
5632 error: 1,
5633 warn: 2,
5634 info: 3
5635};
5636let lastType;
5637let lastMsg;
5638let sameCount = 0;
5639function clearScreen() {
5640 const repeatCount = process.stdout.rows - 2;
5641 const blank = repeatCount > 0 ? "\n".repeat(repeatCount) : "";
5642 console.log(blank);
5643 readline.cursorTo(process.stdout, 0, 0);
5644 readline.clearScreenDown(process.stdout);
5645}
5646let timeFormatter;
5647function getTimeFormatter() {
5648 timeFormatter ??= new Intl.DateTimeFormat(undefined, {
5649 hour: "numeric",
5650 minute: "numeric",
5651 second: "numeric"
5652 });
5653 return timeFormatter;
5654}
5655function createLogger(level = "info", options = {}) {
5656 if (options.customLogger) {
5657 return options.customLogger;
5658 }
5659 const loggedErrors = /* @__PURE__ */ new WeakSet();
5660 const {
5661 prefix = "[vite]",
5662 allowClearScreen = true,
5663 console: console2 = globalThis.console
5664 } = options;
5665 const thresh = LogLevels[level];
5666 const canClearScreen = allowClearScreen && process.stdout.isTTY && !process.env.CI;
5667 const clear = canClearScreen ? clearScreen : () => {
5668 };
5669 function format(type, msg, options2 = {}) {
5670 if (options2.timestamp) {
5671 let tag = "";
5672 if (type === "info") {
5673 tag = colors.cyan(colors.bold(prefix));
5674 } else if (type === "warn") {
5675 tag = colors.yellow(colors.bold(prefix));
5676 } else {
5677 tag = colors.red(colors.bold(prefix));
5678 }
5679 const environment = options2.environment ? options2.environment + " " : "";
5680 return `${colors.dim(getTimeFormatter().format(/* @__PURE__ */ new Date()))} ${tag} ${environment}${msg}`;
5681 } else {
5682 return msg;
5683 }
5684 }
5685 function output(type, msg, options2 = {}) {
5686 if (thresh >= LogLevels[type]) {
5687 const method = type === "info" ? "log" : type;
5688 if (options2.error) {
5689 loggedErrors.add(options2.error);
5690 }
5691 if (canClearScreen) {
5692 if (type === lastType && msg === lastMsg) {
5693 sameCount++;
5694 clear();
5695 console2[method](
5696 format(type, msg, options2),
5697 colors.yellow(`(x${sameCount + 1})`)
5698 );
5699 } else {
5700 sameCount = 0;
5701 lastMsg = msg;
5702 lastType = type;
5703 if (options2.clear) {
5704 clear();
5705 }
5706 console2[method](format(type, msg, options2));
5707 }
5708 } else {
5709 console2[method](format(type, msg, options2));
5710 }
5711 }
5712 }
5713 const warnedMessages = /* @__PURE__ */ new Set();
5714 const logger = {
5715 hasWarned: false,
5716 info(msg, opts) {
5717 output("info", msg, opts);
5718 },
5719 warn(msg, opts) {
5720 logger.hasWarned = true;
5721 output("warn", msg, opts);
5722 },
5723 warnOnce(msg, opts) {
5724 if (warnedMessages.has(msg)) return;
5725 logger.hasWarned = true;
5726 output("warn", msg, opts);
5727 warnedMessages.add(msg);
5728 },
5729 error(msg, opts) {
5730 logger.hasWarned = true;
5731 output("error", msg, opts);
5732 },
5733 clearScreen(type) {
5734 if (thresh >= LogLevels[type]) {
5735 clear();
5736 }
5737 },
5738 hasErrorLogged(error) {
5739 return loggedErrors.has(error);
5740 }
5741 };
5742 return logger;
5743}
5744
5745const ROOT_FILES = [
5746 // '.git',
5747 // https://pnpm.io/workspaces/
5748 "pnpm-workspace.yaml",
5749 // https://rushjs.io/pages/advanced/config_files/
5750 // 'rush.json',
5751 // https://nx.dev/latest/react/getting-started/nx-setup
5752 // 'workspace.json',
5753 // 'nx.json',
5754 // https://github.com/lerna/lerna#lernajson
5755 "lerna.json"
5756];
5757function hasWorkspacePackageJSON(root) {
5758 const path = path$1.join(root, "package.json");
5759 if (!isFileReadable(path)) {
5760 return false;
5761 }
5762 try {
5763 const content = JSON.parse(fs$1.readFileSync(path, "utf-8")) || {};
5764 return !!content.workspaces;
5765 } catch {
5766 return false;
5767 }
5768}
5769function hasRootFile(root) {
5770 return ROOT_FILES.some((file) => fs$1.existsSync(path$1.join(root, file)));
5771}
5772function hasPackageJSON(root) {
5773 const path = path$1.join(root, "package.json");
5774 return fs$1.existsSync(path);
5775}
5776function searchForPackageRoot(current, root = current) {
5777 if (hasPackageJSON(current)) return current;
5778 const dir = path$1.dirname(current);
5779 if (!dir || dir === current) return root;
5780 return searchForPackageRoot(dir, root);
5781}
5782function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
5783 if (hasRootFile(current)) return current;
5784 if (hasWorkspacePackageJSON(current)) return current;
5785 const dir = path$1.dirname(current);
5786 if (!dir || dir === current) return root;
5787 return searchForWorkspaceRoot(dir, root);
5788}
5789
5790function isFileServingAllowed(configOrUrl, urlOrServer) {
5791 const config = typeof urlOrServer === "string" ? configOrUrl : urlOrServer.config;
5792 const url = typeof urlOrServer === "string" ? urlOrServer : configOrUrl;
5793 if (!config.server.fs.strict) return true;
5794 const filePath = fsPathFromUrl(url);
5795 return isFileLoadingAllowed(config, filePath);
5796}
5797function isUriInFilePath(uri, filePath) {
5798 return isSameFileUri(uri, filePath) || isParentDirectory(uri, filePath);
5799}
5800function isFileLoadingAllowed(config, filePath) {
5801 const { fs } = config.server;
5802 if (!fs.strict) return true;
5803 if (config.fsDenyGlob(filePath)) return false;
5804 if (config.safeModulePaths.has(filePath)) return true;
5805 if (fs.allow.some((uri) => isUriInFilePath(uri, filePath))) return true;
5806 return false;
5807}
5808
5809var main$1 = {exports: {}};
5810
5811var name = "dotenv";
5812var version$1 = "16.4.7";
5813var description = "Loads environment variables from .env file";
5814var main = "lib/main.js";
5815var types = "lib/main.d.ts";
5816var exports$1 = {
5817 ".": {
5818 types: "./lib/main.d.ts",
5819 require: "./lib/main.js",
5820 "default": "./lib/main.js"
5821 },
5822 "./config": "./config.js",
5823 "./config.js": "./config.js",
5824 "./lib/env-options": "./lib/env-options.js",
5825 "./lib/env-options.js": "./lib/env-options.js",
5826 "./lib/cli-options": "./lib/cli-options.js",
5827 "./lib/cli-options.js": "./lib/cli-options.js",
5828 "./package.json": "./package.json"
5829};
5830var scripts = {
5831 "dts-check": "tsc --project tests/types/tsconfig.json",
5832 lint: "standard",
5833 pretest: "npm run lint && npm run dts-check",
5834 test: "tap run --allow-empty-coverage --disable-coverage --timeout=60000",
5835 "test:coverage": "tap run --show-full-coverage --timeout=60000 --coverage-report=lcov",
5836 prerelease: "npm test",
5837 release: "standard-version"
5838};
5839var repository = {
5840 type: "git",
5841 url: "git://github.com/motdotla/dotenv.git"
5842};
5843var funding = "https://dotenvx.com";
5844var keywords = [
5845 "dotenv",
5846 "env",
5847 ".env",
5848 "environment",
5849 "variables",
5850 "config",
5851 "settings"
5852];
5853var readmeFilename = "README.md";
5854var license = "BSD-2-Clause";
5855var devDependencies = {
5856 "@types/node": "^18.11.3",
5857 decache: "^4.6.2",
5858 sinon: "^14.0.1",
5859 standard: "^17.0.0",
5860 "standard-version": "^9.5.0",
5861 tap: "^19.2.0",
5862 typescript: "^4.8.4"
5863};
5864var engines = {
5865 node: ">=12"
5866};
5867var browser = {
5868 fs: false
5869};
5870var require$$4 = {
5871 name: name,
5872 version: version$1,
5873 description: description,
5874 main: main,
5875 types: types,
5876 exports: exports$1,
5877 scripts: scripts,
5878 repository: repository,
5879 funding: funding,
5880 keywords: keywords,
5881 readmeFilename: readmeFilename,
5882 license: license,
5883 devDependencies: devDependencies,
5884 engines: engines,
5885 browser: browser
5886};
5887
5888const fs = require$$1$2;
5889const path = require$$1$1;
5890const os = require$$2;
5891const crypto = require$$0$1;
5892const packageJson = require$$4;
5893
5894const version = packageJson.version;
5895
5896const LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
5897
5898// Parse src into an Object
5899function parse (src) {
5900 const obj = {};
5901
5902 // Convert buffer to string
5903 let lines = src.toString();
5904
5905 // Convert line breaks to same format
5906 lines = lines.replace(/\r\n?/mg, '\n');
5907
5908 let match;
5909 while ((match = LINE.exec(lines)) != null) {
5910 const key = match[1];
5911
5912 // Default undefined or null to empty string
5913 let value = (match[2] || '');
5914
5915 // Remove whitespace
5916 value = value.trim();
5917
5918 // Check if double quoted
5919 const maybeQuote = value[0];
5920
5921 // Remove surrounding quotes
5922 value = value.replace(/^(['"`])([\s\S]*)\1$/mg, '$2');
5923
5924 // Expand newlines if double quoted
5925 if (maybeQuote === '"') {
5926 value = value.replace(/\\n/g, '\n');
5927 value = value.replace(/\\r/g, '\r');
5928 }
5929
5930 // Add to object
5931 obj[key] = value;
5932 }
5933
5934 return obj
5935}
5936
5937function _parseVault (options) {
5938 const vaultPath = _vaultPath(options);
5939
5940 // Parse .env.vault
5941 const result = DotenvModule.configDotenv({ path: vaultPath });
5942 if (!result.parsed) {
5943 const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
5944 err.code = 'MISSING_DATA';
5945 throw err
5946 }
5947
5948 // handle scenario for comma separated keys - for use with key rotation
5949 // example: DOTENV_KEY="dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=prod,dotenv://:key_7890@dotenvx.com/vault/.env.vault?environment=prod"
5950 const keys = _dotenvKey(options).split(',');
5951 const length = keys.length;
5952
5953 let decrypted;
5954 for (let i = 0; i < length; i++) {
5955 try {
5956 // Get full key
5957 const key = keys[i].trim();
5958
5959 // Get instructions for decrypt
5960 const attrs = _instructions(result, key);
5961
5962 // Decrypt
5963 decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
5964
5965 break
5966 } catch (error) {
5967 // last key
5968 if (i + 1 >= length) {
5969 throw error
5970 }
5971 // try next key
5972 }
5973 }
5974
5975 // Parse decrypted .env string
5976 return DotenvModule.parse(decrypted)
5977}
5978
5979function _log (message) {
5980 console.log(`[dotenv@${version}][INFO] ${message}`);
5981}
5982
5983function _warn (message) {
5984 console.log(`[dotenv@${version}][WARN] ${message}`);
5985}
5986
5987function _debug (message) {
5988 console.log(`[dotenv@${version}][DEBUG] ${message}`);
5989}
5990
5991function _dotenvKey (options) {
5992 // prioritize developer directly setting options.DOTENV_KEY
5993 if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
5994 return options.DOTENV_KEY
5995 }
5996
5997 // secondary infra already contains a DOTENV_KEY environment variable
5998 if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
5999 return process.env.DOTENV_KEY
6000 }
6001
6002 // fallback to empty string
6003 return ''
6004}
6005
6006function _instructions (result, dotenvKey) {
6007 // Parse DOTENV_KEY. Format is a URI
6008 let uri;
6009 try {
6010 uri = new URL(dotenvKey);
6011 } catch (error) {
6012 if (error.code === 'ERR_INVALID_URL') {
6013 const err = new Error('INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development');
6014 err.code = 'INVALID_DOTENV_KEY';
6015 throw err
6016 }
6017
6018 throw error
6019 }
6020
6021 // Get decrypt key
6022 const key = uri.password;
6023 if (!key) {
6024 const err = new Error('INVALID_DOTENV_KEY: Missing key part');
6025 err.code = 'INVALID_DOTENV_KEY';
6026 throw err
6027 }
6028
6029 // Get environment
6030 const environment = uri.searchParams.get('environment');
6031 if (!environment) {
6032 const err = new Error('INVALID_DOTENV_KEY: Missing environment part');
6033 err.code = 'INVALID_DOTENV_KEY';
6034 throw err
6035 }
6036
6037 // Get ciphertext payload
6038 const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
6039 const ciphertext = result.parsed[environmentKey]; // DOTENV_VAULT_PRODUCTION
6040 if (!ciphertext) {
6041 const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
6042 err.code = 'NOT_FOUND_DOTENV_ENVIRONMENT';
6043 throw err
6044 }
6045
6046 return { ciphertext, key }
6047}
6048
6049function _vaultPath (options) {
6050 let possibleVaultPath = null;
6051
6052 if (options && options.path && options.path.length > 0) {
6053 if (Array.isArray(options.path)) {
6054 for (const filepath of options.path) {
6055 if (fs.existsSync(filepath)) {
6056 possibleVaultPath = filepath.endsWith('.vault') ? filepath : `${filepath}.vault`;
6057 }
6058 }
6059 } else {
6060 possibleVaultPath = options.path.endsWith('.vault') ? options.path : `${options.path}.vault`;
6061 }
6062 } else {
6063 possibleVaultPath = path.resolve(process.cwd(), '.env.vault');
6064 }
6065
6066 if (fs.existsSync(possibleVaultPath)) {
6067 return possibleVaultPath
6068 }
6069
6070 return null
6071}
6072
6073function _resolveHome (envPath) {
6074 return envPath[0] === '~' ? path.join(os.homedir(), envPath.slice(1)) : envPath
6075}
6076
6077function _configVault (options) {
6078 _log('Loading env from encrypted .env.vault');
6079
6080 const parsed = DotenvModule._parseVault(options);
6081
6082 let processEnv = process.env;
6083 if (options && options.processEnv != null) {
6084 processEnv = options.processEnv;
6085 }
6086
6087 DotenvModule.populate(processEnv, parsed, options);
6088
6089 return { parsed }
6090}
6091
6092function configDotenv (options) {
6093 const dotenvPath = path.resolve(process.cwd(), '.env');
6094 let encoding = 'utf8';
6095 const debug = Boolean(options && options.debug);
6096
6097 if (options && options.encoding) {
6098 encoding = options.encoding;
6099 } else {
6100 if (debug) {
6101 _debug('No encoding is specified. UTF-8 is used by default');
6102 }
6103 }
6104
6105 let optionPaths = [dotenvPath]; // default, look for .env
6106 if (options && options.path) {
6107 if (!Array.isArray(options.path)) {
6108 optionPaths = [_resolveHome(options.path)];
6109 } else {
6110 optionPaths = []; // reset default
6111 for (const filepath of options.path) {
6112 optionPaths.push(_resolveHome(filepath));
6113 }
6114 }
6115 }
6116
6117 // Build the parsed data in a temporary object (because we need to return it). Once we have the final
6118 // parsed data, we will combine it with process.env (or options.processEnv if provided).
6119 let lastError;
6120 const parsedAll = {};
6121 for (const path of optionPaths) {
6122 try {
6123 // Specifying an encoding returns a string instead of a buffer
6124 const parsed = DotenvModule.parse(fs.readFileSync(path, { encoding }));
6125
6126 DotenvModule.populate(parsedAll, parsed, options);
6127 } catch (e) {
6128 if (debug) {
6129 _debug(`Failed to load ${path} ${e.message}`);
6130 }
6131 lastError = e;
6132 }
6133 }
6134
6135 let processEnv = process.env;
6136 if (options && options.processEnv != null) {
6137 processEnv = options.processEnv;
6138 }
6139
6140 DotenvModule.populate(processEnv, parsedAll, options);
6141
6142 if (lastError) {
6143 return { parsed: parsedAll, error: lastError }
6144 } else {
6145 return { parsed: parsedAll }
6146 }
6147}
6148
6149// Populates process.env from .env file
6150function config (options) {
6151 // fallback to original dotenv if DOTENV_KEY is not set
6152 if (_dotenvKey(options).length === 0) {
6153 return DotenvModule.configDotenv(options)
6154 }
6155
6156 const vaultPath = _vaultPath(options);
6157
6158 // dotenvKey exists but .env.vault file does not exist
6159 if (!vaultPath) {
6160 _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
6161
6162 return DotenvModule.configDotenv(options)
6163 }
6164
6165 return DotenvModule._configVault(options)
6166}
6167
6168function decrypt (encrypted, keyStr) {
6169 const key = Buffer.from(keyStr.slice(-64), 'hex');
6170 let ciphertext = Buffer.from(encrypted, 'base64');
6171
6172 const nonce = ciphertext.subarray(0, 12);
6173 const authTag = ciphertext.subarray(-16);
6174 ciphertext = ciphertext.subarray(12, -16);
6175
6176 try {
6177 const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce);
6178 aesgcm.setAuthTag(authTag);
6179 return `${aesgcm.update(ciphertext)}${aesgcm.final()}`
6180 } catch (error) {
6181 const isRange = error instanceof RangeError;
6182 const invalidKeyLength = error.message === 'Invalid key length';
6183 const decryptionFailed = error.message === 'Unsupported state or unable to authenticate data';
6184
6185 if (isRange || invalidKeyLength) {
6186 const err = new Error('INVALID_DOTENV_KEY: It must be 64 characters long (or more)');
6187 err.code = 'INVALID_DOTENV_KEY';
6188 throw err
6189 } else if (decryptionFailed) {
6190 const err = new Error('DECRYPTION_FAILED: Please check your DOTENV_KEY');
6191 err.code = 'DECRYPTION_FAILED';
6192 throw err
6193 } else {
6194 throw error
6195 }
6196 }
6197}
6198
6199// Populate process.env with parsed values
6200function populate (processEnv, parsed, options = {}) {
6201 const debug = Boolean(options && options.debug);
6202 const override = Boolean(options && options.override);
6203
6204 if (typeof parsed !== 'object') {
6205 const err = new Error('OBJECT_REQUIRED: Please check the processEnv argument being passed to populate');
6206 err.code = 'OBJECT_REQUIRED';
6207 throw err
6208 }
6209
6210 // Set process.env
6211 for (const key of Object.keys(parsed)) {
6212 if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
6213 if (override === true) {
6214 processEnv[key] = parsed[key];
6215 }
6216
6217 if (debug) {
6218 if (override === true) {
6219 _debug(`"${key}" is already defined and WAS overwritten`);
6220 } else {
6221 _debug(`"${key}" is already defined and was NOT overwritten`);
6222 }
6223 }
6224 } else {
6225 processEnv[key] = parsed[key];
6226 }
6227 }
6228}
6229
6230const DotenvModule = {
6231 configDotenv,
6232 _configVault,
6233 _parseVault,
6234 config,
6235 decrypt,
6236 parse,
6237 populate
6238};
6239
6240main$1.exports.configDotenv = DotenvModule.configDotenv;
6241main$1.exports._configVault = DotenvModule._configVault;
6242main$1.exports._parseVault = DotenvModule._parseVault;
6243main$1.exports.config = DotenvModule.config;
6244main$1.exports.decrypt = DotenvModule.decrypt;
6245var parse_1 = main$1.exports.parse = DotenvModule.parse;
6246main$1.exports.populate = DotenvModule.populate;
6247
6248main$1.exports = DotenvModule;
6249
6250function _resolveEscapeSequences (value) {
6251 return value.replace(/\\\$/g, '$')
6252}
6253
6254function expandValue (value, processEnv, runningParsed) {
6255 const env = { ...runningParsed, ...processEnv }; // process.env wins
6256
6257 const regex = /(?<!\\)\${([^{}]+)}|(?<!\\)\$([A-Za-z_][A-Za-z0-9_]*)/g;
6258
6259 let result = value;
6260 let match;
6261 const seen = new Set(); // self-referential checker
6262
6263 while ((match = regex.exec(result)) !== null) {
6264 seen.add(result);
6265
6266 const [template, bracedExpression, unbracedExpression] = match;
6267 const expression = bracedExpression || unbracedExpression;
6268
6269 // match the operators `:+`, `+`, `:-`, and `-`
6270 const opRegex = /(:\+|\+|:-|-)/;
6271 // find first match
6272 const opMatch = expression.match(opRegex);
6273 const splitter = opMatch ? opMatch[0] : null;
6274
6275 const r = expression.split(splitter);
6276
6277 let defaultValue;
6278 let value;
6279
6280 const key = r.shift();
6281
6282 if ([':+', '+'].includes(splitter)) {
6283 defaultValue = env[key] ? r.join(splitter) : '';
6284 value = null;
6285 } else {
6286 defaultValue = r.join(splitter);
6287 value = env[key];
6288 }
6289
6290 if (value) {
6291 // self-referential check
6292 if (seen.has(value)) {
6293 result = result.replace(template, defaultValue);
6294 } else {
6295 result = result.replace(template, value);
6296 }
6297 } else {
6298 result = result.replace(template, defaultValue);
6299 }
6300
6301 // if the result equaled what was in process.env and runningParsed then stop expanding
6302 if (result === runningParsed[key]) {
6303 break
6304 }
6305
6306 regex.lastIndex = 0; // reset regex search position to re-evaluate after each replacement
6307 }
6308
6309 return result
6310}
6311
6312function expand (options) {
6313 // for use with progressive expansion
6314 // const runningParsed = {}
6315
6316 let processEnv = process.env;
6317 if (options && options.processEnv != null) {
6318 processEnv = options.processEnv;
6319 }
6320
6321 // dotenv.config() ran before this so the assumption is process.env has already been set
6322 for (const key in options.parsed) {
6323 let value = options.parsed[key];
6324
6325 // short-circuit scenario: process.env was already set prior to the file value
6326 if (processEnv[key] && processEnv[key] !== value) {
6327 value = processEnv[key];
6328 } else {
6329 // PATCH: we pass options.parsed instead of runningParsed
6330 // to allow variables declared in other files to be used
6331 value = expandValue(value, processEnv, options.parsed);
6332 }
6333
6334 options.parsed[key] = _resolveEscapeSequences(value);
6335
6336 // for use with progressive expansion
6337 // runningParsed[key] = _resolveEscapeSequences(value)
6338 }
6339
6340 for (const processKey in options.parsed) {
6341 processEnv[processKey] = options.parsed[processKey];
6342 }
6343
6344 return options
6345}
6346
6347var expand_1 = expand;
6348
6349function getEnvFilesForMode(mode, envDir) {
6350 return [
6351 /** default file */
6352 `.env`,
6353 /** local file */
6354 `.env.local`,
6355 /** mode file */
6356 `.env.${mode}`,
6357 /** mode local file */
6358 `.env.${mode}.local`
6359 ].map((file) => normalizePath(path$1.join(envDir, file)));
6360}
6361function loadEnv(mode, envDir, prefixes = "VITE_") {
6362 if (mode === "local") {
6363 throw new Error(
6364 `"local" cannot be used as a mode name because it conflicts with the .local postfix for .env files.`
6365 );
6366 }
6367 prefixes = arraify(prefixes);
6368 const env = {};
6369 const envFiles = getEnvFilesForMode(mode, envDir);
6370 const parsed = Object.fromEntries(
6371 envFiles.flatMap((filePath) => {
6372 if (!tryStatSync(filePath)?.isFile()) return [];
6373 return Object.entries(parse_1(fs$1.readFileSync(filePath)));
6374 })
6375 );
6376 if (parsed.NODE_ENV && process.env.VITE_USER_NODE_ENV === undefined) {
6377 process.env.VITE_USER_NODE_ENV = parsed.NODE_ENV;
6378 }
6379 if (parsed.BROWSER && process.env.BROWSER === undefined) {
6380 process.env.BROWSER = parsed.BROWSER;
6381 }
6382 if (parsed.BROWSER_ARGS && process.env.BROWSER_ARGS === undefined) {
6383 process.env.BROWSER_ARGS = parsed.BROWSER_ARGS;
6384 }
6385 const processEnv = { ...process.env };
6386 expand_1({ parsed, processEnv });
6387 for (const [key, value] of Object.entries(parsed)) {
6388 if (prefixes.some((prefix) => key.startsWith(prefix))) {
6389 env[key] = value;
6390 }
6391 }
6392 for (const key in process.env) {
6393 if (prefixes.some((prefix) => key.startsWith(prefix))) {
6394 env[key] = process.env[key];
6395 }
6396 }
6397 return env;
6398}
6399function resolveEnvPrefix({
6400 envPrefix = "VITE_"
6401}) {
6402 envPrefix = arraify(envPrefix);
6403 if (envPrefix.includes("")) {
6404 throw new Error(
6405 `envPrefix option contains value '', which could lead unexpected exposure of sensitive information.`
6406 );
6407 }
6408 return envPrefix;
6409}
6410
6411exports.esbuildVersion = esbuild.version;
6412exports.createFilter = createFilter;
6413exports.createLogger = createLogger;
6414exports.defaultAllowedOrigins = defaultAllowedOrigins;
6415exports.defaultClientConditions = DEFAULT_CLIENT_CONDITIONS;
6416exports.defaultClientMainFields = DEFAULT_CLIENT_MAIN_FIELDS;
6417exports.defaultServerConditions = DEFAULT_SERVER_CONDITIONS;
6418exports.defaultServerMainFields = DEFAULT_SERVER_MAIN_FIELDS;
6419exports.isCSSRequest = isCSSRequest;
6420exports.isFileLoadingAllowed = isFileLoadingAllowed;
6421exports.isFileServingAllowed = isFileServingAllowed;
6422exports.loadEnv = loadEnv;
6423exports.mergeAlias = mergeAlias;
6424exports.mergeConfig = mergeConfig;
6425exports.normalizePath = normalizePath;
6426exports.perEnvironmentPlugin = perEnvironmentPlugin;
6427exports.perEnvironmentState = perEnvironmentState;
6428exports.resolveEnvPrefix = resolveEnvPrefix;
6429exports.rollupVersion = rollupVersion;
6430exports.searchForWorkspaceRoot = searchForWorkspaceRoot;
6431exports.send = send;
6432exports.splitVendorChunk = splitVendorChunk;
6433exports.splitVendorChunkPlugin = splitVendorChunkPlugin;
6434exports.version = VERSION;
Note: See TracBrowser for help on using the repository browser.