fluxion-ts 0.2.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,487 +1,10 @@
1
1
  import fs from 'node:fs';
2
- import path from 'node:path';
2
+ import path$1 from 'node:path';
3
3
  import cluster from 'node:cluster';
4
4
  import os from 'node:os';
5
5
  import http from 'node:http';
6
6
  import https from 'node:https';
7
7
 
8
- const ANSI_BACKGROUND_OFFSET = 10;
9
-
10
- const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`;
11
-
12
- const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`;
13
-
14
- const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`;
15
-
16
- const styles$1 = {
17
- modifier: {
18
- reset: [0, 0],
19
- // 21 isn't widely supported and 22 does the same thing
20
- bold: [1, 22],
21
- dim: [2, 22],
22
- italic: [3, 23],
23
- underline: [4, 24],
24
- overline: [53, 55],
25
- inverse: [7, 27],
26
- hidden: [8, 28],
27
- strikethrough: [9, 29],
28
- },
29
- color: {
30
- black: [30, 39],
31
- red: [31, 39],
32
- green: [32, 39],
33
- yellow: [33, 39],
34
- blue: [34, 39],
35
- magenta: [35, 39],
36
- cyan: [36, 39],
37
- white: [37, 39],
38
-
39
- // Bright color
40
- blackBright: [90, 39],
41
- gray: [90, 39], // Alias of `blackBright`
42
- grey: [90, 39], // Alias of `blackBright`
43
- redBright: [91, 39],
44
- greenBright: [92, 39],
45
- yellowBright: [93, 39],
46
- blueBright: [94, 39],
47
- magentaBright: [95, 39],
48
- cyanBright: [96, 39],
49
- whiteBright: [97, 39],
50
- },
51
- bgColor: {
52
- bgBlack: [40, 49],
53
- bgRed: [41, 49],
54
- bgGreen: [42, 49],
55
- bgYellow: [43, 49],
56
- bgBlue: [44, 49],
57
- bgMagenta: [45, 49],
58
- bgCyan: [46, 49],
59
- bgWhite: [47, 49],
60
-
61
- // Bright color
62
- bgBlackBright: [100, 49],
63
- bgGray: [100, 49], // Alias of `bgBlackBright`
64
- bgGrey: [100, 49], // Alias of `bgBlackBright`
65
- bgRedBright: [101, 49],
66
- bgGreenBright: [102, 49],
67
- bgYellowBright: [103, 49],
68
- bgBlueBright: [104, 49],
69
- bgMagentaBright: [105, 49],
70
- bgCyanBright: [106, 49],
71
- bgWhiteBright: [107, 49],
72
- },
73
- };
74
-
75
- Object.keys(styles$1.modifier);
76
- const foregroundColorNames = Object.keys(styles$1.color);
77
- const backgroundColorNames = Object.keys(styles$1.bgColor);
78
- [...foregroundColorNames, ...backgroundColorNames];
79
-
80
- function assembleStyles() {
81
- const codes = new Map();
82
-
83
- for (const [groupName, group] of Object.entries(styles$1)) {
84
- for (const [styleName, style] of Object.entries(group)) {
85
- styles$1[styleName] = {
86
- open: `\u001B[${style[0]}m`,
87
- close: `\u001B[${style[1]}m`,
88
- };
89
-
90
- group[styleName] = styles$1[styleName];
91
-
92
- codes.set(style[0], style[1]);
93
- }
94
-
95
- Object.defineProperty(styles$1, groupName, {
96
- value: group,
97
- enumerable: false,
98
- });
99
- }
100
-
101
- Object.defineProperty(styles$1, 'codes', {
102
- value: codes,
103
- enumerable: false,
104
- });
105
-
106
- styles$1.color.close = '\u001B[39m';
107
- styles$1.bgColor.close = '\u001B[49m';
108
-
109
- styles$1.color.ansi = wrapAnsi16();
110
- styles$1.color.ansi256 = wrapAnsi256();
111
- styles$1.color.ansi16m = wrapAnsi16m();
112
- styles$1.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
113
- styles$1.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
114
- styles$1.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
115
-
116
- // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js
117
- Object.defineProperties(styles$1, {
118
- rgbToAnsi256: {
119
- value(red, green, blue) {
120
- // We use the extended greyscale palette here, with the exception of
121
- // black and white. normal palette only has 4 greyscale shades.
122
- if (red === green && green === blue) {
123
- if (red < 8) {
124
- return 16;
125
- }
126
-
127
- if (red > 248) {
128
- return 231;
129
- }
130
-
131
- return Math.round(((red - 8) / 247) * 24) + 232;
132
- }
133
-
134
- return 16
135
- + (36 * Math.round(red / 255 * 5))
136
- + (6 * Math.round(green / 255 * 5))
137
- + Math.round(blue / 255 * 5);
138
- },
139
- enumerable: false,
140
- },
141
- hexToRgb: {
142
- value(hex) {
143
- const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
144
- if (!matches) {
145
- return [0, 0, 0];
146
- }
147
-
148
- let [colorString] = matches;
149
-
150
- if (colorString.length === 3) {
151
- colorString = [...colorString].map(character => character + character).join('');
152
- }
153
-
154
- const integer = Number.parseInt(colorString, 16);
155
-
156
- return [
157
- /* eslint-disable no-bitwise */
158
- (integer >> 16) & 0xFF,
159
- (integer >> 8) & 0xFF,
160
- integer & 0xFF,
161
- /* eslint-enable no-bitwise */
162
- ];
163
- },
164
- enumerable: false,
165
- },
166
- hexToAnsi256: {
167
- value: hex => styles$1.rgbToAnsi256(...styles$1.hexToRgb(hex)),
168
- enumerable: false,
169
- },
170
- ansi256ToAnsi: {
171
- value(code) {
172
- if (code < 8) {
173
- return 30 + code;
174
- }
175
-
176
- if (code < 16) {
177
- return 90 + (code - 8);
178
- }
179
-
180
- let red;
181
- let green;
182
- let blue;
183
-
184
- if (code >= 232) {
185
- red = (((code - 232) * 10) + 8) / 255;
186
- green = red;
187
- blue = red;
188
- } else {
189
- code -= 16;
190
-
191
- const remainder = code % 36;
192
-
193
- red = Math.floor(code / 36) / 5;
194
- green = Math.floor(remainder / 6) / 5;
195
- blue = (remainder % 6) / 5;
196
- }
197
-
198
- const value = Math.max(red, green, blue) * 2;
199
-
200
- if (value === 0) {
201
- return 30;
202
- }
203
-
204
- // eslint-disable-next-line no-bitwise
205
- let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));
206
-
207
- if (value === 2) {
208
- result += 60;
209
- }
210
-
211
- return result;
212
- },
213
- enumerable: false,
214
- },
215
- rgbToAnsi: {
216
- value: (red, green, blue) => styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(red, green, blue)),
217
- enumerable: false,
218
- },
219
- hexToAnsi: {
220
- value: hex => styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(hex)),
221
- enumerable: false,
222
- },
223
- });
224
-
225
- return styles$1;
226
- }
227
-
228
- const ansiStyles = assembleStyles();
229
-
230
- /* eslint-env browser */
231
-
232
- const level = (() => {
233
- if (!('navigator' in globalThis)) {
234
- return 0;
235
- }
236
-
237
- if (globalThis.navigator.userAgentData) {
238
- const brand = navigator.userAgentData.brands.find(({brand}) => brand === 'Chromium');
239
- if (brand && brand.version > 93) {
240
- return 3;
241
- }
242
- }
243
-
244
- if (/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)) {
245
- return 1;
246
- }
247
-
248
- return 0;
249
- })();
250
-
251
- const colorSupport = level !== 0 && {
252
- level};
253
-
254
- const supportsColor = {
255
- stdout: colorSupport,
256
- stderr: colorSupport,
257
- };
258
-
259
- // TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.
260
- function stringReplaceAll(string, substring, replacer) {
261
- let index = string.indexOf(substring);
262
- if (index === -1) {
263
- return string;
264
- }
265
-
266
- const substringLength = substring.length;
267
- let endIndex = 0;
268
- let returnValue = '';
269
- do {
270
- returnValue += string.slice(endIndex, index) + substring + replacer;
271
- endIndex = index + substringLength;
272
- index = string.indexOf(substring, endIndex);
273
- } while (index !== -1);
274
-
275
- returnValue += string.slice(endIndex);
276
- return returnValue;
277
- }
278
-
279
- function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
280
- let endIndex = 0;
281
- let returnValue = '';
282
- do {
283
- const gotCR = string[index - 1] === '\r';
284
- returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
285
- endIndex = index + 1;
286
- index = string.indexOf('\n', endIndex);
287
- } while (index !== -1);
288
-
289
- returnValue += string.slice(endIndex);
290
- return returnValue;
291
- }
292
-
293
- const {stdout: stdoutColor, stderr: stderrColor} = supportsColor;
294
-
295
- const GENERATOR = Symbol('GENERATOR');
296
- const STYLER = Symbol('STYLER');
297
- const IS_EMPTY = Symbol('IS_EMPTY');
298
-
299
- // `supportsColor.level` → `ansiStyles.color[name]` mapping
300
- const levelMapping = [
301
- 'ansi',
302
- 'ansi',
303
- 'ansi256',
304
- 'ansi16m',
305
- ];
306
-
307
- const styles = Object.create(null);
308
-
309
- const applyOptions = (object, options = {}) => {
310
- if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
311
- throw new Error('The `level` option should be an integer from 0 to 3');
312
- }
313
-
314
- // Detect level if not set manually
315
- const colorLevel = stdoutColor ? stdoutColor.level : 0;
316
- object.level = options.level === undefined ? colorLevel : options.level;
317
- };
318
-
319
- const chalkFactory = options => {
320
- const chalk = (...strings) => strings.join(' ');
321
- applyOptions(chalk, options);
322
-
323
- Object.setPrototypeOf(chalk, createChalk.prototype);
324
-
325
- return chalk;
326
- };
327
-
328
- function createChalk(options) {
329
- return chalkFactory(options);
330
- }
331
-
332
- Object.setPrototypeOf(createChalk.prototype, Function.prototype);
333
-
334
- for (const [styleName, style] of Object.entries(ansiStyles)) {
335
- styles[styleName] = {
336
- get() {
337
- const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
338
- Object.defineProperty(this, styleName, {value: builder});
339
- return builder;
340
- },
341
- };
342
- }
343
-
344
- styles.visible = {
345
- get() {
346
- const builder = createBuilder(this, this[STYLER], true);
347
- Object.defineProperty(this, 'visible', {value: builder});
348
- return builder;
349
- },
350
- };
351
-
352
- const getModelAnsi = (model, level, type, ...arguments_) => {
353
- if (model === 'rgb') {
354
- if (level === 'ansi16m') {
355
- return ansiStyles[type].ansi16m(...arguments_);
356
- }
357
-
358
- if (level === 'ansi256') {
359
- return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));
360
- }
361
-
362
- return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));
363
- }
364
-
365
- if (model === 'hex') {
366
- return getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));
367
- }
368
-
369
- return ansiStyles[type][model](...arguments_);
370
- };
371
-
372
- const usedModels = ['rgb', 'hex', 'ansi256'];
373
-
374
- for (const model of usedModels) {
375
- styles[model] = {
376
- get() {
377
- const {level} = this;
378
- return function (...arguments_) {
379
- const styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);
380
- return createBuilder(this, styler, this[IS_EMPTY]);
381
- };
382
- },
383
- };
384
-
385
- const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
386
- styles[bgModel] = {
387
- get() {
388
- const {level} = this;
389
- return function (...arguments_) {
390
- const styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);
391
- return createBuilder(this, styler, this[IS_EMPTY]);
392
- };
393
- },
394
- };
395
- }
396
-
397
- const proto = Object.defineProperties(() => {}, {
398
- ...styles,
399
- level: {
400
- enumerable: true,
401
- get() {
402
- return this[GENERATOR].level;
403
- },
404
- set(level) {
405
- this[GENERATOR].level = level;
406
- },
407
- },
408
- });
409
-
410
- const createStyler = (open, close, parent) => {
411
- let openAll;
412
- let closeAll;
413
- if (parent === undefined) {
414
- openAll = open;
415
- closeAll = close;
416
- } else {
417
- openAll = parent.openAll + open;
418
- closeAll = close + parent.closeAll;
419
- }
420
-
421
- return {
422
- open,
423
- close,
424
- openAll,
425
- closeAll,
426
- parent,
427
- };
428
- };
429
-
430
- const createBuilder = (self, _styler, _isEmpty) => {
431
- // Single argument is hot path, implicit coercion is faster than anything
432
- // eslint-disable-next-line no-implicit-coercion
433
- const builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
434
-
435
- // We alter the prototype because we must return a function, but there is
436
- // no way to create a function with a different prototype
437
- Object.setPrototypeOf(builder, proto);
438
-
439
- builder[GENERATOR] = self;
440
- builder[STYLER] = _styler;
441
- builder[IS_EMPTY] = _isEmpty;
442
-
443
- return builder;
444
- };
445
-
446
- const applyStyle = (self, string) => {
447
- if (self.level <= 0 || !string) {
448
- return self[IS_EMPTY] ? '' : string;
449
- }
450
-
451
- let styler = self[STYLER];
452
-
453
- if (styler === undefined) {
454
- return string;
455
- }
456
-
457
- const {openAll, closeAll} = styler;
458
- if (string.includes('\u001B')) {
459
- while (styler !== undefined) {
460
- // Replace any instances already present with a re-opening code
461
- // otherwise only the part of the string until said closing code
462
- // will be colored, and the rest will simply be 'plain'.
463
- string = stringReplaceAll(string, styler.close, styler.open);
464
-
465
- styler = styler.parent;
466
- }
467
- }
468
-
469
- // We can move both next actions out of loop, because remaining actions in loop won't have
470
- // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
471
- // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
472
- const lfIndex = string.indexOf('\n');
473
- if (lfIndex !== -1) {
474
- string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
475
- }
476
-
477
- return openAll + string + closeAll;
478
- };
479
-
480
- Object.defineProperties(createChalk.prototype, styles);
481
-
482
- const chalk = createChalk();
483
- createChalk({level: stderrColor ? stderrColor.level : 0});
484
-
485
8
  function dtm(dt = new Date()) {
486
9
  const y = dt.getFullYear();
487
10
  const m = String(dt.getMonth() + 1).padStart(2, '0');
@@ -521,20 +44,19 @@ const safeStringify = (value) => {
521
44
  }
522
45
  };
523
46
  const ColoredLevels = {
524
- INFO: chalk.hex('#0386e3')('INFO'),
525
- WARN: chalk.hex('#fb923c')('WARN'),
526
- ERROR: chalk.hex('#ef4444')('ERROR'),
527
- SUCC: chalk.hex('#22c55e')('SUCC'),
528
- DEBUG: chalk.hex('#d327e0')('DEBUG'),
529
- VERBOSE: chalk.hex('#36ffeb')('SUCC'),
47
+ INFO: 'INFO',
48
+ WARN: 'WARN',
49
+ ERROR: 'ERROR',
50
+ SUCC: 'SUCC',
51
+ DEBUG: 'DEBUG',
52
+ VERBOSE: 'VERBOSE',
530
53
  };
531
- const TimestampColor = chalk.hex('#166534');
532
54
  const oneLineLogger = (entry) => {
533
55
  const { level: rawLevel, timestamp: rawTimestamp, event: rawEvent, message: rawMessage, ...fields } = entry;
534
- const timestamp = TimestampColor(`[${rawTimestamp}]`);
56
+ const timestamp = `[${rawTimestamp}]`;
535
57
  const level = ColoredLevels[rawLevel] ?? rawLevel;
536
58
  const body = rawMessage ?? rawEvent;
537
- const fieldsText = $keys(fields).length > 0 ? ` ${chalk.dim(safeStringify(fields))}` : '';
59
+ const fieldsText = $keys(fields).length > 0 ? ` ${safeStringify(fields)}` : '';
538
60
  console.log(`${timestamp} ${level} ${body}${fieldsText}`);
539
61
  };
540
62
  /**
@@ -670,7 +192,7 @@ function readCertificateContent(content, moduleDir) {
670
192
  // Check if it looks like a file path (not a PEM certificate)
671
193
  // PEM certificates start with "-----BEGIN"
672
194
  if (!content.startsWith('-----BEGIN')) {
673
- const filePath = path.isAbsolute(content) ? content : path.join(moduleDir, content);
195
+ const filePath = path$1.isAbsolute(content) ? content : path$1.join(moduleDir, content);
674
196
  if (fs.existsSync(filePath)) {
675
197
  return fs.readFileSync(filePath);
676
198
  }
@@ -708,7 +230,20 @@ function normalizeHttpsOptions(https, moduleDir) {
708
230
  */
709
231
  function normalizeOptions(options) {
710
232
  expect.isObject(options, 'FluxionOptions must be an object');
711
- let { dir, host, port, metaPort, injections = [], moduleDir = process.cwd(), workerOptions = {}, maxRequestBytes = 8_000_000, reloadDelay = 300, apiExts = ['.ts'], routerExclude = [], https, } = options;
233
+ let { dir, host, port, metaPort, injections = [], moduleDir = process.cwd(), workerOptions = {}, maxRequestBytes = 8_000_000, reloadDelay = 300, include = ['**/*'], apiInclude = ['**/*.ts'], exclude = [
234
+ '**/node_modules/**',
235
+ '**/.git/**',
236
+ '**/dist/**',
237
+ '**/build/**',
238
+ '**/.vscode/**',
239
+ '**/.idea/**',
240
+ '**/*.log',
241
+ '**/.DS_Store',
242
+ '**/coverage/**',
243
+ '**/.nyc_output/**',
244
+ '**/*.tmp',
245
+ '**/*.temp',
246
+ ], https, } = options;
712
247
  const logger = options.logger ?? 'one-line';
713
248
  expectLoggerOption(logger);
714
249
  expect.isString(dir, 'FluxionOptions.dir must be a string');
@@ -747,8 +282,9 @@ function normalizeOptions(options) {
747
282
  workerOptions: resolveWorkerOptions(workerOptions),
748
283
  maxRequestBytes,
749
284
  logger,
750
- apiExts,
751
- routerExclude,
285
+ include,
286
+ apiInclude,
287
+ exclude,
752
288
  https: normalizeHttpsOptions(https, moduleDir),
753
289
  };
754
290
  }
@@ -1440,12 +976,14 @@ class FluxionWatcher {
1440
976
  * Recursively register all files in the options directory.
1441
977
  */
1442
978
  init() {
1443
- const dirPath = path.join(process.cwd(), this.cx.options.dir);
979
+ const dirPath = path$1.isAbsolute(this.cx.options.dir)
980
+ ? this.cx.options.dir
981
+ : path$1.join(process.cwd(), this.cx.options.dir);
1444
982
  const registerRecursive = (dir, relativePath) => {
1445
983
  const entries = fs.readdirSync(dir, { withFileTypes: true });
1446
984
  for (const entry of entries) {
1447
- const entryPath = path.join(dir, entry.name);
1448
- const entryRelativePath = path.join(relativePath, entry.name);
985
+ const entryPath = path$1.join(dir, entry.name);
986
+ const entryRelativePath = path$1.join(relativePath, entry.name);
1449
987
  if (entry.isDirectory()) {
1450
988
  registerRecursive(entryPath, entryRelativePath);
1451
989
  }
@@ -1520,76 +1058,2502 @@ class FluxionWatcher {
1520
1058
  }
1521
1059
  }
1522
1060
 
1523
- class FluxionRouter {
1524
- constructor(cx) {
1525
- /**
1526
- * This means the request has been handled by static resource handler, and no more response should be sent.
1527
- */
1528
- this.StaticHandled = Symbol.for('fluxion.router.StaticHandled');
1529
- this.handlers = new Map();
1530
- this.cx = cx;
1061
+ const balanced = (a, b, str) => {
1062
+ const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
1063
+ const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
1064
+ const r = ma !== null && mb != null && range(ma, mb, str);
1065
+ return (r && {
1066
+ start: r[0],
1067
+ end: r[1],
1068
+ pre: str.slice(0, r[0]),
1069
+ body: str.slice(r[0] + ma.length, r[1]),
1070
+ post: str.slice(r[1] + mb.length),
1071
+ });
1072
+ };
1073
+ const maybeMatch = (reg, str) => {
1074
+ const m = str.match(reg);
1075
+ return m ? m[0] : null;
1076
+ };
1077
+ const range = (a, b, str) => {
1078
+ let begs, beg, left, right = undefined, result;
1079
+ let ai = str.indexOf(a);
1080
+ let bi = str.indexOf(b, ai + 1);
1081
+ let i = ai;
1082
+ if (ai >= 0 && bi > 0) {
1083
+ if (a === b) {
1084
+ return [ai, bi];
1085
+ }
1086
+ begs = [];
1087
+ left = str.length;
1088
+ while (i >= 0 && !result) {
1089
+ if (i === ai) {
1090
+ begs.push(i);
1091
+ ai = str.indexOf(a, i + 1);
1092
+ }
1093
+ else if (begs.length === 1) {
1094
+ const r = begs.pop();
1095
+ if (r !== undefined)
1096
+ result = [r, bi];
1097
+ }
1098
+ else {
1099
+ beg = begs.pop();
1100
+ if (beg !== undefined && beg < left) {
1101
+ left = beg;
1102
+ right = bi;
1103
+ }
1104
+ bi = str.indexOf(b, i + 1);
1105
+ }
1106
+ i = ai < bi && ai >= 0 ? ai : bi;
1107
+ }
1108
+ if (begs.length && right !== undefined) {
1109
+ result = [left, right];
1110
+ }
1531
1111
  }
1532
- makeStaticResource(filepath) {
1533
- const fullPath = path.join(this.cx.options.dir, filepath);
1534
- return async (normalized, _req, res) => {
1535
- if (normalized.method !== 'GET' && normalized.method !== 'HEAD') {
1536
- res.statusCode = 405;
1537
- res.setHeader('Allow', 'GET, HEAD');
1538
- res.end();
1539
- return;
1112
+ return result;
1113
+ };
1114
+
1115
+ const escSlash = '\0SLASH' + Math.random() + '\0';
1116
+ const escOpen = '\0OPEN' + Math.random() + '\0';
1117
+ const escClose = '\0CLOSE' + Math.random() + '\0';
1118
+ const escComma = '\0COMMA' + Math.random() + '\0';
1119
+ const escPeriod = '\0PERIOD' + Math.random() + '\0';
1120
+ const escSlashPattern = new RegExp(escSlash, 'g');
1121
+ const escOpenPattern = new RegExp(escOpen, 'g');
1122
+ const escClosePattern = new RegExp(escClose, 'g');
1123
+ const escCommaPattern = new RegExp(escComma, 'g');
1124
+ const escPeriodPattern = new RegExp(escPeriod, 'g');
1125
+ const slashPattern = /\\\\/g;
1126
+ const openPattern = /\\{/g;
1127
+ const closePattern = /\\}/g;
1128
+ const commaPattern = /\\,/g;
1129
+ const periodPattern = /\\\./g;
1130
+ const EXPANSION_MAX = 100_000;
1131
+ function numeric(str) {
1132
+ return !isNaN(str) ? parseInt(str, 10) : str.charCodeAt(0);
1133
+ }
1134
+ function escapeBraces(str) {
1135
+ return str
1136
+ .replace(slashPattern, escSlash)
1137
+ .replace(openPattern, escOpen)
1138
+ .replace(closePattern, escClose)
1139
+ .replace(commaPattern, escComma)
1140
+ .replace(periodPattern, escPeriod);
1141
+ }
1142
+ function unescapeBraces(str) {
1143
+ return str
1144
+ .replace(escSlashPattern, '\\')
1145
+ .replace(escOpenPattern, '{')
1146
+ .replace(escClosePattern, '}')
1147
+ .replace(escCommaPattern, ',')
1148
+ .replace(escPeriodPattern, '.');
1149
+ }
1150
+ /**
1151
+ * Basically just str.split(","), but handling cases
1152
+ * where we have nested braced sections, which should be
1153
+ * treated as individual members, like {a,{b,c},d}
1154
+ */
1155
+ function parseCommaParts(str) {
1156
+ if (!str) {
1157
+ return [''];
1158
+ }
1159
+ const parts = [];
1160
+ const m = balanced('{', '}', str);
1161
+ if (!m) {
1162
+ return str.split(',');
1163
+ }
1164
+ const { pre, body, post } = m;
1165
+ const p = pre.split(',');
1166
+ p[p.length - 1] += '{' + body + '}';
1167
+ const postParts = parseCommaParts(post);
1168
+ if (post.length) {
1169
+ p[p.length - 1] += postParts.shift();
1170
+ p.push.apply(p, postParts);
1171
+ }
1172
+ parts.push.apply(parts, p);
1173
+ return parts;
1174
+ }
1175
+ function expand(str, options = {}) {
1176
+ if (!str) {
1177
+ return [];
1178
+ }
1179
+ const { max = EXPANSION_MAX } = options;
1180
+ // I don't know why Bash 4.3 does this, but it does.
1181
+ // Anything starting with {} will have the first two bytes preserved
1182
+ // but *only* at the top level, so {},a}b will not expand to anything,
1183
+ // but a{},b}c will be expanded to [a}c,abc].
1184
+ // One could argue that this is a bug in Bash, but since the goal of
1185
+ // this module is to match Bash's rules, we escape a leading {}
1186
+ if (str.slice(0, 2) === '{}') {
1187
+ str = '\\{\\}' + str.slice(2);
1188
+ }
1189
+ return expand_(escapeBraces(str), max, true).map(unescapeBraces);
1190
+ }
1191
+ function embrace(str) {
1192
+ return '{' + str + '}';
1193
+ }
1194
+ function isPadded(el) {
1195
+ return /^-?0\d/.test(el);
1196
+ }
1197
+ function lte(i, y) {
1198
+ return i <= y;
1199
+ }
1200
+ function gte(i, y) {
1201
+ return i >= y;
1202
+ }
1203
+ function expand_(str, max, isTop) {
1204
+ /** @type {string[]} */
1205
+ const expansions = [];
1206
+ const m = balanced('{', '}', str);
1207
+ if (!m)
1208
+ return [str];
1209
+ // no need to expand pre, since it is guaranteed to be free of brace-sets
1210
+ const pre = m.pre;
1211
+ const post = m.post.length ? expand_(m.post, max, false) : [''];
1212
+ if (/\$$/.test(m.pre)) {
1213
+ for (let k = 0; k < post.length && k < max; k++) {
1214
+ const expansion = pre + '{' + m.body + '}' + post[k];
1215
+ expansions.push(expansion);
1216
+ }
1217
+ }
1218
+ else {
1219
+ const isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
1220
+ const isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
1221
+ const isSequence = isNumericSequence || isAlphaSequence;
1222
+ const isOptions = m.body.indexOf(',') >= 0;
1223
+ if (!isSequence && !isOptions) {
1224
+ // {a},b}
1225
+ if (m.post.match(/,(?!,).*\}/)) {
1226
+ str = m.pre + '{' + m.body + escClose + m.post;
1227
+ return expand_(str, max, true);
1540
1228
  }
1541
- if (!fs.existsSync(fullPath)) {
1542
- res.statusCode = 404;
1543
- res.end('Not Found');
1544
- return;
1229
+ return [str];
1230
+ }
1231
+ let n;
1232
+ if (isSequence) {
1233
+ n = m.body.split(/\.\./);
1234
+ }
1235
+ else {
1236
+ n = parseCommaParts(m.body);
1237
+ if (n.length === 1 && n[0] !== undefined) {
1238
+ // x{{a,b}}y ==> x{a}y x{b}y
1239
+ n = expand_(n[0], max, false).map(embrace);
1240
+ //XXX is this necessary? Can't seem to hit it in tests.
1241
+ /* c8 ignore start */
1242
+ if (n.length === 1) {
1243
+ return post.map(p => m.pre + n[0] + p);
1244
+ }
1245
+ /* c8 ignore stop */
1545
1246
  }
1546
- const stat = fs.statSync(fullPath);
1547
- if (!stat.isFile()) {
1548
- res.statusCode = 404;
1549
- res.end('Not Found');
1550
- return;
1247
+ }
1248
+ // at this point, n is the parts, and we know it's not a comma set
1249
+ // with a single entry.
1250
+ let N;
1251
+ if (isSequence && n[0] !== undefined && n[1] !== undefined) {
1252
+ const x = numeric(n[0]);
1253
+ const y = numeric(n[1]);
1254
+ const width = Math.max(n[0].length, n[1].length);
1255
+ let incr = n.length === 3 && n[2] !== undefined ?
1256
+ Math.max(Math.abs(numeric(n[2])), 1)
1257
+ : 1;
1258
+ let test = lte;
1259
+ const reverse = y < x;
1260
+ if (reverse) {
1261
+ incr *= -1;
1262
+ test = gte;
1551
1263
  }
1552
- const extension = path.extname(filepath).toLowerCase();
1553
- const contentType = STATIC_CONTENT_TYPES[extension] ?? 'application/octet-stream';
1554
- res.statusCode = 200;
1555
- res.setHeader('Content-Type', contentType);
1556
- res.setHeader('Content-Length', String(stat.size));
1557
- if (normalized.method === 'HEAD') {
1558
- res.end();
1559
- return;
1264
+ const pad = n.some(isPadded);
1265
+ N = [];
1266
+ for (let i = x; test(i, y) && N.length < max; i += incr) {
1267
+ let c;
1268
+ if (isAlphaSequence) {
1269
+ c = String.fromCharCode(i);
1270
+ if (c === '\\') {
1271
+ c = '';
1272
+ }
1273
+ }
1274
+ else {
1275
+ c = String(i);
1276
+ if (pad) {
1277
+ const need = width - c.length;
1278
+ if (need > 0) {
1279
+ const z = new Array(need + 1).join('0');
1280
+ if (i < 0) {
1281
+ c = '-' + z + c.slice(1);
1282
+ }
1283
+ else {
1284
+ c = z + c;
1285
+ }
1286
+ }
1287
+ }
1288
+ }
1289
+ N.push(c);
1560
1290
  }
1561
- return new Promise((resolve, reject) => {
1562
- const stream = fs.createReadStream(fullPath);
1563
- stream.on('error', reject);
1564
- stream.on('end', () => resolve(this.StaticHandled));
1565
- stream.pipe(res);
1566
- });
1291
+ }
1292
+ else {
1293
+ N = [];
1294
+ for (let j = 0; j < n.length; j++) {
1295
+ N.push.apply(N, expand_(n[j], max, false));
1296
+ }
1297
+ }
1298
+ for (let j = 0; j < N.length; j++) {
1299
+ for (let k = 0; k < post.length && expansions.length < max; k++) {
1300
+ const expansion = pre + N[j] + post[k];
1301
+ if (!isTop || isSequence || expansion) {
1302
+ expansions.push(expansion);
1303
+ }
1304
+ }
1305
+ }
1306
+ }
1307
+ return expansions;
1308
+ }
1309
+
1310
+ const MAX_PATTERN_LENGTH = 1024 * 64;
1311
+ const assertValidPattern = (pattern) => {
1312
+ if (typeof pattern !== 'string') {
1313
+ throw new TypeError('invalid pattern');
1314
+ }
1315
+ if (pattern.length > MAX_PATTERN_LENGTH) {
1316
+ throw new TypeError('pattern is too long');
1317
+ }
1318
+ };
1319
+
1320
+ // translate the various posix character classes into unicode properties
1321
+ // this works across all unicode locales
1322
+ // { <posix class>: [<translation>, /u flag required, negated]
1323
+ const posixClasses = {
1324
+ '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
1325
+ '[:alpha:]': ['\\p{L}\\p{Nl}', true],
1326
+ '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
1327
+ '[:blank:]': ['\\p{Zs}\\t', true],
1328
+ '[:cntrl:]': ['\\p{Cc}', true],
1329
+ '[:digit:]': ['\\p{Nd}', true],
1330
+ '[:graph:]': ['\\p{Z}\\p{C}', true, true],
1331
+ '[:lower:]': ['\\p{Ll}', true],
1332
+ '[:print:]': ['\\p{C}', true],
1333
+ '[:punct:]': ['\\p{P}', true],
1334
+ '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
1335
+ '[:upper:]': ['\\p{Lu}', true],
1336
+ '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
1337
+ '[:xdigit:]': ['A-Fa-f0-9', false],
1338
+ };
1339
+ // only need to escape a few things inside of brace expressions
1340
+ // escapes: [ \ ] -
1341
+ const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
1342
+ // escape all regexp magic characters
1343
+ const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
1344
+ // everything has already been escaped, we just have to join
1345
+ const rangesToString = (ranges) => ranges.join('');
1346
+ // takes a glob string at a posix brace expression, and returns
1347
+ // an equivalent regular expression source, and boolean indicating
1348
+ // whether the /u flag needs to be applied, and the number of chars
1349
+ // consumed to parse the character class.
1350
+ // This also removes out of order ranges, and returns ($.) if the
1351
+ // entire class just no good.
1352
+ const parseClass = (glob, position) => {
1353
+ const pos = position;
1354
+ /* c8 ignore start */
1355
+ if (glob.charAt(pos) !== '[') {
1356
+ throw new Error('not in a brace expression');
1357
+ }
1358
+ /* c8 ignore stop */
1359
+ const ranges = [];
1360
+ const negs = [];
1361
+ let i = pos + 1;
1362
+ let sawStart = false;
1363
+ let uflag = false;
1364
+ let escaping = false;
1365
+ let negate = false;
1366
+ let endPos = pos;
1367
+ let rangeStart = '';
1368
+ WHILE: while (i < glob.length) {
1369
+ const c = glob.charAt(i);
1370
+ if ((c === '!' || c === '^') && i === pos + 1) {
1371
+ negate = true;
1372
+ i++;
1373
+ continue;
1374
+ }
1375
+ if (c === ']' && sawStart && !escaping) {
1376
+ endPos = i + 1;
1377
+ break;
1378
+ }
1379
+ sawStart = true;
1380
+ if (c === '\\') {
1381
+ if (!escaping) {
1382
+ escaping = true;
1383
+ i++;
1384
+ continue;
1385
+ }
1386
+ // escaped \ char, fall through and treat like normal char
1387
+ }
1388
+ if (c === '[' && !escaping) {
1389
+ // either a posix class, a collation equivalent, or just a [
1390
+ for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
1391
+ if (glob.startsWith(cls, i)) {
1392
+ // invalid, [a-[] is fine, but not [a-[:alpha]]
1393
+ if (rangeStart) {
1394
+ return ['$.', false, glob.length - pos, true];
1395
+ }
1396
+ i += cls.length;
1397
+ if (neg)
1398
+ negs.push(unip);
1399
+ else
1400
+ ranges.push(unip);
1401
+ uflag = uflag || u;
1402
+ continue WHILE;
1403
+ }
1404
+ }
1405
+ }
1406
+ // now it's just a normal character, effectively
1407
+ escaping = false;
1408
+ if (rangeStart) {
1409
+ // throw this range away if it's not valid, but others
1410
+ // can still match.
1411
+ if (c > rangeStart) {
1412
+ ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
1413
+ }
1414
+ else if (c === rangeStart) {
1415
+ ranges.push(braceEscape(c));
1416
+ }
1417
+ rangeStart = '';
1418
+ i++;
1419
+ continue;
1420
+ }
1421
+ // now might be the start of a range.
1422
+ // can be either c-d or c-] or c<more...>] or c] at this point
1423
+ if (glob.startsWith('-]', i + 1)) {
1424
+ ranges.push(braceEscape(c + '-'));
1425
+ i += 2;
1426
+ continue;
1427
+ }
1428
+ if (glob.startsWith('-', i + 1)) {
1429
+ rangeStart = c;
1430
+ i += 2;
1431
+ continue;
1432
+ }
1433
+ // not the start of a range, just a single character
1434
+ ranges.push(braceEscape(c));
1435
+ i++;
1436
+ }
1437
+ if (endPos < i) {
1438
+ // didn't see the end of the class, not a valid class,
1439
+ // but might still be valid as a literal match.
1440
+ return ['', false, 0, false];
1441
+ }
1442
+ // if we got no ranges and no negates, then we have a range that
1443
+ // cannot possibly match anything, and that poisons the whole glob
1444
+ if (!ranges.length && !negs.length) {
1445
+ return ['$.', false, glob.length - pos, true];
1446
+ }
1447
+ // if we got one positive range, and it's a single character, then that's
1448
+ // not actually a magic pattern, it's just that one literal character.
1449
+ // we should not treat that as "magic", we should just return the literal
1450
+ // character. [_] is a perfectly valid way to escape glob magic chars.
1451
+ if (negs.length === 0 &&
1452
+ ranges.length === 1 &&
1453
+ /^\\?.$/.test(ranges[0]) &&
1454
+ !negate) {
1455
+ const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
1456
+ return [regexpEscape(r), false, endPos - pos, false];
1457
+ }
1458
+ const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
1459
+ const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
1460
+ const comb = ranges.length && negs.length ? '(' + sranges + '|' + snegs + ')'
1461
+ : ranges.length ? sranges
1462
+ : snegs;
1463
+ return [comb, uflag, endPos - pos, true];
1464
+ };
1465
+
1466
+ /**
1467
+ * Un-escape a string that has been escaped with {@link escape}.
1468
+ *
1469
+ * If the {@link MinimatchOptions.windowsPathsNoEscape} option is used, then
1470
+ * square-bracket escapes are removed, but not backslash escapes.
1471
+ *
1472
+ * For example, it will turn the string `'[*]'` into `*`, but it will not
1473
+ * turn `'\\*'` into `'*'`, because `\` is a path separator in
1474
+ * `windowsPathsNoEscape` mode.
1475
+ *
1476
+ * When `windowsPathsNoEscape` is not set, then both square-bracket escapes and
1477
+ * backslash escapes are removed.
1478
+ *
1479
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
1480
+ * or unescaped.
1481
+ *
1482
+ * When `magicalBraces` is not set, escapes of braces (`{` and `}`) will not be
1483
+ * unescaped.
1484
+ */
1485
+ const unescape = (s, { windowsPathsNoEscape = false, magicalBraces = true, } = {}) => {
1486
+ if (magicalBraces) {
1487
+ return windowsPathsNoEscape ?
1488
+ s.replace(/\[([^/\\])\]/g, '$1')
1489
+ : s
1490
+ .replace(/((?!\\).|^)\[([^/\\])\]/g, '$1$2')
1491
+ .replace(/\\([^/])/g, '$1');
1492
+ }
1493
+ return windowsPathsNoEscape ?
1494
+ s.replace(/\[([^/\\{}])\]/g, '$1')
1495
+ : s
1496
+ .replace(/((?!\\).|^)\[([^/\\{}])\]/g, '$1$2')
1497
+ .replace(/\\([^/{}])/g, '$1');
1498
+ };
1499
+
1500
+ // parse a single path portion
1501
+ var _a;
1502
+ const types = new Set(['!', '?', '+', '*', '@']);
1503
+ const isExtglobType = (c) => types.has(c);
1504
+ const isExtglobAST = (c) => isExtglobType(c.type);
1505
+ // Map of which extglob types can adopt the children of a nested extglob
1506
+ //
1507
+ // anything but ! can adopt a matching type:
1508
+ // +(a|+(b|c)|d) => +(a|b|c|d)
1509
+ // *(a|*(b|c)|d) => *(a|b|c|d)
1510
+ // @(a|@(b|c)|d) => @(a|b|c|d)
1511
+ // ?(a|?(b|c)|d) => ?(a|b|c|d)
1512
+ //
1513
+ // * can adopt anything, because 0 or repetition is allowed
1514
+ // *(a|?(b|c)|d) => *(a|b|c|d)
1515
+ // *(a|+(b|c)|d) => *(a|b|c|d)
1516
+ // *(a|@(b|c)|d) => *(a|b|c|d)
1517
+ //
1518
+ // + can adopt @, because 1 or repetition is allowed
1519
+ // +(a|@(b|c)|d) => +(a|b|c|d)
1520
+ //
1521
+ // + and @ CANNOT adopt *, because 0 would be allowed
1522
+ // +(a|*(b|c)|d) => would match "", on *(b|c)
1523
+ // @(a|*(b|c)|d) => would match "", on *(b|c)
1524
+ //
1525
+ // + and @ CANNOT adopt ?, because 0 would be allowed
1526
+ // +(a|?(b|c)|d) => would match "", on ?(b|c)
1527
+ // @(a|?(b|c)|d) => would match "", on ?(b|c)
1528
+ //
1529
+ // ? can adopt @, because 0 or 1 is allowed
1530
+ // ?(a|@(b|c)|d) => ?(a|b|c|d)
1531
+ //
1532
+ // ? and @ CANNOT adopt * or +, because >1 would be allowed
1533
+ // ?(a|*(b|c)|d) => would match bbb on *(b|c)
1534
+ // @(a|*(b|c)|d) => would match bbb on *(b|c)
1535
+ // ?(a|+(b|c)|d) => would match bbb on +(b|c)
1536
+ // @(a|+(b|c)|d) => would match bbb on +(b|c)
1537
+ //
1538
+ // ! CANNOT adopt ! (nothing else can either)
1539
+ // !(a|!(b|c)|d) => !(a|b|c|d) would fail to match on b (not not b|c)
1540
+ //
1541
+ // ! can adopt @
1542
+ // !(a|@(b|c)|d) => !(a|b|c|d)
1543
+ //
1544
+ // ! CANNOT adopt *
1545
+ // !(a|*(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
1546
+ //
1547
+ // ! CANNOT adopt +
1548
+ // !(a|+(b|c)|d) => !(a|b|c|d) would match on bbb, not allowed
1549
+ //
1550
+ // ! CANNOT adopt ?
1551
+ // x!(a|?(b|c)|d) => x!(a|b|c|d) would fail to match "x"
1552
+ const adoptionMap = new Map([
1553
+ ['!', ['@']],
1554
+ ['?', ['?', '@']],
1555
+ ['@', ['@']],
1556
+ ['*', ['*', '+', '?', '@']],
1557
+ ['+', ['+', '@']],
1558
+ ]);
1559
+ // nested extglobs that can be adopted in, but with the addition of
1560
+ // a blank '' element.
1561
+ const adoptionWithSpaceMap = new Map([
1562
+ ['!', ['?']],
1563
+ ['@', ['?']],
1564
+ ['+', ['?', '*']],
1565
+ ]);
1566
+ // union of the previous two maps
1567
+ const adoptionAnyMap = new Map([
1568
+ ['!', ['?', '@']],
1569
+ ['?', ['?', '@']],
1570
+ ['@', ['?', '@']],
1571
+ ['*', ['*', '+', '?', '@']],
1572
+ ['+', ['+', '@', '?', '*']],
1573
+ ]);
1574
+ // Extglobs that can take over their parent if they are the only child
1575
+ // the key is parent, value maps child to resulting extglob parent type
1576
+ // '@' is omitted because it's a special case. An `@` extglob with a single
1577
+ // member can always be usurped by that subpattern.
1578
+ const usurpMap = new Map([
1579
+ ['!', new Map([['!', '@']])],
1580
+ [
1581
+ '?',
1582
+ new Map([
1583
+ ['*', '*'],
1584
+ ['+', '*'],
1585
+ ]),
1586
+ ],
1587
+ [
1588
+ '@',
1589
+ new Map([
1590
+ ['!', '!'],
1591
+ ['?', '?'],
1592
+ ['@', '@'],
1593
+ ['*', '*'],
1594
+ ['+', '+'],
1595
+ ]),
1596
+ ],
1597
+ [
1598
+ '+',
1599
+ new Map([
1600
+ ['?', '*'],
1601
+ ['*', '*'],
1602
+ ]),
1603
+ ],
1604
+ ]);
1605
+ // Patterns that get prepended to bind to the start of either the
1606
+ // entire string, or just a single path portion, to prevent dots
1607
+ // and/or traversal patterns, when needed.
1608
+ // Exts don't need the ^ or / bit, because the root binds that already.
1609
+ const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
1610
+ const startNoDot = '(?!\\.)';
1611
+ // characters that indicate a start of pattern needs the "no dots" bit,
1612
+ // because a dot *might* be matched. ( is not in the list, because in
1613
+ // the case of a child extglob, it will handle the prevention itself.
1614
+ const addPatternStart = new Set(['[', '.']);
1615
+ // cases where traversal is A-OK, no dot prevention needed
1616
+ const justDots = new Set(['..', '.']);
1617
+ const reSpecials = new Set('().*{}+?[]^$\\!');
1618
+ const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
1619
+ // any single thing other than /
1620
+ const qmark$1 = '[^/]';
1621
+ // * => any number of characters
1622
+ const star$1 = qmark$1 + '*?';
1623
+ // use + when we need to ensure that *something* matches, because the * is
1624
+ // the only thing in the path portion.
1625
+ const starNoEmpty = qmark$1 + '+?';
1626
+ // remove the \ chars that we added if we end up doing a nonmagic compare
1627
+ // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
1628
+ let ID = 0;
1629
+ class AST {
1630
+ type;
1631
+ #root;
1632
+ #hasMagic;
1633
+ #uflag = false;
1634
+ #parts = [];
1635
+ #parent;
1636
+ #parentIndex;
1637
+ #negs;
1638
+ #filledNegs = false;
1639
+ #options;
1640
+ #toString;
1641
+ // set to true if it's an extglob with no children
1642
+ // (which really means one child of '')
1643
+ #emptyExt = false;
1644
+ id = ++ID;
1645
+ get depth() {
1646
+ return (this.#parent?.depth ?? -1) + 1;
1647
+ }
1648
+ [Symbol.for('nodejs.util.inspect.custom')]() {
1649
+ return {
1650
+ '@@type': 'AST',
1651
+ id: this.id,
1652
+ type: this.type,
1653
+ root: this.#root.id,
1654
+ parent: this.#parent?.id,
1655
+ depth: this.depth,
1656
+ partsLength: this.#parts.length,
1657
+ parts: this.#parts,
1567
1658
  };
1568
1659
  }
1569
- /**
1570
- * 1. Check if the path exists, if not, delete the handler;
1571
- * 2. If the file extension matches `routerExclude`, delete it and return early;
1572
- * 3. If the file extension matches `apiExts`, register it as an API, otherwise register as static resource;
1573
- * @param filepath
1574
- */
1575
- register(filepath) {
1576
- const fullpath = path.join(process.cwd(), this.cx.options.dir, filepath);
1577
- if (!fs.existsSync(fullpath)) {
1578
- this.handlers.delete(filepath);
1579
- this.cx.logger.info(`[${filepath}] deleted`);
1580
- return;
1660
+ constructor(type, parent, options = {}) {
1661
+ this.type = type;
1662
+ // extglobs are inherently magical
1663
+ if (type)
1664
+ this.#hasMagic = true;
1665
+ this.#parent = parent;
1666
+ this.#root = this.#parent ? this.#parent.#root : this;
1667
+ this.#options = this.#root === this ? options : this.#root.#options;
1668
+ this.#negs = this.#root === this ? [] : this.#root.#negs;
1669
+ if (type === '!' && !this.#root.#filledNegs)
1670
+ this.#negs.push(this);
1671
+ this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
1672
+ }
1673
+ get hasMagic() {
1674
+ /* c8 ignore start */
1675
+ if (this.#hasMagic !== undefined)
1676
+ return this.#hasMagic;
1677
+ /* c8 ignore stop */
1678
+ for (const p of this.#parts) {
1679
+ if (typeof p === 'string')
1680
+ continue;
1681
+ if (p.type || p.hasMagic)
1682
+ return (this.#hasMagic = true);
1581
1683
  }
1582
- delete require.cache[fullpath];
1583
- const extension = path.extname(filepath).toLowerCase();
1584
- // Check if this file should be excluded from registration
1585
- if (this.cx.options.routerExclude.some((ext) => extension === ext)) {
1684
+ // note: will be undefined until we generate the regexp src and find out
1685
+ return this.#hasMagic;
1686
+ }
1687
+ // reconstructs the pattern
1688
+ toString() {
1689
+ return (this.#toString !== undefined ? this.#toString
1690
+ : !this.type ?
1691
+ (this.#toString = this.#parts.map(p => String(p)).join(''))
1692
+ : (this.#toString =
1693
+ this.type +
1694
+ '(' +
1695
+ this.#parts.map(p => String(p)).join('|') +
1696
+ ')'));
1697
+ }
1698
+ #fillNegs() {
1699
+ /* c8 ignore start */
1700
+ if (this !== this.#root)
1701
+ throw new Error('should only call on root');
1702
+ if (this.#filledNegs)
1703
+ return this;
1704
+ /* c8 ignore stop */
1705
+ // call toString() once to fill this out
1706
+ this.toString();
1707
+ this.#filledNegs = true;
1708
+ let n;
1709
+ while ((n = this.#negs.pop())) {
1710
+ if (n.type !== '!')
1711
+ continue;
1712
+ // walk up the tree, appending everthing that comes AFTER parentIndex
1713
+ let p = n;
1714
+ let pp = p.#parent;
1715
+ while (pp) {
1716
+ for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
1717
+ for (const part of n.#parts) {
1718
+ /* c8 ignore start */
1719
+ if (typeof part === 'string') {
1720
+ throw new Error('string part in extglob AST??');
1721
+ }
1722
+ /* c8 ignore stop */
1723
+ part.copyIn(pp.#parts[i]);
1724
+ }
1725
+ }
1726
+ p = pp;
1727
+ pp = p.#parent;
1728
+ }
1729
+ }
1730
+ return this;
1731
+ }
1732
+ push(...parts) {
1733
+ for (const p of parts) {
1734
+ if (p === '')
1735
+ continue;
1736
+ /* c8 ignore start */
1737
+ if (typeof p !== 'string' &&
1738
+ !(p instanceof _a && p.#parent === this)) {
1739
+ throw new Error('invalid part: ' + p);
1740
+ }
1741
+ /* c8 ignore stop */
1742
+ this.#parts.push(p);
1743
+ }
1744
+ }
1745
+ toJSON() {
1746
+ const ret = this.type === null ?
1747
+ this.#parts
1748
+ .slice()
1749
+ .map(p => (typeof p === 'string' ? p : p.toJSON()))
1750
+ : [this.type, ...this.#parts.map(p => p.toJSON())];
1751
+ if (this.isStart() && !this.type)
1752
+ ret.unshift([]);
1753
+ if (this.isEnd() &&
1754
+ (this === this.#root ||
1755
+ (this.#root.#filledNegs && this.#parent?.type === '!'))) {
1756
+ ret.push({});
1757
+ }
1758
+ return ret;
1759
+ }
1760
+ isStart() {
1761
+ if (this.#root === this)
1762
+ return true;
1763
+ // if (this.type) return !!this.#parent?.isStart()
1764
+ if (!this.#parent?.isStart())
1765
+ return false;
1766
+ if (this.#parentIndex === 0)
1767
+ return true;
1768
+ // if everything AHEAD of this is a negation, then it's still the "start"
1769
+ const p = this.#parent;
1770
+ for (let i = 0; i < this.#parentIndex; i++) {
1771
+ const pp = p.#parts[i];
1772
+ if (!(pp instanceof _a && pp.type === '!')) {
1773
+ return false;
1774
+ }
1775
+ }
1776
+ return true;
1777
+ }
1778
+ isEnd() {
1779
+ if (this.#root === this)
1780
+ return true;
1781
+ if (this.#parent?.type === '!')
1782
+ return true;
1783
+ if (!this.#parent?.isEnd())
1784
+ return false;
1785
+ if (!this.type)
1786
+ return this.#parent?.isEnd();
1787
+ // if not root, it'll always have a parent
1788
+ /* c8 ignore start */
1789
+ const pl = this.#parent ? this.#parent.#parts.length : 0;
1790
+ /* c8 ignore stop */
1791
+ return this.#parentIndex === pl - 1;
1792
+ }
1793
+ copyIn(part) {
1794
+ if (typeof part === 'string')
1795
+ this.push(part);
1796
+ else
1797
+ this.push(part.clone(this));
1798
+ }
1799
+ clone(parent) {
1800
+ const c = new _a(this.type, parent);
1801
+ for (const p of this.#parts) {
1802
+ c.copyIn(p);
1803
+ }
1804
+ return c;
1805
+ }
1806
+ static #parseAST(str, ast, pos, opt, extDepth) {
1807
+ const maxDepth = opt.maxExtglobRecursion ?? 2;
1808
+ let escaping = false;
1809
+ let inBrace = false;
1810
+ let braceStart = -1;
1811
+ let braceNeg = false;
1812
+ if (ast.type === null) {
1813
+ // outside of a extglob, append until we find a start
1814
+ let i = pos;
1815
+ let acc = '';
1816
+ while (i < str.length) {
1817
+ const c = str.charAt(i++);
1818
+ // still accumulate escapes at this point, but we do ignore
1819
+ // starts that are escaped
1820
+ if (escaping || c === '\\') {
1821
+ escaping = !escaping;
1822
+ acc += c;
1823
+ continue;
1824
+ }
1825
+ if (inBrace) {
1826
+ if (i === braceStart + 1) {
1827
+ if (c === '^' || c === '!') {
1828
+ braceNeg = true;
1829
+ }
1830
+ }
1831
+ else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
1832
+ inBrace = false;
1833
+ }
1834
+ acc += c;
1835
+ continue;
1836
+ }
1837
+ else if (c === '[') {
1838
+ inBrace = true;
1839
+ braceStart = i;
1840
+ braceNeg = false;
1841
+ acc += c;
1842
+ continue;
1843
+ }
1844
+ // we don't have to check for adoption here, because that's
1845
+ // done at the other recursion point.
1846
+ const doRecurse = !opt.noext &&
1847
+ isExtglobType(c) &&
1848
+ str.charAt(i) === '(' &&
1849
+ extDepth <= maxDepth;
1850
+ if (doRecurse) {
1851
+ ast.push(acc);
1852
+ acc = '';
1853
+ const ext = new _a(c, ast);
1854
+ i = _a.#parseAST(str, ext, i, opt, extDepth + 1);
1855
+ ast.push(ext);
1856
+ continue;
1857
+ }
1858
+ acc += c;
1859
+ }
1860
+ ast.push(acc);
1861
+ return i;
1862
+ }
1863
+ // some kind of extglob, pos is at the (
1864
+ // find the next | or )
1865
+ let i = pos + 1;
1866
+ let part = new _a(null, ast);
1867
+ const parts = [];
1868
+ let acc = '';
1869
+ while (i < str.length) {
1870
+ const c = str.charAt(i++);
1871
+ // still accumulate escapes at this point, but we do ignore
1872
+ // starts that are escaped
1873
+ if (escaping || c === '\\') {
1874
+ escaping = !escaping;
1875
+ acc += c;
1876
+ continue;
1877
+ }
1878
+ if (inBrace) {
1879
+ if (i === braceStart + 1) {
1880
+ if (c === '^' || c === '!') {
1881
+ braceNeg = true;
1882
+ }
1883
+ }
1884
+ else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
1885
+ inBrace = false;
1886
+ }
1887
+ acc += c;
1888
+ continue;
1889
+ }
1890
+ else if (c === '[') {
1891
+ inBrace = true;
1892
+ braceStart = i;
1893
+ braceNeg = false;
1894
+ acc += c;
1895
+ continue;
1896
+ }
1897
+ const doRecurse = !opt.noext &&
1898
+ isExtglobType(c) &&
1899
+ str.charAt(i) === '(' &&
1900
+ /* c8 ignore start - the maxDepth is sufficient here */
1901
+ (extDepth <= maxDepth || (ast && ast.#canAdoptType(c)));
1902
+ /* c8 ignore stop */
1903
+ if (doRecurse) {
1904
+ const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1;
1905
+ part.push(acc);
1906
+ acc = '';
1907
+ const ext = new _a(c, part);
1908
+ part.push(ext);
1909
+ i = _a.#parseAST(str, ext, i, opt, extDepth + depthAdd);
1910
+ continue;
1911
+ }
1912
+ if (c === '|') {
1913
+ part.push(acc);
1914
+ acc = '';
1915
+ parts.push(part);
1916
+ part = new _a(null, ast);
1917
+ continue;
1918
+ }
1919
+ if (c === ')') {
1920
+ if (acc === '' && ast.#parts.length === 0) {
1921
+ ast.#emptyExt = true;
1922
+ }
1923
+ part.push(acc);
1924
+ acc = '';
1925
+ ast.push(...parts, part);
1926
+ return i;
1927
+ }
1928
+ acc += c;
1929
+ }
1930
+ // unfinished extglob
1931
+ // if we got here, it was a malformed extglob! not an extglob, but
1932
+ // maybe something else in there.
1933
+ ast.type = null;
1934
+ ast.#hasMagic = undefined;
1935
+ ast.#parts = [str.substring(pos - 1)];
1936
+ return i;
1937
+ }
1938
+ #canAdoptWithSpace(child) {
1939
+ return this.#canAdopt(child, adoptionWithSpaceMap);
1940
+ }
1941
+ #canAdopt(child, map = adoptionMap) {
1942
+ if (!child ||
1943
+ typeof child !== 'object' ||
1944
+ child.type !== null ||
1945
+ child.#parts.length !== 1 ||
1946
+ this.type === null) {
1947
+ return false;
1948
+ }
1949
+ const gc = child.#parts[0];
1950
+ if (!gc || typeof gc !== 'object' || gc.type === null) {
1951
+ return false;
1952
+ }
1953
+ return this.#canAdoptType(gc.type, map);
1954
+ }
1955
+ #canAdoptType(c, map = adoptionAnyMap) {
1956
+ return !!map.get(this.type)?.includes(c);
1957
+ }
1958
+ #adoptWithSpace(child, index) {
1959
+ const gc = child.#parts[0];
1960
+ const blank = new _a(null, gc, this.options);
1961
+ blank.#parts.push('');
1962
+ gc.push(blank);
1963
+ this.#adopt(child, index);
1964
+ }
1965
+ #adopt(child, index) {
1966
+ const gc = child.#parts[0];
1967
+ this.#parts.splice(index, 1, ...gc.#parts);
1968
+ for (const p of gc.#parts) {
1969
+ if (typeof p === 'object')
1970
+ p.#parent = this;
1971
+ }
1972
+ this.#toString = undefined;
1973
+ }
1974
+ #canUsurpType(c) {
1975
+ const m = usurpMap.get(this.type);
1976
+ return !!m?.has(c);
1977
+ }
1978
+ #canUsurp(child) {
1979
+ if (!child ||
1980
+ typeof child !== 'object' ||
1981
+ child.type !== null ||
1982
+ child.#parts.length !== 1 ||
1983
+ this.type === null ||
1984
+ this.#parts.length !== 1) {
1985
+ return false;
1986
+ }
1987
+ const gc = child.#parts[0];
1988
+ if (!gc || typeof gc !== 'object' || gc.type === null) {
1989
+ return false;
1990
+ }
1991
+ return this.#canUsurpType(gc.type);
1992
+ }
1993
+ #usurp(child) {
1994
+ const m = usurpMap.get(this.type);
1995
+ const gc = child.#parts[0];
1996
+ const nt = m?.get(gc.type);
1997
+ /* c8 ignore start - impossible */
1998
+ if (!nt)
1999
+ return false;
2000
+ /* c8 ignore stop */
2001
+ this.#parts = gc.#parts;
2002
+ for (const p of this.#parts) {
2003
+ if (typeof p === 'object') {
2004
+ p.#parent = this;
2005
+ }
2006
+ }
2007
+ this.type = nt;
2008
+ this.#toString = undefined;
2009
+ this.#emptyExt = false;
2010
+ }
2011
+ static fromGlob(pattern, options = {}) {
2012
+ const ast = new _a(null, undefined, options);
2013
+ _a.#parseAST(pattern, ast, 0, options, 0);
2014
+ return ast;
2015
+ }
2016
+ // returns the regular expression if there's magic, or the unescaped
2017
+ // string if not.
2018
+ toMMPattern() {
2019
+ // should only be called on root
2020
+ /* c8 ignore start */
2021
+ if (this !== this.#root)
2022
+ return this.#root.toMMPattern();
2023
+ /* c8 ignore stop */
2024
+ const glob = this.toString();
2025
+ const [re, body, hasMagic, uflag] = this.toRegExpSource();
2026
+ // if we're in nocase mode, and not nocaseMagicOnly, then we do
2027
+ // still need a regular expression if we have to case-insensitively
2028
+ // match capital/lowercase characters.
2029
+ const anyMagic = hasMagic ||
2030
+ this.#hasMagic ||
2031
+ (this.#options.nocase &&
2032
+ !this.#options.nocaseMagicOnly &&
2033
+ glob.toUpperCase() !== glob.toLowerCase());
2034
+ if (!anyMagic) {
2035
+ return body;
2036
+ }
2037
+ const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
2038
+ return Object.assign(new RegExp(`^${re}$`, flags), {
2039
+ _src: re,
2040
+ _glob: glob,
2041
+ });
2042
+ }
2043
+ get options() {
2044
+ return this.#options;
2045
+ }
2046
+ // returns the string match, the regexp source, whether there's magic
2047
+ // in the regexp (so a regular expression is required) and whether or
2048
+ // not the uflag is needed for the regular expression (for posix classes)
2049
+ // TODO: instead of injecting the start/end at this point, just return
2050
+ // the BODY of the regexp, along with the start/end portions suitable
2051
+ // for binding the start/end in either a joined full-path makeRe context
2052
+ // (where we bind to (^|/), or a standalone matchPart context (where
2053
+ // we bind to ^, and not /). Otherwise slashes get duped!
2054
+ //
2055
+ // In part-matching mode, the start is:
2056
+ // - if not isStart: nothing
2057
+ // - if traversal possible, but not allowed: ^(?!\.\.?$)
2058
+ // - if dots allowed or not possible: ^
2059
+ // - if dots possible and not allowed: ^(?!\.)
2060
+ // end is:
2061
+ // - if not isEnd(): nothing
2062
+ // - else: $
2063
+ //
2064
+ // In full-path matching mode, we put the slash at the START of the
2065
+ // pattern, so start is:
2066
+ // - if first pattern: same as part-matching mode
2067
+ // - if not isStart(): nothing
2068
+ // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
2069
+ // - if dots allowed or not possible: /
2070
+ // - if dots possible and not allowed: /(?!\.)
2071
+ // end is:
2072
+ // - if last pattern, same as part-matching mode
2073
+ // - else nothing
2074
+ //
2075
+ // Always put the (?:$|/) on negated tails, though, because that has to be
2076
+ // there to bind the end of the negated pattern portion, and it's easier to
2077
+ // just stick it in now rather than try to inject it later in the middle of
2078
+ // the pattern.
2079
+ //
2080
+ // We can just always return the same end, and leave it up to the caller
2081
+ // to know whether it's going to be used joined or in parts.
2082
+ // And, if the start is adjusted slightly, can do the same there:
2083
+ // - if not isStart: nothing
2084
+ // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
2085
+ // - if dots allowed or not possible: (?:/|^)
2086
+ // - if dots possible and not allowed: (?:/|^)(?!\.)
2087
+ //
2088
+ // But it's better to have a simpler binding without a conditional, for
2089
+ // performance, so probably better to return both start options.
2090
+ //
2091
+ // Then the caller just ignores the end if it's not the first pattern,
2092
+ // and the start always gets applied.
2093
+ //
2094
+ // But that's always going to be $ if it's the ending pattern, or nothing,
2095
+ // so the caller can just attach $ at the end of the pattern when building.
2096
+ //
2097
+ // So the todo is:
2098
+ // - better detect what kind of start is needed
2099
+ // - return both flavors of starting pattern
2100
+ // - attach $ at the end of the pattern when creating the actual RegExp
2101
+ //
2102
+ // Ah, but wait, no, that all only applies to the root when the first pattern
2103
+ // is not an extglob. If the first pattern IS an extglob, then we need all
2104
+ // that dot prevention biz to live in the extglob portions, because eg
2105
+ // +(*|.x*) can match .xy but not .yx.
2106
+ //
2107
+ // So, return the two flavors if it's #root and the first child is not an
2108
+ // AST, otherwise leave it to the child AST to handle it, and there,
2109
+ // use the (?:^|/) style of start binding.
2110
+ //
2111
+ // Even simplified further:
2112
+ // - Since the start for a join is eg /(?!\.) and the start for a part
2113
+ // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
2114
+ // or start or whatever) and prepend ^ or / at the Regexp construction.
2115
+ toRegExpSource(allowDot) {
2116
+ const dot = allowDot ?? !!this.#options.dot;
2117
+ if (this.#root === this) {
2118
+ this.#flatten();
2119
+ this.#fillNegs();
2120
+ }
2121
+ if (!isExtglobAST(this)) {
2122
+ const noEmpty = this.isStart() &&
2123
+ this.isEnd() &&
2124
+ !this.#parts.some(s => typeof s !== 'string');
2125
+ const src = this.#parts
2126
+ .map(p => {
2127
+ const [re, _, hasMagic, uflag] = typeof p === 'string' ?
2128
+ _a.#parseGlob(p, this.#hasMagic, noEmpty)
2129
+ : p.toRegExpSource(allowDot);
2130
+ this.#hasMagic = this.#hasMagic || hasMagic;
2131
+ this.#uflag = this.#uflag || uflag;
2132
+ return re;
2133
+ })
2134
+ .join('');
2135
+ let start = '';
2136
+ if (this.isStart()) {
2137
+ if (typeof this.#parts[0] === 'string') {
2138
+ // this is the string that will match the start of the pattern,
2139
+ // so we need to protect against dots and such.
2140
+ // '.' and '..' cannot match unless the pattern is that exactly,
2141
+ // even if it starts with . or dot:true is set.
2142
+ const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
2143
+ if (!dotTravAllowed) {
2144
+ const aps = addPatternStart;
2145
+ // check if we have a possibility of matching . or ..,
2146
+ // and prevent that.
2147
+ const needNoTrav =
2148
+ // dots are allowed, and the pattern starts with [ or .
2149
+ (dot && aps.has(src.charAt(0))) ||
2150
+ // the pattern starts with \., and then [ or .
2151
+ (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
2152
+ // the pattern starts with \.\., and then [ or .
2153
+ (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
2154
+ // no need to prevent dots if it can't match a dot, or if a
2155
+ // sub-pattern will be preventing it anyway.
2156
+ const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
2157
+ start =
2158
+ needNoTrav ? startNoTraversal
2159
+ : needNoDot ? startNoDot
2160
+ : '';
2161
+ }
2162
+ }
2163
+ }
2164
+ // append the "end of path portion" pattern to negation tails
2165
+ let end = '';
2166
+ if (this.isEnd() &&
2167
+ this.#root.#filledNegs &&
2168
+ this.#parent?.type === '!') {
2169
+ end = '(?:$|\\/)';
2170
+ }
2171
+ const final = start + src + end;
2172
+ return [
2173
+ final,
2174
+ unescape(src),
2175
+ (this.#hasMagic = !!this.#hasMagic),
2176
+ this.#uflag,
2177
+ ];
2178
+ }
2179
+ // We need to calculate the body *twice* if it's a repeat pattern
2180
+ // at the start, once in nodot mode, then again in dot mode, so a
2181
+ // pattern like *(?) can match 'x.y'
2182
+ const repeated = this.type === '*' || this.type === '+';
2183
+ // some kind of extglob
2184
+ const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
2185
+ let body = this.#partsToRegExp(dot);
2186
+ if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
2187
+ // invalid extglob, has to at least be *something* present, if it's
2188
+ // the entire path portion.
2189
+ const s = this.toString();
2190
+ const me = this;
2191
+ me.#parts = [s];
2192
+ me.type = null;
2193
+ me.#hasMagic = undefined;
2194
+ return [s, unescape(this.toString()), false, false];
2195
+ }
2196
+ let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot ?
2197
+ ''
2198
+ : this.#partsToRegExp(true);
2199
+ if (bodyDotAllowed === body) {
2200
+ bodyDotAllowed = '';
2201
+ }
2202
+ if (bodyDotAllowed) {
2203
+ body = `(?:${body})(?:${bodyDotAllowed})*?`;
2204
+ }
2205
+ // an empty !() is exactly equivalent to a starNoEmpty
2206
+ let final = '';
2207
+ if (this.type === '!' && this.#emptyExt) {
2208
+ final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
2209
+ }
2210
+ else {
2211
+ const close = this.type === '!' ?
2212
+ // !() must match something,but !(x) can match ''
2213
+ '))' +
2214
+ (this.isStart() && !dot && !allowDot ? startNoDot : '') +
2215
+ star$1 +
2216
+ ')'
2217
+ : this.type === '@' ? ')'
2218
+ : this.type === '?' ? ')?'
2219
+ : this.type === '+' && bodyDotAllowed ? ')'
2220
+ : this.type === '*' && bodyDotAllowed ? `)?`
2221
+ : `)${this.type}`;
2222
+ final = start + body + close;
2223
+ }
2224
+ return [
2225
+ final,
2226
+ unescape(body),
2227
+ (this.#hasMagic = !!this.#hasMagic),
2228
+ this.#uflag,
2229
+ ];
2230
+ }
2231
+ #flatten() {
2232
+ if (!isExtglobAST(this)) {
2233
+ for (const p of this.#parts) {
2234
+ if (typeof p === 'object') {
2235
+ p.#flatten();
2236
+ }
2237
+ }
2238
+ }
2239
+ else {
2240
+ // do up to 10 passes to flatten as much as possible
2241
+ let iterations = 0;
2242
+ let done = false;
2243
+ do {
2244
+ done = true;
2245
+ for (let i = 0; i < this.#parts.length; i++) {
2246
+ const c = this.#parts[i];
2247
+ if (typeof c === 'object') {
2248
+ c.#flatten();
2249
+ if (this.#canAdopt(c)) {
2250
+ done = false;
2251
+ this.#adopt(c, i);
2252
+ }
2253
+ else if (this.#canAdoptWithSpace(c)) {
2254
+ done = false;
2255
+ this.#adoptWithSpace(c, i);
2256
+ }
2257
+ else if (this.#canUsurp(c)) {
2258
+ done = false;
2259
+ this.#usurp(c);
2260
+ }
2261
+ }
2262
+ }
2263
+ } while (!done && ++iterations < 10);
2264
+ }
2265
+ this.#toString = undefined;
2266
+ }
2267
+ #partsToRegExp(dot) {
2268
+ return this.#parts
2269
+ .map(p => {
2270
+ // extglob ASTs should only contain parent ASTs
2271
+ /* c8 ignore start */
2272
+ if (typeof p === 'string') {
2273
+ throw new Error('string type in extglob ast??');
2274
+ }
2275
+ /* c8 ignore stop */
2276
+ // can ignore hasMagic, because extglobs are already always magic
2277
+ const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
2278
+ this.#uflag = this.#uflag || uflag;
2279
+ return re;
2280
+ })
2281
+ .filter(p => !(this.isStart() && this.isEnd()) || !!p)
2282
+ .join('|');
2283
+ }
2284
+ static #parseGlob(glob, hasMagic, noEmpty = false) {
2285
+ let escaping = false;
2286
+ let re = '';
2287
+ let uflag = false;
2288
+ // multiple stars that aren't globstars coalesce into one *
2289
+ let inStar = false;
2290
+ for (let i = 0; i < glob.length; i++) {
2291
+ const c = glob.charAt(i);
2292
+ if (escaping) {
2293
+ escaping = false;
2294
+ re += (reSpecials.has(c) ? '\\' : '') + c;
2295
+ continue;
2296
+ }
2297
+ if (c === '*') {
2298
+ if (inStar)
2299
+ continue;
2300
+ inStar = true;
2301
+ re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star$1;
2302
+ hasMagic = true;
2303
+ continue;
2304
+ }
2305
+ else {
2306
+ inStar = false;
2307
+ }
2308
+ if (c === '\\') {
2309
+ if (i === glob.length - 1) {
2310
+ re += '\\\\';
2311
+ }
2312
+ else {
2313
+ escaping = true;
2314
+ }
2315
+ continue;
2316
+ }
2317
+ if (c === '[') {
2318
+ const [src, needUflag, consumed, magic] = parseClass(glob, i);
2319
+ if (consumed) {
2320
+ re += src;
2321
+ uflag = uflag || needUflag;
2322
+ i += consumed - 1;
2323
+ hasMagic = hasMagic || magic;
2324
+ continue;
2325
+ }
2326
+ }
2327
+ if (c === '?') {
2328
+ re += qmark$1;
2329
+ hasMagic = true;
2330
+ continue;
2331
+ }
2332
+ re += regExpEscape$1(c);
2333
+ }
2334
+ return [re, unescape(glob), !!hasMagic, uflag];
2335
+ }
2336
+ }
2337
+ _a = AST;
2338
+
2339
+ /**
2340
+ * Escape all magic characters in a glob pattern.
2341
+ *
2342
+ * If the {@link MinimatchOptions.windowsPathsNoEscape}
2343
+ * option is used, then characters are escaped by wrapping in `[]`, because
2344
+ * a magic character wrapped in a character class can only be satisfied by
2345
+ * that exact character. In this mode, `\` is _not_ escaped, because it is
2346
+ * not interpreted as a magic character, but instead as a path separator.
2347
+ *
2348
+ * If the {@link MinimatchOptions.magicalBraces} option is used,
2349
+ * then braces (`{` and `}`) will be escaped.
2350
+ */
2351
+ const escape = (s, { windowsPathsNoEscape = false, magicalBraces = false, } = {}) => {
2352
+ // don't need to escape +@! because we escape the parens
2353
+ // that make those magic, and escaping ! as [!] isn't valid,
2354
+ // because [!]] is a valid glob class meaning not ']'.
2355
+ if (magicalBraces) {
2356
+ return windowsPathsNoEscape ?
2357
+ s.replace(/[?*()[\]{}]/g, '[$&]')
2358
+ : s.replace(/[?*()[\]\\{}]/g, '\\$&');
2359
+ }
2360
+ return windowsPathsNoEscape ?
2361
+ s.replace(/[?*()[\]]/g, '[$&]')
2362
+ : s.replace(/[?*()[\]\\]/g, '\\$&');
2363
+ };
2364
+
2365
+ const minimatch = (p, pattern, options = {}) => {
2366
+ assertValidPattern(pattern);
2367
+ // shortcut: comments match nothing.
2368
+ if (!options.nocomment && pattern.charAt(0) === '#') {
2369
+ return false;
2370
+ }
2371
+ return new Minimatch(pattern, options).match(p);
2372
+ };
2373
+ // Optimized checking for the most common glob patterns.
2374
+ const starDotExtRE = /^\*+([^+@!?*[(]*)$/;
2375
+ const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
2376
+ const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
2377
+ const starDotExtTestNocase = (ext) => {
2378
+ ext = ext.toLowerCase();
2379
+ return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
2380
+ };
2381
+ const starDotExtTestNocaseDot = (ext) => {
2382
+ ext = ext.toLowerCase();
2383
+ return (f) => f.toLowerCase().endsWith(ext);
2384
+ };
2385
+ const starDotStarRE = /^\*+\.\*+$/;
2386
+ const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
2387
+ const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
2388
+ const dotStarRE = /^\.\*+$/;
2389
+ const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
2390
+ const starRE = /^\*+$/;
2391
+ const starTest = (f) => f.length !== 0 && !f.startsWith('.');
2392
+ const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
2393
+ const qmarksRE = /^\?+([^+@!?*[(]*)?$/;
2394
+ const qmarksTestNocase = ([$0, ext = '']) => {
2395
+ const noext = qmarksTestNoExt([$0]);
2396
+ if (!ext)
2397
+ return noext;
2398
+ ext = ext.toLowerCase();
2399
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext);
2400
+ };
2401
+ const qmarksTestNocaseDot = ([$0, ext = '']) => {
2402
+ const noext = qmarksTestNoExtDot([$0]);
2403
+ if (!ext)
2404
+ return noext;
2405
+ ext = ext.toLowerCase();
2406
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext);
2407
+ };
2408
+ const qmarksTestDot = ([$0, ext = '']) => {
2409
+ const noext = qmarksTestNoExtDot([$0]);
2410
+ return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
2411
+ };
2412
+ const qmarksTest = ([$0, ext = '']) => {
2413
+ const noext = qmarksTestNoExt([$0]);
2414
+ return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
2415
+ };
2416
+ const qmarksTestNoExt = ([$0]) => {
2417
+ const len = $0.length;
2418
+ return (f) => f.length === len && !f.startsWith('.');
2419
+ };
2420
+ const qmarksTestNoExtDot = ([$0]) => {
2421
+ const len = $0.length;
2422
+ return (f) => f.length === len && f !== '.' && f !== '..';
2423
+ };
2424
+ /* c8 ignore start */
2425
+ const defaultPlatform = (typeof process === 'object' && process ?
2426
+ (typeof process.env === 'object' &&
2427
+ process.env &&
2428
+ process.env.__MINIMATCH_TESTING_PLATFORM__) ||
2429
+ process.platform
2430
+ : 'posix');
2431
+ const path = {
2432
+ win32: { sep: '\\' },
2433
+ posix: { sep: '/' },
2434
+ };
2435
+ /* c8 ignore stop */
2436
+ const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
2437
+ minimatch.sep = sep;
2438
+ const GLOBSTAR = Symbol('globstar **');
2439
+ minimatch.GLOBSTAR = GLOBSTAR;
2440
+ // any single thing other than /
2441
+ // don't need to escape / when using new RegExp()
2442
+ const qmark = '[^/]';
2443
+ // * => any number of characters
2444
+ const star = qmark + '*?';
2445
+ // ** when dots are allowed. Anything goes, except .. and .
2446
+ // not (^ or / followed by one or two dots followed by $ or /),
2447
+ // followed by anything, any number of times.
2448
+ const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
2449
+ // not a ^ or / followed by a dot,
2450
+ // followed by anything, any number of times.
2451
+ const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
2452
+ const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
2453
+ minimatch.filter = filter;
2454
+ const ext = (a, b = {}) => Object.assign({}, a, b);
2455
+ const defaults = (def) => {
2456
+ if (!def || typeof def !== 'object' || !Object.keys(def).length) {
2457
+ return minimatch;
2458
+ }
2459
+ const orig = minimatch;
2460
+ const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
2461
+ return Object.assign(m, {
2462
+ Minimatch: class Minimatch extends orig.Minimatch {
2463
+ constructor(pattern, options = {}) {
2464
+ super(pattern, ext(def, options));
2465
+ }
2466
+ static defaults(options) {
2467
+ return orig.defaults(ext(def, options)).Minimatch;
2468
+ }
2469
+ },
2470
+ AST: class AST extends orig.AST {
2471
+ /* c8 ignore start */
2472
+ constructor(type, parent, options = {}) {
2473
+ super(type, parent, ext(def, options));
2474
+ }
2475
+ /* c8 ignore stop */
2476
+ static fromGlob(pattern, options = {}) {
2477
+ return orig.AST.fromGlob(pattern, ext(def, options));
2478
+ }
2479
+ },
2480
+ unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
2481
+ escape: (s, options = {}) => orig.escape(s, ext(def, options)),
2482
+ filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
2483
+ defaults: (options) => orig.defaults(ext(def, options)),
2484
+ makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
2485
+ braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
2486
+ match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
2487
+ sep: orig.sep,
2488
+ GLOBSTAR: GLOBSTAR,
2489
+ });
2490
+ };
2491
+ minimatch.defaults = defaults;
2492
+ // Brace expansion:
2493
+ // a{b,c}d -> abd acd
2494
+ // a{b,}c -> abc ac
2495
+ // a{0..3}d -> a0d a1d a2d a3d
2496
+ // a{b,c{d,e}f}g -> abg acdfg acefg
2497
+ // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
2498
+ //
2499
+ // Invalid sets are not expanded.
2500
+ // a{2..}b -> a{2..}b
2501
+ // a{b}c -> a{b}c
2502
+ const braceExpand = (pattern, options = {}) => {
2503
+ assertValidPattern(pattern);
2504
+ // Thanks to Yeting Li <https://github.com/yetingli> for
2505
+ // improving this regexp to avoid a ReDOS vulnerability.
2506
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
2507
+ // shortcut. no need to expand.
2508
+ return [pattern];
2509
+ }
2510
+ return expand(pattern, { max: options.braceExpandMax });
2511
+ };
2512
+ minimatch.braceExpand = braceExpand;
2513
+ // parse a component of the expanded set.
2514
+ // At this point, no pattern may contain "/" in it
2515
+ // so we're going to return a 2d array, where each entry is the full
2516
+ // pattern, split on '/', and then turned into a regular expression.
2517
+ // A regexp is made at the end which joins each array with an
2518
+ // escaped /, and another full one which joins each regexp with |.
2519
+ //
2520
+ // Following the lead of Bash 4.1, note that "**" only has special meaning
2521
+ // when it is the *only* thing in a path portion. Otherwise, any series
2522
+ // of * is equivalent to a single *. Globstar behavior is enabled by
2523
+ // default, and can be disabled by setting options.noglobstar.
2524
+ const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
2525
+ minimatch.makeRe = makeRe;
2526
+ const match = (list, pattern, options = {}) => {
2527
+ const mm = new Minimatch(pattern, options);
2528
+ list = list.filter(f => mm.match(f));
2529
+ if (mm.options.nonull && !list.length) {
2530
+ list.push(pattern);
2531
+ }
2532
+ return list;
2533
+ };
2534
+ minimatch.match = match;
2535
+ // replace stuff like \* with *
2536
+ const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
2537
+ const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
2538
+ class Minimatch {
2539
+ options;
2540
+ set;
2541
+ pattern;
2542
+ windowsPathsNoEscape;
2543
+ nonegate;
2544
+ negate;
2545
+ comment;
2546
+ empty;
2547
+ preserveMultipleSlashes;
2548
+ partial;
2549
+ globSet;
2550
+ globParts;
2551
+ nocase;
2552
+ isWindows;
2553
+ platform;
2554
+ windowsNoMagicRoot;
2555
+ maxGlobstarRecursion;
2556
+ regexp;
2557
+ constructor(pattern, options = {}) {
2558
+ assertValidPattern(pattern);
2559
+ options = options || {};
2560
+ this.options = options;
2561
+ this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200;
2562
+ this.pattern = pattern;
2563
+ this.platform = options.platform || defaultPlatform;
2564
+ this.isWindows = this.platform === 'win32';
2565
+ // avoid the annoying deprecation flag lol
2566
+ const awe = ('allowWindow' + 'sEscape');
2567
+ this.windowsPathsNoEscape =
2568
+ !!options.windowsPathsNoEscape || options[awe] === false;
2569
+ if (this.windowsPathsNoEscape) {
2570
+ this.pattern = this.pattern.replace(/\\/g, '/');
2571
+ }
2572
+ this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
2573
+ this.regexp = null;
2574
+ this.negate = false;
2575
+ this.nonegate = !!options.nonegate;
2576
+ this.comment = false;
2577
+ this.empty = false;
2578
+ this.partial = !!options.partial;
2579
+ this.nocase = !!this.options.nocase;
2580
+ this.windowsNoMagicRoot =
2581
+ options.windowsNoMagicRoot !== undefined ?
2582
+ options.windowsNoMagicRoot
2583
+ : !!(this.isWindows && this.nocase);
2584
+ this.globSet = [];
2585
+ this.globParts = [];
2586
+ this.set = [];
2587
+ // make the set of regexps etc.
2588
+ this.make();
2589
+ }
2590
+ hasMagic() {
2591
+ if (this.options.magicalBraces && this.set.length > 1) {
2592
+ return true;
2593
+ }
2594
+ for (const pattern of this.set) {
2595
+ for (const part of pattern) {
2596
+ if (typeof part !== 'string')
2597
+ return true;
2598
+ }
2599
+ }
2600
+ return false;
2601
+ }
2602
+ debug(..._) { }
2603
+ make() {
2604
+ const pattern = this.pattern;
2605
+ const options = this.options;
2606
+ // empty patterns and comments match nothing.
2607
+ if (!options.nocomment && pattern.charAt(0) === '#') {
2608
+ this.comment = true;
2609
+ return;
2610
+ }
2611
+ if (!pattern) {
2612
+ this.empty = true;
2613
+ return;
2614
+ }
2615
+ // step 1: figure out negation, etc.
2616
+ this.parseNegate();
2617
+ // step 2: expand braces
2618
+ this.globSet = [...new Set(this.braceExpand())];
2619
+ if (options.debug) {
2620
+ //oxlint-disable-next-line no-console
2621
+ this.debug = (...args) => console.error(...args);
2622
+ }
2623
+ this.debug(this.pattern, this.globSet);
2624
+ // step 3: now we have a set, so turn each one into a series of
2625
+ // path-portion matching patterns.
2626
+ // These will be regexps, except in the case of "**", which is
2627
+ // set to the GLOBSTAR object for globstar behavior,
2628
+ // and will not contain any / characters
2629
+ //
2630
+ // First, we preprocess to make the glob pattern sets a bit simpler
2631
+ // and deduped. There are some perf-killing patterns that can cause
2632
+ // problems with a glob walk, but we can simplify them down a bit.
2633
+ const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
2634
+ this.globParts = this.preprocess(rawGlobParts);
2635
+ this.debug(this.pattern, this.globParts);
2636
+ // glob --> regexps
2637
+ let set = this.globParts.map((s, _, __) => {
2638
+ if (this.isWindows && this.windowsNoMagicRoot) {
2639
+ // check if it's a drive or unc path.
2640
+ const isUNC = s[0] === '' &&
2641
+ s[1] === '' &&
2642
+ (s[2] === '?' || !globMagic.test(s[2])) &&
2643
+ !globMagic.test(s[3]);
2644
+ const isDrive = /^[a-z]:/i.test(s[0]);
2645
+ if (isUNC) {
2646
+ return [
2647
+ ...s.slice(0, 4),
2648
+ ...s.slice(4).map(ss => this.parse(ss)),
2649
+ ];
2650
+ }
2651
+ else if (isDrive) {
2652
+ return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
2653
+ }
2654
+ }
2655
+ return s.map(ss => this.parse(ss));
2656
+ });
2657
+ this.debug(this.pattern, set);
2658
+ // filter out everything that didn't compile properly.
2659
+ this.set = set.filter(s => s.indexOf(false) === -1);
2660
+ // do not treat the ? in UNC paths as magic
2661
+ if (this.isWindows) {
2662
+ for (let i = 0; i < this.set.length; i++) {
2663
+ const p = this.set[i];
2664
+ if (p[0] === '' &&
2665
+ p[1] === '' &&
2666
+ this.globParts[i][2] === '?' &&
2667
+ typeof p[3] === 'string' &&
2668
+ /^[a-z]:$/i.test(p[3])) {
2669
+ p[2] = '?';
2670
+ }
2671
+ }
2672
+ }
2673
+ this.debug(this.pattern, this.set);
2674
+ }
2675
+ // various transforms to equivalent pattern sets that are
2676
+ // faster to process in a filesystem walk. The goal is to
2677
+ // eliminate what we can, and push all ** patterns as far
2678
+ // to the right as possible, even if it increases the number
2679
+ // of patterns that we have to process.
2680
+ preprocess(globParts) {
2681
+ // if we're not in globstar mode, then turn ** into *
2682
+ if (this.options.noglobstar) {
2683
+ for (const partset of globParts) {
2684
+ for (let j = 0; j < partset.length; j++) {
2685
+ if (partset[j] === '**') {
2686
+ partset[j] = '*';
2687
+ }
2688
+ }
2689
+ }
2690
+ }
2691
+ const { optimizationLevel = 1 } = this.options;
2692
+ if (optimizationLevel >= 2) {
2693
+ // aggressive optimization for the purpose of fs walking
2694
+ globParts = this.firstPhasePreProcess(globParts);
2695
+ globParts = this.secondPhasePreProcess(globParts);
2696
+ }
2697
+ else if (optimizationLevel >= 1) {
2698
+ // just basic optimizations to remove some .. parts
2699
+ globParts = this.levelOneOptimize(globParts);
2700
+ }
2701
+ else {
2702
+ // just collapse multiple ** portions into one
2703
+ globParts = this.adjascentGlobstarOptimize(globParts);
2704
+ }
2705
+ return globParts;
2706
+ }
2707
+ // just get rid of adjascent ** portions
2708
+ adjascentGlobstarOptimize(globParts) {
2709
+ return globParts.map(parts => {
2710
+ let gs = -1;
2711
+ while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
2712
+ let i = gs;
2713
+ while (parts[i + 1] === '**') {
2714
+ i++;
2715
+ }
2716
+ if (i !== gs) {
2717
+ parts.splice(gs, i - gs);
2718
+ }
2719
+ }
2720
+ return parts;
2721
+ });
2722
+ }
2723
+ // get rid of adjascent ** and resolve .. portions
2724
+ levelOneOptimize(globParts) {
2725
+ return globParts.map(parts => {
2726
+ parts = parts.reduce((set, part) => {
2727
+ const prev = set[set.length - 1];
2728
+ if (part === '**' && prev === '**') {
2729
+ return set;
2730
+ }
2731
+ if (part === '..') {
2732
+ if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
2733
+ set.pop();
2734
+ return set;
2735
+ }
2736
+ }
2737
+ set.push(part);
2738
+ return set;
2739
+ }, []);
2740
+ return parts.length === 0 ? [''] : parts;
2741
+ });
2742
+ }
2743
+ levelTwoFileOptimize(parts) {
2744
+ if (!Array.isArray(parts)) {
2745
+ parts = this.slashSplit(parts);
2746
+ }
2747
+ let didSomething = false;
2748
+ do {
2749
+ didSomething = false;
2750
+ // <pre>/<e>/<rest> -> <pre>/<rest>
2751
+ if (!this.preserveMultipleSlashes) {
2752
+ for (let i = 1; i < parts.length - 1; i++) {
2753
+ const p = parts[i];
2754
+ // don't squeeze out UNC patterns
2755
+ if (i === 1 && p === '' && parts[0] === '')
2756
+ continue;
2757
+ if (p === '.' || p === '') {
2758
+ didSomething = true;
2759
+ parts.splice(i, 1);
2760
+ i--;
2761
+ }
2762
+ }
2763
+ if (parts[0] === '.' &&
2764
+ parts.length === 2 &&
2765
+ (parts[1] === '.' || parts[1] === '')) {
2766
+ didSomething = true;
2767
+ parts.pop();
2768
+ }
2769
+ }
2770
+ // <pre>/<p>/../<rest> -> <pre>/<rest>
2771
+ let dd = 0;
2772
+ while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
2773
+ const p = parts[dd - 1];
2774
+ if (p &&
2775
+ p !== '.' &&
2776
+ p !== '..' &&
2777
+ p !== '**' &&
2778
+ !(this.isWindows && /^[a-z]:$/i.test(p))) {
2779
+ didSomething = true;
2780
+ parts.splice(dd - 1, 2);
2781
+ dd -= 2;
2782
+ }
2783
+ }
2784
+ } while (didSomething);
2785
+ return parts.length === 0 ? [''] : parts;
2786
+ }
2787
+ // First phase: single-pattern processing
2788
+ // <pre> is 1 or more portions
2789
+ // <rest> is 1 or more portions
2790
+ // <p> is any portion other than ., .., '', or **
2791
+ // <e> is . or ''
2792
+ //
2793
+ // **/.. is *brutal* for filesystem walking performance, because
2794
+ // it effectively resets the recursive walk each time it occurs,
2795
+ // and ** cannot be reduced out by a .. pattern part like a regexp
2796
+ // or most strings (other than .., ., and '') can be.
2797
+ //
2798
+ // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
2799
+ // <pre>/<e>/<rest> -> <pre>/<rest>
2800
+ // <pre>/<p>/../<rest> -> <pre>/<rest>
2801
+ // **/**/<rest> -> **/<rest>
2802
+ //
2803
+ // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
2804
+ // this WOULD be allowed if ** did follow symlinks, or * didn't
2805
+ firstPhasePreProcess(globParts) {
2806
+ let didSomething = false;
2807
+ do {
2808
+ didSomething = false;
2809
+ // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
2810
+ for (let parts of globParts) {
2811
+ let gs = -1;
2812
+ while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
2813
+ let gss = gs;
2814
+ while (parts[gss + 1] === '**') {
2815
+ // <pre>/**/**/<rest> -> <pre>/**/<rest>
2816
+ gss++;
2817
+ }
2818
+ // eg, if gs is 2 and gss is 4, that means we have 3 **
2819
+ // parts, and can remove 2 of them.
2820
+ if (gss > gs) {
2821
+ parts.splice(gs + 1, gss - gs);
2822
+ }
2823
+ let next = parts[gs + 1];
2824
+ const p = parts[gs + 2];
2825
+ const p2 = parts[gs + 3];
2826
+ if (next !== '..')
2827
+ continue;
2828
+ if (!p ||
2829
+ p === '.' ||
2830
+ p === '..' ||
2831
+ !p2 ||
2832
+ p2 === '.' ||
2833
+ p2 === '..') {
2834
+ continue;
2835
+ }
2836
+ didSomething = true;
2837
+ // edit parts in place, and push the new one
2838
+ parts.splice(gs, 1);
2839
+ const other = parts.slice(0);
2840
+ other[gs] = '**';
2841
+ globParts.push(other);
2842
+ gs--;
2843
+ }
2844
+ // <pre>/<e>/<rest> -> <pre>/<rest>
2845
+ if (!this.preserveMultipleSlashes) {
2846
+ for (let i = 1; i < parts.length - 1; i++) {
2847
+ const p = parts[i];
2848
+ // don't squeeze out UNC patterns
2849
+ if (i === 1 && p === '' && parts[0] === '')
2850
+ continue;
2851
+ if (p === '.' || p === '') {
2852
+ didSomething = true;
2853
+ parts.splice(i, 1);
2854
+ i--;
2855
+ }
2856
+ }
2857
+ if (parts[0] === '.' &&
2858
+ parts.length === 2 &&
2859
+ (parts[1] === '.' || parts[1] === '')) {
2860
+ didSomething = true;
2861
+ parts.pop();
2862
+ }
2863
+ }
2864
+ // <pre>/<p>/../<rest> -> <pre>/<rest>
2865
+ let dd = 0;
2866
+ while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
2867
+ const p = parts[dd - 1];
2868
+ if (p && p !== '.' && p !== '..' && p !== '**') {
2869
+ didSomething = true;
2870
+ const needDot = dd === 1 && parts[dd + 1] === '**';
2871
+ const splin = needDot ? ['.'] : [];
2872
+ parts.splice(dd - 1, 2, ...splin);
2873
+ if (parts.length === 0)
2874
+ parts.push('');
2875
+ dd -= 2;
2876
+ }
2877
+ }
2878
+ }
2879
+ } while (didSomething);
2880
+ return globParts;
2881
+ }
2882
+ // second phase: multi-pattern dedupes
2883
+ // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
2884
+ // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
2885
+ // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
2886
+ //
2887
+ // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
2888
+ // ^-- not valid because ** doens't follow symlinks
2889
+ secondPhasePreProcess(globParts) {
2890
+ for (let i = 0; i < globParts.length - 1; i++) {
2891
+ for (let j = i + 1; j < globParts.length; j++) {
2892
+ const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
2893
+ if (matched) {
2894
+ globParts[i] = [];
2895
+ globParts[j] = matched;
2896
+ break;
2897
+ }
2898
+ }
2899
+ }
2900
+ return globParts.filter(gs => gs.length);
2901
+ }
2902
+ partsMatch(a, b, emptyGSMatch = false) {
2903
+ let ai = 0;
2904
+ let bi = 0;
2905
+ let result = [];
2906
+ let which = '';
2907
+ while (ai < a.length && bi < b.length) {
2908
+ if (a[ai] === b[bi]) {
2909
+ result.push(which === 'b' ? b[bi] : a[ai]);
2910
+ ai++;
2911
+ bi++;
2912
+ }
2913
+ else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
2914
+ result.push(a[ai]);
2915
+ ai++;
2916
+ }
2917
+ else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
2918
+ result.push(b[bi]);
2919
+ bi++;
2920
+ }
2921
+ else if (a[ai] === '*' &&
2922
+ b[bi] &&
2923
+ (this.options.dot || !b[bi].startsWith('.')) &&
2924
+ b[bi] !== '**') {
2925
+ if (which === 'b')
2926
+ return false;
2927
+ which = 'a';
2928
+ result.push(a[ai]);
2929
+ ai++;
2930
+ bi++;
2931
+ }
2932
+ else if (b[bi] === '*' &&
2933
+ a[ai] &&
2934
+ (this.options.dot || !a[ai].startsWith('.')) &&
2935
+ a[ai] !== '**') {
2936
+ if (which === 'a')
2937
+ return false;
2938
+ which = 'b';
2939
+ result.push(b[bi]);
2940
+ ai++;
2941
+ bi++;
2942
+ }
2943
+ else {
2944
+ return false;
2945
+ }
2946
+ }
2947
+ // if we fall out of the loop, it means they two are identical
2948
+ // as long as their lengths match
2949
+ return a.length === b.length && result;
2950
+ }
2951
+ parseNegate() {
2952
+ if (this.nonegate)
2953
+ return;
2954
+ const pattern = this.pattern;
2955
+ let negate = false;
2956
+ let negateOffset = 0;
2957
+ for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
2958
+ negate = !negate;
2959
+ negateOffset++;
2960
+ }
2961
+ if (negateOffset)
2962
+ this.pattern = pattern.slice(negateOffset);
2963
+ this.negate = negate;
2964
+ }
2965
+ // set partial to true to test if, for example,
2966
+ // "/a/b" matches the start of "/*/b/*/d"
2967
+ // Partial means, if you run out of file before you run
2968
+ // out of pattern, then that's fine, as long as all
2969
+ // the parts match.
2970
+ matchOne(file, pattern, partial = false) {
2971
+ let fileStartIndex = 0;
2972
+ let patternStartIndex = 0;
2973
+ // UNC paths like //?/X:/... can match X:/... and vice versa
2974
+ // Drive letters in absolute drive or unc paths are always compared
2975
+ // case-insensitively.
2976
+ if (this.isWindows) {
2977
+ const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
2978
+ const fileUNC = !fileDrive &&
2979
+ file[0] === '' &&
2980
+ file[1] === '' &&
2981
+ file[2] === '?' &&
2982
+ /^[a-z]:$/i.test(file[3]);
2983
+ const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
2984
+ const patternUNC = !patternDrive &&
2985
+ pattern[0] === '' &&
2986
+ pattern[1] === '' &&
2987
+ pattern[2] === '?' &&
2988
+ typeof pattern[3] === 'string' &&
2989
+ /^[a-z]:$/i.test(pattern[3]);
2990
+ const fdi = fileUNC ? 3
2991
+ : fileDrive ? 0
2992
+ : undefined;
2993
+ const pdi = patternUNC ? 3
2994
+ : patternDrive ? 0
2995
+ : undefined;
2996
+ if (typeof fdi === 'number' && typeof pdi === 'number') {
2997
+ const [fd, pd] = [
2998
+ file[fdi],
2999
+ pattern[pdi],
3000
+ ];
3001
+ // start matching at the drive letter index of each
3002
+ if (fd.toLowerCase() === pd.toLowerCase()) {
3003
+ pattern[pdi] = fd;
3004
+ patternStartIndex = pdi;
3005
+ fileStartIndex = fdi;
3006
+ }
3007
+ }
3008
+ }
3009
+ // resolve and reduce . and .. portions in the file as well.
3010
+ // don't need to do the second phase, because it's only one string[]
3011
+ const { optimizationLevel = 1 } = this.options;
3012
+ if (optimizationLevel >= 2) {
3013
+ file = this.levelTwoFileOptimize(file);
3014
+ }
3015
+ if (pattern.includes(GLOBSTAR)) {
3016
+ return this.#matchGlobstar(file, pattern, partial, fileStartIndex, patternStartIndex);
3017
+ }
3018
+ return this.#matchOne(file, pattern, partial, fileStartIndex, patternStartIndex);
3019
+ }
3020
+ #matchGlobstar(file, pattern, partial, fileIndex, patternIndex) {
3021
+ // split the pattern into head, tail, and middle of ** delimited parts
3022
+ const firstgs = pattern.indexOf(GLOBSTAR, patternIndex);
3023
+ const lastgs = pattern.lastIndexOf(GLOBSTAR);
3024
+ // split the pattern up into globstar-delimited sections
3025
+ // the tail has to be at the end, and the others just have
3026
+ // to be found in order from the head.
3027
+ const [head, body, tail] = partial ?
3028
+ [
3029
+ pattern.slice(patternIndex, firstgs),
3030
+ pattern.slice(firstgs + 1),
3031
+ [],
3032
+ ]
3033
+ : [
3034
+ pattern.slice(patternIndex, firstgs),
3035
+ pattern.slice(firstgs + 1, lastgs),
3036
+ pattern.slice(lastgs + 1),
3037
+ ];
3038
+ // check the head, from the current file/pattern index.
3039
+ if (head.length) {
3040
+ const fileHead = file.slice(fileIndex, fileIndex + head.length);
3041
+ if (!this.#matchOne(fileHead, head, partial, 0, 0)) {
3042
+ return false;
3043
+ }
3044
+ fileIndex += head.length;
3045
+ patternIndex += head.length;
3046
+ }
3047
+ // now we know the head matches!
3048
+ // if the last portion is not empty, it MUST match the end
3049
+ // check the tail
3050
+ let fileTailMatch = 0;
3051
+ if (tail.length) {
3052
+ // if head + tail > file, then we cannot possibly match
3053
+ if (tail.length + fileIndex > file.length)
3054
+ return false;
3055
+ // try to match the tail
3056
+ let tailStart = file.length - tail.length;
3057
+ if (this.#matchOne(file, tail, partial, tailStart, 0)) {
3058
+ fileTailMatch = tail.length;
3059
+ }
3060
+ else {
3061
+ // affordance for stuff like a/**/* matching a/b/
3062
+ // if the last file portion is '', and there's more to the pattern
3063
+ // then try without the '' bit.
3064
+ if (file[file.length - 1] !== '' ||
3065
+ fileIndex + tail.length === file.length) {
3066
+ return false;
3067
+ }
3068
+ tailStart--;
3069
+ if (!this.#matchOne(file, tail, partial, tailStart, 0)) {
3070
+ return false;
3071
+ }
3072
+ fileTailMatch = tail.length + 1;
3073
+ }
3074
+ }
3075
+ // now we know the tail matches!
3076
+ // the middle is zero or more portions wrapped in **, possibly
3077
+ // containing more ** sections.
3078
+ // so a/**/b/**/c/**/d has become **/b/**/c/**
3079
+ // if it's empty, it means a/**/b, just verify we have no bad dots
3080
+ // if there's no tail, so it ends on /**, then we must have *something*
3081
+ // after the head, or it's not a matc
3082
+ if (!body.length) {
3083
+ let sawSome = !!fileTailMatch;
3084
+ for (let i = fileIndex; i < file.length - fileTailMatch; i++) {
3085
+ const f = String(file[i]);
3086
+ sawSome = true;
3087
+ if (f === '.' ||
3088
+ f === '..' ||
3089
+ (!this.options.dot && f.startsWith('.'))) {
3090
+ return false;
3091
+ }
3092
+ }
3093
+ // in partial mode, we just need to get past all file parts
3094
+ return partial || sawSome;
3095
+ }
3096
+ // now we know that there's one or more body sections, which can
3097
+ // be matched anywhere from the 0 index (because the head was pruned)
3098
+ // through to the length-fileTailMatch index.
3099
+ // split the body up into sections, and note the minimum index it can
3100
+ // be found at (start with the length of all previous segments)
3101
+ // [section, before, after]
3102
+ const bodySegments = [[[], 0]];
3103
+ let currentBody = bodySegments[0];
3104
+ let nonGsParts = 0;
3105
+ const nonGsPartsSums = [0];
3106
+ for (const b of body) {
3107
+ if (b === GLOBSTAR) {
3108
+ nonGsPartsSums.push(nonGsParts);
3109
+ currentBody = [[], 0];
3110
+ bodySegments.push(currentBody);
3111
+ }
3112
+ else {
3113
+ currentBody[0].push(b);
3114
+ nonGsParts++;
3115
+ }
3116
+ }
3117
+ let i = bodySegments.length - 1;
3118
+ const fileLength = file.length - fileTailMatch;
3119
+ for (const b of bodySegments) {
3120
+ b[1] = fileLength - (nonGsPartsSums[i--] + b[0].length);
3121
+ }
3122
+ return !!this.#matchGlobStarBodySections(file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch);
3123
+ }
3124
+ // return false for "nope, not matching"
3125
+ // return null for "not matching, cannot keep trying"
3126
+ #matchGlobStarBodySections(file,
3127
+ // pattern section, last possible position for it
3128
+ bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail) {
3129
+ // take the first body segment, and walk from fileIndex to its "after"
3130
+ // value at the end
3131
+ // If it doesn't match at that position, we increment, until we hit
3132
+ // that final possible position, and give up.
3133
+ // If it does match, then advance and try to rest.
3134
+ // If any of them fail we keep walking forward.
3135
+ // this is still a bit recursively painful, but it's more constrained
3136
+ // than previous implementations, because we never test something that
3137
+ // can't possibly be a valid matching condition.
3138
+ const bs = bodySegments[bodyIndex];
3139
+ if (!bs) {
3140
+ // just make sure that there's no bad dots
3141
+ for (let i = fileIndex; i < file.length; i++) {
3142
+ sawTail = true;
3143
+ const f = file[i];
3144
+ if (f === '.' ||
3145
+ f === '..' ||
3146
+ (!this.options.dot && f.startsWith('.'))) {
3147
+ return false;
3148
+ }
3149
+ }
3150
+ return sawTail;
3151
+ }
3152
+ // have a non-globstar body section to test
3153
+ const [body, after] = bs;
3154
+ while (fileIndex <= after) {
3155
+ const m = this.#matchOne(file.slice(0, fileIndex + body.length), body, partial, fileIndex, 0);
3156
+ // if limit exceeded, no match. intentional false negative,
3157
+ // acceptable break in correctness for security.
3158
+ if (m && globStarDepth < this.maxGlobstarRecursion) {
3159
+ // match! see if the rest match. if so, we're done!
3160
+ const sub = this.#matchGlobStarBodySections(file, bodySegments, fileIndex + body.length, bodyIndex + 1, partial, globStarDepth + 1, sawTail);
3161
+ if (sub !== false) {
3162
+ return sub;
3163
+ }
3164
+ }
3165
+ const f = file[fileIndex];
3166
+ if (f === '.' ||
3167
+ f === '..' ||
3168
+ (!this.options.dot && f.startsWith('.'))) {
3169
+ return false;
3170
+ }
3171
+ fileIndex++;
3172
+ }
3173
+ // walked off. no point continuing
3174
+ return partial || null;
3175
+ }
3176
+ #matchOne(file, pattern, partial, fileIndex, patternIndex) {
3177
+ let fi;
3178
+ let pi;
3179
+ let pl;
3180
+ let fl;
3181
+ for (fi = fileIndex,
3182
+ pi = patternIndex,
3183
+ fl = file.length,
3184
+ pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
3185
+ this.debug('matchOne loop');
3186
+ let p = pattern[pi];
3187
+ let f = file[fi];
3188
+ this.debug(pattern, p, f);
3189
+ // should be impossible.
3190
+ // some invalid regexp stuff in the set.
3191
+ /* c8 ignore start */
3192
+ if (p === false || p === GLOBSTAR) {
3193
+ return false;
3194
+ }
3195
+ /* c8 ignore stop */
3196
+ // something other than **
3197
+ // non-magic patterns just have to match exactly
3198
+ // patterns with magic have been turned into regexps.
3199
+ let hit;
3200
+ if (typeof p === 'string') {
3201
+ hit = f === p;
3202
+ this.debug('string match', p, f, hit);
3203
+ }
3204
+ else {
3205
+ hit = p.test(f);
3206
+ this.debug('pattern match', p, f, hit);
3207
+ }
3208
+ if (!hit)
3209
+ return false;
3210
+ }
3211
+ // Note: ending in / means that we'll get a final ""
3212
+ // at the end of the pattern. This can only match a
3213
+ // corresponding "" at the end of the file.
3214
+ // If the file ends in /, then it can only match a
3215
+ // a pattern that ends in /, unless the pattern just
3216
+ // doesn't have any more for it. But, a/b/ should *not*
3217
+ // match "a/b/*", even though "" matches against the
3218
+ // [^/]*? pattern, except in partial mode, where it might
3219
+ // simply not be reached yet.
3220
+ // However, a/b/ should still satisfy a/*
3221
+ // now either we fell off the end of the pattern, or we're done.
3222
+ if (fi === fl && pi === pl) {
3223
+ // ran out of pattern and filename at the same time.
3224
+ // an exact hit!
3225
+ return true;
3226
+ }
3227
+ else if (fi === fl) {
3228
+ // ran out of file, but still had pattern left.
3229
+ // this is ok if we're doing the match as part of
3230
+ // a glob fs traversal.
3231
+ return partial;
3232
+ }
3233
+ else if (pi === pl) {
3234
+ // ran out of pattern, still have file left.
3235
+ // this is only acceptable if we're on the very last
3236
+ // empty segment of a file with a trailing slash.
3237
+ // a/* should match a/b/
3238
+ return fi === fl - 1 && file[fi] === '';
3239
+ /* c8 ignore start */
3240
+ }
3241
+ else {
3242
+ // should be unreachable.
3243
+ throw new Error('wtf?');
3244
+ }
3245
+ /* c8 ignore stop */
3246
+ }
3247
+ braceExpand() {
3248
+ return braceExpand(this.pattern, this.options);
3249
+ }
3250
+ parse(pattern) {
3251
+ assertValidPattern(pattern);
3252
+ const options = this.options;
3253
+ // shortcuts
3254
+ if (pattern === '**')
3255
+ return GLOBSTAR;
3256
+ if (pattern === '')
3257
+ return '';
3258
+ // far and away, the most common glob pattern parts are
3259
+ // *, *.*, and *.<ext> Add a fast check method for those.
3260
+ let m;
3261
+ let fastTest = null;
3262
+ if ((m = pattern.match(starRE))) {
3263
+ fastTest = options.dot ? starTestDot : starTest;
3264
+ }
3265
+ else if ((m = pattern.match(starDotExtRE))) {
3266
+ fastTest = (options.nocase ?
3267
+ options.dot ?
3268
+ starDotExtTestNocaseDot
3269
+ : starDotExtTestNocase
3270
+ : options.dot ? starDotExtTestDot
3271
+ : starDotExtTest)(m[1]);
3272
+ }
3273
+ else if ((m = pattern.match(qmarksRE))) {
3274
+ fastTest = (options.nocase ?
3275
+ options.dot ?
3276
+ qmarksTestNocaseDot
3277
+ : qmarksTestNocase
3278
+ : options.dot ? qmarksTestDot
3279
+ : qmarksTest)(m);
3280
+ }
3281
+ else if ((m = pattern.match(starDotStarRE))) {
3282
+ fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
3283
+ }
3284
+ else if ((m = pattern.match(dotStarRE))) {
3285
+ fastTest = dotStarTest;
3286
+ }
3287
+ const re = AST.fromGlob(pattern, this.options).toMMPattern();
3288
+ if (fastTest && typeof re === 'object') {
3289
+ // Avoids overriding in frozen environments
3290
+ Reflect.defineProperty(re, 'test', { value: fastTest });
3291
+ }
3292
+ return re;
3293
+ }
3294
+ makeRe() {
3295
+ if (this.regexp || this.regexp === false)
3296
+ return this.regexp;
3297
+ // at this point, this.set is a 2d array of partial
3298
+ // pattern strings, or "**".
3299
+ //
3300
+ // It's better to use .match(). This function shouldn't
3301
+ // be used, really, but it's pretty convenient sometimes,
3302
+ // when you just want to work with a regex.
3303
+ const set = this.set;
3304
+ if (!set.length) {
3305
+ this.regexp = false;
3306
+ return this.regexp;
3307
+ }
3308
+ const options = this.options;
3309
+ const twoStar = options.noglobstar ? star
3310
+ : options.dot ? twoStarDot
3311
+ : twoStarNoDot;
3312
+ const flags = new Set(options.nocase ? ['i'] : []);
3313
+ // regexpify non-globstar patterns
3314
+ // if ** is only item, then we just do one twoStar
3315
+ // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
3316
+ // if ** is last, append (\/twoStar|) to previous
3317
+ // if ** is in the middle, append (\/|\/twoStar\/) to previous
3318
+ // then filter out GLOBSTAR symbols
3319
+ let re = set
3320
+ .map(pattern => {
3321
+ const pp = pattern.map(p => {
3322
+ if (p instanceof RegExp) {
3323
+ for (const f of p.flags.split(''))
3324
+ flags.add(f);
3325
+ }
3326
+ return (typeof p === 'string' ? regExpEscape(p)
3327
+ : p === GLOBSTAR ? GLOBSTAR
3328
+ : p._src);
3329
+ });
3330
+ pp.forEach((p, i) => {
3331
+ const next = pp[i + 1];
3332
+ const prev = pp[i - 1];
3333
+ if (p !== GLOBSTAR || prev === GLOBSTAR) {
3334
+ return;
3335
+ }
3336
+ if (prev === undefined) {
3337
+ if (next !== undefined && next !== GLOBSTAR) {
3338
+ pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
3339
+ }
3340
+ else {
3341
+ pp[i] = twoStar;
3342
+ }
3343
+ }
3344
+ else if (next === undefined) {
3345
+ pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + ')?';
3346
+ }
3347
+ else if (next !== GLOBSTAR) {
3348
+ pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
3349
+ pp[i + 1] = GLOBSTAR;
3350
+ }
3351
+ });
3352
+ const filtered = pp.filter(p => p !== GLOBSTAR);
3353
+ // For partial matches, we need to make the pattern match
3354
+ // any prefix of the full path. We do this by generating
3355
+ // alternative patterns that match progressively longer prefixes.
3356
+ if (this.partial && filtered.length >= 1) {
3357
+ const prefixes = [];
3358
+ for (let i = 1; i <= filtered.length; i++) {
3359
+ prefixes.push(filtered.slice(0, i).join('/'));
3360
+ }
3361
+ return '(?:' + prefixes.join('|') + ')';
3362
+ }
3363
+ return filtered.join('/');
3364
+ })
3365
+ .join('|');
3366
+ // need to wrap in parens if we had more than one thing with |,
3367
+ // otherwise only the first will be anchored to ^ and the last to $
3368
+ const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
3369
+ // must match entire pattern
3370
+ // ending in a * or ** will make it less strict.
3371
+ re = '^' + open + re + close + '$';
3372
+ // In partial mode, '/' should always match as it's a valid prefix for any pattern
3373
+ if (this.partial) {
3374
+ re = '^(?:\\/|' + open + re.slice(1, -1) + close + ')$';
3375
+ }
3376
+ // can match anything, as long as it's not this.
3377
+ if (this.negate)
3378
+ re = '^(?!' + re + ').+$';
3379
+ try {
3380
+ this.regexp = new RegExp(re, [...flags].join(''));
3381
+ /* c8 ignore start */
3382
+ }
3383
+ catch {
3384
+ // should be impossible
3385
+ this.regexp = false;
3386
+ }
3387
+ /* c8 ignore stop */
3388
+ return this.regexp;
3389
+ }
3390
+ slashSplit(p) {
3391
+ // if p starts with // on windows, we preserve that
3392
+ // so that UNC paths aren't broken. Otherwise, any number of
3393
+ // / characters are coalesced into one, unless
3394
+ // preserveMultipleSlashes is set to true.
3395
+ if (this.preserveMultipleSlashes) {
3396
+ return p.split('/');
3397
+ }
3398
+ else if (this.isWindows && /^\/\/[^/]+/.test(p)) {
3399
+ // add an extra '' for the one we lose
3400
+ return ['', ...p.split(/\/+/)];
3401
+ }
3402
+ else {
3403
+ return p.split(/\/+/);
3404
+ }
3405
+ }
3406
+ match(f, partial = this.partial) {
3407
+ this.debug('match', f, this.pattern);
3408
+ // short-circuit in the case of busted things.
3409
+ // comments, etc.
3410
+ if (this.comment) {
3411
+ return false;
3412
+ }
3413
+ if (this.empty) {
3414
+ return f === '';
3415
+ }
3416
+ if (f === '/' && partial) {
3417
+ return true;
3418
+ }
3419
+ const options = this.options;
3420
+ // windows: need to use /, not \
3421
+ if (this.isWindows) {
3422
+ f = f.split('\\').join('/');
3423
+ }
3424
+ // treat the test path as a set of pathparts.
3425
+ const ff = this.slashSplit(f);
3426
+ this.debug(this.pattern, 'split', ff);
3427
+ // just ONE of the pattern sets in this.set needs to match
3428
+ // in order for it to be valid. If negating, then just one
3429
+ // match means that we have failed.
3430
+ // Either way, return on the first hit.
3431
+ const set = this.set;
3432
+ this.debug(this.pattern, 'set', set);
3433
+ // Find the basename of the path by looking for the last non-empty segment
3434
+ let filename = ff[ff.length - 1];
3435
+ if (!filename) {
3436
+ for (let i = ff.length - 2; !filename && i >= 0; i--) {
3437
+ filename = ff[i];
3438
+ }
3439
+ }
3440
+ for (const pattern of set) {
3441
+ let file = ff;
3442
+ if (options.matchBase && pattern.length === 1) {
3443
+ file = [filename];
3444
+ }
3445
+ const hit = this.matchOne(file, pattern, partial);
3446
+ if (hit) {
3447
+ if (options.flipNegate) {
3448
+ return true;
3449
+ }
3450
+ return !this.negate;
3451
+ }
3452
+ }
3453
+ // didn't get any hits. this is success if it's a negative
3454
+ // pattern, failure otherwise.
3455
+ if (options.flipNegate) {
3456
+ return false;
3457
+ }
3458
+ return this.negate;
3459
+ }
3460
+ static defaults(def) {
3461
+ return minimatch.defaults(def).Minimatch;
3462
+ }
3463
+ }
3464
+ /* c8 ignore stop */
3465
+ minimatch.AST = AST;
3466
+ minimatch.Minimatch = Minimatch;
3467
+ minimatch.escape = escape;
3468
+ minimatch.unescape = unescape;
3469
+
3470
+ class FluxionRouter {
3471
+ constructor(cx) {
3472
+ /**
3473
+ * This means the request has been handled by static resource handler, and no more response should be sent.
3474
+ */
3475
+ this.StaticHandled = Symbol.for('fluxion.router.StaticHandled');
3476
+ this.handlers = new Map();
3477
+ this.cx = cx;
3478
+ }
3479
+ makeStaticResource(filepath) {
3480
+ const fullPath = path$1.isAbsolute(this.cx.options.dir)
3481
+ ? path$1.join(this.cx.options.dir, filepath)
3482
+ : path$1.join(process.cwd(), this.cx.options.dir, filepath);
3483
+ return async (normalized, _req, res) => {
3484
+ if (normalized.method !== 'GET' && normalized.method !== 'HEAD') {
3485
+ res.statusCode = 405;
3486
+ res.setHeader('Allow', 'GET, HEAD');
3487
+ res.end();
3488
+ return;
3489
+ }
3490
+ if (!fs.existsSync(fullPath)) {
3491
+ res.statusCode = 404;
3492
+ res.end('Not Found');
3493
+ return;
3494
+ }
3495
+ const stat = fs.statSync(fullPath);
3496
+ if (!stat.isFile()) {
3497
+ res.statusCode = 404;
3498
+ res.end('Not Found');
3499
+ return;
3500
+ }
3501
+ const extension = path$1.extname(filepath).toLowerCase();
3502
+ const contentType = STATIC_CONTENT_TYPES[extension] ?? 'application/octet-stream';
3503
+ res.statusCode = 200;
3504
+ res.setHeader('Content-Type', contentType);
3505
+ res.setHeader('Content-Length', String(stat.size));
3506
+ if (normalized.method === 'HEAD') {
3507
+ res.end();
3508
+ return;
3509
+ }
3510
+ return new Promise((resolve, reject) => {
3511
+ const stream = fs.createReadStream(fullPath);
3512
+ stream.on('error', reject);
3513
+ stream.on('end', () => resolve(this.StaticHandled));
3514
+ stream.pipe(res);
3515
+ });
3516
+ };
3517
+ }
3518
+ /**
3519
+ * File registration logic with fast-glob pattern matching:
3520
+ * 1. Check if the path exists, if not, delete the handler;
3521
+ * 2. If file doesn't match include patterns, skip registration;
3522
+ * 3. If file matches exclude patterns, skip registration;
3523
+ * 4. If file matches apiInclude patterns, register as API handler;
3524
+ * 5. Otherwise, register as static resource.
3525
+ * @param filepath
3526
+ */
3527
+ register(filepath) {
3528
+ const fullpath = path$1.isAbsolute(this.cx.options.dir)
3529
+ ? path$1.join(this.cx.options.dir, filepath)
3530
+ : path$1.join(process.cwd(), this.cx.options.dir, filepath);
3531
+ if (!fs.existsSync(fullpath)) {
3532
+ this.handlers.delete(filepath);
3533
+ this.cx.logger.info(`[${filepath}] deleted`);
3534
+ return;
3535
+ }
3536
+ delete require.cache[fullpath];
3537
+ // Step 2: Check if file matches include patterns (default: all files)
3538
+ // If not matching, skip registration
3539
+ const matchesInclude = this.cx.options.include.some((pattern) => minimatch(filepath, pattern));
3540
+ if (!matchesInclude) {
3541
+ this.handlers.delete(filepath);
3542
+ this.cx.logger.info(`[${filepath}] skipped (not in include)`);
3543
+ return;
3544
+ }
3545
+ // Step 3: Check if file matches exclude patterns
3546
+ // If matching, skip registration
3547
+ const matchesExclude = this.cx.options.exclude.some((pattern) => minimatch(filepath, pattern));
3548
+ if (matchesExclude) {
1586
3549
  this.handlers.delete(filepath);
1587
3550
  this.cx.logger.info(`[${filepath}] excluded`);
1588
3551
  return;
1589
3552
  }
1590
- // register as api
1591
- // ! Files with extensions matching `apiExts` are considered as API handlers.
1592
- if (this.cx.options.apiExts.some((ext) => extension === ext)) {
3553
+ // Step 4 & 5: Check if file matches apiInclude patterns
3554
+ // If matching, register as API handler; otherwise as static resource
3555
+ const matchesApiInclude = this.cx.options.apiInclude.some((pattern) => minimatch(filepath, pattern));
3556
+ if (matchesApiInclude) {
1593
3557
  const handler = loadFunction({ modulePath: fullpath });
1594
3558
  this.handlers.set(filepath, handler);
1595
3559
  this.cx.logger.info(`[${filepath}] handler registered`);