@prostojs/rewrite 0.1.1 → 0.2.0

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