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