@prostojs/rewrite 0.0.4 → 0.1.1

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.
Files changed (37) hide show
  1. package/dist/index.cjs +3985 -0
  2. package/dist/{rewrite.d.ts → index.d.ts} +125 -147
  3. package/dist/index.mjs +3978 -0
  4. package/package.json +40 -43
  5. package/dist/rewrite.cjs.prod.js +0 -848
  6. package/dist/rewrite.esm-browser.prod.js +0 -1
  7. package/dist/rewrite.esm-bundler.js +0 -729
  8. package/dist/rewrite.global.prod.js +0 -1
  9. package/dist/src/__test__/html-parser.spec.d.ts +0 -2
  10. package/dist/src/__test__/html-parser.spec.d.ts.map +0 -1
  11. package/dist/src/__test__/mixed-parser.spec.d.ts +0 -2
  12. package/dist/src/__test__/mixed-parser.spec.d.ts.map +0 -1
  13. package/dist/src/__test__/rewriter.spec.d.ts +0 -2
  14. package/dist/src/__test__/rewriter.spec.d.ts.map +0 -1
  15. package/dist/src/__test__/strings.spec.d.ts +0 -2
  16. package/dist/src/__test__/strings.spec.d.ts.map +0 -1
  17. package/dist/src/__test__/text-parser.spec.d.ts +0 -2
  18. package/dist/src/__test__/text-parser.spec.d.ts.map +0 -1
  19. package/dist/src/constants.d.ts +0 -3
  20. package/dist/src/constants.d.ts.map +0 -1
  21. package/dist/src/files.d.ts +0 -8
  22. package/dist/src/files.d.ts.map +0 -1
  23. package/dist/src/index.d.ts +0 -18
  24. package/dist/src/index.d.ts.map +0 -1
  25. package/dist/src/rw-common.d.ts +0 -13
  26. package/dist/src/rw-common.d.ts.map +0 -1
  27. package/dist/src/rw-html-parser.d.ts +0 -17
  28. package/dist/src/rw-html-parser.d.ts.map +0 -1
  29. package/dist/src/rw-text-parser.d.ts +0 -31
  30. package/dist/src/rw-text-parser.d.ts.map +0 -1
  31. package/dist/src/string-expression.d.ts +0 -4
  32. package/dist/src/string-expression.d.ts.map +0 -1
  33. package/dist/src/types.d.ts +0 -96
  34. package/dist/src/types.d.ts.map +0 -1
  35. package/dist/src/utils.d.ts +0 -3
  36. package/dist/src/utils.d.ts.map +0 -1
  37. package/index.js +0 -2
