@ohos-ports/html-minifier-next 8.4.2-beta.0 → 8.10.8-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 (46) hide show
  1. package/README.md +147 -33
  2. package/cli.js +70 -54
  3. package/dist/types/htmlminifier.d.ts +87 -33
  4. package/dist/types/htmlminifier.d.ts.map +1 -1
  5. package/dist/types/htmlparser.d.ts +4 -1
  6. package/dist/types/htmlparser.d.ts.map +1 -1
  7. package/dist/types/lib/attributes.d.ts +12 -10
  8. package/dist/types/lib/attributes.d.ts.map +1 -1
  9. package/dist/types/lib/constants.d.ts +38 -3
  10. package/dist/types/lib/constants.d.ts.map +1 -1
  11. package/dist/types/lib/content.d.ts.map +1 -1
  12. package/dist/types/lib/elements.d.ts.map +1 -1
  13. package/dist/types/lib/fragments.d.ts +1 -0
  14. package/dist/types/lib/fragments.d.ts.map +1 -1
  15. package/dist/types/lib/option-definitions.d.ts.map +1 -1
  16. package/dist/types/lib/options.d.ts +14 -46
  17. package/dist/types/lib/options.d.ts.map +1 -1
  18. package/dist/types/lib/unused-css.d.ts +34 -4
  19. package/dist/types/lib/unused-css.d.ts.map +1 -1
  20. package/dist/types/lib/urls.d.ts.map +1 -1
  21. package/dist/types/lib/utils.d.ts +31 -1
  22. package/dist/types/lib/utils.d.ts.map +1 -1
  23. package/dist/types/lib/whitespace.d.ts +57 -5
  24. package/dist/types/lib/whitespace.d.ts.map +1 -1
  25. package/dist/types/presets.d.ts +1 -2
  26. package/dist/types/presets.d.ts.map +1 -1
  27. package/dist/types/tokenchain.d.ts.map +1 -1
  28. package/html-minifier-next.schema.json +15 -7
  29. package/package.json +17 -18
  30. package/src/htmlminifier.js +1103 -392
  31. package/src/htmlparser.js +452 -200
  32. package/src/lib/attributes.js +201 -112
  33. package/src/lib/constants.js +130 -19
  34. package/src/lib/content.js +1 -6
  35. package/src/lib/elements.js +17 -12
  36. package/src/lib/file-pool.js +18 -2
  37. package/src/lib/file-write.js +87 -0
  38. package/src/lib/fragments.js +74 -8
  39. package/src/lib/option-definitions.js +17 -10
  40. package/src/lib/options.js +151 -71
  41. package/src/lib/unused-css.js +145 -27
  42. package/src/lib/urls.js +0 -9
  43. package/src/lib/utils.js +210 -45
  44. package/src/lib/whitespace.js +173 -63
  45. package/src/presets.js +1 -2
  46. package/src/tokenchain.js +1 -4
package/src/htmlparser.js CHANGED
@@ -5,22 +5,30 @@
5
5
  * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
6
6
  */
7
7
 
8
- import { isThenable, embedSource, findTagEnd } from './lib/utils.js';
9
- import { endlessRawTextElements, escapableRawTextElements, genericRawTextElements, RE_HTML_ENCODING } from './lib/constants.js';
8
+ import { isThenable, isQuirksDoctype, embedSource, findTagEnd } from './lib/utils.js';
9
+ import { endlessRawTextElements, escapableRawTextElements, formattingElements, genericRawTextElements, processingInstructionTag, RE_HTML_ENCODING, RE_WS_ONLY } from './lib/constants.js';
10
10
 
11
11
  /** @import { HTMLAttribute } from './lib/attributes.js' */
12
12
 
13
- // Type definitions
14
-
15
13
  /**
14
+ * `start`, `chars`, and `comment` return `undefined` when their work needs no `await`
15
+ * and a Promise when it does; the parse loop awaits only what it gets back. `end`,
16
+ * `processingInstruction`, `doctype`, and `strayEnd` never suspend. `start` is
17
+ * synchronous wherever it is passed no attributes, which is what keeps the calls
18
+ * inside `parseEndTag` synchronous. `chars` is told by its sixth argument when
19
+ * the text is all an SVG `script` or `style` element holds, and so its source.
16
20
  * @typedef {{
17
21
  * start?: Function,
18
22
  * end?: Function,
19
23
  * chars?: Function,
20
24
  * comment?: Function,
25
+ * processingInstruction?: Function,
21
26
  * doctype?: Function,
27
+ * strayEnd?: Function,
28
+ * parseError?: Function | undefined,
22
29
  * continueOnParseError?: boolean | undefined,
23
30
  * partialMarkup?: boolean | undefined,
31
+ * noQuirksMode?: boolean | undefined,
24
32
  * wantsNextTag?: boolean | undefined,
25
33
  * selfClosingSlash?: boolean | undefined,
26
34
  * customAttrSurround?: RegExp[][] | undefined,
@@ -43,18 +51,21 @@ import { endlessRawTextElements, escapableRawTextElements, genericRawTextElement
43
51
  const singleAttrIdentifier = /([^\s"'<>/=]+)/;
44
52
  const singleAttrAssigns = [/=/];
45
53
  const singleAttrValues = [
46
- // Attr value double quotes
47
54
  /"([^"]*)"+/.source,
48
- // Attr value, single quotes
49
55
  /'([^']*)'+/.source,
50
56
  // Attr value, no quotes (strict: excludes `=` per HTML spec)
51
57
  /([^ \t\n\f\r"'`=<>]+)/.source
52
58
  ];
53
- // Lenient unquoted value pattern for `continueOnParseError`:
54
- // allows `<`, `=`, and ``` per HTML error-recovery rules
55
- // (all are parse errors in unquoted-attribute-value state but appended to the value)
56
- // `"` and `'` remain excluded—permitting them requires broader test coverage
59
+ // Lenient unquoted value pattern for `continueOnParseError`: Allows `<`, `=`, and backticks per
60
+ // HTML error-recovery rules (all are parse errors in unquoted-attribute-value state but appended to
61
+ // the value); `"` and `'` remain excluded—permitting them requires broader test coverage
57
62
  const singleAttrValueLenientUnquoted = /([^ \t\n\f\r"'>]+)/.source;
63
+ // The characters the lenient pattern takes in beyond the strict one, each a parse error
64
+ const RE_UNQUOTED_VALUE_ERROR = /[<=`]/;
65
+ // The rest of an unquoted value, strict and lenient, as one character class read in a single
66
+ // pass from where the attribute window cut the value short
67
+ const RE_UNQUOTED_VALUE_REST = new RegExp(/** @type {string} */ (singleAttrValues[2]).slice(1, -2) + '*', 'y');
68
+ const RE_UNQUOTED_VALUE_REST_LENIENT = new RegExp(singleAttrValueLenientUnquoted.slice(1, -2) + '*', 'y');
58
69
  // https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
