@mdream/js 2.0.0-beta.1 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +402 -126
  2. package/dist/_chunks/clean.mjs +526 -0
  3. package/dist/_chunks/const.mjs +3 -7
  4. package/dist/_chunks/extraction.d.mts +14 -0
  5. package/dist/_chunks/html.mjs +260 -0
  6. package/dist/_chunks/markdown-processor.mjs +1077 -828
  7. package/dist/_chunks/minimal.mjs +29 -0
  8. package/dist/_chunks/output-runner.mjs +54 -0
  9. package/dist/_chunks/parse.mjs +134 -1501
  10. package/dist/_chunks/plugin.mjs +14 -0
  11. package/dist/_chunks/src.mjs +291 -0
  12. package/dist/_chunks/tag-overrides.mjs +138 -0
  13. package/dist/_chunks/{plugins.mjs → tailwind.mjs} +145 -292
  14. package/dist/_chunks/text.mjs +583 -0
  15. package/dist/_chunks/types.d.mts +136 -126
  16. package/dist/_chunks/url.mjs +82 -0
  17. package/dist/_chunks/utils.mjs +659 -0
  18. package/dist/clean.d.mts +10 -0
  19. package/dist/clean.mjs +2 -0
  20. package/dist/cli.mjs +47 -8
  21. package/dist/html.d.mts +6 -0
  22. package/dist/html.mjs +2 -0
  23. package/dist/index.d.mts +5 -4
  24. package/dist/index.mjs +4 -58
  25. package/dist/parse.d.mts +15 -10
  26. package/dist/plugins.d.mts +13 -28
  27. package/dist/plugins.mjs +52 -2
  28. package/dist/preset/minimal.d.mts +14 -2
  29. package/dist/preset/minimal.mjs +1 -32
  30. package/dist/splitter.d.mts +12 -4
  31. package/dist/splitter.mjs +386 -113
  32. package/dist/text.d.mts +6 -0
  33. package/dist/text.mjs +2 -0
  34. package/package.json +34 -8
  35. package/dist/_chunks/index.d.mts +0 -9
  36. package/dist/_chunks/minimal.d.mts +0 -6
  37. package/dist/_chunks/resolve-plugins.mjs +0 -44
  38. package/dist/_chunks/stream.mjs +0 -37
  39. package/dist/core.d.mts +0 -15
  40. package/dist/core.mjs +0 -28