package/dist/index.mjs ADDED
@@ -0,0 +1,3978 @@
1
+ const htmlVoidTags = [
2
+ 'area',
3
+ 'base',
4
+ 'br',
5
+ 'col',
6
+ 'command',
7
+ 'embed',
8
+ 'hr',
9
+ 'img',
10
+ 'input',
11
+ 'keygen',
12
+ 'link',
13
+ 'meta',
14
+ 'param',
15
+ 'source',
16
+ 'track',
17
+ 'wbr',
18
+ ];
19
+ const htmlTextTags = [
20
+ 'script',
21
+ 'style',
22
+ ];
23
+
24
+ async function readDir(dirPath) {
25
+ {
26
+ const path = await import('path');
27
+ const fs = await import('fs');
28
+ async function* getFiles(dir) {
29
+ const dirents = await fs.promises.readdir(dir, { withFileTypes: true });
30
+ for (const dirent of dirents) {
31
+ const res = path.resolve(dir, dirent.name);
32
+ if (dirent.isDirectory()) {
33
+ yield* getFiles(res);
34
+ }
35
+ else {
36
+ yield res;
37
+ }
38
+ }
39
+ }
40
+ return getFiles(dirPath);
41
+ }
42
+ }
43
+ async function readFile(filePath) {
44
+ {
45
+ const fs = await import('fs');
46
+ return new Promise((resolve, reject) => {
47
+ fs.exists(filePath, (yes) => {
48
+ if (yes) {
49
+ fs.readFile(filePath, (err, file) => {
50
+ if (err)
51
+ return reject(err);
52
+ resolve(file.toString());
53
+ });
54
+ }
55
+ else {
56
+ reject('File ' + filePath + ' does not exist.');
57
+ }
58
+ });
59
+ });
60
+ }
61
+ }
62
+ async function writeFile(targetPath, data) {
63
+ {
64
+ const path = await import('path');
65
+ const fs = await import('fs');
66
+ const dirname = path.dirname(targetPath);
67
+ await fs.promises.mkdir(dirname, { recursive: true });
68
+ await fs.promises.writeFile(targetPath, data);
69
+ return;
70
+ }
71
+ }
72
+ async function copyFile(filePath, targetPath) {
73
+ {
74
+ if (filePath === targetPath)
75
+ return;
76
+ const path = await import('path');
77
+ const fs = await import('fs');
78
+ const dirname = path.dirname(targetPath);
79
+ await fs.promises.mkdir(dirname, { recursive: true });
80
+ await fs.promises.copyFile(filePath, targetPath);
81
+ return;
82
+ }
83
+ }
84
+ async function pathResolve(p) {
85
+ {
86
+ const path = await import('path');
87
+ return path.resolve(p);
88
+ }
89
+ }
90
+ async function pathJoin(...parts) {
91
+ {
92
+ const path = await import('path');
93
+ return path.join(...parts);
94
+ }
95
+ }
96
+
97
+ const dim = '';
98
+ const reset = '';
99
+ class ProstoTree {
100
+ constructor(options) {
101
+ var _a, _b, _c, _d;
102
+ const label = (options === null || options === void 0 ? void 0 : options.label) || 'label';
103
+ const children = (options === null || options === void 0 ? void 0 : options.children) || 'children';
104
+ const branchWidth = typeof (options === null || options === void 0 ? void 0 : options.branchWidth) === 'number' ? options === null || options === void 0 ? void 0 : options.branchWidth : 2;
105
+ const hLine = (((_a = options === null || options === void 0 ? void 0 : options.branches) === null || _a === void 0 ? void 0 : _a.hLine) || '─').repeat(branchWidth - 1);
106
+ const branches = {
107
+ end: ((_b = options === null || options === void 0 ? void 0 : options.branches) === null || _b === void 0 ? void 0 : _b.end) || dim + '└',
108
+ middle: ((_c = options === null || options === void 0 ? void 0 : options.branches) === null || _c === void 0 ? void 0 : _c.middle) || dim + '├',
109
+ vLine: ((_d = options === null || options === void 0 ? void 0 : options.branches) === null || _d === void 0 ? void 0 : _d.vLine) || dim + '│',
110
+ hLine,
111
+ };
112
+ this.options = {
113
+ label: label,
114
+ children: children,
115
+ renderLabel: (options === null || options === void 0 ? void 0 : options.renderLabel) || (n => typeof n === 'string' ? n : n[label]),
116
+ branches,
117
+ branchWidth,
118
+ };
119
+ }
120
+ _render(root, opts) {
121
+ const { children, renderLabel } = this.options;
122
+ let s = `${renderLabel(root, '')}\n`;
123
+ const { end, middle, vLine, hLine } = this.options.branches;
124
+ const endBranch = end + hLine + reset + ' ';
125
+ const middleBranch = middle + hLine + reset + ' ';
126
+ const { branchWidth } = this.options;
127
+ if (root) {
128
+ treeNode(root);
129
+ }
130
+ function treeNode(node, behind = '', level = 1) {
131
+ const items = (node && node[children]);
132
+ const count = items && items.length || 0;
133
+ if (items) {
134
+ if ((opts === null || opts === void 0 ? void 0 : opts.level) && opts.level < level) {
135
+ s += behind + endBranch + renderCollapsedChildren(items.length) + '\n';
136
+ }
137
+ else {
138
+ let itemsToRender = items;
139
+ const collapsedCount = Math.max(0, count - ((opts === null || opts === void 0 ? void 0 : opts.childrenLimit) || count));
140
+ if ((opts === null || opts === void 0 ? void 0 : opts.childrenLimit) && count > opts.childrenLimit) {
141
+ itemsToRender = opts.showLast ? items.slice(count - opts.childrenLimit) : items.slice(0, opts.childrenLimit);
142
+ }
143
+ if (collapsedCount && (opts === null || opts === void 0 ? void 0 : opts.showLast))
144
+ s += behind + middleBranch + renderCollapsedChildren(collapsedCount) + '\n';
145
+ itemsToRender.forEach((childNode, i) => {
146
+ const last = i + 1 === count;
147
+ const branch = last ? endBranch : middleBranch;
148
+ const nextBehind = behind + (last ? ' ' : vLine) + ' '.repeat(branchWidth);
149
+ s += behind + branch + renderLabel(childNode, nextBehind) + '\n';
150
+ if (typeof childNode === 'object') {
151
+ treeNode(childNode, nextBehind, level + 1);
152
+ }
153
+ });
154
+ if (collapsedCount && !(opts === null || opts === void 0 ? void 0 : opts.showLast))
155
+ s += behind + endBranch + renderCollapsedChildren(collapsedCount) + '\n';
156
+ }
157
+ }
158
+ }
159
+ return s;
160
+ }
161
+ render(root, opts) {
162
+ return this._render(root, opts);
163
+ }
164
+ print(root, opts) {
165
+ const s = this.render(root, opts);
166
+ console.log(s);
167
+ return s;
168
+ }
169
+ }
170
+ function renderCollapsedChildren(count) {
171
+ return dim + '+ ' + '' + count.toString() + ` item${count === 1 ? '' : 's'}` + reset;
172
+ }
173
+
174
+ function renderCodeFragment(lines, options) {
175
+ const row = (options.row || 1) - 1;
176
+ const rowEnd = options.rowEnd ? options.rowEnd - 1 : -1;
177
+ const limit = Math.min(options.limit || 6, lines.length);
178
+ const offset = Math.min(options.offset || 3, lines.length);
179
+ const error = options.error;
180
+ const errorEnd = options.errorEnd;
181
+ let output = '';
182
+ const delta = rowEnd - row;
183
+ const maxIndex = lines.length;
184
+ if (delta > limit) {
185
+ let longestLine = 0;
186
+ const newLimit = Math.floor(limit / 2);
187
+ for (let i = 0; i < newLimit + offset; i++) {
188
+ const index = row + i - offset;
189
+ const line = lines[index] || '';
190
+ longestLine = Math.max(line.length, longestLine);
191
+ output += renderLine(line, index < maxIndex ? index + 1 : '', index === row ? error : undefined, index === row || index === rowEnd ? 'bold' : '');
192
+ }
193
+ let output2 = '';
194
+ for (let i = newLimit + offset; i > 0; i--) {
195
+ const index = rowEnd - i + offset;
196
+ const line = lines[index] || '';
197
+ longestLine = Math.max(line.length, longestLine);
198
+ output2 += renderLine(line, index < maxIndex ? index + 1 : '', index === rowEnd ? errorEnd : undefined, index === row || index === rowEnd ? 'bold' : '');
199
+ }
200
+ output += renderLine('—'.repeat(longestLine), '———', undefined, 'dim') + output2;
201
+ }
202
+ else {
203
+ for (let i = 0; i < limit + offset; i++) {
204
+ const index = row + i - offset;
205
+ if (index <= lines.length + 1) {
206
+ const errorCol = index === row ? error : index === rowEnd ? errorEnd : undefined;
207
+ output += renderLine(lines[index], index < maxIndex ? index + 1 : '', errorCol, index === row || index === rowEnd ? 'bold' : '');
208
+ }
209
+ }
210
+ }
211
+ return output;
212
+ }
213
+ function lineStyles(s) {
214
+ return '' + (s || '')
215
+ .replace(/([a-z_]+)/ig, '' + '$1' + '\x1b[39;33m')
216
+ .replace(/([\=\.\/'"`\:\+]+)/ig, '' + '$1' + '');
217
+ }
218
+ function lineStylesError(s) {
219
+ return '' + (s || '') + '';
220
+ }
221
+ function renderLine(line, index, error, style = '') {
222
+ const st = (style === 'bold' ? '' : '') + (style === 'dim' ? '' : '');
223
+ if (typeof error === 'number') {
224
+ const errorLength = (/[\.-\s\(\)\*\/\+\{\}\[\]\?\'\"\`\<\>]/.exec(line.slice(error + 1)) || { index: line.length - error }).index + 1;
225
+ return renderLineNumber(index, true) +
226
+ st +
227
+ lineStyles(line.slice(0, error)) +
228
+ lineStylesError(line.slice(error, error + errorLength)) +
229
+ lineStyles(line.slice(error + errorLength)) +
230
+ renderLineNumber('', true) + ' '.repeat(error) + '' + '' + '~'.repeat(Math.max(1, errorLength));
231
+ }
232
+ return renderLineNumber(index, undefined, style === 'bold') + st + lineStyles(line);
233
+ }
234
+ function renderLineNumber(i, isError = false, bold = false) {
235
+ let s = ' ';
236
+ const sep = i === '———';
237
+ if (i && i > 0 || typeof i === 'string') {
238
+ s = ' ' + String(i);
239
+ }
240
+ s = s.slice(s.length - 5);
241
+ return '\n' + '' + (sep ? '' : '') +
242
+ (isError ? '' + '' : (bold ? '' : '')) +
243
+ s + (sep ? i : ' | ') + '';
244
+ }
245
+
246
+ function escapeRegex$1(s) {
247
+ return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
248
+ }
249
+
250
+ class ProstoParserNodeBase {
251
+ addRecognizes(...args) {
252
+ for (const node of args) {
253
+ if (!this.options.recognizes)
254
+ this.options.recognizes = [];
255
+ if (!this.options.recognizes.includes(node)) {
256
+ this.options.recognizes.push(node);
257
+ }
258
+ }
259
+ return this;
260
+ }
261
+ addAbsorbs(node, rule = 'append') {
262
+ this.options.absorbs = this.options.absorbs || {};
263
+ if (Array.isArray(node)) {
264
+ node.forEach(n => {
265
+ this.options.absorbs[n.id] = rule;
266
+ this.addRecognizes(n);
267
+ });
268
+ }
269
+ else {
270
+ this.options.absorbs[node.id] = rule;
271
+ this.addRecognizes(node);
272
+ }
273
+ return this;
274
+ }
275
+ addPopsAfterNode(...args) {
276
+ for (const node of args) {
277
+ if (!this.options.popsAfterNode)
278
+ this.options.popsAfterNode = [];
279
+ if (!this.options.popsAfterNode.includes(node)) {
280
+ this.options.popsAfterNode.push(node);
281
+ }
282
+ }
283
+ this.addRecognizes(...args);
284
+ return this;
285
+ }
286
+ addHoistChildren(...args) {
287
+ if (!this.options.hoistChildren)
288
+ this.options.hoistChildren = [];
289
+ this.options.hoistChildren.push(...args);
290
+ return this;
291
+ }
292
+ set icon(value) {
293
+ this.options.icon = value;
294
+ }
295
+ set label(value) {
296
+ this.options.label = value;
297
+ }
298
+ get startsWith() {
299
+ return this.options.startsWith;
300
+ }
301
+ set startsWith(value) {
302
+ this.options.startsWith = value;
303
+ }
304
+ get endsWith() {
305
+ return this.options.endsWith;
306
+ }
307
+ set endsWith(value) {
308
+ this.options.endsWith = value;
309
+ }
310
+ getPopsAtEOFSource() {
311
+ return this.options.popsAtEOFSource;
312
+ }
313
+ popsAtEOFSource(value) {
314
+ this.options.popsAtEOFSource = value;
315
+ return this;
316
+ }
317
+ get absorbs() {
318
+ return this.options.absorbs;
319
+ }
320
+ get badToken() {
321
+ return this.options.badToken;
322
+ }
323
+ set badToken(value) {
324
+ this.options.badToken = value;
325
+ }
326
+ get skipToken() {
327
+ return this.options.skipToken;
328
+ }
329
+ set skipToken(value) {
330
+ this.options.skipToken = value;
331
+ }
332
+ get recognizes() {
333
+ return this.options.recognizes || [];
334
+ }
335
+ set recognizes(value) {
336
+ this.options.recognizes = value;
337
+ }
338
+ get hoistChildren() {
339
+ return this.options.hoistChildren || [];
340
+ }
341
+ set hoistChildren(value) {
342
+ this.options.hoistChildren = value;
343
+ }
344
+ getMapContent() {
345
+ return this.options.mapContent;
346
+ }
347
+ mapContent(key, value = 'copy') {
348
+ this.options.mapContent = this.options.mapContent || {};
349
+ this.options.mapContent[key] = value;
350
+ return this;
351
+ }
352
+ onMatch(value) {
353
+ this.options.onMatch = value;
354
+ return this;
355
+ }
356
+ onAppendContent(value) {
357
+ this.options.onAppendContent = value;
358
+ return this;
359
+ }
360
+ onAfterChildParse(value) {
361
+ this.options.onAfterChildParse = value;
362
+ return this;
363
+ }
364
+ onBeforeChildParse(value) {
365
+ this.options.onBeforeChildParse = value;
366
+ return this;
367
+ }
368
+ onMatchStartToken(value) {
369
+ if (this.options.startsWith) {
370
+ this.options.startsWith.onMatchToken = value;
371
+ }
372
+ return this;
373
+ }
374
+ onMatchEndToken(value) {
375
+ if (this.options.endsWith) {
376
+ this.options.endsWith.onMatchToken = value;
377
+ }
378
+ return this;
379
+ }
380
+ initCustomData(value) {
381
+ this.options.initCustomData = value;
382
+ return this;
383
+ }
384
+ onPop(value) {
385
+ this.options.onPop = value;
386
+ return this;
387
+ }
388
+ get popsAfterNode() {
389
+ return this.options.popsAfterNode || [];
390
+ }
391
+ set popsAfterNode(nodes) {
392
+ this.options.popsAfterNode = nodes;
393
+ }
394
+ clearStartsWith() {
395
+ delete this.options.startsWith;
396
+ return this;
397
+ }
398
+ clearEndsWith() {
399
+ delete this.options.endsWith;
400
+ return this;
401
+ }
402
+ clearPopsAtEOFSource() {
403
+ delete this.options.popsAtEOFSource;
404
+ return this;
405
+ }
406
+ clearBadToken() {
407
+ delete this.options.badToken;
408
+ return this;
409
+ }
410
+ clearSkipToken() {
411
+ delete this.options.skipToken;
412
+ return this;
413
+ }
414
+ clearAbsorbs(node) {
415
+ if (this.options.absorbs) {
416
+ if (node && Array.isArray(node)) {
417
+ for (const n of node) {
418
+ delete this.options.absorbs[n.id];
419
+ }
420
+ }
421
+ else if (node) {
422
+ delete this.options.absorbs[node.id];
423
+ }
424
+ else {
425
+ this.options.absorbs = {};
426
+ }
427
+ }
428
+ return this;
429
+ }
430
+ clearRecognizes(...args) {
431
+ var _a;
432
+ if (args.length) {
433
+ this.options.recognizes = (_a = this.options.recognizes) === null || _a === void 0 ? void 0 : _a.filter(n => !args.includes(n));
434
+ }
435
+ else {
436
+ this.options.recognizes = [];
437
+ }
438
+ return this;
439
+ }
440
+ clearHoistChildren() {
441
+ delete this.options.hoistChildren;
442
+ return this;
443
+ }
444
+ clearMapContent() {
445
+ delete this.options.mapContent;
446
+ return this;
447
+ }
448
+ removeOnPop() {
449
+ delete this.options.onPop;
450
+ return this;
451
+ }
452
+ removeOnMatch() {
453
+ delete this.options.onMatch;
454
+ return this;
455
+ }
456
+ removeOnAppendContent() {
457
+ delete this.options.onAppendContent;
458
+ return this;
459
+ }
460
+ removeOnBeforeChildParse() {
461
+ delete this.options.onBeforeChildParse;
462
+ return this;
463
+ }
464
+ removeOnAfterChildParse() {
465
+ delete this.options.onAfterChildParse;
466
+ return this;
467
+ }
468
+ fireNodeMatched(matched, cbData) {
469
+ return this.options.startsWith ? this.fireMatched(this.options.startsWith, matched, cbData) : { confirmed: true };
470
+ }
471
+ fireNodeEndMatched(matched, cbData) {
472
+ return this.options.endsWith ? this.fireMatched(this.options.endsWith, matched, cbData) : { confirmed: true };
473
+ }
474
+ fireMatched(descr, matched, cbData) {
475
+ const { omit, eject, onMatchToken } = descr;
476
+ let cbResult = true;
477
+ if (onMatchToken) {
478
+ cbResult = onMatchToken({
479
+ ...cbData,
480
+ matched,
481
+ });
482
+ }
483
+ const cbOmit = typeof cbResult === 'object' ? cbResult.omit : undefined;
484
+ const cbEject = typeof cbResult === 'object' ? cbResult.eject : undefined;
485
+ return {
486
+ omit: cbOmit !== undefined ? cbOmit : omit,
487
+ eject: cbEject !== undefined ? cbEject : eject,
488
+ confirmed: cbResult !== false,
489
+ };
490
+ }
491
+ getStartTokenRg() {
492
+ return this.getRgOutOfTokenDescriptor(this.options.startsWith);
493
+ }
494
+ getEndTokenRg() {
495
+ return this.getRgOutOfTokenDescriptor(this.options.endsWith);
496
+ }
497
+ getConstraintTokens() {
498
+ return {
499
+ skip: this.getRgOutOfTokenDescriptor(this.options.skipToken ? { token: this.options.skipToken } : undefined) || undefined,
500
+ bad: this.getRgOutOfTokenDescriptor(this.options.badToken ? { token: this.options.badToken } : undefined) || undefined,
501
+ };
502
+ }
503
+ getRgOutOfTokenDescriptor(descr) {
504
+ if (descr) {
505
+ const prefix = descr.ignoreBackSlashed ? /(?<=(?:^|[^\\])(?:\\\\)*)/.source : '';
506
+ let token;
507
+ if (typeof descr.token === 'function') {
508
+ token = descr.token(this);
509
+ }
510
+ else {
511
+ token = descr.token;
512
+ }
513
+ if (token instanceof RegExp) {
514
+ return new RegExp(prefix + token.source, token.flags);
515
+ }
516
+ else {
517
+ return new RegExp(`${prefix}(?:${[token].flat().map(t => escapeRegex$1(t)).join('|')})`);
518
+ }
519
+ }
520
+ }
521
+ }
522
+
523
+ class ProstoHoistManager {
524
+ constructor() {
525
+ this.data = {};
526
+ }
527
+ addHoistOptions(ctx) {
528
+ if (ctx.hoistChildren) {
529
+ ctx.hoistChildren.forEach(options => {
530
+ const nodeId = typeof options.node === 'object' ? options.node.id : options.node;
531
+ const hoist = this.data[nodeId] = (this.data[nodeId] || {});
532
+ if (hoist) {
533
+ hoist[ctx.index] = {
534
+ options,
535
+ context: ctx,
536
+ };
537
+ }
538
+ });
539
+ }
540
+ }
541
+ removeHoistOptions(ctx) {
542
+ if (ctx.hoistChildren) {
543
+ ctx.hoistChildren.forEach(options => {
544
+ const nodeId = typeof options.node === 'object' ? options.node.id : options.node;
545
+ const hoist = this.data[nodeId];
546
+ if (hoist) {
547
+ delete hoist[ctx.index];
548
+ }
549
+ });
550
+ }
551
+ }
552
+ processHoistOptions(ctx) {
553
+ const id = ctx.node.id;
554
+ const hoist = this.data[id];
555
+ if (hoist) {
556
+ Object.keys(hoist).map(i => hoist[i]).forEach(({ options, context }) => {
557
+ const customData = context.getCustomData();
558
+ if (options.deep === true || Number(options.deep) >= (ctx.level - context.level)) {
559
+ if (options.asArray) {
560
+ const hoisted = customData[options.as] = (customData[options.as] || []);
561
+ if (!Array.isArray(hoisted)) {
562
+ if (!options.onConflict || options.onConflict === 'error') {
563
+ throw new Error(`Can not hoist "${ctx.node.name}" to "${context.node.name}" as "${options.as}". "${options.as}" already exists and it is not an Array Type.`);
564
+ }
565
+ else if (options.onConflict === 'overwrite') {
566
+ customData[options.as] = [doTheMapRule(options, ctx)];
567
+ }
568
+ else if (options.onConflict !== 'ignore') {
569
+ throw new Error(`Unsupported hoisting option onConflict "${options.onConflict}"`);
570
+ }
571
+ }
572
+ else {
573
+ hoisted.push(doTheMapRule(options, ctx));
574
+ }
575
+ }
576
+ else {
577
+ if (customData[options.as]) {
578
+ if (!options.onConflict || options.onConflict === 'error') {
579
+ throw new Error(`Can not hoist multiple "${ctx.node.name}" to "${context.node.name}" as "${options.as}". "${options.as}" already exists.`);
580
+ }
581
+ else if (options.onConflict === 'overwrite') {
582
+ customData[options.as] = doTheMapRule(options, ctx);
583
+ }
584
+ else if (options.onConflict !== 'ignore') {
585
+ throw new Error(`Unsupported hoisting option onConflict "${options.onConflict}"`);
586
+ }
587
+ }
588
+ else {
589
+ customData[options.as] = doTheMapRule(options, ctx);
590
+ }
591
+ }
592
+ if (options.removeChildFromContent) {
593
+ context.content = context.content.filter(c => c !== ctx);
594
+ }
595
+ }
596
+ });
597
+ }
598
+ function doTheMapRule(options, ctx) {
599
+ var _a;
600
+ if (typeof options.mapRule === 'function') {
601
+ return options.mapRule(ctx);
602
+ }
603
+ if (options.mapRule === 'content.join') {
604
+ return ctx.content.join('');
605
+ }
606
+ if ((_a = options.mapRule) === null || _a === void 0 ? void 0 : _a.startsWith('customData')) {
607
+ const key = options.mapRule.slice(11);
608
+ if (key) {
609
+ return ctx.getCustomData()[key];
610
+ }
611
+ else {
612
+ return ctx.getCustomData();
613
+ }
614
+ }
615
+ return ctx;
616
+ }
617
+ }
618
+ }
619
+
620
+ const banner = '' + '[parser]' + '';
621
+ class ProstoParserContext {
622
+ constructor(root) {
623
+ this.root = root;
624
+ this.nodes = {};
625
+ this.pos = 0;
626
+ this.index = 0;
627
+ this.behind = '';
628
+ this.here = '';
629
+ this.src = '';
630
+ this.stack = [];
631
+ this.l = 0;
632
+ this.hoistManager = new ProstoHoistManager();
633
+ this.context = root;
634
+ }
635
+ parse(src) {
636
+ this.src = src,
637
+ this.here = src,
638
+ this.l = src.length;
639
+ const cache = {};
640
+ while (this.pos < this.l) {
641
+ const searchTokens = this.context.getSearchTokens();
642
+ let closestIndex = Number.MAX_SAFE_INTEGER;
643
+ let closestToken;
644
+ let matched;
645
+ for (const t of searchTokens) {
646
+ const key = t.g.source;
647
+ t.g.lastIndex = this.pos;
648
+ let cached = cache[key];
649
+ if (cached === null)
650
+ continue;
651
+ if (cached && cached.index < this.pos) {
652
+ cached = null;
653
+ delete cache[key];
654
+ }
655
+ if (!cached) {
656
+ cached = t.g.exec(this.src);
657
+ if (cached || (this.pos === 0 && !cached)) {
658
+ cache[key] = cached;
659
+ }
660
+ }
661
+ if (cached && cached.index < closestIndex) {
662
+ closestIndex = cached.index;
663
+ matched = cached;
664
+ closestToken = t;
665
+ if (closestIndex === this.pos)
666
+ break;
667
+ }
668
+ }
669
+ if (closestToken && matched) {
670
+ const toAppend = this.src.slice(this.pos, closestIndex);
671
+ if (toAppend) {
672
+ this.context.appendContent(toAppend);
673
+ this.jump(toAppend.length);
674
+ }
675
+ const matchedToken = matched[0];
676
+ if (closestToken.node) {
677
+ const { omit, eject, confirmed } = closestToken.node.fireNodeMatched(matched, this.getCallbackData(matched));
678
+ if (!confirmed)
679
+ continue;
680
+ let toAppend = '';
681
+ if (eject) {
682
+ this.context.appendContent(matchedToken);
683
+ }
684
+ else if (!omit) {
685
+ toAppend = matchedToken;
686
+ }
687
+ this.jump(matchedToken.length);
688
+ this.pushNewContext(closestToken.node, toAppend ? [toAppend] : []);
689
+ this.context.fireOnMatch(matched);
690
+ continue;
691
+ }
692
+ else {
693
+ const { omit, eject, confirmed } = this.context.fireNodeEndMatched(matched, this.getCallbackData(matched));
694
+ if (!confirmed)
695
+ continue;
696
+ if (!eject && !omit) {
697
+ this.context.appendContent(matchedToken);
698
+ }
699
+ if (!eject) {
700
+ this.jump(matchedToken.length);
701
+ }
702
+ this.context.mapNamedGroups(matched);
703
+ this.pop();
704
+ continue;
705
+ }
706
+ }
707
+ else {
708
+ this.context.appendContent(this.here);
709
+ this.jump(this.here.length);
710
+ }
711
+ }
712
+ if (this.context !== this.root) {
713
+ while (this.context.getPopsAtEOFSource() && this.stack.length > 0)
714
+ this.pop();
715
+ }
716
+ if (this.context !== this.root) {
717
+ this.panicBlock(`Unexpected end of the source string while parsing "${this.context.node.name}" (${this.context.index}) node.`);
718
+ }
719
+ return this.root;
720
+ }
721
+ pop() {
722
+ const parentContext = this.stack.pop();
723
+ this.context.fireOnPop();
724
+ if (parentContext) {
725
+ parentContext.fireAfterChildParse(this.context);
726
+ parentContext.fireAbsorb(this.context);
727
+ this.context.cleanup();
728
+ const node = this.context.node;
729
+ this.context = parentContext;
730
+ if (parentContext.popsAfterNode.includes(node)) {
731
+ this.pop();
732
+ }
733
+ }
734
+ else {
735
+ this.context.cleanup();
736
+ }
737
+ }
738
+ pushNewContext(newNode, content) {
739
+ this.index++;
740
+ const ctx = newNode.createContext(this.index, this.stack.length + 1, this);
741
+ ctx.content = content;
742
+ this.context.fireBeforeChildParse(ctx);
743
+ this.context.pushChild(ctx);
744
+ this.stack.push(this.context);
745
+ this.hoistManager.addHoistOptions(this.context);
746
+ this.context = ctx;
747
+ return ctx;
748
+ }
749
+ fromStack(depth = 0) {
750
+ return this.stack[this.stack.length - depth - 1];
751
+ }
752
+ jump(n = 1) {
753
+ this.pos += n;
754
+ this.behind = this.src.slice(0, this.pos);
755
+ this.here = this.src.slice(this.pos, this.l);
756
+ return this.pos;
757
+ }
758
+ getCallbackData(matched) {
759
+ return {
760
+ parserContext: this,
761
+ context: this.context,
762
+ matched,
763
+ customData: this.context.getCustomData(),
764
+ };
765
+ }
766
+ getPosition(offset = 0) {
767
+ var _a;
768
+ const past = this.src.slice(0, this.pos + offset).split('\n');
769
+ const row = past.length;
770
+ const col = ((_a = past.pop()) === null || _a === void 0 ? void 0 : _a.length) || 0;
771
+ return {
772
+ row, col, pos: this.pos,
773
+ };
774
+ }
775
+ panic(message, errorBackOffset = 0) {
776
+ if (this.pos > 0) {
777
+ const { row, col } = this.getPosition(-errorBackOffset);
778
+ console.error(banner + '', message, '');
779
+ console.log(this.context.toTree({ childrenLimit: 5, showLast: true, level: 1 }));
780
+ console.error(renderCodeFragment(this.src.split('\n'), {
781
+ row: row,
782
+ error: col,
783
+ }));
784
+ }
785
+ throw new Error(message);
786
+ }
787
+ panicBlock(message, topBackOffset = 0, bottomBackOffset = 0) {
788
+ if (this.pos > 0) {
789
+ const { row, col } = this.getPosition(-bottomBackOffset);
790
+ console.error(banner + '', message, '');
791
+ console.log(this.context.toTree({ childrenLimit: 13, showLast: true, level: 12 }));
792
+ console.error(renderCodeFragment(this.src.split('\n'), {
793
+ row: this.context.startPos.row,
794
+ error: this.context.startPos.col - topBackOffset,
795
+ rowEnd: row,
796
+ errorEnd: col,
797
+ }));
798
+ }
799
+ throw new Error(message);
800
+ }
801
+ }
802
+
803
+ const styles = {
804
+ banner: (s) => '' + s + '',
805
+ text: (s) => '' + s + '',
806
+ valuesDim: (s) => '' + '' + s + '' + '',
807
+ boolean: (s) => '' + s + '',
808
+ booleanDim: (s) => '' + '' + s + '' + '',
809
+ underscore: (s) => '' + s + '',
810
+ values: (s) => (typeof s === 'string' ? '' : '') + cut(s.toString(), 30) + '',
811
+ nodeDim: (s) => '' + '' + s + '' + '',
812
+ node: (s) => '' + s + '',
813
+ };
814
+ const stringOutputLimit = 70;
815
+ const parserTree = new ProstoTree({
816
+ children: 'content',
817
+ renderLabel: (context) => {
818
+ if (typeof context === 'string') {
819
+ return styles.text('«' + cut(context, stringOutputLimit) + '' + '»');
820
+ }
821
+ else if (typeof context === 'object' && context instanceof ProstoParserNodeContext) {
822
+ let keys = '';
823
+ const data = context.getCustomData();
824
+ Object.keys(data).forEach(key => {
825
+ const val = data[key];
826
+ if (typeof val === 'string' || typeof val === 'number') {
827
+ keys += ' ' + styles.valuesDim(key + '(') + styles.values(val) + styles.valuesDim(')');
828
+ }
829
+ else if (Array.isArray(val)) {
830
+ keys += ' ' + styles.valuesDim(key + `[${val.length}]`);
831
+ }
832
+ else if (typeof val === 'object') {
833
+ keys += ' ' + styles.valuesDim(`{ ${key} }`);
834
+ }
835
+ else if (typeof val === 'boolean' && val) {
836
+ const st = key ? styles.boolean : styles.booleanDim;
837
+ keys += ' ' + `${styles.underscore(st(key))}${st(val ? '☑' : '☐')}`;
838
+ }
839
+ });
840
+ return styles.node(context.icon + (context.label ? ' ' : '')) + styles.nodeDim(context.label) + keys;
841
+ }
842
+ return '';
843
+ },
844
+ });
845
+ function cut(s, n) {
846
+ const c = s.replace(/\n/g, '\\n');
847
+ if (c.length <= n)
848
+ return c;
849
+ return c.slice(0, n) + '' + '…';
850
+ }
851
+
852
+ class ProstoParserNodeContext extends ProstoParserNodeBase {
853
+ constructor(_node, index, level, parserContext) {
854
+ super();
855
+ this._node = _node;
856
+ this.index = index;
857
+ this.level = level;
858
+ this.content = [];
859
+ this._customData = {};
860
+ this.hasNodes = [];
861
+ this.count = {};
862
+ this.mapContentRules = {
863
+ 'first': (content) => content[0],
864
+ 'shift': (content) => content.shift(),
865
+ 'pop': (content) => content.pop(),
866
+ 'last': (content) => content[content.length - 1],
867
+ 'join': (content) => content.join(''),
868
+ 'join-clear': (content) => content.splice(0).join(''),
869
+ 'copy': (content) => content,
870
+ };
871
+ this.options = _node.getOptions();
872
+ if (this.options.initCustomData) {
873
+ this._customData = this.options.initCustomData();
874
+ }
875
+ this._label = this.options.label || '';
876
+ this._icon = this.options.icon || '◦';
877
+ this.parserContext = parserContext || new ProstoParserContext(this);
878
+ if (parserContext) {
879
+ this.parent = parserContext.context || parserContext.root;
880
+ }
881
+ this.startPos = this.parserContext.getPosition();
882
+ this.endPos = this.parserContext.getPosition();
883
+ }
884
+ getOptions() {
885
+ return this.options;
886
+ }
887
+ extractCustomDataTree() {
888
+ let content = this.content;
889
+ if (this.contentCopiedTo) {
890
+ content = this.customData[this.contentCopiedTo];
891
+ }
892
+ if (Array.isArray(content)) {
893
+ return content.map(c => {
894
+ if (typeof c === 'string') {
895
+ return c;
896
+ }
897
+ else {
898
+ return extract(c);
899
+ }
900
+ });
901
+ }
902
+ else {
903
+ const c = content;
904
+ if (c instanceof ProstoParserNodeContext) {
905
+ return extract(c);
906
+ }
907
+ else {
908
+ return content;
909
+ }
910
+ }
911
+ function extract(c) {
912
+ const cd = { ...c.getCustomData() };
913
+ if (c.contentCopiedTo) {
914
+ cd[c.contentCopiedTo] = c.extractCustomDataTree();
915
+ }
916
+ return cd;
917
+ }
918
+ }
919
+ getPrevNode(n = 1) {
920
+ if (this.parent) {
921
+ const index = this.parent.content.findIndex(n => n === this) - n;
922
+ if (index >= 0)
923
+ return this.parent.content[index];
924
+ }
925
+ }
926
+ getPrevContext(n = 1) {
927
+ if (this.parent) {
928
+ const contexts = this.parent.content.filter(n => n instanceof ProstoParserNodeContext);
929
+ const index = contexts.findIndex(n => n === this) - n;
930
+ if (index >= 0)
931
+ return contexts[index];
932
+ }
933
+ }
934
+ set icon(value) {
935
+ this._icon = value;
936
+ }
937
+ get icon() {
938
+ return this._icon;
939
+ }
940
+ set label(value) {
941
+ this._label = value;
942
+ }
943
+ get label() {
944
+ return this._label;
945
+ }
946
+ getCustomData() {
947
+ return this._customData;
948
+ }
949
+ get customData() {
950
+ return this._customData;
951
+ }
952
+ get nodeId() {
953
+ return this._node.id;
954
+ }
955
+ get node() {
956
+ return this._node;
957
+ }
958
+ toTree(options) {
959
+ return parserTree.render(this, options);
960
+ }
961
+ getSearchTokens() {
962
+ var _a;
963
+ const rg = this.getEndTokenRg();
964
+ const tokens = rg ? [{
965
+ rg,
966
+ y: addFlag(rg, 'y'),
967
+ g: addFlag(rg, 'g'),
968
+ }] : [];
969
+ (_a = this.options.recognizes) === null || _a === void 0 ? void 0 : _a.forEach(node => {
970
+ const rg = node.getStartTokenRg();
971
+ if (rg) {
972
+ tokens.push({
973
+ rg,
974
+ y: addFlag(rg, 'y'),
975
+ g: addFlag(rg, 'g'),
976
+ node,
977
+ });
978
+ }
979
+ });
980
+ function addFlag(rg, f) {
981
+ return new RegExp(rg.source, rg.flags + f);
982
+ }
983
+ return tokens;
984
+ }
985
+ appendContent(input) {
986
+ let s = input;
987
+ this.endPos = this.parserContext.getPosition();
988
+ let { skip, bad } = this.getConstraintTokens();
989
+ skip = skip ? new RegExp(skip.source, skip.flags + 'g') : skip;
990
+ bad = bad ? new RegExp(bad.source, bad.flags + 'g') : bad;
991
+ if (skip) {
992
+ s = s.replace(skip, '');
993
+ }
994
+ if (bad) {
995
+ const m = bad.exec(s);
996
+ if (m) {
997
+ this.parserContext.jump(m.index);
998
+ this.parserContext.panic(`The token "${m[0].replace(/"/g, '\\"')}" is not allowed in "${this.node.name}".`);
999
+ }
1000
+ }
1001
+ s = this.fireOnAppendContent(s);
1002
+ if (s) {
1003
+ this.content.push(s);
1004
+ }
1005
+ }
1006
+ cleanup() {
1007
+ this.options = null;
1008
+ }
1009
+ pushChild(child) {
1010
+ const absorbRule = this.options.absorbs && this.options.absorbs[child.node.id];
1011
+ if (!absorbRule) {
1012
+ this.content.push(child);
1013
+ }
1014
+ }
1015
+ fireAbsorb(child) {
1016
+ const absorbRule = this.options.absorbs && this.options.absorbs[child.node.id];
1017
+ if (absorbRule) {
1018
+ switch (absorbRule) {
1019
+ case 'append':
1020
+ this.content.push(...child.content);
1021
+ break;
1022
+ case 'join':
1023
+ this.appendContent(child.content.join(''));
1024
+ break;
1025
+ default:
1026
+ const [action, target] = absorbRule.split('->');
1027
+ const cd = this.getCustomData();
1028
+ if (action === 'copy') {
1029
+ cd[target] = child.content;
1030
+ }
1031
+ else if (action === 'join') {
1032
+ cd[target] = child.content.join('');
1033
+ }
1034
+ else {
1035
+ this.parserContext.panic(`Absorb action "${action}" is not supported.`);
1036
+ }
1037
+ }
1038
+ }
1039
+ }
1040
+ has(node) {
1041
+ return this.hasNodes.includes(node);
1042
+ }
1043
+ countOf(node) {
1044
+ return this.count[node.id] || 0;
1045
+ }
1046
+ mapNamedGroups(matched) {
1047
+ if (matched.groups) {
1048
+ const cd = this.getCustomData();
1049
+ for (const [key, value] of Object.entries(matched.groups)) {
1050
+ if (key === 'content') {
1051
+ this.appendContent(value);
1052
+ }
1053
+ else {
1054
+ cd[key] = value;
1055
+ }
1056
+ }
1057
+ }
1058
+ }
1059
+ fireOnPop() {
1060
+ this.endPos = this.parserContext.getPosition();
1061
+ this.processMappings();
1062
+ const data = this.parserContext.getCallbackData();
1063
+ this.node.beforeOnPop(data);
1064
+ if (this.options.onPop) {
1065
+ this.options.onPop(data);
1066
+ }
1067
+ }
1068
+ fireOnMatch(matched) {
1069
+ this.mapNamedGroups(matched);
1070
+ const data = this.parserContext.getCallbackData(matched);
1071
+ this.node.beforeOnMatch(data);
1072
+ if (this.options.onMatch) {
1073
+ return this.options.onMatch(data);
1074
+ }
1075
+ }
1076
+ fireBeforeChildParse(child) {
1077
+ const data = this.parserContext.getCallbackData();
1078
+ this.node.beforeOnBeforeChildParse(child, data);
1079
+ if (this.options.onBeforeChildParse) {
1080
+ return this.options.onBeforeChildParse(child, data);
1081
+ }
1082
+ }
1083
+ fireAfterChildParse(child) {
1084
+ if (!this.hasNodes.includes(child.node)) {
1085
+ this.hasNodes.push(child.node);
1086
+ }
1087
+ this.count[child.node.id] = this.count[child.node.id] || 0;
1088
+ this.count[child.node.id]++;
1089
+ const data = this.parserContext.getCallbackData();
1090
+ this.node.beforeOnAfterChildParse(child, data);
1091
+ if (this.options.onAfterChildParse) {
1092
+ return this.options.onAfterChildParse(child, data);
1093
+ }
1094
+ }
1095
+ fireOnAppendContent(s) {
1096
+ let _s = s;
1097
+ const data = this.parserContext.getCallbackData();
1098
+ _s = this.node.beforeOnAppendContent(_s, data);
1099
+ if (this.options.onAppendContent) {
1100
+ _s = this.options.onAppendContent(_s, data);
1101
+ }
1102
+ return _s;
1103
+ }
1104
+ processMappings() {
1105
+ this.parserContext.hoistManager.removeHoistOptions(this);
1106
+ this.parserContext.hoistManager.processHoistOptions(this);
1107
+ this.processMapContent();
1108
+ }
1109
+ processMapContent() {
1110
+ const targetNodeOptions = this.options;
1111
+ if (targetNodeOptions.mapContent) {
1112
+ Object.keys(targetNodeOptions.mapContent).forEach((key) => {
1113
+ const keyOfT = key;
1114
+ if (targetNodeOptions.mapContent && targetNodeOptions.mapContent[keyOfT]) {
1115
+ const mapRule = targetNodeOptions.mapContent[keyOfT];
1116
+ if (typeof mapRule === 'function') {
1117
+ this._customData[keyOfT] = mapRule(this.content);
1118
+ }
1119
+ else {
1120
+ const ruleKey = mapRule;
1121
+ if (ruleKey === 'copy')
1122
+ this.contentCopiedTo = keyOfT;
1123
+ this._customData[keyOfT] = this.mapContentRules[ruleKey](this.content);
1124
+ }
1125
+ if (!this.contentCopiedTo && (typeof mapRule === 'function' || ['first', 'shift', 'pop', 'last'].includes(mapRule))) {
1126
+ this.contentCopiedTo = keyOfT;
1127
+ }
1128
+ }
1129
+ });
1130
+ }
1131
+ }
1132
+ }
1133
+
1134
+ let idCounter = 0;
1135
+ class ProstoParserNode extends ProstoParserNodeBase {
1136
+ constructor(options) {
1137
+ super();
1138
+ this.options = options;
1139
+ this.id = idCounter++;
1140
+ }
1141
+ getOptions() {
1142
+ return {
1143
+ label: this.options.label || '',
1144
+ icon: this.options.icon || '',
1145
+ startsWith: (this.options.startsWith ? { ...this.options.startsWith } : this.options.startsWith),
1146
+ endsWith: (this.options.endsWith ? { ...this.options.endsWith } : this.options.endsWith),
1147
+ popsAfterNode: [...(this.options.popsAfterNode || [])],
1148
+ popsAtEOFSource: this.options.popsAtEOFSource || false,
1149
+ badToken: this.options.badToken || '',
1150
+ skipToken: this.options.skipToken || '',
1151
+ recognizes: [...(this.options.recognizes || [])],
1152
+ hoistChildren: [...(this.options.hoistChildren || [])],
1153
+ mapContent: {
1154
+ ...this.options.mapContent,
1155
+ },
1156
+ onPop: this.options.onPop,
1157
+ onMatch: this.options.onMatch,
1158
+ onAppendContent: this.options.onAppendContent,
1159
+ onAfterChildParse: this.options.onAfterChildParse,
1160
+ onBeforeChildParse: this.options.onBeforeChildParse,
1161
+ initCustomData: this.options.initCustomData,
1162
+ absorbs: this.options.absorbs,
1163
+ };
1164
+ }
1165
+ createContext(index, level, rootContext) {
1166
+ return new ProstoParserNodeContext(this, index, level, rootContext);
1167
+ }
1168
+ get name() {
1169
+ return this.constructor.name + '[' + this.id.toString() + ']' + '(' + (this.options.label || this.options.icon || '') + ')';
1170
+ }
1171
+ parse(source) {
1172
+ return this.createContext(0, 0).parserContext.parse(source);
1173
+ }
1174
+ beforeOnPop(data) {
1175
+ }
1176
+ beforeOnMatch(data) {
1177
+ }
1178
+ beforeOnAppendContent(s, data) {
1179
+ return s;
1180
+ }
1181
+ beforeOnAfterChildParse(child, data) {
1182
+ }
1183
+ beforeOnBeforeChildParse(child, data) {
1184
+ }
1185
+ }
1186
+
1187
+ class BasicNode extends ProstoParserNode {
1188
+ constructor(options) {
1189
+ var _a, _b;
1190
+ const startsWith = (options === null || options === void 0 ? void 0 : options.tokens) ? { token: options === null || options === void 0 ? void 0 : options.tokens[0] } : undefined;
1191
+ const endsWith = (options === null || options === void 0 ? void 0 : options.tokens) ? { token: options === null || options === void 0 ? void 0 : options.tokens[1] } : undefined;
1192
+ const [startOption, endOption] = ((_a = options.tokenOE) === null || _a === void 0 ? void 0 : _a.split('-')) || [];
1193
+ const [startBSlash, endBSlash] = ((_b = options.backSlash) === null || _b === void 0 ? void 0 : _b.split('-')) || [];
1194
+ if (startsWith) {
1195
+ startsWith.omit = startOption === 'omit';
1196
+ startsWith.eject = startOption === 'eject';
1197
+ startsWith.ignoreBackSlashed = startBSlash === 'ignore';
1198
+ }
1199
+ if (endsWith) {
1200
+ endsWith.omit = endOption === 'omit';
1201
+ endsWith.eject = endOption === 'eject';
1202
+ endsWith.ignoreBackSlashed = endBSlash === 'ignore';
1203
+ }
1204
+ super({
1205
+ icon: options.icon || '',
1206
+ label: typeof options.label === 'string' ? options.label : '',
1207
+ startsWith,
1208
+ endsWith,
1209
+ badToken: options.badToken,
1210
+ skipToken: options.skipToken,
1211
+ });
1212
+ if (options.recursive) {
1213
+ this.addAbsorbs(this, 'join');
1214
+ }
1215
+ }
1216
+ }
1217
+
1218
+ const stringNodeOptions = {
1219
+ label: '',
1220
+ icon: '"',
1221
+ tokens: [/(?<quote>["'`])/, ({ customData }) => customData.quote || ''],
1222
+ backSlash: '-ignore',
1223
+ };
1224
+ const stringNode = new BasicNode(stringNodeOptions);
1225
+ function stringExpressionNodeFactory(interpolationDelimiters) {
1226
+ return new BasicNode({
1227
+ label: 'string',
1228
+ icon: '≈',
1229
+ tokens: [interpolationDelimiters[0], interpolationDelimiters[1]],
1230
+ tokenOE: 'omit-omit',
1231
+ })
1232
+ .addAbsorbs(stringNode, 'join')
1233
+ .mapContent('expression', 'join-clear')
1234
+ .onPop(({ parserContext, customData: { expression } }) => {
1235
+ try {
1236
+ new Function(expression);
1237
+ }
1238
+ catch (e) {
1239
+ parserContext.panic('Invalid expression: ' + e.message, expression.length + interpolationDelimiters[0].length + interpolationDelimiters[1].length);
1240
+ }
1241
+ })
1242
+ .initCustomData(() => ({
1243
+ expression: '',
1244
+ code: ({ customData }, level = 0) => ' '.repeat(level * 2) + `__ += ${customData.expression.trim()}\n`,
1245
+ }));
1246
+ }
1247
+
1248
+ function escapeRegex(s) {
1249
+ return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
1250
+ }
1251
+ function debug(message) {
1252
+ console.log('' + '' + '' + '[rewrite] DEBUG: ' + message + '');
1253
+ }
1254
+
1255
+ function genSafeFunc(code) {
1256
+ try {
1257
+ return new Function('__ctx__', 'process', 'window', 'global', 'require', code);
1258
+ }
1259
+ catch (e) {
1260
+ console.error(e.message);
1261
+ console.error(e.stack);
1262
+ throw e;
1263
+ }
1264
+ }
1265
+ function escapeString(s) { return s.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\n/g, '\\n').replace(/\$/g, '\\$'); }
1266
+ function pushString(s) {
1267
+ return `__ += \`${escapeString(s)}\`\n`;
1268
+ }
1269
+ function renderCode(context, level = 1) {
1270
+ let s = '';
1271
+ let result = '';
1272
+ function renderS() {
1273
+ if (s) {
1274
+ result += indent + pushString(s);
1275
+ s = '';
1276
+ }
1277
+ }
1278
+ const indent = ' '.repeat(level * 2);
1279
+ context.content.forEach(c => {
1280
+ if (typeof c === 'string') {
1281
+ s += c;
1282
+ }
1283
+ else {
1284
+ renderS();
1285
+ const data = c.getCustomData();
1286
+ if (data.openCode) {
1287
+ result += indent + data.openCode;
1288
+ }
1289
+ if (data.code) {
1290
+ result += data.code(c, level);
1291
+ }
1292
+ result += renderCode(c, level + (data.openCode ? 1 : 0));
1293
+ if (data.closeCode) {
1294
+ result += indent + data.closeCode;
1295
+ }
1296
+ }
1297
+ });
1298
+ renderS();
1299
+ return result;
1300
+ }
1301
+ function getRewriter(rootNode, debug$1 = false) {
1302
+ function getCode(source) {
1303
+ const result = rootNode.parse(source);
1304
+ if (debug$1) {
1305
+ debug('Parsed tree view:\n' + result.toTree());
1306
+ }
1307
+ return 'let __ = \'\'\n' +
1308
+ 'let __v = \'\'\n' +
1309
+ 'with (__ctx__) {\n' +
1310
+ renderCode(result) +
1311
+ '}\n' +
1312
+ 'return __';
1313
+ }
1314
+ function getFunc(source) {
1315
+ const code = getCode(source);
1316
+ const func = genSafeFunc(code);
1317
+ return (context) => {
1318
+ try {
1319
+ return func(context);
1320
+ }
1321
+ catch (e) {
1322
+ throwErrorFromFunction(e, code);
1323
+ }
1324
+ };
1325
+ }
1326
+ function print(source) {
1327
+ return console.log(rootNode.parse(source).toTree());
1328
+ }
1329
+ return {
1330
+ genRewriteCode: getCode,
1331
+ genRewriteFunction: getFunc,
1332
+ printAsTree: print,
1333
+ rewrite: (source, context) => getFunc(source)(context || {}),
1334
+ };
1335
+ }
1336
+ function throwErrorFromFunction(e, code) {
1337
+ var _a;
1338
+ const relevantLine = ((_a = e.stack) === null || _a === void 0 ? void 0 : _a.split('\n')[1]) || '';
1339
+ const regex = /<anonymous>:(\d+):(\d+)\)/g;
1340
+ const match = regex.exec(relevantLine);
1341
+ if (match) {
1342
+ const row = parseInt(match[1], 10) - 2;
1343
+ const col = parseInt(match[2], 10) - 1;
1344
+ const output = renderCodeFragment(code.split('\n'), {
1345
+ row,
1346
+ error: col,
1347
+ });
1348
+ console.error('' + e.message + '');
1349
+ console.error(output);
1350
+ }
1351
+ throw e;
1352
+ }
1353
+ function getStringExpressionRewriter(interpolationDelimiters = ['{{', '}}']) {
1354
+ const stringExpression = stringExpressionNodeFactory(interpolationDelimiters);
1355
+ const rootNode = new BasicNode({}).addRecognizes(stringExpression);
1356
+ function getCode(source) {
1357
+ const result = rootNode.parse(source);
1358
+ return 'let __ = []\n' +
1359
+ 'with (__ctx__) {\n' +
1360
+ result.content.map(c => `__.push(${typeof c === 'string'
1361
+ ? `\`${escapeString(c)}\``
1362
+ : `${c.getCustomData().expression}`})`).join('\n ') +
1363
+ '}\n' +
1364
+ 'return __.length === 1 ? __[0] : __.join(\'\')';
1365
+ }
1366
+ function getFunc(source) {
1367
+ const code = getCode(source);
1368
+ const func = genSafeFunc(code);
1369
+ return (context) => {
1370
+ try {
1371
+ return func(context);
1372
+ }
1373
+ catch (e) {
1374
+ throwErrorFromFunction(e, code);
1375
+ }
1376
+ };
1377
+ }
1378
+ function print(source) {
1379
+ return console.log(rootNode.parse(source).toTree());
1380
+ }
1381
+ return {
1382
+ genRewriteCode: getCode,
1383
+ genRewriteFunction: getFunc,
1384
+ printAsTree: print,
1385
+ rewrite: (source, context) => getFunc(source)(context || {}),
1386
+ };
1387
+ }
1388
+
1389
+ const docTypeNodeOptions = {
1390
+ label: 'Document Type',
1391
+ tokens: ['<!DOCTYPE ', '>'],
1392
+ };
1393
+ const cDataNodeOptions = {
1394
+ icon: '<![CDATA[',
1395
+ tokens: ['<![CDATA[', ']]>'],
1396
+ };
1397
+ const commentNodeOptions = {
1398
+ label: 'comment',
1399
+ icon: '“',
1400
+ tokens: ['<!--', '-->'],
1401
+ };
1402
+ const valueNodeOptions = {
1403
+ label: 'value',
1404
+ icon: '=',
1405
+ tokens: [/=(?<quote>["'`])/, ({ customData }) => customData.quote || ''],
1406
+ backSlash: '-ignore',
1407
+ tokenOE: 'omit-omit',
1408
+ };
1409
+ const valueNode = new BasicNode(valueNodeOptions);
1410
+ const unquotedValueNodeOptions = {
1411
+ label: 'value',
1412
+ icon: '=',
1413
+ tokens: [/=(?<content>\w+)/, /[\s\/\>]/],
1414
+ tokenOE: 'omit-eject',
1415
+ };
1416
+ const unquotedValueNode = new BasicNode(unquotedValueNodeOptions);
1417
+ const innerNodeOptions = {
1418
+ label: 'inner',
1419
+ tokens: ['>', '</'],
1420
+ tokenOE: '-eject',
1421
+ };
1422
+ const htmlBlockTypes = [
1423
+ {
1424
+ key: 'for',
1425
+ exprRequired: true,
1426
+ compatible: ['if'],
1427
+ opening: true,
1428
+ renderOpen: (v) => `for (${v || ''}) {\n`,
1429
+ },
1430
+ {
1431
+ key: 'if',
1432
+ exprRequired: true,
1433
+ compatible: ['for'],
1434
+ opening: true,
1435
+ renderOpen: (v) => `if (${v || ''}) {\n`,
1436
+ },
1437
+ {
1438
+ key: 'else-if',
1439
+ closingKey: 'IF',
1440
+ exprRequired: true,
1441
+ opening: false,
1442
+ overtakes: ['if', 'else-if'],
1443
+ renderOpen: (v) => `} else if (${v || ''}) {\n`,
1444
+ },
1445
+ {
1446
+ key: 'else',
1447
+ closingKey: 'IF',
1448
+ exprRequired: false,
1449
+ opening: false,
1450
+ overtakes: ['if', 'else-if'],
1451
+ renderOpen: () => '} else {\n',
1452
+ },
1453
+ ];
1454
+ const htmlBlockTypesO = {};
1455
+ htmlBlockTypes.forEach(b => htmlBlockTypesO[b.key] = b);
1456
+ const getHtmlParser = (opts, recognizeTextDirective = false) => {
1457
+ const rootNode = new BasicNode({ icon: 'Html Mode' });
1458
+ const docTypeNode = new BasicNode(docTypeNodeOptions);
1459
+ const cDataNode = new BasicNode(cDataNodeOptions);
1460
+ const commentNode = new BasicNode(commentNodeOptions);
1461
+ const innerNode = new BasicNode(innerNodeOptions);
1462
+ const stringExpressionNode = stringExpressionNodeFactory(opts.exprDelimeters);
1463
+ const attrNode = attributeNodeFactory();
1464
+ const attrBlockOperationNode = attributeNodeFactory('↳', opts.blockOperation, 'block');
1465
+ const attrExprNode = attributeNodeFactory('≈', opts.attrExpression, 'expr');
1466
+ const attrNodes = [attrBlockOperationNode, attrExprNode, attrNode];
1467
+ const textDirectiveNode = new BasicNode({
1468
+ icon: 'T',
1469
+ tokens: [
1470
+ new RegExp(`^\\s*(?:<!--)${escapeRegex(opts.directive)}\\s*text-mode-on\\s*-->\\s*$`, 'm'),
1471
+ new RegExp(`^\\s*(?:<!--)${escapeRegex(opts.directive)}\\s*text-mode-off\\s*-->\\s*$`, 'm'),
1472
+ ],
1473
+ tokenOE: 'omit-omit',
1474
+ })
1475
+ .onMatch(({ parserContext }) => parserContext.jump())
1476
+ .onPop(({ parserContext }) => parserContext.jump());
1477
+ const tagNode = new BasicNode({
1478
+ tokens: [
1479
+ /<(?<tag>[\w:\-\.]+)/,
1480
+ ({ customData }) => {
1481
+ if (customData.isVoid)
1482
+ return /\/?>\s*/;
1483
+ if (customData.isText)
1484
+ return new RegExp(`\\s*<\\/(?<endTag>${escapeRegex(customData.tag)})\\s*>\\s*`);
1485
+ return /(?:\/\>|\<\/(?<endTag>[\w:\-\.]+)\s*\>\s*)/;
1486
+ },
1487
+ ],
1488
+ })
1489
+ .onMatch(({ context, customData }) => {
1490
+ context.icon = customData.tag,
1491
+ customData.isVoid = opts.voidTags.includes(customData.tag);
1492
+ customData.isText = opts.textTags.includes(customData.tag);
1493
+ if (customData.isVoid) {
1494
+ context.clearRecognizes(innerNode);
1495
+ }
1496
+ if (customData.isText && !recognizeTextDirective) {
1497
+ context.addAbsorbs(innerNode, 'join');
1498
+ }
1499
+ })
1500
+ .onBeforeChildParse((child, { customData }) => {
1501
+ if (customData.isText && child.node === innerNode) {
1502
+ child.clearRecognizes();
1503
+ if (recognizeTextDirective) {
1504
+ child.addRecognizes(textDirectiveNode);
1505
+ }
1506
+ child.removeOnAppendContent();
1507
+ child.endsWith = {
1508
+ token: new RegExp(`<\\/(?<endTag>${escapeRegex(customData.tag)})\\s*>`),
1509
+ eject: true,
1510
+ };
1511
+ }
1512
+ })
1513
+ .onAfterChildParse((child, { context }) => {
1514
+ if (child.node === innerNode) {
1515
+ context.clearRecognizes();
1516
+ }
1517
+ })
1518
+ .onPop(({ customData: { isVoid, tag, endTag, operations }, parserContext, customData, context }) => {
1519
+ var _a, _b;
1520
+ if (operations && operations.length) {
1521
+ operations = operations.sort((a) => a.key === 'for' ? -1 : 1);
1522
+ customData.operation = operations[0].key;
1523
+ for (let i = 0; i < operations.length; i++) {
1524
+ const { key, value } = operations[i];
1525
+ const descr = htmlBlockTypesO[key];
1526
+ if (!descr) {
1527
+ parserContext.panicBlock(`Unknown block operation "${key}".`, tag.length, tag.length + 1);
1528
+ }
1529
+ if (descr.exprRequired && !value) {
1530
+ parserContext.panicBlock(`Expression required for "${key}" operation.`, tag.length, tag.length + 1);
1531
+ }
1532
+ if (!descr.exprRequired && !!value) {
1533
+ parserContext.panicBlock(`Unexpected expression for "${key}" operation.`, tag.length, tag.length + 1);
1534
+ }
1535
+ if (descr.overtakes) {
1536
+ const prevNode = context.getPrevNode();
1537
+ const prevContext = context.getPrevContext();
1538
+ if (typeof prevNode === 'string' && prevNode.replace(/[\s\n\r]/g, '')) {
1539
+ parserContext.panicBlock(`Unexpected block operation "${descr.key}".`, tag.length, tag.length + 1);
1540
+ }
1541
+ if (!prevContext ||
1542
+ !descr.overtakes.includes(prevContext.getCustomData().operation)) {
1543
+ parserContext.panicBlock(`Unexpected block operation "${descr.key}".`, tag.length, tag.length + 1);
1544
+ }
1545
+ const prevData = prevContext.getCustomData();
1546
+ prevData.closeCode = '';
1547
+ }
1548
+ }
1549
+ if (operations.length === 1) {
1550
+ const descr = htmlBlockTypesO[operations[0].key];
1551
+ customData.openCode = descr.renderOpen(operations[0].value);
1552
+ customData.closeCode = '}\n';
1553
+ }
1554
+ else if (operations.length === 2) {
1555
+ const descr1 = htmlBlockTypesO[operations[0].key];
1556
+ const descr2 = htmlBlockTypesO[operations[1].key];
1557
+ if (!((_a = descr1.compatible) === null || _a === void 0 ? void 0 : _a.includes(descr2.key)) || !((_b = descr2.compatible) === null || _b === void 0 ? void 0 : _b.includes(descr1.key))) {
1558
+ parserContext.panicBlock(`Block operation "${descr1.key}" is not compatible with "${descr2.key}".`, tag.length, tag.length + 1);
1559
+ }
1560
+ customData.openCode = descr1.renderOpen(operations[0].value) + descr2.renderOpen(operations[1].value);
1561
+ customData.closeCode = '}\n}\n';
1562
+ }
1563
+ else {
1564
+ parserContext.panicBlock(`Too many block operations "${operations.map(o => o.key).join(', ')}".`, tag.length, tag.length + 1);
1565
+ }
1566
+ }
1567
+ if (!isVoid && typeof endTag === 'string' && tag !== endTag) {
1568
+ parserContext.panicBlock(`Open tag <${tag}> and closing tag </${endTag}> must be equal.`, tag.length || 0, endTag.length + 1);
1569
+ }
1570
+ })
1571
+ .addRecognizes(innerNode, ...attrNodes)
1572
+ .addHoistChildren({
1573
+ node: attrBlockOperationNode,
1574
+ as: 'operations',
1575
+ asArray: true,
1576
+ deep: 1,
1577
+ mapRule: 'customData',
1578
+ });
1579
+ if (recognizeTextDirective) {
1580
+ rootNode.addRecognizes(textDirectiveNode);
1581
+ innerNode.addRecognizes(textDirectiveNode);
1582
+ cDataNode.addRecognizes(textDirectiveNode);
1583
+ }
1584
+ rootNode.addRecognizes(docTypeNode, commentNode, tagNode, stringExpressionNode);
1585
+ innerNode.addRecognizes(commentNode, cDataNode, tagNode, stringExpressionNode);
1586
+ commentNode.addRecognizes(stringExpressionNode);
1587
+ cDataNode.addRecognizes(stringExpressionNode);
1588
+ return {
1589
+ rootNode,
1590
+ innerNode,
1591
+ commentNode,
1592
+ cDataNode,
1593
+ docTypeNode,
1594
+ stringExpressionNode,
1595
+ attrNode,
1596
+ attrBlockOperationNode,
1597
+ attrExprNode,
1598
+ tagNode,
1599
+ textDirectiveNode,
1600
+ };
1601
+ };
1602
+ const getHtmlRewriter = (opts, debug = false) => {
1603
+ return getRewriter(getHtmlParser(opts).rootNode, debug);
1604
+ };
1605
+ function attributeNodeFactory(icon = '=', prefix, type = 'plain') {
1606
+ const attrNodeOptions = {
1607
+ label: '',
1608
+ icon,
1609
+ tokens: [
1610
+ prefix ? new RegExp(`${escapeRegex(prefix)}(?<key>[\\w:\\-\\.]+)`) : /(?<key>[\w:\-\.]+)/,
1611
+ /[\s\n\/>]/,
1612
+ ],
1613
+ tokenOE: 'omit-eject',
1614
+ };
1615
+ const quoteEsc = {
1616
+ '"': '&quot;',
1617
+ '\'': '&apos;',
1618
+ };
1619
+ function escapeVal(value, quote) {
1620
+ let v = '';
1621
+ if (value) {
1622
+ v += '=';
1623
+ v += quote ? (quote + value.replace(new RegExp(quote, 'g'), quoteEsc[quote]) + quote) : value;
1624
+ }
1625
+ return v;
1626
+ }
1627
+ const children = [unquotedValueNode, valueNode];
1628
+ const codeFuncs = {
1629
+ plain: ({ customData: { key, value, quote } }, level = 0) => {
1630
+ return ' '.repeat(level * 2) + pushString(key + escapeVal(value, quote));
1631
+ },
1632
+ block: () => '',
1633
+ expr: ({ customData: { key, value, quote } }, level = 0) => {
1634
+ const q = (quote || '');
1635
+ const indent = ' '.repeat(level * 2);
1636
+ let s = indent + '__v = ' + (value || '\'\'') + '\n';
1637
+ s += indent + 'if (typeof __v === \'boolean\') {\n';
1638
+ s += indent + ` if (__v) __ += \`${key}\`\n`;
1639
+ s += indent + '} else {\n';
1640
+ s += indent + ` __ += \`${key}=${q}` + '${' + ` (__v || '').replace(/${q}/g, '${quoteEsc[q]}') }${q}\`\n`;
1641
+ s += indent + '}\n';
1642
+ return s;
1643
+ },
1644
+ };
1645
+ const attrNode = new BasicNode(attrNodeOptions)
1646
+ .addPopsAfterNode(...children)
1647
+ .addHoistChildren({
1648
+ node: valueNode,
1649
+ as: 'quote',
1650
+ deep: 1,
1651
+ mapRule: 'customData.quote',
1652
+ })
1653
+ .onPop(({ parserContext, customData: { value, quote } }) => {
1654
+ if (type === 'expr' && value) {
1655
+ try {
1656
+ new Function(value);
1657
+ }
1658
+ catch (e) {
1659
+ parserContext.panic('Invalid expression: ' + e.message, value.length + 1);
1660
+ }
1661
+ }
1662
+ if (type === 'expr' && !quote) {
1663
+ parserContext.panic('Expression must be quoted.', (value === null || value === void 0 ? void 0 : value.length) || 1);
1664
+ }
1665
+ })
1666
+ .addAbsorbs(children, 'join->value')
1667
+ .initCustomData(() => ({
1668
+ key: '',
1669
+ code: codeFuncs[type],
1670
+ }));
1671
+ return attrNode;
1672
+ }
1673
+
1674
+ const textBlockTypes = [
1675
+ {
1676
+ key: 'FOR',
1677
+ exprRequired: true,
1678
+ opening: true,
1679
+ code: ({ customData }) => `for ${customData.expression} {\n`,
1680
+ },
1681
+ {
1682
+ key: 'IF',
1683
+ exprRequired: true,
1684
+ opening: true,
1685
+ code: ({ customData }) => `if ${customData.expression} {\n`,
1686
+ },
1687
+ {
1688
+ key: 'ELSEIF',
1689
+ closingKey: 'IF',
1690
+ exprRequired: true,
1691
+ opening: false,
1692
+ overtakes: ['IF', 'ELSEIF'],
1693
+ code: ({ customData }) => `} else if ${customData.expression} {\n`,
1694
+ },
1695
+ {
1696
+ key: 'ELSE',
1697
+ closingKey: 'IF',
1698
+ exprRequired: false,
1699
+ opening: false,
1700
+ overtakes: ['IF', 'ELSEIF'],
1701
+ code: () => '} else {\n',
1702
+ },
1703
+ ];
1704
+ const textBlockTypesO = {};
1705
+ textBlockTypes.forEach(b => textBlockTypesO[b.key] = b);
1706
+ const getTextParser = (opts, recognizeHtmlDirective = false) => {
1707
+ const rootNode = new BasicNode({ icon: 'Text Mode' });
1708
+ const stringExpressionNode = stringExpressionNodeFactory(opts.exprDelimeters);
1709
+ const blockOperationNode = new BasicNode({
1710
+ label: '',
1711
+ icon: '↳',
1712
+ tokens: [
1713
+ new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.blockOperation)}\\s*(?<block>\\w+[^\\S\\r\\n]*\\w*)[^\\S\\r\\n]*(?<expression>\\(.*\\))?(?<rest>[^\\n]*)?$`, 'm'),
1714
+ new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.blockOperation)}\\s*(?<endBlock>END[^\\S\\r\\n]*\\w*)[^\\S\\r\\n]*(?<endExpression>\\(.*\\))?(?<endRest>[^\\n]*)?$`, 'm'),
1715
+ ],
1716
+ tokenOE: 'omit-omit',
1717
+ })
1718
+ .onMatchStartToken(({ customData, parserContext, matched }) => {
1719
+ const { block, expression, rest } = matched.groups;
1720
+ const descr = textBlockTypesO[block.replace(/[\s\n]/g, '')];
1721
+ if (!descr) {
1722
+ parserContext.panic(`Unknown block operation "${block.trim()}".`, -matched[0].indexOf(block));
1723
+ }
1724
+ if (descr.exprRequired && !expression) {
1725
+ parserContext.panic(`Expression required for "${block.trim()}" operation.`, -matched[0].length);
1726
+ }
1727
+ if (!descr.exprRequired && !!expression) {
1728
+ parserContext.panic(`Unexpected expression for "${block.trim()}" operation.`, -matched[0].indexOf(expression));
1729
+ }
1730
+ if (rest) {
1731
+ parserContext.panic(`Unexpected text "${rest}" in "${block.trim()}" operation.`, -matched[0].length + rest.length);
1732
+ }
1733
+ if (descr.opening) {
1734
+ return true;
1735
+ }
1736
+ if (descr.overtakes && descr.overtakes.includes(customData.block)) {
1737
+ parserContext.pop();
1738
+ return true;
1739
+ }
1740
+ if (customData.block) {
1741
+ parserContext.panic(`Unexpected block operation "${block.trim()}" after "${customData.block}" block.`);
1742
+ }
1743
+ else {
1744
+ parserContext.panic(`Unexpected block operation "${block.trim()}".`);
1745
+ }
1746
+ })
1747
+ .onMatch(({ customData, context, parserContext }) => {
1748
+ customData.block = customData.block.replace(/[\s\n]/g, '');
1749
+ customData.descr = textBlockTypesO[customData.block];
1750
+ customData.openCode = customData.descr.code(context);
1751
+ parserContext.jump();
1752
+ })
1753
+ .onPop(({ parserContext }) => parserContext.jump())
1754
+ .onMatchEndToken(({ customData, matched, parserContext }) => {
1755
+ const { endBlock } = matched.groups;
1756
+ const endKey = 'END' + (customData.descr.closingKey || customData.descr.key);
1757
+ if (endKey !== endBlock.replace(/[\s\n]/g, '')) {
1758
+ parserContext.panic('Wrong closing block instruction ' + endBlock, matched[0].length);
1759
+ }
1760
+ customData.closeCode = '}\n';
1761
+ return true;
1762
+ })
1763
+ .popsAtEOFSource(true);
1764
+ const revealNode = new BasicNode({
1765
+ icon: ':',
1766
+ tokens: [
1767
+ new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.revealLine)}[^\\S\\r\\n]*`, 'm'),
1768
+ /$/m,
1769
+ ],
1770
+ tokenOE: 'omit-',
1771
+ })
1772
+ .addRecognizes(stringExpressionNode)
1773
+ .popsAtEOFSource(true);
1774
+ const ignoreDirectiveNode = new BasicNode({
1775
+ icon: ':',
1776
+ tokens: [
1777
+ new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.directive)}\\s*ignore-next-line\\s*$`, 'm'),
1778
+ /^[^\n]*$/m,
1779
+ ],
1780
+ tokenOE: 'omit-',
1781
+ })
1782
+ .popsAtEOFSource(true);
1783
+ const htmlDirectiveNode = new BasicNode({
1784
+ icon: 'H',
1785
+ tokens: [
1786
+ new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.directive)}\\s*html-mode-on\\s*$`, 'm'),
1787
+ new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.directive)}\\s*html-mode-off\\s*$`, 'm'),
1788
+ ],
1789
+ tokenOE: 'omit-omit',
1790
+ })
1791
+ .onMatch(({ parserContext }) => parserContext.jump())
1792
+ .onPop(({ parserContext }) => parserContext.jump());
1793
+ blockOperationNode.addRecognizes(ignoreDirectiveNode, blockOperationNode, revealNode, stringExpressionNode);
1794
+ rootNode.addRecognizes(ignoreDirectiveNode, blockOperationNode, revealNode, stringExpressionNode);
1795
+ if (recognizeHtmlDirective) {
1796
+ rootNode.addRecognizes(htmlDirectiveNode);
1797
+ blockOperationNode.addRecognizes(htmlDirectiveNode);
1798
+ }
1799
+ return {
1800
+ stringExpressionNode,
1801
+ revealNode,
1802
+ ignoreDirectiveNode,
1803
+ blockOperationNode,
1804
+ rootNode,
1805
+ htmlDirectiveNode,
1806
+ };
1807
+ };
1808
+ const getTextRewriter = (opts, debug = false) => {
1809
+ return getRewriter(getTextParser(opts).rootNode, debug);
1810
+ };
1811
+
1812
+ function getDefaultExportFromCjs (x) {
1813
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
1814
+ }
1815
+
1816
+ var balancedMatch = balanced$1;
1817
+ function balanced$1(a, b, str) {
1818
+ if (a instanceof RegExp) a = maybeMatch(a, str);
1819
+ if (b instanceof RegExp) b = maybeMatch(b, str);
1820
+
1821
+ var r = range(a, b, str);
1822
+
1823
+ return r && {
1824
+ start: r[0],
1825
+ end: r[1],
1826
+ pre: str.slice(0, r[0]),
1827
+ body: str.slice(r[0] + a.length, r[1]),
1828
+ post: str.slice(r[1] + b.length)
1829
+ };
1830
+ }
1831
+
1832
+ function maybeMatch(reg, str) {
1833
+ var m = str.match(reg);
1834
+ return m ? m[0] : null;
1835
+ }
1836
+
1837
+ balanced$1.range = range;
1838
+ function range(a, b, str) {
1839
+ var begs, beg, left, right, result;
1840
+ var ai = str.indexOf(a);
1841
+ var bi = str.indexOf(b, ai + 1);
1842
+ var i = ai;
1843
+
1844
+ if (ai >= 0 && bi > 0) {
1845
+ if(a===b) {
1846
+ return [ai, bi];
1847
+ }
1848
+ begs = [];
1849
+ left = str.length;
1850
+
1851
+ while (i >= 0 && !result) {
1852
+ if (i == ai) {
1853
+ begs.push(i);
1854
+ ai = str.indexOf(a, i + 1);
1855
+ } else if (begs.length == 1) {
1856
+ result = [ begs.pop(), bi ];
1857
+ } else {
1858
+ beg = begs.pop();
1859
+ if (beg < left) {
1860
+ left = beg;
1861
+ right = bi;
1862
+ }
1863
+
1864
+ bi = str.indexOf(b, i + 1);
1865
+ }
1866
+
1867
+ i = ai < bi && ai >= 0 ? ai : bi;
1868
+ }
1869
+
1870
+ if (begs.length) {
1871
+ result = [ left, right ];
1872
+ }
1873
+ }
1874
+
1875
+ return result;
1876
+ }
1877
+
1878
+ var balanced = balancedMatch;
1879
+
1880
+ var braceExpansion = expandTop;
1881
+
1882
+ var escSlash = '\0SLASH'+Math.random()+'\0';
1883
+ var escOpen = '\0OPEN'+Math.random()+'\0';
1884
+ var escClose = '\0CLOSE'+Math.random()+'\0';
1885
+ var escComma = '\0COMMA'+Math.random()+'\0';
1886
+ var escPeriod = '\0PERIOD'+Math.random()+'\0';
1887
+
1888
+ function numeric(str) {
1889
+ return parseInt(str, 10) == str
1890
+ ? parseInt(str, 10)
1891
+ : str.charCodeAt(0);
1892
+ }
1893
+
1894
+ function escapeBraces(str) {
1895
+ return str.split('\\\\').join(escSlash)
1896
+ .split('\\{').join(escOpen)
1897
+ .split('\\}').join(escClose)
1898
+ .split('\\,').join(escComma)
1899
+ .split('\\.').join(escPeriod);
1900
+ }
1901
+
1902
+ function unescapeBraces(str) {
1903
+ return str.split(escSlash).join('\\')
1904
+ .split(escOpen).join('{')
1905
+ .split(escClose).join('}')
1906
+ .split(escComma).join(',')
1907
+ .split(escPeriod).join('.');
1908
+ }
1909
+
1910
+
1911
+ // Basically just str.split(","), but handling cases
1912
+ // where we have nested braced sections, which should be
1913
+ // treated as individual members, like {a,{b,c},d}
1914
+ function parseCommaParts(str) {
1915
+ if (!str)
1916
+ return [''];
1917
+
1918
+ var parts = [];
1919
+ var m = balanced('{', '}', str);
1920
+
1921
+ if (!m)
1922
+ return str.split(',');
1923
+
1924
+ var pre = m.pre;
1925
+ var body = m.body;
1926
+ var post = m.post;
1927
+ var p = pre.split(',');
1928
+
1929
+ p[p.length-1] += '{' + body + '}';
1930
+ var postParts = parseCommaParts(post);
1931
+ if (post.length) {
1932
+ p[p.length-1] += postParts.shift();
1933
+ p.push.apply(p, postParts);
1934
+ }
1935
+
1936
+ parts.push.apply(parts, p);
1937
+
1938
+ return parts;
1939
+ }
1940
+
1941
+ function expandTop(str) {
1942
+ if (!str)
1943
+ return [];
1944
+
1945
+ // I don't know why Bash 4.3 does this, but it does.
1946
+ // Anything starting with {} will have the first two bytes preserved
1947
+ // but *only* at the top level, so {},a}b will not expand to anything,
1948
+ // but a{},b}c will be expanded to [a}c,abc].
1949
+ // One could argue that this is a bug in Bash, but since the goal of
1950
+ // this module is to match Bash's rules, we escape a leading {}
1951
+ if (str.substr(0, 2) === '{}') {
1952
+ str = '\\{\\}' + str.substr(2);
1953
+ }
1954
+
1955
+ return expand(escapeBraces(str), true).map(unescapeBraces);
1956
+ }
1957
+
1958
+ function embrace(str) {
1959
+ return '{' + str + '}';
1960
+ }
1961
+ function isPadded(el) {
1962
+ return /^-?0\d/.test(el);
1963
+ }
1964
+
1965
+ function lte(i, y) {
1966
+ return i <= y;
1967
+ }
1968
+ function gte(i, y) {
1969
+ return i >= y;
1970
+ }
1971
+
1972
+ function expand(str, isTop) {
1973
+ var expansions = [];
1974
+
1975
+ var m = balanced('{', '}', str);
1976
+ if (!m) return [str];
1977
+
1978
+ // no need to expand pre, since it is guaranteed to be free of brace-sets
1979
+ var pre = m.pre;
1980
+ var post = m.post.length
1981
+ ? expand(m.post, false)
1982
+ : [''];
1983
+
1984
+ if (/\$$/.test(m.pre)) {
1985
+ for (var k = 0; k < post.length; k++) {
1986
+ var expansion = pre+ '{' + m.body + '}' + post[k];
1987
+ expansions.push(expansion);
1988
+ }
1989
+ } else {
1990
+ var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
1991
+ var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
1992
+ var isSequence = isNumericSequence || isAlphaSequence;
1993
+ var isOptions = m.body.indexOf(',') >= 0;
1994
+ if (!isSequence && !isOptions) {
1995
+ // {a},b}
1996
+ if (m.post.match(/,.*\}/)) {
1997
+ str = m.pre + '{' + m.body + escClose + m.post;
1998
+ return expand(str);
1999
+ }
2000
+ return [str];
2001
+ }
2002
+
2003
+ var n;
2004
+ if (isSequence) {
2005
+ n = m.body.split(/\.\./);
2006
+ } else {
2007
+ n = parseCommaParts(m.body);
2008
+ if (n.length === 1) {
2009
+ // x{{a,b}}y ==> x{a}y x{b}y
2010
+ n = expand(n[0], false).map(embrace);
2011
+ if (n.length === 1) {
2012
+ return post.map(function(p) {
2013
+ return m.pre + n[0] + p;
2014
+ });
2015
+ }
2016
+ }
2017
+ }
2018
+
2019
+ // at this point, n is the parts, and we know it's not a comma set
2020
+ // with a single entry.
2021
+ var N;
2022
+
2023
+ if (isSequence) {
2024
+ var x = numeric(n[0]);
2025
+ var y = numeric(n[1]);
2026
+ var width = Math.max(n[0].length, n[1].length);
2027
+ var incr = n.length == 3
2028
+ ? Math.abs(numeric(n[2]))
2029
+ : 1;
2030
+ var test = lte;
2031
+ var reverse = y < x;
2032
+ if (reverse) {
2033
+ incr *= -1;
2034
+ test = gte;
2035
+ }
2036
+ var pad = n.some(isPadded);
2037
+
2038
+ N = [];
2039
+
2040
+ for (var i = x; test(i, y); i += incr) {
2041
+ var c;
2042
+ if (isAlphaSequence) {
2043
+ c = String.fromCharCode(i);
2044
+ if (c === '\\')
2045
+ c = '';
2046
+ } else {
2047
+ c = String(i);
2048
+ if (pad) {
2049
+ var need = width - c.length;
2050
+ if (need > 0) {
2051
+ var z = new Array(need + 1).join('0');
2052
+ if (i < 0)
2053
+ c = '-' + z + c.slice(1);
2054
+ else
2055
+ c = z + c;
2056
+ }
2057
+ }
2058
+ }
2059
+ N.push(c);
2060
+ }
2061
+ } else {
2062
+ N = [];
2063
+
2064
+ for (var j = 0; j < n.length; j++) {
2065
+ N.push.apply(N, expand(n[j], false));
2066
+ }
2067
+ }
2068
+
2069
+ for (var j = 0; j < N.length; j++) {
2070
+ for (var k = 0; k < post.length; k++) {
2071
+ var expansion = pre + N[j] + post[k];
2072
+ if (!isTop || isSequence || expansion)
2073
+ expansions.push(expansion);
2074
+ }
2075
+ }
2076
+ }
2077
+
2078
+ return expansions;
2079
+ }
2080
+
2081
+ var expand$1 = /*@__PURE__*/getDefaultExportFromCjs(braceExpansion);
2082
+
2083
+ const MAX_PATTERN_LENGTH = 1024 * 64;
2084
+ const assertValidPattern = (pattern) => {
2085
+ if (typeof pattern !== 'string') {
2086
+ throw new TypeError('invalid pattern');
2087
+ }
2088
+ if (pattern.length > MAX_PATTERN_LENGTH) {
2089
+ throw new TypeError('pattern is too long');
2090
+ }
2091
+ };
2092
+
2093
+ // translate the various posix character classes into unicode properties
2094
+ // this works across all unicode locales
2095
+ // { <posix class>: [<translation>, /u flag required, negated]
2096
+ const posixClasses = {
2097
+ '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
2098
+ '[:alpha:]': ['\\p{L}\\p{Nl}', true],
2099
+ '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
2100
+ '[:blank:]': ['\\p{Zs}\\t', true],
2101
+ '[:cntrl:]': ['\\p{Cc}', true],
2102
+ '[:digit:]': ['\\p{Nd}', true],
2103
+ '[:graph:]': ['\\p{Z}\\p{C}', true, true],
2104
+ '[:lower:]': ['\\p{Ll}', true],
2105
+ '[:print:]': ['\\p{C}', true],
2106
+ '[:punct:]': ['\\p{P}', true],
2107
+ '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
2108
+ '[:upper:]': ['\\p{Lu}', true],
2109
+ '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
2110
+ '[:xdigit:]': ['A-Fa-f0-9', false],
2111
+ };
2112
+ // only need to escape a few things inside of brace expressions
2113
+ // escapes: [ \ ] -
2114
+ const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
2115
+ // escape all regexp magic characters
2116
+ const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
2117
+ // everything has already been escaped, we just have to join
2118
+ const rangesToString = (ranges) => ranges.join('');
2119
+ // takes a glob string at a posix brace expression, and returns
2120
+ // an equivalent regular expression source, and boolean indicating
2121
+ // whether the /u flag needs to be applied, and the number of chars
2122
+ // consumed to parse the character class.
2123
+ // This also removes out of order ranges, and returns ($.) if the
2124
+ // entire class just no good.
2125
+ const parseClass = (glob, position) => {
2126
+ const pos = position;
2127
+ /* c8 ignore start */
2128
+ if (glob.charAt(pos) !== '[') {
2129
+ throw new Error('not in a brace expression');
2130
+ }
2131
+ /* c8 ignore stop */
2132
+ const ranges = [];
2133
+ const negs = [];
2134
+ let i = pos + 1;
2135
+ let sawStart = false;
2136
+ let uflag = false;
2137
+ let escaping = false;
2138
+ let negate = false;
2139
+ let endPos = pos;
2140
+ let rangeStart = '';
2141
+ WHILE: while (i < glob.length) {
2142
+ const c = glob.charAt(i);
2143
+ if ((c === '!' || c === '^') && i === pos + 1) {
2144
+ negate = true;
2145
+ i++;
2146
+ continue;
2147
+ }
2148
+ if (c === ']' && sawStart && !escaping) {
2149
+ endPos = i + 1;
2150
+ break;
2151
+ }
2152
+ sawStart = true;
2153
+ if (c === '\\') {
2154
+ if (!escaping) {
2155
+ escaping = true;
2156
+ i++;
2157
+ continue;
2158
+ }
2159
+ // escaped \ char, fall through and treat like normal char
2160
+ }
2161
+ if (c === '[' && !escaping) {
2162
+ // either a posix class, a collation equivalent, or just a [
2163
+ for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
2164
+ if (glob.startsWith(cls, i)) {
2165
+ // invalid, [a-[] is fine, but not [a-[:alpha]]
2166
+ if (rangeStart) {
2167
+ return ['$.', false, glob.length - pos, true];
2168
+ }
2169
+ i += cls.length;
2170
+ if (neg)
2171
+ negs.push(unip);
2172
+ else
2173
+ ranges.push(unip);
2174
+ uflag = uflag || u;
2175
+ continue WHILE;
2176
+ }
2177
+ }
2178
+ }
2179
+ // now it's just a normal character, effectively
2180
+ escaping = false;
2181
+ if (rangeStart) {
2182
+ // throw this range away if it's not valid, but others
2183
+ // can still match.
2184
+ if (c > rangeStart) {
2185
+ ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
2186
+ }
2187
+ else if (c === rangeStart) {
2188
+ ranges.push(braceEscape(c));
2189
+ }
2190
+ rangeStart = '';
2191
+ i++;
2192
+ continue;
2193
+ }
2194
+ // now might be the start of a range.
2195
+ // can be either c-d or c-] or c<more...>] or c] at this point
2196
+ if (glob.startsWith('-]', i + 1)) {
2197
+ ranges.push(braceEscape(c + '-'));
2198
+ i += 2;
2199
+ continue;
2200
+ }
2201
+ if (glob.startsWith('-', i + 1)) {
2202
+ rangeStart = c;
2203
+ i += 2;
2204
+ continue;
2205
+ }
2206
+ // not the start of a range, just a single character
2207
+ ranges.push(braceEscape(c));
2208
+ i++;
2209
+ }
2210
+ if (endPos < i) {
2211
+ // didn't see the end of the class, not a valid class,
2212
+ // but might still be valid as a literal match.
2213
+ return ['', false, 0, false];
2214
+ }
2215
+ // if we got no ranges and no negates, then we have a range that
2216
+ // cannot possibly match anything, and that poisons the whole glob
2217
+ if (!ranges.length && !negs.length) {
2218
+ return ['$.', false, glob.length - pos, true];
2219
+ }
2220
+ // if we got one positive range, and it's a single character, then that's
2221
+ // not actually a magic pattern, it's just that one literal character.
2222
+ // we should not treat that as "magic", we should just return the literal
2223
+ // character. [_] is a perfectly valid way to escape glob magic chars.
2224
+ if (negs.length === 0 &&
2225
+ ranges.length === 1 &&
2226
+ /^\\?.$/.test(ranges[0]) &&
2227
+ !negate) {
2228
+ const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
2229
+ return [regexpEscape(r), false, endPos - pos, false];
2230
+ }
2231
+ const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
2232
+ const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
2233
+ const comb = ranges.length && negs.length
2234
+ ? '(' + sranges + '|' + snegs + ')'
2235
+ : ranges.length
2236
+ ? sranges
2237
+ : snegs;
2238
+ return [comb, uflag, endPos - pos, true];
2239
+ };
2240
+
2241
+ /**
2242
+ * Un-escape a string that has been escaped with {@link escape}.
2243
+ *
2244
+ * If the {@link windowsPathsNoEscape} option is used, then square-brace
2245
+ * escapes are removed, but not backslash escapes. For example, it will turn
2246
+ * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
2247
+ * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
2248
+ *
2249
+ * When `windowsPathsNoEscape` is not set, then both brace escapes and
2250
+ * backslash escapes are removed.
2251
+ *
2252
+ * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
2253
+ * or unescaped.
2254
+ */
2255
+ const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
2256
+ return windowsPathsNoEscape
2257
+ ? s.replace(/\[([^\/\\])\]/g, '$1')
2258
+ : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
2259
+ };
2260
+
2261
+ // parse a single path portion
2262
+ const types = new Set(['!', '?', '+', '*', '@']);
2263
+ const isExtglobType = (c) => types.has(c);
2264
+ // Patterns that get prepended to bind to the start of either the
2265
+ // entire string, or just a single path portion, to prevent dots
2266
+ // and/or traversal patterns, when needed.
2267
+ // Exts don't need the ^ or / bit, because the root binds that already.
2268
+ const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
2269
+ const startNoDot = '(?!\\.)';
2270
+ // characters that indicate a start of pattern needs the "no dots" bit,
2271
+ // because a dot *might* be matched. ( is not in the list, because in
2272
+ // the case of a child extglob, it will handle the prevention itself.
2273
+ const addPatternStart = new Set(['[', '.']);
2274
+ // cases where traversal is A-OK, no dot prevention needed
2275
+ const justDots = new Set(['..', '.']);
2276
+ const reSpecials = new Set('().*{}+?[]^$\\!');
2277
+ const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
2278
+ // any single thing other than /
2279
+ const qmark$1 = '[^/]';
2280
+ // * => any number of characters
2281
+ const star$1 = qmark$1 + '*?';
2282
+ // use + when we need to ensure that *something* matches, because the * is
2283
+ // the only thing in the path portion.
2284
+ const starNoEmpty = qmark$1 + '+?';
2285
+ // remove the \ chars that we added if we end up doing a nonmagic compare
2286
+ // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
2287
+ class AST {
2288
+ type;
2289
+ #root;
2290
+ #hasMagic;
2291
+ #uflag = false;
2292
+ #parts = [];
2293
+ #parent;
2294
+ #parentIndex;
2295
+ #negs;
2296
+ #filledNegs = false;
2297
+ #options;
2298
+ #toString;
2299
+ // set to true if it's an extglob with no children
2300
+ // (which really means one child of '')
2301
+ #emptyExt = false;
2302
+ constructor(type, parent, options = {}) {
2303
+ this.type = type;
2304
+ // extglobs are inherently magical
2305
+ if (type)
2306
+ this.#hasMagic = true;
2307
+ this.#parent = parent;
2308
+ this.#root = this.#parent ? this.#parent.#root : this;
2309
+ this.#options = this.#root === this ? options : this.#root.#options;
2310
+ this.#negs = this.#root === this ? [] : this.#root.#negs;
2311
+ if (type === '!' && !this.#root.#filledNegs)
2312
+ this.#negs.push(this);
2313
+ this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
2314
+ }
2315
+ get hasMagic() {
2316
+ /* c8 ignore start */
2317
+ if (this.#hasMagic !== undefined)
2318
+ return this.#hasMagic;
2319
+ /* c8 ignore stop */
2320
+ for (const p of this.#parts) {
2321
+ if (typeof p === 'string')
2322
+ continue;
2323
+ if (p.type || p.hasMagic)
2324
+ return (this.#hasMagic = true);
2325
+ }
2326
+ // note: will be undefined until we generate the regexp src and find out
2327
+ return this.#hasMagic;
2328
+ }
2329
+ // reconstructs the pattern
2330
+ toString() {
2331
+ if (this.#toString !== undefined)
2332
+ return this.#toString;
2333
+ if (!this.type) {
2334
+ return (this.#toString = this.#parts.map(p => String(p)).join(''));
2335
+ }
2336
+ else {
2337
+ return (this.#toString =
2338
+ this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
2339
+ }
2340
+ }
2341
+ #fillNegs() {
2342
+ /* c8 ignore start */
2343
+ if (this !== this.#root)
2344
+ throw new Error('should only call on root');
2345
+ if (this.#filledNegs)
2346
+ return this;
2347
+ /* c8 ignore stop */
2348
+ // call toString() once to fill this out
2349
+ this.toString();
2350
+ this.#filledNegs = true;
2351
+ let n;
2352
+ while ((n = this.#negs.pop())) {
2353
+ if (n.type !== '!')
2354
+ continue;
2355
+ // walk up the tree, appending everthing that comes AFTER parentIndex
2356
+ let p = n;
2357
+ let pp = p.#parent;
2358
+ while (pp) {
2359
+ for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
2360
+ for (const part of n.#parts) {
2361
+ /* c8 ignore start */
2362
+ if (typeof part === 'string') {
2363
+ throw new Error('string part in extglob AST??');
2364
+ }
2365
+ /* c8 ignore stop */
2366
+ part.copyIn(pp.#parts[i]);
2367
+ }
2368
+ }
2369
+ p = pp;
2370
+ pp = p.#parent;
2371
+ }
2372
+ }
2373
+ return this;
2374
+ }
2375
+ push(...parts) {
2376
+ for (const p of parts) {
2377
+ if (p === '')
2378
+ continue;
2379
+ /* c8 ignore start */
2380
+ if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
2381
+ throw new Error('invalid part: ' + p);
2382
+ }
2383
+ /* c8 ignore stop */
2384
+ this.#parts.push(p);
2385
+ }
2386
+ }
2387
+ toJSON() {
2388
+ const ret = this.type === null
2389
+ ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
2390
+ : [this.type, ...this.#parts.map(p => p.toJSON())];
2391
+ if (this.isStart() && !this.type)
2392
+ ret.unshift([]);
2393
+ if (this.isEnd() &&
2394
+ (this === this.#root ||
2395
+ (this.#root.#filledNegs && this.#parent?.type === '!'))) {
2396
+ ret.push({});
2397
+ }
2398
+ return ret;
2399
+ }
2400
+ isStart() {
2401
+ if (this.#root === this)
2402
+ return true;
2403
+ // if (this.type) return !!this.#parent?.isStart()
2404
+ if (!this.#parent?.isStart())
2405
+ return false;
2406
+ if (this.#parentIndex === 0)
2407
+ return true;
2408
+ // if everything AHEAD of this is a negation, then it's still the "start"
2409
+ const p = this.#parent;
2410
+ for (let i = 0; i < this.#parentIndex; i++) {
2411
+ const pp = p.#parts[i];
2412
+ if (!(pp instanceof AST && pp.type === '!')) {
2413
+ return false;
2414
+ }
2415
+ }
2416
+ return true;
2417
+ }
2418
+ isEnd() {
2419
+ if (this.#root === this)
2420
+ return true;
2421
+ if (this.#parent?.type === '!')
2422
+ return true;
2423
+ if (!this.#parent?.isEnd())
2424
+ return false;
2425
+ if (!this.type)
2426
+ return this.#parent?.isEnd();
2427
+ // if not root, it'll always have a parent
2428
+ /* c8 ignore start */
2429
+ const pl = this.#parent ? this.#parent.#parts.length : 0;
2430
+ /* c8 ignore stop */
2431
+ return this.#parentIndex === pl - 1;
2432
+ }
2433
+ copyIn(part) {
2434
+ if (typeof part === 'string')
2435
+ this.push(part);
2436
+ else
2437
+ this.push(part.clone(this));
2438
+ }
2439
+ clone(parent) {
2440
+ const c = new AST(this.type, parent);
2441
+ for (const p of this.#parts) {
2442
+ c.copyIn(p);
2443
+ }
2444
+ return c;
2445
+ }
2446
+ static #parseAST(str, ast, pos, opt) {
2447
+ let escaping = false;
2448
+ let inBrace = false;
2449
+ let braceStart = -1;
2450
+ let braceNeg = false;
2451
+ if (ast.type === null) {
2452
+ // outside of a extglob, append until we find a start
2453
+ let i = pos;
2454
+ let acc = '';
2455
+ while (i < str.length) {
2456
+ const c = str.charAt(i++);
2457
+ // still accumulate escapes at this point, but we do ignore
2458
+ // starts that are escaped
2459
+ if (escaping || c === '\\') {
2460
+ escaping = !escaping;
2461
+ acc += c;
2462
+ continue;
2463
+ }
2464
+ if (inBrace) {
2465
+ if (i === braceStart + 1) {
2466
+ if (c === '^' || c === '!') {
2467
+ braceNeg = true;
2468
+ }
2469
+ }
2470
+ else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
2471
+ inBrace = false;
2472
+ }
2473
+ acc += c;
2474
+ continue;
2475
+ }
2476
+ else if (c === '[') {
2477
+ inBrace = true;
2478
+ braceStart = i;
2479
+ braceNeg = false;
2480
+ acc += c;
2481
+ continue;
2482
+ }
2483
+ if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
2484
+ ast.push(acc);
2485
+ acc = '';
2486
+ const ext = new AST(c, ast);
2487
+ i = AST.#parseAST(str, ext, i, opt);
2488
+ ast.push(ext);
2489
+ continue;
2490
+ }
2491
+ acc += c;
2492
+ }
2493
+ ast.push(acc);
2494
+ return i;
2495
+ }
2496
+ // some kind of extglob, pos is at the (
2497
+ // find the next | or )
2498
+ let i = pos + 1;
2499
+ let part = new AST(null, ast);
2500
+ const parts = [];
2501
+ let acc = '';
2502
+ while (i < str.length) {
2503
+ const c = str.charAt(i++);
2504
+ // still accumulate escapes at this point, but we do ignore
2505
+ // starts that are escaped
2506
+ if (escaping || c === '\\') {
2507
+ escaping = !escaping;
2508
+ acc += c;
2509
+ continue;
2510
+ }
2511
+ if (inBrace) {
2512
+ if (i === braceStart + 1) {
2513
+ if (c === '^' || c === '!') {
2514
+ braceNeg = true;
2515
+ }
2516
+ }
2517
+ else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
2518
+ inBrace = false;
2519
+ }
2520
+ acc += c;
2521
+ continue;
2522
+ }
2523
+ else if (c === '[') {
2524
+ inBrace = true;
2525
+ braceStart = i;
2526
+ braceNeg = false;
2527
+ acc += c;
2528
+ continue;
2529
+ }
2530
+ if (isExtglobType(c) && str.charAt(i) === '(') {
2531
+ part.push(acc);
2532
+ acc = '';
2533
+ const ext = new AST(c, part);
2534
+ part.push(ext);
2535
+ i = AST.#parseAST(str, ext, i, opt);
2536
+ continue;
2537
+ }
2538
+ if (c === '|') {
2539
+ part.push(acc);
2540
+ acc = '';
2541
+ parts.push(part);
2542
+ part = new AST(null, ast);
2543
+ continue;
2544
+ }
2545
+ if (c === ')') {
2546
+ if (acc === '' && ast.#parts.length === 0) {
2547
+ ast.#emptyExt = true;
2548
+ }
2549
+ part.push(acc);
2550
+ acc = '';
2551
+ ast.push(...parts, part);
2552
+ return i;
2553
+ }
2554
+ acc += c;
2555
+ }
2556
+ // unfinished extglob
2557
+ // if we got here, it was a malformed extglob! not an extglob, but
2558
+ // maybe something else in there.
2559
+ ast.type = null;
2560
+ ast.#hasMagic = undefined;
2561
+ ast.#parts = [str.substring(pos - 1)];
2562
+ return i;
2563
+ }
2564
+ static fromGlob(pattern, options = {}) {
2565
+ const ast = new AST(null, undefined, options);
2566
+ AST.#parseAST(pattern, ast, 0, options);
2567
+ return ast;
2568
+ }
2569
+ // returns the regular expression if there's magic, or the unescaped
2570
+ // string if not.
2571
+ toMMPattern() {
2572
+ // should only be called on root
2573
+ /* c8 ignore start */
2574
+ if (this !== this.#root)
2575
+ return this.#root.toMMPattern();
2576
+ /* c8 ignore stop */
2577
+ const glob = this.toString();
2578
+ const [re, body, hasMagic, uflag] = this.toRegExpSource();
2579
+ // if we're in nocase mode, and not nocaseMagicOnly, then we do
2580
+ // still need a regular expression if we have to case-insensitively
2581
+ // match capital/lowercase characters.
2582
+ const anyMagic = hasMagic ||
2583
+ this.#hasMagic ||
2584
+ (this.#options.nocase &&
2585
+ !this.#options.nocaseMagicOnly &&
2586
+ glob.toUpperCase() !== glob.toLowerCase());
2587
+ if (!anyMagic) {
2588
+ return body;
2589
+ }
2590
+ const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
2591
+ return Object.assign(new RegExp(`^${re}$`, flags), {
2592
+ _src: re,
2593
+ _glob: glob,
2594
+ });
2595
+ }
2596
+ // returns the string match, the regexp source, whether there's magic
2597
+ // in the regexp (so a regular expression is required) and whether or
2598
+ // not the uflag is needed for the regular expression (for posix classes)
2599
+ // TODO: instead of injecting the start/end at this point, just return
2600
+ // the BODY of the regexp, along with the start/end portions suitable
2601
+ // for binding the start/end in either a joined full-path makeRe context
2602
+ // (where we bind to (^|/), or a standalone matchPart context (where
2603
+ // we bind to ^, and not /). Otherwise slashes get duped!
2604
+ //
2605
+ // In part-matching mode, the start is:
2606
+ // - if not isStart: nothing
2607
+ // - if traversal possible, but not allowed: ^(?!\.\.?$)
2608
+ // - if dots allowed or not possible: ^
2609
+ // - if dots possible and not allowed: ^(?!\.)
2610
+ // end is:
2611
+ // - if not isEnd(): nothing
2612
+ // - else: $
2613
+ //
2614
+ // In full-path matching mode, we put the slash at the START of the
2615
+ // pattern, so start is:
2616
+ // - if first pattern: same as part-matching mode
2617
+ // - if not isStart(): nothing
2618
+ // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
2619
+ // - if dots allowed or not possible: /
2620
+ // - if dots possible and not allowed: /(?!\.)
2621
+ // end is:
2622
+ // - if last pattern, same as part-matching mode
2623
+ // - else nothing
2624
+ //
2625
+ // Always put the (?:$|/) on negated tails, though, because that has to be
2626
+ // there to bind the end of the negated pattern portion, and it's easier to
2627
+ // just stick it in now rather than try to inject it later in the middle of
2628
+ // the pattern.
2629
+ //
2630
+ // We can just always return the same end, and leave it up to the caller
2631
+ // to know whether it's going to be used joined or in parts.
2632
+ // And, if the start is adjusted slightly, can do the same there:
2633
+ // - if not isStart: nothing
2634
+ // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
2635
+ // - if dots allowed or not possible: (?:/|^)
2636
+ // - if dots possible and not allowed: (?:/|^)(?!\.)
2637
+ //
2638
+ // But it's better to have a simpler binding without a conditional, for
2639
+ // performance, so probably better to return both start options.
2640
+ //
2641
+ // Then the caller just ignores the end if it's not the first pattern,
2642
+ // and the start always gets applied.
2643
+ //
2644
+ // But that's always going to be $ if it's the ending pattern, or nothing,
2645
+ // so the caller can just attach $ at the end of the pattern when building.
2646
+ //
2647
+ // So the todo is:
2648
+ // - better detect what kind of start is needed
2649
+ // - return both flavors of starting pattern
2650
+ // - attach $ at the end of the pattern when creating the actual RegExp
2651
+ //
2652
+ // Ah, but wait, no, that all only applies to the root when the first pattern
2653
+ // is not an extglob. If the first pattern IS an extglob, then we need all
2654
+ // that dot prevention biz to live in the extglob portions, because eg
2655
+ // +(*|.x*) can match .xy but not .yx.
2656
+ //
2657
+ // So, return the two flavors if it's #root and the first child is not an
2658
+ // AST, otherwise leave it to the child AST to handle it, and there,
2659
+ // use the (?:^|/) style of start binding.
2660
+ //
2661
+ // Even simplified further:
2662
+ // - Since the start for a join is eg /(?!\.) and the start for a part
2663
+ // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
2664
+ // or start or whatever) and prepend ^ or / at the Regexp construction.
2665
+ toRegExpSource(allowDot) {
2666
+ const dot = allowDot ?? !!this.#options.dot;
2667
+ if (this.#root === this)
2668
+ this.#fillNegs();
2669
+ if (!this.type) {
2670
+ const noEmpty = this.isStart() && this.isEnd();
2671
+ const src = this.#parts
2672
+ .map(p => {
2673
+ const [re, _, hasMagic, uflag] = typeof p === 'string'
2674
+ ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
2675
+ : p.toRegExpSource(allowDot);
2676
+ this.#hasMagic = this.#hasMagic || hasMagic;
2677
+ this.#uflag = this.#uflag || uflag;
2678
+ return re;
2679
+ })
2680
+ .join('');
2681
+ let start = '';
2682
+ if (this.isStart()) {
2683
+ if (typeof this.#parts[0] === 'string') {
2684
+ // this is the string that will match the start of the pattern,
2685
+ // so we need to protect against dots and such.
2686
+ // '.' and '..' cannot match unless the pattern is that exactly,
2687
+ // even if it starts with . or dot:true is set.
2688
+ const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
2689
+ if (!dotTravAllowed) {
2690
+ const aps = addPatternStart;
2691
+ // check if we have a possibility of matching . or ..,
2692
+ // and prevent that.
2693
+ const needNoTrav =
2694
+ // dots are allowed, and the pattern starts with [ or .
2695
+ (dot && aps.has(src.charAt(0))) ||
2696
+ // the pattern starts with \., and then [ or .
2697
+ (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
2698
+ // the pattern starts with \.\., and then [ or .
2699
+ (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
2700
+ // no need to prevent dots if it can't match a dot, or if a
2701
+ // sub-pattern will be preventing it anyway.
2702
+ const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
2703
+ start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
2704
+ }
2705
+ }
2706
+ }
2707
+ // append the "end of path portion" pattern to negation tails
2708
+ let end = '';
2709
+ if (this.isEnd() &&
2710
+ this.#root.#filledNegs &&
2711
+ this.#parent?.type === '!') {
2712
+ end = '(?:$|\\/)';
2713
+ }
2714
+ const final = start + src + end;
2715
+ return [
2716
+ final,
2717
+ unescape(src),
2718
+ (this.#hasMagic = !!this.#hasMagic),
2719
+ this.#uflag,
2720
+ ];
2721
+ }
2722
+ // We need to calculate the body *twice* if it's a repeat pattern
2723
+ // at the start, once in nodot mode, then again in dot mode, so a
2724
+ // pattern like *(?) can match 'x.y'
2725
+ const repeated = this.type === '*' || this.type === '+';
2726
+ // some kind of extglob
2727
+ const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
2728
+ let body = this.#partsToRegExp(dot);
2729
+ if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
2730
+ // invalid extglob, has to at least be *something* present, if it's
2731
+ // the entire path portion.
2732
+ const s = this.toString();
2733
+ this.#parts = [s];
2734
+ this.type = null;
2735
+ this.#hasMagic = undefined;
2736
+ return [s, unescape(this.toString()), false, false];
2737
+ }
2738
+ // XXX abstract out this map method
2739
+ let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
2740
+ ? ''
2741
+ : this.#partsToRegExp(true);
2742
+ if (bodyDotAllowed === body) {
2743
+ bodyDotAllowed = '';
2744
+ }
2745
+ if (bodyDotAllowed) {
2746
+ body = `(?:${body})(?:${bodyDotAllowed})*?`;
2747
+ }
2748
+ // an empty !() is exactly equivalent to a starNoEmpty
2749
+ let final = '';
2750
+ if (this.type === '!' && this.#emptyExt) {
2751
+ final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
2752
+ }
2753
+ else {
2754
+ const close = this.type === '!'
2755
+ ? // !() must match something,but !(x) can match ''
2756
+ '))' +
2757
+ (this.isStart() && !dot && !allowDot ? startNoDot : '') +
2758
+ star$1 +
2759
+ ')'
2760
+ : this.type === '@'
2761
+ ? ')'
2762
+ : this.type === '?'
2763
+ ? ')?'
2764
+ : this.type === '+' && bodyDotAllowed
2765
+ ? ')'
2766
+ : this.type === '*' && bodyDotAllowed
2767
+ ? `)?`
2768
+ : `)${this.type}`;
2769
+ final = start + body + close;
2770
+ }
2771
+ return [
2772
+ final,
2773
+ unescape(body),
2774
+ (this.#hasMagic = !!this.#hasMagic),
2775
+ this.#uflag,
2776
+ ];
2777
+ }
2778
+ #partsToRegExp(dot) {
2779
+ return this.#parts
2780
+ .map(p => {
2781
+ // extglob ASTs should only contain parent ASTs
2782
+ /* c8 ignore start */
2783
+ if (typeof p === 'string') {
2784
+ throw new Error('string type in extglob ast??');
2785
+ }
2786
+ /* c8 ignore stop */
2787
+ // can ignore hasMagic, because extglobs are already always magic
2788
+ const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
2789
+ this.#uflag = this.#uflag || uflag;
2790
+ return re;
2791
+ })
2792
+ .filter(p => !(this.isStart() && this.isEnd()) || !!p)
2793
+ .join('|');
2794
+ }
2795
+ static #parseGlob(glob, hasMagic, noEmpty = false) {
2796
+ let escaping = false;
2797
+ let re = '';
2798
+ let uflag = false;
2799
+ for (let i = 0; i < glob.length; i++) {
2800
+ const c = glob.charAt(i);
2801
+ if (escaping) {
2802
+ escaping = false;
2803
+ re += (reSpecials.has(c) ? '\\' : '') + c;
2804
+ continue;
2805
+ }
2806
+ if (c === '\\') {
2807
+ if (i === glob.length - 1) {
2808
+ re += '\\\\';
2809
+ }
2810
+ else {
2811
+ escaping = true;
2812
+ }
2813
+ continue;
2814
+ }
2815
+ if (c === '[') {
2816
+ const [src, needUflag, consumed, magic] = parseClass(glob, i);
2817
+ if (consumed) {
2818
+ re += src;
2819
+ uflag = uflag || needUflag;
2820
+ i += consumed - 1;
2821
+ hasMagic = hasMagic || magic;
2822
+ continue;
2823
+ }
2824
+ }
2825
+ if (c === '*') {
2826
+ if (noEmpty && glob === '*')
2827
+ re += starNoEmpty;
2828
+ else
2829
+ re += star$1;
2830
+ hasMagic = true;
2831
+ continue;
2832
+ }
2833
+ if (c === '?') {
2834
+ re += qmark$1;
2835
+ hasMagic = true;
2836
+ continue;
2837
+ }
2838
+ re += regExpEscape$1(c);
2839
+ }
2840
+ return [re, unescape(glob), !!hasMagic, uflag];
2841
+ }
2842
+ }
2843
+
2844
+ /**
2845
+ * Escape all magic characters in a glob pattern.
2846
+ *
2847
+ * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
2848
+ * option is used, then characters are escaped by wrapping in `[]`, because
2849
+ * a magic character wrapped in a character class can only be satisfied by
2850
+ * that exact character. In this mode, `\` is _not_ escaped, because it is
2851
+ * not interpreted as a magic character, but instead as a path separator.
2852
+ */
2853
+ const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
2854
+ // don't need to escape +@! because we escape the parens
2855
+ // that make those magic, and escaping ! as [!] isn't valid,
2856
+ // because [!]] is a valid glob class meaning not ']'.
2857
+ return windowsPathsNoEscape
2858
+ ? s.replace(/[?*()[\]]/g, '[$&]')
2859
+ : s.replace(/[?*()[\]\\]/g, '\\$&');
2860
+ };
2861
+
2862
+ const minimatch = (p, pattern, options = {}) => {
2863
+ assertValidPattern(pattern);
2864
+ // shortcut: comments match nothing.
2865
+ if (!options.nocomment && pattern.charAt(0) === '#') {
2866
+ return false;
2867
+ }
2868
+ return new Minimatch(pattern, options).match(p);
2869
+ };
2870
+ // Optimized checking for the most common glob patterns.
2871
+ const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
2872
+ const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
2873
+ const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
2874
+ const starDotExtTestNocase = (ext) => {
2875
+ ext = ext.toLowerCase();
2876
+ return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
2877
+ };
2878
+ const starDotExtTestNocaseDot = (ext) => {
2879
+ ext = ext.toLowerCase();
2880
+ return (f) => f.toLowerCase().endsWith(ext);
2881
+ };
2882
+ const starDotStarRE = /^\*+\.\*+$/;
2883
+ const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
2884
+ const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
2885
+ const dotStarRE = /^\.\*+$/;
2886
+ const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
2887
+ const starRE = /^\*+$/;
2888
+ const starTest = (f) => f.length !== 0 && !f.startsWith('.');
2889
+ const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
2890
+ const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
2891
+ const qmarksTestNocase = ([$0, ext = '']) => {
2892
+ const noext = qmarksTestNoExt([$0]);
2893
+ if (!ext)
2894
+ return noext;
2895
+ ext = ext.toLowerCase();
2896
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext);
2897
+ };
2898
+ const qmarksTestNocaseDot = ([$0, ext = '']) => {
2899
+ const noext = qmarksTestNoExtDot([$0]);
2900
+ if (!ext)
2901
+ return noext;
2902
+ ext = ext.toLowerCase();
2903
+ return (f) => noext(f) && f.toLowerCase().endsWith(ext);
2904
+ };
2905
+ const qmarksTestDot = ([$0, ext = '']) => {
2906
+ const noext = qmarksTestNoExtDot([$0]);
2907
+ return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
2908
+ };
2909
+ const qmarksTest = ([$0, ext = '']) => {
2910
+ const noext = qmarksTestNoExt([$0]);
2911
+ return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
2912
+ };
2913
+ const qmarksTestNoExt = ([$0]) => {
2914
+ const len = $0.length;
2915
+ return (f) => f.length === len && !f.startsWith('.');
2916
+ };
2917
+ const qmarksTestNoExtDot = ([$0]) => {
2918
+ const len = $0.length;
2919
+ return (f) => f.length === len && f !== '.' && f !== '..';
2920
+ };
2921
+ /* c8 ignore start */
2922
+ const defaultPlatform = (typeof process === 'object' && process
2923
+ ? (typeof process.env === 'object' &&
2924
+ process.env &&
2925
+ process.env.__MINIMATCH_TESTING_PLATFORM__) ||
2926
+ process.platform
2927
+ : 'posix');
2928
+ const path = {
2929
+ win32: { sep: '\\' },
2930
+ posix: { sep: '/' },
2931
+ };
2932
+ /* c8 ignore stop */
2933
+ const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
2934
+ minimatch.sep = sep;
2935
+ const GLOBSTAR = Symbol('globstar **');
2936
+ minimatch.GLOBSTAR = GLOBSTAR;
2937
+ // any single thing other than /
2938
+ // don't need to escape / when using new RegExp()
2939
+ const qmark = '[^/]';
2940
+ // * => any number of characters
2941
+ const star = qmark + '*?';
2942
+ // ** when dots are allowed. Anything goes, except .. and .
2943
+ // not (^ or / followed by one or two dots followed by $ or /),
2944
+ // followed by anything, any number of times.
2945
+ const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
2946
+ // not a ^ or / followed by a dot,
2947
+ // followed by anything, any number of times.
2948
+ const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
2949
+ const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
2950
+ minimatch.filter = filter;
2951
+ const ext = (a, b = {}) => Object.assign({}, a, b);
2952
+ const defaults = (def) => {
2953
+ if (!def || typeof def !== 'object' || !Object.keys(def).length) {
2954
+ return minimatch;
2955
+ }
2956
+ const orig = minimatch;
2957
+ const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
2958
+ return Object.assign(m, {
2959
+ Minimatch: class Minimatch extends orig.Minimatch {
2960
+ constructor(pattern, options = {}) {
2961
+ super(pattern, ext(def, options));
2962
+ }
2963
+ static defaults(options) {
2964
+ return orig.defaults(ext(def, options)).Minimatch;
2965
+ }
2966
+ },
2967
+ AST: class AST extends orig.AST {
2968
+ /* c8 ignore start */
2969
+ constructor(type, parent, options = {}) {
2970
+ super(type, parent, ext(def, options));
2971
+ }
2972
+ /* c8 ignore stop */
2973
+ static fromGlob(pattern, options = {}) {
2974
+ return orig.AST.fromGlob(pattern, ext(def, options));
2975
+ }
2976
+ },
2977
+ unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
2978
+ escape: (s, options = {}) => orig.escape(s, ext(def, options)),
2979
+ filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
2980
+ defaults: (options) => orig.defaults(ext(def, options)),
2981
+ makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
2982
+ braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
2983
+ match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
2984
+ sep: orig.sep,
2985
+ GLOBSTAR: GLOBSTAR,
2986
+ });
2987
+ };
2988
+ minimatch.defaults = defaults;
2989
+ // Brace expansion:
2990
+ // a{b,c}d -> abd acd
2991
+ // a{b,}c -> abc ac
2992
+ // a{0..3}d -> a0d a1d a2d a3d
2993
+ // a{b,c{d,e}f}g -> abg acdfg acefg
2994
+ // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
2995
+ //
2996
+ // Invalid sets are not expanded.
2997
+ // a{2..}b -> a{2..}b
2998
+ // a{b}c -> a{b}c
2999
+ const braceExpand = (pattern, options = {}) => {
3000
+ assertValidPattern(pattern);
3001
+ // Thanks to Yeting Li <https://github.com/yetingli> for
3002
+ // improving this regexp to avoid a ReDOS vulnerability.
3003
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
3004
+ // shortcut. no need to expand.
3005
+ return [pattern];
3006
+ }
3007
+ return expand$1(pattern);
3008
+ };
3009
+ minimatch.braceExpand = braceExpand;
3010
+ // parse a component of the expanded set.
3011
+ // At this point, no pattern may contain "/" in it
3012
+ // so we're going to return a 2d array, where each entry is the full
3013
+ // pattern, split on '/', and then turned into a regular expression.
3014
+ // A regexp is made at the end which joins each array with an
3015
+ // escaped /, and another full one which joins each regexp with |.
3016
+ //
3017
+ // Following the lead of Bash 4.1, note that "**" only has special meaning
3018
+ // when it is the *only* thing in a path portion. Otherwise, any series
3019
+ // of * is equivalent to a single *. Globstar behavior is enabled by
3020
+ // default, and can be disabled by setting options.noglobstar.
3021
+ const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
3022
+ minimatch.makeRe = makeRe;
3023
+ const match = (list, pattern, options = {}) => {
3024
+ const mm = new Minimatch(pattern, options);
3025
+ list = list.filter(f => mm.match(f));
3026
+ if (mm.options.nonull && !list.length) {
3027
+ list.push(pattern);
3028
+ }
3029
+ return list;
3030
+ };
3031
+ minimatch.match = match;
3032
+ // replace stuff like \* with *
3033
+ const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
3034
+ const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
3035
+ class Minimatch {
3036
+ options;
3037
+ set;
3038
+ pattern;
3039
+ windowsPathsNoEscape;
3040
+ nonegate;
3041
+ negate;
3042
+ comment;
3043
+ empty;
3044
+ preserveMultipleSlashes;
3045
+ partial;
3046
+ globSet;
3047
+ globParts;
3048
+ nocase;
3049
+ isWindows;
3050
+ platform;
3051
+ windowsNoMagicRoot;
3052
+ regexp;
3053
+ constructor(pattern, options = {}) {
3054
+ assertValidPattern(pattern);
3055
+ options = options || {};
3056
+ this.options = options;
3057
+ this.pattern = pattern;
3058
+ this.platform = options.platform || defaultPlatform;
3059
+ this.isWindows = this.platform === 'win32';
3060
+ this.windowsPathsNoEscape =
3061
+ !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
3062
+ if (this.windowsPathsNoEscape) {
3063
+ this.pattern = this.pattern.replace(/\\/g, '/');
3064
+ }
3065
+ this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
3066
+ this.regexp = null;
3067
+ this.negate = false;
3068
+ this.nonegate = !!options.nonegate;
3069
+ this.comment = false;
3070
+ this.empty = false;
3071
+ this.partial = !!options.partial;
3072
+ this.nocase = !!this.options.nocase;
3073
+ this.windowsNoMagicRoot =
3074
+ options.windowsNoMagicRoot !== undefined
3075
+ ? options.windowsNoMagicRoot
3076
+ : !!(this.isWindows && this.nocase);
3077
+ this.globSet = [];
3078
+ this.globParts = [];
3079
+ this.set = [];
3080
+ // make the set of regexps etc.
3081
+ this.make();
3082
+ }
3083
+ hasMagic() {
3084
+ if (this.options.magicalBraces && this.set.length > 1) {
3085
+ return true;
3086
+ }
3087
+ for (const pattern of this.set) {
3088
+ for (const part of pattern) {
3089
+ if (typeof part !== 'string')
3090
+ return true;
3091
+ }
3092
+ }
3093
+ return false;
3094
+ }
3095
+ debug(..._) { }
3096
+ make() {
3097
+ const pattern = this.pattern;
3098
+ const options = this.options;
3099
+ // empty patterns and comments match nothing.
3100
+ if (!options.nocomment && pattern.charAt(0) === '#') {
3101
+ this.comment = true;
3102
+ return;
3103
+ }
3104
+ if (!pattern) {
3105
+ this.empty = true;
3106
+ return;
3107
+ }
3108
+ // step 1: figure out negation, etc.
3109
+ this.parseNegate();
3110
+ // step 2: expand braces
3111
+ this.globSet = [...new Set(this.braceExpand())];
3112
+ if (options.debug) {
3113
+ this.debug = (...args) => console.error(...args);
3114
+ }
3115
+ this.debug(this.pattern, this.globSet);
3116
+ // step 3: now we have a set, so turn each one into a series of
3117
+ // path-portion matching patterns.
3118
+ // These will be regexps, except in the case of "**", which is
3119
+ // set to the GLOBSTAR object for globstar behavior,
3120
+ // and will not contain any / characters
3121
+ //
3122
+ // First, we preprocess to make the glob pattern sets a bit simpler
3123
+ // and deduped. There are some perf-killing patterns that can cause
3124
+ // problems with a glob walk, but we can simplify them down a bit.
3125
+ const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
3126
+ this.globParts = this.preprocess(rawGlobParts);
3127
+ this.debug(this.pattern, this.globParts);
3128
+ // glob --> regexps
3129
+ let set = this.globParts.map((s, _, __) => {
3130
+ if (this.isWindows && this.windowsNoMagicRoot) {
3131
+ // check if it's a drive or unc path.
3132
+ const isUNC = s[0] === '' &&
3133
+ s[1] === '' &&
3134
+ (s[2] === '?' || !globMagic.test(s[2])) &&
3135
+ !globMagic.test(s[3]);
3136
+ const isDrive = /^[a-z]:/i.test(s[0]);
3137
+ if (isUNC) {
3138
+ return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
3139
+ }
3140
+ else if (isDrive) {
3141
+ return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
3142
+ }
3143
+ }
3144
+ return s.map(ss => this.parse(ss));
3145
+ });
3146
+ this.debug(this.pattern, set);
3147
+ // filter out everything that didn't compile properly.
3148
+ this.set = set.filter(s => s.indexOf(false) === -1);
3149
+ // do not treat the ? in UNC paths as magic
3150
+ if (this.isWindows) {
3151
+ for (let i = 0; i < this.set.length; i++) {
3152
+ const p = this.set[i];
3153
+ if (p[0] === '' &&
3154
+ p[1] === '' &&
3155
+ this.globParts[i][2] === '?' &&
3156
+ typeof p[3] === 'string' &&
3157
+ /^[a-z]:$/i.test(p[3])) {
3158
+ p[2] = '?';
3159
+ }
3160
+ }
3161
+ }
3162
+ this.debug(this.pattern, this.set);
3163
+ }
3164
+ // various transforms to equivalent pattern sets that are
3165
+ // faster to process in a filesystem walk. The goal is to
3166
+ // eliminate what we can, and push all ** patterns as far
3167
+ // to the right as possible, even if it increases the number
3168
+ // of patterns that we have to process.
3169
+ preprocess(globParts) {
3170
+ // if we're not in globstar mode, then turn all ** into *
3171
+ if (this.options.noglobstar) {
3172
+ for (let i = 0; i < globParts.length; i++) {
3173
+ for (let j = 0; j < globParts[i].length; j++) {
3174
+ if (globParts[i][j] === '**') {
3175
+ globParts[i][j] = '*';
3176
+ }
3177
+ }
3178
+ }
3179
+ }
3180
+ const { optimizationLevel = 1 } = this.options;
3181
+ if (optimizationLevel >= 2) {
3182
+ // aggressive optimization for the purpose of fs walking
3183
+ globParts = this.firstPhasePreProcess(globParts);
3184
+ globParts = this.secondPhasePreProcess(globParts);
3185
+ }
3186
+ else if (optimizationLevel >= 1) {
3187
+ // just basic optimizations to remove some .. parts
3188
+ globParts = this.levelOneOptimize(globParts);
3189
+ }
3190
+ else {
3191
+ globParts = this.adjascentGlobstarOptimize(globParts);
3192
+ }
3193
+ return globParts;
3194
+ }
3195
+ // just get rid of adjascent ** portions
3196
+ adjascentGlobstarOptimize(globParts) {
3197
+ return globParts.map(parts => {
3198
+ let gs = -1;
3199
+ while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
3200
+ let i = gs;
3201
+ while (parts[i + 1] === '**') {
3202
+ i++;
3203
+ }
3204
+ if (i !== gs) {
3205
+ parts.splice(gs, i - gs);
3206
+ }
3207
+ }
3208
+ return parts;
3209
+ });
3210
+ }
3211
+ // get rid of adjascent ** and resolve .. portions
3212
+ levelOneOptimize(globParts) {
3213
+ return globParts.map(parts => {
3214
+ parts = parts.reduce((set, part) => {
3215
+ const prev = set[set.length - 1];
3216
+ if (part === '**' && prev === '**') {
3217
+ return set;
3218
+ }
3219
+ if (part === '..') {
3220
+ if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
3221
+ set.pop();
3222
+ return set;
3223
+ }
3224
+ }
3225
+ set.push(part);
3226
+ return set;
3227
+ }, []);
3228
+ return parts.length === 0 ? [''] : parts;
3229
+ });
3230
+ }
3231
+ levelTwoFileOptimize(parts) {
3232
+ if (!Array.isArray(parts)) {
3233
+ parts = this.slashSplit(parts);
3234
+ }
3235
+ let didSomething = false;
3236
+ do {
3237
+ didSomething = false;
3238
+ // <pre>/<e>/<rest> -> <pre>/<rest>
3239
+ if (!this.preserveMultipleSlashes) {
3240
+ for (let i = 1; i < parts.length - 1; i++) {
3241
+ const p = parts[i];
3242
+ // don't squeeze out UNC patterns
3243
+ if (i === 1 && p === '' && parts[0] === '')
3244
+ continue;
3245
+ if (p === '.' || p === '') {
3246
+ didSomething = true;
3247
+ parts.splice(i, 1);
3248
+ i--;
3249
+ }
3250
+ }
3251
+ if (parts[0] === '.' &&
3252
+ parts.length === 2 &&
3253
+ (parts[1] === '.' || parts[1] === '')) {
3254
+ didSomething = true;
3255
+ parts.pop();
3256
+ }
3257
+ }
3258
+ // <pre>/<p>/../<rest> -> <pre>/<rest>
3259
+ let dd = 0;
3260
+ while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
3261
+ const p = parts[dd - 1];
3262
+ if (p && p !== '.' && p !== '..' && p !== '**') {
3263
+ didSomething = true;
3264
+ parts.splice(dd - 1, 2);
3265
+ dd -= 2;
3266
+ }
3267
+ }
3268
+ } while (didSomething);
3269
+ return parts.length === 0 ? [''] : parts;
3270
+ }
3271
+ // First phase: single-pattern processing
3272
+ // <pre> is 1 or more portions
3273
+ // <rest> is 1 or more portions
3274
+ // <p> is any portion other than ., .., '', or **
3275
+ // <e> is . or ''
3276
+ //
3277
+ // **/.. is *brutal* for filesystem walking performance, because
3278
+ // it effectively resets the recursive walk each time it occurs,
3279
+ // and ** cannot be reduced out by a .. pattern part like a regexp
3280
+ // or most strings (other than .., ., and '') can be.
3281
+ //
3282
+ // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
3283
+ // <pre>/<e>/<rest> -> <pre>/<rest>
3284
+ // <pre>/<p>/../<rest> -> <pre>/<rest>
3285
+ // **/**/<rest> -> **/<rest>
3286
+ //
3287
+ // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
3288
+ // this WOULD be allowed if ** did follow symlinks, or * didn't
3289
+ firstPhasePreProcess(globParts) {
3290
+ let didSomething = false;
3291
+ do {
3292
+ didSomething = false;
3293
+ // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
3294
+ for (let parts of globParts) {
3295
+ let gs = -1;
3296
+ while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
3297
+ let gss = gs;
3298
+ while (parts[gss + 1] === '**') {
3299
+ // <pre>/**/**/<rest> -> <pre>/**/<rest>
3300
+ gss++;
3301
+ }
3302
+ // eg, if gs is 2 and gss is 4, that means we have 3 **
3303
+ // parts, and can remove 2 of them.
3304
+ if (gss > gs) {
3305
+ parts.splice(gs + 1, gss - gs);
3306
+ }
3307
+ let next = parts[gs + 1];
3308
+ const p = parts[gs + 2];
3309
+ const p2 = parts[gs + 3];
3310
+ if (next !== '..')
3311
+ continue;
3312
+ if (!p ||
3313
+ p === '.' ||
3314
+ p === '..' ||
3315
+ !p2 ||
3316
+ p2 === '.' ||
3317
+ p2 === '..') {
3318
+ continue;
3319
+ }
3320
+ didSomething = true;
3321
+ // edit parts in place, and push the new one
3322
+ parts.splice(gs, 1);
3323
+ const other = parts.slice(0);
3324
+ other[gs] = '**';
3325
+ globParts.push(other);
3326
+ gs--;
3327
+ }
3328
+ // <pre>/<e>/<rest> -> <pre>/<rest>
3329
+ if (!this.preserveMultipleSlashes) {
3330
+ for (let i = 1; i < parts.length - 1; i++) {
3331
+ const p = parts[i];
3332
+ // don't squeeze out UNC patterns
3333
+ if (i === 1 && p === '' && parts[0] === '')
3334
+ continue;
3335
+ if (p === '.' || p === '') {
3336
+ didSomething = true;
3337
+ parts.splice(i, 1);
3338
+ i--;
3339
+ }
3340
+ }
3341
+ if (parts[0] === '.' &&
3342
+ parts.length === 2 &&
3343
+ (parts[1] === '.' || parts[1] === '')) {
3344
+ didSomething = true;
3345
+ parts.pop();
3346
+ }
3347
+ }
3348
+ // <pre>/<p>/../<rest> -> <pre>/<rest>
3349
+ let dd = 0;
3350
+ while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
3351
+ const p = parts[dd - 1];
3352
+ if (p && p !== '.' && p !== '..' && p !== '**') {
3353
+ didSomething = true;
3354
+ const needDot = dd === 1 && parts[dd + 1] === '**';
3355
+ const splin = needDot ? ['.'] : [];
3356
+ parts.splice(dd - 1, 2, ...splin);
3357
+ if (parts.length === 0)
3358
+ parts.push('');
3359
+ dd -= 2;
3360
+ }
3361
+ }
3362
+ }
3363
+ } while (didSomething);
3364
+ return globParts;
3365
+ }
3366
+ // second phase: multi-pattern dedupes
3367
+ // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
3368
+ // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
3369
+ // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
3370
+ //
3371
+ // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
3372
+ // ^-- not valid because ** doens't follow symlinks
3373
+ secondPhasePreProcess(globParts) {
3374
+ for (let i = 0; i < globParts.length - 1; i++) {
3375
+ for (let j = i + 1; j < globParts.length; j++) {
3376
+ const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
3377
+ if (!matched)
3378
+ continue;
3379
+ globParts[i] = matched;
3380
+ globParts[j] = [];
3381
+ }
3382
+ }
3383
+ return globParts.filter(gs => gs.length);
3384
+ }
3385
+ partsMatch(a, b, emptyGSMatch = false) {
3386
+ let ai = 0;
3387
+ let bi = 0;
3388
+ let result = [];
3389
+ let which = '';
3390
+ while (ai < a.length && bi < b.length) {
3391
+ if (a[ai] === b[bi]) {
3392
+ result.push(which === 'b' ? b[bi] : a[ai]);
3393
+ ai++;
3394
+ bi++;
3395
+ }
3396
+ else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
3397
+ result.push(a[ai]);
3398
+ ai++;
3399
+ }
3400
+ else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
3401
+ result.push(b[bi]);
3402
+ bi++;
3403
+ }
3404
+ else if (a[ai] === '*' &&
3405
+ b[bi] &&
3406
+ (this.options.dot || !b[bi].startsWith('.')) &&
3407
+ b[bi] !== '**') {
3408
+ if (which === 'b')
3409
+ return false;
3410
+ which = 'a';
3411
+ result.push(a[ai]);
3412
+ ai++;
3413
+ bi++;
3414
+ }
3415
+ else if (b[bi] === '*' &&
3416
+ a[ai] &&
3417
+ (this.options.dot || !a[ai].startsWith('.')) &&
3418
+ a[ai] !== '**') {
3419
+ if (which === 'a')
3420
+ return false;
3421
+ which = 'b';
3422
+ result.push(b[bi]);
3423
+ ai++;
3424
+ bi++;
3425
+ }
3426
+ else {
3427
+ return false;
3428
+ }
3429
+ }
3430
+ // if we fall out of the loop, it means they two are identical
3431
+ // as long as their lengths match
3432
+ return a.length === b.length && result;
3433
+ }
3434
+ parseNegate() {
3435
+ if (this.nonegate)
3436
+ return;
3437
+ const pattern = this.pattern;
3438
+ let negate = false;
3439
+ let negateOffset = 0;
3440
+ for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
3441
+ negate = !negate;
3442
+ negateOffset++;
3443
+ }
3444
+ if (negateOffset)
3445
+ this.pattern = pattern.slice(negateOffset);
3446
+ this.negate = negate;
3447
+ }
3448
+ // set partial to true to test if, for example,
3449
+ // "/a/b" matches the start of "/*/b/*/d"
3450
+ // Partial means, if you run out of file before you run
3451
+ // out of pattern, then that's fine, as long as all
3452
+ // the parts match.
3453
+ matchOne(file, pattern, partial = false) {
3454
+ const options = this.options;
3455
+ // UNC paths like //?/X:/... can match X:/... and vice versa
3456
+ // Drive letters in absolute drive or unc paths are always compared
3457
+ // case-insensitively.
3458
+ if (this.isWindows) {
3459
+ const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
3460
+ const fileUNC = !fileDrive &&
3461
+ file[0] === '' &&
3462
+ file[1] === '' &&
3463
+ file[2] === '?' &&
3464
+ /^[a-z]:$/i.test(file[3]);
3465
+ const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
3466
+ const patternUNC = !patternDrive &&
3467
+ pattern[0] === '' &&
3468
+ pattern[1] === '' &&
3469
+ pattern[2] === '?' &&
3470
+ typeof pattern[3] === 'string' &&
3471
+ /^[a-z]:$/i.test(pattern[3]);
3472
+ const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
3473
+ const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
3474
+ if (typeof fdi === 'number' && typeof pdi === 'number') {
3475
+ const [fd, pd] = [file[fdi], pattern[pdi]];
3476
+ if (fd.toLowerCase() === pd.toLowerCase()) {
3477
+ pattern[pdi] = fd;
3478
+ if (pdi > fdi) {
3479
+ pattern = pattern.slice(pdi);
3480
+ }
3481
+ else if (fdi > pdi) {
3482
+ file = file.slice(fdi);
3483
+ }
3484
+ }
3485
+ }
3486
+ }
3487
+ // resolve and reduce . and .. portions in the file as well.
3488
+ // dont' need to do the second phase, because it's only one string[]
3489
+ const { optimizationLevel = 1 } = this.options;
3490
+ if (optimizationLevel >= 2) {
3491
+ file = this.levelTwoFileOptimize(file);
3492
+ }
3493
+ this.debug('matchOne', this, { file, pattern });
3494
+ this.debug('matchOne', file.length, pattern.length);
3495
+ for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
3496
+ this.debug('matchOne loop');
3497
+ var p = pattern[pi];
3498
+ var f = file[fi];
3499
+ this.debug(pattern, p, f);
3500
+ // should be impossible.
3501
+ // some invalid regexp stuff in the set.
3502
+ /* c8 ignore start */
3503
+ if (p === false) {
3504
+ return false;
3505
+ }
3506
+ /* c8 ignore stop */
3507
+ if (p === GLOBSTAR) {
3508
+ this.debug('GLOBSTAR', [pattern, p, f]);
3509
+ // "**"
3510
+ // a/**/b/**/c would match the following:
3511
+ // a/b/x/y/z/c
3512
+ // a/x/y/z/b/c
3513
+ // a/b/x/b/x/c
3514
+ // a/b/c
3515
+ // To do this, take the rest of the pattern after
3516
+ // the **, and see if it would match the file remainder.
3517
+ // If so, return success.
3518
+ // If not, the ** "swallows" a segment, and try again.
3519
+ // This is recursively awful.
3520
+ //
3521
+ // a/**/b/**/c matching a/b/x/y/z/c
3522
+ // - a matches a
3523
+ // - doublestar
3524
+ // - matchOne(b/x/y/z/c, b/**/c)
3525
+ // - b matches b
3526
+ // - doublestar
3527
+ // - matchOne(x/y/z/c, c) -> no
3528
+ // - matchOne(y/z/c, c) -> no
3529
+ // - matchOne(z/c, c) -> no
3530
+ // - matchOne(c, c) yes, hit
3531
+ var fr = fi;
3532
+ var pr = pi + 1;
3533
+ if (pr === pl) {
3534
+ this.debug('** at the end');
3535
+ // a ** at the end will just swallow the rest.
3536
+ // We have found a match.
3537
+ // however, it will not swallow /.x, unless
3538
+ // options.dot is set.
3539
+ // . and .. are *never* matched by **, for explosively
3540
+ // exponential reasons.
3541
+ for (; fi < fl; fi++) {
3542
+ if (file[fi] === '.' ||
3543
+ file[fi] === '..' ||
3544
+ (!options.dot && file[fi].charAt(0) === '.'))
3545
+ return false;
3546
+ }
3547
+ return true;
3548
+ }
3549
+ // ok, let's see if we can swallow whatever we can.
3550
+ while (fr < fl) {
3551
+ var swallowee = file[fr];
3552
+ this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
3553
+ // XXX remove this slice. Just pass the start index.
3554
+ if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
3555
+ this.debug('globstar found match!', fr, fl, swallowee);
3556
+ // found a match.
3557
+ return true;
3558
+ }
3559
+ else {
3560
+ // can't swallow "." or ".." ever.
3561
+ // can only swallow ".foo" when explicitly asked.
3562
+ if (swallowee === '.' ||
3563
+ swallowee === '..' ||
3564
+ (!options.dot && swallowee.charAt(0) === '.')) {
3565
+ this.debug('dot detected!', file, fr, pattern, pr);
3566
+ break;
3567
+ }
3568
+ // ** swallows a segment, and continue.
3569
+ this.debug('globstar swallow a segment, and continue');
3570
+ fr++;
3571
+ }
3572
+ }
3573
+ // no match was found.
3574
+ // However, in partial mode, we can't say this is necessarily over.
3575
+ /* c8 ignore start */
3576
+ if (partial) {
3577
+ // ran out of file
3578
+ this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
3579
+ if (fr === fl) {
3580
+ return true;
3581
+ }
3582
+ }
3583
+ /* c8 ignore stop */
3584
+ return false;
3585
+ }
3586
+ // something other than **
3587
+ // non-magic patterns just have to match exactly
3588
+ // patterns with magic have been turned into regexps.
3589
+ let hit;
3590
+ if (typeof p === 'string') {
3591
+ hit = f === p;
3592
+ this.debug('string match', p, f, hit);
3593
+ }
3594
+ else {
3595
+ hit = p.test(f);
3596
+ this.debug('pattern match', p, f, hit);
3597
+ }
3598
+ if (!hit)
3599
+ return false;
3600
+ }
3601
+ // Note: ending in / means that we'll get a final ""
3602
+ // at the end of the pattern. This can only match a
3603
+ // corresponding "" at the end of the file.
3604
+ // If the file ends in /, then it can only match a
3605
+ // a pattern that ends in /, unless the pattern just
3606
+ // doesn't have any more for it. But, a/b/ should *not*
3607
+ // match "a/b/*", even though "" matches against the
3608
+ // [^/]*? pattern, except in partial mode, where it might
3609
+ // simply not be reached yet.
3610
+ // However, a/b/ should still satisfy a/*
3611
+ // now either we fell off the end of the pattern, or we're done.
3612
+ if (fi === fl && pi === pl) {
3613
+ // ran out of pattern and filename at the same time.
3614
+ // an exact hit!
3615
+ return true;
3616
+ }
3617
+ else if (fi === fl) {
3618
+ // ran out of file, but still had pattern left.
3619
+ // this is ok if we're doing the match as part of
3620
+ // a glob fs traversal.
3621
+ return partial;
3622
+ }
3623
+ else if (pi === pl) {
3624
+ // ran out of pattern, still have file left.
3625
+ // this is only acceptable if we're on the very last
3626
+ // empty segment of a file with a trailing slash.
3627
+ // a/* should match a/b/
3628
+ return fi === fl - 1 && file[fi] === '';
3629
+ /* c8 ignore start */
3630
+ }
3631
+ else {
3632
+ // should be unreachable.
3633
+ throw new Error('wtf?');
3634
+ }
3635
+ /* c8 ignore stop */
3636
+ }
3637
+ braceExpand() {
3638
+ return braceExpand(this.pattern, this.options);
3639
+ }
3640
+ parse(pattern) {
3641
+ assertValidPattern(pattern);
3642
+ const options = this.options;
3643
+ // shortcuts
3644
+ if (pattern === '**')
3645
+ return GLOBSTAR;
3646
+ if (pattern === '')
3647
+ return '';
3648
+ // far and away, the most common glob pattern parts are
3649
+ // *, *.*, and *.<ext> Add a fast check method for those.
3650
+ let m;
3651
+ let fastTest = null;
3652
+ if ((m = pattern.match(starRE))) {
3653
+ fastTest = options.dot ? starTestDot : starTest;
3654
+ }
3655
+ else if ((m = pattern.match(starDotExtRE))) {
3656
+ fastTest = (options.nocase
3657
+ ? options.dot
3658
+ ? starDotExtTestNocaseDot
3659
+ : starDotExtTestNocase
3660
+ : options.dot
3661
+ ? starDotExtTestDot
3662
+ : starDotExtTest)(m[1]);
3663
+ }
3664
+ else if ((m = pattern.match(qmarksRE))) {
3665
+ fastTest = (options.nocase
3666
+ ? options.dot
3667
+ ? qmarksTestNocaseDot
3668
+ : qmarksTestNocase
3669
+ : options.dot
3670
+ ? qmarksTestDot
3671
+ : qmarksTest)(m);
3672
+ }
3673
+ else if ((m = pattern.match(starDotStarRE))) {
3674
+ fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
3675
+ }
3676
+ else if ((m = pattern.match(dotStarRE))) {
3677
+ fastTest = dotStarTest;
3678
+ }
3679
+ const re = AST.fromGlob(pattern, this.options).toMMPattern();
3680
+ return fastTest ? Object.assign(re, { test: fastTest }) : re;
3681
+ }
3682
+ makeRe() {
3683
+ if (this.regexp || this.regexp === false)
3684
+ return this.regexp;
3685
+ // at this point, this.set is a 2d array of partial
3686
+ // pattern strings, or "**".
3687
+ //
3688
+ // It's better to use .match(). This function shouldn't
3689
+ // be used, really, but it's pretty convenient sometimes,
3690
+ // when you just want to work with a regex.
3691
+ const set = this.set;
3692
+ if (!set.length) {
3693
+ this.regexp = false;
3694
+ return this.regexp;
3695
+ }
3696
+ const options = this.options;
3697
+ const twoStar = options.noglobstar
3698
+ ? star
3699
+ : options.dot
3700
+ ? twoStarDot
3701
+ : twoStarNoDot;
3702
+ const flags = new Set(options.nocase ? ['i'] : []);
3703
+ // regexpify non-globstar patterns
3704
+ // if ** is only item, then we just do one twoStar
3705
+ // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
3706
+ // if ** is last, append (\/twoStar|) to previous
3707
+ // if ** is in the middle, append (\/|\/twoStar\/) to previous
3708
+ // then filter out GLOBSTAR symbols
3709
+ let re = set
3710
+ .map(pattern => {
3711
+ const pp = pattern.map(p => {
3712
+ if (p instanceof RegExp) {
3713
+ for (const f of p.flags.split(''))
3714
+ flags.add(f);
3715
+ }
3716
+ return typeof p === 'string'
3717
+ ? regExpEscape(p)
3718
+ : p === GLOBSTAR
3719
+ ? GLOBSTAR
3720
+ : p._src;
3721
+ });
3722
+ pp.forEach((p, i) => {
3723
+ const next = pp[i + 1];
3724
+ const prev = pp[i - 1];
3725
+ if (p !== GLOBSTAR || prev === GLOBSTAR) {
3726
+ return;
3727
+ }
3728
+ if (prev === undefined) {
3729
+ if (next !== undefined && next !== GLOBSTAR) {
3730
+ pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
3731
+ }
3732
+ else {
3733
+ pp[i] = twoStar;
3734
+ }
3735
+ }
3736
+ else if (next === undefined) {
3737
+ pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
3738
+ }
3739
+ else if (next !== GLOBSTAR) {
3740
+ pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
3741
+ pp[i + 1] = GLOBSTAR;
3742
+ }
3743
+ });
3744
+ return pp.filter(p => p !== GLOBSTAR).join('/');
3745
+ })
3746
+ .join('|');
3747
+ // need to wrap in parens if we had more than one thing with |,
3748
+ // otherwise only the first will be anchored to ^ and the last to $
3749
+ const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
3750
+ // must match entire pattern
3751
+ // ending in a * or ** will make it less strict.
3752
+ re = '^' + open + re + close + '$';
3753
+ // can match anything, as long as it's not this.
3754
+ if (this.negate)
3755
+ re = '^(?!' + re + ').+$';
3756
+ try {
3757
+ this.regexp = new RegExp(re, [...flags].join(''));
3758
+ /* c8 ignore start */
3759
+ }
3760
+ catch (ex) {
3761
+ // should be impossible
3762
+ this.regexp = false;
3763
+ }
3764
+ /* c8 ignore stop */
3765
+ return this.regexp;
3766
+ }
3767
+ slashSplit(p) {
3768
+ // if p starts with // on windows, we preserve that
3769
+ // so that UNC paths aren't broken. Otherwise, any number of
3770
+ // / characters are coalesced into one, unless
3771
+ // preserveMultipleSlashes is set to true.
3772
+ if (this.preserveMultipleSlashes) {
3773
+ return p.split('/');
3774
+ }
3775
+ else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
3776
+ // add an extra '' for the one we lose
3777
+ return ['', ...p.split(/\/+/)];
3778
+ }
3779
+ else {
3780
+ return p.split(/\/+/);
3781
+ }
3782
+ }
3783
+ match(f, partial = this.partial) {
3784
+ this.debug('match', f, this.pattern);
3785
+ // short-circuit in the case of busted things.
3786
+ // comments, etc.
3787
+ if (this.comment) {
3788
+ return false;
3789
+ }
3790
+ if (this.empty) {
3791
+ return f === '';
3792
+ }
3793
+ if (f === '/' && partial) {
3794
+ return true;
3795
+ }
3796
+ const options = this.options;
3797
+ // windows: need to use /, not \
3798
+ if (this.isWindows) {
3799
+ f = f.split('\\').join('/');
3800
+ }
3801
+ // treat the test path as a set of pathparts.
3802
+ const ff = this.slashSplit(f);
3803
+ this.debug(this.pattern, 'split', ff);
3804
+ // just ONE of the pattern sets in this.set needs to match
3805
+ // in order for it to be valid. If negating, then just one
3806
+ // match means that we have failed.
3807
+ // Either way, return on the first hit.
3808
+ const set = this.set;
3809
+ this.debug(this.pattern, 'set', set);
3810
+ // Find the basename of the path by looking for the last non-empty segment
3811
+ let filename = ff[ff.length - 1];
3812
+ if (!filename) {
3813
+ for (let i = ff.length - 2; !filename && i >= 0; i--) {
3814
+ filename = ff[i];
3815
+ }
3816
+ }
3817
+ for (let i = 0; i < set.length; i++) {
3818
+ const pattern = set[i];
3819
+ let file = ff;
3820
+ if (options.matchBase && pattern.length === 1) {
3821
+ file = [filename];
3822
+ }
3823
+ const hit = this.matchOne(file, pattern, partial);
3824
+ if (hit) {
3825
+ if (options.flipNegate) {
3826
+ return true;
3827
+ }
3828
+ return !this.negate;
3829
+ }
3830
+ }
3831
+ // didn't get any hits. this is success if it's a negative
3832
+ // pattern, failure otherwise.
3833
+ if (options.flipNegate) {
3834
+ return false;
3835
+ }
3836
+ return this.negate;
3837
+ }
3838
+ static defaults(def) {
3839
+ return minimatch.defaults(def).Minimatch;
3840
+ }
3841
+ }
3842
+ /* c8 ignore stop */
3843
+ minimatch.AST = AST;
3844
+ minimatch.Minimatch = Minimatch;
3845
+ minimatch.escape = escape;
3846
+ minimatch.unescape = unescape;
3847
+
3848
+ const defaultDelimeters = ['{{', '}}'];
3849
+ class ProstoRewrite {
3850
+ constructor(options) {
3851
+ var _a, _b;
3852
+ this.options = {
3853
+ defaultMode: (options === null || options === void 0 ? void 0 : options.defaultMode) || 'auto',
3854
+ debug: (options === null || options === void 0 ? void 0 : options.debug) || false,
3855
+ htmlPattern: ((options === null || options === void 0 ? void 0 : options.htmlPattern) || ['*.{html,xhtml,xml,svg}']).map(p => new Minimatch(p, { matchBase: true })) ,
3856
+ textPattern: ((options === null || options === void 0 ? void 0 : options.textPattern) || [
3857
+ '*.{js,jsx,ts,tsx,txt,json,yml,yaml,md,ini}',
3858
+ 'Dockerfile',
3859
+ '*config',
3860
+ '.gitignore',
3861
+ ]).map(p => new Minimatch(p, { matchBase: true })) ,
3862
+ html: {
3863
+ exprDelimeters: defaultDelimeters,
3864
+ attrExpression: ':',
3865
+ blockOperation: 'v-',
3866
+ directive: '!@',
3867
+ voidTags: ((_a = options === null || options === void 0 ? void 0 : options.html) === null || _a === void 0 ? void 0 : _a.voidTags) || htmlVoidTags,
3868
+ textTags: ((_b = options === null || options === void 0 ? void 0 : options.html) === null || _b === void 0 ? void 0 : _b.textTags) || htmlTextTags,
3869
+ ...options === null || options === void 0 ? void 0 : options.html,
3870
+ },
3871
+ text: {
3872
+ exprDelimeters: defaultDelimeters,
3873
+ blockOperation: '=',
3874
+ revealLine: ':',
3875
+ directive: '!@',
3876
+ ...options === null || options === void 0 ? void 0 : options.text,
3877
+ },
3878
+ };
3879
+ }
3880
+ get mixedRewriter() {
3881
+ const textNodes = getTextParser(this.options.text, true);
3882
+ const htmlNodes = getHtmlParser(this.options.html, true);
3883
+ textNodes.htmlDirectiveNode.addRecognizes(...htmlNodes.rootNode.recognizes);
3884
+ htmlNodes.textDirectiveNode.addRecognizes(...textNodes.rootNode.recognizes);
3885
+ return {
3886
+ text: getRewriter(textNodes.rootNode, this.options.debug),
3887
+ html: getRewriter(htmlNodes.rootNode, this.options.debug),
3888
+ };
3889
+ }
3890
+ get textRewriter() {
3891
+ return getTextRewriter(this.options.text, this.options.debug);
3892
+ }
3893
+ get htmlRewriter() {
3894
+ return getHtmlRewriter(this.options.html, this.options.debug);
3895
+ }
3896
+ async rewriteFile(opts, context) {
3897
+ const file = await readFile(opts.input);
3898
+ const mode = this.determineMode(opts.mode || this.options.defaultMode, opts.input, file);
3899
+ let output = file;
3900
+ const modes = this.mixedRewriter;
3901
+ if (mode) {
3902
+ this.debug('Parsing file in ' + mode + ' mode. ' + '' + '' + opts.input);
3903
+ output = modes[mode].rewrite(file, context);
3904
+ }
3905
+ else {
3906
+ this.debug('File isn\'t recognized as text nor as html. ' + '' + '' + opts.input);
3907
+ }
3908
+ if (opts.output) {
3909
+ if (mode) {
3910
+ await writeFile(opts.output, output);
3911
+ this.debug('File has been rewritten in ' + mode + ' mode. ' + '' + '' + opts.output);
3912
+ }
3913
+ else {
3914
+ await copyFile(opts.input, opts.output);
3915
+ this.debug('File rewriting was skipped. File copied. ' + '' + '' + opts.output);
3916
+ }
3917
+ }
3918
+ return output;
3919
+ }
3920
+ async rewriteDir(opts, context) {
3921
+ const files = await readDir(opts.baseDir);
3922
+ const dirPath = await pathResolve(opts.baseDir);
3923
+ const include = opts.include && opts.include.length ? opts.include.map(s => new Minimatch(s, { matchBase: true })) : null;
3924
+ const exclude = opts.exclude && opts.exclude.length ? opts.exclude.map(s => new Minimatch(s, { matchBase: true })) : null;
3925
+ const rename = opts.renameFile || (f => f);
3926
+ for await (const filePath of files) {
3927
+ let included = true;
3928
+ let excluded = false;
3929
+ if (include)
3930
+ included = !!include.find(m => m.match(filePath));
3931
+ if (exclude && included)
3932
+ excluded = !!exclude.find(m => m.match(filePath));
3933
+ if (!included || excluded)
3934
+ continue;
3935
+ const relativeFilePath = rename(filePath.slice(dirPath.length + 1));
3936
+ let targetPath;
3937
+ if (opts.output) {
3938
+ targetPath = await pathJoin(opts.output, relativeFilePath);
3939
+ }
3940
+ const output = await this.rewriteFile({
3941
+ mode: opts.mode,
3942
+ input: filePath,
3943
+ output: targetPath,
3944
+ }, context);
3945
+ if (opts.onFile) {
3946
+ opts.onFile(filePath, output);
3947
+ }
3948
+ }
3949
+ }
3950
+ determineMode(mode, path, content) {
3951
+ if (mode === 'text')
3952
+ return 'text';
3953
+ if (mode === 'html')
3954
+ return 'html';
3955
+ if (mode === 'auto') {
3956
+ const isText = !!this.options.textPattern.find(m => m.match(path));
3957
+ const isHtml = !!this.options.htmlPattern.find(m => m.match(path));
3958
+ if (isText && isHtml) {
3959
+ if (/^<!DOCTYPE\s/.test(content))
3960
+ return 'html';
3961
+ if (/^<\?xml\s/.test(content))
3962
+ return 'html';
3963
+ return 'text';
3964
+ }
3965
+ if (isText)
3966
+ return 'text';
3967
+ if (isHtml)
3968
+ return 'html';
3969
+ }
3970
+ }
3971
+ debug(message) {
3972
+ if (!this.options.debug)
3973
+ return;
3974
+ debug(message);
3975
+ }
3976
+ }
3977
+
3978
+ export { ProstoRewrite, genSafeFunc, getRewriter, getStringExpressionRewriter, pushString, renderCode };