@ohos-ports/html-minifier-next 8.4.2-beta.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.
Files changed (51) hide show
  1. package/LICENSE.txt +23 -0
  2. package/README.md +776 -0
  3. package/cli.js +1209 -0
  4. package/dist/types/htmlminifier.d.ts +556 -0
  5. package/dist/types/htmlminifier.d.ts.map +1 -0
  6. package/dist/types/htmlparser.d.ts +25 -0
  7. package/dist/types/htmlparser.d.ts.map +1 -0
  8. package/dist/types/lib/attributes.d.ts +155 -0
  9. package/dist/types/lib/attributes.d.ts.map +1 -0
  10. package/dist/types/lib/constants.d.ts +110 -0
  11. package/dist/types/lib/constants.d.ts.map +1 -0
  12. package/dist/types/lib/content.d.ts +51 -0
  13. package/dist/types/lib/content.d.ts.map +1 -0
  14. package/dist/types/lib/elements.d.ts +57 -0
  15. package/dist/types/lib/elements.d.ts.map +1 -0
  16. package/dist/types/lib/fragments.d.ts +46 -0
  17. package/dist/types/lib/fragments.d.ts.map +1 -0
  18. package/dist/types/lib/option-definitions.d.ts +33 -0
  19. package/dist/types/lib/option-definitions.d.ts.map +1 -0
  20. package/dist/types/lib/options.d.ts +120 -0
  21. package/dist/types/lib/options.d.ts.map +1 -0
  22. package/dist/types/lib/unused-css.d.ts +46 -0
  23. package/dist/types/lib/unused-css.d.ts.map +1 -0
  24. package/dist/types/lib/urls.d.ts +15 -0
  25. package/dist/types/lib/urls.d.ts.map +1 -0
  26. package/dist/types/lib/utils.d.ts +102 -0
  27. package/dist/types/lib/utils.d.ts.map +1 -0
  28. package/dist/types/lib/whitespace.d.ts +45 -0
  29. package/dist/types/lib/whitespace.d.ts.map +1 -0
  30. package/dist/types/presets.d.ts +49 -0
  31. package/dist/types/presets.d.ts.map +1 -0
  32. package/dist/types/tokenchain.d.ts +26 -0
  33. package/dist/types/tokenchain.d.ts.map +1 -0
  34. package/html-minifier-next.schema.json +306 -0
  35. package/package.json +100 -0
  36. package/src/htmlminifier.js +2294 -0
  37. package/src/htmlparser.js +1069 -0
  38. package/src/lib/attributes.js +928 -0
  39. package/src/lib/constants.js +285 -0
  40. package/src/lib/content.js +190 -0
  41. package/src/lib/elements.js +274 -0
  42. package/src/lib/file-pool.js +177 -0
  43. package/src/lib/fragments.js +274 -0
  44. package/src/lib/option-definitions.js +231 -0
  45. package/src/lib/options.js +730 -0
  46. package/src/lib/unused-css.js +379 -0
  47. package/src/lib/urls.js +155 -0
  48. package/src/lib/utils.js +861 -0
  49. package/src/lib/whitespace.js +321 -0
  50. package/src/presets.js +57 -0
  51. package/src/tokenchain.js +123 -0