@@ -1,1494 +1,44 @@
1
- import { BLOCKQUOTE_SPACING, LIST_ITEM_SPACING, NO_SPACING, TABLE_ROW_SPACING, TagIdMap, isInsideRawHtmlBlock } from "./const.mjs";
2
- const HTML_ENTITIES = {
3
- AElig: "Æ",
4
- AMP: "&",
5
- Aacute: "Á",
6
- Acirc: "Â",
7
- Agrave: "À",
8
- $Alpha: "Α",
9
- Aring: "Å",
10
- Atilde: "Ã",
11
- Auml: "Ä",
12
- $Beta: "Β",
13
- COPY: "©",
14
- Ccedil: "Ç",
15
- $Chi: "Χ",
16
- $Dagger: "‡",
17
- $Delta: "Δ",
18
- ETH: "Ð",
19
- Eacute: "É",
20
- Ecirc: "Ê",
21
- Egrave: "È",
22
- $Epsilon: "Ε",
23
- $Eta: "Η",
24
- Euml: "Ë",
25
- GT: ">",
26
- $Gamma: "Γ",
27
- Iacute: "Í",
28
- Icirc: "Î",
29
- Igrave: "Ì",
30
- $Iota: "Ι",
31
- Iuml: "Ï",
32
- $Kappa: "Κ",
33
- LT: "<",
34
- $Lambda: "Λ",
35
- $Mu: "Μ",
36
- Ntilde: "Ñ",
37
- $Nu: "Ν",
38
- $OElig: "Œ",
39
- Oacute: "Ó",
40
- Ocirc: "Ô",
41
- Ograve: "Ò",
42
- $Omega: "Ω",
43
- $Omicron: "Ο",
44
- Oslash: "Ø",
45
- Otilde: "Õ",
46
- Ouml: "Ö",
47
- $Phi: "Φ",
48
- $Pi: "Π",
49
- $Prime: "″",
50
- $Psi: "Ψ",
51
- QUOT: "\"",
52
- REG: "®",
53
- $Rho: "Ρ",
54
- $Scaron: "Š",
55
- $Sigma: "Σ",
56
- THORN: "Þ",
57
- $Tau: "Τ",
58
- $Theta: "Θ",
59
- Uacute: "Ú",
60
- Ucirc: "Û",
61
- Ugrave: "Ù",
62
- $Upsilon: "Υ",
63
- Uuml: "Ü",
64
- $Xi: "Ξ",
65
- Yacute: "Ý",
66
- $Yuml: "Ÿ",
67
- $Zeta: "Ζ",
68
- aacute: "á",
69
- acirc: "â",
70
- acute: "´",
71
- aelig: "æ",
72
- agrave: "à",
73
- $alefsym: "ℵ",
74
- $alpha: "α",
75
- amp: "&",
76
- $and: "∧",
77
- $ang: "∠",
78
- $apos: "'",
79
- aring: "å",
80
- $asymp: "≈",
81
- atilde: "ã",
82
- auml: "ä",
83
- $bdquo: "„",
84
- $beta: "β",
85
- brvbar: "¦",
86
- $bull: "•",
87
- $cap: "∩",
88
- ccedil: "ç",
89
- cedil: "¸",
90
- cent: "¢",
91
- $chi: "χ",
92
- $circ: "ˆ",
93
- $clubs: "♣",
94
- $cong: "≅",
95
- copy: "©",
96
- $crarr: "↵",
97
- $cup: "∪",
98
- curren: "¤",
99
- $dArr: "⇓",
100
- $dagger: "†",
101
- $darr: "↓",
102
- deg: "°",
103
- $delta: "δ",
104
- $diams: "♦",
105
- divide: "÷",
106
- eacute: "é",
107
- ecirc: "ê",
108
- egrave: "è",
109
- $empty: "∅",
110
- $epsilon: "ε",
111
- $equiv: "≡",
112
- $eta: "η",
113
- eth: "ð",
114
- euml: "ë",
115
- $euro: "€",
116
- $exist: "∃",
117
- $fnof: "ƒ",
118
- $forall: "∀",
119
- frac12: "½",
120
- frac14: "¼",
121
- frac34: "¾",
122
- $frasl: "⁄",
123
- $gamma: "γ",
124
- $ge: "≥",
125
- gt: ">",
126
- $hArr: "⇔",
127
- $harr: "↔",
128
- $hearts: "♥",
129
- $hellip: "…",
130
- iacute: "í",
131
- icirc: "î",
132
- iexcl: "¡",
133
- igrave: "ì",
134
- $image: "ℑ",
135
- $infin: "∞",
136
- $int: "∫",
137
- $iota: "ι",
138
- iquest: "¿",
139
- $isin: "∈",
140
- iuml: "ï",
141
- $kappa: "κ",
142
- $lArr: "⇐",
143
- $lambda: "λ",
144
- $lang: "⟨",
145
- laquo: "«",
146
- $larr: "←",
147
- $lceil: "⌈",
148
- $ldquo: "“",
149
- $le: "≤",
150
- $lfloor: "⌊",
151
- $lowast: "∗",
152
- $loz: "◊",
153
- $lsaquo: "‹",
154
- $lsquo: "‘",
155
- lt: "<",
156
- macr: "¯",
157
- $mdash: "—",
158
- micro: "µ",
159
- middot: "·",
160
- $minus: "−",
161
- $mu: "μ",
162
- $nabla: "∇",
163
- nbsp: "\xA0",
164
- $ndash: "–",
165
- $ne: "≠",
166
- $ni: "∋",
167
- not: "¬",
168
- $notin: "∉",
169
- $nsub: "⊄",
170
- ntilde: "ñ",
171
- $nu: "ν",
172
- oacute: "ó",
173
- ocirc: "ô",
174
- $oelig: "œ",
175
- ograve: "ò",
176
- $oline: "‾",
177
- $omega: "ω",
178
- $omicron: "ο",
179
- $oplus: "⊕",
180
- $or: "∨",
181
- ordf: "ª",
182
- ordm: "º",
183
- oslash: "ø",
184
- otilde: "õ",
185
- $otimes: "⊗",
186
- ouml: "ö",
187
- para: "¶",
188
- $part: "∂",
189
- $permil: "‰",
190
- $perp: "⊥",
191
- $phi: "φ",
192
- $pi: "π",
193
- $piv: "ϖ",
194
- plusmn: "±",
195
- pound: "£",
196
- $prime: "′",
197
- $prod: "∏",
198
- $prop: "∝",
199
- $psi: "ψ",
200
- quot: "\"",
201
- $rArr: "⇒",
202
- $radic: "√",
203
- $rang: "⟩",
204
- raquo: "»",
205
- $rarr: "→",
206
- $rceil: "⌉",
207
- $rdquo: "”",
208
- $real: "ℜ",
209
- reg: "®",
210
- $rfloor: "⌋",
211
- $rho: "ρ",
212
- $rsaquo: "›",
213
- $rsquo: "’",
214
- $sbquo: "‚",
215
- $scaron: "š",
216
- $sdot: "⋅",
217
- sect: "§",
218
- shy: "­",
219
- $sigma: "σ",
220
- $sigmaf: "ς",
221
- $sim: "∼",
222
- $spades: "♠",
223
- $sub: "⊂",
224
- $sube: "⊆",
225
- $sum: "∑",
226
- $sup: "⊃",
227
- sup1: "¹",
228
- sup2: "²",
229
- sup3: "³",
230
- $supe: "⊇",
231
- szlig: "ß",
232
- $tau: "τ",
233
- $there4: "∴",
234
- $theta: "θ",
235
- $thetasym: "ϑ",
236
- thorn: "þ",
237
- $tilde: "˜",
238
- times: "×",
239
- $trade: "™",
240
- $uArr: "⇑",
241
- uacute: "ú",
242
- $uarr: "↑",
243
- ucirc: "û",
244
- ugrave: "ù",
245
- uml: "¨",
246
- $upsih: "ϒ",
247
- $upsilon: "υ",
248
- uuml: "ü",
249
- $weierp: "℘",
250
- $xi: "ξ",
251
- yacute: "ý",
252
- yen: "¥",
253
- yuml: "ÿ",
254
- $zeta: "ζ"
255
- };
256
- function lowerAscii(code) {
257
- return code >= 65 && code <= 90 ? code + 32 : code;
258
- }
259
- function isInsideHeading(depthMap) {
260
- for (let tagId = 7; tagId <= 12; tagId++) if (depthMap[tagId]) return true;
261
- return false;
262
- }
263
- function isInsideTableCell(state) {
264
- const depthMap = state.depthMap;
265
- return depthMap[32] > 0 || depthMap[31] > 0;
266
- }
267
- function schemeMatches(href, start, end, scheme) {
268
- let matched = 0;
269
- for (let index = start; index < end; index++) {
270
- const code = href.charCodeAt(index);
271
- if (code === 9 || code === 10 || code === 13) continue;
272
- if (lowerAscii(code) !== scheme.charCodeAt(matched)) return false;
273
- if (++matched === scheme.length) return true;
274
- }
275
- return false;
276
- }
277
- function isDataUrl(src) {
278
- let start = 0;
279
- while (start < src.length && src.charCodeAt(start) <= 32) start++;
280
- let end = src.length;
281
- while (end > start && src.charCodeAt(end - 1) <= 32) end--;
282
- return schemeMatches(src, start, end, "data:");
283
- }
284
- function isEmptyLinkHref(href) {
285
- let start = 0;
286
- while (start < href.length && href.charCodeAt(start) <= 32) start++;
287
- let end = href.length;
288
- while (end > start && href.charCodeAt(end - 1) <= 32) end--;
289
- switch (lowerAscii(href.charCodeAt(start))) {
290
- case 35: return end - start === 1;
291
- case 106: return schemeMatches(href, start, end, "javascript:");
292
- case 100: return schemeMatches(href, start, end, "data:");
293
- case 118: return schemeMatches(href, start, end, "vbscript:");
294
- default: return false;
295
- }
296
- }
297
- function isSafeHtmlUrl(href, image = false) {
298
- let start = 0;
299
- while (start < href.length && href.charCodeAt(start) <= 32) start++;
300
- let end = href.length;
301
- while (end > start && href.charCodeAt(end - 1) <= 32) end--;
302
- if (start === end) return false;
303
- for (let index = start; index < end; index++) {
304
- const code = href.charCodeAt(index);
305
- if (code === 9 || code === 10 || code === 13) continue;
306
- if (code === 58) switch (lowerAscii(href.charCodeAt(start))) {
307
- case 104: return schemeMatches(href, start, end, "http:") || schemeMatches(href, start, end, "https:");
308
- case 109: return !image && schemeMatches(href, start, end, "mailto:");
309
- case 116: return !image && schemeMatches(href, start, end, "tel:");
310
- case 102: return !image && schemeMatches(href, start, end, "ftp:");
311
- default: return false;
312
- }
313
- if (code === 47 || code === 63 || code === 35) return true;
314
- const lower = lowerAscii(code);
315
- if (!(lower >= 97 && lower <= 122 || code >= 48 && code <= 57 || code === 43 || code === 45 || code === 46)) return true;
316
- }
317
- return true;
318
- }
319
- function escapeHtml(value, attribute = false, protectMarkdown = false) {
320
- let escaped = "";
321
- let copiedUntil = 0;
322
- for (let index = 0; index < value.length; index++) {
323
- const code = value.charCodeAt(index);
324
- let replacement;
325
- if (code === 38) replacement = "&amp;";
326
- else if (code === 60) replacement = "&lt;";
327
- else if (code === 62) replacement = "&gt;";
328
- else if (attribute && code === 34) replacement = "&quot;";
329
- else if (protectMarkdown && code === 91) replacement = "&#91;";
330
- else if (protectMarkdown && code === 93) replacement = "&#93;";
331
- if (replacement !== void 0) {
332
- escaped += value.slice(copiedUntil, index) + replacement;
333
- copiedUntil = index + 1;
334
- }
335
- }
336
- return copiedUntil === 0 ? value : escaped + value.slice(copiedUntil);
337
- }
338
- function continuationPrefix(node, listIndentWidths, includeBlockquotes = true) {
339
- const chain = [];
340
- let current = node.parent;
341
- while (current) {
342
- chain.push(current);
343
- current = current.parent;
344
- }
345
- let prefix = "";
346
- let listIndex = 0;
347
- for (let i = chain.length - 1; i >= 0; i--) {
348
- const tagId = chain[i].tagId;
349
- if (tagId === 22 && includeBlockquotes) prefix += "> ";
350
- else if (tagId === 25) {
351
- prefix += " ".repeat(listIndentWidths[listIndex] ?? 2);
352
- listIndex++;
353
- }
354
- }
355
- return prefix;
356
- }
357
- const C1_REPLACEMENTS = "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ";
358
- function isAsciiAlphaNumeric(code) {
359
- return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
360
- }
361
- function isHtmlAsciiWhitespace(code) {
362
- return code === 32 || code === 9 || code === 10 || code === 12 || code === 13;
363
- }
364
- const LANGUAGE_PREFIX = [
365
- 108,
366
- 97,
367
- 110,
368
- 103,
369
- 117,
370
- 97,
371
- 103,
372
- 101,
373
- 45
374
- ];
375
- function hasLanguagePrefix(value, start) {
376
- for (let offset = 0; offset < 9; offset++) if (value.charCodeAt(start + offset) !== LANGUAGE_PREFIX[offset]) return false;
377
- return true;
378
- }
379
- function isUnsafeFenceInfoCode(code) {
380
- if (code < 32 || code === 127) return true;
381
- return code === 34 || code === 39 || code === 38 || code === 60 || code === 62 || code === 96 || code === 126;
382
- }
383
- function getLanguageFromClass(className) {
384
- if (!className) return "";
385
- const length = className.length;
386
- let index = 0;
387
- while (index < length) {
388
- if (isHtmlAsciiWhitespace(className.charCodeAt(index))) {
389
- index++;
390
- continue;
391
- }
392
- const tokenStart = index;
393
- do
394
- index++;
395
- while (index < length && !isHtmlAsciiWhitespace(className.charCodeAt(index)));
396
- const tokenEnd = index;
397
- const languageStart = tokenStart + 9;
398
- if (languageStart >= tokenEnd || !hasLanguagePrefix(className, tokenStart)) continue;
399
- let valid = true;
400
- for (let cursor = languageStart; cursor < tokenEnd; cursor++) if (isUnsafeFenceInfoCode(className.charCodeAt(cursor))) {
401
- valid = false;
402
- break;
403
- }
404
- if (valid) return className.slice(languageStart, tokenEnd);
405
- }
406
- return "";
407
- }
408
- function parseUnsignedInteger(raw) {
409
- if (raw === void 0 || !/^[\t\n\f\r ]*\+?\d+[\t\n\f\r ]*$/.test(raw)) return void 0;
410
- const value = Number(raw);
411
- return value <= 4294967295 ? value : void 0;
412
- }
413
- function lastOutputChar(buffer, end = buffer.length) {
414
- for (let index = end - 1; index >= 0; index--) {
415
- const fragment = buffer[index];
416
- if (fragment.length > 0) return fragment.charCodeAt(fragment.length - 1);
417
- }
418
- return -1;
419
- }
420
- function blockOpenPrefix(buffer, prefix, end = buffer.length) {
421
- switch (lastOutputChar(buffer, end)) {
422
- case -1: return;
423
- case 32: {
424
- let fragment = end - 1;
425
- let index = buffer[fragment].length;
426
- for (;;) {
427
- if (index === 0) {
428
- if (--fragment < 0) return void 0;
429
- index = buffer[fragment].length;
430
- continue;
431
- }
432
- const code = buffer[fragment].charCodeAt(--index);
433
- if (code !== 32) return code === 10 || listMarkerLineStart(buffer, fragment, index) ? void 0 : `\n\n${prefix ?? ""}`;
434
- }
435
- }
436
- case 10: return prefix || void 0;
437
- default: return `\n\n${prefix ?? ""}`;
438
- }
439
- }
440
- function figcaptionOwnsBlockSpacing(node, plainText) {
441
- let parent = node.parent;
442
- while (parent) {
443
- if (parent.tagId === 32 || parent.tagId === 31) return false;
444
- if (!plainText && parent.tagId !== 37 && parent.tagHandler?.collapsesInnerWhiteSpace) return false;
445
- parent = parent.parent;
446
- }
447
- return true;
448
- }
449
- function listMarkerLineStart(buffer, fragmentIndex, markerIndex) {
450
- const marker = buffer[fragmentIndex].charCodeAt(markerIndex);
451
- const ordered = marker === 46 || marker === 41;
452
- if (!ordered && marker !== 45 && marker !== 42 && marker !== 43) return false;
453
- let digits = 0;
454
- let spaces = 0;
455
- let fragment = fragmentIndex;
456
- let cursor = markerIndex;
457
- for (;;) {
458
- if (cursor === 0) {
459
- if (--fragment < 0) return !ordered || digits > 0;
460
- cursor = buffer[fragment].length;
461
- continue;
462
- }
463
- const code = buffer[fragment].charCodeAt(--cursor);
464
- if (ordered && spaces === 0 && code >= 48 && code <= 57) {
465
- if (++digits > 9) return false;
466
- continue;
467
- }
468
- if (ordered && digits === 0) return false;
469
- if (code === 32) {
470
- if (++spaces > 3) return false;
471
- continue;
472
- }
473
- return code === 10;
474
- }
475
- }
476
- const MAX_ORDERED_START = 999999999;
477
- function orderedItemNumber(list, index) {
478
- const raw = list?.attributes?.start;
479
- if (raw === void 0) return index + 1;
480
- const start = parseUnsignedInteger(raw);
481
- if (start === void 0 || start > MAX_ORDERED_START) return Math.min(1 + index, MAX_ORDERED_START);
482
- return Math.min(start + index, MAX_ORDERED_START);
483
- }
484
- function numericReplacement(codePoint) {
485
- if (codePoint === 0 || codePoint > 1114111 || codePoint >= 55296 && codePoint <= 57343) return "�";
486
- if (codePoint >= 128 && codePoint <= 159) return C1_REPLACEMENTS[codePoint - 128];
487
- return String.fromCodePoint(codePoint);
488
- }
489
- function isCharacterReferenceTail(text, start) {
490
- let index = start;
491
- if (text.charCodeAt(index) === 35) {
492
- index++;
493
- const hex = text.charCodeAt(index) === 120 || text.charCodeAt(index) === 88;
494
- if (hex) index++;
495
- const digitStart = index;
496
- while (index < text.length) {
497
- const code = text.charCodeAt(index);
498
- if (!(code >= 48 && code <= 57) && !(hex && (code >= 65 && code <= 70 || code >= 97 && code <= 102))) break;
499
- index++;
500
- }
501
- return index > digitStart && text.charCodeAt(index) === 59;
502
- }
503
- const nameStart = index;
504
- while (index < text.length && isAsciiAlphaNumeric(text.charCodeAt(index))) index++;
505
- return index > nameStart && text.charCodeAt(index) === 59;
506
- }
507
- function decodedReference(replacement, text, next, protectDecodedEntityReferences) {
508
- return replacement === "&" && protectDecodedEntityReferences && isCharacterReferenceTail(text, next) ? "\\&" : replacement;
509
- }
510
- function decodeHTMLEntities(text, inAttribute = false, protectDecodedEntityReferences = false) {
511
- let result = "";
512
- let i = 0;
513
- const len = text.length;
514
- while (i < len) {
515
- if (text.charCodeAt(i) !== 38) {
516
- const plainStart = i;
517
- while (i < len && text.charCodeAt(i) !== 38) i++;
518
- result += text.slice(plainStart, i);
519
- continue;
520
- }
521
- if (i + 2 < len && text.charCodeAt(i + 1) === 35) {
522
- let end = i + 2;
523
- const isHex = text.charCodeAt(end) === 120 || text.charCodeAt(end) === 88;
524
- if (isHex) end++;
525
- const digitStart = end;
526
- let codePoint = 0;
527
- while (end < len) {
528
- const code = text.charCodeAt(end);
529
- let digit = -1;
530
- if (code >= 48 && code <= 57) digit = code - 48;
531
- else if (isHex && code >= 65 && code <= 70) digit = code - 55;
532
- else if (isHex && code >= 97 && code <= 102) digit = code - 87;
533
- if (digit < 0) break;
534
- codePoint = codePoint * (isHex ? 16 : 10) + digit;
535
- end++;
536
- }
537
- if (end > digitStart) {
538
- result += decodedReference(numericReplacement(codePoint), text, text.charCodeAt(end) === 59 ? end + 1 : end, protectDecodedEntityReferences);
539
- if (text.charCodeAt(end) === 59) end++;
540
- i = end;
541
- continue;
542
- }
543
- }
544
- const nameStart = i + 1;
545
- let nameEnd = nameStart;
546
- const scanEnd = Math.min(len, nameStart + 8);
547
- while (nameEnd < scanEnd && isAsciiAlphaNumeric(text.charCodeAt(nameEnd))) nameEnd++;
548
- if (nameEnd > nameStart && text.charCodeAt(nameEnd) === 59) {
549
- const name = text.slice(nameStart, nameEnd);
550
- const direct = HTML_ENTITIES[name];
551
- const replacement = typeof direct === "string" ? direct : HTML_ENTITIES[`$${name}`];
552
- if (replacement !== void 0) {
553
- result += decodedReference(replacement, text, nameEnd + 1, protectDecodedEntityReferences);
554
- i = nameEnd + 1;
555
- continue;
556
- }
557
- }
558
- let legacyEnd = Math.min(nameEnd, nameStart + 6);
559
- let decodedLegacy = false;
560
- while (legacyEnd > nameStart) {
561
- const name = text.slice(nameStart, legacyEnd);
562
- const replacement = HTML_ENTITIES[name];
563
- if (typeof replacement === "string") {
564
- const next = text.charCodeAt(legacyEnd);
565
- if (replacement !== void 0 && !(inAttribute && (next === 61 || isAsciiAlphaNumeric(next)))) {
566
- result += decodedReference(replacement, text, legacyEnd, protectDecodedEntityReferences);
567
- i = legacyEnd;
568
- decodedLegacy = true;
569
- }
570
- break;
571
- }
572
- legacyEnd--;
573
- }
574
- if (decodedLegacy) continue;
575
- result += "&";
576
- i++;
577
- }
578
- return result;
579
- }
580
- function isInlineNode(node) {
581
- const isInline = node.tagHandler?.isInline;
582
- return isInline === void 0 ? node.tagId === -1 : isInline;
583
- }
584
- function traverseUpToFirstBlockNode(node) {
585
- let firstBlockParent = node;
586
- const parentsToIncrement = [firstBlockParent];
587
- while (isInlineNode(firstBlockParent)) {
588
- if (!firstBlockParent.parent) break;
589
- firstBlockParent = firstBlockParent.parent;
590
- parentsToIncrement.push(firstBlockParent);
591
- }
592
- return parentsToIncrement;
593
- }
594
- function markRenderedChildContent(node) {
595
- let parent = node.parent;
596
- let anchorInScope = false;
597
- while (parent) {
598
- parent.childTextNodeIndex = (parent.childTextNodeIndex || 0) + 1;
599
- if (parent.tagId === 26) anchorInScope = true;
600
- if (!isInlineNode(parent)) break;
601
- parent = parent.parent;
602
- }
603
- if (anchorInScope) return;
604
- let anchorFound = false;
605
- while (parent?.parent) {
606
- parent = parent.parent;
607
- if (!anchorFound) {
608
- if (parent.tagId !== 26) continue;
609
- anchorFound = true;
610
- }
611
- parent.childTextNodeIndex = (parent.childTextNodeIndex || 0) + 1;
612
- if (!isInlineNode(parent)) return;
613
- }
614
- }
615
- const TRACKING_PARAM_RE = /^(?:utm_|fbclid|gclid|mc_eid|msclkid|oly_)/;
616
- const URL_SCHEME_RE = /^[A-Z][\dA-Z+.-]*:/i;
617
- const SLASH_CHAR$1 = 47;
618
- function stripTrackingParams(url) {
619
- const queryStart = url.indexOf("?");
620
- const fragmentStart = url.indexOf("#");
621
- if (queryStart === -1 || fragmentStart !== -1 && fragmentStart < queryStart) return url;
622
- const queryEnd = fragmentStart === -1 ? url.length : fragmentStart;
623
- const query = url.slice(queryStart + 1, queryEnd).split("&").filter((parameter) => !TRACKING_PARAM_RE.test(parameter)).join("&");
624
- return `${url.slice(0, queryStart)}${query ? `?${query}` : ""}${url.slice(queryEnd)}`;
625
- }
626
- function pathEnd(value, from) {
627
- const query = value.indexOf("?", from);
628
- const fragment = value.indexOf("#", from);
629
- if (query === -1) return fragment === -1 ? value.length : fragment;
630
- return fragment === -1 ? query : Math.min(query, fragment);
631
- }
632
- function hasDotSegment(path) {
633
- return path.includes(".") && (path === "." || path === ".." || path.startsWith("./") || path.startsWith("../") || path.includes("/./") || path.includes("/../") || path.endsWith("/.") || path.endsWith("/.."));
634
- }
635
- function mergeDotSegments(dir, rest) {
636
- let out = dir;
637
- let index = 0;
638
- for (;;) {
639
- let end = rest.indexOf("/", index);
640
- const last = end === -1;
641
- if (last) end = rest.length;
642
- const segment = rest.slice(index, end);
643
- if (segment === "..") out = out.slice(0, out.lastIndexOf("/", out.length - 2) + 1);
644
- else if (segment !== ".") out += last ? segment : `${segment}/`;
645
- if (last) return out;
646
- index = end + 1;
647
- }
648
- }
649
- let baseOrigin;
650
- let baseRoot = "";
651
- let basePath = "";
652
- let baseDir = "";
653
- function loadBase(origin) {
654
- if (origin !== baseOrigin) {
655
- baseOrigin = origin;
656
- baseRoot = "";
657
- const authority = origin.indexOf("://");
658
- if (authority !== -1) {
659
- const end = pathEnd(origin, authority + 3);
660
- const slash = origin.indexOf("/", authority + 3);
661
- const rootEnd = slash === -1 || slash > end ? end : slash;
662
- baseRoot = origin.slice(0, rootEnd);
663
- basePath = origin.slice(rootEnd, end);
664
- baseDir = basePath.slice(0, basePath.lastIndexOf("/") + 1) || "/";
665
- }
666
- }
667
- return baseRoot !== "";
668
- }
669
- function resolveAgainstBase(origin, url) {
670
- if (!loadBase(origin)) {
671
- let prefix = origin;
672
- while (prefix.endsWith("/")) prefix = prefix.slice(0, -1);
673
- const path = url.startsWith("./") ? url.slice(2) : url;
674
- return `${prefix}${path.charCodeAt(0) === SLASH_CHAR$1 ? "" : "/"}${path}`;
675
- }
676
- const end = pathEnd(url, 0);
677
- const path = url.slice(0, end);
678
- const suffix = end === url.length ? "" : url.slice(end);
679
- if (!path) return `${baseRoot}${basePath}${suffix}`;
680
- const dot = hasDotSegment(path);
681
- if (path.charCodeAt(0) === SLASH_CHAR$1) return `${baseRoot}${dot ? mergeDotSegments("/", path.slice(1)) : path}${suffix}`;
682
- return `${baseRoot}${dot ? mergeDotSegments(baseDir, path) : baseDir + path}${suffix}`;
683
- }
684
- function resolveUrl(url, origin, clean) {
685
- if (!url || url[0] === "#") return url;
686
- const isSlash = url.charCodeAt(0) === SLASH_CHAR$1;
687
- let resolved = url;
688
- if (isSlash && url.charCodeAt(1) === SLASH_CHAR$1) {
689
- let scheme = "https";
690
- if (origin && loadBase(origin)) scheme = baseRoot.slice(0, baseRoot.indexOf(":"));
691
- resolved = `${scheme}:${url}`;
692
- } else if (origin && (isSlash || !URL_SCHEME_RE.test(url))) resolved = resolveAgainstBase(origin, url);
693
- return (clean === true || !!clean && clean.urls === true) && resolved.includes("?") ? stripTrackingParams(resolved) : resolved;
694
- }
695
- function safeAnchorOutput(node, options, entering, protectMarkdown = false) {
696
- const href = node.attributes?.href;
697
- if (!href || !isSafeHtmlUrl(href)) return;
698
- const resolved = resolveUrl(href, options?.origin, options?.clean);
699
- if (!isSafeHtmlUrl(resolved)) return;
700
- if (!entering) return "</a>";
701
- return `<a href="${escapeHtml(resolved, true, protectMarkdown)}"${node.attributes?.title === void 0 ? "" : ` title="${escapeHtml(node.attributes.title, true, protectMarkdown)}"`}>`;
702
- }
703
- function serializeMarkdownDestination(destination) {
704
- if (!/[\t\n\f\r ()\\<>]/.test(destination)) return destination;
705
- return `<${/[\\<>]/.test(destination) ? destination.replace(/[\\<>]/g, "\\$&") : destination}>`;
706
- }
707
- function stripsEmptyLink(state, href) {
708
- const clean = state.options?.clean;
709
- if (!(clean === true || typeof clean === "object" && clean.emptyLinks)) return false;
710
- return isEmptyLinkHref(href);
711
- }
712
- function serializeMarkdownTitle(title) {
713
- return /[\\"]/.test(title) ? title.replace(/[\\"]/g, "\\$&") : title;
714
- }
715
- function serializeMarkdownResource(destination, title) {
716
- const serializedTitle = title ? ` "${serializeMarkdownTitle(title)}"` : "";
717
- return `(${serializeMarkdownDestination(destination)}${serializedTitle})`;
718
- }
719
- function serializeImageDescription(alt) {
720
- return /[\\[\]*_`~<&]/.test(alt) ? alt.replace(/[\\[\]*_`~<&]/g, "\\$&") : alt;
721
- }
722
- function isAutolinkUri(s) {
723
- if (!(s.startsWith("http://") || s.startsWith("https://") || s.startsWith("ftp://") || s.startsWith("mailto:"))) return false;
724
- for (let i = 0; i < s.length; i++) {
725
- const c = s.charCodeAt(i);
726
- if (c === 32 || c === 60 || c === 62 || c === 10 || c === 13 || c === 9) return false;
727
- }
728
- return true;
729
- }
730
- function renderBreak(node, state) {
731
- const depthMap = state.depthMap;
732
- if (isInsideTableCell(state) || isInsideRawHtmlBlock(depthMap) || isInsideHeading(depthMap)) return "<br>";
733
- if (depthMap[34] || depthMap[23]) return "\n";
734
- return ` \n${continuationPrefix(node, state.listIndentWidths || [], !state.bufferedBlockquoteDepth)}`;
735
- }
736
- const breakHandler = {
737
- enter: ({ node, state }) => renderBreak(node, state),
738
- isSelfClosing: true,
739
- spacing: NO_SPACING,
740
- collapsesInnerWhiteSpace: true,
741
- isInline: true
742
- };
743
- function escapeTrailingHeadingHashes(buffer) {
744
- let index = buffer.length - 1;
745
- while (index >= 0 && buffer[index] === "") index--;
746
- if (index < 0) return;
747
- const entry = buffer[index];
748
- let end = entry.length;
749
- while (end > 0 && (entry[end - 1] === " " || entry[end - 1] === " ")) end--;
750
- let run = end;
751
- while (run > 0 && entry[run - 1] === "#") run--;
752
- if (run === end) return;
753
- const previous = buffer[index - 1];
754
- const before = run > 0 ? entry[run - 1] : previous?.charAt(previous.length - 1);
755
- if (before !== " " && before !== " ") return;
756
- buffer[index] = `${entry.slice(0, run)}\\${entry.slice(run)}`;
757
- }
758
- const LINE_FRESH = -1;
759
- const LINE_OPEN = 0;
760
- const LINE_ROW = 1;
761
- const LINE_CONTENT = 2;
762
- function lineStateBeforeRow(buffer) {
763
- let fragment = buffer.length - 1;
764
- while (fragment >= 0 && buffer[fragment].length === 0) fragment--;
765
- if (fragment < 0) return LINE_OPEN;
766
- const tail = buffer[fragment];
767
- if (tail.charCodeAt(tail.length - 1) === 10) return LINE_FRESH;
768
- let firstNonSpace = -1;
769
- let markerFragment = -1;
770
- let markerIndex = -1;
771
- let cursor = tail.length;
772
- for (;;) {
773
- if (cursor === 0) {
774
- if (--fragment < 0) break;
775
- cursor = buffer[fragment].length;
776
- continue;
777
- }
778
- const code = buffer[fragment].charCodeAt(--cursor);
779
- if (code === 10) break;
780
- if (code !== 32 && code !== 9) {
781
- firstNonSpace = code;
782
- if (markerFragment < 0) {
783
- markerFragment = fragment;
784
- markerIndex = cursor;
785
- }
786
- }
787
- }
788
- if (firstNonSpace === -1) return LINE_OPEN;
789
- if (firstNonSpace === 124) return LINE_ROW;
790
- return listMarkerLineStart(buffer, markerFragment, markerIndex) ? LINE_OPEN : LINE_CONTENT;
791
- }
792
- function rowMarker(state) {
793
- const indent = state.listIndent;
794
- const lineState = lineStateBeforeRow(state.buffer);
795
- if (!indent) return lineState === LINE_ROW ? "\n| " : lineState === LINE_CONTENT ? "\n\n| " : "| ";
796
- switch (lineState) {
797
- case LINE_ROW: return `\n${indent}| `;
798
- case LINE_CONTENT: return `\n\n${indent}| `;
799
- case LINE_FRESH: return `${indent}| `;
800
- default: return "| ";
801
- }
802
- }
803
- const MAX_CELL_SPAN = 64;
804
- function cellEnter(node, state) {
805
- if (node.index === 0) return "";
806
- const header = state.tableHeaderCells || 0;
807
- return header > 0 && (state.tableCurrentRowCells || 0) >= header ? " " : " | ";
808
- }
809
- function cellExit(node, state) {
810
- const parsedSpan = parseUnsignedInteger(node.attributes?.colspan);
811
- const span = parsedSpan && parsedSpan < 256 ? Math.min(parsedSpan, MAX_CELL_SPAN) : 1;
812
- state.tableCurrentRowCells += span;
813
- return span > 1 ? " |".repeat(span - 1) : void 0;
814
- }
815
- function handleHeading(depth) {
816
- return {
817
- enter: ({ state }) => {
818
- if ((state.depthMap?.[26] || 0) > 0 || isInsideTableCell(state)) return `<h${depth}>`;
819
- return `${"#".repeat(depth)} `;
820
- },
821
- exit: ({ state }) => {
822
- if ((state.depthMap?.[26] || 0) > 0 || isInsideTableCell(state)) return `</h${depth}>`;
823
- escapeTrailingHeadingHashes(state.buffer);
824
- },
825
- collapsesInnerWhiteSpace: true
826
- };
827
- }
828
- const Strong = {
829
- enter: ({ state }) => {
830
- if ((state.depthMap?.[15] || 0) > 1) return "";
831
- return "**";
832
- },
833
- exit: ({ node, state }) => {
834
- if ((state.depthMap?.[15] || 0) + (node.tagId === 15 ? 1 : 0) > 1) return "";
835
- return "**";
836
- },
837
- collapsesInnerWhiteSpace: true,
838
- spacing: NO_SPACING,
839
- isInline: true
840
- };
841
- const Emphasis = {
842
- enter: ({ state }) => {
843
- if ((state.depthMap?.[17] || 0) > 1) return "";
844
- return "*";
845
- },
846
- exit: ({ node, state }) => {
847
- if ((state.depthMap?.[17] || 0) + (node.tagId === 17 ? 1 : 0) > 1) return "";
848
- return "*";
849
- },
850
- collapsesInnerWhiteSpace: true,
851
- spacing: NO_SPACING,
852
- isInline: true
853
- };
854
- const Strikethrough = {
855
- enter: () => "~~",
856
- exit: () => "~~",
857
- collapsesInnerWhiteSpace: true,
858
- spacing: NO_SPACING,
859
- isInline: true
860
- };
861
- const INERT_RAWTEXT = {
1
+ import { NO_SPACING, TagIdMap, isInsideRawHtmlBlock } from "./const.mjs";
2
+ import { decodeHTMLEntities, traverseUpToFirstBlockNode } from "./utils.mjs";
3
+ const selfClosing = { isSelfClosing: true };
4
+ const rawText = { isNonNesting: true };
5
+ const inertRawText = {
862
6
  isNonNesting: true,
863
- excludesTextNodes: true,
864
- spacing: NO_SPACING
7
+ excludesTextNodes: true
865
8
  };
866
- const tagHandlers = {
867
- [1]: {
868
- spacing: NO_SPACING,
869
- collapsesInnerWhiteSpace: true
870
- },
871
- [2]: {
872
- enter: () => "<details>",
873
- exit: ({ state }) => isInsideTableCell(state) ? "</details>" : "</details>\n\n"
874
- },
875
- [3]: {
876
- enter: () => "<summary>",
877
- exit: ({ state }) => isInsideTableCell(state) ? "</summary>" : "</summary>\n\n"
878
- },
879
- [4]: {
880
- excludesTextNodes: true,
881
- collapsesInnerWhiteSpace: true,
882
- isNonNesting: true,
883
- spacing: NO_SPACING
884
- },
885
- [52]: {
886
- excludesTextNodes: true,
887
- isNonNesting: true
888
- },
889
- [53]: {
890
- isNonNesting: true,
891
- excludesTextNodes: true
892
- },
893
- [5]: {
894
- collapsesInnerWhiteSpace: true,
895
- isSelfClosing: true,
896
- spacing: NO_SPACING
897
- },
898
- [6]: breakHandler,
899
- [7]: handleHeading(1),
900
- [8]: handleHeading(2),
901
- [9]: handleHeading(3),
902
- [10]: handleHeading(4),
903
- [11]: handleHeading(5),
904
- [12]: handleHeading(6),
905
- [13]: {
906
- enter: ({ node, state }) => {
907
- if (isInsideTableCell(state)) return "<hr>";
908
- if (!(state.depthMap?.[25] || state.bufferedBlockquoteDepth)) return "---";
909
- const prefix = continuationPrefix(node, state.listIndentWidths || [], !state.bufferedBlockquoteDepth);
910
- if (!prefix) return "---";
911
- if (state.depthMap?.[25]) state.listRulePending = prefix;
912
- const open = blockOpenPrefix(state.buffer, prefix);
913
- return open === void 0 ? "***" : `${open}---`;
914
- },
915
- isSelfClosing: true
916
- },
917
- [14]: Strong,
918
- [15]: Strong,
919
- [16]: Emphasis,
920
- [17]: Emphasis,
921
- [18]: Strikethrough,
922
- [110]: Strikethrough,
923
- [111]: Strikethrough,
924
- [19]: {
925
- enter: () => "<sub>",
926
- exit: () => "</sub>",
927
- collapsesInnerWhiteSpace: true,
928
- spacing: NO_SPACING,
929
- isInline: true
930
- },
931
- [20]: {
932
- enter: () => "<sup>",
933
- exit: () => "</sup>",
934
- collapsesInnerWhiteSpace: true,
935
- spacing: NO_SPACING,
936
- isInline: true
937
- },
938
- [21]: {
939
- enter: () => "<ins>",
940
- exit: () => "</ins>",
941
- collapsesInnerWhiteSpace: true,
942
- spacing: NO_SPACING,
943
- isInline: true
944
- },
945
- [22]: {
946
- enter: ({ state }) => {
947
- return {
948
- _tag: "BlockquoteEnter",
949
- output: (state.depthMap?.[25] || 0) > 0 ? "\n" : void 0
950
- };
951
- },
952
- exit: () => ({ _tag: "BlockquoteExit" }),
953
- spacing: BLOCKQUOTE_SPACING
954
- },
955
- [34]: {
956
- enter: ({ node, state }) => {
957
- if (isInsideTableCell(state)) return "<pre>";
958
- return {
959
- _tag: "PreEnter",
960
- language: getLanguageFromClass(node.attributes?.class)
961
- };
962
- },
963
- exit: ({ state }) => {
964
- if (isInsideTableCell(state)) return "</pre>";
965
- return { _tag: "PreExit" };
966
- }
967
- },
968
- [23]: {
969
- enter: ({ node, state }) => {
970
- if ((state.depthMap?.[34] || 0) > 0) {
971
- if (isInsideTableCell(state)) return "<code>";
972
- if (state.preFenceOpen) return;
973
- const language = getLanguageFromClass(node.attributes?.class);
974
- if ((state.depthMap?.[25] || 0) > 0) {
975
- const indent = state.listIndent;
976
- return {
977
- _tag: "CodeFenceEnter",
978
- language,
979
- output: `${blockOpenPrefix(state.buffer, indent) ?? ""}\`\`\`${language}\n`
980
- };
981
- }
982
- return {
983
- _tag: "CodeFenceEnter",
984
- language,
985
- output: `\`\`\`${language}\n`
986
- };
987
- }
988
- if (isInsideRawHtmlBlock(state.depthMap)) return "<code>";
989
- if ((state.depthMap?.[25] || 0) > 0) {
990
- const lastEntry = state.buffer.at(-1);
991
- const lastChar = lastEntry?.charAt(lastEntry.length - 1) || "";
992
- if (lastChar && lastChar !== " " && lastChar !== "\n" && lastChar !== " " && lastChar !== "*" && lastChar !== "_" && lastChar !== "~" && lastChar !== "[" && lastChar !== ">") return {
993
- _tag: "CodeSpanEnter",
994
- output: ` \``
995
- };
996
- }
997
- return {
998
- _tag: "CodeSpanEnter",
999
- output: "`"
1000
- };
1001
- },
1002
- exit: ({ state }) => {
1003
- if ((state.depthMap?.[34] || 0) > 0) {
1004
- if (isInsideTableCell(state)) return "</code>";
1005
- return;
1006
- }
1007
- if (isInsideRawHtmlBlock(state.depthMap)) return "</code>";
1008
- return { _tag: "CodeSpanExit" };
1009
- },
1010
- collapsesInnerWhiteSpace: true,
1011
- spacing: NO_SPACING,
1012
- isInline: true
1013
- },
1014
- [24]: {
1015
- enter: ({ state }) => isInsideTableCell(state) ? "<ul>" : void 0,
1016
- exit: ({ state }) => isInsideTableCell(state) ? "</ul>" : void 0
1017
- },
1018
- [33]: {
1019
- enter: ({ state }) => isInsideTableCell(state) ? "<ol>" : void 0,
1020
- exit: ({ state }) => isInsideTableCell(state) ? "</ol>" : void 0
1021
- },
1022
- [25]: {
1023
- enter: ({ node, state }) => {
1024
- if (isInsideTableCell(state)) return "<li>";
1025
- const marker = node.parent?.tagId === 33 ? `${orderedItemNumber(node.parent, node.index)}. ` : "- ";
1026
- return `${state.listIndent}${marker}`;
1027
- },
1028
- exit: ({ state }) => isInsideTableCell(state) ? "</li>" : void 0,
1029
- spacing: LIST_ITEM_SPACING
1030
- },
1031
- [26]: {
1032
- enter: ({ node, state }) => {
1033
- if (node.attributes?.href !== void 0) {
1034
- if (stripsEmptyLink(state, node.attributes.href)) return;
1035
- if (isInsideRawHtmlBlock(state.depthMap)) return safeAnchorOutput(node, state.options, true, true);
1036
- return "[";
1037
- }
1038
- },
1039
- exit: ({ node, state }) => {
1040
- if (node.attributes?.href === void 0) return "";
1041
- if (stripsEmptyLink(state, node.attributes.href)) return "";
1042
- if (isInsideRawHtmlBlock(state.depthMap) && !node.tagHandler?.literalEnter) return safeAnchorOutput(node, state.options, false, true);
1043
- const href = resolveUrl(node.attributes.href, state.options?.origin, state.options?.clean);
1044
- let title = node.attributes?.title;
1045
- if (state.lastContentCache === title) title = "";
1046
- if (!title && isAutolinkUri(href)) {
1047
- const buf = state.buffer;
1048
- let i = buf.length - 1;
1049
- let textLen = 0;
1050
- let captionBracket = -1;
1051
- let captionTextLen = 0;
1052
- while (i >= 0) {
1053
- const entry = buf[i];
1054
- if (entry === "[") break;
1055
- if (captionBracket < 0 && state.depthMap?.[106] && entry.endsWith("*[")) {
1056
- captionBracket = i;
1057
- captionTextLen = textLen;
1058
- }
1059
- textLen += entry.length;
1060
- i--;
1061
- }
1062
- const captionLink = i < 0 && captionBracket >= 0;
1063
- if (captionLink) {
1064
- i = captionBracket;
1065
- textLen = captionTextLen;
1066
- }
1067
- if (i >= 0 && textLen === href.length && buf.slice(i + 1).join("") === href) {
1068
- if (captionLink) buf[i] = buf[i].slice(0, -1);
1069
- buf.length = i + (captionLink ? 1 : 0);
1070
- const auto = `<${href}>`;
1071
- buf.push(auto);
1072
- state.lastContentCache = auto;
1073
- return "";
1074
- }
1075
- }
1076
- return `]${serializeMarkdownResource(href, title)}`;
1077
- },
1078
- collapsesInnerWhiteSpace: true,
1079
- spacing: NO_SPACING,
1080
- isInline: true
1081
- },
1082
- [27]: {
1083
- enter: ({ node, state }) => {
1084
- const alt = node.attributes?.alt || "";
1085
- const rawSrc = node.attributes?.src || "";
1086
- const src = isDataUrl(rawSrc) ? "" : resolveUrl(rawSrc, state.options?.origin, state.options?.clean);
1087
- const clean = state.options?.clean;
1088
- if ((clean === true || clean !== void 0 && clean !== false && clean.emptyImages === true) && !alt.trim()) {
1089
- if (state.depthMap?.[106]) return void 0;
1090
- } else markRenderedChildContent(node);
1091
- return `![${serializeImageDescription(alt)}]${serializeMarkdownResource(src, node.attributes?.title)}`;
1092
- },
1093
- collapsesInnerWhiteSpace: true,
1094
- isSelfClosing: true,
1095
- spacing: NO_SPACING,
1096
- isInline: true
1097
- },
1098
- [28]: {
1099
- enter: ({ state }) => {
1100
- if (isInsideTableCell(state)) return "<table>";
1101
- if ((state.depthMap?.[28] || 0) <= 1) state.tableRenderedTable = false;
1102
- state.tableColumnAlignments = [];
1103
- state.tableHeaderCells = 0;
1104
- },
1105
- exit: ({ state }) => isInsideTableCell(state) ? "</table>" : void 0
1106
- },
1107
- [107]: { enter: ({ state }) => {
1108
- if ((state.depthMap?.[25] || 0) === 0 || isInsideTableCell(state)) return void 0;
1109
- return blockOpenPrefix(state.buffer, state.listIndent);
1110
- } },
1111
- [29]: {
1112
- enter: ({ state }) => {
1113
- if (isInsideTableCell(state)) return "<thead>";
1114
- },
1115
- exit: ({ state }) => isInsideTableCell(state) ? "</thead>" : void 0,
1116
- spacing: TABLE_ROW_SPACING,
1117
- excludesTextNodes: true
1118
- },
1119
- [30]: {
1120
- enter: ({ state }) => {
1121
- if (isInsideTableCell(state)) return "<tr>";
1122
- state.tableCurrentRowCells = 0;
1123
- return rowMarker(state);
1124
- },
1125
- exit: ({ state }) => {
1126
- if (isInsideTableCell(state) || (state.depthMap?.[28] || 0) > 1) return "</tr>";
1127
- if (!state.tableRenderedTable) {
1128
- state.tableRenderedTable = true;
1129
- const alignments = state.tableColumnAlignments;
1130
- while (alignments.length < state.tableCurrentRowCells) alignments.push("");
1131
- const alignmentMarkers = alignments.map((align) => {
1132
- switch (align) {
1133
- case "left": return ":---";
1134
- case "center": return ":---:";
1135
- case "right": return "---:";
1136
- default: return "---";
1137
- }
1138
- });
1139
- state.tableHeaderCells = alignments.length;
1140
- return ` |\n${(state.depthMap?.[25] || 0) > 0 ? state.listIndent : ""}| ${alignmentMarkers.join(" | ")} |`;
1141
- }
1142
- return " |";
1143
- },
1144
- excludesTextNodes: true,
1145
- spacing: TABLE_ROW_SPACING
1146
- },
1147
- [31]: {
1148
- enter: ({ node, state }) => {
1149
- if ((state.depthMap?.[28] || 0) > 1) return "<th>";
1150
- const align = node.attributes?.align?.toLowerCase();
1151
- if (align) state.tableColumnAlignments.push(align);
1152
- else if (state.tableColumnAlignments.length <= state.tableCurrentRowCells) state.tableColumnAlignments.push("");
1153
- return cellEnter(node, state);
1154
- },
1155
- exit: ({ node, state }) => {
1156
- if ((state.depthMap?.[28] || 0) > 1) return "</th>";
1157
- return cellExit(node, state);
1158
- },
1159
- collapsesInnerWhiteSpace: true,
1160
- spacing: NO_SPACING
1161
- },
1162
- [32]: {
1163
- enter: ({ node, state }) => {
1164
- if ((state.depthMap?.[28] || 0) > 1) return "<td>";
1165
- return cellEnter(node, state);
1166
- },
1167
- exit: ({ node, state }) => {
1168
- if ((state.depthMap?.[28] || 0) > 1) return "</td>";
1169
- return cellExit(node, state);
1170
- },
1171
- collapsesInnerWhiteSpace: true,
1172
- spacing: NO_SPACING
1173
- },
1174
- [35]: { enter: ({ state }) => {
1175
- if ((state.depthMap?.[25] || 0) > 0 && !isInsideTableCell(state)) {
1176
- const lastEntry = state.buffer.at(-1);
1177
- const lastChar = lastEntry?.charAt(lastEntry.length - 1) || "";
1178
- if (lastChar && lastChar !== " " && lastChar !== "\n") return `\n\n${state.listIndent}`;
1179
- }
1180
- } },
1181
- [36]: {},
1182
- [37]: {
1183
- collapsesInnerWhiteSpace: true,
1184
- spacing: NO_SPACING,
1185
- isInline: true
1186
- },
1187
- [41]: {},
1188
- [42]: {
1189
- collapsesInnerWhiteSpace: true,
1190
- spacing: NO_SPACING,
1191
- isInline: true
1192
- },
1193
- [43]: {
1194
- collapsesInnerWhiteSpace: true,
1195
- spacing: NO_SPACING,
1196
- isInline: true
1197
- },
1198
- [44]: { spacing: NO_SPACING },
1199
- [45]: {
1200
- enter: ({ state }) => {
1201
- if ((state.depthMap?.[28] || 0) > 1) return "<center>";
1202
- },
1203
- exit: ({ state }) => {
1204
- if ((state.depthMap?.[28] || 0) > 1) return "</center>";
1205
- },
1206
- spacing: NO_SPACING
1207
- },
1208
- [38]: {
1209
- spacing: NO_SPACING,
1210
- excludesTextNodes: true
1211
- },
1212
- [39]: {
1213
- spacing: TABLE_ROW_SPACING,
1214
- excludesTextNodes: true
1215
- },
1216
- [46]: {
1217
- enter: () => "`",
1218
- exit: () => "`",
1219
- collapsesInnerWhiteSpace: true,
1220
- spacing: NO_SPACING,
1221
- isInline: true
1222
- },
1223
- [47]: { spacing: NO_SPACING },
1224
- [40]: { spacing: NO_SPACING },
1225
- [54]: {
1226
- isSelfClosing: true,
1227
- spacing: NO_SPACING,
1228
- collapsesInnerWhiteSpace: true,
1229
- isInline: true
1230
- },
1231
- [55]: {
1232
- isSelfClosing: true,
1233
- spacing: NO_SPACING,
1234
- isInline: true,
1235
- collapsesInnerWhiteSpace: true
1236
- },
1237
- [56]: {
1238
- isSelfClosing: true,
1239
- spacing: NO_SPACING,
1240
- isInline: true,
1241
- collapsesInnerWhiteSpace: true
1242
- },
1243
- [57]: {
1244
- isSelfClosing: true,
1245
- spacing: NO_SPACING
1246
- },
1247
- [58]: {
1248
- isSelfClosing: true,
1249
- spacing: NO_SPACING
1250
- },
1251
- [59]: {
1252
- isSelfClosing: true,
1253
- spacing: NO_SPACING,
1254
- isInline: true,
1255
- collapsesInnerWhiteSpace: true
1256
- },
1257
- [60]: {
1258
- isSelfClosing: true,
1259
- spacing: NO_SPACING,
1260
- isInline: true,
1261
- collapsesInnerWhiteSpace: true
1262
- },
1263
- [61]: {
1264
- isSelfClosing: true,
1265
- spacing: NO_SPACING
1266
- },
1267
- [62]: {
1268
- isSelfClosing: true,
1269
- spacing: NO_SPACING
1270
- },
1271
- [63]: {
1272
- isSelfClosing: true,
1273
- spacing: NO_SPACING
1274
- },
1275
- [64]: {
1276
- isSelfClosing: true,
1277
- spacing: NO_SPACING,
1278
- isInline: true,
1279
- collapsesInnerWhiteSpace: true
1280
- },
1281
- [49]: { spacing: NO_SPACING },
1282
- [65]: { spacing: NO_SPACING },
1283
- [66]: {
1284
- isNonNesting: true,
1285
- spacing: NO_SPACING
1286
- },
1287
- [67]: { spacing: NO_SPACING },
1288
- [109]: { spacing: NO_SPACING },
1289
- [68]: { spacing: NO_SPACING },
1290
- [69]: { spacing: NO_SPACING },
1291
- [70]: { spacing: NO_SPACING },
1292
- [71]: { spacing: NO_SPACING },
1293
- [72]: { spacing: NO_SPACING },
1294
- [73]: { ...INERT_RAWTEXT },
1295
- [74]: { spacing: NO_SPACING },
1296
- [75]: { spacing: NO_SPACING },
1297
- [76]: { spacing: NO_SPACING },
1298
- [77]: { spacing: NO_SPACING },
1299
- [78]: {
1300
- excludesTextNodes: true,
1301
- spacing: NO_SPACING
1302
- },
1303
- [79]: {
1304
- enter: () => "",
1305
- exit: () => "",
1306
- collapsesInnerWhiteSpace: true,
1307
- spacing: NO_SPACING,
1308
- isInline: true
1309
- },
1310
- [80]: {
1311
- enter: () => "<mark>",
1312
- exit: () => "</mark>",
1313
- collapsesInnerWhiteSpace: true,
1314
- spacing: NO_SPACING,
1315
- isInline: true
1316
- },
1317
- [81]: {
1318
- enter: () => "\"",
1319
- exit: () => "\"",
1320
- collapsesInnerWhiteSpace: true,
1321
- spacing: NO_SPACING,
1322
- isInline: true
1323
- },
1324
- [82]: {
1325
- enter: () => "`",
1326
- exit: () => "`",
1327
- collapsesInnerWhiteSpace: true,
1328
- spacing: NO_SPACING,
1329
- isInline: true
1330
- },
1331
- [83]: {
1332
- enter: () => "",
1333
- exit: () => "",
1334
- collapsesInnerWhiteSpace: true,
1335
- spacing: NO_SPACING,
1336
- isInline: true
1337
- },
1338
- [84]: { ...INERT_RAWTEXT },
1339
- [112]: { ...INERT_RAWTEXT },
1340
- [108]: {
1341
- isNonNesting: true,
1342
- excludesTextNodes: true,
1343
- spacing: NO_SPACING
1344
- },
1345
- [85]: { ...INERT_RAWTEXT },
1346
- [86]: {
1347
- isNonNesting: true,
1348
- spacing: NO_SPACING
1349
- },
1350
- [87]: {
1351
- isNonNesting: true,
1352
- spacing: NO_SPACING
1353
- },
1354
- [88]: { spacing: NO_SPACING },
1355
- [89]: {
1356
- enter: () => {
1357
- return "<u>";
1358
- },
1359
- exit: () => {
1360
- return "</u>";
1361
- },
1362
- collapsesInnerWhiteSpace: true,
1363
- spacing: NO_SPACING,
1364
- isInline: true
1365
- },
1366
- [90]: {
1367
- enter: () => "*",
1368
- exit: () => "*",
1369
- collapsesInnerWhiteSpace: true,
1370
- spacing: NO_SPACING,
1371
- isInline: true
1372
- },
1373
- [91]: {
1374
- enter: () => "**",
1375
- exit: () => "**",
1376
- collapsesInnerWhiteSpace: true,
1377
- spacing: NO_SPACING,
1378
- isInline: true
1379
- },
1380
- [92]: {
1381
- enter: () => "`",
1382
- exit: () => "`",
1383
- collapsesInnerWhiteSpace: true,
1384
- spacing: NO_SPACING,
1385
- isInline: true
1386
- },
1387
- [93]: {
1388
- enter: () => "",
1389
- exit: () => "",
1390
- collapsesInnerWhiteSpace: true,
1391
- spacing: NO_SPACING,
1392
- isInline: true
1393
- },
1394
- [94]: {
1395
- enter: () => "",
1396
- exit: () => "",
1397
- collapsesInnerWhiteSpace: true,
1398
- spacing: NO_SPACING,
1399
- isInline: true
1400
- },
1401
- [95]: {
1402
- enter: () => "",
1403
- exit: () => "",
1404
- collapsesInnerWhiteSpace: true,
1405
- spacing: NO_SPACING,
1406
- isInline: true
1407
- },
1408
- [96]: {
1409
- enter: () => "",
1410
- exit: () => "",
1411
- collapsesInnerWhiteSpace: true,
1412
- spacing: NO_SPACING,
1413
- isInline: true
1414
- },
1415
- [97]: {
1416
- enter: () => "",
1417
- exit: () => "",
1418
- collapsesInnerWhiteSpace: true,
1419
- spacing: NO_SPACING,
1420
- isInline: true
1421
- },
1422
- [100]: {
1423
- enter: () => "<address>",
1424
- exit: () => "</address>",
1425
- spacing: NO_SPACING,
1426
- collapsesInnerWhiteSpace: true
1427
- },
1428
- [101]: {
1429
- spacing: NO_SPACING,
1430
- enter: () => "<dl>",
1431
- exit: () => "</dl>"
1432
- },
1433
- [99]: {
1434
- enter: () => "<dt>",
1435
- exit: () => "</dt>",
1436
- collapsesInnerWhiteSpace: true,
1437
- spacing: [0, 1]
1438
- },
1439
- [98]: {
1440
- enter: () => "<dd>",
1441
- exit: () => "</dd>",
1442
- spacing: [0, 1]
1443
- },
1444
- [50]: {},
1445
- [51]: {},
1446
- [105]: {},
1447
- [104]: {},
1448
- [102]: {},
1449
- [106]: {
1450
- exit: () => "*",
1451
- collapsesInnerWhiteSpace: true,
1452
- isInline: true
1453
- }
9
+ const parserTagHandlers = {
10
+ [4]: inertRawText,
11
+ [52]: inertRawText,
12
+ [53]: inertRawText,
13
+ [5]: selfClosing,
14
+ [6]: selfClosing,
15
+ [13]: selfClosing,
16
+ [27]: selfClosing,
17
+ [29]: { excludesTextNodes: true },
18
+ [30]: { excludesTextNodes: true },
19
+ [38]: { excludesTextNodes: true },
20
+ [39]: { excludesTextNodes: true },
21
+ [54]: selfClosing,
22
+ [55]: selfClosing,
23
+ [56]: selfClosing,
24
+ [57]: selfClosing,
25
+ [58]: selfClosing,
26
+ [59]: selfClosing,
27
+ [60]: selfClosing,
28
+ [61]: selfClosing,
29
+ [62]: selfClosing,
30
+ [63]: selfClosing,
31
+ [64]: selfClosing,
32
+ [66]: rawText,
33
+ [73]: inertRawText,
34
+ [78]: { excludesTextNodes: true },
35
+ [84]: inertRawText,
36
+ [112]: inertRawText,
37
+ [108]: inertRawText,
38
+ [85]: inertRawText,
39
+ [86]: rawText,
40
+ [87]: rawText
1454
41
  };
1455
- function buildTagOverrideHandlers(overrides) {
1456
- const result = /* @__PURE__ */ new Map();
1457
- for (const tagName in overrides) {
1458
- const override = overrides[tagName];
1459
- if (!override) continue;
1460
- if (typeof override === "string") {
1461
- const targetId = TagIdMap[override];
1462
- if (targetId !== void 0) {
1463
- const baseHandler = tagHandlers[targetId];
1464
- if (baseHandler) result.set(tagName, {
1465
- ...baseHandler,
1466
- aliasTagId: targetId
1467
- });
1468
- }
1469
- } else {
1470
- const baseId = TagIdMap[tagName];
1471
- const baseHandler = baseId !== void 0 ? tagHandlers[baseId] : void 0;
1472
- const handler = baseHandler ? { ...baseHandler } : {};
1473
- if (override.enter !== void 0) {
1474
- const enterStr = override.enter;
1475
- handler.enter = () => enterStr;
1476
- handler.literalEnter = true;
1477
- }
1478
- if (override.exit !== void 0) {
1479
- const exitStr = override.exit;
1480
- handler.exit = () => exitStr;
1481
- handler.literalExit = true;
1482
- }
1483
- if (override.spacing !== void 0) handler.spacing = override.spacing;
1484
- if (override.isInline !== void 0) handler.isInline = override.isInline;
1485
- if (override.isSelfClosing !== void 0) handler.isSelfClosing = override.isSelfClosing;
1486
- if (override.collapsesInnerWhiteSpace !== void 0) handler.collapsesInnerWhiteSpace = override.collapsesInnerWhiteSpace;
1487
- result.set(tagName, handler);
1488
- }
1489
- }
1490
- return result;
1491
- }
1492
42
  const UNKNOWN_TAG_HANDLER = {
1493
43
  isInline: true,
1494
44
  spacing: NO_SPACING
@@ -1520,7 +70,7 @@ function isAsciiAlpha(code) {
1520
70
  }
1521
71
  function shouldProtectDecodedEntityReferences(state) {
1522
72
  const depthMap = state.depthMap;
1523
- return !state.plainText && !depthMap[34] && !depthMap[23] && !isInsideRawHtmlBlock(depthMap);
73
+ return !state.plainText && !depthMap[4] && !depthMap[34] && !depthMap[23] && !isInsideRawHtmlBlock(depthMap);
1524
74
  }
1525
75
  const SCRIPT_DATA = 0;
1526
76
  const SCRIPT_DATA_ESCAPED = 1;
@@ -1800,10 +350,17 @@ function finalizeParse(leftover, state, handleEvent) {
1800
350
  const scriptText = takeScriptText(state);
1801
351
  if (scriptText) processTextBuffer(scriptText, state, handleEvent);
1802
352
  } else if (leftover.length > 0) {
1803
- const incompleteTagIndex = findIncompleteTagResidualIndex(leftover);
1804
- const text = incompleteTagIndex === -1 ? leftover : leftover.slice(0, incompleteTagIndex);
353
+ const trailing = state.trailingText || "";
354
+ let text = trailing;
355
+ if (state.currentNode?.tagHandler?.isNonNesting) {
356
+ if (state.rawtextEndTagPending) text = "";
357
+ } else {
358
+ const incompleteTagIndex = findIncompleteTagResidualIndex(trailing);
359
+ if (incompleteTagIndex !== -1) text = trailing.slice(0, incompleteTagIndex);
360
+ }
1805
361
  if (text) processTextBuffer(text, state, handleEvent);
1806
362
  }
363
+ state.trailingText = void 0;
1807
364
  while (state.currentNode) closeNode(state.currentNode, state, handleEvent);
1808
365
  }
1809
366
  const EMPTY_ATTRIBUTES = Object.freeze({});
@@ -1917,7 +474,7 @@ function findScriptEndTag(html, start, parseState) {
1917
474
  return scriptScanResult(parseState, state, SCRIPT_SCAN_COMPLETE);
1918
475
  }
1919
476
  function pushScriptTextChunk(state, text) {
1920
- if (!text) return;
477
+ if (!text || state.discardExcludedText && state.currentNode?.tagHandler?.excludesTextNodes) return;
1921
478
  (state.scriptTextChunks ??= []).push(text);
1922
479
  state.textBufferContainsNonWhitespace = true;
1923
480
  state.lastCharWasWhitespace = false;
@@ -1925,6 +482,7 @@ function pushScriptTextChunk(state, text) {
1925
482
  }
1926
483
  function scanScriptChunk(html, start, state) {
1927
484
  const result = findScriptEndTag(html, start, state);
485
+ if (state.discardExcludedText && state.currentNode?.tagHandler?.excludesTextNodes) return result;
1928
486
  if (result === SCRIPT_SCAN_COMPLETE) pushScriptTextChunk(state, html.substring(start));
1929
487
  else if (result <= SCRIPT_SEQUENCE_INCOMPLETE) pushScriptTextChunk(state, html.substring(start, -result - 2));
1930
488
  else pushScriptTextChunk(state, html.substring(start, result));
@@ -1958,7 +516,8 @@ function parseHtml(html, options = {}) {
1958
516
  const state = {
1959
517
  depthMap: /* @__PURE__ */ new Uint16Array(113),
1960
518
  depth: 0,
1961
- resolvedPlugins: options.resolvedPlugins || []
519
+ resolvedPlugins: options.resolvedPlugins || [],
520
+ tagHandlers: options.tagHandlers
1962
521
  };
1963
522
  let remainingHtml = parseHtmlInternal(html, state, (event) => {
1964
523
  events.push(event);
@@ -1975,12 +534,14 @@ function parseHtmlStream(html, state, onEvent) {
1975
534
  function parseHtmlInternal(htmlChunk, state, handleEvent) {
1976
535
  let textBuffer = "";
1977
536
  let runStart = 0;
537
+ let declarationPending = false;
1978
538
  state.depthMap ??= /* @__PURE__ */ new Uint16Array(113);
1979
539
  state.depth ??= 0;
1980
540
  state.lastCharWasWhitespace ??= true;
1981
541
  state.justClosedTag ??= false;
1982
542
  state.isFirstTextInElement ??= false;
1983
543
  state.scriptDataState ??= SCRIPT_DATA;
544
+ state.rawtextEndTagPending = false;
1984
545
  let i = 0;
1985
546
  const chunkLength = htmlChunk.length;
1986
547
  if (state.currentNode && isScriptElement(state.currentNode)) {
@@ -2004,15 +565,26 @@ function parseHtmlInternal(htmlChunk, state, handleEvent) {
2004
565
  i++;
2005
566
  continue;
2006
567
  }
2007
- if (inPreTag) textBuffer += htmlChunk[i];
2008
- else if (currentCharCode === SPACE_CHAR || !state.lastCharWasWhitespace) textBuffer += " ";
568
+ if (inPreTag) {
569
+ const whitespaceStart = i;
570
+ while (i + 1 < chunkLength && isWhitespace(htmlChunk.charCodeAt(i + 1))) i++;
571
+ textBuffer += htmlChunk.substring(whitespaceStart, i + 1);
572
+ } else if (currentCharCode === SPACE_CHAR || !state.lastCharWasWhitespace) textBuffer += " ";
2009
573
  state.lastCharWasWhitespace = true;
2010
574
  state.textBufferContainsWhitespace = true;
2011
575
  } else {
2012
576
  state.textBufferContainsNonWhitespace = true;
2013
577
  state.lastCharWasWhitespace = false;
2014
578
  state.justClosedTag = false;
2015
- textBuffer += htmlChunk[i];
579
+ const textStart = i++;
580
+ while (i < chunkLength) {
581
+ const code = htmlChunk.charCodeAt(i);
582
+ if (code === LT_CHAR || isWhitespace(code)) break;
583
+ if (code === AMPERSAND_CHAR) state.hasEncodedHtmlEntity = true;
584
+ i++;
585
+ }
586
+ textBuffer += htmlChunk.substring(textStart, i);
587
+ continue;
2016
588
  }
2017
589
  i++;
2018
590
  continue;
@@ -2044,10 +616,20 @@ function parseHtmlInternal(htmlChunk, state, handleEvent) {
2044
616
  }
2045
617
  }
2046
618
  if (nextCharCode === EXCLAMATION_CHAR) {
619
+ const handler = state.currentNode?.tagHandler;
620
+ const visibleRawText = state.flattenedRawTagName !== void 0 ? !state.flattenedRawExcludesText : handler?.isNonNesting && !handler.excludesTextNodes;
621
+ const discardDeclaration = state.discardExcludedText && !visibleRawText;
2047
622
  if (htmlChunk.charCodeAt(i + 2) === OPEN_BRACKET_CHAR) {
2048
623
  if (htmlChunk.startsWith("<![CDATA[", i)) {
2049
624
  const end = htmlChunk.indexOf("]]>", i + 9);
2050
625
  if (end === -1) {
626
+ if (discardDeclaration && !state.tagOverrideHandlers?.has("#cdata-section")) {
627
+ if (textBuffer.length > 0) processTextBuffer(textBuffer, state, handleEvent);
628
+ const boundary = `<![CDATA[${htmlChunk.slice(-2)}`;
629
+ state.trailingText = boundary;
630
+ return boundary;
631
+ }
632
+ declarationPending = true;
2051
633
  textBuffer += htmlChunk.substring(i);
2052
634
  break;
2053
635
  }
@@ -2062,6 +644,7 @@ function parseHtmlInternal(htmlChunk, state, handleEvent) {
2062
644
  continue;
2063
645
  }
2064
646
  if (chunkLength - i < 9 && "<![CDATA[".startsWith(htmlChunk.substring(i))) {
647
+ declarationPending = true;
2065
648
  textBuffer += htmlChunk.substring(i);
2066
649
  break;
2067
650
  }
@@ -2076,6 +659,12 @@ function parseHtmlInternal(htmlChunk, state, handleEvent) {
2076
659
  i = result.newPosition;
2077
660
  runStart = i;
2078
661
  } else {
662
+ declarationPending = true;
663
+ if (discardDeclaration && htmlChunk.length - i >= 4) {
664
+ const boundary = htmlChunk.charCodeAt(i + 2) === DASH_CHAR && htmlChunk.charCodeAt(i + 3) === DASH_CHAR ? result.remainingText.length <= 7 ? result.remainingText : `<!--x${result.remainingText.slice(-3)}` : "<!x";
665
+ state.trailingText = boundary;
666
+ return boundary;
667
+ }
2079
668
  textBuffer += result.remainingText;
2080
669
  break;
2081
670
  }
@@ -2087,6 +676,12 @@ function parseHtmlInternal(htmlChunk, state, handleEvent) {
2087
676
  if (c === GT_CHAR || c === SLASH_CHAR || isWhitespace(c)) break;
2088
677
  peekEnd++;
2089
678
  }
679
+ if (peekEnd === chunkLength) {
680
+ state.textBufferContainsNonWhitespace = true;
681
+ state.lastCharWasWhitespace = false;
682
+ textBuffer += htmlChunk.substring(i);
683
+ break;
684
+ }
2090
685
  const peekTagName = normalizeTagName(htmlChunk.substring(i + 2, peekEnd));
2091
686
  const peekHandler = state.tagOverrideHandlers?.get(peekTagName);
2092
687
  const peekTagId = effectiveTagId(peekTagName, TagIdMap[peekTagName] ?? -1, state);
@@ -2105,6 +700,7 @@ function parseHtmlInternal(htmlChunk, state, handleEvent) {
2105
700
  i = result.newPosition;
2106
701
  runStart = i;
2107
702
  } else {
703
+ state.rawtextEndTagPending = state.flattenedRawTagName !== void 0 || !!state.currentNode?.tagHandler?.isNonNesting;
2108
704
  textBuffer += result.remainingText;
2109
705
  break;
2110
706
  }
@@ -2180,8 +776,35 @@ function parseHtmlInternal(htmlChunk, state, handleEvent) {
2180
776
  }
2181
777
  }
2182
778
  }
2183
- const remainingHtml = textBuffer.length > 0 ? htmlChunk.substring(runStart) : "";
779
+ let remainingHtml = textBuffer.length > 0 ? htmlChunk.substring(runStart) : "";
780
+ if (state.discardExcludedText && (state.flattenedRawExcludesText || state.currentNode?.tagHandler?.isNonNesting && state.currentNode.tagHandler.excludesTextNodes) && remainingHtml && !declarationPending && !(state.currentNode && isScriptElement(state.currentNode))) {
781
+ const boundary = state.rawtextEndTagPending ? 0 : remainingHtml.lastIndexOf("<");
782
+ const tagName = state.flattenedRawTagName || state.currentNode.name;
783
+ let keepBoundary = boundary >= 0 && remainingHtml.charCodeAt(boundary + 1) === SLASH_CHAR;
784
+ if (boundary === remainingHtml.length - 1) keepBoundary = true;
785
+ else if (keepBoundary && !state.rawtextEndTagPending) {
786
+ const available = remainingHtml.length - boundary - 2;
787
+ const nameLength = Math.min(available, tagName.length);
788
+ for (let offset = 0; offset < nameLength; offset++) {
789
+ const code = remainingHtml.charCodeAt(boundary + 2 + offset);
790
+ if ((code >= 65 && code <= 90 ? code + 32 : code) !== tagName.charCodeAt(offset)) {
791
+ keepBoundary = false;
792
+ break;
793
+ }
794
+ }
795
+ if (available > tagName.length) {
796
+ const delimiter = remainingHtml.charCodeAt(boundary + 2 + tagName.length);
797
+ keepBoundary = keepBoundary && (delimiter === GT_CHAR || delimiter === SLASH_CHAR || isWhitespace(delimiter));
798
+ }
799
+ }
800
+ remainingHtml = keepBoundary ? remainingHtml.substring(boundary) : "";
801
+ textBuffer = remainingHtml;
802
+ state.textBufferContainsWhitespace = false;
803
+ state.textBufferContainsNonWhitespace = false;
804
+ state.hasEncodedHtmlEntity = false;
805
+ }
2184
806
  if (remainingHtml.length > 0 && isWhitespace(remainingHtml.charCodeAt(0))) state.lastCharWasWhitespace = false;
807
+ state.trailingText = textBuffer;
2185
808
  return remainingHtml;
2186
809
  }
2187
810
  function processTextBuffer(textBuffer, state, handleEvent) {
@@ -2205,6 +828,9 @@ function processTextBuffer(textBuffer, state, handleEvent) {
2205
828
  containsWhitespace,
2206
829
  excludedFromMarkdown: false
2207
830
  };
831
+ if (state.endTagClosedNothing) rootTextNode.joinsPrevious = true;
832
+ if (containsWhitespace) rootTextNode.trimsAtLineStart = true;
833
+ state.endTagClosedNothing = false;
2208
834
  handleEvent({
2209
835
  type: 0,
2210
836
  node: rootTextNode
@@ -2219,7 +845,9 @@ function processTextBuffer(textBuffer, state, handleEvent) {
2219
845
  if (text.length === 0) return;
2220
846
  const parentsToIncrement = traverseUpToFirstBlockNode(state.currentNode);
2221
847
  const firstBlockParent = parentsToIncrement.at(-1);
2222
- if (containsWhitespace && !firstBlockParent?.childTextNodeIndex) {
848
+ const firstInBlock = containsWhitespace && !firstBlockParent.childTextNodeIndex;
849
+ const inlineAtRoot = firstInBlock && !firstBlockParent.parent && (firstBlockParent.tagHandler?.isInline ?? firstBlockParent.tagId === -1);
850
+ if (firstInBlock && !inlineAtRoot) {
2223
851
  let start = 0;
2224
852
  while (start < text.length && (inPreTag ? text.charCodeAt(start) === NEWLINE_CHAR || text.charCodeAt(start) === CARRIAGE_RETURN_CHAR : isWhitespace(text.charCodeAt(start)))) start++;
2225
853
  if (start > 0) text = text.substring(start);
@@ -2237,6 +865,9 @@ function processTextBuffer(textBuffer, state, handleEvent) {
2237
865
  containsWhitespace,
2238
866
  excludedFromMarkdown: excludesTextNodes
2239
867
  };
868
+ if (state.endTagClosedNothing) textNode.joinsPrevious = true;
869
+ if (inlineAtRoot) textNode.trimsAtLineStart = true;
870
+ state.endTagClosedNothing = false;
2240
871
  for (const parent of parentsToIncrement) parent.childTextNodeIndex = (parent.childTextNodeIndex || 0) + 1;
2241
872
  handleEvent({
2242
873
  type: 0,
@@ -2370,7 +1001,7 @@ function processClosingTag(htmlChunk, position, state, handleEvent) {
2370
1001
  if (curr) {
2371
1002
  while (state.currentNode && state.currentNode !== curr) closeNode(state.currentNode, state, handleEvent);
2372
1003
  closeNode(curr, state, handleEvent);
2373
- }
1004
+ } else state.endTagClosedNothing = true;
2374
1005
  state.justClosedTag = true;
2375
1006
  return {
2376
1007
  complete: true,
@@ -2400,6 +1031,7 @@ function closeNode(node, state, handleEvent) {
2400
1031
  const tagId = node.tagId;
2401
1032
  if (tagId !== void 0 && tagId >= 0 && tagId < 113) state.depthMap[tagId] = Math.max(0, (state.depthMap[tagId] || 0) - 1);
2402
1033
  state.depth--;
1034
+ state.endTagClosedNothing = false;
2403
1035
  handleEvent({
2404
1036
  type: 1,
2405
1037
  node
@@ -2520,7 +1152,7 @@ function processCdataSection(content, state, handleEvent) {
2520
1152
  function processOpeningTag(tagName, tagId, htmlChunk, i, state, handleEvent) {
2521
1153
  tagId = effectiveTagId(tagName, tagId, state);
2522
1154
  if (state.currentNode?.tagHandler?.isNonNesting) closeNode(state.currentNode, state, handleEvent);
2523
- const tagHandler = state.tagOverrideHandlers?.get(tagName) ?? (tagId === -1 ? UNKNOWN_TAG_HANDLER : tagHandlers[tagId]);
1155
+ const tagHandler = state.tagOverrideHandlers?.get(tagName) ?? (tagId === -1 ? UNKNOWN_TAG_HANDLER : state.tagHandlers?.[tagId] ?? parserTagHandlers[tagId]);
2524
1156
  const result = scanTagAttributes(htmlChunk, i, tagHandler);
2525
1157
  if (result._tag === "incomplete") return {
2526
1158
  complete: false,
@@ -2624,6 +1256,7 @@ function processOpeningTag(tagName, tagId, htmlChunk, i, state, handleEvent) {
2624
1256
  const tag = new ParsedElementNode(tagName, result.attributes, state.currentNode, state.depth, currentWalkIndex, tagId, tagHandler);
2625
1257
  if (tagId === 78 || state.currentNode?.excludedFromMarkdown) tag.excludedFromMarkdown = true;
2626
1258
  state.lastTextNode = tag;
1259
+ state.endTagClosedNothing = false;
2627
1260
  handleEvent({
2628
1261
  type: 0,
2629
1262
  node: tag
@@ -2753,4 +1386,4 @@ function parseAttributes(attrStr) {
2753
1386
  if (result._tag === "incomplete") throw new Error("Isolated attribute scans always complete at EOF");
2754
1387
  return result.attributes === EMPTY_ATTRIBUTES ? {} : result.attributes;
2755
1388
  }
2756
- export { blockOpenPrefix, breakHandler, buildTagOverrideHandlers, continuationPrefix, escapeHtml, figcaptionOwnsBlockSpacing, finalizeParse, getLanguageFromClass, isCharacterReferenceTail, isDataUrl, isEmptyLinkHref, isInsideHeading, isInsideTableCell, isSafeHtmlUrl, lastOutputChar, listMarkerLineStart, markRenderedChildContent, orderedItemNumber, parseAttributes, parseHtml, parseHtmlStream, parseUnsignedInteger, renderBreak, resolveUrl, safeAnchorOutput };
1389
+ export { finalizeParse, parseAttributes, parseHtml, parseHtmlStream, parserTagHandlers };