@oliasoft-open-source/node-json-migrator 4.6.0-beta-2 → 5.0.0

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.cjs DELETED
@@ -1,4824 +0,0 @@
1
- 'use strict';
2
-
3
- var path = require('path');
4
- var fs$1 = require('fs');
5
- var crypto = require('crypto');
6
- var node_url = require('node:url');
7
- var node_path = require('node:path');
8
- var xi = require('node:fs');
9
- var promises = require('node:fs/promises');
10
- var node_events = require('node:events');
11
- var Pe = require('node:stream');
12
- var node_string_decoder = require('node:string_decoder');
13
- var process$1 = require('process');
14
- var child_process = require('child_process');
15
-
16
- function _interopNamespaceDefault(e) {
17
- var n = Object.create(null);
18
- if (e) {
19
- Object.keys(e).forEach(function (k) {
20
- if (k !== 'default') {
21
- var d = Object.getOwnPropertyDescriptor(e, k);
22
- Object.defineProperty(n, k, d.get ? d : {
23
- enumerable: true,
24
- get: function () { return e[k]; }
25
- });
26
- }
27
- });
28
- }
29
- n.default = e;
30
- return Object.freeze(n);
31
- }
32
-
33
- var xi__namespace = /*#__PURE__*/_interopNamespaceDefault(xi);
34
-
35
- const ANSI_BACKGROUND_OFFSET = 10;
36
- const wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
37
- const wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
38
- const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
39
- const styles$1 = {
40
- modifier: {
41
- reset: [0, 0],
42
- // 21 isn't widely supported and 22 does the same thing
43
- bold: [1, 22],
44
- dim: [2, 22],
45
- italic: [3, 23],
46
- underline: [4, 24],
47
- overline: [53, 55],
48
- inverse: [7, 27],
49
- hidden: [8, 28],
50
- strikethrough: [9, 29]
51
- },
52
- color: {
53
- black: [30, 39],
54
- red: [31, 39],
55
- green: [32, 39],
56
- yellow: [33, 39],
57
- blue: [34, 39],
58
- magenta: [35, 39],
59
- cyan: [36, 39],
60
- white: [37, 39],
61
- // Bright color
62
- blackBright: [90, 39],
63
- gray: [90, 39],
64
- // Alias of `blackBright`
65
- grey: [90, 39],
66
- // Alias of `blackBright`
67
- redBright: [91, 39],
68
- greenBright: [92, 39],
69
- yellowBright: [93, 39],
70
- blueBright: [94, 39],
71
- magentaBright: [95, 39],
72
- cyanBright: [96, 39],
73
- whiteBright: [97, 39]
74
- },
75
- bgColor: {
76
- bgBlack: [40, 49],
77
- bgRed: [41, 49],
78
- bgGreen: [42, 49],
79
- bgYellow: [43, 49],
80
- bgBlue: [44, 49],
81
- bgMagenta: [45, 49],
82
- bgCyan: [46, 49],
83
- bgWhite: [47, 49],
84
- // Bright color
85
- bgBlackBright: [100, 49],
86
- bgGray: [100, 49],
87
- // Alias of `bgBlackBright`
88
- bgGrey: [100, 49],
89
- // Alias of `bgBlackBright`
90
- bgRedBright: [101, 49],
91
- bgGreenBright: [102, 49],
92
- bgYellowBright: [103, 49],
93
- bgBlueBright: [104, 49],
94
- bgMagentaBright: [105, 49],
95
- bgCyanBright: [106, 49],
96
- bgWhiteBright: [107, 49]
97
- }
98
- };
99
- Object.keys(styles$1.modifier);
100
- const foregroundColorNames = Object.keys(styles$1.color);
101
- const backgroundColorNames = Object.keys(styles$1.bgColor);
102
- [...foregroundColorNames, ...backgroundColorNames];
103
- function assembleStyles() {
104
- const codes = /* @__PURE__ */ new Map();
105
- for (const [groupName, group] of Object.entries(styles$1)) {
106
- for (const [styleName, style] of Object.entries(group)) {
107
- styles$1[styleName] = {
108
- open: `\x1B[${style[0]}m`,
109
- close: `\x1B[${style[1]}m`
110
- };
111
- group[styleName] = styles$1[styleName];
112
- codes.set(style[0], style[1]);
113
- }
114
- Object.defineProperty(styles$1, groupName, {
115
- value: group,
116
- enumerable: false
117
- });
118
- }
119
- Object.defineProperty(styles$1, "codes", {
120
- value: codes,
121
- enumerable: false
122
- });
123
- styles$1.color.close = "\x1B[39m";
124
- styles$1.bgColor.close = "\x1B[49m";
125
- styles$1.color.ansi = wrapAnsi16();
126
- styles$1.color.ansi256 = wrapAnsi256();
127
- styles$1.color.ansi16m = wrapAnsi16m();
128
- styles$1.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
129
- styles$1.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
130
- styles$1.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
131
- Object.defineProperties(styles$1, {
132
- rgbToAnsi256: {
133
- value(red, green, blue) {
134
- if (red === green && green === blue) {
135
- if (red < 8) {
136
- return 16;
137
- }
138
- if (red > 248) {
139
- return 231;
140
- }
141
- return Math.round((red - 8) / 247 * 24) + 232;
142
- }
143
- return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
144
- },
145
- enumerable: false
146
- },
147
- hexToRgb: {
148
- value(hex) {
149
- const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
150
- if (!matches) {
151
- return [0, 0, 0];
152
- }
153
- let [colorString] = matches;
154
- if (colorString.length === 3) {
155
- colorString = [...colorString].map((character) => character + character).join("");
156
- }
157
- const integer = Number.parseInt(colorString, 16);
158
- return [
159
- /* eslint-disable no-bitwise */
160
- integer >> 16 & 255,
161
- integer >> 8 & 255,
162
- integer & 255
163
- /* eslint-enable no-bitwise */
164
- ];
165
- },
166
- enumerable: false
167
- },
168
- hexToAnsi256: {
169
- value: (hex) => styles$1.rgbToAnsi256(...styles$1.hexToRgb(hex)),
170
- enumerable: false
171
- },
172
- ansi256ToAnsi: {
173
- value(code) {
174
- if (code < 8) {
175
- return 30 + code;
176
- }
177
- if (code < 16) {
178
- return 90 + (code - 8);
179
- }
180
- let red;
181
- let green;
182
- let blue;
183
- if (code >= 232) {
184
- red = ((code - 232) * 10 + 8) / 255;
185
- green = red;
186
- blue = red;
187
- } else {
188
- code -= 16;
189
- const remainder = code % 36;
190
- red = Math.floor(code / 36) / 5;
191
- green = Math.floor(remainder / 6) / 5;
192
- blue = remainder % 6 / 5;
193
- }
194
- const value = Math.max(red, green, blue) * 2;
195
- if (value === 0) {
196
- return 30;
197
- }
198
- let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
199
- if (value === 2) {
200
- result += 60;
201
- }
202
- return result;
203
- },
204
- enumerable: false
205
- },
206
- rgbToAnsi: {
207
- value: (red, green, blue) => styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(red, green, blue)),
208
- enumerable: false
209
- },
210
- hexToAnsi: {
211
- value: (hex) => styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(hex)),
212
- enumerable: false
213
- }
214
- });
215
- return styles$1;
216
- }
217
- const ansiStyles = assembleStyles();
218
-
219
- const level = (() => {
220
- if (!("navigator" in globalThis)) {
221
- return 0;
222
- }
223
- if (globalThis.navigator.userAgentData) {
224
- const brand = navigator.userAgentData.brands.find(({ brand: brand2 }) => brand2 === "Chromium");
225
- if (brand && brand.version > 93) {
226
- return 3;
227
- }
228
- }
229
- if (/\b(Chrome|Chromium)\//.test(globalThis.navigator.userAgent)) {
230
- return 1;
231
- }
232
- return 0;
233
- })();
234
- const colorSupport = level !== 0 && {
235
- level};
236
- const supportsColor = {
237
- stdout: colorSupport,
238
- stderr: colorSupport
239
- };
240
-
241
- function stringReplaceAll(string, substring, replacer) {
242
- let index = string.indexOf(substring);
243
- if (index === -1) {
244
- return string;
245
- }
246
- const substringLength = substring.length;
247
- let endIndex = 0;
248
- let returnValue = "";
249
- do {
250
- returnValue += string.slice(endIndex, index) + substring + replacer;
251
- endIndex = index + substringLength;
252
- index = string.indexOf(substring, endIndex);
253
- } while (index !== -1);
254
- returnValue += string.slice(endIndex);
255
- return returnValue;
256
- }
257
- function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
258
- let endIndex = 0;
259
- let returnValue = "";
260
- do {
261
- const gotCR = string[index - 1] === "\r";
262
- returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
263
- endIndex = index + 1;
264
- index = string.indexOf("\n", endIndex);
265
- } while (index !== -1);
266
- returnValue += string.slice(endIndex);
267
- return returnValue;
268
- }
269
-
270
- const { stdout: stdoutColor, stderr: stderrColor } = supportsColor;
271
- const GENERATOR = Symbol("GENERATOR");
272
- const STYLER = Symbol("STYLER");
273
- const IS_EMPTY = Symbol("IS_EMPTY");
274
- const levelMapping = [
275
- "ansi",
276
- "ansi",
277
- "ansi256",
278
- "ansi16m"
279
- ];
280
- const styles = /* @__PURE__ */ Object.create(null);
281
- const applyOptions = (object, options = {}) => {
282
- if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
283
- throw new Error("The `level` option should be an integer from 0 to 3");
284
- }
285
- const colorLevel = stdoutColor ? stdoutColor.level : 0;
286
- object.level = options.level === void 0 ? colorLevel : options.level;
287
- };
288
- const chalkFactory = (options) => {
289
- const chalk2 = (...strings) => strings.join(" ");
290
- applyOptions(chalk2, options);
291
- Object.setPrototypeOf(chalk2, createChalk.prototype);
292
- return chalk2;
293
- };
294
- function createChalk(options) {
295
- return chalkFactory(options);
296
- }
297
- Object.setPrototypeOf(createChalk.prototype, Function.prototype);
298
- for (const [styleName, style] of Object.entries(ansiStyles)) {
299
- styles[styleName] = {
300
- get() {
301
- const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
302
- Object.defineProperty(this, styleName, { value: builder });
303
- return builder;
304
- }
305
- };
306
- }
307
- styles.visible = {
308
- get() {
309
- const builder = createBuilder(this, this[STYLER], true);
310
- Object.defineProperty(this, "visible", { value: builder });
311
- return builder;
312
- }
313
- };
314
- const getModelAnsi = (model, level, type, ...arguments_) => {
315
- if (model === "rgb") {
316
- if (level === "ansi16m") {
317
- return ansiStyles[type].ansi16m(...arguments_);
318
- }
319
- if (level === "ansi256") {
320
- return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));
321
- }
322
- return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));
323
- }
324
- if (model === "hex") {
325
- return getModelAnsi("rgb", level, type, ...ansiStyles.hexToRgb(...arguments_));
326
- }
327
- return ansiStyles[type][model](...arguments_);
328
- };
329
- const usedModels = ["rgb", "hex", "ansi256"];
330
- for (const model of usedModels) {
331
- styles[model] = {
332
- get() {
333
- const { level } = this;
334
- return function(...arguments_) {
335
- const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansiStyles.color.close, this[STYLER]);
336
- return createBuilder(this, styler, this[IS_EMPTY]);
337
- };
338
- }
339
- };
340
- const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
341
- styles[bgModel] = {
342
- get() {
343
- const { level } = this;
344
- return function(...arguments_) {
345
- const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansiStyles.bgColor.close, this[STYLER]);
346
- return createBuilder(this, styler, this[IS_EMPTY]);
347
- };
348
- }
349
- };
350
- }
351
- const proto = Object.defineProperties(() => {
352
- }, {
353
- ...styles,
354
- level: {
355
- enumerable: true,
356
- get() {
357
- return this[GENERATOR].level;
358
- },
359
- set(level) {
360
- this[GENERATOR].level = level;
361
- }
362
- }
363
- });
364
- const createStyler = (open, close, parent) => {
365
- let openAll;
366
- let closeAll;
367
- if (parent === void 0) {
368
- openAll = open;
369
- closeAll = close;
370
- } else {
371
- openAll = parent.openAll + open;
372
- closeAll = close + parent.closeAll;
373
- }
374
- return {
375
- open,
376
- close,
377
- openAll,
378
- closeAll,
379
- parent
380
- };
381
- };
382
- const createBuilder = (self, _styler, _isEmpty) => {
383
- const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
384
- Object.setPrototypeOf(builder, proto);
385
- builder[GENERATOR] = self;
386
- builder[STYLER] = _styler;
387
- builder[IS_EMPTY] = _isEmpty;
388
- return builder;
389
- };
390
- const applyStyle = (self, string) => {
391
- if (self.level <= 0 || !string) {
392
- return self[IS_EMPTY] ? "" : string;
393
- }
394
- let styler = self[STYLER];
395
- if (styler === void 0) {
396
- return string;
397
- }
398
- const { openAll, closeAll } = styler;
399
- if (string.includes("\x1B")) {
400
- while (styler !== void 0) {
401
- string = stringReplaceAll(string, styler.close, styler.open);
402
- styler = styler.parent;
403
- }
404
- }
405
- const lfIndex = string.indexOf("\n");
406
- if (lfIndex !== -1) {
407
- string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
408
- }
409
- return openAll + string + closeAll;
410
- };
411
- Object.defineProperties(createChalk.prototype, styles);
412
- const chalk = createChalk();
413
- createChalk({ level: stderrColor ? stderrColor.level : 0 });
414
-
415
- function difference(firstArr, secondArr) {
416
- const secondSet = new Set(secondArr);
417
- return firstArr.filter((item) => !secondSet.has(item));
418
- }
419
-
420
- function flatten(arr, depth = 1) {
421
- const result = [];
422
- const flooredDepth = Math.floor(depth);
423
- const recursive = (arr2, currentDepth) => {
424
- for (let i = 0; i < arr2.length; i++) {
425
- const item = arr2[i];
426
- if (Array.isArray(item) && currentDepth < flooredDepth) {
427
- recursive(item, currentDepth + 1);
428
- } else {
429
- result.push(item);
430
- }
431
- }
432
- };
433
- recursive(arr, 0);
434
- return result;
435
- }
436
-
437
- function intersection(firstArr, secondArr) {
438
- const secondSet = new Set(secondArr);
439
- return firstArr.filter((item) => secondSet.has(item));
440
- }
441
-
442
- function isSymbol(value) {
443
- return typeof value === "symbol" || value instanceof Symbol;
444
- }
445
-
446
- function uniq(arr) {
447
- return [...new Set(arr)];
448
- }
449
-
450
- function union(arr1, arr2) {
451
- return uniq(arr1.concat(arr2));
452
- }
453
-
454
- function xor(arr1, arr2) {
455
- return difference(union(arr1, arr2), intersection(arr1, arr2));
456
- }
457
-
458
- function isPlainObject(value) {
459
- if (!value || typeof value !== "object") {
460
- return false;
461
- }
462
- const proto = Object.getPrototypeOf(value);
463
- const hasObjectPrototype = proto === null || proto === Object.prototype || Object.getPrototypeOf(proto) === null;
464
- if (!hasObjectPrototype) {
465
- return false;
466
- }
467
- return Object.prototype.toString.call(value) === "[object Object]";
468
- }
469
-
470
- function isUnsafeProperty(key) {
471
- return key === "__proto__";
472
- }
473
-
474
- function merge(target, source) {
475
- const sourceKeys = Object.keys(source);
476
- for (let i = 0; i < sourceKeys.length; i++) {
477
- const key = sourceKeys[i];
478
- if (isUnsafeProperty(key)) {
479
- continue;
480
- }
481
- const sourceValue = source[key];
482
- const targetValue = target[key];
483
- if (isMergeableValue(sourceValue) && isMergeableValue(targetValue)) {
484
- target[key] = merge(targetValue, sourceValue);
485
- } else if (Array.isArray(sourceValue)) {
486
- target[key] = merge([], sourceValue);
487
- } else if (isPlainObject(sourceValue)) {
488
- target[key] = merge({}, sourceValue);
489
- } else if (targetValue === void 0 || sourceValue !== void 0) {
490
- target[key] = sourceValue;
491
- }
492
- }
493
- return target;
494
- }
495
- function isMergeableValue(value) {
496
- return isPlainObject(value) || Array.isArray(value);
497
- }
498
-
499
- function omit(obj, keys) {
500
- const result = { ...obj };
501
- for (let i = 0; i < keys.length; i++) {
502
- const key = keys[i];
503
- delete result[key];
504
- }
505
- return result;
506
- }
507
-
508
- function isEqualsSameValueZero(value, other) {
509
- return value === other || Number.isNaN(value) && Number.isNaN(other);
510
- }
511
-
512
- function isLength(value) {
513
- return Number.isSafeInteger(value) && value >= 0;
514
- }
515
-
516
- function isString(value) {
517
- return typeof value === "string";
518
- }
519
-
520
- const planSchemaValidator = validate14;
521
- const schema32 = { "items": { "properties": { "fileHash": { "type": ["string"] }}} };
522
- const pattern0 = new RegExp("^[1-9][0-9]*(.[1-9][0-9]*)*$", "u");
523
- function validate14(data, { instancePath = "", parentData, parentDataProperty, rootData = data } = {}) {
524
- let vErrors = null;
525
- let errors = 0;
526
- if (Array.isArray(data)) {
527
- const len0 = data.length;
528
- for (let i0 = 0; i0 < len0; i0++) {
529
- let data0 = data[i0];
530
- if (data0 && typeof data0 == "object" && !Array.isArray(data0)) {
531
- if (data0.fileHash === void 0) {
532
- const err0 = { instancePath: instancePath + "/" + i0, schemaPath: "#/items/required", keyword: "required", params: { missingProperty: "fileHash" }, message: "must have required property 'fileHash'" };
533
- if (vErrors === null) {
534
- vErrors = [err0];
535
- } else {
536
- vErrors.push(err0);
537
- }
538
- errors++;
539
- }
540
- if (data0.fileName === void 0) {
541
- const err1 = { instancePath: instancePath + "/" + i0, schemaPath: "#/items/required", keyword: "required", params: { missingProperty: "fileName" }, message: "must have required property 'fileName'" };
542
- if (vErrors === null) {
543
- vErrors = [err1];
544
- } else {
545
- vErrors.push(err1);
546
- }
547
- errors++;
548
- }
549
- if (data0.sequence === void 0) {
550
- const err2 = { instancePath: instancePath + "/" + i0, schemaPath: "#/items/required", keyword: "required", params: { missingProperty: "sequence" }, message: "must have required property 'sequence'" };
551
- if (vErrors === null) {
552
- vErrors = [err2];
553
- } else {
554
- vErrors.push(err2);
555
- }
556
- errors++;
557
- }
558
- for (const key0 in data0) {
559
- if (!(key0 === "fileHash" || key0 === "fileName" || key0 === "sequence")) {
560
- const err3 = { instancePath: instancePath + "/" + i0, schemaPath: "#/items/additionalProperties", keyword: "additionalProperties", params: { additionalProperty: key0 }, message: "must NOT have additional properties" };
561
- if (vErrors === null) {
562
- vErrors = [err3];
563
- } else {
564
- vErrors.push(err3);
565
- }
566
- errors++;
567
- }
568
- }
569
- if (data0.fileHash !== void 0) {
570
- if (typeof data0.fileHash !== "string") {
571
- const err4 = { instancePath: instancePath + "/" + i0 + "/fileHash", schemaPath: "#/items/properties/fileHash/type", keyword: "type", params: { type: schema32.items.properties.fileHash.type }, message: "must be string" };
572
- if (vErrors === null) {
573
- vErrors = [err4];
574
- } else {
575
- vErrors.push(err4);
576
- }
577
- errors++;
578
- }
579
- }
580
- if (data0.fileName !== void 0) {
581
- if (typeof data0.fileName !== "string") {
582
- const err5 = { instancePath: instancePath + "/" + i0 + "/fileName", schemaPath: "#/items/properties/fileName/type", keyword: "type", params: { type: "string" }, message: "must be string" };
583
- if (vErrors === null) {
584
- vErrors = [err5];
585
- } else {
586
- vErrors.push(err5);
587
- }
588
- errors++;
589
- }
590
- }
591
- if (data0.sequence !== void 0) {
592
- let data3 = data0.sequence;
593
- if (typeof data3 === "string") {
594
- if (!pattern0.test(data3)) {
595
- const err6 = { instancePath: instancePath + "/" + i0 + "/sequence", schemaPath: "#/items/properties/sequence/pattern", keyword: "pattern", params: { pattern: "^[1-9][0-9]*(.[1-9][0-9]*)*$" }, message: 'must match pattern "^[1-9][0-9]*(.[1-9][0-9]*)*$"' };
596
- if (vErrors === null) {
597
- vErrors = [err6];
598
- } else {
599
- vErrors.push(err6);
600
- }
601
- errors++;
602
- }
603
- } else {
604
- const err7 = { instancePath: instancePath + "/" + i0 + "/sequence", schemaPath: "#/items/properties/sequence/type", keyword: "type", params: { type: "string" }, message: "must be string" };
605
- if (vErrors === null) {
606
- vErrors = [err7];
607
- } else {
608
- vErrors.push(err7);
609
- }
610
- errors++;
611
- }
612
- }
613
- } else {
614
- const err8 = { instancePath: instancePath + "/" + i0, schemaPath: "#/items/type", keyword: "type", params: { type: "object" }, message: "must be object" };
615
- if (vErrors === null) {
616
- vErrors = [err8];
617
- } else {
618
- vErrors.push(err8);
619
- }
620
- errors++;
621
- }
622
- }
623
- } else {
624
- const err9 = { instancePath, schemaPath: "#/type", keyword: "type", params: { type: "array" }, message: "must be array" };
625
- if (vErrors === null) {
626
- vErrors = [err9];
627
- } else {
628
- vErrors.push(err9);
629
- }
630
- errors++;
631
- }
632
- validate14.errors = vErrors;
633
- return errors === 0;
634
- }
635
-
636
- const isNonEmptyString = (input) => isString(input) && input.length > 0;
637
- const validatePlan = (plan) => {
638
- const valid = planSchemaValidator(plan);
639
- const errors = planSchemaValidator.errors;
640
- if (errors?.length) {
641
- errors.forEach(
642
- (e) => console.error(
643
- `${e.message}${e.instancePath ? `at ${e.instancePath}` : ""}`
644
- )
645
- );
646
- }
647
- return valid;
648
- };
649
- const validateFileDescription = (description) => {
650
- if (!description) {
651
- return false;
652
- }
653
- const validFileName = /^([a-z]+|(([a-z]+-)+[a-z]+))$/g;
654
- return validFileName.test(description);
655
- };
656
- const validateFileName = (fileName) => {
657
- const validFileName = /^([a-z]+|(([a-z]+-)+[a-z]+))(.js|.skip.js)$/g;
658
- return validFileName.test(fileName);
659
- };
660
- const throwIfFileNamesInvalid = (fileEntries) => {
661
- const invalidFileNames = fileEntries.filter((f) => !f.isValidFileName).map((f) => f.fileName);
662
- if (invalidFileNames.length) {
663
- invalidFileNames.forEach((name) => console.error(chalk.red(name)));
664
- throw new Error("Invalid migration filename format (use kebab-case)");
665
- }
666
- };
667
- const warnIfFilesHaveBeenRemovedFromPlan = (migrationEntries, historicalMigrations) => {
668
- const fileNames = migrationEntries.map((f) => f.fileName);
669
- const deletedFilesNames = historicalMigrations.filter((e) => !fileNames.includes(e.fileName)).map((e) => e.fileName);
670
- if (deletedFilesNames.length) {
671
- deletedFilesNames.forEach((name) => console.warn(chalk.yellow(name)));
672
- console.warn(
673
- chalk.yellow(
674
- "Previously executed migration files have been deleted from plan.json (rename file to .skip.js and replace with a new file instead)"
675
- )
676
- );
677
- }
678
- };
679
- const throwIfFilesHaveChanged = (migrationEntries) => {
680
- const changedFilesNames = migrationEntries.filter((m) => {
681
- const {
682
- fileHash,
683
- fileHashFromPlan,
684
- fileHashFromHistory,
685
- skippedFileHashes
686
- } = m;
687
- const matchesHistory = !isNonEmptyString(fileHashFromHistory) || [fileHash].concat(skippedFileHashes).includes(fileHashFromHistory);
688
- const matchesPlan = !isNonEmptyString(fileHashFromPlan) || [fileHash].concat(skippedFileHashes).includes(fileHashFromPlan);
689
- return !(matchesHistory && matchesPlan);
690
- }).map((f) => f.fileName);
691
- if (changedFilesNames.length) {
692
- changedFilesNames.forEach((name) => console.error(chalk.red(name)));
693
- throw new Error(
694
- "Not allowed to change migration files (for unreleased local work, you can use the `force` option)"
695
- );
696
- }
697
- };
698
- const throwIfSequenceHasChanged = (migrationEntries) => {
699
- const changeSequences = migrationEntries.filter((m) => {
700
- const { sequence, sequenceFromHistory } = m;
701
- const changed = isString(sequenceFromHistory) && sequenceFromHistory !== sequence;
702
- return changed;
703
- }).map((f) => f.fileName);
704
- if (changeSequences.length) {
705
- changeSequences.forEach((name) => console.error(chalk.red(name)));
706
- throw new Error("Not allowed to change migration sequences in plan.json");
707
- }
708
- };
709
- const throwIfSequenceNotUnique = (migrationEntries) => {
710
- const sequenceNumbers = migrationEntries.map((f) => f.sequence);
711
- const repeatedSequenceNumbers = sequenceNumbers.filter(
712
- //https://stackoverflow.com/a/59517965/942635
713
- /* @__PURE__ */ ((s) => (v) => s.has(v) || !s.add(v))(/* @__PURE__ */ new Set())
714
- );
715
- const duplicates = migrationEntries.filter((f) => repeatedSequenceNumbers.includes(f.sequence)).map((f) => f.fileName);
716
- if (duplicates.length) {
717
- duplicates.forEach((fileName) => console.error(chalk.red(fileName)));
718
- throw new Error(
719
- "Migrations must have unique sequence numbers in plan.json"
720
- );
721
- }
722
- };
723
- const throwIfSequenceHasIntegerGaps = (migrationEntries) => {
724
- const toInteger = (sequence) => parseInt(sequence.split(".")[0], 10);
725
- const unique = (arr) => Array.from(new Set(arr));
726
- const sequences = migrationEntries.map((s) => s.sequence);
727
- const sequenceIntegers = sequences.map((s) => toInteger(s));
728
- const uniqueSequenceIntegers = unique(sequenceIntegers);
729
- const orderedUniqueSequenceIntegers = uniqueSequenceIntegers.sort(
730
- (a, b) => a - b
731
- );
732
- const max = orderedUniqueSequenceIntegers[orderedUniqueSequenceIntegers.length - 1];
733
- const expected = Array.from({ length: max }, (_v, k) => k + 1);
734
- const missing = xor(orderedUniqueSequenceIntegers, expected);
735
- if (missing.length) {
736
- throw new Error(
737
- `Migration sequence numbers in plan.json have unexpected gaps: ${missing.join(
738
- ", "
739
- )}`
740
- );
741
- }
742
- };
743
- const throwIfFileNamesNotUnique = (migrationEntries) => {
744
- const fileNames = migrationEntries.map((f) => f.fileName);
745
- const repeatedFileNames = fileNames.filter(
746
- //https://stackoverflow.com/a/59517965/942635
747
- /* @__PURE__ */ ((s) => (v) => s.has(v) || !s.add(v))(/* @__PURE__ */ new Set())
748
- );
749
- if (repeatedFileNames.length) {
750
- repeatedFileNames.forEach((fileName) => console.error(chalk.red(fileName)));
751
- throw new Error("Migration file names must be unique");
752
- }
753
- };
754
- const throwIfFilesNotFound = (migrationEntries, importModule) => {
755
- const migrationsWithoutFiles = migrationEntries.filter(
756
- (m) => !m.script || importModule && !m.script && !m.migrator
757
- );
758
- if (migrationsWithoutFiles.length) {
759
- migrationsWithoutFiles.forEach(
760
- (migration) => console.error(chalk.red(migration.fileName))
761
- );
762
- throw new Error(
763
- "Migration files from plan.json are missing from filesystem"
764
- );
765
- }
766
- };
767
-
768
- const capitalize = (word) => {
769
- if (!word) return "";
770
- return word[0].toUpperCase() + word.slice(1);
771
- };
772
-
773
- const lazyImportMigration = async (filePath, fileHash) => {
774
- return (await import(filePath + "?v=" + fileHash))?.default ?? null;
775
- };
776
- const LoaderModule = { lazyImportMigration };
777
-
778
- const hash = (string) => crypto.createHash("sha256").update(string).digest("hex");
779
-
780
- var Gt = (n7, t, e) => {
781
- let s = n7 instanceof RegExp ? ce(n7, e) : n7, i = t instanceof RegExp ? ce(t, e) : t, r = s !== null && i != null && ss(s, i, e);
782
- return r && { start: r[0], end: r[1], pre: e.slice(0, r[0]), body: e.slice(r[0] + s.length, r[1]), post: e.slice(r[1] + i.length) };
783
- }, ce = (n7, t) => {
784
- let e = t.match(n7);
785
- return e ? e[0] : null;
786
- }, ss = (n7, t, e) => {
787
- let s, i, r, o, h, a = e.indexOf(n7), l = e.indexOf(t, a + 1), f = a;
788
- if (a >= 0 && l > 0) {
789
- if (n7 === t) return [a, l];
790
- for (s = [], r = e.length; f >= 0 && !h; ) {
791
- if (f === a) s.push(f), a = e.indexOf(n7, f + 1);
792
- else if (s.length === 1) {
793
- let c = s.pop();
794
- c !== void 0 && (h = [c, l]);
795
- } else i = s.pop(), i !== void 0 && i < r && (r = i, o = l), l = e.indexOf(t, f + 1);
796
- f = a < l && a >= 0 ? a : l;
797
- }
798
- s.length && o !== void 0 && (h = [r, o]);
799
- }
800
- return h;
801
- };
802
- var fe = "\0SLASH" + Math.random() + "\0", ue = "\0OPEN" + Math.random() + "\0", qt = "\0CLOSE" + Math.random() + "\0", de = "\0COMMA" + Math.random() + "\0", pe = "\0PERIOD" + Math.random() + "\0", is = new RegExp(fe, "g"), rs = new RegExp(ue, "g"), ns = new RegExp(qt, "g"), os = new RegExp(de, "g"), hs = new RegExp(pe, "g"), as = /\\\\/g, ls = /\\{/g, cs = /\\}/g, fs = /\\,/g, us = /\\./g, ds = 1e5;
803
- function Ht(n7) {
804
- return isNaN(n7) ? n7.charCodeAt(0) : parseInt(n7, 10);
805
- }
806
- function ps(n7) {
807
- return n7.replace(as, fe).replace(ls, ue).replace(cs, qt).replace(fs, de).replace(us, pe);
808
- }
809
- function ms(n7) {
810
- return n7.replace(is, "\\").replace(rs, "{").replace(ns, "}").replace(os, ",").replace(hs, ".");
811
- }
812
- function me(n7) {
813
- if (!n7) return [""];
814
- let t = [], e = Gt("{", "}", n7);
815
- if (!e) return n7.split(",");
816
- let { pre: s, body: i, post: r } = e, o = s.split(",");
817
- o[o.length - 1] += "{" + i + "}";
818
- let h = me(r);
819
- return r.length && (o[o.length - 1] += h.shift(), o.push.apply(o, h)), t.push.apply(t, o), t;
820
- }
821
- function ge(n7, t = {}) {
822
- if (!n7) return [];
823
- let { max: e = ds } = t;
824
- return n7.slice(0, 2) === "{}" && (n7 = "\\{\\}" + n7.slice(2)), ht(ps(n7), e, true).map(ms);
825
- }
826
- function gs(n7) {
827
- return "{" + n7 + "}";
828
- }
829
- function ws(n7) {
830
- return /^-?0\d/.test(n7);
831
- }
832
- function ys(n7, t) {
833
- return n7 <= t;
834
- }
835
- function bs(n7, t) {
836
- return n7 >= t;
837
- }
838
- function ht(n7, t, e) {
839
- let s = [], i = Gt("{", "}", n7);
840
- if (!i) return [n7];
841
- let r = i.pre, o = i.post.length ? ht(i.post, t, false) : [""];
842
- if (/\$$/.test(i.pre)) for (let h = 0; h < o.length && h < t; h++) {
843
- let a = r + "{" + i.body + "}" + o[h];
844
- s.push(a);
845
- }
846
- else {
847
- let h = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(i.body), a = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(i.body), l = h || a, f = i.body.indexOf(",") >= 0;
848
- if (!l && !f) return i.post.match(/,(?!,).*\}/) ? (n7 = i.pre + "{" + i.body + qt + i.post, ht(n7, t, true)) : [n7];
849
- let c;
850
- if (l) c = i.body.split(/\.\./);
851
- else if (c = me(i.body), c.length === 1 && c[0] !== void 0 && (c = ht(c[0], t, false).map(gs), c.length === 1)) return o.map((u) => i.pre + c[0] + u);
852
- let d;
853
- if (l && c[0] !== void 0 && c[1] !== void 0) {
854
- let u = Ht(c[0]), m = Ht(c[1]), p = Math.max(c[0].length, c[1].length), w = c.length === 3 && c[2] !== void 0 ? Math.abs(Ht(c[2])) : 1, g = ys;
855
- m < u && (w *= -1, g = bs);
856
- let E = c.some(ws);
857
- d = [];
858
- for (let y = u; g(y, m); y += w) {
859
- let b;
860
- if (a) b = String.fromCharCode(y), b === "\\" && (b = "");
861
- else if (b = String(y), E) {
862
- let z = p - b.length;
863
- if (z > 0) {
864
- let $ = new Array(z + 1).join("0");
865
- y < 0 ? b = "-" + $ + b.slice(1) : b = $ + b;
866
- }
867
- }
868
- d.push(b);
869
- }
870
- } else {
871
- d = [];
872
- for (let u = 0; u < c.length; u++) d.push.apply(d, ht(c[u], t, false));
873
- }
874
- for (let u = 0; u < d.length; u++) for (let m = 0; m < o.length && s.length < t; m++) {
875
- let p = r + d[u] + o[m];
876
- (!e || l || p) && s.push(p);
877
- }
878
- }
879
- return s;
880
- }
881
- var at = (n7) => {
882
- if (typeof n7 != "string") throw new TypeError("invalid pattern");
883
- if (n7.length > 65536) throw new TypeError("pattern is too long");
884
- };
885
- var Ss = { "[:alnum:]": ["\\p{L}\\p{Nl}\\p{Nd}", true], "[:alpha:]": ["\\p{L}\\p{Nl}", true], "[:ascii:]": ["\\x00-\\x7f", false], "[:blank:]": ["\\p{Zs}\\t", true], "[:cntrl:]": ["\\p{Cc}", true], "[:digit:]": ["\\p{Nd}", true], "[:graph:]": ["\\p{Z}\\p{C}", true, true], "[:lower:]": ["\\p{Ll}", true], "[:print:]": ["\\p{C}", true], "[:punct:]": ["\\p{P}", true], "[:space:]": ["\\p{Z}\\t\\r\\n\\v\\f", true], "[:upper:]": ["\\p{Lu}", true], "[:word:]": ["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}", true], "[:xdigit:]": ["A-Fa-f0-9", false] }, lt = (n7) => n7.replace(/[[\]\\-]/g, "\\$&"), Es = (n7) => n7.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), we = (n7) => n7.join(""), ye = (n7, t) => {
886
- let e = t;
887
- if (n7.charAt(e) !== "[") throw new Error("not in a brace expression");
888
- let s = [], i = [], r = e + 1, o = false, h = false, a = false, l = false, f = e, c = "";
889
- t: for (; r < n7.length; ) {
890
- let p = n7.charAt(r);
891
- if ((p === "!" || p === "^") && r === e + 1) {
892
- l = true, r++;
893
- continue;
894
- }
895
- if (p === "]" && o && !a) {
896
- f = r + 1;
897
- break;
898
- }
899
- if (o = true, p === "\\" && !a) {
900
- a = true, r++;
901
- continue;
902
- }
903
- if (p === "[" && !a) {
904
- for (let [w, [g, S, E]] of Object.entries(Ss)) if (n7.startsWith(w, r)) {
905
- if (c) return ["$.", false, n7.length - e, true];
906
- r += w.length, E ? i.push(g) : s.push(g), h = h || S;
907
- continue t;
908
- }
909
- }
910
- if (a = false, c) {
911
- p > c ? s.push(lt(c) + "-" + lt(p)) : p === c && s.push(lt(p)), c = "", r++;
912
- continue;
913
- }
914
- if (n7.startsWith("-]", r + 1)) {
915
- s.push(lt(p + "-")), r += 2;
916
- continue;
917
- }
918
- if (n7.startsWith("-", r + 1)) {
919
- c = p, r += 2;
920
- continue;
921
- }
922
- s.push(lt(p)), r++;
923
- }
924
- if (f < r) return ["", false, 0, false];
925
- if (!s.length && !i.length) return ["$.", false, n7.length - e, true];
926
- if (i.length === 0 && s.length === 1 && /^\\?.$/.test(s[0]) && !l) {
927
- let p = s[0].length === 2 ? s[0].slice(-1) : s[0];
928
- return [Es(p), false, f - e, false];
929
- }
930
- let d = "[" + (l ? "^" : "") + we(s) + "]", u = "[" + (l ? "" : "^") + we(i) + "]";
931
- return [s.length && i.length ? "(" + d + "|" + u + ")" : s.length ? d : u, h, f - e, true];
932
- };
933
- var W = (n7, { windowsPathsNoEscape: t = false, magicalBraces: e = true } = {}) => e ? t ? n7.replace(/\[([^\/\\])\]/g, "$1") : n7.replace(/((?!\\).|^)\[([^\/\\])\]/g, "$1$2").replace(/\\([^\/])/g, "$1") : t ? n7.replace(/\[([^\/\\{}])\]/g, "$1") : n7.replace(/((?!\\).|^)\[([^\/\\{}])\]/g, "$1$2").replace(/\\([^\/{}])/g, "$1");
934
- var xs = /* @__PURE__ */ new Set(["!", "?", "+", "*", "@"]), be = (n7) => xs.has(n7), vs = "(?!(?:^|/)\\.\\.?(?:$|/))", Ct = "(?!\\.)", Cs = /* @__PURE__ */ new Set(["[", "."]), Ts = /* @__PURE__ */ new Set(["..", "."]), As = new Set("().*{}+?[]^$\\!"), ks = (n7) => n7.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), Kt = "[^/]", Se = Kt + "*?", Ee = Kt + "+?", Q = class n {
935
- type;
936
- #t;
937
- #s;
938
- #n = false;
939
- #r = [];
940
- #o;
941
- #S;
942
- #w;
943
- #c = false;
944
- #h;
945
- #u;
946
- #f = false;
947
- constructor(t, e, s = {}) {
948
- this.type = t, t && (this.#s = true), this.#o = e, this.#t = this.#o ? this.#o.#t : this, this.#h = this.#t === this ? s : this.#t.#h, this.#w = this.#t === this ? [] : this.#t.#w, t === "!" && !this.#t.#c && this.#w.push(this), this.#S = this.#o ? this.#o.#r.length : 0;
949
- }
950
- get hasMagic() {
951
- if (this.#s !== void 0) return this.#s;
952
- for (let t of this.#r) if (typeof t != "string" && (t.type || t.hasMagic)) return this.#s = true;
953
- return this.#s;
954
- }
955
- toString() {
956
- return this.#u !== void 0 ? this.#u : this.type ? this.#u = this.type + "(" + this.#r.map((t) => String(t)).join("|") + ")" : this.#u = this.#r.map((t) => String(t)).join("");
957
- }
958
- #a() {
959
- if (this !== this.#t) throw new Error("should only call on root");
960
- if (this.#c) return this;
961
- this.toString(), this.#c = true;
962
- let t;
963
- for (; t = this.#w.pop(); ) {
964
- if (t.type !== "!") continue;
965
- let e = t, s = e.#o;
966
- for (; s; ) {
967
- for (let i = e.#S + 1; !s.type && i < s.#r.length; i++) for (let r of t.#r) {
968
- if (typeof r == "string") throw new Error("string part in extglob AST??");
969
- r.copyIn(s.#r[i]);
970
- }
971
- e = s, s = e.#o;
972
- }
973
- }
974
- return this;
975
- }
976
- push(...t) {
977
- for (let e of t) if (e !== "") {
978
- if (typeof e != "string" && !(e instanceof n && e.#o === this)) throw new Error("invalid part: " + e);
979
- this.#r.push(e);
980
- }
981
- }
982
- toJSON() {
983
- let t = this.type === null ? this.#r.slice().map((e) => typeof e == "string" ? e : e.toJSON()) : [this.type, ...this.#r.map((e) => e.toJSON())];
984
- return this.isStart() && !this.type && t.unshift([]), this.isEnd() && (this === this.#t || this.#t.#c && this.#o?.type === "!") && t.push({}), t;
985
- }
986
- isStart() {
987
- if (this.#t === this) return true;
988
- if (!this.#o?.isStart()) return false;
989
- if (this.#S === 0) return true;
990
- let t = this.#o;
991
- for (let e = 0; e < this.#S; e++) {
992
- let s = t.#r[e];
993
- if (!(s instanceof n && s.type === "!")) return false;
994
- }
995
- return true;
996
- }
997
- isEnd() {
998
- if (this.#t === this || this.#o?.type === "!") return true;
999
- if (!this.#o?.isEnd()) return false;
1000
- if (!this.type) return this.#o?.isEnd();
1001
- let t = this.#o ? this.#o.#r.length : 0;
1002
- return this.#S === t - 1;
1003
- }
1004
- copyIn(t) {
1005
- typeof t == "string" ? this.push(t) : this.push(t.clone(this));
1006
- }
1007
- clone(t) {
1008
- let e = new n(this.type, t);
1009
- for (let s of this.#r) e.copyIn(s);
1010
- return e;
1011
- }
1012
- static #i(t, e, s, i) {
1013
- let r = false, o = false, h = -1, a = false;
1014
- if (e.type === null) {
1015
- let u = s, m = "";
1016
- for (; u < t.length; ) {
1017
- let p = t.charAt(u++);
1018
- if (r || p === "\\") {
1019
- r = !r, m += p;
1020
- continue;
1021
- }
1022
- if (o) {
1023
- u === h + 1 ? (p === "^" || p === "!") && (a = true) : p === "]" && !(u === h + 2 && a) && (o = false), m += p;
1024
- continue;
1025
- } else if (p === "[") {
1026
- o = true, h = u, a = false, m += p;
1027
- continue;
1028
- }
1029
- if (!i.noext && be(p) && t.charAt(u) === "(") {
1030
- e.push(m), m = "";
1031
- let w = new n(p, e);
1032
- u = n.#i(t, w, u, i), e.push(w);
1033
- continue;
1034
- }
1035
- m += p;
1036
- }
1037
- return e.push(m), u;
1038
- }
1039
- let l = s + 1, f = new n(null, e), c = [], d = "";
1040
- for (; l < t.length; ) {
1041
- let u = t.charAt(l++);
1042
- if (r || u === "\\") {
1043
- r = !r, d += u;
1044
- continue;
1045
- }
1046
- if (o) {
1047
- l === h + 1 ? (u === "^" || u === "!") && (a = true) : u === "]" && !(l === h + 2 && a) && (o = false), d += u;
1048
- continue;
1049
- } else if (u === "[") {
1050
- o = true, h = l, a = false, d += u;
1051
- continue;
1052
- }
1053
- if (be(u) && t.charAt(l) === "(") {
1054
- f.push(d), d = "";
1055
- let m = new n(u, f);
1056
- f.push(m), l = n.#i(t, m, l, i);
1057
- continue;
1058
- }
1059
- if (u === "|") {
1060
- f.push(d), d = "", c.push(f), f = new n(null, e);
1061
- continue;
1062
- }
1063
- if (u === ")") return d === "" && e.#r.length === 0 && (e.#f = true), f.push(d), d = "", e.push(...c, f), l;
1064
- d += u;
1065
- }
1066
- return e.type = null, e.#s = void 0, e.#r = [t.substring(s - 1)], l;
1067
- }
1068
- static fromGlob(t, e = {}) {
1069
- let s = new n(null, void 0, e);
1070
- return n.#i(t, s, 0, e), s;
1071
- }
1072
- toMMPattern() {
1073
- if (this !== this.#t) return this.#t.toMMPattern();
1074
- let t = this.toString(), [e, s, i, r] = this.toRegExpSource();
1075
- if (!(i || this.#s || this.#h.nocase && !this.#h.nocaseMagicOnly && t.toUpperCase() !== t.toLowerCase())) return s;
1076
- let h = (this.#h.nocase ? "i" : "") + (r ? "u" : "");
1077
- return Object.assign(new RegExp(`^${e}$`, h), { _src: e, _glob: t });
1078
- }
1079
- get options() {
1080
- return this.#h;
1081
- }
1082
- toRegExpSource(t) {
1083
- let e = t ?? !!this.#h.dot;
1084
- if (this.#t === this && this.#a(), !this.type) {
1085
- let a = this.isStart() && this.isEnd() && !this.#r.some((u) => typeof u != "string"), l = this.#r.map((u) => {
1086
- let [m, p, w, g] = typeof u == "string" ? n.#E(u, this.#s, a) : u.toRegExpSource(t);
1087
- return this.#s = this.#s || w, this.#n = this.#n || g, m;
1088
- }).join(""), f = "";
1089
- if (this.isStart() && typeof this.#r[0] == "string" && !(this.#r.length === 1 && Ts.has(this.#r[0]))) {
1090
- let m = Cs, p = e && m.has(l.charAt(0)) || l.startsWith("\\.") && m.has(l.charAt(2)) || l.startsWith("\\.\\.") && m.has(l.charAt(4)), w = !e && !t && m.has(l.charAt(0));
1091
- f = p ? vs : w ? Ct : "";
1092
- }
1093
- let c = "";
1094
- return this.isEnd() && this.#t.#c && this.#o?.type === "!" && (c = "(?:$|\\/)"), [f + l + c, W(l), this.#s = !!this.#s, this.#n];
1095
- }
1096
- let s = this.type === "*" || this.type === "+", i = this.type === "!" ? "(?:(?!(?:" : "(?:", r = this.#d(e);
1097
- if (this.isStart() && this.isEnd() && !r && this.type !== "!") {
1098
- let a = this.toString();
1099
- return this.#r = [a], this.type = null, this.#s = void 0, [a, W(this.toString()), false, false];
1100
- }
1101
- let o = !s || t || e || !Ct ? "" : this.#d(true);
1102
- o === r && (o = ""), o && (r = `(?:${r})(?:${o})*?`);
1103
- let h = "";
1104
- if (this.type === "!" && this.#f) h = (this.isStart() && !e ? Ct : "") + Ee;
1105
- else {
1106
- let a = this.type === "!" ? "))" + (this.isStart() && !e && !t ? Ct : "") + Se + ")" : this.type === "@" ? ")" : this.type === "?" ? ")?" : this.type === "+" && o ? ")" : this.type === "*" && o ? ")?" : `)${this.type}`;
1107
- h = i + r + a;
1108
- }
1109
- return [h, W(r), this.#s = !!this.#s, this.#n];
1110
- }
1111
- #d(t) {
1112
- return this.#r.map((e) => {
1113
- if (typeof e == "string") throw new Error("string type in extglob ast??");
1114
- let [s, i, r, o] = e.toRegExpSource(t);
1115
- return this.#n = this.#n || o, s;
1116
- }).filter((e) => !(this.isStart() && this.isEnd()) || !!e).join("|");
1117
- }
1118
- static #E(t, e, s = false) {
1119
- let i = false, r = "", o = false;
1120
- for (let h = 0; h < t.length; h++) {
1121
- let a = t.charAt(h);
1122
- if (i) {
1123
- i = false, r += (As.has(a) ? "\\" : "") + a;
1124
- continue;
1125
- }
1126
- if (a === "\\") {
1127
- h === t.length - 1 ? r += "\\\\" : i = true;
1128
- continue;
1129
- }
1130
- if (a === "[") {
1131
- let [l, f, c, d] = ye(t, h);
1132
- if (c) {
1133
- r += l, o = o || f, h += c - 1, e = e || d;
1134
- continue;
1135
- }
1136
- }
1137
- if (a === "*") {
1138
- r += s && t === "*" ? Ee : Se, e = true;
1139
- continue;
1140
- }
1141
- if (a === "?") {
1142
- r += Kt, e = true;
1143
- continue;
1144
- }
1145
- r += ks(a);
1146
- }
1147
- return [r, W(t), !!e, o];
1148
- }
1149
- };
1150
- var tt = (n7, { windowsPathsNoEscape: t = false, magicalBraces: e = false } = {}) => e ? t ? n7.replace(/[?*()[\]{}]/g, "[$&]") : n7.replace(/[?*()[\]\\{}]/g, "\\$&") : t ? n7.replace(/[?*()[\]]/g, "[$&]") : n7.replace(/[?*()[\]\\]/g, "\\$&");
1151
- var O = (n7, t, e = {}) => (at(t), !e.nocomment && t.charAt(0) === "#" ? false : new D(t, e).match(n7)), Rs = /^\*+([^+@!?\*\[\(]*)$/, Os = (n7) => (t) => !t.startsWith(".") && t.endsWith(n7), Fs = (n7) => (t) => t.endsWith(n7), Ds = (n7) => (n7 = n7.toLowerCase(), (t) => !t.startsWith(".") && t.toLowerCase().endsWith(n7)), Ms = (n7) => (n7 = n7.toLowerCase(), (t) => t.toLowerCase().endsWith(n7)), Ns = /^\*+\.\*+$/, _s = (n7) => !n7.startsWith(".") && n7.includes("."), Ls = (n7) => n7 !== "." && n7 !== ".." && n7.includes("."), Ws = /^\.\*+$/, Ps = (n7) => n7 !== "." && n7 !== ".." && n7.startsWith("."), js = /^\*+$/, Is = (n7) => n7.length !== 0 && !n7.startsWith("."), zs = (n7) => n7.length !== 0 && n7 !== "." && n7 !== "..", Bs = /^\?+([^+@!?\*\[\(]*)?$/, Us = ([n7, t = ""]) => {
1152
- let e = Ce([n7]);
1153
- return t ? (t = t.toLowerCase(), (s) => e(s) && s.toLowerCase().endsWith(t)) : e;
1154
- }, $s = ([n7, t = ""]) => {
1155
- let e = Te([n7]);
1156
- return t ? (t = t.toLowerCase(), (s) => e(s) && s.toLowerCase().endsWith(t)) : e;
1157
- }, Gs = ([n7, t = ""]) => {
1158
- let e = Te([n7]);
1159
- return t ? (s) => e(s) && s.endsWith(t) : e;
1160
- }, Hs = ([n7, t = ""]) => {
1161
- let e = Ce([n7]);
1162
- return t ? (s) => e(s) && s.endsWith(t) : e;
1163
- }, Ce = ([n7]) => {
1164
- let t = n7.length;
1165
- return (e) => e.length === t && !e.startsWith(".");
1166
- }, Te = ([n7]) => {
1167
- let t = n7.length;
1168
- return (e) => e.length === t && e !== "." && e !== "..";
1169
- }, Ae = typeof process == "object" && process ? typeof process.env == "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix", xe = { win32: { sep: "\\" }, posix: { sep: "/" } }, qs = Ae === "win32" ? xe.win32.sep : xe.posix.sep;
1170
- O.sep = qs;
1171
- var A = Symbol("globstar **");
1172
- O.GLOBSTAR = A;
1173
- var Ks = "[^/]", Vs = Ks + "*?", Ys = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?", Xs = "(?:(?!(?:\\/|^)\\.).)*?", Js = (n7, t = {}) => (e) => O(e, n7, t);
1174
- O.filter = Js;
1175
- var N = (n7, t = {}) => Object.assign({}, n7, t), Zs = (n7) => {
1176
- if (!n7 || typeof n7 != "object" || !Object.keys(n7).length) return O;
1177
- let t = O;
1178
- return Object.assign((s, i, r = {}) => t(s, i, N(n7, r)), { Minimatch: class extends t.Minimatch {
1179
- constructor(i, r = {}) {
1180
- super(i, N(n7, r));
1181
- }
1182
- static defaults(i) {
1183
- return t.defaults(N(n7, i)).Minimatch;
1184
- }
1185
- }, AST: class extends t.AST {
1186
- constructor(i, r, o = {}) {
1187
- super(i, r, N(n7, o));
1188
- }
1189
- static fromGlob(i, r = {}) {
1190
- return t.AST.fromGlob(i, N(n7, r));
1191
- }
1192
- }, unescape: (s, i = {}) => t.unescape(s, N(n7, i)), escape: (s, i = {}) => t.escape(s, N(n7, i)), filter: (s, i = {}) => t.filter(s, N(n7, i)), defaults: (s) => t.defaults(N(n7, s)), makeRe: (s, i = {}) => t.makeRe(s, N(n7, i)), braceExpand: (s, i = {}) => t.braceExpand(s, N(n7, i)), match: (s, i, r = {}) => t.match(s, i, N(n7, r)), sep: t.sep, GLOBSTAR: A });
1193
- };
1194
- O.defaults = Zs;
1195
- var ke = (n7, t = {}) => (at(n7), t.nobrace || !/\{(?:(?!\{).)*\}/.test(n7) ? [n7] : ge(n7, { max: t.braceExpandMax }));
1196
- O.braceExpand = ke;
1197
- var Qs = (n7, t = {}) => new D(n7, t).makeRe();
1198
- O.makeRe = Qs;
1199
- var ti = (n7, t, e = {}) => {
1200
- let s = new D(t, e);
1201
- return n7 = n7.filter((i) => s.match(i)), s.options.nonull && !n7.length && n7.push(t), n7;
1202
- };
1203
- O.match = ti;
1204
- var ve = /[?*]|[+@!]\(.*?\)|\[|\]/, ei = (n7) => n7.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), D = class {
1205
- options;
1206
- set;
1207
- pattern;
1208
- windowsPathsNoEscape;
1209
- nonegate;
1210
- negate;
1211
- comment;
1212
- empty;
1213
- preserveMultipleSlashes;
1214
- partial;
1215
- globSet;
1216
- globParts;
1217
- nocase;
1218
- isWindows;
1219
- platform;
1220
- windowsNoMagicRoot;
1221
- regexp;
1222
- constructor(t, e = {}) {
1223
- at(t), e = e || {}, this.options = e, this.pattern = t, this.platform = e.platform || Ae, this.isWindows = this.platform === "win32";
1224
- let s = "allowWindowsEscape";
1225
- this.windowsPathsNoEscape = !!e.windowsPathsNoEscape || e[s] === false, this.windowsPathsNoEscape && (this.pattern = this.pattern.replace(/\\/g, "/")), this.preserveMultipleSlashes = !!e.preserveMultipleSlashes, this.regexp = null, this.negate = false, this.nonegate = !!e.nonegate, this.comment = false, this.empty = false, this.partial = !!e.partial, this.nocase = !!this.options.nocase, this.windowsNoMagicRoot = e.windowsNoMagicRoot !== void 0 ? e.windowsNoMagicRoot : !!(this.isWindows && this.nocase), this.globSet = [], this.globParts = [], this.set = [], this.make();
1226
- }
1227
- hasMagic() {
1228
- if (this.options.magicalBraces && this.set.length > 1) return true;
1229
- for (let t of this.set) for (let e of t) if (typeof e != "string") return true;
1230
- return false;
1231
- }
1232
- debug(...t) {
1233
- }
1234
- make() {
1235
- let t = this.pattern, e = this.options;
1236
- if (!e.nocomment && t.charAt(0) === "#") {
1237
- this.comment = true;
1238
- return;
1239
- }
1240
- if (!t) {
1241
- this.empty = true;
1242
- return;
1243
- }
1244
- this.parseNegate(), this.globSet = [...new Set(this.braceExpand())], e.debug && (this.debug = (...r) => console.error(...r)), this.debug(this.pattern, this.globSet);
1245
- let s = this.globSet.map((r) => this.slashSplit(r));
1246
- this.globParts = this.preprocess(s), this.debug(this.pattern, this.globParts);
1247
- let i = this.globParts.map((r, o, h) => {
1248
- if (this.isWindows && this.windowsNoMagicRoot) {
1249
- let a = r[0] === "" && r[1] === "" && (r[2] === "?" || !ve.test(r[2])) && !ve.test(r[3]), l = /^[a-z]:/i.test(r[0]);
1250
- if (a) return [...r.slice(0, 4), ...r.slice(4).map((f) => this.parse(f))];
1251
- if (l) return [r[0], ...r.slice(1).map((f) => this.parse(f))];
1252
- }
1253
- return r.map((a) => this.parse(a));
1254
- });
1255
- if (this.debug(this.pattern, i), this.set = i.filter((r) => r.indexOf(false) === -1), this.isWindows) for (let r = 0; r < this.set.length; r++) {
1256
- let o = this.set[r];
1257
- o[0] === "" && o[1] === "" && this.globParts[r][2] === "?" && typeof o[3] == "string" && /^[a-z]:$/i.test(o[3]) && (o[2] = "?");
1258
- }
1259
- this.debug(this.pattern, this.set);
1260
- }
1261
- preprocess(t) {
1262
- if (this.options.noglobstar) for (let s = 0; s < t.length; s++) for (let i = 0; i < t[s].length; i++) t[s][i] === "**" && (t[s][i] = "*");
1263
- let { optimizationLevel: e = 1 } = this.options;
1264
- return e >= 2 ? (t = this.firstPhasePreProcess(t), t = this.secondPhasePreProcess(t)) : e >= 1 ? t = this.levelOneOptimize(t) : t = this.adjascentGlobstarOptimize(t), t;
1265
- }
1266
- adjascentGlobstarOptimize(t) {
1267
- return t.map((e) => {
1268
- let s = -1;
1269
- for (; (s = e.indexOf("**", s + 1)) !== -1; ) {
1270
- let i = s;
1271
- for (; e[i + 1] === "**"; ) i++;
1272
- i !== s && e.splice(s, i - s);
1273
- }
1274
- return e;
1275
- });
1276
- }
1277
- levelOneOptimize(t) {
1278
- return t.map((e) => (e = e.reduce((s, i) => {
1279
- let r = s[s.length - 1];
1280
- return i === "**" && r === "**" ? s : i === ".." && r && r !== ".." && r !== "." && r !== "**" ? (s.pop(), s) : (s.push(i), s);
1281
- }, []), e.length === 0 ? [""] : e));
1282
- }
1283
- levelTwoFileOptimize(t) {
1284
- Array.isArray(t) || (t = this.slashSplit(t));
1285
- let e = false;
1286
- do {
1287
- if (e = false, !this.preserveMultipleSlashes) {
1288
- for (let i = 1; i < t.length - 1; i++) {
1289
- let r = t[i];
1290
- i === 1 && r === "" && t[0] === "" || (r === "." || r === "") && (e = true, t.splice(i, 1), i--);
1291
- }
1292
- t[0] === "." && t.length === 2 && (t[1] === "." || t[1] === "") && (e = true, t.pop());
1293
- }
1294
- let s = 0;
1295
- for (; (s = t.indexOf("..", s + 1)) !== -1; ) {
1296
- let i = t[s - 1];
1297
- i && i !== "." && i !== ".." && i !== "**" && (e = true, t.splice(s - 1, 2), s -= 2);
1298
- }
1299
- } while (e);
1300
- return t.length === 0 ? [""] : t;
1301
- }
1302
- firstPhasePreProcess(t) {
1303
- let e = false;
1304
- do {
1305
- e = false;
1306
- for (let s of t) {
1307
- let i = -1;
1308
- for (; (i = s.indexOf("**", i + 1)) !== -1; ) {
1309
- let o = i;
1310
- for (; s[o + 1] === "**"; ) o++;
1311
- o > i && s.splice(i + 1, o - i);
1312
- let h = s[i + 1], a = s[i + 2], l = s[i + 3];
1313
- if (h !== ".." || !a || a === "." || a === ".." || !l || l === "." || l === "..") continue;
1314
- e = true, s.splice(i, 1);
1315
- let f = s.slice(0);
1316
- f[i] = "**", t.push(f), i--;
1317
- }
1318
- if (!this.preserveMultipleSlashes) {
1319
- for (let o = 1; o < s.length - 1; o++) {
1320
- let h = s[o];
1321
- o === 1 && h === "" && s[0] === "" || (h === "." || h === "") && (e = true, s.splice(o, 1), o--);
1322
- }
1323
- s[0] === "." && s.length === 2 && (s[1] === "." || s[1] === "") && (e = true, s.pop());
1324
- }
1325
- let r = 0;
1326
- for (; (r = s.indexOf("..", r + 1)) !== -1; ) {
1327
- let o = s[r - 1];
1328
- if (o && o !== "." && o !== ".." && o !== "**") {
1329
- e = true;
1330
- let a = r === 1 && s[r + 1] === "**" ? ["."] : [];
1331
- s.splice(r - 1, 2, ...a), s.length === 0 && s.push(""), r -= 2;
1332
- }
1333
- }
1334
- }
1335
- } while (e);
1336
- return t;
1337
- }
1338
- secondPhasePreProcess(t) {
1339
- for (let e = 0; e < t.length - 1; e++) for (let s = e + 1; s < t.length; s++) {
1340
- let i = this.partsMatch(t[e], t[s], !this.preserveMultipleSlashes);
1341
- if (i) {
1342
- t[e] = [], t[s] = i;
1343
- break;
1344
- }
1345
- }
1346
- return t.filter((e) => e.length);
1347
- }
1348
- partsMatch(t, e, s = false) {
1349
- let i = 0, r = 0, o = [], h = "";
1350
- for (; i < t.length && r < e.length; ) if (t[i] === e[r]) o.push(h === "b" ? e[r] : t[i]), i++, r++;
1351
- else if (s && t[i] === "**" && e[r] === t[i + 1]) o.push(t[i]), i++;
1352
- else if (s && e[r] === "**" && t[i] === e[r + 1]) o.push(e[r]), r++;
1353
- else if (t[i] === "*" && e[r] && (this.options.dot || !e[r].startsWith(".")) && e[r] !== "**") {
1354
- if (h === "b") return false;
1355
- h = "a", o.push(t[i]), i++, r++;
1356
- } else if (e[r] === "*" && t[i] && (this.options.dot || !t[i].startsWith(".")) && t[i] !== "**") {
1357
- if (h === "a") return false;
1358
- h = "b", o.push(e[r]), i++, r++;
1359
- } else return false;
1360
- return t.length === e.length && o;
1361
- }
1362
- parseNegate() {
1363
- if (this.nonegate) return;
1364
- let t = this.pattern, e = false, s = 0;
1365
- for (let i = 0; i < t.length && t.charAt(i) === "!"; i++) e = !e, s++;
1366
- s && (this.pattern = t.slice(s)), this.negate = e;
1367
- }
1368
- matchOne(t, e, s = false) {
1369
- let i = this.options;
1370
- if (this.isWindows) {
1371
- let p = typeof t[0] == "string" && /^[a-z]:$/i.test(t[0]), w = !p && t[0] === "" && t[1] === "" && t[2] === "?" && /^[a-z]:$/i.test(t[3]), g = typeof e[0] == "string" && /^[a-z]:$/i.test(e[0]), S = !g && e[0] === "" && e[1] === "" && e[2] === "?" && typeof e[3] == "string" && /^[a-z]:$/i.test(e[3]), E = w ? 3 : p ? 0 : void 0, y = S ? 3 : g ? 0 : void 0;
1372
- if (typeof E == "number" && typeof y == "number") {
1373
- let [b, z] = [t[E], e[y]];
1374
- b.toLowerCase() === z.toLowerCase() && (e[y] = b, y > E ? e = e.slice(y) : E > y && (t = t.slice(E)));
1375
- }
1376
- }
1377
- let { optimizationLevel: r = 1 } = this.options;
1378
- r >= 2 && (t = this.levelTwoFileOptimize(t)), this.debug("matchOne", this, { file: t, pattern: e }), this.debug("matchOne", t.length, e.length);
1379
- for (var o = 0, h = 0, a = t.length, l = e.length; o < a && h < l; o++, h++) {
1380
- this.debug("matchOne loop");
1381
- var f = e[h], c = t[o];
1382
- if (this.debug(e, f, c), f === false) return false;
1383
- if (f === A) {
1384
- this.debug("GLOBSTAR", [e, f, c]);
1385
- var d = o, u = h + 1;
1386
- if (u === l) {
1387
- for (this.debug("** at the end"); o < a; o++) if (t[o] === "." || t[o] === ".." || !i.dot && t[o].charAt(0) === ".") return false;
1388
- return true;
1389
- }
1390
- for (; d < a; ) {
1391
- var m = t[d];
1392
- if (this.debug(`
1393
- globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) return this.debug("globstar found match!", d, a, m), true;
1394
- if (m === "." || m === ".." || !i.dot && m.charAt(0) === ".") {
1395
- this.debug("dot detected!", t, d, e, u);
1396
- break;
1397
- }
1398
- this.debug("globstar swallow a segment, and continue"), d++;
1399
- }
1400
- return !!(s && (this.debug(`
1401
- >>> no match, partial?`, t, d, e, u), d === a));
1402
- }
1403
- let p;
1404
- if (typeof f == "string" ? (p = c === f, this.debug("string match", f, c, p)) : (p = f.test(c), this.debug("pattern match", f, c, p)), !p) return false;
1405
- }
1406
- if (o === a && h === l) return true;
1407
- if (o === a) return s;
1408
- if (h === l) return o === a - 1 && t[o] === "";
1409
- throw new Error("wtf?");
1410
- }
1411
- braceExpand() {
1412
- return ke(this.pattern, this.options);
1413
- }
1414
- parse(t) {
1415
- at(t);
1416
- let e = this.options;
1417
- if (t === "**") return A;
1418
- if (t === "") return "";
1419
- let s, i = null;
1420
- (s = t.match(js)) ? i = e.dot ? zs : Is : (s = t.match(Rs)) ? i = (e.nocase ? e.dot ? Ms : Ds : e.dot ? Fs : Os)(s[1]) : (s = t.match(Bs)) ? i = (e.nocase ? e.dot ? $s : Us : e.dot ? Gs : Hs)(s) : (s = t.match(Ns)) ? i = e.dot ? Ls : _s : (s = t.match(Ws)) && (i = Ps);
1421
- let r = Q.fromGlob(t, this.options).toMMPattern();
1422
- return i && typeof r == "object" && Reflect.defineProperty(r, "test", { value: i }), r;
1423
- }
1424
- makeRe() {
1425
- if (this.regexp || this.regexp === false) return this.regexp;
1426
- let t = this.set;
1427
- if (!t.length) return this.regexp = false, this.regexp;
1428
- let e = this.options, s = e.noglobstar ? Vs : e.dot ? Ys : Xs, i = new Set(e.nocase ? ["i"] : []), r = t.map((a) => {
1429
- let l = a.map((c) => {
1430
- if (c instanceof RegExp) for (let d of c.flags.split("")) i.add(d);
1431
- return typeof c == "string" ? ei(c) : c === A ? A : c._src;
1432
- });
1433
- l.forEach((c, d) => {
1434
- let u = l[d + 1], m = l[d - 1];
1435
- c !== A || m === A || (m === void 0 ? u !== void 0 && u !== A ? l[d + 1] = "(?:\\/|" + s + "\\/)?" + u : l[d] = s : u === void 0 ? l[d - 1] = m + "(?:\\/|\\/" + s + ")?" : u !== A && (l[d - 1] = m + "(?:\\/|\\/" + s + "\\/)" + u, l[d + 1] = A));
1436
- });
1437
- let f = l.filter((c) => c !== A);
1438
- if (this.partial && f.length >= 1) {
1439
- let c = [];
1440
- for (let d = 1; d <= f.length; d++) c.push(f.slice(0, d).join("/"));
1441
- return "(?:" + c.join("|") + ")";
1442
- }
1443
- return f.join("/");
1444
- }).join("|"), [o, h] = t.length > 1 ? ["(?:", ")"] : ["", ""];
1445
- r = "^" + o + r + h + "$", this.partial && (r = "^(?:\\/|" + o + r.slice(1, -1) + h + ")$"), this.negate && (r = "^(?!" + r + ").+$");
1446
- try {
1447
- this.regexp = new RegExp(r, [...i].join(""));
1448
- } catch {
1449
- this.regexp = false;
1450
- }
1451
- return this.regexp;
1452
- }
1453
- slashSplit(t) {
1454
- return this.preserveMultipleSlashes ? t.split("/") : this.isWindows && /^\/\/[^\/]+/.test(t) ? ["", ...t.split(/\/+/)] : t.split(/\/+/);
1455
- }
1456
- match(t, e = this.partial) {
1457
- if (this.debug("match", t, this.pattern), this.comment) return false;
1458
- if (this.empty) return t === "";
1459
- if (t === "/" && e) return true;
1460
- let s = this.options;
1461
- this.isWindows && (t = t.split("\\").join("/"));
1462
- let i = this.slashSplit(t);
1463
- this.debug(this.pattern, "split", i);
1464
- let r = this.set;
1465
- this.debug(this.pattern, "set", r);
1466
- let o = i[i.length - 1];
1467
- if (!o) for (let h = i.length - 2; !o && h >= 0; h--) o = i[h];
1468
- for (let h = 0; h < r.length; h++) {
1469
- let a = r[h], l = i;
1470
- if (s.matchBase && a.length === 1 && (l = [o]), this.matchOne(l, a, e)) return s.flipNegate ? true : !this.negate;
1471
- }
1472
- return s.flipNegate ? false : this.negate;
1473
- }
1474
- static defaults(t) {
1475
- return O.defaults(t).Minimatch;
1476
- }
1477
- };
1478
- O.AST = Q;
1479
- O.Minimatch = D;
1480
- O.escape = tt;
1481
- O.unescape = W;
1482
- var si = typeof performance == "object" && performance && typeof performance.now == "function" ? performance : Date, Oe = /* @__PURE__ */ new Set(), Vt = typeof process == "object" && process ? process : {}, Fe = (n7, t, e, s) => {
1483
- typeof Vt.emitWarning == "function" ? Vt.emitWarning(n7, t, e, s) : console.error(`[${e}] ${t}: ${n7}`);
1484
- }, At = globalThis.AbortController, Re = globalThis.AbortSignal;
1485
- if (typeof At > "u") {
1486
- Re = class {
1487
- onabort;
1488
- _onabort = [];
1489
- reason;
1490
- aborted = false;
1491
- addEventListener(e, s) {
1492
- this._onabort.push(s);
1493
- }
1494
- }, At = class {
1495
- constructor() {
1496
- t();
1497
- }
1498
- signal = new Re();
1499
- abort(e) {
1500
- if (!this.signal.aborted) {
1501
- this.signal.reason = e, this.signal.aborted = true;
1502
- for (let s of this.signal._onabort) s(e);
1503
- this.signal.onabort?.(e);
1504
- }
1505
- }
1506
- };
1507
- let n7 = Vt.env?.LRU_CACHE_IGNORE_AC_WARNING !== "1", t = () => {
1508
- n7 && (n7 = false, Fe("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.", "NO_ABORT_CONTROLLER", "ENOTSUP", t));
1509
- };
1510
- }
1511
- var ii = (n7) => !Oe.has(n7);
1512
- var q = (n7) => n7 && n7 === Math.floor(n7) && n7 > 0 && isFinite(n7), De = (n7) => q(n7) ? n7 <= Math.pow(2, 8) ? Uint8Array : n7 <= Math.pow(2, 16) ? Uint16Array : n7 <= Math.pow(2, 32) ? Uint32Array : n7 <= Number.MAX_SAFE_INTEGER ? Tt : null : null, Tt = class extends Array {
1513
- constructor(n7) {
1514
- super(n7), this.fill(0);
1515
- }
1516
- }, ri = class ct {
1517
- heap;
1518
- length;
1519
- static #t = false;
1520
- static create(t) {
1521
- let e = De(t);
1522
- if (!e) return [];
1523
- ct.#t = true;
1524
- let s = new ct(t, e);
1525
- return ct.#t = false, s;
1526
- }
1527
- constructor(t, e) {
1528
- if (!ct.#t) throw new TypeError("instantiate Stack using Stack.create(n)");
1529
- this.heap = new e(t), this.length = 0;
1530
- }
1531
- push(t) {
1532
- this.heap[this.length++] = t;
1533
- }
1534
- pop() {
1535
- return this.heap[--this.length];
1536
- }
1537
- }, ft = class Me {
1538
- #t;
1539
- #s;
1540
- #n;
1541
- #r;
1542
- #o;
1543
- #S;
1544
- #w;
1545
- #c;
1546
- get perf() {
1547
- return this.#c;
1548
- }
1549
- ttl;
1550
- ttlResolution;
1551
- ttlAutopurge;
1552
- updateAgeOnGet;
1553
- updateAgeOnHas;
1554
- allowStale;
1555
- noDisposeOnSet;
1556
- noUpdateTTL;
1557
- maxEntrySize;
1558
- sizeCalculation;
1559
- noDeleteOnFetchRejection;
1560
- noDeleteOnStaleGet;
1561
- allowStaleOnFetchAbort;
1562
- allowStaleOnFetchRejection;
1563
- ignoreFetchAbort;
1564
- #h;
1565
- #u;
1566
- #f;
1567
- #a;
1568
- #i;
1569
- #d;
1570
- #E;
1571
- #b;
1572
- #p;
1573
- #R;
1574
- #m;
1575
- #C;
1576
- #T;
1577
- #g;
1578
- #y;
1579
- #x;
1580
- #A;
1581
- #e;
1582
- #_;
1583
- static unsafeExposeInternals(t) {
1584
- return { starts: t.#T, ttls: t.#g, autopurgeTimers: t.#y, sizes: t.#C, keyMap: t.#f, keyList: t.#a, valList: t.#i, next: t.#d, prev: t.#E, get head() {
1585
- return t.#b;
1586
- }, get tail() {
1587
- return t.#p;
1588
- }, free: t.#R, isBackgroundFetch: (e) => t.#l(e), backgroundFetch: (e, s, i, r) => t.#U(e, s, i, r), moveToTail: (e) => t.#W(e), indexes: (e) => t.#F(e), rindexes: (e) => t.#D(e), isStale: (e) => t.#v(e) };
1589
- }
1590
- get max() {
1591
- return this.#t;
1592
- }
1593
- get maxSize() {
1594
- return this.#s;
1595
- }
1596
- get calculatedSize() {
1597
- return this.#u;
1598
- }
1599
- get size() {
1600
- return this.#h;
1601
- }
1602
- get fetchMethod() {
1603
- return this.#S;
1604
- }
1605
- get memoMethod() {
1606
- return this.#w;
1607
- }
1608
- get dispose() {
1609
- return this.#n;
1610
- }
1611
- get onInsert() {
1612
- return this.#r;
1613
- }
1614
- get disposeAfter() {
1615
- return this.#o;
1616
- }
1617
- constructor(t) {
1618
- let { max: e = 0, ttl: s, ttlResolution: i = 1, ttlAutopurge: r, updateAgeOnGet: o, updateAgeOnHas: h, allowStale: a, dispose: l, onInsert: f, disposeAfter: c, noDisposeOnSet: d, noUpdateTTL: u, maxSize: m = 0, maxEntrySize: p = 0, sizeCalculation: w, fetchMethod: g, memoMethod: S, noDeleteOnFetchRejection: E, noDeleteOnStaleGet: y, allowStaleOnFetchRejection: b, allowStaleOnFetchAbort: z, ignoreFetchAbort: $, perf: J } = t;
1619
- if (J !== void 0 && typeof J?.now != "function") throw new TypeError("perf option must have a now() method if specified");
1620
- if (this.#c = J ?? si, e !== 0 && !q(e)) throw new TypeError("max option must be a nonnegative integer");
1621
- let Z = e ? De(e) : Array;
1622
- if (!Z) throw new Error("invalid max value: " + e);
1623
- if (this.#t = e, this.#s = m, this.maxEntrySize = p || this.#s, this.sizeCalculation = w, this.sizeCalculation) {
1624
- if (!this.#s && !this.maxEntrySize) throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");
1625
- if (typeof this.sizeCalculation != "function") throw new TypeError("sizeCalculation set to non-function");
1626
- }
1627
- if (S !== void 0 && typeof S != "function") throw new TypeError("memoMethod must be a function if defined");
1628
- if (this.#w = S, g !== void 0 && typeof g != "function") throw new TypeError("fetchMethod must be a function if specified");
1629
- if (this.#S = g, this.#A = !!g, this.#f = /* @__PURE__ */ new Map(), this.#a = new Array(e).fill(void 0), this.#i = new Array(e).fill(void 0), this.#d = new Z(e), this.#E = new Z(e), this.#b = 0, this.#p = 0, this.#R = ri.create(e), this.#h = 0, this.#u = 0, typeof l == "function" && (this.#n = l), typeof f == "function" && (this.#r = f), typeof c == "function" ? (this.#o = c, this.#m = []) : (this.#o = void 0, this.#m = void 0), this.#x = !!this.#n, this.#_ = !!this.#r, this.#e = !!this.#o, this.noDisposeOnSet = !!d, this.noUpdateTTL = !!u, this.noDeleteOnFetchRejection = !!E, this.allowStaleOnFetchRejection = !!b, this.allowStaleOnFetchAbort = !!z, this.ignoreFetchAbort = !!$, this.maxEntrySize !== 0) {
1630
- if (this.#s !== 0 && !q(this.#s)) throw new TypeError("maxSize must be a positive integer if specified");
1631
- if (!q(this.maxEntrySize)) throw new TypeError("maxEntrySize must be a positive integer if specified");
1632
- this.#G();
1633
- }
1634
- if (this.allowStale = !!a, this.noDeleteOnStaleGet = !!y, this.updateAgeOnGet = !!o, this.updateAgeOnHas = !!h, this.ttlResolution = q(i) || i === 0 ? i : 1, this.ttlAutopurge = !!r, this.ttl = s || 0, this.ttl) {
1635
- if (!q(this.ttl)) throw new TypeError("ttl must be a positive integer if specified");
1636
- this.#M();
1637
- }
1638
- if (this.#t === 0 && this.ttl === 0 && this.#s === 0) throw new TypeError("At least one of max, maxSize, or ttl is required");
1639
- if (!this.ttlAutopurge && !this.#t && !this.#s) {
1640
- let $t = "LRU_CACHE_UNBOUNDED";
1641
- ii($t) && (Oe.add($t), Fe("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.", "UnboundedCacheWarning", $t, Me));
1642
- }
1643
- }
1644
- getRemainingTTL(t) {
1645
- return this.#f.has(t) ? 1 / 0 : 0;
1646
- }
1647
- #M() {
1648
- let t = new Tt(this.#t), e = new Tt(this.#t);
1649
- this.#g = t, this.#T = e;
1650
- let s = this.ttlAutopurge ? new Array(this.#t) : void 0;
1651
- this.#y = s, this.#j = (o, h, a = this.#c.now()) => {
1652
- if (e[o] = h !== 0 ? a : 0, t[o] = h, s?.[o] && (clearTimeout(s[o]), s[o] = void 0), h !== 0 && s) {
1653
- let l = setTimeout(() => {
1654
- this.#v(o) && this.#O(this.#a[o], "expire");
1655
- }, h + 1);
1656
- l.unref && l.unref(), s[o] = l;
1657
- }
1658
- }, this.#k = (o) => {
1659
- e[o] = t[o] !== 0 ? this.#c.now() : 0;
1660
- }, this.#N = (o, h) => {
1661
- if (t[h]) {
1662
- let a = t[h], l = e[h];
1663
- if (!a || !l) return;
1664
- o.ttl = a, o.start = l, o.now = i || r();
1665
- let f = o.now - l;
1666
- o.remainingTTL = a - f;
1667
- }
1668
- };
1669
- let i = 0, r = () => {
1670
- let o = this.#c.now();
1671
- if (this.ttlResolution > 0) {
1672
- i = o;
1673
- let h = setTimeout(() => i = 0, this.ttlResolution);
1674
- h.unref && h.unref();
1675
- }
1676
- return o;
1677
- };
1678
- this.getRemainingTTL = (o) => {
1679
- let h = this.#f.get(o);
1680
- if (h === void 0) return 0;
1681
- let a = t[h], l = e[h];
1682
- if (!a || !l) return 1 / 0;
1683
- let f = (i || r()) - l;
1684
- return a - f;
1685
- }, this.#v = (o) => {
1686
- let h = e[o], a = t[o];
1687
- return !!a && !!h && (i || r()) - h > a;
1688
- };
1689
- }
1690
- #k = () => {
1691
- };
1692
- #N = () => {
1693
- };
1694
- #j = () => {
1695
- };
1696
- #v = () => false;
1697
- #G() {
1698
- let t = new Tt(this.#t);
1699
- this.#u = 0, this.#C = t, this.#P = (e) => {
1700
- this.#u -= t[e], t[e] = 0;
1701
- }, this.#I = (e, s, i, r) => {
1702
- if (this.#l(s)) return 0;
1703
- if (!q(i)) if (r) {
1704
- if (typeof r != "function") throw new TypeError("sizeCalculation must be a function");
1705
- if (i = r(s, e), !q(i)) throw new TypeError("sizeCalculation return invalid (expect positive integer)");
1706
- } else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");
1707
- return i;
1708
- }, this.#L = (e, s, i) => {
1709
- if (t[e] = s, this.#s) {
1710
- let r = this.#s - t[e];
1711
- for (; this.#u > r; ) this.#B(true);
1712
- }
1713
- this.#u += t[e], i && (i.entrySize = s, i.totalCalculatedSize = this.#u);
1714
- };
1715
- }
1716
- #P = (t) => {
1717
- };
1718
- #L = (t, e, s) => {
1719
- };
1720
- #I = (t, e, s, i) => {
1721
- if (s || i) throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");
1722
- return 0;
1723
- };
1724
- *#F({ allowStale: t = this.allowStale } = {}) {
1725
- if (this.#h) for (let e = this.#p; !(!this.#z(e) || ((t || !this.#v(e)) && (yield e), e === this.#b)); ) e = this.#E[e];
1726
- }
1727
- *#D({ allowStale: t = this.allowStale } = {}) {
1728
- if (this.#h) for (let e = this.#b; !(!this.#z(e) || ((t || !this.#v(e)) && (yield e), e === this.#p)); ) e = this.#d[e];
1729
- }
1730
- #z(t) {
1731
- return t !== void 0 && this.#f.get(this.#a[t]) === t;
1732
- }
1733
- *entries() {
1734
- for (let t of this.#F()) this.#i[t] !== void 0 && this.#a[t] !== void 0 && !this.#l(this.#i[t]) && (yield [this.#a[t], this.#i[t]]);
1735
- }
1736
- *rentries() {
1737
- for (let t of this.#D()) this.#i[t] !== void 0 && this.#a[t] !== void 0 && !this.#l(this.#i[t]) && (yield [this.#a[t], this.#i[t]]);
1738
- }
1739
- *keys() {
1740
- for (let t of this.#F()) {
1741
- let e = this.#a[t];
1742
- e !== void 0 && !this.#l(this.#i[t]) && (yield e);
1743
- }
1744
- }
1745
- *rkeys() {
1746
- for (let t of this.#D()) {
1747
- let e = this.#a[t];
1748
- e !== void 0 && !this.#l(this.#i[t]) && (yield e);
1749
- }
1750
- }
1751
- *values() {
1752
- for (let t of this.#F()) this.#i[t] !== void 0 && !this.#l(this.#i[t]) && (yield this.#i[t]);
1753
- }
1754
- *rvalues() {
1755
- for (let t of this.#D()) this.#i[t] !== void 0 && !this.#l(this.#i[t]) && (yield this.#i[t]);
1756
- }
1757
- [Symbol.iterator]() {
1758
- return this.entries();
1759
- }
1760
- [Symbol.toStringTag] = "LRUCache";
1761
- find(t, e = {}) {
1762
- for (let s of this.#F()) {
1763
- let i = this.#i[s], r = this.#l(i) ? i.__staleWhileFetching : i;
1764
- if (r !== void 0 && t(r, this.#a[s], this)) return this.get(this.#a[s], e);
1765
- }
1766
- }
1767
- forEach(t, e = this) {
1768
- for (let s of this.#F()) {
1769
- let i = this.#i[s], r = this.#l(i) ? i.__staleWhileFetching : i;
1770
- r !== void 0 && t.call(e, r, this.#a[s], this);
1771
- }
1772
- }
1773
- rforEach(t, e = this) {
1774
- for (let s of this.#D()) {
1775
- let i = this.#i[s], r = this.#l(i) ? i.__staleWhileFetching : i;
1776
- r !== void 0 && t.call(e, r, this.#a[s], this);
1777
- }
1778
- }
1779
- purgeStale() {
1780
- let t = false;
1781
- for (let e of this.#D({ allowStale: true })) this.#v(e) && (this.#O(this.#a[e], "expire"), t = true);
1782
- return t;
1783
- }
1784
- info(t) {
1785
- let e = this.#f.get(t);
1786
- if (e === void 0) return;
1787
- let s = this.#i[e], i = this.#l(s) ? s.__staleWhileFetching : s;
1788
- if (i === void 0) return;
1789
- let r = { value: i };
1790
- if (this.#g && this.#T) {
1791
- let o = this.#g[e], h = this.#T[e];
1792
- if (o && h) {
1793
- let a = o - (this.#c.now() - h);
1794
- r.ttl = a, r.start = Date.now();
1795
- }
1796
- }
1797
- return this.#C && (r.size = this.#C[e]), r;
1798
- }
1799
- dump() {
1800
- let t = [];
1801
- for (let e of this.#F({ allowStale: true })) {
1802
- let s = this.#a[e], i = this.#i[e], r = this.#l(i) ? i.__staleWhileFetching : i;
1803
- if (r === void 0 || s === void 0) continue;
1804
- let o = { value: r };
1805
- if (this.#g && this.#T) {
1806
- o.ttl = this.#g[e];
1807
- let h = this.#c.now() - this.#T[e];
1808
- o.start = Math.floor(Date.now() - h);
1809
- }
1810
- this.#C && (o.size = this.#C[e]), t.unshift([s, o]);
1811
- }
1812
- return t;
1813
- }
1814
- load(t) {
1815
- this.clear();
1816
- for (let [e, s] of t) {
1817
- if (s.start) {
1818
- let i = Date.now() - s.start;
1819
- s.start = this.#c.now() - i;
1820
- }
1821
- this.set(e, s.value, s);
1822
- }
1823
- }
1824
- set(t, e, s = {}) {
1825
- if (e === void 0) return this.delete(t), this;
1826
- let { ttl: i = this.ttl, start: r, noDisposeOnSet: o = this.noDisposeOnSet, sizeCalculation: h = this.sizeCalculation, status: a } = s, { noUpdateTTL: l = this.noUpdateTTL } = s, f = this.#I(t, e, s.size || 0, h);
1827
- if (this.maxEntrySize && f > this.maxEntrySize) return a && (a.set = "miss", a.maxEntrySizeExceeded = true), this.#O(t, "set"), this;
1828
- let c = this.#h === 0 ? void 0 : this.#f.get(t);
1829
- if (c === void 0) c = this.#h === 0 ? this.#p : this.#R.length !== 0 ? this.#R.pop() : this.#h === this.#t ? this.#B(false) : this.#h, this.#a[c] = t, this.#i[c] = e, this.#f.set(t, c), this.#d[this.#p] = c, this.#E[c] = this.#p, this.#p = c, this.#h++, this.#L(c, f, a), a && (a.set = "add"), l = false, this.#_ && this.#r?.(e, t, "add");
1830
- else {
1831
- this.#W(c);
1832
- let d = this.#i[c];
1833
- if (e !== d) {
1834
- if (this.#A && this.#l(d)) {
1835
- d.__abortController.abort(new Error("replaced"));
1836
- let { __staleWhileFetching: u } = d;
1837
- u !== void 0 && !o && (this.#x && this.#n?.(u, t, "set"), this.#e && this.#m?.push([u, t, "set"]));
1838
- } else o || (this.#x && this.#n?.(d, t, "set"), this.#e && this.#m?.push([d, t, "set"]));
1839
- if (this.#P(c), this.#L(c, f, a), this.#i[c] = e, a) {
1840
- a.set = "replace";
1841
- let u = d && this.#l(d) ? d.__staleWhileFetching : d;
1842
- u !== void 0 && (a.oldValue = u);
1843
- }
1844
- } else a && (a.set = "update");
1845
- this.#_ && this.onInsert?.(e, t, e === d ? "update" : "replace");
1846
- }
1847
- if (i !== 0 && !this.#g && this.#M(), this.#g && (l || this.#j(c, i, r), a && this.#N(a, c)), !o && this.#e && this.#m) {
1848
- let d = this.#m, u;
1849
- for (; u = d?.shift(); ) this.#o?.(...u);
1850
- }
1851
- return this;
1852
- }
1853
- pop() {
1854
- try {
1855
- for (; this.#h; ) {
1856
- let t = this.#i[this.#b];
1857
- if (this.#B(true), this.#l(t)) {
1858
- if (t.__staleWhileFetching) return t.__staleWhileFetching;
1859
- } else if (t !== void 0) return t;
1860
- }
1861
- } finally {
1862
- if (this.#e && this.#m) {
1863
- let t = this.#m, e;
1864
- for (; e = t?.shift(); ) this.#o?.(...e);
1865
- }
1866
- }
1867
- }
1868
- #B(t) {
1869
- let e = this.#b, s = this.#a[e], i = this.#i[e];
1870
- return this.#A && this.#l(i) ? i.__abortController.abort(new Error("evicted")) : (this.#x || this.#e) && (this.#x && this.#n?.(i, s, "evict"), this.#e && this.#m?.push([i, s, "evict"])), this.#P(e), this.#y?.[e] && (clearTimeout(this.#y[e]), this.#y[e] = void 0), t && (this.#a[e] = void 0, this.#i[e] = void 0, this.#R.push(e)), this.#h === 1 ? (this.#b = this.#p = 0, this.#R.length = 0) : this.#b = this.#d[e], this.#f.delete(s), this.#h--, e;
1871
- }
1872
- has(t, e = {}) {
1873
- let { updateAgeOnHas: s = this.updateAgeOnHas, status: i } = e, r = this.#f.get(t);
1874
- if (r !== void 0) {
1875
- let o = this.#i[r];
1876
- if (this.#l(o) && o.__staleWhileFetching === void 0) return false;
1877
- if (this.#v(r)) i && (i.has = "stale", this.#N(i, r));
1878
- else return s && this.#k(r), i && (i.has = "hit", this.#N(i, r)), true;
1879
- } else i && (i.has = "miss");
1880
- return false;
1881
- }
1882
- peek(t, e = {}) {
1883
- let { allowStale: s = this.allowStale } = e, i = this.#f.get(t);
1884
- if (i === void 0 || !s && this.#v(i)) return;
1885
- let r = this.#i[i];
1886
- return this.#l(r) ? r.__staleWhileFetching : r;
1887
- }
1888
- #U(t, e, s, i) {
1889
- let r = e === void 0 ? void 0 : this.#i[e];
1890
- if (this.#l(r)) return r;
1891
- let o = new At(), { signal: h } = s;
1892
- h?.addEventListener("abort", () => o.abort(h.reason), { signal: o.signal });
1893
- let a = { signal: o.signal, options: s, context: i }, l = (p, w = false) => {
1894
- let { aborted: g } = o.signal, S = s.ignoreFetchAbort && p !== void 0, E = s.ignoreFetchAbort || !!(s.allowStaleOnFetchAbort && p !== void 0);
1895
- if (s.status && (g && !w ? (s.status.fetchAborted = true, s.status.fetchError = o.signal.reason, S && (s.status.fetchAbortIgnored = true)) : s.status.fetchResolved = true), g && !S && !w) return c(o.signal.reason, E);
1896
- let y = u, b = this.#i[e];
1897
- return (b === u || S && w && b === void 0) && (p === void 0 ? y.__staleWhileFetching !== void 0 ? this.#i[e] = y.__staleWhileFetching : this.#O(t, "fetch") : (s.status && (s.status.fetchUpdated = true), this.set(t, p, a.options))), p;
1898
- }, f = (p) => (s.status && (s.status.fetchRejected = true, s.status.fetchError = p), c(p, false)), c = (p, w) => {
1899
- let { aborted: g } = o.signal, S = g && s.allowStaleOnFetchAbort, E = S || s.allowStaleOnFetchRejection, y = E || s.noDeleteOnFetchRejection, b = u;
1900
- if (this.#i[e] === u && (!y || !w && b.__staleWhileFetching === void 0 ? this.#O(t, "fetch") : S || (this.#i[e] = b.__staleWhileFetching)), E) return s.status && b.__staleWhileFetching !== void 0 && (s.status.returnedStale = true), b.__staleWhileFetching;
1901
- if (b.__returned === b) throw p;
1902
- }, d = (p, w) => {
1903
- let g = this.#S?.(t, r, a);
1904
- g && g instanceof Promise && g.then((S) => p(S === void 0 ? void 0 : S), w), o.signal.addEventListener("abort", () => {
1905
- (!s.ignoreFetchAbort || s.allowStaleOnFetchAbort) && (p(void 0), s.allowStaleOnFetchAbort && (p = (S) => l(S, true)));
1906
- });
1907
- };
1908
- s.status && (s.status.fetchDispatched = true);
1909
- let u = new Promise(d).then(l, f), m = Object.assign(u, { __abortController: o, __staleWhileFetching: r, __returned: void 0 });
1910
- return e === void 0 ? (this.set(t, m, { ...a.options, status: void 0 }), e = this.#f.get(t)) : this.#i[e] = m, m;
1911
- }
1912
- #l(t) {
1913
- if (!this.#A) return false;
1914
- let e = t;
1915
- return !!e && e instanceof Promise && e.hasOwnProperty("__staleWhileFetching") && e.__abortController instanceof At;
1916
- }
1917
- async fetch(t, e = {}) {
1918
- let { allowStale: s = this.allowStale, updateAgeOnGet: i = this.updateAgeOnGet, noDeleteOnStaleGet: r = this.noDeleteOnStaleGet, ttl: o = this.ttl, noDisposeOnSet: h = this.noDisposeOnSet, size: a = 0, sizeCalculation: l = this.sizeCalculation, noUpdateTTL: f = this.noUpdateTTL, noDeleteOnFetchRejection: c = this.noDeleteOnFetchRejection, allowStaleOnFetchRejection: d = this.allowStaleOnFetchRejection, ignoreFetchAbort: u = this.ignoreFetchAbort, allowStaleOnFetchAbort: m = this.allowStaleOnFetchAbort, context: p, forceRefresh: w = false, status: g, signal: S } = e;
1919
- if (!this.#A) return g && (g.fetch = "get"), this.get(t, { allowStale: s, updateAgeOnGet: i, noDeleteOnStaleGet: r, status: g });
1920
- let E = { allowStale: s, updateAgeOnGet: i, noDeleteOnStaleGet: r, ttl: o, noDisposeOnSet: h, size: a, sizeCalculation: l, noUpdateTTL: f, noDeleteOnFetchRejection: c, allowStaleOnFetchRejection: d, allowStaleOnFetchAbort: m, ignoreFetchAbort: u, status: g, signal: S }, y = this.#f.get(t);
1921
- if (y === void 0) {
1922
- g && (g.fetch = "miss");
1923
- let b = this.#U(t, y, E, p);
1924
- return b.__returned = b;
1925
- } else {
1926
- let b = this.#i[y];
1927
- if (this.#l(b)) {
1928
- let Z = s && b.__staleWhileFetching !== void 0;
1929
- return g && (g.fetch = "inflight", Z && (g.returnedStale = true)), Z ? b.__staleWhileFetching : b.__returned = b;
1930
- }
1931
- let z = this.#v(y);
1932
- if (!w && !z) return g && (g.fetch = "hit"), this.#W(y), i && this.#k(y), g && this.#N(g, y), b;
1933
- let $ = this.#U(t, y, E, p), J = $.__staleWhileFetching !== void 0 && s;
1934
- return g && (g.fetch = z ? "stale" : "refresh", J && z && (g.returnedStale = true)), J ? $.__staleWhileFetching : $.__returned = $;
1935
- }
1936
- }
1937
- async forceFetch(t, e = {}) {
1938
- let s = await this.fetch(t, e);
1939
- if (s === void 0) throw new Error("fetch() returned undefined");
1940
- return s;
1941
- }
1942
- memo(t, e = {}) {
1943
- let s = this.#w;
1944
- if (!s) throw new Error("no memoMethod provided to constructor");
1945
- let { context: i, forceRefresh: r, ...o } = e, h = this.get(t, o);
1946
- if (!r && h !== void 0) return h;
1947
- let a = s(t, h, { options: o, context: i });
1948
- return this.set(t, a, o), a;
1949
- }
1950
- get(t, e = {}) {
1951
- let { allowStale: s = this.allowStale, updateAgeOnGet: i = this.updateAgeOnGet, noDeleteOnStaleGet: r = this.noDeleteOnStaleGet, status: o } = e, h = this.#f.get(t);
1952
- if (h !== void 0) {
1953
- let a = this.#i[h], l = this.#l(a);
1954
- return o && this.#N(o, h), this.#v(h) ? (o && (o.get = "stale"), l ? (o && s && a.__staleWhileFetching !== void 0 && (o.returnedStale = true), s ? a.__staleWhileFetching : void 0) : (r || this.#O(t, "expire"), o && s && (o.returnedStale = true), s ? a : void 0)) : (o && (o.get = "hit"), l ? a.__staleWhileFetching : (this.#W(h), i && this.#k(h), a));
1955
- } else o && (o.get = "miss");
1956
- }
1957
- #$(t, e) {
1958
- this.#E[e] = t, this.#d[t] = e;
1959
- }
1960
- #W(t) {
1961
- t !== this.#p && (t === this.#b ? this.#b = this.#d[t] : this.#$(this.#E[t], this.#d[t]), this.#$(this.#p, t), this.#p = t);
1962
- }
1963
- delete(t) {
1964
- return this.#O(t, "delete");
1965
- }
1966
- #O(t, e) {
1967
- let s = false;
1968
- if (this.#h !== 0) {
1969
- let i = this.#f.get(t);
1970
- if (i !== void 0) if (this.#y?.[i] && (clearTimeout(this.#y?.[i]), this.#y[i] = void 0), s = true, this.#h === 1) this.#H(e);
1971
- else {
1972
- this.#P(i);
1973
- let r = this.#i[i];
1974
- if (this.#l(r) ? r.__abortController.abort(new Error("deleted")) : (this.#x || this.#e) && (this.#x && this.#n?.(r, t, e), this.#e && this.#m?.push([r, t, e])), this.#f.delete(t), this.#a[i] = void 0, this.#i[i] = void 0, i === this.#p) this.#p = this.#E[i];
1975
- else if (i === this.#b) this.#b = this.#d[i];
1976
- else {
1977
- let o = this.#E[i];
1978
- this.#d[o] = this.#d[i];
1979
- let h = this.#d[i];
1980
- this.#E[h] = this.#E[i];
1981
- }
1982
- this.#h--, this.#R.push(i);
1983
- }
1984
- }
1985
- if (this.#e && this.#m?.length) {
1986
- let i = this.#m, r;
1987
- for (; r = i?.shift(); ) this.#o?.(...r);
1988
- }
1989
- return s;
1990
- }
1991
- clear() {
1992
- return this.#H("delete");
1993
- }
1994
- #H(t) {
1995
- for (let e of this.#D({ allowStale: true })) {
1996
- let s = this.#i[e];
1997
- if (this.#l(s)) s.__abortController.abort(new Error("deleted"));
1998
- else {
1999
- let i = this.#a[e];
2000
- this.#x && this.#n?.(s, i, t), this.#e && this.#m?.push([s, i, t]);
2001
- }
2002
- }
2003
- if (this.#f.clear(), this.#i.fill(void 0), this.#a.fill(void 0), this.#g && this.#T) {
2004
- this.#g.fill(0), this.#T.fill(0);
2005
- for (let e of this.#y ?? []) e !== void 0 && clearTimeout(e);
2006
- this.#y?.fill(void 0);
2007
- }
2008
- if (this.#C && this.#C.fill(0), this.#b = 0, this.#p = 0, this.#R.length = 0, this.#u = 0, this.#h = 0, this.#e && this.#m) {
2009
- let e = this.#m, s;
2010
- for (; s = e?.shift(); ) this.#o?.(...s);
2011
- }
2012
- }
2013
- };
2014
- var Ne = typeof process == "object" && process ? process : { stdout: null, stderr: null }, oi = (n7) => !!n7 && typeof n7 == "object" && (n7 instanceof V || n7 instanceof Pe || hi(n7) || ai(n7)), hi = (n7) => !!n7 && typeof n7 == "object" && n7 instanceof node_events.EventEmitter && typeof n7.pipe == "function" && n7.pipe !== Pe.Writable.prototype.pipe, ai = (n7) => !!n7 && typeof n7 == "object" && n7 instanceof node_events.EventEmitter && typeof n7.write == "function" && typeof n7.end == "function", G = Symbol("EOF"), H = Symbol("maybeEmitEnd"), K = Symbol("emittedEnd"), kt = Symbol("emittingEnd"), ut = Symbol("emittedError"), Rt = Symbol("closed"), _e = Symbol("read"), Ot = Symbol("flush"), Le = Symbol("flushChunk"), P = Symbol("encoding"), et = Symbol("decoder"), v = Symbol("flowing"), dt = Symbol("paused"), st = Symbol("resume"), C = Symbol("buffer"), F = Symbol("pipes"), T = Symbol("bufferLength"), Yt = Symbol("bufferPush"), Ft = Symbol("bufferShift"), k = Symbol("objectMode"), x = Symbol("destroyed"), Xt = Symbol("error"), Jt = Symbol("emitData"), We = Symbol("emitEnd"), Zt = Symbol("emitEnd2"), B = Symbol("async"), Qt = Symbol("abort"), Dt = Symbol("aborted"), pt = Symbol("signal"), Y = Symbol("dataListeners"), M = Symbol("discarded"), mt = (n7) => Promise.resolve().then(n7), li = (n7) => n7(), ci = (n7) => n7 === "end" || n7 === "finish" || n7 === "prefinish", fi = (n7) => n7 instanceof ArrayBuffer || !!n7 && typeof n7 == "object" && n7.constructor && n7.constructor.name === "ArrayBuffer" && n7.byteLength >= 0, ui = (n7) => !Buffer.isBuffer(n7) && ArrayBuffer.isView(n7), Mt = class {
2015
- src;
2016
- dest;
2017
- opts;
2018
- ondrain;
2019
- constructor(t, e, s) {
2020
- this.src = t, this.dest = e, this.opts = s, this.ondrain = () => t[st](), this.dest.on("drain", this.ondrain);
2021
- }
2022
- unpipe() {
2023
- this.dest.removeListener("drain", this.ondrain);
2024
- }
2025
- proxyErrors(t) {
2026
- }
2027
- end() {
2028
- this.unpipe(), this.opts.end && this.dest.end();
2029
- }
2030
- }, te = class extends Mt {
2031
- unpipe() {
2032
- this.src.removeListener("error", this.proxyErrors), super.unpipe();
2033
- }
2034
- constructor(t, e, s) {
2035
- super(t, e, s), this.proxyErrors = (i) => e.emit("error", i), t.on("error", this.proxyErrors);
2036
- }
2037
- }, di = (n7) => !!n7.objectMode, pi = (n7) => !n7.objectMode && !!n7.encoding && n7.encoding !== "buffer", V = class extends node_events.EventEmitter {
2038
- [v] = false;
2039
- [dt] = false;
2040
- [F] = [];
2041
- [C] = [];
2042
- [k];
2043
- [P];
2044
- [B];
2045
- [et];
2046
- [G] = false;
2047
- [K] = false;
2048
- [kt] = false;
2049
- [Rt] = false;
2050
- [ut] = null;
2051
- [T] = 0;
2052
- [x] = false;
2053
- [pt];
2054
- [Dt] = false;
2055
- [Y] = 0;
2056
- [M] = false;
2057
- writable = true;
2058
- readable = true;
2059
- constructor(...t) {
2060
- let e = t[0] || {};
2061
- if (super(), e.objectMode && typeof e.encoding == "string") throw new TypeError("Encoding and objectMode may not be used together");
2062
- di(e) ? (this[k] = true, this[P] = null) : pi(e) ? (this[P] = e.encoding, this[k] = false) : (this[k] = false, this[P] = null), this[B] = !!e.async, this[et] = this[P] ? new node_string_decoder.StringDecoder(this[P]) : null, e && e.debugExposeBuffer === true && Object.defineProperty(this, "buffer", { get: () => this[C] }), e && e.debugExposePipes === true && Object.defineProperty(this, "pipes", { get: () => this[F] });
2063
- let { signal: s } = e;
2064
- s && (this[pt] = s, s.aborted ? this[Qt]() : s.addEventListener("abort", () => this[Qt]()));
2065
- }
2066
- get bufferLength() {
2067
- return this[T];
2068
- }
2069
- get encoding() {
2070
- return this[P];
2071
- }
2072
- set encoding(t) {
2073
- throw new Error("Encoding must be set at instantiation time");
2074
- }
2075
- setEncoding(t) {
2076
- throw new Error("Encoding must be set at instantiation time");
2077
- }
2078
- get objectMode() {
2079
- return this[k];
2080
- }
2081
- set objectMode(t) {
2082
- throw new Error("objectMode must be set at instantiation time");
2083
- }
2084
- get async() {
2085
- return this[B];
2086
- }
2087
- set async(t) {
2088
- this[B] = this[B] || !!t;
2089
- }
2090
- [Qt]() {
2091
- this[Dt] = true, this.emit("abort", this[pt]?.reason), this.destroy(this[pt]?.reason);
2092
- }
2093
- get aborted() {
2094
- return this[Dt];
2095
- }
2096
- set aborted(t) {
2097
- }
2098
- write(t, e, s) {
2099
- if (this[Dt]) return false;
2100
- if (this[G]) throw new Error("write after end");
2101
- if (this[x]) return this.emit("error", Object.assign(new Error("Cannot call write after a stream was destroyed"), { code: "ERR_STREAM_DESTROYED" })), true;
2102
- typeof e == "function" && (s = e, e = "utf8"), e || (e = "utf8");
2103
- let i = this[B] ? mt : li;
2104
- if (!this[k] && !Buffer.isBuffer(t)) {
2105
- if (ui(t)) t = Buffer.from(t.buffer, t.byteOffset, t.byteLength);
2106
- else if (fi(t)) t = Buffer.from(t);
2107
- else if (typeof t != "string") throw new Error("Non-contiguous data written to non-objectMode stream");
2108
- }
2109
- return this[k] ? (this[v] && this[T] !== 0 && this[Ot](true), this[v] ? this.emit("data", t) : this[Yt](t), this[T] !== 0 && this.emit("readable"), s && i(s), this[v]) : t.length ? (typeof t == "string" && !(e === this[P] && !this[et]?.lastNeed) && (t = Buffer.from(t, e)), Buffer.isBuffer(t) && this[P] && (t = this[et].write(t)), this[v] && this[T] !== 0 && this[Ot](true), this[v] ? this.emit("data", t) : this[Yt](t), this[T] !== 0 && this.emit("readable"), s && i(s), this[v]) : (this[T] !== 0 && this.emit("readable"), s && i(s), this[v]);
2110
- }
2111
- read(t) {
2112
- if (this[x]) return null;
2113
- if (this[M] = false, this[T] === 0 || t === 0 || t && t > this[T]) return this[H](), null;
2114
- this[k] && (t = null), this[C].length > 1 && !this[k] && (this[C] = [this[P] ? this[C].join("") : Buffer.concat(this[C], this[T])]);
2115
- let e = this[_e](t || null, this[C][0]);
2116
- return this[H](), e;
2117
- }
2118
- [_e](t, e) {
2119
- if (this[k]) this[Ft]();
2120
- else {
2121
- let s = e;
2122
- t === s.length || t === null ? this[Ft]() : typeof s == "string" ? (this[C][0] = s.slice(t), e = s.slice(0, t), this[T] -= t) : (this[C][0] = s.subarray(t), e = s.subarray(0, t), this[T] -= t);
2123
- }
2124
- return this.emit("data", e), !this[C].length && !this[G] && this.emit("drain"), e;
2125
- }
2126
- end(t, e, s) {
2127
- return typeof t == "function" && (s = t, t = void 0), typeof e == "function" && (s = e, e = "utf8"), t !== void 0 && this.write(t, e), s && this.once("end", s), this[G] = true, this.writable = false, (this[v] || !this[dt]) && this[H](), this;
2128
- }
2129
- [st]() {
2130
- this[x] || (!this[Y] && !this[F].length && (this[M] = true), this[dt] = false, this[v] = true, this.emit("resume"), this[C].length ? this[Ot]() : this[G] ? this[H]() : this.emit("drain"));
2131
- }
2132
- resume() {
2133
- return this[st]();
2134
- }
2135
- pause() {
2136
- this[v] = false, this[dt] = true, this[M] = false;
2137
- }
2138
- get destroyed() {
2139
- return this[x];
2140
- }
2141
- get flowing() {
2142
- return this[v];
2143
- }
2144
- get paused() {
2145
- return this[dt];
2146
- }
2147
- [Yt](t) {
2148
- this[k] ? this[T] += 1 : this[T] += t.length, this[C].push(t);
2149
- }
2150
- [Ft]() {
2151
- return this[k] ? this[T] -= 1 : this[T] -= this[C][0].length, this[C].shift();
2152
- }
2153
- [Ot](t = false) {
2154
- do
2155
- ;
2156
- while (this[Le](this[Ft]()) && this[C].length);
2157
- !t && !this[C].length && !this[G] && this.emit("drain");
2158
- }
2159
- [Le](t) {
2160
- return this.emit("data", t), this[v];
2161
- }
2162
- pipe(t, e) {
2163
- if (this[x]) return t;
2164
- this[M] = false;
2165
- let s = this[K];
2166
- return e = e || {}, t === Ne.stdout || t === Ne.stderr ? e.end = false : e.end = e.end !== false, e.proxyErrors = !!e.proxyErrors, s ? e.end && t.end() : (this[F].push(e.proxyErrors ? new te(this, t, e) : new Mt(this, t, e)), this[B] ? mt(() => this[st]()) : this[st]()), t;
2167
- }
2168
- unpipe(t) {
2169
- let e = this[F].find((s) => s.dest === t);
2170
- e && (this[F].length === 1 ? (this[v] && this[Y] === 0 && (this[v] = false), this[F] = []) : this[F].splice(this[F].indexOf(e), 1), e.unpipe());
2171
- }
2172
- addListener(t, e) {
2173
- return this.on(t, e);
2174
- }
2175
- on(t, e) {
2176
- let s = super.on(t, e);
2177
- if (t === "data") this[M] = false, this[Y]++, !this[F].length && !this[v] && this[st]();
2178
- else if (t === "readable" && this[T] !== 0) super.emit("readable");
2179
- else if (ci(t) && this[K]) super.emit(t), this.removeAllListeners(t);
2180
- else if (t === "error" && this[ut]) {
2181
- let i = e;
2182
- this[B] ? mt(() => i.call(this, this[ut])) : i.call(this, this[ut]);
2183
- }
2184
- return s;
2185
- }
2186
- removeListener(t, e) {
2187
- return this.off(t, e);
2188
- }
2189
- off(t, e) {
2190
- let s = super.off(t, e);
2191
- return t === "data" && (this[Y] = this.listeners("data").length, this[Y] === 0 && !this[M] && !this[F].length && (this[v] = false)), s;
2192
- }
2193
- removeAllListeners(t) {
2194
- let e = super.removeAllListeners(t);
2195
- return (t === "data" || t === void 0) && (this[Y] = 0, !this[M] && !this[F].length && (this[v] = false)), e;
2196
- }
2197
- get emittedEnd() {
2198
- return this[K];
2199
- }
2200
- [H]() {
2201
- !this[kt] && !this[K] && !this[x] && this[C].length === 0 && this[G] && (this[kt] = true, this.emit("end"), this.emit("prefinish"), this.emit("finish"), this[Rt] && this.emit("close"), this[kt] = false);
2202
- }
2203
- emit(t, ...e) {
2204
- let s = e[0];
2205
- if (t !== "error" && t !== "close" && t !== x && this[x]) return false;
2206
- if (t === "data") return !this[k] && !s ? false : this[B] ? (mt(() => this[Jt](s)), true) : this[Jt](s);
2207
- if (t === "end") return this[We]();
2208
- if (t === "close") {
2209
- if (this[Rt] = true, !this[K] && !this[x]) return false;
2210
- let r = super.emit("close");
2211
- return this.removeAllListeners("close"), r;
2212
- } else if (t === "error") {
2213
- this[ut] = s, super.emit(Xt, s);
2214
- let r = !this[pt] || this.listeners("error").length ? super.emit("error", s) : false;
2215
- return this[H](), r;
2216
- } else if (t === "resume") {
2217
- let r = super.emit("resume");
2218
- return this[H](), r;
2219
- } else if (t === "finish" || t === "prefinish") {
2220
- let r = super.emit(t);
2221
- return this.removeAllListeners(t), r;
2222
- }
2223
- let i = super.emit(t, ...e);
2224
- return this[H](), i;
2225
- }
2226
- [Jt](t) {
2227
- for (let s of this[F]) s.dest.write(t) === false && this.pause();
2228
- let e = this[M] ? false : super.emit("data", t);
2229
- return this[H](), e;
2230
- }
2231
- [We]() {
2232
- return this[K] ? false : (this[K] = true, this.readable = false, this[B] ? (mt(() => this[Zt]()), true) : this[Zt]());
2233
- }
2234
- [Zt]() {
2235
- if (this[et]) {
2236
- let e = this[et].end();
2237
- if (e) {
2238
- for (let s of this[F]) s.dest.write(e);
2239
- this[M] || super.emit("data", e);
2240
- }
2241
- }
2242
- for (let e of this[F]) e.end();
2243
- let t = super.emit("end");
2244
- return this.removeAllListeners("end"), t;
2245
- }
2246
- async collect() {
2247
- let t = Object.assign([], { dataLength: 0 });
2248
- this[k] || (t.dataLength = 0);
2249
- let e = this.promise();
2250
- return this.on("data", (s) => {
2251
- t.push(s), this[k] || (t.dataLength += s.length);
2252
- }), await e, t;
2253
- }
2254
- async concat() {
2255
- if (this[k]) throw new Error("cannot concat in objectMode");
2256
- let t = await this.collect();
2257
- return this[P] ? t.join("") : Buffer.concat(t, t.dataLength);
2258
- }
2259
- async promise() {
2260
- return new Promise((t, e) => {
2261
- this.on(x, () => e(new Error("stream destroyed"))), this.on("error", (s) => e(s)), this.on("end", () => t());
2262
- });
2263
- }
2264
- [Symbol.asyncIterator]() {
2265
- this[M] = false;
2266
- let t = false, e = async () => (this.pause(), t = true, { value: void 0, done: true });
2267
- return { next: () => {
2268
- if (t) return e();
2269
- let i = this.read();
2270
- if (i !== null) return Promise.resolve({ done: false, value: i });
2271
- if (this[G]) return e();
2272
- let r, o, h = (c) => {
2273
- this.off("data", a), this.off("end", l), this.off(x, f), e(), o(c);
2274
- }, a = (c) => {
2275
- this.off("error", h), this.off("end", l), this.off(x, f), this.pause(), r({ value: c, done: !!this[G] });
2276
- }, l = () => {
2277
- this.off("error", h), this.off("data", a), this.off(x, f), e(), r({ done: true, value: void 0 });
2278
- }, f = () => h(new Error("stream destroyed"));
2279
- return new Promise((c, d) => {
2280
- o = d, r = c, this.once(x, f), this.once("error", h), this.once("end", l), this.once("data", a);
2281
- });
2282
- }, throw: e, return: e, [Symbol.asyncIterator]() {
2283
- return this;
2284
- } };
2285
- }
2286
- [Symbol.iterator]() {
2287
- this[M] = false;
2288
- let t = false, e = () => (this.pause(), this.off(Xt, e), this.off(x, e), this.off("end", e), t = true, { done: true, value: void 0 }), s = () => {
2289
- if (t) return e();
2290
- let i = this.read();
2291
- return i === null ? e() : { done: false, value: i };
2292
- };
2293
- return this.once("end", e), this.once(Xt, e), this.once(x, e), { next: s, throw: e, return: e, [Symbol.iterator]() {
2294
- return this;
2295
- } };
2296
- }
2297
- destroy(t) {
2298
- if (this[x]) return t ? this.emit("error", t) : this.emit(x), this;
2299
- this[x] = true, this[M] = true, this[C].length = 0, this[T] = 0;
2300
- let e = this;
2301
- return typeof e.close == "function" && !this[Rt] && e.close(), t ? this.emit("error", t) : this.emit(x), this;
2302
- }
2303
- static get isStream() {
2304
- return oi;
2305
- }
2306
- };
2307
- var vi = fs$1.realpathSync.native, wt = { lstatSync: fs$1.lstatSync, readdir: fs$1.readdir, readdirSync: fs$1.readdirSync, readlinkSync: fs$1.readlinkSync, realpathSync: vi, promises: { lstat: promises.lstat, readdir: promises.readdir, readlink: promises.readlink, realpath: promises.realpath } }, Ue = (n7) => !n7 || n7 === wt || n7 === xi__namespace ? wt : { ...wt, ...n7, promises: { ...wt.promises, ...n7.promises || {} } }, $e = /^\\\\\?\\([a-z]:)\\?$/i, Ri = (n7) => n7.replace(/\//g, "\\").replace($e, "$1\\"), Oi = /[\\\/]/, L = 0, Ge = 1, He = 2, U = 4, qe = 6, Ke = 8, X = 10, Ve = 12, _ = 15, gt = ~_, se = 16, je = 32, yt = 64, j = 128, Nt = 256, Lt = 512, Ie = yt | j | Lt, Fi = 1023, ie = (n7) => n7.isFile() ? Ke : n7.isDirectory() ? U : n7.isSymbolicLink() ? X : n7.isCharacterDevice() ? He : n7.isBlockDevice() ? qe : n7.isSocket() ? Ve : n7.isFIFO() ? Ge : L, ze = new ft({ max: 2 ** 12 }), bt = (n7) => {
2308
- let t = ze.get(n7);
2309
- if (t) return t;
2310
- let e = n7.normalize("NFKD");
2311
- return ze.set(n7, e), e;
2312
- }, Be = new ft({ max: 2 ** 12 }), _t = (n7) => {
2313
- let t = Be.get(n7);
2314
- if (t) return t;
2315
- let e = bt(n7.toLowerCase());
2316
- return Be.set(n7, e), e;
2317
- }, Wt = class extends ft {
2318
- constructor() {
2319
- super({ max: 256 });
2320
- }
2321
- }, ne = class extends ft {
2322
- constructor(t = 16 * 1024) {
2323
- super({ maxSize: t, sizeCalculation: (e) => e.length + 1 });
2324
- }
2325
- }, Ye = Symbol("PathScurry setAsCwd"), R = class {
2326
- name;
2327
- root;
2328
- roots;
2329
- parent;
2330
- nocase;
2331
- isCWD = false;
2332
- #t;
2333
- #s;
2334
- get dev() {
2335
- return this.#s;
2336
- }
2337
- #n;
2338
- get mode() {
2339
- return this.#n;
2340
- }
2341
- #r;
2342
- get nlink() {
2343
- return this.#r;
2344
- }
2345
- #o;
2346
- get uid() {
2347
- return this.#o;
2348
- }
2349
- #S;
2350
- get gid() {
2351
- return this.#S;
2352
- }
2353
- #w;
2354
- get rdev() {
2355
- return this.#w;
2356
- }
2357
- #c;
2358
- get blksize() {
2359
- return this.#c;
2360
- }
2361
- #h;
2362
- get ino() {
2363
- return this.#h;
2364
- }
2365
- #u;
2366
- get size() {
2367
- return this.#u;
2368
- }
2369
- #f;
2370
- get blocks() {
2371
- return this.#f;
2372
- }
2373
- #a;
2374
- get atimeMs() {
2375
- return this.#a;
2376
- }
2377
- #i;
2378
- get mtimeMs() {
2379
- return this.#i;
2380
- }
2381
- #d;
2382
- get ctimeMs() {
2383
- return this.#d;
2384
- }
2385
- #E;
2386
- get birthtimeMs() {
2387
- return this.#E;
2388
- }
2389
- #b;
2390
- get atime() {
2391
- return this.#b;
2392
- }
2393
- #p;
2394
- get mtime() {
2395
- return this.#p;
2396
- }
2397
- #R;
2398
- get ctime() {
2399
- return this.#R;
2400
- }
2401
- #m;
2402
- get birthtime() {
2403
- return this.#m;
2404
- }
2405
- #C;
2406
- #T;
2407
- #g;
2408
- #y;
2409
- #x;
2410
- #A;
2411
- #e;
2412
- #_;
2413
- #M;
2414
- #k;
2415
- get parentPath() {
2416
- return (this.parent || this).fullpath();
2417
- }
2418
- get path() {
2419
- return this.parentPath;
2420
- }
2421
- constructor(t, e = L, s, i, r, o, h) {
2422
- this.name = t, this.#C = r ? _t(t) : bt(t), this.#e = e & Fi, this.nocase = r, this.roots = i, this.root = s || this, this.#_ = o, this.#g = h.fullpath, this.#x = h.relative, this.#A = h.relativePosix, this.parent = h.parent, this.parent ? this.#t = this.parent.#t : this.#t = Ue(h.fs);
2423
- }
2424
- depth() {
2425
- return this.#T !== void 0 ? this.#T : this.parent ? this.#T = this.parent.depth() + 1 : this.#T = 0;
2426
- }
2427
- childrenCache() {
2428
- return this.#_;
2429
- }
2430
- resolve(t) {
2431
- if (!t) return this;
2432
- let e = this.getRootString(t), i = t.substring(e.length).split(this.splitSep);
2433
- return e ? this.getRoot(e).#N(i) : this.#N(i);
2434
- }
2435
- #N(t) {
2436
- let e = this;
2437
- for (let s of t) e = e.child(s);
2438
- return e;
2439
- }
2440
- children() {
2441
- let t = this.#_.get(this);
2442
- if (t) return t;
2443
- let e = Object.assign([], { provisional: 0 });
2444
- return this.#_.set(this, e), this.#e &= ~se, e;
2445
- }
2446
- child(t, e) {
2447
- if (t === "" || t === ".") return this;
2448
- if (t === "..") return this.parent || this;
2449
- let s = this.children(), i = this.nocase ? _t(t) : bt(t);
2450
- for (let a of s) if (a.#C === i) return a;
2451
- let r = this.parent ? this.sep : "", o = this.#g ? this.#g + r + t : void 0, h = this.newChild(t, L, { ...e, parent: this, fullpath: o });
2452
- return this.canReaddir() || (h.#e |= j), s.push(h), h;
2453
- }
2454
- relative() {
2455
- if (this.isCWD) return "";
2456
- if (this.#x !== void 0) return this.#x;
2457
- let t = this.name, e = this.parent;
2458
- if (!e) return this.#x = this.name;
2459
- let s = e.relative();
2460
- return s + (!s || !e.parent ? "" : this.sep) + t;
2461
- }
2462
- relativePosix() {
2463
- if (this.sep === "/") return this.relative();
2464
- if (this.isCWD) return "";
2465
- if (this.#A !== void 0) return this.#A;
2466
- let t = this.name, e = this.parent;
2467
- if (!e) return this.#A = this.fullpathPosix();
2468
- let s = e.relativePosix();
2469
- return s + (!s || !e.parent ? "" : "/") + t;
2470
- }
2471
- fullpath() {
2472
- if (this.#g !== void 0) return this.#g;
2473
- let t = this.name, e = this.parent;
2474
- if (!e) return this.#g = this.name;
2475
- let i = e.fullpath() + (e.parent ? this.sep : "") + t;
2476
- return this.#g = i;
2477
- }
2478
- fullpathPosix() {
2479
- if (this.#y !== void 0) return this.#y;
2480
- if (this.sep === "/") return this.#y = this.fullpath();
2481
- if (!this.parent) {
2482
- let i = this.fullpath().replace(/\\/g, "/");
2483
- return /^[a-z]:\//i.test(i) ? this.#y = `//?/${i}` : this.#y = i;
2484
- }
2485
- let t = this.parent, e = t.fullpathPosix(), s = e + (!e || !t.parent ? "" : "/") + this.name;
2486
- return this.#y = s;
2487
- }
2488
- isUnknown() {
2489
- return (this.#e & _) === L;
2490
- }
2491
- isType(t) {
2492
- return this[`is${t}`]();
2493
- }
2494
- getType() {
2495
- return this.isUnknown() ? "Unknown" : this.isDirectory() ? "Directory" : this.isFile() ? "File" : this.isSymbolicLink() ? "SymbolicLink" : this.isFIFO() ? "FIFO" : this.isCharacterDevice() ? "CharacterDevice" : this.isBlockDevice() ? "BlockDevice" : this.isSocket() ? "Socket" : "Unknown";
2496
- }
2497
- isFile() {
2498
- return (this.#e & _) === Ke;
2499
- }
2500
- isDirectory() {
2501
- return (this.#e & _) === U;
2502
- }
2503
- isCharacterDevice() {
2504
- return (this.#e & _) === He;
2505
- }
2506
- isBlockDevice() {
2507
- return (this.#e & _) === qe;
2508
- }
2509
- isFIFO() {
2510
- return (this.#e & _) === Ge;
2511
- }
2512
- isSocket() {
2513
- return (this.#e & _) === Ve;
2514
- }
2515
- isSymbolicLink() {
2516
- return (this.#e & X) === X;
2517
- }
2518
- lstatCached() {
2519
- return this.#e & je ? this : void 0;
2520
- }
2521
- readlinkCached() {
2522
- return this.#M;
2523
- }
2524
- realpathCached() {
2525
- return this.#k;
2526
- }
2527
- readdirCached() {
2528
- let t = this.children();
2529
- return t.slice(0, t.provisional);
2530
- }
2531
- canReadlink() {
2532
- if (this.#M) return true;
2533
- if (!this.parent) return false;
2534
- let t = this.#e & _;
2535
- return !(t !== L && t !== X || this.#e & Nt || this.#e & j);
2536
- }
2537
- calledReaddir() {
2538
- return !!(this.#e & se);
2539
- }
2540
- isENOENT() {
2541
- return !!(this.#e & j);
2542
- }
2543
- isNamed(t) {
2544
- return this.nocase ? this.#C === _t(t) : this.#C === bt(t);
2545
- }
2546
- async readlink() {
2547
- let t = this.#M;
2548
- if (t) return t;
2549
- if (this.canReadlink() && this.parent) try {
2550
- let e = await this.#t.promises.readlink(this.fullpath()), s = (await this.parent.realpath())?.resolve(e);
2551
- if (s) return this.#M = s;
2552
- } catch (e) {
2553
- this.#D(e.code);
2554
- return;
2555
- }
2556
- }
2557
- readlinkSync() {
2558
- let t = this.#M;
2559
- if (t) return t;
2560
- if (this.canReadlink() && this.parent) try {
2561
- let e = this.#t.readlinkSync(this.fullpath()), s = this.parent.realpathSync()?.resolve(e);
2562
- if (s) return this.#M = s;
2563
- } catch (e) {
2564
- this.#D(e.code);
2565
- return;
2566
- }
2567
- }
2568
- #j(t) {
2569
- this.#e |= se;
2570
- for (let e = t.provisional; e < t.length; e++) {
2571
- let s = t[e];
2572
- s && s.#v();
2573
- }
2574
- }
2575
- #v() {
2576
- this.#e & j || (this.#e = (this.#e | j) & gt, this.#G());
2577
- }
2578
- #G() {
2579
- let t = this.children();
2580
- t.provisional = 0;
2581
- for (let e of t) e.#v();
2582
- }
2583
- #P() {
2584
- this.#e |= Lt, this.#L();
2585
- }
2586
- #L() {
2587
- if (this.#e & yt) return;
2588
- let t = this.#e;
2589
- (t & _) === U && (t &= gt), this.#e = t | yt, this.#G();
2590
- }
2591
- #I(t = "") {
2592
- t === "ENOTDIR" || t === "EPERM" ? this.#L() : t === "ENOENT" ? this.#v() : this.children().provisional = 0;
2593
- }
2594
- #F(t = "") {
2595
- t === "ENOTDIR" ? this.parent.#L() : t === "ENOENT" && this.#v();
2596
- }
2597
- #D(t = "") {
2598
- let e = this.#e;
2599
- e |= Nt, t === "ENOENT" && (e |= j), (t === "EINVAL" || t === "UNKNOWN") && (e &= gt), this.#e = e, t === "ENOTDIR" && this.parent && this.parent.#L();
2600
- }
2601
- #z(t, e) {
2602
- return this.#U(t, e) || this.#B(t, e);
2603
- }
2604
- #B(t, e) {
2605
- let s = ie(t), i = this.newChild(t.name, s, { parent: this }), r = i.#e & _;
2606
- return r !== U && r !== X && r !== L && (i.#e |= yt), e.unshift(i), e.provisional++, i;
2607
- }
2608
- #U(t, e) {
2609
- for (let s = e.provisional; s < e.length; s++) {
2610
- let i = e[s];
2611
- if ((this.nocase ? _t(t.name) : bt(t.name)) === i.#C) return this.#l(t, i, s, e);
2612
- }
2613
- }
2614
- #l(t, e, s, i) {
2615
- let r = e.name;
2616
- return e.#e = e.#e & gt | ie(t), r !== t.name && (e.name = t.name), s !== i.provisional && (s === i.length - 1 ? i.pop() : i.splice(s, 1), i.unshift(e)), i.provisional++, e;
2617
- }
2618
- async lstat() {
2619
- if ((this.#e & j) === 0) try {
2620
- return this.#$(await this.#t.promises.lstat(this.fullpath())), this;
2621
- } catch (t) {
2622
- this.#F(t.code);
2623
- }
2624
- }
2625
- lstatSync() {
2626
- if ((this.#e & j) === 0) try {
2627
- return this.#$(this.#t.lstatSync(this.fullpath())), this;
2628
- } catch (t) {
2629
- this.#F(t.code);
2630
- }
2631
- }
2632
- #$(t) {
2633
- let { atime: e, atimeMs: s, birthtime: i, birthtimeMs: r, blksize: o, blocks: h, ctime: a, ctimeMs: l, dev: f, gid: c, ino: d, mode: u, mtime: m, mtimeMs: p, nlink: w, rdev: g, size: S, uid: E } = t;
2634
- this.#b = e, this.#a = s, this.#m = i, this.#E = r, this.#c = o, this.#f = h, this.#R = a, this.#d = l, this.#s = f, this.#S = c, this.#h = d, this.#n = u, this.#p = m, this.#i = p, this.#r = w, this.#w = g, this.#u = S, this.#o = E;
2635
- let y = ie(t);
2636
- this.#e = this.#e & gt | y | je, y !== L && y !== U && y !== X && (this.#e |= yt);
2637
- }
2638
- #W = [];
2639
- #O = false;
2640
- #H(t) {
2641
- this.#O = false;
2642
- let e = this.#W.slice();
2643
- this.#W.length = 0, e.forEach((s) => s(null, t));
2644
- }
2645
- readdirCB(t, e = false) {
2646
- if (!this.canReaddir()) {
2647
- e ? t(null, []) : queueMicrotask(() => t(null, []));
2648
- return;
2649
- }
2650
- let s = this.children();
2651
- if (this.calledReaddir()) {
2652
- let r = s.slice(0, s.provisional);
2653
- e ? t(null, r) : queueMicrotask(() => t(null, r));
2654
- return;
2655
- }
2656
- if (this.#W.push(t), this.#O) return;
2657
- this.#O = true;
2658
- let i = this.fullpath();
2659
- this.#t.readdir(i, { withFileTypes: true }, (r, o) => {
2660
- if (r) this.#I(r.code), s.provisional = 0;
2661
- else {
2662
- for (let h of o) this.#z(h, s);
2663
- this.#j(s);
2664
- }
2665
- this.#H(s.slice(0, s.provisional));
2666
- });
2667
- }
2668
- #q;
2669
- async readdir() {
2670
- if (!this.canReaddir()) return [];
2671
- let t = this.children();
2672
- if (this.calledReaddir()) return t.slice(0, t.provisional);
2673
- let e = this.fullpath();
2674
- if (this.#q) await this.#q;
2675
- else {
2676
- let s = () => {
2677
- };
2678
- this.#q = new Promise((i) => s = i);
2679
- try {
2680
- for (let i of await this.#t.promises.readdir(e, { withFileTypes: true })) this.#z(i, t);
2681
- this.#j(t);
2682
- } catch (i) {
2683
- this.#I(i.code), t.provisional = 0;
2684
- }
2685
- this.#q = void 0, s();
2686
- }
2687
- return t.slice(0, t.provisional);
2688
- }
2689
- readdirSync() {
2690
- if (!this.canReaddir()) return [];
2691
- let t = this.children();
2692
- if (this.calledReaddir()) return t.slice(0, t.provisional);
2693
- let e = this.fullpath();
2694
- try {
2695
- for (let s of this.#t.readdirSync(e, { withFileTypes: true })) this.#z(s, t);
2696
- this.#j(t);
2697
- } catch (s) {
2698
- this.#I(s.code), t.provisional = 0;
2699
- }
2700
- return t.slice(0, t.provisional);
2701
- }
2702
- canReaddir() {
2703
- if (this.#e & Ie) return false;
2704
- let t = _ & this.#e;
2705
- return t === L || t === U || t === X;
2706
- }
2707
- shouldWalk(t, e) {
2708
- return (this.#e & U) === U && !(this.#e & Ie) && !t.has(this) && (!e || e(this));
2709
- }
2710
- async realpath() {
2711
- if (this.#k) return this.#k;
2712
- if (!((Lt | Nt | j) & this.#e)) try {
2713
- let t = await this.#t.promises.realpath(this.fullpath());
2714
- return this.#k = this.resolve(t);
2715
- } catch {
2716
- this.#P();
2717
- }
2718
- }
2719
- realpathSync() {
2720
- if (this.#k) return this.#k;
2721
- if (!((Lt | Nt | j) & this.#e)) try {
2722
- let t = this.#t.realpathSync(this.fullpath());
2723
- return this.#k = this.resolve(t);
2724
- } catch {
2725
- this.#P();
2726
- }
2727
- }
2728
- [Ye](t) {
2729
- if (t === this) return;
2730
- t.isCWD = false, this.isCWD = true;
2731
- let e = /* @__PURE__ */ new Set([]), s = [], i = this;
2732
- for (; i && i.parent; ) e.add(i), i.#x = s.join(this.sep), i.#A = s.join("/"), i = i.parent, s.push("..");
2733
- for (i = t; i && i.parent && !e.has(i); ) i.#x = void 0, i.#A = void 0, i = i.parent;
2734
- }
2735
- }, Pt = class n2 extends R {
2736
- sep = "\\";
2737
- splitSep = Oi;
2738
- constructor(t, e = L, s, i, r, o, h) {
2739
- super(t, e, s, i, r, o, h);
2740
- }
2741
- newChild(t, e = L, s = {}) {
2742
- return new n2(t, e, this.root, this.roots, this.nocase, this.childrenCache(), s);
2743
- }
2744
- getRootString(t) {
2745
- return node_path.win32.parse(t).root;
2746
- }
2747
- getRoot(t) {
2748
- if (t = Ri(t.toUpperCase()), t === this.root.name) return this.root;
2749
- for (let [e, s] of Object.entries(this.roots)) if (this.sameRoot(t, e)) return this.roots[t] = s;
2750
- return this.roots[t] = new it(t, this).root;
2751
- }
2752
- sameRoot(t, e = this.root.name) {
2753
- return t = t.toUpperCase().replace(/\//g, "\\").replace($e, "$1\\"), t === e;
2754
- }
2755
- }, jt = class n3 extends R {
2756
- splitSep = "/";
2757
- sep = "/";
2758
- constructor(t, e = L, s, i, r, o, h) {
2759
- super(t, e, s, i, r, o, h);
2760
- }
2761
- getRootString(t) {
2762
- return t.startsWith("/") ? "/" : "";
2763
- }
2764
- getRoot(t) {
2765
- return this.root;
2766
- }
2767
- newChild(t, e = L, s = {}) {
2768
- return new n3(t, e, this.root, this.roots, this.nocase, this.childrenCache(), s);
2769
- }
2770
- }, It = class {
2771
- root;
2772
- rootPath;
2773
- roots;
2774
- cwd;
2775
- #t;
2776
- #s;
2777
- #n;
2778
- nocase;
2779
- #r;
2780
- constructor(t = process.cwd(), e, s, { nocase: i, childrenCacheSize: r = 16 * 1024, fs: o = wt } = {}) {
2781
- this.#r = Ue(o), (t instanceof URL || t.startsWith("file://")) && (t = node_url.fileURLToPath(t));
2782
- let h = e.resolve(t);
2783
- this.roots = /* @__PURE__ */ Object.create(null), this.rootPath = this.parseRootPath(h), this.#t = new Wt(), this.#s = new Wt(), this.#n = new ne(r);
2784
- let a = h.substring(this.rootPath.length).split(s);
2785
- if (a.length === 1 && !a[0] && a.pop(), i === void 0) throw new TypeError("must provide nocase setting to PathScurryBase ctor");
2786
- this.nocase = i, this.root = this.newRoot(this.#r), this.roots[this.rootPath] = this.root;
2787
- let l = this.root, f = a.length - 1, c = e.sep, d = this.rootPath, u = false;
2788
- for (let m of a) {
2789
- let p = f--;
2790
- l = l.child(m, { relative: new Array(p).fill("..").join(c), relativePosix: new Array(p).fill("..").join("/"), fullpath: d += (u ? "" : c) + m }), u = true;
2791
- }
2792
- this.cwd = l;
2793
- }
2794
- depth(t = this.cwd) {
2795
- return typeof t == "string" && (t = this.cwd.resolve(t)), t.depth();
2796
- }
2797
- childrenCache() {
2798
- return this.#n;
2799
- }
2800
- resolve(...t) {
2801
- let e = "";
2802
- for (let r = t.length - 1; r >= 0; r--) {
2803
- let o = t[r];
2804
- if (!(!o || o === ".") && (e = e ? `${o}/${e}` : o, this.isAbsolute(o))) break;
2805
- }
2806
- let s = this.#t.get(e);
2807
- if (s !== void 0) return s;
2808
- let i = this.cwd.resolve(e).fullpath();
2809
- return this.#t.set(e, i), i;
2810
- }
2811
- resolvePosix(...t) {
2812
- let e = "";
2813
- for (let r = t.length - 1; r >= 0; r--) {
2814
- let o = t[r];
2815
- if (!(!o || o === ".") && (e = e ? `${o}/${e}` : o, this.isAbsolute(o))) break;
2816
- }
2817
- let s = this.#s.get(e);
2818
- if (s !== void 0) return s;
2819
- let i = this.cwd.resolve(e).fullpathPosix();
2820
- return this.#s.set(e, i), i;
2821
- }
2822
- relative(t = this.cwd) {
2823
- return typeof t == "string" && (t = this.cwd.resolve(t)), t.relative();
2824
- }
2825
- relativePosix(t = this.cwd) {
2826
- return typeof t == "string" && (t = this.cwd.resolve(t)), t.relativePosix();
2827
- }
2828
- basename(t = this.cwd) {
2829
- return typeof t == "string" && (t = this.cwd.resolve(t)), t.name;
2830
- }
2831
- dirname(t = this.cwd) {
2832
- return typeof t == "string" && (t = this.cwd.resolve(t)), (t.parent || t).fullpath();
2833
- }
2834
- async readdir(t = this.cwd, e = { withFileTypes: true }) {
2835
- typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t, t = this.cwd);
2836
- let { withFileTypes: s } = e;
2837
- if (t.canReaddir()) {
2838
- let i = await t.readdir();
2839
- return s ? i : i.map((r) => r.name);
2840
- } else return [];
2841
- }
2842
- readdirSync(t = this.cwd, e = { withFileTypes: true }) {
2843
- typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t, t = this.cwd);
2844
- let { withFileTypes: s = true } = e;
2845
- return t.canReaddir() ? s ? t.readdirSync() : t.readdirSync().map((i) => i.name) : [];
2846
- }
2847
- async lstat(t = this.cwd) {
2848
- return typeof t == "string" && (t = this.cwd.resolve(t)), t.lstat();
2849
- }
2850
- lstatSync(t = this.cwd) {
2851
- return typeof t == "string" && (t = this.cwd.resolve(t)), t.lstatSync();
2852
- }
2853
- async readlink(t = this.cwd, { withFileTypes: e } = { withFileTypes: false }) {
2854
- typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t.withFileTypes, t = this.cwd);
2855
- let s = await t.readlink();
2856
- return e ? s : s?.fullpath();
2857
- }
2858
- readlinkSync(t = this.cwd, { withFileTypes: e } = { withFileTypes: false }) {
2859
- typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t.withFileTypes, t = this.cwd);
2860
- let s = t.readlinkSync();
2861
- return e ? s : s?.fullpath();
2862
- }
2863
- async realpath(t = this.cwd, { withFileTypes: e } = { withFileTypes: false }) {
2864
- typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t.withFileTypes, t = this.cwd);
2865
- let s = await t.realpath();
2866
- return e ? s : s?.fullpath();
2867
- }
2868
- realpathSync(t = this.cwd, { withFileTypes: e } = { withFileTypes: false }) {
2869
- typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t.withFileTypes, t = this.cwd);
2870
- let s = t.realpathSync();
2871
- return e ? s : s?.fullpath();
2872
- }
2873
- async walk(t = this.cwd, e = {}) {
2874
- typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t, t = this.cwd);
2875
- let { withFileTypes: s = true, follow: i = false, filter: r, walkFilter: o } = e, h = [];
2876
- (!r || r(t)) && h.push(s ? t : t.fullpath());
2877
- let a = /* @__PURE__ */ new Set(), l = (c, d) => {
2878
- a.add(c), c.readdirCB((u, m) => {
2879
- if (u) return d(u);
2880
- let p = m.length;
2881
- if (!p) return d();
2882
- let w = () => {
2883
- --p === 0 && d();
2884
- };
2885
- for (let g of m) (!r || r(g)) && h.push(s ? g : g.fullpath()), i && g.isSymbolicLink() ? g.realpath().then((S) => S?.isUnknown() ? S.lstat() : S).then((S) => S?.shouldWalk(a, o) ? l(S, w) : w()) : g.shouldWalk(a, o) ? l(g, w) : w();
2886
- }, true);
2887
- }, f = t;
2888
- return new Promise((c, d) => {
2889
- l(f, (u) => {
2890
- if (u) return d(u);
2891
- c(h);
2892
- });
2893
- });
2894
- }
2895
- walkSync(t = this.cwd, e = {}) {
2896
- typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t, t = this.cwd);
2897
- let { withFileTypes: s = true, follow: i = false, filter: r, walkFilter: o } = e, h = [];
2898
- (!r || r(t)) && h.push(s ? t : t.fullpath());
2899
- let a = /* @__PURE__ */ new Set([t]);
2900
- for (let l of a) {
2901
- let f = l.readdirSync();
2902
- for (let c of f) {
2903
- (!r || r(c)) && h.push(s ? c : c.fullpath());
2904
- let d = c;
2905
- if (c.isSymbolicLink()) {
2906
- if (!(i && (d = c.realpathSync()))) continue;
2907
- d.isUnknown() && d.lstatSync();
2908
- }
2909
- d.shouldWalk(a, o) && a.add(d);
2910
- }
2911
- }
2912
- return h;
2913
- }
2914
- [Symbol.asyncIterator]() {
2915
- return this.iterate();
2916
- }
2917
- iterate(t = this.cwd, e = {}) {
2918
- return typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t, t = this.cwd), this.stream(t, e)[Symbol.asyncIterator]();
2919
- }
2920
- [Symbol.iterator]() {
2921
- return this.iterateSync();
2922
- }
2923
- *iterateSync(t = this.cwd, e = {}) {
2924
- typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t, t = this.cwd);
2925
- let { withFileTypes: s = true, follow: i = false, filter: r, walkFilter: o } = e;
2926
- (!r || r(t)) && (yield s ? t : t.fullpath());
2927
- let h = /* @__PURE__ */ new Set([t]);
2928
- for (let a of h) {
2929
- let l = a.readdirSync();
2930
- for (let f of l) {
2931
- (!r || r(f)) && (yield s ? f : f.fullpath());
2932
- let c = f;
2933
- if (f.isSymbolicLink()) {
2934
- if (!(i && (c = f.realpathSync()))) continue;
2935
- c.isUnknown() && c.lstatSync();
2936
- }
2937
- c.shouldWalk(h, o) && h.add(c);
2938
- }
2939
- }
2940
- }
2941
- stream(t = this.cwd, e = {}) {
2942
- typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t, t = this.cwd);
2943
- let { withFileTypes: s = true, follow: i = false, filter: r, walkFilter: o } = e, h = new V({ objectMode: true });
2944
- (!r || r(t)) && h.write(s ? t : t.fullpath());
2945
- let a = /* @__PURE__ */ new Set(), l = [t], f = 0, c = () => {
2946
- let d = false;
2947
- for (; !d; ) {
2948
- let u = l.shift();
2949
- if (!u) {
2950
- f === 0 && h.end();
2951
- return;
2952
- }
2953
- f++, a.add(u);
2954
- let m = (w, g, S = false) => {
2955
- if (w) return h.emit("error", w);
2956
- if (i && !S) {
2957
- let E = [];
2958
- for (let y of g) y.isSymbolicLink() && E.push(y.realpath().then((b) => b?.isUnknown() ? b.lstat() : b));
2959
- if (E.length) {
2960
- Promise.all(E).then(() => m(null, g, true));
2961
- return;
2962
- }
2963
- }
2964
- for (let E of g) E && (!r || r(E)) && (h.write(s ? E : E.fullpath()) || (d = true));
2965
- f--;
2966
- for (let E of g) {
2967
- let y = E.realpathCached() || E;
2968
- y.shouldWalk(a, o) && l.push(y);
2969
- }
2970
- d && !h.flowing ? h.once("drain", c) : p || c();
2971
- }, p = true;
2972
- u.readdirCB(m, true), p = false;
2973
- }
2974
- };
2975
- return c(), h;
2976
- }
2977
- streamSync(t = this.cwd, e = {}) {
2978
- typeof t == "string" ? t = this.cwd.resolve(t) : t instanceof R || (e = t, t = this.cwd);
2979
- let { withFileTypes: s = true, follow: i = false, filter: r, walkFilter: o } = e, h = new V({ objectMode: true }), a = /* @__PURE__ */ new Set();
2980
- (!r || r(t)) && h.write(s ? t : t.fullpath());
2981
- let l = [t], f = 0, c = () => {
2982
- let d = false;
2983
- for (; !d; ) {
2984
- let u = l.shift();
2985
- if (!u) {
2986
- f === 0 && h.end();
2987
- return;
2988
- }
2989
- f++, a.add(u);
2990
- let m = u.readdirSync();
2991
- for (let p of m) (!r || r(p)) && (h.write(s ? p : p.fullpath()) || (d = true));
2992
- f--;
2993
- for (let p of m) {
2994
- let w = p;
2995
- if (p.isSymbolicLink()) {
2996
- if (!(i && (w = p.realpathSync()))) continue;
2997
- w.isUnknown() && w.lstatSync();
2998
- }
2999
- w.shouldWalk(a, o) && l.push(w);
3000
- }
3001
- }
3002
- d && !h.flowing && h.once("drain", c);
3003
- };
3004
- return c(), h;
3005
- }
3006
- chdir(t = this.cwd) {
3007
- let e = this.cwd;
3008
- this.cwd = typeof t == "string" ? this.cwd.resolve(t) : t, this.cwd[Ye](e);
3009
- }
3010
- }, it = class extends It {
3011
- sep = "\\";
3012
- constructor(t = process.cwd(), e = {}) {
3013
- let { nocase: s = true } = e;
3014
- super(t, node_path.win32, "\\", { ...e, nocase: s }), this.nocase = s;
3015
- for (let i = this.cwd; i; i = i.parent) i.nocase = this.nocase;
3016
- }
3017
- parseRootPath(t) {
3018
- return node_path.win32.parse(t).root.toUpperCase();
3019
- }
3020
- newRoot(t) {
3021
- return new Pt(this.rootPath, U, void 0, this.roots, this.nocase, this.childrenCache(), { fs: t });
3022
- }
3023
- isAbsolute(t) {
3024
- return t.startsWith("/") || t.startsWith("\\") || /^[a-z]:(\/|\\)/i.test(t);
3025
- }
3026
- }, rt = class extends It {
3027
- sep = "/";
3028
- constructor(t = process.cwd(), e = {}) {
3029
- let { nocase: s = false } = e;
3030
- super(t, node_path.posix, "/", { ...e, nocase: s }), this.nocase = s;
3031
- }
3032
- parseRootPath(t) {
3033
- return "/";
3034
- }
3035
- newRoot(t) {
3036
- return new jt(this.rootPath, U, void 0, this.roots, this.nocase, this.childrenCache(), { fs: t });
3037
- }
3038
- isAbsolute(t) {
3039
- return t.startsWith("/");
3040
- }
3041
- }, St = class extends rt {
3042
- constructor(t = process.cwd(), e = {}) {
3043
- let { nocase: s = true } = e;
3044
- super(t, { ...e, nocase: s });
3045
- }
3046
- }; process.platform === "win32" ? Pt : jt; var Xe = process.platform === "win32" ? it : process.platform === "darwin" ? St : rt;
3047
- var Di = (n7) => n7.length >= 1, Mi = (n7) => n7.length >= 1, nt = class n4 {
3048
- #t;
3049
- #s;
3050
- #n;
3051
- length;
3052
- #r;
3053
- #o;
3054
- #S;
3055
- #w;
3056
- #c;
3057
- #h;
3058
- #u = true;
3059
- constructor(t, e, s, i) {
3060
- if (!Di(t)) throw new TypeError("empty pattern list");
3061
- if (!Mi(e)) throw new TypeError("empty glob list");
3062
- if (e.length !== t.length) throw new TypeError("mismatched pattern list and glob list lengths");
3063
- if (this.length = t.length, s < 0 || s >= this.length) throw new TypeError("index out of range");
3064
- if (this.#t = t, this.#s = e, this.#n = s, this.#r = i, this.#n === 0) {
3065
- if (this.isUNC()) {
3066
- let [r, o, h, a, ...l] = this.#t, [f, c, d, u, ...m] = this.#s;
3067
- l[0] === "" && (l.shift(), m.shift());
3068
- let p = [r, o, h, a, ""].join("/"), w = [f, c, d, u, ""].join("/");
3069
- this.#t = [p, ...l], this.#s = [w, ...m], this.length = this.#t.length;
3070
- } else if (this.isDrive() || this.isAbsolute()) {
3071
- let [r, ...o] = this.#t, [h, ...a] = this.#s;
3072
- o[0] === "" && (o.shift(), a.shift());
3073
- let l = r + "/", f = h + "/";
3074
- this.#t = [l, ...o], this.#s = [f, ...a], this.length = this.#t.length;
3075
- }
3076
- }
3077
- }
3078
- pattern() {
3079
- return this.#t[this.#n];
3080
- }
3081
- isString() {
3082
- return typeof this.#t[this.#n] == "string";
3083
- }
3084
- isGlobstar() {
3085
- return this.#t[this.#n] === A;
3086
- }
3087
- isRegExp() {
3088
- return this.#t[this.#n] instanceof RegExp;
3089
- }
3090
- globString() {
3091
- return this.#S = this.#S || (this.#n === 0 ? this.isAbsolute() ? this.#s[0] + this.#s.slice(1).join("/") : this.#s.join("/") : this.#s.slice(this.#n).join("/"));
3092
- }
3093
- hasMore() {
3094
- return this.length > this.#n + 1;
3095
- }
3096
- rest() {
3097
- return this.#o !== void 0 ? this.#o : this.hasMore() ? (this.#o = new n4(this.#t, this.#s, this.#n + 1, this.#r), this.#o.#h = this.#h, this.#o.#c = this.#c, this.#o.#w = this.#w, this.#o) : this.#o = null;
3098
- }
3099
- isUNC() {
3100
- let t = this.#t;
3101
- return this.#c !== void 0 ? this.#c : this.#c = this.#r === "win32" && this.#n === 0 && t[0] === "" && t[1] === "" && typeof t[2] == "string" && !!t[2] && typeof t[3] == "string" && !!t[3];
3102
- }
3103
- isDrive() {
3104
- let t = this.#t;
3105
- return this.#w !== void 0 ? this.#w : this.#w = this.#r === "win32" && this.#n === 0 && this.length > 1 && typeof t[0] == "string" && /^[a-z]:$/i.test(t[0]);
3106
- }
3107
- isAbsolute() {
3108
- let t = this.#t;
3109
- return this.#h !== void 0 ? this.#h : this.#h = t[0] === "" && t.length > 1 || this.isDrive() || this.isUNC();
3110
- }
3111
- root() {
3112
- let t = this.#t[0];
3113
- return typeof t == "string" && this.isAbsolute() && this.#n === 0 ? t : "";
3114
- }
3115
- checkFollowGlobstar() {
3116
- return !(this.#n === 0 || !this.isGlobstar() || !this.#u);
3117
- }
3118
- markFollowGlobstar() {
3119
- return this.#n === 0 || !this.isGlobstar() || !this.#u ? false : (this.#u = false, true);
3120
- }
3121
- };
3122
- var Ni = typeof process == "object" && process && typeof process.platform == "string" ? process.platform : "linux", ot = class {
3123
- relative;
3124
- relativeChildren;
3125
- absolute;
3126
- absoluteChildren;
3127
- platform;
3128
- mmopts;
3129
- constructor(t, { nobrace: e, nocase: s, noext: i, noglobstar: r, platform: o = Ni }) {
3130
- this.relative = [], this.absolute = [], this.relativeChildren = [], this.absoluteChildren = [], this.platform = o, this.mmopts = { dot: true, nobrace: e, nocase: s, noext: i, noglobstar: r, optimizationLevel: 2, platform: o, nocomment: true, nonegate: true };
3131
- for (let h of t) this.add(h);
3132
- }
3133
- add(t) {
3134
- let e = new D(t, this.mmopts);
3135
- for (let s = 0; s < e.set.length; s++) {
3136
- let i = e.set[s], r = e.globParts[s];
3137
- if (!i || !r) throw new Error("invalid pattern object");
3138
- for (; i[0] === "." && r[0] === "."; ) i.shift(), r.shift();
3139
- let o = new nt(i, r, 0, this.platform), h = new D(o.globString(), this.mmopts), a = r[r.length - 1] === "**", l = o.isAbsolute();
3140
- l ? this.absolute.push(h) : this.relative.push(h), a && (l ? this.absoluteChildren.push(h) : this.relativeChildren.push(h));
3141
- }
3142
- }
3143
- ignored(t) {
3144
- let e = t.fullpath(), s = `${e}/`, i = t.relative() || ".", r = `${i}/`;
3145
- for (let o of this.relative) if (o.match(i) || o.match(r)) return true;
3146
- for (let o of this.absolute) if (o.match(e) || o.match(s)) return true;
3147
- return false;
3148
- }
3149
- childrenIgnored(t) {
3150
- let e = t.fullpath() + "/", s = (t.relative() || ".") + "/";
3151
- for (let i of this.relativeChildren) if (i.match(s)) return true;
3152
- for (let i of this.absoluteChildren) if (i.match(e)) return true;
3153
- return false;
3154
- }
3155
- };
3156
- var oe = class n5 {
3157
- store;
3158
- constructor(t = /* @__PURE__ */ new Map()) {
3159
- this.store = t;
3160
- }
3161
- copy() {
3162
- return new n5(new Map(this.store));
3163
- }
3164
- hasWalked(t, e) {
3165
- return this.store.get(t.fullpath())?.has(e.globString());
3166
- }
3167
- storeWalked(t, e) {
3168
- let s = t.fullpath(), i = this.store.get(s);
3169
- i ? i.add(e.globString()) : this.store.set(s, /* @__PURE__ */ new Set([e.globString()]));
3170
- }
3171
- }, he = class {
3172
- store = /* @__PURE__ */ new Map();
3173
- add(t, e, s) {
3174
- let i = (e ? 2 : 0) | (s ? 1 : 0), r = this.store.get(t);
3175
- this.store.set(t, r === void 0 ? i : i & r);
3176
- }
3177
- entries() {
3178
- return [...this.store.entries()].map(([t, e]) => [t, !!(e & 2), !!(e & 1)]);
3179
- }
3180
- }, ae = class {
3181
- store = /* @__PURE__ */ new Map();
3182
- add(t, e) {
3183
- if (!t.canReaddir()) return;
3184
- let s = this.store.get(t);
3185
- s ? s.find((i) => i.globString() === e.globString()) || s.push(e) : this.store.set(t, [e]);
3186
- }
3187
- get(t) {
3188
- let e = this.store.get(t);
3189
- if (!e) throw new Error("attempting to walk unknown path");
3190
- return e;
3191
- }
3192
- entries() {
3193
- return this.keys().map((t) => [t, this.store.get(t)]);
3194
- }
3195
- keys() {
3196
- return [...this.store.keys()].filter((t) => t.canReaddir());
3197
- }
3198
- }, Et = class n6 {
3199
- hasWalkedCache;
3200
- matches = new he();
3201
- subwalks = new ae();
3202
- patterns;
3203
- follow;
3204
- dot;
3205
- opts;
3206
- constructor(t, e) {
3207
- this.opts = t, this.follow = !!t.follow, this.dot = !!t.dot, this.hasWalkedCache = e ? e.copy() : new oe();
3208
- }
3209
- processPatterns(t, e) {
3210
- this.patterns = e;
3211
- let s = e.map((i) => [t, i]);
3212
- for (let [i, r] of s) {
3213
- this.hasWalkedCache.storeWalked(i, r);
3214
- let o = r.root(), h = r.isAbsolute() && this.opts.absolute !== false;
3215
- if (o) {
3216
- i = i.resolve(o === "/" && this.opts.root !== void 0 ? this.opts.root : o);
3217
- let c = r.rest();
3218
- if (c) r = c;
3219
- else {
3220
- this.matches.add(i, true, false);
3221
- continue;
3222
- }
3223
- }
3224
- if (i.isENOENT()) continue;
3225
- let a, l, f = false;
3226
- for (; typeof (a = r.pattern()) == "string" && (l = r.rest()); ) i = i.resolve(a), r = l, f = true;
3227
- if (a = r.pattern(), l = r.rest(), f) {
3228
- if (this.hasWalkedCache.hasWalked(i, r)) continue;
3229
- this.hasWalkedCache.storeWalked(i, r);
3230
- }
3231
- if (typeof a == "string") {
3232
- let c = a === ".." || a === "" || a === ".";
3233
- this.matches.add(i.resolve(a), h, c);
3234
- continue;
3235
- } else if (a === A) {
3236
- (!i.isSymbolicLink() || this.follow || r.checkFollowGlobstar()) && this.subwalks.add(i, r);
3237
- let c = l?.pattern(), d = l?.rest();
3238
- if (!l || (c === "" || c === ".") && !d) this.matches.add(i, h, c === "" || c === ".");
3239
- else if (c === "..") {
3240
- let u = i.parent || i;
3241
- d ? this.hasWalkedCache.hasWalked(u, d) || this.subwalks.add(u, d) : this.matches.add(u, h, true);
3242
- }
3243
- } else a instanceof RegExp && this.subwalks.add(i, r);
3244
- }
3245
- return this;
3246
- }
3247
- subwalkTargets() {
3248
- return this.subwalks.keys();
3249
- }
3250
- child() {
3251
- return new n6(this.opts, this.hasWalkedCache);
3252
- }
3253
- filterEntries(t, e) {
3254
- let s = this.subwalks.get(t), i = this.child();
3255
- for (let r of e) for (let o of s) {
3256
- let h = o.isAbsolute(), a = o.pattern(), l = o.rest();
3257
- a === A ? i.testGlobstar(r, o, l, h) : a instanceof RegExp ? i.testRegExp(r, a, l, h) : i.testString(r, a, l, h);
3258
- }
3259
- return i;
3260
- }
3261
- testGlobstar(t, e, s, i) {
3262
- if ((this.dot || !t.name.startsWith(".")) && (e.hasMore() || this.matches.add(t, i, false), t.canReaddir() && (this.follow || !t.isSymbolicLink() ? this.subwalks.add(t, e) : t.isSymbolicLink() && (s && e.checkFollowGlobstar() ? this.subwalks.add(t, s) : e.markFollowGlobstar() && this.subwalks.add(t, e)))), s) {
3263
- let r = s.pattern();
3264
- if (typeof r == "string" && r !== ".." && r !== "" && r !== ".") this.testString(t, r, s.rest(), i);
3265
- else if (r === "..") {
3266
- let o = t.parent || t;
3267
- this.subwalks.add(o, s);
3268
- } else r instanceof RegExp && this.testRegExp(t, r, s.rest(), i);
3269
- }
3270
- }
3271
- testRegExp(t, e, s, i) {
3272
- e.test(t.name) && (s ? this.subwalks.add(t, s) : this.matches.add(t, i, false));
3273
- }
3274
- testString(t, e, s, i) {
3275
- t.isNamed(e) && (s ? this.subwalks.add(t, s) : this.matches.add(t, i, false));
3276
- }
3277
- };
3278
- var _i = (n7, t) => typeof n7 == "string" ? new ot([n7], t) : Array.isArray(n7) ? new ot(n7, t) : n7, zt = class {
3279
- path;
3280
- patterns;
3281
- opts;
3282
- seen = /* @__PURE__ */ new Set();
3283
- paused = false;
3284
- aborted = false;
3285
- #t = [];
3286
- #s;
3287
- #n;
3288
- signal;
3289
- maxDepth;
3290
- includeChildMatches;
3291
- constructor(t, e, s) {
3292
- if (this.patterns = t, this.path = e, this.opts = s, this.#n = !s.posix && s.platform === "win32" ? "\\" : "/", this.includeChildMatches = s.includeChildMatches !== false, (s.ignore || !this.includeChildMatches) && (this.#s = _i(s.ignore ?? [], s), !this.includeChildMatches && typeof this.#s.add != "function")) {
3293
- let i = "cannot ignore child matches, ignore lacks add() method.";
3294
- throw new Error(i);
3295
- }
3296
- this.maxDepth = s.maxDepth || 1 / 0, s.signal && (this.signal = s.signal, this.signal.addEventListener("abort", () => {
3297
- this.#t.length = 0;
3298
- }));
3299
- }
3300
- #r(t) {
3301
- return this.seen.has(t) || !!this.#s?.ignored?.(t);
3302
- }
3303
- #o(t) {
3304
- return !!this.#s?.childrenIgnored?.(t);
3305
- }
3306
- pause() {
3307
- this.paused = true;
3308
- }
3309
- resume() {
3310
- if (this.signal?.aborted) return;
3311
- this.paused = false;
3312
- let t;
3313
- for (; !this.paused && (t = this.#t.shift()); ) t();
3314
- }
3315
- onResume(t) {
3316
- this.signal?.aborted || (this.paused ? this.#t.push(t) : t());
3317
- }
3318
- async matchCheck(t, e) {
3319
- if (e && this.opts.nodir) return;
3320
- let s;
3321
- if (this.opts.realpath) {
3322
- if (s = t.realpathCached() || await t.realpath(), !s) return;
3323
- t = s;
3324
- }
3325
- let r = t.isUnknown() || this.opts.stat ? await t.lstat() : t;
3326
- if (this.opts.follow && this.opts.nodir && r?.isSymbolicLink()) {
3327
- let o = await r.realpath();
3328
- o && (o.isUnknown() || this.opts.stat) && await o.lstat();
3329
- }
3330
- return this.matchCheckTest(r, e);
3331
- }
3332
- matchCheckTest(t, e) {
3333
- return t && (this.maxDepth === 1 / 0 || t.depth() <= this.maxDepth) && (!e || t.canReaddir()) && (!this.opts.nodir || !t.isDirectory()) && (!this.opts.nodir || !this.opts.follow || !t.isSymbolicLink() || !t.realpathCached()?.isDirectory()) && !this.#r(t) ? t : void 0;
3334
- }
3335
- matchCheckSync(t, e) {
3336
- if (e && this.opts.nodir) return;
3337
- let s;
3338
- if (this.opts.realpath) {
3339
- if (s = t.realpathCached() || t.realpathSync(), !s) return;
3340
- t = s;
3341
- }
3342
- let r = t.isUnknown() || this.opts.stat ? t.lstatSync() : t;
3343
- if (this.opts.follow && this.opts.nodir && r?.isSymbolicLink()) {
3344
- let o = r.realpathSync();
3345
- o && (o?.isUnknown() || this.opts.stat) && o.lstatSync();
3346
- }
3347
- return this.matchCheckTest(r, e);
3348
- }
3349
- matchFinish(t, e) {
3350
- if (this.#r(t)) return;
3351
- if (!this.includeChildMatches && this.#s?.add) {
3352
- let r = `${t.relativePosix()}/**`;
3353
- this.#s.add(r);
3354
- }
3355
- let s = this.opts.absolute === void 0 ? e : this.opts.absolute;
3356
- this.seen.add(t);
3357
- let i = this.opts.mark && t.isDirectory() ? this.#n : "";
3358
- if (this.opts.withFileTypes) this.matchEmit(t);
3359
- else if (s) {
3360
- let r = this.opts.posix ? t.fullpathPosix() : t.fullpath();
3361
- this.matchEmit(r + i);
3362
- } else {
3363
- let r = this.opts.posix ? t.relativePosix() : t.relative(), o = this.opts.dotRelative && !r.startsWith(".." + this.#n) ? "." + this.#n : "";
3364
- this.matchEmit(r ? o + r + i : "." + i);
3365
- }
3366
- }
3367
- async match(t, e, s) {
3368
- let i = await this.matchCheck(t, s);
3369
- i && this.matchFinish(i, e);
3370
- }
3371
- matchSync(t, e, s) {
3372
- let i = this.matchCheckSync(t, s);
3373
- i && this.matchFinish(i, e);
3374
- }
3375
- walkCB(t, e, s) {
3376
- this.signal?.aborted && s(), this.walkCB2(t, e, new Et(this.opts), s);
3377
- }
3378
- walkCB2(t, e, s, i) {
3379
- if (this.#o(t)) return i();
3380
- if (this.signal?.aborted && i(), this.paused) {
3381
- this.onResume(() => this.walkCB2(t, e, s, i));
3382
- return;
3383
- }
3384
- s.processPatterns(t, e);
3385
- let r = 1, o = () => {
3386
- --r === 0 && i();
3387
- };
3388
- for (let [h, a, l] of s.matches.entries()) this.#r(h) || (r++, this.match(h, a, l).then(() => o()));
3389
- for (let h of s.subwalkTargets()) {
3390
- if (this.maxDepth !== 1 / 0 && h.depth() >= this.maxDepth) continue;
3391
- r++;
3392
- let a = h.readdirCached();
3393
- h.calledReaddir() ? this.walkCB3(h, a, s, o) : h.readdirCB((l, f) => this.walkCB3(h, f, s, o), true);
3394
- }
3395
- o();
3396
- }
3397
- walkCB3(t, e, s, i) {
3398
- s = s.filterEntries(t, e);
3399
- let r = 1, o = () => {
3400
- --r === 0 && i();
3401
- };
3402
- for (let [h, a, l] of s.matches.entries()) this.#r(h) || (r++, this.match(h, a, l).then(() => o()));
3403
- for (let [h, a] of s.subwalks.entries()) r++, this.walkCB2(h, a, s.child(), o);
3404
- o();
3405
- }
3406
- walkCBSync(t, e, s) {
3407
- this.signal?.aborted && s(), this.walkCB2Sync(t, e, new Et(this.opts), s);
3408
- }
3409
- walkCB2Sync(t, e, s, i) {
3410
- if (this.#o(t)) return i();
3411
- if (this.signal?.aborted && i(), this.paused) {
3412
- this.onResume(() => this.walkCB2Sync(t, e, s, i));
3413
- return;
3414
- }
3415
- s.processPatterns(t, e);
3416
- let r = 1, o = () => {
3417
- --r === 0 && i();
3418
- };
3419
- for (let [h, a, l] of s.matches.entries()) this.#r(h) || this.matchSync(h, a, l);
3420
- for (let h of s.subwalkTargets()) {
3421
- if (this.maxDepth !== 1 / 0 && h.depth() >= this.maxDepth) continue;
3422
- r++;
3423
- let a = h.readdirSync();
3424
- this.walkCB3Sync(h, a, s, o);
3425
- }
3426
- o();
3427
- }
3428
- walkCB3Sync(t, e, s, i) {
3429
- s = s.filterEntries(t, e);
3430
- let r = 1, o = () => {
3431
- --r === 0 && i();
3432
- };
3433
- for (let [h, a, l] of s.matches.entries()) this.#r(h) || this.matchSync(h, a, l);
3434
- for (let [h, a] of s.subwalks.entries()) r++, this.walkCB2Sync(h, a, s.child(), o);
3435
- o();
3436
- }
3437
- }, xt = class extends zt {
3438
- matches = /* @__PURE__ */ new Set();
3439
- constructor(t, e, s) {
3440
- super(t, e, s);
3441
- }
3442
- matchEmit(t) {
3443
- this.matches.add(t);
3444
- }
3445
- async walk() {
3446
- if (this.signal?.aborted) throw this.signal.reason;
3447
- return this.path.isUnknown() && await this.path.lstat(), await new Promise((t, e) => {
3448
- this.walkCB(this.path, this.patterns, () => {
3449
- this.signal?.aborted ? e(this.signal.reason) : t(this.matches);
3450
- });
3451
- }), this.matches;
3452
- }
3453
- walkSync() {
3454
- if (this.signal?.aborted) throw this.signal.reason;
3455
- return this.path.isUnknown() && this.path.lstatSync(), this.walkCBSync(this.path, this.patterns, () => {
3456
- if (this.signal?.aborted) throw this.signal.reason;
3457
- }), this.matches;
3458
- }
3459
- }, vt = class extends zt {
3460
- results;
3461
- constructor(t, e, s) {
3462
- super(t, e, s), this.results = new V({ signal: this.signal, objectMode: true }), this.results.on("drain", () => this.resume()), this.results.on("resume", () => this.resume());
3463
- }
3464
- matchEmit(t) {
3465
- this.results.write(t), this.results.flowing || this.pause();
3466
- }
3467
- stream() {
3468
- let t = this.path;
3469
- return t.isUnknown() ? t.lstat().then(() => {
3470
- this.walkCB(t, this.patterns, () => this.results.end());
3471
- }) : this.walkCB(t, this.patterns, () => this.results.end()), this.results;
3472
- }
3473
- streamSync() {
3474
- return this.path.isUnknown() && this.path.lstatSync(), this.walkCBSync(this.path, this.patterns, () => this.results.end()), this.results;
3475
- }
3476
- };
3477
- var Wi = typeof process == "object" && process && typeof process.platform == "string" ? process.platform : "linux", I = class {
3478
- absolute;
3479
- cwd;
3480
- root;
3481
- dot;
3482
- dotRelative;
3483
- follow;
3484
- ignore;
3485
- magicalBraces;
3486
- mark;
3487
- matchBase;
3488
- maxDepth;
3489
- nobrace;
3490
- nocase;
3491
- nodir;
3492
- noext;
3493
- noglobstar;
3494
- pattern;
3495
- platform;
3496
- realpath;
3497
- scurry;
3498
- stat;
3499
- signal;
3500
- windowsPathsNoEscape;
3501
- withFileTypes;
3502
- includeChildMatches;
3503
- opts;
3504
- patterns;
3505
- constructor(t, e) {
3506
- if (!e) throw new TypeError("glob options required");
3507
- if (this.withFileTypes = !!e.withFileTypes, this.signal = e.signal, this.follow = !!e.follow, this.dot = !!e.dot, this.dotRelative = !!e.dotRelative, this.nodir = !!e.nodir, this.mark = !!e.mark, e.cwd ? (e.cwd instanceof URL || e.cwd.startsWith("file://")) && (e.cwd = node_url.fileURLToPath(e.cwd)) : this.cwd = "", this.cwd = e.cwd || "", this.root = e.root, this.magicalBraces = !!e.magicalBraces, this.nobrace = !!e.nobrace, this.noext = !!e.noext, this.realpath = !!e.realpath, this.absolute = e.absolute, this.includeChildMatches = e.includeChildMatches !== false, this.noglobstar = !!e.noglobstar, this.matchBase = !!e.matchBase, this.maxDepth = typeof e.maxDepth == "number" ? e.maxDepth : 1 / 0, this.stat = !!e.stat, this.ignore = e.ignore, this.withFileTypes && this.absolute !== void 0) throw new Error("cannot set absolute and withFileTypes:true");
3508
- if (typeof t == "string" && (t = [t]), this.windowsPathsNoEscape = !!e.windowsPathsNoEscape || e.allowWindowsEscape === false, this.windowsPathsNoEscape && (t = t.map((a) => a.replace(/\\/g, "/"))), this.matchBase) {
3509
- if (e.noglobstar) throw new TypeError("base matching requires globstar");
3510
- t = t.map((a) => a.includes("/") ? a : `./**/${a}`);
3511
- }
3512
- if (this.pattern = t, this.platform = e.platform || Wi, this.opts = { ...e, platform: this.platform }, e.scurry) {
3513
- if (this.scurry = e.scurry, e.nocase !== void 0 && e.nocase !== e.scurry.nocase) throw new Error("nocase option contradicts provided scurry option");
3514
- } else {
3515
- let a = e.platform === "win32" ? it : e.platform === "darwin" ? St : e.platform ? rt : Xe;
3516
- this.scurry = new a(this.cwd, { nocase: e.nocase, fs: e.fs });
3517
- }
3518
- this.nocase = this.scurry.nocase;
3519
- let s = this.platform === "darwin" || this.platform === "win32", i = { ...e, dot: this.dot, matchBase: this.matchBase, nobrace: this.nobrace, nocase: this.nocase, nocaseMagicOnly: s, nocomment: true, noext: this.noext, nonegate: true, optimizationLevel: 2, platform: this.platform, windowsPathsNoEscape: this.windowsPathsNoEscape, debug: !!this.opts.debug }, r = this.pattern.map((a) => new D(a, i)), [o, h] = r.reduce((a, l) => (a[0].push(...l.set), a[1].push(...l.globParts), a), [[], []]);
3520
- this.patterns = o.map((a, l) => {
3521
- let f = h[l];
3522
- if (!f) throw new Error("invalid pattern object");
3523
- return new nt(a, f, 0, this.platform);
3524
- });
3525
- }
3526
- async walk() {
3527
- return [...await new xt(this.patterns, this.scurry.cwd, { ...this.opts, maxDepth: this.maxDepth !== 1 / 0 ? this.maxDepth + this.scurry.cwd.depth() : 1 / 0, platform: this.platform, nocase: this.nocase, includeChildMatches: this.includeChildMatches }).walk()];
3528
- }
3529
- walkSync() {
3530
- return [...new xt(this.patterns, this.scurry.cwd, { ...this.opts, maxDepth: this.maxDepth !== 1 / 0 ? this.maxDepth + this.scurry.cwd.depth() : 1 / 0, platform: this.platform, nocase: this.nocase, includeChildMatches: this.includeChildMatches }).walkSync()];
3531
- }
3532
- stream() {
3533
- return new vt(this.patterns, this.scurry.cwd, { ...this.opts, maxDepth: this.maxDepth !== 1 / 0 ? this.maxDepth + this.scurry.cwd.depth() : 1 / 0, platform: this.platform, nocase: this.nocase, includeChildMatches: this.includeChildMatches }).stream();
3534
- }
3535
- streamSync() {
3536
- return new vt(this.patterns, this.scurry.cwd, { ...this.opts, maxDepth: this.maxDepth !== 1 / 0 ? this.maxDepth + this.scurry.cwd.depth() : 1 / 0, platform: this.platform, nocase: this.nocase, includeChildMatches: this.includeChildMatches }).streamSync();
3537
- }
3538
- iterateSync() {
3539
- return this.streamSync()[Symbol.iterator]();
3540
- }
3541
- [Symbol.iterator]() {
3542
- return this.iterateSync();
3543
- }
3544
- iterate() {
3545
- return this.stream()[Symbol.asyncIterator]();
3546
- }
3547
- [Symbol.asyncIterator]() {
3548
- return this.iterate();
3549
- }
3550
- };
3551
- var le = (n7, t = {}) => {
3552
- Array.isArray(n7) || (n7 = [n7]);
3553
- for (let e of n7) if (new D(e, t).hasMagic()) return true;
3554
- return false;
3555
- };
3556
- function Bt(n7, t = {}) {
3557
- return new I(n7, t).streamSync();
3558
- }
3559
- function Qe(n7, t = {}) {
3560
- return new I(n7, t).stream();
3561
- }
3562
- function ts(n7, t = {}) {
3563
- return new I(n7, t).walkSync();
3564
- }
3565
- async function Je(n7, t = {}) {
3566
- return new I(n7, t).walk();
3567
- }
3568
- function Ut(n7, t = {}) {
3569
- return new I(n7, t).iterateSync();
3570
- }
3571
- function es(n7, t = {}) {
3572
- return new I(n7, t).iterate();
3573
- }
3574
- var Pi = Bt, ji = Object.assign(Qe, { sync: Bt }), Ii = Ut, zi = Object.assign(es, { sync: Ut }), Bi = Object.assign(ts, { stream: Bt, iterate: Ut }), Ze = Object.assign(Je, { glob: Je, globSync: ts, sync: Bi, globStream: Qe, stream: ji, globStreamSync: Bt, streamSync: Pi, globIterate: es, iterate: zi, globIterateSync: Ut, iterateSync: Ii, Glob: I, hasMagic: le, escape: tt, unescape: W });
3575
- Ze.glob = Ze;
3576
-
3577
- function isArrayLike(value) {
3578
- return value != null && typeof value !== "function" && isLength(value.length);
3579
- }
3580
-
3581
- function toKey(value) {
3582
- if (typeof value === "string" || typeof value === "symbol") {
3583
- return value;
3584
- }
3585
- if (Object.is(value?.valueOf?.(), -0)) {
3586
- return "-0";
3587
- }
3588
- return String(value);
3589
- }
3590
-
3591
- function toString(value) {
3592
- if (value == null) {
3593
- return "";
3594
- }
3595
- if (typeof value === "string") {
3596
- return value;
3597
- }
3598
- if (Array.isArray(value)) {
3599
- return value.map(toString).join(",");
3600
- }
3601
- const result = String(value);
3602
- if (result === "0" && Object.is(Number(value), -0)) {
3603
- return "-0";
3604
- }
3605
- return result;
3606
- }
3607
-
3608
- function toPath(deepKey) {
3609
- if (Array.isArray(deepKey)) {
3610
- return deepKey.map(toKey);
3611
- }
3612
- if (typeof deepKey === "symbol") {
3613
- return [deepKey];
3614
- }
3615
- deepKey = toString(deepKey);
3616
- const result = [];
3617
- const length = deepKey.length;
3618
- if (length === 0) {
3619
- return result;
3620
- }
3621
- let index = 0;
3622
- let key = "";
3623
- let quoteChar = "";
3624
- let bracket = false;
3625
- if (deepKey.charCodeAt(0) === 46) {
3626
- result.push("");
3627
- index++;
3628
- }
3629
- while (index < length) {
3630
- const char = deepKey[index];
3631
- if (quoteChar) {
3632
- if (char === "\\" && index + 1 < length) {
3633
- index++;
3634
- key += deepKey[index];
3635
- } else if (char === quoteChar) {
3636
- quoteChar = "";
3637
- } else {
3638
- key += char;
3639
- }
3640
- } else if (bracket) {
3641
- if (char === '"' || char === "'") {
3642
- quoteChar = char;
3643
- } else if (char === "]") {
3644
- bracket = false;
3645
- result.push(key);
3646
- key = "";
3647
- } else {
3648
- key += char;
3649
- }
3650
- } else {
3651
- if (char === "[") {
3652
- bracket = true;
3653
- if (key) {
3654
- result.push(key);
3655
- key = "";
3656
- }
3657
- } else if (char === ".") {
3658
- if (key) {
3659
- result.push(key);
3660
- key = "";
3661
- }
3662
- } else {
3663
- key += char;
3664
- }
3665
- }
3666
- index++;
3667
- }
3668
- if (key) {
3669
- result.push(key);
3670
- }
3671
- return result;
3672
- }
3673
-
3674
- function isObject(value) {
3675
- return value !== null && (typeof value === "object" || typeof value === "function");
3676
- }
3677
-
3678
- const IS_UNSIGNED_INTEGER = /^(?:0|[1-9]\d*)$/;
3679
- function isIndex(value, length = Number.MAX_SAFE_INTEGER) {
3680
- switch (typeof value) {
3681
- case "number": {
3682
- return Number.isInteger(value) && value >= 0 && value < length;
3683
- }
3684
- case "symbol": {
3685
- return false;
3686
- }
3687
- case "string": {
3688
- return IS_UNSIGNED_INTEGER.test(value);
3689
- }
3690
- }
3691
- }
3692
-
3693
- function isIterateeCall(value, index, object) {
3694
- if (!isObject(object)) {
3695
- return false;
3696
- }
3697
- if (typeof index === "number" && isArrayLike(object) && isIndex(index) && index < object.length || typeof index === "string" && index in object) {
3698
- return isEqualsSameValueZero(object[index], value);
3699
- }
3700
- return false;
3701
- }
3702
-
3703
- function getPriority(a) {
3704
- if (typeof a === "symbol") {
3705
- return 1;
3706
- }
3707
- if (a === null) {
3708
- return 2;
3709
- }
3710
- if (a === void 0) {
3711
- return 3;
3712
- }
3713
- if (a !== a) {
3714
- return 4;
3715
- }
3716
- return 0;
3717
- }
3718
- const compareValues = (a, b, order) => {
3719
- if (a !== b) {
3720
- const aPriority = getPriority(a);
3721
- const bPriority = getPriority(b);
3722
- if (aPriority === bPriority && aPriority === 0) {
3723
- if (a < b) {
3724
- return order === "desc" ? 1 : -1;
3725
- }
3726
- if (a > b) {
3727
- return order === "desc" ? -1 : 1;
3728
- }
3729
- }
3730
- return order === "desc" ? bPriority - aPriority : aPriority - bPriority;
3731
- }
3732
- return 0;
3733
- };
3734
-
3735
- const regexIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
3736
- const regexIsPlainProp = /^\w*$/;
3737
- function isKey(value, object) {
3738
- if (Array.isArray(value)) {
3739
- return false;
3740
- }
3741
- if (typeof value === "number" || typeof value === "boolean" || value == null || isSymbol(value)) {
3742
- return true;
3743
- }
3744
- return typeof value === "string" && (regexIsPlainProp.test(value) || !regexIsDeepProp.test(value)) || object != null;
3745
- }
3746
-
3747
- function orderBy(collection, criteria, orders, guard) {
3748
- if (collection == null) {
3749
- return [];
3750
- }
3751
- orders = orders;
3752
- if (!Array.isArray(collection)) {
3753
- collection = Object.values(collection);
3754
- }
3755
- if (!Array.isArray(criteria)) {
3756
- criteria = criteria == null ? [null] : [criteria];
3757
- }
3758
- if (criteria.length === 0) {
3759
- criteria = [null];
3760
- }
3761
- if (!Array.isArray(orders)) {
3762
- orders = orders == null ? [] : [orders];
3763
- }
3764
- orders = orders.map((order) => String(order));
3765
- const getValueByNestedPath = (object, path) => {
3766
- let target = object;
3767
- for (let i = 0; i < path.length && target != null; ++i) {
3768
- target = target[path[i]];
3769
- }
3770
- return target;
3771
- };
3772
- const getValueByCriterion = (criterion, object) => {
3773
- if (object == null || criterion == null) {
3774
- return object;
3775
- }
3776
- if (typeof criterion === "object" && "key" in criterion) {
3777
- if (Object.hasOwn(object, criterion.key)) {
3778
- return object[criterion.key];
3779
- }
3780
- return getValueByNestedPath(object, criterion.path);
3781
- }
3782
- if (typeof criterion === "function") {
3783
- return criterion(object);
3784
- }
3785
- if (Array.isArray(criterion)) {
3786
- return getValueByNestedPath(object, criterion);
3787
- }
3788
- if (typeof object === "object") {
3789
- return object[criterion];
3790
- }
3791
- return object;
3792
- };
3793
- const preparedCriteria = criteria.map((criterion) => {
3794
- if (Array.isArray(criterion) && criterion.length === 1) {
3795
- criterion = criterion[0];
3796
- }
3797
- if (criterion == null || typeof criterion === "function" || Array.isArray(criterion) || isKey(criterion)) {
3798
- return criterion;
3799
- }
3800
- return { key: criterion, path: toPath(criterion) };
3801
- });
3802
- const preparedCollection = collection.map((item) => ({
3803
- original: item,
3804
- criteria: preparedCriteria.map((criterion) => getValueByCriterion(criterion, item))
3805
- }));
3806
- return preparedCollection.slice().sort((a, b) => {
3807
- for (let i = 0; i < preparedCriteria.length; i++) {
3808
- const comparedResult = compareValues(a.criteria[i], b.criteria[i], orders[i]);
3809
- if (comparedResult !== 0) {
3810
- return comparedResult;
3811
- }
3812
- }
3813
- return 0;
3814
- }).map((item) => item.original);
3815
- }
3816
-
3817
- function sortBy(collection, ...criteria) {
3818
- const length = criteria.length;
3819
- if (length > 1 && isIterateeCall(collection, criteria[0], criteria[1])) {
3820
- criteria = [];
3821
- } else if (length > 2 && isIterateeCall(criteria[0], criteria[1], criteria[2])) {
3822
- criteria = [criteria[0]];
3823
- }
3824
- return orderBy(collection, flatten(criteria), ["asc"]);
3825
- }
3826
-
3827
- const sortFilePathsByFilename = (filePaths) => sortBy(filePaths, (file) => {
3828
- return path.parse(file).base;
3829
- });
3830
- const getMigrationFilePaths = async (pathToMigrations) => {
3831
- const filePath = (pattern) => `${pathToMigrations}${pattern}`;
3832
- const filePaths = await Ze(filePath("/**/*.js"), {
3833
- ignore: [
3834
- filePath("/**/*.skip?([0-9]*).js"),
3835
- filePath("/**/index.js"),
3836
- filePath("/**/plan.json"),
3837
- filePath("/**/*.bundle.js"),
3838
- filePath("/**/*.test.js"),
3839
- filePath("/**/*.spec.js"),
3840
- filePath("/**/__tests__/*"),
3841
- filePath("/**/__test__/*")
3842
- ]
3843
- });
3844
- return sortFilePathsByFilename(filePaths);
3845
- };
3846
- const getSkippedFilePaths = async (pathToMigrations) => {
3847
- const filePath = (pattern) => `${pathToMigrations}${pattern}`;
3848
- const filePaths = await Ze(filePath("/**/*.skip?([0-9]*).js"), {
3849
- ignore: [
3850
- filePath("/**/index.js"),
3851
- filePath("/**/plan.json"),
3852
- filePath("/**/*.bundle.js"),
3853
- filePath("/**/*.test.js"),
3854
- filePath("/**/*.spec.js"),
3855
- filePath("/**/__tests__/*"),
3856
- filePath("/**/__test__/*")
3857
- ]
3858
- });
3859
- return sortFilePathsByFilename(filePaths);
3860
- };
3861
-
3862
- const migrationTablesExist = (db, entity) => {
3863
- const query = `
3864
- SELECT EXISTS (
3865
- SELECT FROM information_schema.tables
3866
- WHERE table_schema = 'public'
3867
- AND table_name = $(tableName)
3868
- )
3869
- `;
3870
- const params = { tableName: `${entity}_migrations` };
3871
- return db.one(query, params);
3872
- };
3873
- const createMigrationsTables = (db, entity) => {
3874
- const query = `
3875
- CREATE TABLE IF NOT EXISTS $(migrationsTable:name) (
3876
- file_hash TEXT NOT NULL PRIMARY KEY,
3877
- file_name TEXT NOT NULL,
3878
- sequence TEXT NOT NULL,
3879
- created_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
3880
- UNIQUE (file_name),
3881
- UNIQUE (sequence)
3882
- );
3883
- CREATE TABLE IF NOT EXISTS $(versionsTable:name) (
3884
- version TEXT NOT NULL PRIMARY KEY,
3885
- plan TEXT NOT NULL,
3886
- created_on TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
3887
- );
3888
- `;
3889
- const params = {
3890
- migrationsTable: `${entity}_migrations`,
3891
- versionsTable: `${entity}_versions`
3892
- };
3893
- return db.none(query, params);
3894
- };
3895
- const getMigrationRecords = (db, entity) => {
3896
- const query = `
3897
- SELECT file_hash, file_name, sequence
3898
- FROM $(migrationsTable:name)
3899
- ORDER BY sequence
3900
- `;
3901
- const params = { migrationsTable: `${entity}_migrations` };
3902
- return db.manyOrNone(query, params).then(
3903
- (data) => data.map((r) => ({
3904
- fileHash: r.file_hash,
3905
- fileName: r.file_name,
3906
- sequence: r.sequence
3907
- }))
3908
- );
3909
- };
3910
- const insertMigrationsRecords = (db, pgpHelpers, entity, migrations) => {
3911
- if (migrations.length) {
3912
- const toInsert = migrations.map((m) => ({
3913
- file_name: m.fileName,
3914
- file_hash: m.fileHash,
3915
- sequence: m.sequence
3916
- })).filter((m) => m.file_hash !== null);
3917
- const cs = new pgpHelpers.ColumnSet(
3918
- ["file_name", "file_hash", "sequence"],
3919
- {
3920
- table: new pgpHelpers.TableName({ table: `${entity}_migrations` })
3921
- }
3922
- );
3923
- const onConflict = " ON CONFLICT(file_name) DO NOTHING";
3924
- const query = pgpHelpers.insert(toInsert, cs) + onConflict;
3925
- return db.none(query);
3926
- }
3927
- };
3928
- const replaceMigrationsRecords = async (db, pgpHelpers, entity, migrations) => {
3929
- const query = `DELETE FROM $(migrationsTableName:name)`;
3930
- const params = { migrationsTableName: `${entity}_migrations` };
3931
- await db.none(query, params);
3932
- await insertMigrationsRecords(db, pgpHelpers, entity, migrations);
3933
- };
3934
- const insertVersions = (db, pgpHelpers, entity, records) => {
3935
- const cs = new pgpHelpers.ColumnSet(["version", "plan"], {
3936
- table: new pgpHelpers.TableName({ table: `${entity}_versions` })
3937
- });
3938
- const onConflict = " ON CONFLICT(version) DO NOTHING";
3939
- const query = pgpHelpers.insert(records, cs) + onConflict;
3940
- return db.none(query);
3941
- };
3942
- const getPlanFromVersion = (db, entity, version) => {
3943
- const query = `
3944
- SELECT plan FROM $(versionsTable:name)
3945
- WHERE version=$(version);
3946
- `;
3947
- const params = {
3948
- version,
3949
- versionsTable: `${entity}_versions`
3950
- };
3951
- return db.oneOrNone(query, params, (r) => r?.plan || null);
3952
- };
3953
- const getVersions = async (db, entity) => {
3954
- const query = `
3955
- SELECT
3956
- version,
3957
- plan
3958
- FROM $(versionsTable:name) ORDER BY created_on DESC
3959
- `;
3960
- const params = {
3961
- versionsTable: `${entity}_versions`
3962
- };
3963
- return db.any(query, params);
3964
- };
3965
- const filterRecordsWithNoPendingMigrations = ({
3966
- records,
3967
- latestPlan
3968
- }) => {
3969
- return records.filter((record) => {
3970
- const currentHashes = new Set(
3971
- (record?.currentPlan ?? []).map((p) => p.fileHash)
3972
- );
3973
- return latestPlan.some((p) => !currentHashes.has(p.fileHash));
3974
- });
3975
- };
3976
- const getRecordList = async (db, entity, entityTableName, entityColumnNames, latestVersion, latestPlan) => {
3977
- const query = `
3978
- SELECT
3979
- e.$(entityIdColumn:name) AS id,
3980
- e.$(entityNameColumn:name) AS name,
3981
- e.$(entityCreatedColumn:name) AS created,
3982
- e.$(entityVersionColumn:name) AS version,
3983
- v_current.plan::json AS currentplan
3984
- FROM $(entityTable:name) e
3985
- LEFT JOIN $(entityVersionsTable:name) v_current
3986
- ON v_current.version = e.$(entityVersionColumn:name)
3987
- WHERE
3988
- e.$(entityVersionColumn:name) IS NULL
3989
- OR e.$(entityVersionColumn:name) = ''
3990
- OR e.$(entityVersionColumn:name) <> $(latestVersion)
3991
- `;
3992
- const params = {
3993
- entityTable: entityTableName,
3994
- entityVersionsTable: `${entity}_versions`,
3995
- entityIdColumn: entityColumnNames.id,
3996
- entityNameColumn: entityColumnNames.name,
3997
- entityCreatedColumn: entityColumnNames.created,
3998
- entityVersionColumn: entityColumnNames.version,
3999
- latestVersion
4000
- };
4001
- const records = (await db.any(query, params)).map((r) => ({
4002
- ...r,
4003
- currentPlan: r.currentplan
4004
- }));
4005
- return filterRecordsWithNoPendingMigrations({ records, latestPlan });
4006
- };
4007
- const getRecord = async (t, entityTableName, entityColumnNames, entityId) => {
4008
- const query = `
4009
- SELECT *
4010
- FROM $(entityTable:name)
4011
- WHERE $(entityIdColumn:name) = $(entityId)
4012
- `;
4013
- const params = {
4014
- entityTable: entityTableName,
4015
- entityId,
4016
- entityIdColumn: entityColumnNames.id
4017
- };
4018
- return t.one(query, params);
4019
- };
4020
- const updateRecord = async (t, entityTableName, entityColumnNames, entityId, currentVersion, nextData, nextVersion, etag) => {
4021
- const useEtag = typeof etag === "number";
4022
- const query = `
4023
- UPDATE $(entityTable:name)
4024
- SET
4025
- $(payloadColumn:name) = $(nextData),
4026
- $(versionColumn:name) = $(nextVersion)
4027
- ${useEtag ? ", $(etagColumn:name) = $(etagColumn:name) + 1" : ""}
4028
- WHERE $(idColumn:name) = $(entityId)
4029
- AND $(versionColumn:name) = $(currentVersion)
4030
- ${useEtag ? "AND $(etagColumn:name) = $(etag)" : ""}
4031
- RETURNING *
4032
- `;
4033
- const params = {
4034
- entityTable: entityTableName,
4035
- idColumn: entityColumnNames.id,
4036
- payloadColumn: entityColumnNames.payload,
4037
- versionColumn: entityColumnNames.version,
4038
- etagColumn: entityColumnNames.etag,
4039
- entityId,
4040
- currentVersion,
4041
- nextData,
4042
- nextVersion,
4043
- etag
4044
- };
4045
- return t.oneOrNone(query, params);
4046
- };
4047
-
4048
- const formatJSON = (json) => {
4049
- try {
4050
- return JSON.stringify(JSON.parse(json), null, 2);
4051
- } catch (e) {
4052
- console.warn("Unable to parse JSON");
4053
- throw new Error(e);
4054
- }
4055
- };
4056
- const sortEntry = (entry) => Object.keys(entry).sort().reduce((obj, key) => {
4057
- obj[key] = entry[key];
4058
- return obj;
4059
- }, {});
4060
- const MAX_SEQUENCE = 1e6;
4061
- const sortPlanEntries = (plannedMigrations) => {
4062
- const result = plannedMigrations.sort(
4063
- (a, b) => a.sequence.replace(/\d+/g, (n) => `${+n + MAX_SEQUENCE}`).localeCompare(
4064
- b.sequence.replace(/\d+/g, (n) => `${+n + MAX_SEQUENCE}`)
4065
- )
4066
- ).map((p) => sortEntry(p));
4067
- return result;
4068
- };
4069
- const getNextSequenceString = (sortedPlannedMigrations) => {
4070
- const lastMigration = sortedPlannedMigrations[sortedPlannedMigrations.length - 1];
4071
- if (!lastMigration) {
4072
- return "1";
4073
- }
4074
- const currentLastSequenceNumber = lastMigration.sequence;
4075
- return `${parseInt(`${currentLastSequenceNumber}`, 10) + 1}`;
4076
- };
4077
- const readPlan = async (directory) => {
4078
- let plan;
4079
- try {
4080
- plan = await fs$1.promises.readFile(`${directory}/plan.json`, {
4081
- encoding: "utf8"
4082
- });
4083
- return formatJSON(plan);
4084
- } catch {
4085
- throw new Error("Invalid JSON for migrator plan.js (unable to parse file)");
4086
- }
4087
- };
4088
- const parsePlan$1 = (plan) => {
4089
- let plannedMigrations;
4090
- try {
4091
- plannedMigrations = JSON.parse(plan);
4092
- } catch {
4093
- throw new Error("Invalid JSON for migrator plan.js (unable to parse file)");
4094
- }
4095
- if (!validatePlan(plannedMigrations)) {
4096
- throw new Error(
4097
- "Invalid JSON for migrator plan.js (does not match schema)"
4098
- );
4099
- }
4100
- return sortPlanEntries(plannedMigrations);
4101
- };
4102
- const writePlan = async (directory, content) => {
4103
- await fs$1.promises.writeFile(path.resolve(`${directory}/plan.json`), content, {
4104
- encoding: "utf8"
4105
- });
4106
- };
4107
- const generatePlanEntries = (sortedMigrationEntries) => sortedMigrationEntries.map((m) => ({
4108
- fileHash: m.fileHash,
4109
- fileName: m.fileName,
4110
- sequence: m.sequence
4111
- }));
4112
- const loadMigrationFunctionsFromStrings = async (sortedMigrationEntries, importModule) => Promise.all(
4113
- sortedMigrationEntries.map(async (m) => {
4114
- const { filePath, fileHash } = m;
4115
- const migrator = filePath && fileHash && importModule ? await LoaderModule.lazyImportMigration(
4116
- path.resolve(filePath),
4117
- fileHash
4118
- ) : null;
4119
- return {
4120
- fileHash: m.fileHash,
4121
- migrator
4122
- };
4123
- })
4124
- );
4125
- const loadMigrationFunctions = async (sortedMigrationEntries, _nextVersion, importModule = true) => {
4126
- const migrationFunctions = await loadMigrationFunctionsFromStrings(
4127
- sortedMigrationEntries,
4128
- importModule
4129
- );
4130
- return merge(sortedMigrationEntries, migrationFunctions);
4131
- };
4132
- const getPlannedMigrations = async ({ config }) => {
4133
- const {
4134
- directory,
4135
- database,
4136
- entity,
4137
- force,
4138
- pgpHelpers,
4139
- dry,
4140
- importModule = true,
4141
- autoInitializeTable = true
4142
- } = config;
4143
- if (autoInitializeTable && database && !dry) {
4144
- const tablesExist = await migrationTablesExist(database, entity);
4145
- if (!tablesExist) {
4146
- await createMigrationsTables(database, entity);
4147
- }
4148
- }
4149
- const rawPlan = await readPlan(directory);
4150
- const parsedPlan = parsePlan$1(rawPlan);
4151
- const plannedMigrations = parsedPlan.map((m) => ({
4152
- fileHashFromPlan: m.fileHash,
4153
- fileName: m.fileName,
4154
- sequence: m.sequence
4155
- }));
4156
- const filePaths = await getMigrationFilePaths(directory);
4157
- const skippedFilePaths = await getSkippedFilePaths(directory);
4158
- const plannedMigrationsWithFileEntries = await Promise.all(
4159
- plannedMigrations.map(async (m) => {
4160
- const { fileName } = m;
4161
- const isValidFileName = validateFileName(fileName);
4162
- const filePath = filePaths.find((f) => path.parse(f).base === m.fileName);
4163
- const script = filePath ? await fs$1.promises.readFile(filePath, { encoding: "utf8" }) : null;
4164
- const fileHash = script ? hash(script) : null;
4165
- const skipMatch = "(.skip|.skip\\d+).js$";
4166
- const nameMatch = path.parse(m.fileName).name;
4167
- const regex = new RegExp(`${nameMatch}${skipMatch}`, "g");
4168
- const matchingSkippedFilePaths = skippedFilePaths.filter((f) => {
4169
- const name = path.parse(f).base;
4170
- return name.match(regex);
4171
- });
4172
- const skippedFileHashes = await Promise.all(
4173
- matchingSkippedFilePaths.map(async (skippedFilePath) => {
4174
- const skippedScript = await fs$1.promises.readFile(skippedFilePath, {
4175
- encoding: "utf8"
4176
- });
4177
- return skippedScript ? hash(skippedScript) : null;
4178
- })
4179
- );
4180
- return {
4181
- ...m,
4182
- filePath,
4183
- isValidFileName,
4184
- script,
4185
- fileHash,
4186
- skippedFileHashes
4187
- };
4188
- })
4189
- );
4190
- const historicalMigrations = database ? await getMigrationRecords(database, entity) : [];
4191
- const plannedMigrationsWithHistory = plannedMigrationsWithFileEntries.map(
4192
- (m) => {
4193
- const historicalMigration = historicalMigrations.find(
4194
- (h) => h.fileName === m.fileName
4195
- );
4196
- return {
4197
- ...m,
4198
- fileHashFromHistory: historicalMigration?.fileHash || null,
4199
- sequenceFromHistory: historicalMigration?.sequence || null
4200
- };
4201
- }
4202
- );
4203
- throwIfFilesNotFound(plannedMigrationsWithHistory, importModule);
4204
- throwIfFileNamesInvalid(plannedMigrationsWithHistory);
4205
- throwIfFileNamesNotUnique(plannedMigrationsWithHistory);
4206
- throwIfSequenceNotUnique(plannedMigrationsWithHistory);
4207
- if (!force) {
4208
- warnIfFilesHaveBeenRemovedFromPlan(
4209
- plannedMigrationsWithHistory,
4210
- historicalMigrations
4211
- );
4212
- throwIfFilesHaveChanged(plannedMigrationsWithHistory);
4213
- throwIfSequenceHasChanged(plannedMigrationsWithHistory);
4214
- }
4215
- throwIfSequenceHasIntegerGaps(plannedMigrationsWithHistory);
4216
- const validatedPlannedMigrations = generatePlanEntries(
4217
- plannedMigrationsWithHistory
4218
- );
4219
- const validatedPlan = JSON.stringify(validatedPlannedMigrations, null, 2);
4220
- const nextVersion = hash(validatedPlan);
4221
- const planHasChanged = validatedPlan !== rawPlan;
4222
- if (!dry && planHasChanged) {
4223
- await writePlan(directory, validatedPlan);
4224
- }
4225
- if (database && !dry) {
4226
- await replaceMigrationsRecords(
4227
- database,
4228
- pgpHelpers,
4229
- entity,
4230
- validatedPlannedMigrations
4231
- );
4232
- const versionRecord = [{ version: nextVersion, plan: validatedPlan }];
4233
- await insertVersions(database, pgpHelpers, entity, versionRecord);
4234
- }
4235
- const plannedMigrationsWithFunctions = await loadMigrationFunctions(
4236
- plannedMigrationsWithHistory,
4237
- nextVersion,
4238
- importModule
4239
- );
4240
- return {
4241
- validatedPlan: validatedPlannedMigrations,
4242
- plannedMigrations: plannedMigrationsWithFunctions,
4243
- nextVersion
4244
- };
4245
- };
4246
- const PlanModule = { getPlannedMigrations };
4247
-
4248
- const templateMigrationFileWithMetaDataLegacy = (entity) => `import produce from 'immer';
4249
- //other imports not allowed
4250
-
4251
- export default (${entity}, metaData = {}) => produce(${entity}, (draft) => {
4252
- // https://immerjs.github.io/immer/produce#example
4253
- });
4254
- `;
4255
- const templateMigrationFileWithMetaData = (entity) => `import { produce } from 'immer';
4256
- //other imports not allowed
4257
-
4258
- export default (${entity}, metaData = {}) => produce(${entity}, (draft) => {
4259
- // https://immerjs.github.io/immer/produce#example
4260
- });
4261
- `;
4262
- const templateMigrationFileLegacy = (entity) => `import produce from 'immer';
4263
- //other imports not allowed
4264
-
4265
- export default (${entity}) => produce(${entity}, (draft) => {
4266
- // https://immerjs.github.io/immer/produce#example
4267
- });
4268
- `;
4269
- const templateMigrationFile = (entity) => `import { produce } from 'immer';
4270
- //other imports not allowed
4271
-
4272
- export default (${entity}) => produce(${entity}, (draft) => {
4273
- // https://immerjs.github.io/immer/produce#example
4274
- });
4275
- `;
4276
- const getTemplateMigrationFile = async (entity, enableMetaData) => {
4277
- let template = enableMetaData ? templateMigrationFileWithMetaDataLegacy(entity) : templateMigrationFileLegacy(entity);
4278
- try {
4279
- await import('immer').then(({ produce }) => {
4280
- if (produce) {
4281
- template = enableMetaData ? templateMigrationFileWithMetaData(entity) : templateMigrationFile(entity);
4282
- }
4283
- });
4284
- } catch {
4285
- }
4286
- return template;
4287
- };
4288
- const templateTestFile = (fileName, entity, enableMetaData) => `import { describe, test } from 'node:test';
4289
- import assert from 'node:assert/strict';
4290
- import migrate from './${fileName}';
4291
-
4292
- describe('${entity} change', () => {
4293
- test('should migrate an empty ${entity}', () => {
4294
- // arrange
4295
- const ${entity} = {};
4296
-
4297
- // act
4298
- const next${capitalize(entity)} = ${enableMetaData ? `migrate(${entity}, /* metaData */ {})` : `migrate(${entity})`};
4299
-
4300
- // assert
4301
- assert.ok(next${capitalize(entity)});
4302
- });
4303
- });
4304
- `;
4305
- const createMigration = async (directory, description, entity, enableMetaData) => {
4306
- if (!validateFileDescription(description)) {
4307
- throw new Error("Invalid migration description");
4308
- }
4309
- try {
4310
- const directoryFullPath = path.resolve(directory, description);
4311
- const fileName = `${description}.js`;
4312
- const testFileName = `${description}.test.js`;
4313
- const filePath = path.resolve(directoryFullPath, fileName);
4314
- const testFilePath = path.resolve(directoryFullPath, testFileName);
4315
- await fs$1.promises.mkdir(directoryFullPath, { recursive: true });
4316
- const templateMigrationScript = await getTemplateMigrationFile(
4317
- entity,
4318
- enableMetaData
4319
- );
4320
- await fs$1.promises.writeFile(filePath, templateMigrationScript, {
4321
- encoding: "utf8"
4322
- });
4323
- await fs$1.promises.writeFile(
4324
- testFilePath,
4325
- templateTestFile(fileName, entity, enableMetaData),
4326
- {
4327
- encoding: "utf8"
4328
- }
4329
- );
4330
- const rawPlan = await readPlan(directory);
4331
- const plannedMigrations = parsePlan$1(rawPlan);
4332
- const nextPlannedMigrations = plannedMigrations.concat({
4333
- fileHash: "",
4334
- fileName,
4335
- sequence: getNextSequenceString(plannedMigrations)
4336
- });
4337
- const nextPlan = JSON.stringify(nextPlannedMigrations, null, 2);
4338
- await writePlan(directory, nextPlan);
4339
- console.log(chalk.green(`Created new ${entity} migration ${fileName} \u2713`));
4340
- } catch (error) {
4341
- console.log(chalk.red(error));
4342
- throw new Error("Unable to create migration file");
4343
- }
4344
- };
4345
-
4346
- const getPlannedVersion = async ({ config }) => {
4347
- const { directory } = config;
4348
- const currentPlan = await readPlan(directory);
4349
- return hash(currentPlan);
4350
- };
4351
-
4352
- const errorMessage = (fileName, message, stack) => `Unhandled exception in file ${fileName}: ${message}
4353
-
4354
- ${stack}
4355
- `;
4356
- const pipe = (migrations, payload, metaData) => (
4357
- // structuredClone is to remove Immer artefacts - TODO check this
4358
- structuredClone(
4359
- migrations.reduce((v, m) => {
4360
- if (typeof m?.migrator !== "function") {
4361
- throw new TypeError("Expected a function");
4362
- }
4363
- try {
4364
- return m.migrator(v, metaData);
4365
- } catch (error) {
4366
- throw new Error(errorMessage(m?.fileName, error.message, error.stack));
4367
- }
4368
- }, payload)
4369
- )
4370
- );
4371
- const PipeModule = { pipe };
4372
-
4373
- const { platform } = process$1;
4374
- const isWindows = platform === "win32";
4375
- const terminals = Object.freeze({
4376
- bash: "bash",
4377
- cmd: "cmd"
4378
- });
4379
- const historyError = `Unable to fetch migrations history from git. Possible reasons:
4380
- - Have you merged latest master branch into your environment (fetch latest migrations)?
4381
- - Are you trying to downgrade data (not allowed), e.g. newer data into an older environment?
4382
- - Not allowed to export data from TEST and import to PROD
4383
- - Not allowed to export data from feature branches and import into TEST, PROD or master ENVs
4384
- - On Windows? Do you have git and a terminal (bash or cmd) in your PATH? Try cmder.app, gitforwindows.org, or WSL
4385
- `;
4386
- const commandAvailable = (command) => {
4387
- try {
4388
- const exists = isWindows ? "where" : "which";
4389
- child_process.execSync(`${exists} ${command}`);
4390
- return true;
4391
- } catch {
4392
- return false;
4393
- }
4394
- };
4395
- const gitAvailable = () => commandAvailable("git");
4396
- const cmdAvailable = () => isWindows && commandAvailable("cmd");
4397
- const bashAvailable = () => {
4398
- if (commandAvailable("bash")) {
4399
- try {
4400
- const response = child_process.execSync("bash --version").toString();
4401
- return response.includes("version");
4402
- } catch {
4403
- return false;
4404
- }
4405
- }
4406
- return false;
4407
- };
4408
- const getTerminal = () => {
4409
- const bashActive = bashAvailable();
4410
- const cmdActive = cmdAvailable();
4411
- if (!(bashActive || cmdActive)) {
4412
- throw new Error(
4413
- "bash terminal (or cmd.exe on Windows) must be installed and in PATH"
4414
- );
4415
- }
4416
- return isWindows && !bashActive ? terminals.cmd : terminals.bash;
4417
- };
4418
- const exec = (command, terminal) => new Promise((resolve, reject) => {
4419
- const useWinCmd = terminal === terminals.cmd;
4420
- const args = useWinCmd ? ["/c", command] : ["-c", command];
4421
- const thread = child_process.spawn(terminal, args, {
4422
- stdio: ["inherit", "pipe", "pipe"]
4423
- });
4424
- const stdOut = [];
4425
- const stdErr = [];
4426
- thread.stdout.on("data", (data) => {
4427
- stdOut.push(data.toString());
4428
- });
4429
- thread.stderr.on("data", (data) => {
4430
- stdErr.push(data.toString());
4431
- });
4432
- thread.on("close", () => {
4433
- if (stdErr.length) {
4434
- reject(stdErr.join(""));
4435
- }
4436
- resolve(stdOut.join(""));
4437
- });
4438
- });
4439
- const getPlanRevisionsFromGit = async (planFilePath, terminal) => {
4440
- const command = terminal === terminals.bash ? `git rev-list --pretty="format:%H|%ad" HEAD ${planFilePath}` : `git rev-list --pretty="%H|%ad" HEAD ${planFilePath}`;
4441
- const stdOut = await exec(command, terminal);
4442
- const lines = stdOut.split(/\r\n|\r|\n/).filter((r) => r?.includes("|")).map((r) => r?.replace(/"/g, ""));
4443
- return lines.map((line) => {
4444
- const [version, timeStamp] = line.split("|");
4445
- const utcTimeStamp = new Date(timeStamp).toISOString();
4446
- return { version, timeStamp: utcTimeStamp };
4447
- });
4448
- };
4449
- const getPlanFromGit = async (planFilePath, revision, terminal) => {
4450
- return exec(`git show ${revision}:${planFilePath}`, terminal);
4451
- };
4452
- const getHistoricalPlansFromGit = async (planFilePath) => {
4453
- try {
4454
- const gitActive = gitAvailable();
4455
- if (!gitActive) {
4456
- throw new Error("git must be installed and in PATH");
4457
- }
4458
- const terminal = getTerminal();
4459
- const revisions = await getPlanRevisionsFromGit(planFilePath, terminal);
4460
- const historicalPlans = await Promise.all(
4461
- revisions.map(async (revision) => {
4462
- const plan = await getPlanFromGit(
4463
- planFilePath,
4464
- revision.version,
4465
- terminal
4466
- );
4467
- const version = hash(plan);
4468
- return {
4469
- revision,
4470
- version,
4471
- plan
4472
- };
4473
- })
4474
- );
4475
- return {
4476
- historicalPlans
4477
- };
4478
- } catch (error) {
4479
- console.error(chalk.red(error));
4480
- throw new Error("Unable to fetch plan.json history from git");
4481
- }
4482
- };
4483
-
4484
- const getExecutedMigrationsFromVersion = async (database, pgpHelpers, entity, directory, currentVersion, plannedVersion, plannedMigrations) => {
4485
- if (!currentVersion) {
4486
- return [];
4487
- }
4488
- if (currentVersion === plannedVersion) {
4489
- return plannedMigrations;
4490
- } else {
4491
- let planFromVersion = await getPlanFromVersion(
4492
- database,
4493
- entity,
4494
- currentVersion
4495
- );
4496
- if (planFromVersion === null) {
4497
- console.warn(
4498
- chalk.yellow(
4499
- `Version not found in ${entity}_version table, trying git history instead`
4500
- )
4501
- );
4502
- const planFilePath = `${directory}/plan.json`;
4503
- const { historicalPlans } = await getHistoricalPlansFromGit(planFilePath);
4504
- if (historicalPlans.length) {
4505
- await insertVersions(database, pgpHelpers, entity, historicalPlans);
4506
- planFromVersion = historicalPlans.find((p) => p.version === currentVersion)?.plan || null;
4507
- }
4508
- }
4509
- if (planFromVersion !== null) {
4510
- let migrationsFromHistory = null;
4511
- try {
4512
- migrationsFromHistory = JSON.parse(planFromVersion);
4513
- } catch {
4514
- throw new Error(
4515
- `Invalid record in ${entity}_version table (cannot parse JSON)`
4516
- );
4517
- }
4518
- if (!validatePlan(migrationsFromHistory)) {
4519
- throw new Error(
4520
- `Invalid plan in ${entity}_version table (does not match schema)`
4521
- );
4522
- } else {
4523
- return migrationsFromHistory;
4524
- }
4525
- } else {
4526
- console.error(chalk.red(historyError));
4527
- throw new Error(`Unable to migrate, could not find version history`);
4528
- }
4529
- }
4530
- };
4531
-
4532
- const shortHash = (hash) => hash ? hash.substring(0, 8) : "";
4533
- const getPendingMigrations = ({
4534
- plannedMigrations,
4535
- executedMigrations,
4536
- printPendingFileNames = false,
4537
- force
4538
- }) => {
4539
- const pendingMigrations = plannedMigrations.filter((m) => {
4540
- const executed = executedMigrations.find((e) => e?.fileName === m.fileName);
4541
- const skippedFileHashes = m?.skippedFileHashes;
4542
- const isSkippedAndPreviouslyExecuted = skippedFileHashes?.includes(
4543
- executed?.fileHash
4544
- );
4545
- return executed === void 0 || executed?.fileHash !== m?.fileHash && force && !isSkippedAndPreviouslyExecuted;
4546
- });
4547
- if (printPendingFileNames) {
4548
- pendingMigrations.forEach((m) => {
4549
- console.log(chalk.gray(` ${m.fileName} ${shortHash(m?.fileHash)}`));
4550
- });
4551
- }
4552
- return pendingMigrations.map((m) => ({
4553
- fileName: m.fileName,
4554
- migrator: m.migrator
4555
- }));
4556
- };
4557
- const getPendingMigrators = async ({ config }) => {
4558
- const {
4559
- directory,
4560
- database,
4561
- pgpHelpers,
4562
- entity,
4563
- version,
4564
- printPendingFileNames,
4565
- force
4566
- } = config;
4567
- const { plannedMigrations, nextVersion } = await PlanModule.getPlannedMigrations({
4568
- config
4569
- });
4570
- const executedMigrations = database ? await getExecutedMigrationsFromVersion(
4571
- database,
4572
- pgpHelpers,
4573
- entity,
4574
- directory,
4575
- version,
4576
- nextVersion,
4577
- plannedMigrations
4578
- ) : [];
4579
- const pendingMigrators = getPendingMigrations({
4580
- plannedMigrations,
4581
- executedMigrations,
4582
- printPendingFileNames,
4583
- force
4584
- });
4585
- return {
4586
- pendingMigrators,
4587
- nextVersion: plannedMigrations.length < executedMigrations.length ? version : nextVersion
4588
- };
4589
- };
4590
-
4591
- const migrate = async ({
4592
- payload,
4593
- config,
4594
- metaData
4595
- }) => {
4596
- const { pendingMigrators, nextVersion } = await getPendingMigrators({
4597
- config
4598
- });
4599
- return {
4600
- nextPayload: pendingMigrators.length ? PipeModule.pipe(pendingMigrators, payload, metaData) : payload,
4601
- nextVersion
4602
- };
4603
- };
4604
-
4605
- const MAX_ATTEMPTS = 3;
4606
- const migrateRecord = async ({
4607
- record,
4608
- config,
4609
- beforeMigrateRecord,
4610
- afterMigrateRecord
4611
- }) => {
4612
- const { dry } = config;
4613
- console.log(chalk.gray(` ${record.name}`));
4614
- try {
4615
- await config.database.tx(async (transaction) => {
4616
- const currentRecord = await getRecord(
4617
- transaction,
4618
- config.entityTableName,
4619
- config.entityColumnNames,
4620
- record.id
4621
- );
4622
- const {
4623
- [config.entityColumnNames.payload]: payload,
4624
- [config.entityColumnNames.etag]: etag,
4625
- [config.entityColumnNames.version]: currentVersion
4626
- } = currentRecord;
4627
- await beforeMigrateRecord({
4628
- currentRecord,
4629
- transaction,
4630
- dry
4631
- });
4632
- const { nextPayload: nextData, nextVersion } = await migrate({
4633
- payload,
4634
- config: {
4635
- ...config,
4636
- version: currentVersion,
4637
- printPendingFileNames: true
4638
- },
4639
- metaData: omit(currentRecord, [config.entityColumnNames.payload])
4640
- });
4641
- if (!dry) {
4642
- const nextRecord = await updateRecord(
4643
- transaction,
4644
- config?.entityTableName,
4645
- config?.entityColumnNames,
4646
- record.id,
4647
- currentVersion,
4648
- nextData,
4649
- nextVersion,
4650
- etag
4651
- );
4652
- if (!nextRecord) {
4653
- throw new Error(
4654
- "Failed to patch record with newest migration - The record was probably updated while migrating..."
4655
- );
4656
- }
4657
- await afterMigrateRecord({
4658
- currentRecord,
4659
- nextRecord,
4660
- transaction,
4661
- dry
4662
- });
4663
- }
4664
- });
4665
- return null;
4666
- } catch (error) {
4667
- const migrationErrorPayload = {
4668
- [config.entityColumnNames.id]: record.id,
4669
- [config.entityColumnNames.name]: record.name,
4670
- [config.entityColumnNames.created]: record.created,
4671
- error,
4672
- stackTrace: error.stack
4673
- };
4674
- console.log(
4675
- chalk.red(
4676
- ` ${capitalize(config.entity)} migration with id ${record.id} failed:
4677
- ${error.stack}`
4678
- )
4679
- );
4680
- return migrationErrorPayload;
4681
- }
4682
- };
4683
- const migrateRecords = async ({
4684
- recordList,
4685
- config,
4686
- beforeMigrateRecord,
4687
- afterMigrateRecord,
4688
- onMigrationErrors
4689
- }) => {
4690
- const { dry } = config;
4691
- const migrationErrors = [];
4692
- if (recordList.length) {
4693
- console.log(chalk.gray("Executing record migration scripts..."));
4694
- for await (const record of recordList) {
4695
- let attempt = 0;
4696
- while (attempt < MAX_ATTEMPTS) {
4697
- attempt += 1;
4698
- if (attempt > 1) {
4699
- console.log(chalk.gray("Retrying migration..."));
4700
- }
4701
- const migrationErrorPayload = await migrateRecord({
4702
- record,
4703
- config,
4704
- beforeMigrateRecord,
4705
- afterMigrateRecord
4706
- });
4707
- if (!migrationErrorPayload) {
4708
- break;
4709
- }
4710
- if (migrationErrorPayload && attempt === MAX_ATTEMPTS) {
4711
- migrationErrors.push(migrationErrorPayload);
4712
- }
4713
- }
4714
- }
4715
- }
4716
- if (migrationErrors.length) {
4717
- try {
4718
- await onMigrationErrors({
4719
- migrationErrors,
4720
- dry
4721
- });
4722
- } catch (error) {
4723
- console.log(
4724
- chalk.red(
4725
- `Handling errors for ${config.entity} migrations failed:
4726
- ${error.stack}`
4727
- )
4728
- );
4729
- }
4730
- console.log(
4731
- chalk.yellow(
4732
- `Completed ${config?.entity ?? "entity"} migrations (some failed)${config?.dry ? " [dry-run, no output written]" : ""} \u2713`
4733
- )
4734
- );
4735
- } else {
4736
- console.log(
4737
- chalk.green(
4738
- `Completed ${config?.entity ?? "entity"} migrations (success)${config?.dry ? " [dry-run, no output written]" : ""} \u2713`
4739
- )
4740
- );
4741
- }
4742
- };
4743
- const migrateAll = async ({
4744
- config,
4745
- beforeMigrateRecord,
4746
- afterMigrateRecord,
4747
- onMigrationErrors
4748
- }) => {
4749
- const { validatedPlan: latestPlan, nextVersion: latestVersion } = await getPlannedMigrations({
4750
- config
4751
- });
4752
- const recordList = await getRecordList(
4753
- config?.database,
4754
- config?.entity,
4755
- config?.entityTableName,
4756
- config?.entityColumnNames,
4757
- latestVersion,
4758
- latestPlan
4759
- );
4760
- await migrateRecords({
4761
- config,
4762
- recordList,
4763
- beforeMigrateRecord,
4764
- afterMigrateRecord,
4765
- onMigrationErrors
4766
- });
4767
- };
4768
-
4769
- const parsePlan = (plan) => {
4770
- return (() => {
4771
- try {
4772
- return JSON.parse(plan);
4773
- } catch {
4774
- console.error("Unable to parse plan.json");
4775
- return null;
4776
- }
4777
- })();
4778
- };
4779
- const printVersionHistory = async ({ config }) => {
4780
- const { database, entity, directory } = config;
4781
- try {
4782
- const planFilePath = `${directory}/plan.json`;
4783
- const versionHistoryFromDatabase = await getVersions(database, entity);
4784
- const fullDatabaseVersionHistory = versionHistoryFromDatabase.map((d) => {
4785
- const plan = parsePlan(d?.plan);
4786
- const finalMigration = plan?.length ? plan[plan.length - 1] : null;
4787
- return {
4788
- planVersion: d?.version,
4789
- lastFileName: finalMigration?.fileName || null,
4790
- lastSequence: finalMigration?.sequence || null
4791
- };
4792
- });
4793
- const { historicalPlans: fullHistoricalPlans } = await getHistoricalPlansFromGit(planFilePath);
4794
- const fullGitVersionHistory = fullHistoricalPlans.map((p) => {
4795
- const plan = parsePlan(p?.plan);
4796
- const finalMigration = plan?.length ? plan[plan.length - 1] : null;
4797
- return {
4798
- gitCommitHash: p?.revision?.version,
4799
- planVersion: p?.version,
4800
- timeStamp: p?.revision?.timeStamp,
4801
- lastFileName: finalMigration?.fileName || null,
4802
- lastSequence: finalMigration?.sequence || null
4803
- };
4804
- });
4805
- const output = {
4806
- fullDatabaseVersionHistory,
4807
- fullGitVersionHistory
4808
- };
4809
- console.log(JSON.stringify(output, null, 2));
4810
- } catch (error) {
4811
- console.error(chalk.red(error));
4812
- console.error(chalk.red(historyError));
4813
- throw new Error("Unable to print debug history");
4814
- }
4815
- };
4816
-
4817
- exports.createMigration = createMigration;
4818
- exports.getPlannedMigrations = getPlannedMigrations;
4819
- exports.getPlannedVersion = getPlannedVersion;
4820
- exports.getVersions = getVersions;
4821
- exports.migrate = migrate;
4822
- exports.migrateAll = migrateAll;
4823
- exports.pipe = pipe;
4824
- exports.printVersionHistory = printVersionHistory;