@@ -0,0 +1,861 @@
1
+ /**
2
+ * General utility functions
3
+ */
4
+
5
+ /**
6
+ * @param {unknown} obj
7
+ * @returns {string}
8
+ */
9
+ function stableStringify(obj) {
10
+ if (obj == null || typeof obj !== 'object') return JSON.stringify(obj);
11
+ if (Array.isArray(obj)) return '[' + obj.map(stableStringify).join(',') + ']';
12
+ const keys = Object.keys(obj).sort();
13
+ let out = '{';
14
+ for (let i = 0; i < keys.length; i++) {
15
+ const k = keys[i] ?? '';
16
+ out += JSON.stringify(k) + ':' + stableStringify(/** @type {Record<string, unknown>} */ (obj)[k]) + (i < keys.length - 1 ? ',' : '');
17
+ }
18
+ return out + '}';
19
+ }
20
+
21
+ // LRU cache for strings and promises
22
+
23
+ class LRU {
24
+ constructor(limit = 200) {
25
+ this.limit = limit;
26
+ this.gets = 0;
27
+ this.hits = 0;
28
+ /** @type {Map<string, unknown>} */
29
+ this.map = new Map();
30
+ }
31
+ /** @param {string} key */
32
+ get(key) {
33
+ this.gets++;
34
+ if (this.map.has(key)) {
35
+ this.hits++;
36
+ const v = this.map.get(key);
37
+ this.map.delete(key);
38
+ this.map.set(key, v);
39
+ return v;
40
+ }
41
+ return undefined;
42
+ }
43
+ /**
44
+ * @param {string} key
45
+ * @param {unknown} value
46
+ */
47
+ set(key, value) {
48
+ if (this.map.has(key)) this.map.delete(key);
49
+ this.map.set(key, value);
50
+ if (this.map.size > this.limit) {
51
+ const first = this.map.keys().next().value;
52
+ if (first !== undefined) this.map.delete(first);
53
+ }
54
+ }
55
+ /** @param {string} key */
56
+ delete(key) { this.map.delete(key); }
57
+ /** @returns {{ gets: number, hits: number, size: number, limit: number }} */
58
+ stats() {
59
+ return { gets: this.gets, hits: this.hits, size: this.map.size, limit: this.limit };
60
+ }
61
+ }
62
+
63
+ // Content longer than this (in UTF-16 code units, roughly bytes for typical CSS/JS/SVG) is
64
+ // minified normally but never stored in a minification cache—caps worst-case cache memory
65
+ // (entry count × this size) without affecting realistically sized inline content
66
+ const MAX_CACHE_ENTRY_SIZE = 1024 * 1024; // 1 MB
67
+
68
+ // FNV-1a 32-bit hash for large-input cache keys
69
+
70
+ /** @param {string} str */
71
+ function hashContent(str) {
72
+ let hash = 2166136261;
73
+ for (let i = 0; i < str.length; i++) {
74
+ hash ^= str.charCodeAt(i);
75
+ hash = Math.imul(hash, 16777619);
76
+ }
77
+ return (hash >>> 0).toString(36);
78
+ }
79
+
80
+ // Unique ID generator
81
+
82
+ /** @param {string} value */
83
+ function uniqueId(value) {
84
+ let id;
85
+ do {
86
+ id = 'u' + crypto.randomUUID().replace(/-/g, '');
87
+ } while (~value.indexOf(id));
88
+ return id;
89
+ }
90
+
91
+ // Identity and transform functions
92
+
93
+ /** @param {string} value */
94
+ function identity(value) {
95
+ return value;
96
+ }
97
+
98
+ /**
99
+ * @param {unknown} value
100
+ * @returns {value is PromiseLike<any>}
101
+ */
102
+ function isThenable(value) {
103
+ return value != null && typeof value === 'object' && typeof /** @type {any} */ (value).then === 'function';
104
+ }
105
+
106
+ /** @param {string} value */
107
+ function lowercase(value) {
108
+ return value.toLowerCase();
109
+ }
110
+
111
+ // Option name to CLI flag name (ASCII-only, no Unicode needed)
112
+ /** @param {string} value */
113
+ function paramCase(value) {
114
+ return value.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
115
+ }
116
+
117
+ // Replace async helper
118
+
119
+ /**
120
+ * Asynchronously replace matches in a string.
121
+ * @param {string} str - Input string
122
+ * @param {RegExp} regex - Regular expression with global flag
123
+ * @param {Function} asyncFn - Async function to process each match
124
+ * @returns {Promise<string>} Processed string
125
+ */
126
+ async function replaceAsync(str, regex, asyncFn) {
127
+ /** @type {Promise<string>[]} */
128
+ const promises = [];
129
+
130
+ str.replace(regex, /** @returns {string} */ (match, ...args) => {
131
+ const promise = asyncFn(match, ...args);
132
+ promises.push(promise);
133
+ return match;
134
+ });
135
+
136
+ const data = await Promise.all(promises);
137
+ let next = 0;
138
+ return str.replace(regex, () => data[next++] ?? '');
139
+ }
140
+
141
+ // String patterns to RegExp conversion (for JSON config support)
142
+
143
+ /** @param {string | RegExp} value */
144
+ function parseRegExp(value) {
145
+ if (typeof value === 'string') {
146
+ if (!value) return undefined; // Empty string = not configured
147
+ const match = value.match(/^\/(.+)\/([dgimsuvy]*)$/);
148
+ if (match) {
149
+ return new RegExp(match[1] ?? '', match[2] ?? '');
150
+ }
151
+ return new RegExp(value);
152
+ }
153
+ return value;
154
+ }
155
+
156
+ // Regex source reading, shared by the analysis and the rewriting below
157
+
158
+ const RE_ASCII_LETTER = /^[a-zA-Z]$/;
159
+ const RE_HEX_PAIR = /^[0-9a-fA-F]{2}$/;
160
+ const RE_HEX_QUAD = /^[0-9a-fA-F]{4}$/;
161
+
162
+ /**
163
+ * @param {string} source @param {number} index - Index of the opening `[`
164
+ * @param {boolean} [nested] - Whether the pattern carries `v`, where a class nests
165
+ * inside a class and the first `]` need not be the one that closes it
166
+ * @returns {number} Index just past the closing `]`
167
+ */
168
+ function skipCharacterClass(source, index, nested = false) {
169
+ let i = index + 1;
170
+ let open = 1;
171
+ while (i < source.length && open > 0) {
172
+ const char = source[i];
173
+ if (char === '\\') i += tokenLength(source, i);
174
+ else {
175
+ if (nested && char === '[') open++;
176
+ else if (char === ']') open--;
177
+ i++;
178
+ }
179
+ }
180
+ return i;
181
+ }
182
+
183
+ /**
184
+ * Length of the token at `index`, so that a multi-character escape is read whole
185
+ * rather than leaving its tail to be mistaken for literals.
186
+ * @param {string} source @param {number} index
187
+ */
188
+ function tokenLength(source, index) {
189
+ if (source[index] !== '\\') return 1;
190
+ const next = source[index + 1];
191
+ if (next === 'x' && RE_HEX_PAIR.test(source.slice(index + 2, index + 4))) return 4;
192
+ if (next === 'u') {
193
+ if (source[index + 2] === '{') {
194
+ const close = source.indexOf('}', index + 3);
195
+ if (close !== -1) return close - index + 1;
196
+ }
197
+ if (RE_HEX_QUAD.test(source.slice(index + 2, index + 6))) return 6;
198
+ }
199
+ if (next === 'c' && RE_ASCII_LETTER.test(source[index + 2] ?? '')) return 3;
200
+ // A `v` class holds string literals, which fold as strings or not at all
201
+ if (next === 'q' && source[index + 2] === '{') {
202
+ const close = source.indexOf('}', index + 3);
203
+ if (close !== -1) return close - index + 1;
204
+ }
205
+ // A property name or a group name is syntax, not text to fold
206
+ if ((next === 'p' || next === 'P') && source[index + 2] === '{') {
207
+ const close = source.indexOf('}', index + 3);
208
+ if (close !== -1) return close - index + 1;
209
+ }
210
+ if (next === 'k' && source[index + 2] === '<') {
211
+ const close = source.indexOf('>', index + 3);
212
+ if (close !== -1) return close - index + 1;
213
+ }
214
+ return 2;
215
+ }
216
+
217
+ // ReDoS risk detection for user-supplied patterns
218
+
219
+ // Quantifier following an atom, with its optional lazy `?`; the captures hold
220
+ // the bounds of a `{n,m}` form, the upper one empty when the form is `{n,}`
221
+ const RE_QUANTIFIER = /(?:[*+?]|\{(\d+)(?:,(\d*))?\})\??/y;
222
+
223
+ // Bounds for the walk below: Patterns beyond either are judged risky unread,
224
+ // which keeps a pathological source from nesting the analysis into a stack
225
+ // overflow or making it rescan its groups once per level
226
+ const MAX_PATTERN_LENGTH = 10000;
227
+ const MAX_PATTERN_DEPTH = 50;
228
+
229
+ // A group that only wraps its body backtracks the way that body does, so
230
+ // `(?:a)` and `a` count as the same atom; lookarounds are left alone
231
+ const RE_TRANSPARENT_GROUP = /^\((?:\?:|\?<[^>=!][^>]*>)?([\s\S]*)\)$/;
232
+
233
+ // A quantifier of exactly one repetition, which is notation rather than shape
234
+ const RE_EXACT_ONE = /\{1(?:,1)?\}\??$/;
235
+
236
+ // An atom that matches without consuming, so what precedes it stays adjacent to
237
+ // what follows; a group that can match empty is left out, being rare enough that
238
+ // missing it costs less than reading every body for it
239
+ const RE_ZERO_WIDTH = /^(?:[$^]|\\[bB]|\((?:\?[=!]|\?<[=!]))/;
240
+
241
+ // How many repeats an atom may still be adjacent to across atoms matching empty;
242
+ // comparing against every one of them is what the bound keeps from turning
243
+ // quadratic on a pattern that is nothing but repeats
244
+ const MAX_REACHABLE = 50;
245
+
246
+ /** @param {string} atom - Atom as it reads in the source */
247
+ function unwrapAtom(atom) {
248
+ let inner = atom;
249
+ for (let level = 0; level < MAX_PATTERN_DEPTH; level++) {
250
+ const next = inner.replace(RE_EXACT_ONE, '').replace(RE_TRANSPARENT_GROUP, '$1');
251
+ if (next === inner) break;
252
+ inner = next;
253
+ }
254
+ return inner;
255
+ }
256
+
257
+ // Two atoms that repeat unboundedly side by side split a run between them in as
258
+ // many ways as the run is long, whenever both can consume the same character.
259
+ // Comparing what they match, rather than how they are spelled, is what catches
260
+ // `[a]*a*` and `\w*\d*` alongside `a*a*`.
261
+
262
+ const MAX_CODE_POINT = 0x10FFFF;
263
+
264
+ /** @type {Record<string, [number, number][]>} */
265
+ const CLASS_ESCAPE_RANGES = {
266
+ d: [[0x30, 0x39]],
267
+ w: [[0x30, 0x39], [0x41, 0x5A], [0x5F, 0x5F], [0x61, 0x7A]],
268
+ s: [[0x09, 0x0D], [0x20, 0x20], [0xA0, 0xA0], [0x1680, 0x1680], [0x2000, 0x200A],
269
+ [0x2028, 0x2029], [0x202F, 0x202F], [0x205F, 0x205F], [0x3000, 0x3000], [0xFEFF, 0xFEFF]]
270
+ };
271
+
272
+ /** @type {Record<string, number>} */
273
+ const CONTROL_ESCAPE_CODES = { 0: 0x00, f: 0x0C, n: 0x0A, r: 0x0D, t: 0x09, v: 0x0B };
274
+
275
+ // An escape that stands for something other than one character of text
276
+ const RE_NON_CHARACTER_ESCAPE = /[bBdDkpPsSwW1-9]/;
277
+
278
+ /** @param {[number, number][]} ranges */
279
+ function complement(ranges) {
280
+ const sorted = [...ranges].sort((one, other) => one[0] - other[0]);
281
+ /** @type {[number, number][]} */
282
+ const out = [];
283
+ let next = 0;
284
+ for (const [low, high] of sorted) {
285
+ if (low > next) out.push([next, low - 1]);
286
+ next = Math.max(next, high + 1);
287
+ }
288
+ if (next <= MAX_CODE_POINT) out.push([next, MAX_CODE_POINT]);
289
+ return out;
290
+ }
291
+
292
+ // `.` as a bare source reads it, without the `s` flag the source cannot carry
293
+ const DOT_RANGES = complement([[0x0A, 0x0A], [0x0D, 0x0D], [0x2028, 0x2029]]);
294
+
295
+ /**
296
+ * @param {string} token - One token, as `tokenLength` measures it
297
+ * @param {boolean} [inClass] - Whether the token sits inside a character class
298
+ * @returns {[number, number][] | null} What it matches, or `null` where it is not
299
+ * one character of text
300
+ */
301
+ function tokenRanges(token, inClass = false) {
302
+ if (token[0] !== '\\') {
303
+ const code = token.codePointAt(0) ?? 0;
304
+ return String.fromCodePoint(code) === token ? [[code, code]] : null;
305
+ }
306
+
307
+ const kind = token[1] ?? '';
308
+ const named = CLASS_ESCAPE_RANGES[kind.toLowerCase()];
309
+ if (named) return kind === kind.toLowerCase() ? named : complement(named);
310
+
311
+ const control = CONTROL_ESCAPE_CODES[kind];
312
+ if (control !== undefined) return [[control, control]];
313
+
314
+ if (kind === 'x' || kind === 'u') {
315
+ const code = Number.parseInt(token[2] === '{' ? token.slice(3, -1) : token.slice(2), 16);
316
+ return Number.isNaN(code) || code > MAX_CODE_POINT ? null : [[code, code]];
317
+ }
318
+ if (kind === 'c') {
319
+ const code = token.charCodeAt(2) % 32;
320
+ return [[code, code]];
321
+ }
322
+ // `\b` asserts a word boundary on its own, and is a backspace inside a class
323
+ if (kind === 'b' && inClass) return [[0x08, 0x08]];
324
+ // `\q{…}` stands for whole strings, not for a character
325
+ if (token.startsWith('\\q{')) return null;
326
+ if (RE_NON_CHARACTER_ESCAPE.test(kind)) return null;
327
+
328
+ // The rest is punctuation escaped to be read as itself
329
+ const code = token.codePointAt(1) ?? 0;
330
+ return String.fromCodePoint(code) === token.slice(1) ? [[code, code]] : null;
331
+ }
332
+
333
+ /** @param {[number, number][] | null} ranges @returns {number | null} The one code point it holds */
334
+ function singleCode(ranges) {
335
+ const [range] = ranges ?? [];
336
+ return ranges?.length === 1 && range && range[0] === range[1] ? range[0] : null;
337
+ }
338
+
339
+ /**
340
+ * @param {string} atom - Atom as it reads in the source, already unwrapped
341
+ * @param {boolean} [nested] - Whether the pattern carries `v`
342
+ * @param {number} [depth] - Class nesting level of this call
343
+ * @returns {[number, number][] | null} What it matches, or `null` where it is not
344
+ * one character of text, or one this does not read
345
+ */
346
+ function atomRanges(atom, nested = false, depth = 0) {
347
+ if (depth > MAX_PATTERN_DEPTH) return null;
348
+ if (atom === '.') return DOT_RANGES;
349
+ if (atom[0] !== '[') return tokenRanges(atom);
350
+ if (!atom.endsWith(']')) return null;
351
+
352
+ let i = atom[1] === '^' ? 2 : 1;
353
+ const negated = i === 2;
354
+ const end = atom.length - 1;
355
+ /** @type {[number, number][]} */
356
+ const members = [];
357
+
358
+ while (i < end) {
359
+ // A `v` class nests, and nesting alone is a union to read through
360
+ if (nested && atom[i] === '[') {
361
+ const close = skipCharacterClass(atom, i, true);
362
+ const inner = atomRanges(atom.slice(i, close), true, depth + 1);
363
+ if (!inner) return null;
364
+ members.push(...inner);
365
+ i = close;
366
+ continue;
367
+ }
368
+ // Subtraction and intersection are not unions, and are left unread
369
+ //
370
+ // @@ Read `--` and `&&` as set difference and intersection
371
+ // (so that a `v` class built is compared rather than passed unjudged)
372
+ if (nested && (atom.startsWith('--', i) || atom.startsWith('&&', i))) return null;
373
+
374
+ const fromLength = tokenLength(atom, i);
375
+ const from = tokenRanges(atom.slice(i, i + fromLength), true);
376
+ if (!from) return null;
377
+ i += fromLength;
378
+
379
+ // A dash right before the closing `]` is a member, not the start of a range
380
+ if (atom[i] !== '-' || i + 1 >= end) {
381
+ members.push(...from);
382
+ continue;
383
+ }
384
+ const toLength = tokenLength(atom, i + 1);
385
+ // Only single characters bound a range; `\d-z` is not a range at all
386
+ const low = singleCode(from);
387
+ const high = singleCode(tokenRanges(atom.slice(i + 1, i + 1 + toLength), true));
388
+ if (low === null || high === null) return null;
389
+ members.push([low, high]);
390
+ i += 1 + toLength;
391
+ }
392
+
393
+ return negated ? complement(members) : members;
394
+ }
395
+
396
+ /** @param {[number, number][]} ranges @param {[number, number][]} other */
397
+ function rangesIntersect(ranges, other) {
398
+ return ranges.some(([low, high]) => other.some(([otherLow, otherHigh]) =>
399
+ low <= otherHigh && otherLow <= high));
400
+ }
401
+
402
+ // Embedding a pattern in a larger regex drops the flags it carried, so the two
403
+ // a source can carry on its own are rewritten into it
404
+ //
405
+ // @@ Replace with inline `(?i:…)` and `(?s:…)` modifiers once Node floor reaches 24
406
+
407
+ /** @param {string} char @returns {boolean} Whether the character has a single-character counterpart */
408
+ function foldsCase(char) {
409
+ const lower = char.toLowerCase();
410
+ const upper = char.toUpperCase();
411
+ return lower !== upper && lower.length === 1 && upper.length === 1;
412
+ }
413
+
414
+ /** @param {string} char */
415
+ function isLower(char) {
416
+ return char === char.toLowerCase();
417
+ }
418
+
419
+ /**
420
+ * @param {string} source - Regex source, assumed syntactically valid
421
+ * @param {boolean} [nested] - Whether the pattern carries `v`
422
+ */
423
+ function expandDotAll(source, nested = false) {
424
+ let out = '';
425
+ let i = 0;
426
+ while (i < source.length) {
427
+ const char = source[i];
428
+ if (char === '\\') {
429
+ const length = tokenLength(source, i);
430
+ out += source.slice(i, i + length);
431
+ i += length;
432
+ } else if (char === '[') {
433
+ const end = skipCharacterClass(source, i, nested);
434
+ out += source.slice(i, end);
435
+ i = end;
436
+ } else if (char === '.') {
437
+ out += '[\\s\\S]';
438
+ i++;
439
+ } else {
440
+ out += char;
441
+ i++;
442
+ }
443
+ }
444
+ return out;
445
+ }
446
+
447
+ /**
448
+ * @param {string} source - Regex source, assumed syntactically valid
449
+ * @param {boolean} [nested] - Whether the pattern carries `v`
450
+ */
451
+ function foldCase(source, nested = false) {
452
+ let out = '';
453
+ let i = 0;
454
+ let open = 0;
455
+
456
+ while (i < source.length) {
457
+ const char = source[i] ?? '';
458
+
459
+ if (open === 0) {
460
+ if (char === '\\') {
461
+ const length = tokenLength(source, i);
462
+ out += source.slice(i, i + length);
463
+ i += length;
464
+ } else if (char === '[') {
465
+ open = 1;
466
+ out += char;
467
+ i++;
468
+ } else if (char === '(' && source.startsWith('(?<', i) &&
469
+ source[i + 3] !== '=' && source[i + 3] !== '!') {
470
+ // A capture group’s name is syntax, and folding it is a syntax error
471
+ const close = source.indexOf('>', i + 3);
472
+ const end = close === -1 ? i + 3 : close + 1;
473
+ out += source.slice(i, end);
474
+ i = end;
475
+ } else {
476
+ out += foldsCase(char) ? '[' + char.toLowerCase() + char.toUpperCase() + ']' : char;
477
+ i++;
478
+ }
479
+ continue;
480
+ }
481
+
482
+ if (nested && char === '[') {
483
+ open++;
484
+ out += char;
485
+ i++;
486
+ continue;
487
+ }
488
+
489
+ if (char === ']') {
490
+ open--;
491
+ out += char;
492
+ i++;
493
+ continue;
494
+ }
495
+
496
+ const fromLength = tokenLength(source, i);
497
+ const from = source.slice(i, i + fromLength);
498
+ const afterFrom = i + fromLength;
499
+
500
+ // A range needs the other case’s range beside it—only where both ends are
501
+ // ASCII letters, the one span whose two cases are contiguous and parallel
502
+ // (`ÿ` uppercases to `Ÿ`, 150 code points past where its range ends)
503
+ if (source[afterFrom] === '-' && afterFrom + 1 < source.length && source[afterFrom + 1] !== ']') {
504
+ const toLength = tokenLength(source, afterFrom + 1);
505
+ const to = source.slice(afterFrom + 1, afterFrom + 1 + toLength);
506
+ out += RE_ASCII_LETTER.test(from) && RE_ASCII_LETTER.test(to) && isLower(from) === isLower(to)
507
+ ? from + '-' + to + (isLower(from)
508
+ ? from.toUpperCase() + '-' + to.toUpperCase()
509
+ : from.toLowerCase() + '-' + to.toLowerCase())
510
+ : from + '-' + to;
511
+ i = afterFrom + 1 + toLength;
512
+ continue;
513
+ }
514
+
515
+ out += fromLength === 1 && foldsCase(from) ? from.toLowerCase() + from.toUpperCase() : from;
516
+ i = afterFrom;
517
+ }
518
+
519
+ return out;
520
+ }
521
+
522
+ /**
523
+ * Whether a source anchors anywhere, so that `m` would move where it matches
524
+ * @param {string} source @param {boolean} [nested] - Whether the pattern carries `v`
525
+ */
526
+ function hasAnchor(source, nested = false) {
527
+ let i = 0;
528
+ while (i < source.length) {
529
+ if (source[i] === '\\') i += tokenLength(source, i);
530
+ // Inside a class `^` negates and `$` is a member, so neither anchors there
531
+ else if (source[i] === '[') i = skipCharacterClass(source, i, nested);
532
+ else if (source[i] === '^' || source[i] === '$') return true;
533
+ else i++;
534
+ }
535
+ return false;
536
+ }
537
+
538
+ // A property escape or a code point escape, both of which read as literal text
539
+ // where the flag that gives them meaning is gone
540
+ const RE_UNICODE_ESCAPE = /\\[pP]\{|\\u\{/;
541
+
542
+ // The characters `u` folds by Unicode rules and a source without it does not:
543
+ // `/s/iu` matches `\u017F` and `/k/iu` matches `\u212A`, where neither does on its
544
+ // own. Characters past the BMP fold this way, too, and are caught as astral first.
545
+ const RE_UNICODE_FOLDING = /[\u004B\u0053\u006B\u0073\u00C5\u00DF\u00E5\u017F\u0398\u03A9\u03B8\u03C9\u03D1\u03F4\u1E9E\u1F80-\u1FAF\u1FB3\u1FBC\u1FC3\u1FCC\u1FF3\u1FFC\u2126\u212A\u212B]/;
546
+
547
+ /**
548
+ * Which flag changes what a source matches, so that embedding the source where the
549
+ * flag cannot follow would silently match something else. `u` and `v` only narrow
550
+ * what syntax is legal, so a source valid under either stays valid without it—the
551
+ * difference never surfaces as a syntax error, and this stands in for the one that
552
+ * would otherwise be raised.
553
+ * @param {RegExp} pattern
554
+ * @returns {'u' | 'v' | 'm' | null} The flag the source depends on, or `null` where
555
+ * every flag it carries would leave the source matching the same
556
+ */
557
+ function lostFlag(pattern) {
558
+ const { source, unicode, unicodeSets } = pattern;
559
+ // `m` moves where `^` and `$` match, and only matters where the source has one
560
+ if (pattern.multiline && hasAnchor(source, unicodeSets)) return 'm';
561
+ if (!unicode && !unicodeSets) return null;
562
+ const flag = unicodeSets ? 'v' : 'u';
563
+ if (RE_UNICODE_ESCAPE.test(source)) return flag;
564
+ // Case folding under `i` follows Unicode rules only while the flag is there. A
565
+ // character can be written literally or as an escape, so the source is read
566
+ // token by token rather than scanned for the characters themselves; `singleCode`
567
+ // leaves out `\d` and friends, which fold alike with the flag and without it.
568
+ if (pattern.ignoreCase) {
569
+ for (let i = 0; i < source.length;) {
570
+ const length = tokenLength(source, i);
571
+ const code = singleCode(tokenRanges(source.slice(i, i + length), true));
572
+ if (code !== null && RE_UNICODE_FOLDING.test(String.fromCodePoint(code))) return flag;
573
+ i += length;
574
+ }
575
+ }
576
+ // Past the BMP a character is one code point with the flag, two units without,
577
+ // which is what a quantifier or a class beside it would go on to read wrongly
578
+ for (const char of source) {
579
+ if ((char.codePointAt(0) ?? 0) > 0xFFFF) return flag;
580
+ }
581
+ if (!unicodeSets) return null;
582
+
583
+ // `v` alone lets a class nest, subtract, intersect, and hold whole strings
584
+ let i = 0;
585
+ while (i < source.length) {
586
+ if (source[i] === '\\') {
587
+ i += tokenLength(source, i);
588
+ continue;
589
+ }
590
+ if (source[i] !== '[') {
591
+ i++;
592
+ continue;
593
+ }
594
+ const end = skipCharacterClass(source, i, true);
595
+ for (let j = i + 1; j < end - 1;) {
596
+ if (source[j] === '\\') {
597
+ if (source.startsWith('\\q{', j)) return 'v';
598
+ j += tokenLength(source, j);
599
+ continue;
600
+ }
601
+ if (source[j] === '[' || source.startsWith('--', j) || source.startsWith('&&', j)) return 'v';
602
+ j++;
603
+ }
604
+ i = end;
605
+ }
606
+ return null;
607
+ }
608
+
609
+ /**
610
+ * A pattern’s source, rewritten to match the way its own flags make it match, for
611
+ * embedding in a larger regex that cannot carry them. `i` and `s` fit into a
612
+ * source; `m`, `u`, and `v` do not, and are left to the pattern it joins. Where
613
+ * `i` cannot be written in—a backreference, a range outside ASCII, a range that
614
+ * spans letters without being one—the source stands as it is, matching less than
615
+ * the pattern would rather than more.
616
+ * @param {RegExp} pattern
617
+ * @returns {string}
618
+ */
619
+ function embedSource(pattern) {
620
+ let source = pattern.source;
621
+ if (pattern.dotAll) source = expandDotAll(source, pattern.unicodeSets);
622
+ if (pattern.ignoreCase) source = foldCase(source, pattern.unicodeSets);
623
+ return source;
624
+ }
625
+
626
+ /**
627
+ * @typedef {{text: string, ranges: [number, number][] | null}} Repeat - An unbounded
628
+ * repeat, as it reads and as the set of characters it matches
629
+ */
630
+
631
+ /**
632
+ * @param {Repeat[]} reachable - Repeats that could still sit adjacent to what comes next
633
+ * @param {Repeat} repeat
634
+ * @returns {boolean} Whether the two can consume the same character, and so split
635
+ * the same run of input between them
636
+ */
637
+ function splitsWith(reachable, repeat) {
638
+ return reachable.some(earlier => earlier.text === repeat.text ||
639
+ (!!repeat.ranges && !!earlier.ranges && rangesIntersect(repeat.ranges, earlier.ranges)));
640
+ }
641
+
642
+ /**
643
+ * @param {Repeat[]} into
644
+ * @param {Repeat[]} repeats
645
+ * @returns {void} Adds the repeats, keeping only the most recent ones the walk
646
+ * still compares against
647
+ */
648
+ function collectReachable(into, repeats) {
649
+ for (const repeat of repeats) {
650
+ into.push(repeat);
651
+ if (into.length > MAX_REACHABLE) into.shift();
652
+ }
653
+ }
654
+
655
+ /**
656
+ * Walk a regex source for the shapes whose backtracking blows up: an unlimited
657
+ * quantifier over a group that itself contains a variable quantifier (`(a+)+`,
658
+ * `(a?)+`) or alternates, and two unbounded repeats that can consume the same
659
+ * character with only atoms matching empty between them (`.*.*`, `[a]*a*`,
660
+ * `\w*\d*`, `a*b*a*`, `a*(b*)a*`, `(a*)a*`). A lone unlimited quantifier stays
661
+ * linear, so `[\s\S]*?` up to a literal terminator passes.
662
+ * @param {string} source - Regex source, assumed syntactically valid
663
+ * @param {number} [depth] - Group nesting level of this call
664
+ * @param {boolean} [nested] - Whether the pattern carries `v`
665
+ * @returns {{risky: boolean, varies: boolean, alternates: boolean, deep: boolean,
666
+ * empty: boolean, leading: Repeat[], trailing: Repeat[]}} What the walk found,
667
+ * with the repeats that reach the source’s start and end for a caller to compare
668
+ * against what stands beside it
669
+ */
670
+ function analyzeQuantifiers(source, depth = 0, nested = false) {
671
+ if (depth > MAX_PATTERN_DEPTH) return { risky: true, varies: true, alternates: true, deep: true, empty: true, leading: [], trailing: [] };
672
+
673
+ let risky = false;
674
+ let varies = false;
675
+ let alternates = false;
676
+ let deep = false;
677
+ // Whether every atom of the branch being read matches empty, and whether any
678
+ // branch before it did
679
+ let branchEmpty = true;
680
+ let anyBranchEmpty = false;
681
+ // The unbounded repeats that could still sit adjacent to what comes next, most
682
+ // recent last; an atom matching empty leaves the ones before it reachable
683
+ /** @type {Repeat[]} */
684
+ const reachable = [];
685
+ // The repeats a caller can reach from either end, gathered across branches
686
+ /** @type {Repeat[]} */
687
+ const leading = [];
688
+ /** @type {Repeat[]} */
689
+ const trailing = [];
690
+ /** @type {Repeat[]} */
691
+ let branchLeading = [];
692
+ let i = 0;
693
+
694
+ while (i < source.length) {
695
+ const start = i;
696
+ const char = source[i];
697
+ /** @type {ReturnType<typeof analyzeQuantifiers> | null} */
698
+ let group = null;
699
+
700
+ if (char === '|') {
701
+ // Alternatives are separate expressions, so nothing carries across
702
+ alternates = true;
703
+ anyBranchEmpty ||= branchEmpty;
704
+ branchEmpty = true;
705
+ collectReachable(leading, branchLeading);
706
+ collectReachable(trailing, reachable);
707
+ branchLeading = [];
708
+ reachable.length = 0;
709
+ i++;
710
+ continue;
711
+ } else if (char === '\\') {
712
+ i += tokenLength(source, i);
713
+ } else if (char === '[') {
714
+ i = skipCharacterClass(source, i, nested);
715
+ } else if (char === '(') {
716
+ let open = 1;
717
+ i++;
718
+ while (i < source.length && open > 0) {
719
+ const inner = source[i];
720
+ if (inner === '\\') {
721
+ i += tokenLength(source, i);
722
+ } else if (inner === '[') {
723
+ i = skipCharacterClass(source, i, nested);
724
+ } else {
725
+ if (inner === '(') open++;
726
+ else if (inner === ')') open--;
727
+ i++;
728
+ }
729
+ }
730
+ // Drop the group prefix (`?:`, `?=`, `?<name>`, …) before reading the body
731
+ group = analyzeQuantifiers(source.slice(start + 1, i - 1).replace(/^\?(?:[:=!]|<[=!]|<[^>]*>)/, ''), depth + 1, nested);
732
+ } else {
733
+ i++;
734
+ }
735
+
736
+ const atom = source.slice(start, i);
737
+ RE_QUANTIFIER.lastIndex = i;
738
+ const quantifier = RE_QUANTIFIER.exec(source);
739
+ const upper = quantifier?.[2];
740
+ const repeats = !!quantifier && (quantifier[0][0] === '*' || quantifier[0][0] === '+' || upper === '');
741
+ // A count that can vary—anything but `{n}` and its `{n,n}` spelling—makes
742
+ // the group ambiguous about how much it consumes, which multiplies under an
743
+ // unlimited repeat
744
+ const exact = !!quantifier && quantifier[0][0] === '{' &&
745
+ (upper === undefined || (upper !== '' && Number(upper) === Number(quantifier[1])));
746
+ const variable = !!quantifier && !exact;
747
+ // An atom matches empty where it is zero-width, where its quantifier may
748
+ // repeat none, or where a group body matches empty however often it repeats—
749
+ // `(b*)`, carrying the quantifier inside the group rather than on it
750
+ const least = quantifier && (quantifier[0][0] === '+' ? 1
751
+ : quantifier[0][0] === '{' ? Number(quantifier[1]) : 0);
752
+ const body = RE_ZERO_WIDTH.test(atom) || (!!group && group.empty);
753
+ const nullable = body || (!!quantifier && least === 0);
754
+ if (quantifier) i = RE_QUANTIFIER.lastIndex;
755
+
756
+ // A lookaround is atomic: It backtracks nothing, so what it holds neither
757
+ // reaches out of it nor is reached into
758
+ const opaque = RE_ZERO_WIDTH.test(atom);
759
+ if (group) {
760
+ if (group.risky || (repeats && (group.varies || group.alternates))) risky = true;
761
+ if (group.varies) varies = true;
762
+ // A group alternates whether the `|` sits at its top level or deeper
763
+ if (group.alternates) alternates = true;
764
+ if (group.deep) deep = true;
765
+ // A group is no wall: What it repeats at its start splits the same run as
766
+ // what stands unbounded before it
767
+ if (!opaque && group.leading.some(repeat => splitsWith(reachable, repeat))) risky = true;
768
+ }
769
+ if (variable) varies = true;
770
+ const text = unwrapAtom(atom);
771
+ const ranges = atomRanges(text, nested);
772
+ if (repeats && splitsWith(reachable, { text, ranges })) risky = true;
773
+
774
+ // Whatever a caller could reach before this atom, it reaches this one, too
775
+ if (branchEmpty) {
776
+ if (repeats) collectReachable(branchLeading, [{ text, ranges }]);
777
+ if (group && !opaque) collectReachable(branchLeading, group.leading);
778
+ }
779
+ // Nothing reaches past an atom that has to consume something
780
+ if (!nullable) {
781
+ reachable.length = 0;
782
+ branchEmpty = false;
783
+ }
784
+ if (group && !opaque) collectReachable(reachable, group.trailing);
785
+ if (repeats) collectReachable(reachable, [{ text, ranges }]);
786
+ }
787
+
788
+ collectReachable(leading, branchLeading);
789
+ collectReachable(trailing, reachable);
790
+
791
+ return { risky, varies, alternates, deep, empty: anyBranchEmpty || branchEmpty, leading, trailing };
792
+ }
793
+
794
+ /**
795
+ * @param {RegExp | string} pattern - Pattern to judge, or a bare source to read
796
+ * as it stands
797
+ * @returns {string | null} What makes the pattern a backtracking risk, phrased
798
+ * to follow the pattern itself, or `null` where it is none
799
+ */
800
+ function describeQuantifierRisk(pattern) {
801
+ const source = typeof pattern === 'string' ? pattern : pattern.source;
802
+ // A pattern too big to read is refused for that, not for a shape nobody saw;
803
+ // its own length is what counts, not the length folding case inflates it to
804
+ if (source.length > MAX_PATTERN_LENGTH) {
805
+ return `runs past ${MAX_PATTERN_LENGTH.toLocaleString()} characters, too long to analyze for catastrophic backtracking—shorten it, or split it into several patterns`;
806
+ }
807
+ // `i` and `s` change what the source matches, so they are written into it
808
+ // before the shapes are read
809
+ const analysis = typeof pattern === 'string'
810
+ ? analyzeQuantifiers(source)
811
+ : analyzeQuantifiers(embedSource(pattern), 0, pattern.unicodeSets);
812
+ if (analysis.deep) {
813
+ return `nests groups more than ${MAX_PATTERN_DEPTH.toLocaleString()} deep, too deep to analyze for catastrophic backtracking—flatten it, or split it into several patterns`;
814
+ }
815
+ return analysis.risky
816
+ ? 'compounds quantifiers or alternation in a way that may cause ReDoS—bound the repetition (e.g., `{0,1000}`) instead'
817
+ : null;
818
+ }
819
+
820
+ /**
821
+ * Find the index of the `>` that closes an opening tag, correctly skipping
822
+ * over quoted attribute values (which may contain `>`).
823
+ * @param {string} html
824
+ * @param {number} pos - Start position (just after the tag name)
825
+ * @param {number} [limit] - Position to stop the search at (exclusive)
826
+ * @returns {number} Index of the closing `>`, or -1 if not found
827
+ */
828
+ function findTagEnd(html, pos, limit = html.length) {
829
+ let i = pos;
830
+ while (i < limit) {
831
+ const ch = html[i];
832
+ if (ch === '>') return i;
833
+ if (ch === '"' || ch === "'") {
834
+ const q = ch;
835
+ i++;
836
+ while (i < limit && html[i] !== q) i++;
837
+ }
838
+ i++;
839
+ }
840
+ return -1;
841
+ }
842
+
843
+ // Exports
844
+
845
+ export {
846
+ stableStringify,
847
+ findTagEnd,
848
+ LRU,
849
+ MAX_CACHE_ENTRY_SIZE,
850
+ hashContent,
851
+ uniqueId,
852
+ identity,
853
+ isThenable,
854
+ lowercase,
855
+ paramCase,
856
+ replaceAsync,
857
+ parseRegExp,
858
+ embedSource,
859
+ lostFlag,
860
+ describeQuantifierRisk
861
+ };