59
70
  const qnameCapture = (function () {
60
71
  // https://www.npmjs.com/package/ncname
@@ -67,13 +78,6 @@ const qnameCapture = (function () {
67
78
  })();
68
79
  const startTagOpen = new RegExp('^<' + qnameCapture);
69
80
  const endTagOpen = new RegExp('^</' + qnameCapture);
70
- export const endTag = new RegExp('^</' + qnameCapture + '[^>]*>');
71
-
72
- let IS_REGEX_CAPTURING_BROKEN = false;
73
- 'x'.replace(/x(.)?/g, function (/** @type {string} */ m, /** @type {string | undefined} */ g) {
74
- IS_REGEX_CAPTURING_BROKEN = g === '';
75
- return m;
76
- });
77
81
 
78
82
  // Empty elements
79
83
  const empty = new Set(['area', 'base', 'basefont', 'br', 'col', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
@@ -81,12 +85,13 @@ const empty = new Set(['area', 'base', 'basefont', 'br', 'col', 'embed', 'frame'
81
85
  // Elements that you can, intentionally, leave open (and which close themselves)
82
86
  const closeSelf = new Set(['colgroup', 'dd', 'dt', 'li', 'option', 'p', 'td', 'tfoot', 'th', 'thead', 'tr', 'source']);
83
87
 
84
- // Attributes that have their values filled in `disabled='disabled'`
85
- const fillAttrs = new Set(['checked', 'compact', 'declare', 'defer', 'disabled', 'ismap', 'multiple', 'nohref', 'noresize', 'noshade', 'nowrap', 'readonly', 'selected']);
86
-
87
88
  // Special elements (can contain anything)
88
89
  const special = new Set(['script', 'style']);
89
90
 
91
+ // Where a CDATA section starts and ends, which holds text in foreign content
92
+ const cdataOpen = '<![CDATA[';
93
+ const cdataClose = ']]>';
94
+
90
95
  // Elements whose children are HTML rather than foreign content, each only in
91
96
  // the namespace it belongs to (`annotation-xml` is one, too, but only for some
92
97
  // `encoding` values, so it is checked separately)
@@ -94,9 +99,19 @@ const special = new Set(['script', 'style']);
94
99
  const svgIntegrationPoints = new Set(['foreignobject', 'desc', 'title']);
95
100
  const mathIntegrationPoints = new Set(['mi', 'mo', 'mn', 'ms', 'mtext']);
96
101
 
97
- // HTML elements, https://html.spec.whatwg.org/multipage/indices.html#elements-3
98
- // Phrasing content, https://html.spec.whatwg.org/multipage/dom.html#phrasing-content
99
- const nonPhrasing = new Set(['address', 'article', 'aside', 'base', 'blockquote', 'body', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dialog', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'legend', 'li', 'listing', 'main', 'menu', 'menuitem', 'meta', 'nav', 'ol', 'optgroup', 'option', 'param', 'plaintext', 'pre', 'rp', 'rt', 'search', 'section', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'xmp']);
102
+ // Start tags that close foreign content and are read as HTML (`font` only with
103
+ // `color`, `face`, or `size`)
104
+ // https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inforeign
105
+ const breaksOutOfForeignContent = new Set(['b', 'big', 'blockquote', 'body', 'br', 'center', 'code', 'dd', 'div', 'dl', 'dt', 'em', 'embed', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'hr', 'i', 'img', 'li', 'listing', 'menu', 'meta', 'nobr', 'ol', 'p', 'pre', 'ruby', 's', 'small', 'span', 'strong', 'strike', 'sub', 'sup', 'table', 'tt', 'u', 'ul', 'var']);
106
+ const RE_FONT_BREAKOUT_ATTR = /^(?:color|face|size)$/i;
107
+
108
+ // Elements that end the scope an open `p` is looked for in
109
+ // https://html.spec.whatwg.org/multipage/parsing.html#has-an-element-in-button-scope
110
+ const buttonScopeBoundaries = new Set(['applet', 'button', 'caption', 'html', 'marquee', 'object', 'table', 'td', 'template', 'th']);
111
+ // Start tags that close an open `p` (other start tags, like `meta` or `style`, go in it, or are
112
+ // ignored, like `td` outside a table)
113
+ // https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inbody
114
+ const closesP = new Set(['address', 'article', 'aside', 'blockquote', 'center', 'dd', 'details', 'dialog', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'li', 'listing', 'main', 'menu', 'nav', 'ol', 'p', 'plaintext', 'pre', 'search', 'section', 'summary', 'table', 'ul', 'xmp']);
100
115
 
101
116
  // A tag name ends at whitespace, a slash, or the closing bracket, so `</scriptx>` names a
102
117
  // different element and does not end this one
@@ -148,7 +163,7 @@ function findEndTagClose(text, nameEnd) {
148
163
  // A quoted attribute value can hold a `>` that does not end the tag it stands in, so a
149
164
  // quote ahead of that bracket calls for a scan that knows about quoting. It stops at the
150
165
  // next `<`, which no tag reaches past: The scans of consecutive tags then never overlap,
151
- // and an unquoted value that spans one leaves the first bracket as the end, as before.
166
+ // and an unquoted value that spans one leaves the first bracket as the end, as `indexOf` does.
152
167
  for (let index = nameEnd; index < close; index++) {
153
168
  const character = text[index];
154
169
  if (character === '"' || character === "'") {
@@ -262,31 +277,47 @@ export class HTMLParser {
262
277
  const fullHtml = this.html;
263
278
  const fullLength = fullHtml.length;
264
279
 
265
- /** @type {Array<{tag: string, lowerTag: string, attrs: HTMLAttribute[], namespace: string}>} */
280
+ // `pScope` is the index of the `p` a start tag would close from within the entry, or -1
281
+ /** @type {Array<{tag: string, lowerTag: string, attrs: HTMLAttribute[], namespace: string, pScope: number}>} */
266
282
  const stack = [];
267
283
  /** @type {string} */
268
284
  let lastTag = '';
285
+ // The document mode, which only the first doctype sets, and only after
286
+ // nothing but comments and whitespace (with `noQuirksMode`, to no-quirks,
287
+ // as the doctype gets replaced by the HTML one): `table` closes an open `p`
288
+ // in no-quirks mode but not in quirks mode; without such a doctype (as in a
289
+ // fragment) the mode is unknown, so the `p` stays open as in quirks mode,
290
+ // and its end tag, which no-quirks mode reads as stray, has to stay, too
291
+ /** @type {'' | 'quirks' | 'no-quirks'} */
292
+ let docMode = '';
293
+ let docModeSettable = true;
294
+ // Open `p` elements a `table` started in while the mode was unknown
295
+ /** @type {WeakSet<object>} */
296
+ const pHoldingTable = new WeakSet();
269
297
  // Lowercase counterpart of `lastTag`, kept in sync to avoid per-iteration lowercasing
270
298
  /** @type {string} */
271
299
  let lastTagLower = '';
272
- // Use cached attribute regex for this handler configuration
273
300
  const attribute = getAttrRegexForHandler(handler);
274
301
  const attributeY = getAttrRegexStickyForHandler(handler);
275
302
  /** @type {string | undefined} */
276
303
  let prevTag;
277
304
  /** @type {string | undefined} */
278
305
  let nextTag;
306
+ // One shared empty array for the resets—nothing ever writes to `prevAttrs`/`nextAttrs`
279
307
  /** @type {HTMLAttribute[]} */
280
- let prevAttrs = [];
308
+ const emptyAttrs = [];
281
309
  /** @type {HTMLAttribute[]} */
282
- let nextAttrs = [];
310
+ let prevAttrs = emptyAttrs;
311
+ /** @type {HTMLAttribute[]} */
312
+ let nextAttrs = emptyAttrs;
283
313
 
284
314
  // Sticky regex versions for position-based matching (avoids string slicing)
285
315
  const startTagOpenY = new RegExp(startTagOpen.source.slice(1), 'y');
286
316
  const endTagOpenY = new RegExp(endTagOpen.source.slice(1), 'y');
287
- const doctypeY = /<!DOCTYPE[^<>]+>/iy;
317
+ const doctypeY = /<!DOCTYPE[^<>]*>/iy;
288
318
  const commentTestY = /<!--/y;
289
319
  const conditionalTestY = /<!\[/y;
320
+ const processingInstructionY = /<\?([A-Za-z_][\w-]*)[\t\n\f\r ?>]/y;
290
321
 
291
322
  // Cached next-tag from lookahead (avoids re-parsing the same tag)
292
323
  let cachedNextStartTag = null;
@@ -296,11 +327,9 @@ export class HTMLParser {
296
327
  let pos = 0;
297
328
  let lastPos;
298
329
 
299
- // An end tag always ends at a `>`; without one ahead, matching the name only to find
300
- // no bracket behind it repeats the name run at every position, which costs O(n²) on a
301
- // long unclosed name (e.g., `</aaaa…` with no `>`). Track the next `>` monotonically—
302
- // `pos` only advances, so the aggregate scan work stays O(n)—and skip the match when
303
- // none lies ahead, where the tag could not be complete anyway.
330
+ // An end tag always ends at a `>`; without one ahead, matching the name would rescan the name
331
+ // run at every position, O(n²) on a long unclosed name (`</aaaa…`). Tracking the next `>`
332
+ // (`pos` only advances, so this stays O(n)) skips the match where the tag cannot be complete.
304
333
  let nextGtPos = fullHtml.indexOf('>');
305
334
  const hasCloseAtOrAfter = (/** @type {number} */ p) => {
306
335
  if (nextGtPos !== -1 && nextGtPos < p) {
@@ -316,7 +345,33 @@ export class HTMLParser {
316
345
  let commentEndAhead = true;
317
346
  let conditionalEndAhead = true;
318
347
 
319
- // Helper to advance position
348
+ // The end of the processing instruction at `p`, or -1 where there is none: `xml` and
349
+ // `xml-stylesheet` open a bogus comment instead, and one without a `>` is dropped
350
+ // https://html.spec.whatwg.org/multipage/parsing.html#processing-instruction-open-state
351
+ const matchProcessingInstruction = (/** @type {number} */ p) => {
352
+ if (!hasCloseAtOrAfter(p)) return -1;
353
+ processingInstructionY.lastIndex = p;
354
+ const match = processingInstructionY.exec(fullHtml);
355
+ if (!match) return -1;
356
+ const target = (match[1] ?? '').toLowerCase();
357
+ return target === 'xml' || target === 'xml-stylesheet' ? -1 : nextGtPos + 1;
358
+ };
359
+
360
+ // Where what `<?` at `p` opens ends, when it is not a processing instruction: A valid target
361
+ // without a `>` is dropped (`dropped`), anything else is a bogus comment up to the next `>`
362
+ const matchBogusProcessingInstruction = (/** @type {number} */ p) => {
363
+ let i = p + 2;
364
+ const nameCode = fullHtml.charCodeAt(i) | 32;
365
+ let dropped = i >= fullLength;
366
+ if (nameCode >= 97 && nameCode <= 122 || fullHtml[i] === '_') {
367
+ while (i < fullLength && /[\w-]/.test(fullHtml[i] ?? '')) i++;
368
+ const target = fullHtml.substring(p + 2, i).toLowerCase();
369
+ dropped = i >= fullLength || (/[\t\n\f\r ?>]/.test(fullHtml[i] ?? '') && target !== 'xml' && target !== 'xml-stylesheet');
370
+ }
371
+ if (dropped) return { end: fullLength, dropped };
372
+ return { end: hasCloseAtOrAfter(p + 2) ? nextGtPos + 1 : fullLength, dropped };
373
+ };
374
+
320
375
  const advance = (/** @type {number} */ n) => { pos += n; };
321
376
 
322
377
  // Lazy line/column calculation—only compute on actual errors
@@ -334,7 +389,29 @@ export class HTMLParser {
334
389
  return { line, column };
335
390
  };
336
391
 
337
- // Helper to safely extract substring when needed for stacked tag content
392
+ // Recoveries are reported in document order, so each picks up where the last left off
393
+ let reportedPos = 0;
394
+ let reportedLoc = { line: 1, column: 1 };
395
+ const reportParseError = (/** @type {number} */ position, /** @type {string} */ recovery) => {
396
+ if (!handler.parseError) return;
397
+ if (position < reportedPos) {
398
+ reportedPos = 0;
399
+ reportedLoc = { line: 1, column: 1 };
400
+ }
401
+ let { line, column } = reportedLoc;
402
+ for (let i = reportedPos; i < position; i++) {
403
+ if (fullHtml.charCodeAt(i) === 10) {
404
+ line++;
405
+ column = 1;
406
+ } else {
407
+ column++;
408
+ }
409
+ }
410
+ reportedPos = position;
411
+ reportedLoc = { line, column };
412
+ handler.parseError(`Parse error at line ${line}, column ${column}: ${recovery}`);
413
+ };
414
+
338
415
  const sliceFromPos = (/** @type {number} */ startPos) => {
339
416
  return fullHtml.slice(startPos);
340
417
  };
@@ -377,29 +454,68 @@ export class HTMLParser {
377
454
  const startsForeignContent = (/** @type {string} */ lowerTag) =>
378
455
  Boolean(namespaceInside(stack[stack.length - 1])) || lowerTag === 'svg' || lowerTag === 'math';
379
456
 
380
- // Whether the content of the element being parsed is read as text rather than markup
381
- // (`script` and `style` hold text in every namespace; the rest do so as HTML elements only)
457
+ // Whether the content of the element being parsed is read as text rather than
458
+ // markup, which only HTML elements hold—in foreign content, `script` and `style`
459
+ // hold markup, too
382
460
  const holdsRawText = (/** @type {string} */ tag) =>
383
- special.has(tag) ||
384
- ((genericRawTextElements.has(tag) || escapableRawTextElements.has(tag)) && !inForeignContent());
461
+ (special.has(tag) || genericRawTextElements.has(tag) || escapableRawTextElements.has(tag)) && !inForeignContent();
462
+
463
+ // Where the content of the last SVG `script` or `style` start tag begins, which text
464
+ // there is the source of when it runs up to the element’s end tag
465
+ let sourcePos = -1;
466
+
467
+ // Whether the text from `textStart` is all such an element holds; kept out of the parse
468
+ // loop, which slows down with every line it grows by
469
+ const isSource = (/** @type {number} */ textStart) =>
470
+ sourcePos === textStart && fullHtml.charCodeAt(pos + 1) === 47 && matchEndTag(pos)?.name.toLowerCase() === lastTagLower;
471
+
472
+ // In foreign content, text runs through CDATA sections, and one without an end to the
473
+ // end of the input (-1)
474
+ const skipCDATA = (/** @type {number} */ textEnd) => {
475
+ while (textEnd !== -1 && fullHtml.startsWith(cdataOpen, textEnd)) {
476
+ const cdataEnd = fullHtml.indexOf(cdataClose, textEnd + cdataOpen.length);
477
+ textEnd = cdataEnd === -1 ? -1 : fullHtml.indexOf('<', cdataEnd + cdataClose.length);
478
+ }
479
+ return textEnd;
480
+ };
481
+
482
+ // The answer changes only when the top of the stack does, so it is recomputed per stack
483
+ // change rather than per loop iteration (`stackVersion` covers same-named tags whose
484
+ // namespace differs, as a name alone does not say which element sits on top)
485
+ let stackVersion = 0;
486
+ let rawTextVersion = -1;
487
+ let rawTextTag = '';
488
+ let rawTextResult = false;
489
+ const topHoldsRawText = () => {
490
+ if (stackVersion !== rawTextVersion || lastTagLower !== rawTextTag) {
491
+ rawTextResult = holdsRawText(lastTagLower);
492
+ rawTextVersion = stackVersion;
493
+ rawTextTag = lastTagLower;
494
+ }
495
+ return rawTextResult;
496
+ };
385
497
 
386
498
  while (pos < fullLength) {
387
499
  lastPos = pos;
388
500
 
389
501
  // Make sure not to be in an element whose content is text, not markup
390
- if (!lastTagLower || !holdsRawText(lastTagLower)) {
391
- const textEnd = fullHtml.indexOf('<', pos);
502
+ if (!lastTagLower || !topHoldsRawText()) {
503
+ let textEnd = fullHtml.indexOf('<', pos);
504
+ if (textEnd !== -1 && lastTagLower && fullHtml.charCodeAt(textEnd + 1) === 33 && inForeignContent()) {
505
+ textEnd = skipCDATA(textEnd);
506
+ }
392
507
 
393
508
  if (textEnd === pos) {
394
- // Tag found at current position
395
-
396
- // Check cache from previous lookahead (avoids re-parsing the same tag)
509
+ // Tag found at current position; the lookahead may have parsed it already
397
510
  if (cachedNextStartTag && cachedNextStartTag.pos === pos) {
398
511
  const startTagMatch = cachedNextStartTag.match;
399
512
  cachedNextStartTag = null;
400
513
  cachedNextEndTag = null;
401
514
  advance(startTagMatch.advance);
402
- prevTag = await handleStartTag(startTagMatch);
515
+ // Awaited only when the handler has reason to, which is what keeps a plain
516
+ // document off the microtask queue once per tag
517
+ const started = handleStartTag(startTagMatch);
518
+ prevTag = isThenable(started) ? await started : started;
403
519
  continue;
404
520
  }
405
521
  if (cachedNextEndTag && cachedNextEndTag.pos === pos) {
@@ -407,8 +523,8 @@ export class HTMLParser {
407
523
  cachedNextStartTag = null;
408
524
  cachedNextEndTag = null;
409
525
  advance(endTagMatch.text.length);
410
- prevTag = '/' + await parseEndTag(endTagMatch.text, endTagMatch.name);
411
- prevAttrs = [];
526
+ prevTag = '/' + parseEndTag(endTagMatch.text, endTagMatch.name);
527
+ prevAttrs = emptyAttrs;
412
528
  continue;
413
529
  }
414
530
  cachedNextStartTag = null;
@@ -420,7 +536,6 @@ export class HTMLParser {
420
536
  // another one never run—a name lookup costs several regex executions
421
537
  const nextCode = fullHtml.charCodeAt(pos + 1);
422
538
  if (nextCode === 33) { // `!`
423
- // Comment
424
539
  commentTestY.lastIndex = pos;
425
540
  if (commentTestY.test(fullHtml)) {
426
541
  const commentEnd = commentEndAhead ? fullHtml.indexOf('-->', pos + 4) : -1;
@@ -433,7 +548,7 @@ export class HTMLParser {
433
548
  }
434
549
  advance(commentEnd + 3 - pos);
435
550
  prevTag = '';
436
- prevAttrs = [];
551
+ prevAttrs = emptyAttrs;
437
552
  continue;
438
553
  }
439
554
  }
@@ -451,21 +566,49 @@ export class HTMLParser {
451
566
  }
452
567
  advance(conditionalEnd + 2 - pos);
453
568
  prevTag = '';
454
- prevAttrs = [];
569
+ prevAttrs = emptyAttrs;
455
570
  continue;
456
571
  }
457
572
  }
458
573
 
459
- // Doctype
460
574
  doctypeY.lastIndex = pos;
461
575
  const doctypeMatch = doctypeY.exec(fullHtml);
462
576
  if (doctypeMatch) {
577
+ if (docModeSettable) {
578
+ docMode = handler.noQuirksMode || !isQuirksDoctype(doctypeMatch[0]) ? 'no-quirks' : 'quirks';
579
+ docModeSettable = false;
580
+ }
463
581
  if (handler.doctype) {
464
- handler.doctype(doctypeMatch[0]);
582
+ handler.doctype(doctypeMatch[0], docMode === 'no-quirks');
465
583
  }
466
584
  advance(doctypeMatch[0].length);
467
585
  prevTag = '';
468
- prevAttrs = [];
586
+ prevAttrs = emptyAttrs;
587
+ continue;
588
+ }
589
+ } else if (nextCode === 63) { // `?`
590
+ const processingInstructionEnd = matchProcessingInstruction(pos);
591
+ if (processingInstructionEnd !== -1) {
592
+ if (handler.processingInstruction) {
593
+ handler.processingInstruction(fullHtml.substring(pos, processingInstructionEnd));
594
+ }
595
+ advance(processingInstructionEnd - pos);
596
+ prevTag = processingInstructionTag;
597
+ prevAttrs = emptyAttrs;
598
+ continue;
599
+ }
600
+ if (handler.continueOnParseError) {
601
+ const { end, dropped } = matchBogusProcessingInstruction(pos);
602
+ reportParseError(pos, dropped ? 'Dropped processing instruction without `>`' : 'Read `<?` without a processing instruction target as comment');
603
+ if (!dropped && handler.comment) {
604
+ // The data starts with the `?`, and the markup stays as written
605
+ const data = fullHtml.substring(pos + 1, fullHtml[end - 1] === '>' ? end - 1 : end);
606
+ const result = handler.comment(data, false, fullHtml.substring(pos, end));
607
+ if (isThenable(result)) await result;
608
+ }
609
+ advance(end - pos);
610
+ prevTag = '';
611
+ prevAttrs = emptyAttrs;
469
612
  continue;
470
613
  }
471
614
  } else if (nextCode === 47) { // `/`
@@ -475,25 +618,36 @@ export class HTMLParser {
475
618
  const endTagMatch = matchEndTag(pos);
476
619
  if (endTagMatch) {
477
620
  advance(endTagMatch.text.length);
478
- prevTag = '/' + await parseEndTag(endTagMatch.text, endTagMatch.name);
479
- prevAttrs = [];
621
+ prevTag = '/' + parseEndTag(endTagMatch.text, endTagMatch.name);
622
+ prevAttrs = emptyAttrs;
480
623
  continue;
481
624
  }
482
625
  }
626
+ // Without a letter for a name, browsers drop `</>` and read anything else up to
627
+ // the next `>` (or the end of the input) as a bogus comment, never as text
628
+ const nameCode = fullHtml.charCodeAt(pos + 2) | 32;
629
+ if (handler.continueOnParseError && pos + 2 < fullLength && !(nameCode >= 97 && nameCode <= 122)) {
630
+ const bogusEnd = hasCloseAtOrAfter(pos + 2) ? nextGtPos : fullLength;
631
+ reportParseError(pos, bogusEnd === pos + 2 ? 'Dropped end tag without a name' : 'Read end tag without a name as comment');
632
+ if (bogusEnd > pos + 2 && handler.comment) {
633
+ const result = handler.comment(fullHtml.substring(pos + 2, bogusEnd));
634
+ if (isThenable(result)) await result;
635
+ }
636
+ advance(Math.min(bogusEnd + 1, fullLength) - pos);
637
+ prevTag = '';
638
+ prevAttrs = emptyAttrs;
639
+ continue;
640
+ }
483
641
  } else {
484
- // Start tag
485
642
  const startTagMatch = parseStartTag(pos);
486
643
  if (startTagMatch) {
487
644
  advance(startTagMatch.advance);
488
- prevTag = await handleStartTag(startTagMatch);
645
+ const started = handleStartTag(startTagMatch);
646
+ prevTag = isThenable(started) ? await started : started;
489
647
  continue;
490
648
  }
491
649
  }
492
-
493
- // Treat `<` as text
494
- if (handler.continueOnParseError) {
495
- // Continue looking for next tag
496
- }
650
+ // Otherwise, the `<` is read as text
497
651
  }
498
652
 
499
653
  let text;
@@ -504,45 +658,62 @@ export class HTMLParser {
504
658
  text = fullHtml.substring(pos);
505
659
  advance(fullLength - pos);
506
660
  }
661
+ // Text keeps a later doctype from setting the mode (template code may render to text
662
+ // or to nothing), except for whitespace and a byte order mark at the start, which
663
+ // browsers strip (as it runs before the first tag only, this costs next to nothing)
664
+ if (docModeSettable) {
665
+ const bom = pos === text.length && text.charCodeAt(0) === 0xFEFF;
666
+ const rest = bom ? text.slice(1) : text;
667
+ if (rest && !RE_WS_ONLY.test(rest)) {
668
+ docModeSettable = false;
669
+ }
670
+ }
507
671
 
508
672
  // Next tag for whitespace processing context
509
673
  if (handler.wantsNextTag) {
510
674
  // Same dispatch as above: A start tag cannot follow `<` + `/` or `!`,
511
675
  // an end tag requires `/`—the other matcher never runs
512
676
  const nextCode = fullHtml.charCodeAt(pos + 1);
513
- if (nextCode !== 47 && nextCode !== 33) {
677
+ if (nextCode === 63) {
678
+ nextTag = matchProcessingInstruction(pos) !== -1 ? processingInstructionTag : '';
679
+ nextAttrs = emptyAttrs;
680
+ } else if (nextCode !== 47 && nextCode !== 33) {
514
681
  const nextStartTagMatch = parseStartTag(pos);
515
682
  if (nextStartTagMatch) {
516
- nextTag = nextStartTagMatch.tagName;
517
- // Extract minimal attribute info for whitespace logic (just name/value pairs)
518
- nextAttrs = extractAttrInfo(nextStartTagMatch.attrs);
683
+ // Lowercase, as `prevTag` is, so `SPAN` reads as `span` to the whitespace logic
684
+ nextTag = nextStartTagMatch.lowerTagName;
685
+ // Extract minimal attribute info for whitespace logic (just name/value pairs)—
686
+ // only consulted next to an `input` (hidden inputs), so skip the extraction
687
+ // for every other tag rather than allocating attribute objects for each
688
+ nextAttrs = nextTag === 'input' ? extractAttrInfo(nextStartTagMatch.attrs) : emptyAttrs;
519
689
  cachedNextStartTag = { match: nextStartTagMatch, pos };
520
690
  } else {
521
691
  nextTag = '';
522
- nextAttrs = [];
692
+ nextAttrs = emptyAttrs;
523
693
  }
524
694
  } else if (nextCode === 47 && hasCloseAtOrAfter(pos)) {
525
695
  const nextEndTagMatch = matchEndTag(pos);
526
696
  if (nextEndTagMatch) {
527
- nextTag = '/' + nextEndTagMatch.name;
528
- nextAttrs = [];
697
+ nextTag = '/' + nextEndTagMatch.name.toLowerCase();
698
+ nextAttrs = emptyAttrs;
529
699
  cachedNextEndTag = { match: nextEndTagMatch, pos };
530
700
  } else {
531
701
  nextTag = '';
532
- nextAttrs = [];
702
+ nextAttrs = emptyAttrs;
533
703
  }
534
704
  } else {
535
705
  nextTag = '';
536
- nextAttrs = [];
706
+ nextAttrs = emptyAttrs;
537
707
  }
538
708
  }
539
709
 
540
710
  if (handler.chars) {
541
- const result = handler.chars(text, prevTag, nextTag, prevAttrs, nextAttrs);
711
+ // An element whose end tag follows its start tag’s text alone has that text for content
712
+ const result = handler.chars(text, prevTag, nextTag, prevAttrs, nextAttrs, sourcePos !== -1 && isSource(pos - text.length));
542
713
  if (isThenable(result)) await result;
543
714
  }
544
715
  prevTag = '';
545
- prevAttrs = [];
716
+ prevAttrs = emptyAttrs;
546
717
  } else {
547
718
  const stackedTag = lastTagLower;
548
719
  const isEscapableRawText = escapableRawTextElements.has(stackedTag);
@@ -562,11 +733,11 @@ export class HTMLParser {
562
733
  }
563
734
  // Advance HTML past the matched special tag content and its closing tag
564
735
  advance(rawText.length);
565
- await parseEndTag('</' + stackedTag + '>', stackedTag);
736
+ parseEndTag('</' + stackedTag + '>', stackedTag);
566
737
  // What follows stands after that end tag, not after the start tag still named here—
567
738
  // whitespace next to `textarea` stays verbatim only while the element is open
568
739
  prevTag = '/' + stackedTag;
569
- prevAttrs = [];
740
+ prevAttrs = emptyAttrs;
570
741
  } else {
571
742
  // Without an end tag of its own, the element holds the rest of the input as text
572
743
  if (handler.chars && remaining) {
@@ -580,6 +751,7 @@ export class HTMLParser {
580
751
  // Nothing that stands behind the start tag is markup, so no end tag may be
581
752
  // generated for the element, or for anything it stands in
582
753
  stack.length = 0;
754
+ stackVersion++;
583
755
  lastTag = '';
584
756
  lastTagLower = '';
585
757
  }
@@ -588,18 +760,21 @@ export class HTMLParser {
588
760
 
589
761
  if (pos === lastPos) {
590
762
  if (handler.continueOnParseError) {
591
- // Skip the problematic character and continue
763
+ // Keep the problematic character as text and move on
764
+ docModeSettable = false;
765
+ reportParseError(pos, `Kept \`${fullHtml[pos]}\` as text`);
592
766
  if (handler.chars) {
593
767
  const result = handler.chars(fullHtml[pos], prevTag, '', prevAttrs, []);
594
768
  if (isThenable(result)) await result;
595
769
  }
596
770
  advance(1);
597
771
  prevTag = '';
598
- prevAttrs = [];
772
+ prevAttrs = emptyAttrs;
599
773
  continue;
600
774
  }
601
775
  const loc = getLineColumn(pos);
602
- // Include some context before the error position so the snippet contains the offending markup plus preceding characters (e.g., `invalid<tag`)
776
+ // Include some context before the error position so the snippet contains the offending
777
+ // markup plus preceding characters (e.g., `invalid<tag`)
603
778
  const CONTEXT_BEFORE = 50;
604
779
  const startPos = Math.max(0, pos - CONTEXT_BEFORE);
605
780
  const snippet = fullHtml.slice(startPos, startPos + 200).replace(/\n/g, ' ');
@@ -609,11 +784,10 @@ export class HTMLParser {
609
784
 
610
785
  if (!handler.partialMarkup) {
611
786
  // Clean up any remaining tags
612
- await parseEndTag('', '');
787
+ parseEndTag('', '');
613
788
  }
614
789
 
615
- // Helper to extract minimal attribute info (name/value pairs) from raw attribute matches
616
- // Used for whitespace collapsing logic—doesn’t need full processing
790
+ // Minimal attribute info (name/value pairs) from raw matches, for whitespace collapsing
617
791
  function extractAttrInfo(/** @type {Array<Array<string | undefined>>} */ rawAttrs) {
618
792
  if (!rawAttrs || !rawAttrs.length) return [];
619
793
 
@@ -621,12 +795,11 @@ export class HTMLParser {
621
795
  const baseIndex = 1 + numCustomParts;
622
796
 
623
797
  return /** @type {HTMLAttribute[]} */ (rawAttrs.map((/** @type {Array<string | undefined>} */ args) => {
624
- // Extract attribute name (always at `baseIndex`)
625
798
  const name = args[baseIndex];
626
- // Extract value from double-quoted (`baseIndex + 2`), single-quoted (`baseIndex + 3`), or unquoted (`baseIndex + 4`)
799
+ // Double-quoted (`baseIndex + 2`), single-quoted (`+ 3`), or unquoted (`+ 4`)
627
800
  const value = args[baseIndex + 2] ?? args[baseIndex + 3] ?? args[baseIndex + 4];
628
801
  return { name: name?.toLowerCase() ?? '', value };
629
- }).filter(attr => attr.name)); // Filter out invalid entries
802
+ }).filter(attr => attr.name));
630
803
  }
631
804
 
632
805
  /**
@@ -654,10 +827,9 @@ export class HTMLParser {
654
827
  return close === -1 ? null : { text: fullHtml.slice(startPos, close + 1), name };
655
828
  }
656
829
 
657
- // Where a tag ends: After optional whitespace, at `>` or `/>`. Scanned by hand in a
658
- // single pass, where a regex did the same with one execution per attribute. The
659
- // result packs length and slash into one number (`length << 1 | hasSlash`, 0 for no
660
- // match) so the per-attribute loop allocates nothing.
830
+ // Where a tag ends: After optional whitespace, at `>` or `/>`. Scanned by hand in one pass, as
831
+ // a regex costs an execution per attribute; the result packs length and slash into one number
832
+ // (`length << 1 | hasSlash`, 0 for no match), so the per-attribute loop allocates nothing.
661
833
  function matchTagClose(/** @type {number} */ currentPos) {
662
834
  let scan = currentPos;
663
835
  let code = fullHtml.charCodeAt(scan);
@@ -689,17 +861,18 @@ export class HTMLParser {
689
861
  tagName = start[1] ?? '';
690
862
  consumed = start[0].length;
691
863
  }
692
- /** @type {{tagName: string, attrs: Array<Array<string|undefined>>, advance: number, unarySlash?: string}} */
864
+ /** @type {{tagName: string, lowerTagName: string, attrs: Array<Array<string|undefined>>, advance: number, unarySlash?: string}} */
693
865
  const match = {
694
866
  tagName,
867
+ // Once per tag, for the look-ahead as well as for the start tag itself
868
+ lowerTagName: tagName.toLowerCase(),
695
869
  attrs: [],
696
870
  advance: 0
697
871
  };
698
872
  let currentPos = startPos + consumed;
699
873
  let close, attr;
700
874
 
701
- // Safety limit: Max length of input to check for attributes
702
- // Protects against catastrophic backtracking on massive attribute values
875
+ // Caps the input the attribute regex sees, against catastrophic backtracking on huge values
703
876
  const MAX_ATTR_PARSE_LENGTH = 20000; // 20 KB should be enough for any reasonable tag
704
877
 
705
878
  while (true) {
@@ -709,7 +882,6 @@ export class HTMLParser {
709
882
  break;
710
883
  }
711
884
 
712
- // Limit the input length to pass to the regex to prevent catastrophic backtracking
713
885
  const remainingLen = fullLength - currentPos;
714
886
  const isLimited = remainingLen > MAX_ATTR_PARSE_LENGTH;
715
887
 
@@ -726,11 +898,22 @@ export class HTMLParser {
726
898
 
727
899
  // If input was limited and there’s a match, check if the value might be truncated
728
900
  if (attr) {
729
- // Check if the attribute value extends beyond our search window
730
901
  const attrEnd = attr[0].length;
731
- // If the match ends near the limit, the value might be truncated
732
- if (attrEnd > MAX_ATTR_PARSE_LENGTH - 100) {
733
- // Manually extract this attribute to handle potentially huge value
902
+ const numCustomParts = handler.customAttrSurround
903
+ ? handler.customAttrSurround.length * NCP
904
+ : 0;
905
+ const baseIndex = 1 + numCustomParts;
906
+ const unquotedValue = attr[baseIndex + 4];
907
+ if (unquotedValue !== undefined && attrEnd === searchStr.length) {
908
+ // An unquoted value running into the window’s end is read on past it
909
+ const unquotedRest = handler.continueOnParseError ? RE_UNQUOTED_VALUE_REST_LENIENT : RE_UNQUOTED_VALUE_REST;
910
+ unquotedRest.lastIndex = currentPos + attrEnd;
911
+ const rest = unquotedRest.exec(fullHtml)?.[0] ?? '';
912
+ attr[0] += rest;
913
+ attr[baseIndex + 4] = unquotedValue + rest;
914
+ } else if (attrEnd > MAX_ATTR_PARSE_LENGTH - 100) {
915
+ // If the match ends near the limit, a quoted value might be truncated,
916
+ // so extract the attribute manually
734
917
  const manualMatch = searchStr.match(/^\s*([^\s"'<>/=]+)\s*=\s*/);
735
918
  if (manualMatch) {
736
919
  const quoteChar = searchStr[manualMatch[0].length];
@@ -738,17 +921,12 @@ export class HTMLParser {
738
921
  const closeQuote = searchStr.indexOf(quoteChar, manualMatch[0].length + 1);
739
922
  if (closeQuote !== -1) {
740
923
  const fullAttrLen = closeQuote + 1;
741
- const numCustomParts = handler.customAttrSurround
742
- ? handler.customAttrSurround.length * NCP
743
- : 0;
744
- const baseIndex = 1 + numCustomParts;
745
924
 
746
925
  attr = [];
747
926
  attr[0] = searchStr.substring(0, fullAttrLen);
748
927
  attr[baseIndex] = manualMatch[1]; // Attribute name
749
928
  attr[baseIndex + 1] = '='; // `customAssign` (falls back to "=" for huge attributes)
750
929
  const value = searchStr.substring(manualMatch[0].length + 1, closeQuote);
751
- // Place value at correct index based on quote type
752
930
  if (quoteChar === '"') {
753
931
  attr[baseIndex + 2] = value; // Double-quoted value
754
932
  } else {
@@ -760,30 +938,20 @@ export class HTMLParser {
760
938
  continue;
761
939
  }
762
940
  }
763
- // Note: Unquoted attribute values are intentionally not handled here
764
- // Per HTML spec, unquoted values cannot contain spaces or special chars,
765
- // making a 20 KB+ unquoted value practically impossible; if encountered,
766
- // it’s malformed HTML and using the truncated regex match is acceptable
767
941
  }
768
- } else {
942
+ } else if (attr[baseIndex + 1] === undefined) {
769
943
  // If attr has no value assign but `=` follows in `fullHtml`,
770
944
  // the value would be cut off—reset to trigger manual extraction below
771
- const numCustomParts = handler.customAttrSurround
772
- ? handler.customAttrSurround.length * NCP
773
- : 0;
774
- const baseIndex = 1 + numCustomParts;
775
- if (attr[baseIndex + 1] === undefined) {
776
- const posAfterName = currentPos + attrEnd;
777
- if (/^\s*=/.test(fullHtml.slice(posAfterName, posAfterName + 50))) {
778
- attr = null;
779
- }
945
+ const posAfterName = currentPos + attrEnd;
946
+ if (/^\s*=/.test(fullHtml.slice(posAfterName, posAfterName + 50))) {
947
+ attr = null;
780
948
  }
781
949
  }
782
950
  }
783
951
 
784
952
  if (!attr) {
785
- // If input was limited and there’s no match, try manual extraction
786
- // This handles cases where quoted attributes exceed `MAX_ATTR_PARSE_LENGTH`
953
+ // If input was limited and there’s no match, a quoted value may exceed
954
+ // `MAX_ATTR_PARSE_LENGTH`, so try manual extraction
787
955
  const manualMatch = searchStr.match(/^\s*([^\s"'<>/=]+)\s*=\s*/);
788
956
  if (manualMatch) {
789
957
  const quoteChar = searchStr[manualMatch[0].length];
@@ -800,9 +968,8 @@ export class HTMLParser {
800
968
  attr = [];
801
969
  attr[0] = fullHtml.substring(currentPos, closeQuote + 1);
802
970
  attr[baseIndex] = manualMatch[1]; // Attribute name
803
- attr[baseIndex + 1] = '='; // customAssign
971
+ attr[baseIndex + 1] = '='; // `customAssign`
804
972
  const value = fullHtml.substring(currentPos + manualMatch[0].length + 1, closeQuote);
805
- // Place value at correct index based on quote type
806
973
  if (quoteChar === '"') {
807
974
  attr[baseIndex + 2] = value; // Double-quoted value
808
975
  } else {
@@ -850,7 +1017,6 @@ export class HTMLParser {
850
1017
  if (currentTag === needle) {
851
1018
  return stackIndex;
852
1019
  }
853
- // Stop searching if hitting a table boundary
854
1020
  if (currentTag === 'table') {
855
1021
  break;
856
1022
  }
@@ -868,6 +1034,7 @@ export class HTMLParser {
868
1034
  }
869
1035
  }
870
1036
  stack.length = stackIndex;
1037
+ stackVersion++;
871
1038
  lastTag = stackIndex ? (stack[stackIndex - 1]?.tag ?? '') : '';
872
1039
  lastTagLower = stackIndex ? (stack[stackIndex - 1]?.lowerTag ?? '') : '';
873
1040
  }
@@ -882,13 +1049,98 @@ export class HTMLParser {
882
1049
  return false;
883
1050
  }
884
1051
 
885
- async function handleStartTag(/** @type {{tagName: string, attrs: Array<Array<string | undefined>>, advance: number, unarySlash?: string}} */ match) {
1052
+ // The lenient attribute pattern takes characters into unquoted values that the strict
1053
+ // one rejects; the start tag has just been consumed, so it ends right before `pos`
1054
+ function reportUnquotedValueErrors(/** @type {{attrs: Array<Array<string | undefined>>, advance: number}} */ match) {
1055
+ let attrPos = pos - match.advance;
1056
+ for (const attr of match.attrs) {
1057
+ const text = attr[0] ?? '';
1058
+ attrPos = fullHtml.indexOf(text, attrPos);
1059
+ const surroundCount = handler.customAttrSurround ? handler.customAttrSurround.length : 0;
1060
+ for (let i = 0; i <= surroundCount; i++) {
1061
+ // Unquoted values sit at index 5 of each surround block, and 4 behind the plain name
1062
+ const value = i < surroundCount ? attr[1 + i * NCP + 5] : attr[1 + surroundCount * NCP + 4];
1063
+ const errorIndex = value ? value.search(RE_UNQUOTED_VALUE_ERROR) : -1;
1064
+ if (value && errorIndex !== -1) {
1065
+ reportParseError(attrPos + text.lastIndexOf(value) + errorIndex, `Kept \`${value[errorIndex]}\` in unquoted attribute value`);
1066
+ }
1067
+ }
1068
+ attrPos += text.length;
1069
+ }
1070
+ }
1071
+
1072
+ // Returns the lowercase name for the parse loop, or a Promise of it
1073
+ // when `handler.start` awaits (which only happens with attributes)
1074
+ function handleStartTag(/** @type {{tagName: string, lowerTagName: string, attrs: Array<Array<string | undefined>>, advance: number, unarySlash?: string}} */ match) {
886
1075
  const tagName = match.tagName;
887
- const lowerTagName = tagName.toLowerCase();
1076
+ const lowerTagName = match.lowerTagName;
888
1077
  let unarySlash = match.unarySlash;
889
1078
 
890
- if (lastTagLower === 'p' && nonPhrasing.has(lowerTagName)) {
891
- await parseEndTag('', lastTag);
1079
+ docModeSettable = false;
1080
+ if (handler.parseError) reportUnquotedValueErrors(match);
1081
+ // A plain loop, so a tag costs no closure allocation per attribute
1082
+ const rawAttrs = match.attrs;
1083
+ /** @type {HTMLAttribute[]} */
1084
+ const attrs = [];
1085
+ for (let i = 0; i < rawAttrs.length; i++) {
1086
+ const args = /** @type {Array<string | undefined>} */ (rawAttrs[i]);
1087
+ /** @type {string | undefined} */
1088
+ let name, value, customOpen, customClose, customAssign, quote;
1089
+
1090
+ // Where `customAssign` sits; the value is in one of the three slots after it
1091
+ let assignIndex = -1;
1092
+ let j = 1;
1093
+ if (handler.customAttrSurround) {
1094
+ for (let s = 0, l = handler.customAttrSurround.length; s < l; s++, j += NCP) {
1095
+ name = args[j + 1];
1096
+ if (name) {
1097
+ assignIndex = j + 2;
1098
+ customOpen = args[j];
1099
+ customClose = args[j + 6];
1100
+ break;
1101
+ }
1102
+ }
1103
+ }
1104
+
1105
+ if (!name && (name = args[j])) {
1106
+ assignIndex = j + 1;
1107
+ }
1108
+
1109
+ if (name) {
1110
+ customAssign = args[assignIndex];
1111
+ if (typeof (value = args[assignIndex + 1]) !== 'undefined') {
1112
+ quote = '"';
1113
+ } else if (typeof (value = args[assignIndex + 2]) !== 'undefined') {
1114
+ quote = '\'';
1115
+ } else {
1116
+ value = args[assignIndex + 3];
1117
+ quote = '';
1118
+ }
1119
+ }
1120
+
1121
+ attrs.push({
1122
+ name: name ?? '',
1123
+ value,
1124
+ customAssign: customAssign || '=',
1125
+ customOpen: customOpen || '',
1126
+ customClose: customClose || '',
1127
+ quote: quote || ''
1128
+ });
1129
+ }
1130
+
1131
+ // HTML reads these as its own, so the foreign elements open end here
1132
+ if (namespaceInside(stack[stack.length - 1]) && (breaksOutOfForeignContent.has(lowerTagName) ||
1133
+ (lowerTagName === 'font' && attrs.some(attr => RE_FONT_BREAKOUT_ATTR.test(attr.name))))) {
1134
+ closeForeignContent();
1135
+ }
1136
+
1137
+ const pIndex = stack.length ? (stack[stack.length - 1]?.pScope ?? -1) : -1;
1138
+ if (pIndex >= 0 && closesP.has(lowerTagName)) {
1139
+ if (lowerTagName !== 'table' || docMode === 'no-quirks') {
1140
+ parseEndTag('', stack[pIndex]?.tag ?? 'p');
1141
+ } else if (!docMode) {
1142
+ pHoldingTable.add(/** @type {object} */ (stack[pIndex]));
1143
+ }
892
1144
  }
893
1145
  // A row or cell start tag closes the row or cell still open in the same table,
894
1146
  // which may sit deeper down the stack than the element that was opened last
@@ -908,7 +1160,6 @@ export class HTMLParser {
908
1160
  closeIfFoundInCurrentTable('thead');
909
1161
  }
910
1162
  } else if (lowerTagName === 'thead') {
911
- // If a `tbody` or `tfoot` is open in the current table, close it
912
1163
  if (!closeIfFoundInCurrentTable('tbody')) {
913
1164
  closeIfFoundInCurrentTable('tfoot');
914
1165
  }
@@ -916,22 +1167,22 @@ export class HTMLParser {
916
1167
  if (lowerTagName === 'col' && findTagInCurrentTable('colgroup') < 0) {
917
1168
  lastTag = 'colgroup';
918
1169
  lastTagLower = 'colgroup';
919
- stack.push({ tag: lastTag, lowerTag: 'colgroup', attrs: [], namespace: namespaceInside(stack[stack.length - 1]) });
1170
+ pushOpenElement(lastTag, 'colgroup', []);
920
1171
  if (handler.start) {
921
- await handler.start(lastTag, [], false, '', true);
1172
+ handler.start(lastTag, [], false, '', true);
922
1173
  }
923
1174
  } else if (lowerTagName !== 'col' && lastTagLower === 'colgroup') {
924
1175
  // Auto-close synthetic `<colgroup>` when a non-`col` element starts
925
- await parseEndTag('', 'colgroup');
1176
+ parseEndTag('', 'colgroup');
926
1177
  }
927
1178
 
928
1179
  if (closeSelf.has(lowerTagName) && lastTagLower === lowerTagName) {
929
- await parseEndTag('', tagName);
1180
+ parseEndTag('', tagName);
930
1181
  }
931
1182
 
932
1183
  // Handle `dt`/`dd` cross-closing: `dt` followed by `dd`, or `dd` followed by `dt`
933
1184
  if ((lowerTagName === 'dt' || lowerTagName === 'dd') && (lastTagLower === 'dt' || lastTagLower === 'dd')) {
934
- await parseEndTag('', lastTag);
1185
+ parseEndTag('', lastTag);
935
1186
  }
936
1187
 
937
1188
  // HTML ignores the slash on a start tag—only in SVG and MathML does it close the
@@ -939,76 +1190,42 @@ export class HTMLParser {
939
1190
  const selfClosed = !!unarySlash && (handler.selfClosingSlash || startsForeignContent(lowerTagName));
940
1191
  const unary = empty.has(lowerTagName) || (lowerTagName === 'html' && lastTagLower === 'head') || selfClosed;
941
1192
 
942
- const attrs = /** @type {HTMLAttribute[]} */ (match.attrs.map(function (/** @type {Array<string | undefined>} */ args) {
943
- /** @type {string | undefined} */
944
- let name, value, customOpen, customClose, customAssign, quote;
945
-
946
- // Hackish workaround for Firefox bug, https://bugzilla.mozilla.org/show_bug.cgi?id=369778
947
- if (IS_REGEX_CAPTURING_BROKEN && (args[0] ?? '').indexOf('""') === -1) {
948
- if (args[3] === '') { delete args[3]; }
949
- if (args[4] === '') { delete args[4]; }
950
- if (args[5] === '') { delete args[5]; }
951
- }
952
-
953
- function populate(/** @type {number} */ index) {
954
- customAssign = args[index];
955
- value = args[index + 1];
956
- if (typeof value !== 'undefined') {
957
- return '"';
958
- }
959
- value = args[index + 2];
960
- if (typeof value !== 'undefined') {
961
- return '\'';
962
- }
963
- value = args[index + 3];
964
- if (typeof value === 'undefined' && name && fillAttrs.has(name.toLowerCase())) {
965
- value = name;
966
- }
967
- return '';
968
- }
969
-
970
- let j = 1;
971
- if (handler.customAttrSurround) {
972
- for (let i = 0, l = handler.customAttrSurround.length; i < l; i++, j += NCP) {
973
- name = args[j + 1];
974
- if (name) {
975
- quote = populate(j + 2);
976
- customOpen = args[j];
977
- customClose = args[j + 6];
978
- break;
979
- }
980
- }
981
- }
982
-
983
- if (!name && (name = args[j])) {
984
- quote = populate(j + 1);
985
- }
986
-
987
- return {
988
- name: name ?? '',
989
- value,
990
- customAssign: customAssign || '=',
991
- customOpen: customOpen || '',
992
- customClose: customClose || '',
993
- quote: quote || ''
994
- };
995
- }));
996
-
997
1193
  if (!unary) {
998
- stack.push({ tag: tagName, lowerTag: lowerTagName, attrs, namespace: namespaceInside(stack[stack.length - 1]) });
1194
+ const namespace = pushOpenElement(tagName, lowerTagName, attrs);
999
1195
  lastTag = tagName;
1000
1196
  lastTagLower = lowerTagName;
1001
1197
  unarySlash = '';
1198
+ if (namespace === 'svg' && special.has(lowerTagName)) {
1199
+ sourcePos = pos;
1200
+ }
1002
1201
  }
1003
1202
 
1004
- // Store attributes for `prevAttrs` tracking (used in whitespace collapsing)
1203
+ // `prevAttrs` feeds whitespace collapsing
1005
1204
  prevAttrs = attrs;
1006
1205
 
1007
- if (handler.start) {
1008
- await handler.start(tagName, attrs, unary, unarySlash);
1206
+ // The name is returned so the parse loop can skip lowercasing it again
1207
+ const started = handler.start?.(tagName, attrs, unary, unarySlash);
1208
+ return isThenable(started) ? started.then(() => lowerTagName) : lowerTagName;
1209
+ }
1210
+
1211
+ // Pushes an open element, noting the `p` in scope from within it: its own index
1212
+ // for a `p`, none past a scope boundary, foreign element, or `noscript` (which
1213
+ // holds text with scripting), and otherwise its parent’s; returns the namespace it sits in
1214
+ function pushOpenElement(/** @type {string} */ tag, /** @type {string} */ lowerTag, /** @type {HTMLAttribute[]} */ attrs) {
1215
+ const parent = stack.length ? stack[stack.length - 1] : undefined;
1216
+ const namespace = namespaceInside(parent);
1217
+ let pScope = -1;
1218
+ if (!namespace) {
1219
+ if (lowerTag === 'p') {
1220
+ pScope = stack.length;
1221
+ } else if (parent && parent.pScope !== -1 && !buttonScopeBoundaries.has(lowerTag) && lowerTag !== 'svg' && lowerTag !== 'math' && lowerTag !== 'noscript') {
1222
+ // Most elements sit outside any `p`, so the boundary checks only run inside one
1223
+ pScope = parent.pScope;
1224
+ }
1009
1225
  }
1010
- // Returned so the parse loop can skip lowercasing the name again
1011
- return lowerTagName;
1226
+ stack.push({ tag, lowerTag, attrs, namespace, pScope });
1227
+ stackVersion++;
1228
+ return namespace;
1012
1229
  }
1013
1230
 
1014
1231
  // `needle` must already be lowercase
@@ -1022,10 +1239,38 @@ export class HTMLParser {
1022
1239
  return stackIndex;
1023
1240
  }
1024
1241
 
1025
- async function parseEndTag(/** @type {string} */ tag, /** @type {string} */ tagName) {
1242
+ // Closes the foreign elements open down to the nearest HTML element or
1243
+ // integration point, writing their end tags so that an SVG stays well-formed
1244
+ // for SVGO (none of them is an HTML `p`, so none can hold a table). This
1245
+ // repeats the closing loop of `parseEndTag`, as sharing it costs that
1246
+ // hot function about 1%.
1247
+ function closeForeignContent() {
1248
+ let stackIndex = stack.length;
1249
+ while (stackIndex && namespaceInside(stack[stackIndex - 1])) {
1250
+ stackIndex--;
1251
+ }
1252
+ for (let i = stack.length - 1; i >= stackIndex; i--) {
1253
+ if (handler.end) {
1254
+ const entry = stack[i];
1255
+ handler.end(entry?.tag, entry?.attrs, false, '', false);
1256
+ }
1257
+ }
1258
+ stack.length = stackIndex;
1259
+ stackVersion++;
1260
+ lastTag = stackIndex ? (stack[stackIndex - 1]?.tag ?? '') : '';
1261
+ lastTagLower = stackIndex ? (stack[stackIndex - 1]?.lowerTag ?? '') : '';
1262
+ }
1263
+
1264
+ function parseEndTag(/** @type {string} */ tag, /** @type {string} */ tagName) {
1265
+ docModeSettable = false;
1026
1266
  let stackIndex;
1027
1267
  const lowerTagName = tagName ? tagName.toLowerCase() : '';
1028
1268
 
1269
+ // As with the start tags that break out of foreign content
1270
+ if (tag && (lowerTagName === 'p' || lowerTagName === 'br') && namespaceInside(stack[stack.length - 1])) {
1271
+ closeForeignContent();
1272
+ }
1273
+
1029
1274
  // Find the closest opened tag of the same type
1030
1275
  if (tagName) {
1031
1276
  stackIndex = findTag(lowerTagName);
@@ -1033,34 +1278,41 @@ export class HTMLParser {
1033
1278
  stackIndex = 0;
1034
1279
  }
1035
1280
 
1281
+ // Whatever follows the name, which browsers drop but a custom fragment may stand in for
1282
+ const rest = tag.length > tagName.length + 3 ? tag.slice(tagName.length + 2, -1) : '';
1283
+
1036
1284
  if (stackIndex >= 0) {
1037
1285
  // Close all the open elements, up the stack
1038
1286
  for (let i = stack.length - 1; i >= stackIndex; i--) {
1039
1287
  if (handler.end) {
1040
- handler.end(stack[i]?.tag, stack[i]?.attrs, i > stackIndex || !tag);
1288
+ const entry = stack[i];
1289
+ handler.end(entry?.tag, entry?.attrs, i > stackIndex || !tag, i === stackIndex ? rest : '', entry?.lowerTag === 'p' && pHoldingTable.has(entry));
1041
1290
  }
1042
1291
  }
1043
1292
 
1044
- // Remove the open elements from the stack
1045
1293
  stack.length = stackIndex;
1294
+ stackVersion++;
1046
1295
  lastTag = stackIndex ? (stack[stackIndex - 1]?.tag ?? '') : '';
1047
1296
  lastTagLower = stackIndex ? (stack[stackIndex - 1]?.lowerTag ?? '') : '';
1048
- } else if (handler.partialMarkup && tagName) {
1049
- // In partial markup mode, preserve stray end tags
1297
+ } else if ((handler.partialMarkup || formattingElements.has(lowerTagName)) && tagName) {
1298
+ // In partial markup mode, preserve stray end tags, and those of formatting elements always
1050
1299
  if (handler.end) {
1051
- handler.end(tagName, [], false);
1300
+ handler.end(tagName, [], false, rest);
1052
1301
  }
1053
1302
  } else if (lowerTagName === 'br') {
1054
1303
  if (handler.start) {
1055
- await handler.start(tagName, [], true, '');
1304
+ handler.start(tagName, [], true, '');
1056
1305
  }
1057
1306
  } else if (lowerTagName === 'p') {
1058
1307
  if (handler.start) {
1059
- await handler.start(tagName, [], false, '', true);
1308
+ handler.start(tagName, [], false, '', true);
1060
1309
  }
1061
1310
  if (handler.end) {
1062
1311
  handler.end(tagName, []);
1063
1312
  }
1313
+ } else if (handler.strayEnd) {
1314
+ // An end tag with nothing to close is dropped
1315
+ handler.strayEnd();
1064
1316
  }
1065
1317
  // Returned so the parse loop can skip lowercasing the name again
1066
1318
  return lowerTagName;