@mdream/js 1.7.2 → 2.0.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 (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 -827
  7. package/dist/_chunks/minimal.mjs +29 -0
  8. package/dist/_chunks/output-runner.mjs +54 -0
  9. package/dist/_chunks/parse.mjs +136 -1490
  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 -122
  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 -34
  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 -27
  30. package/dist/splitter.d.mts +12 -4
  31. package/dist/splitter.mjs +355 -113
  32. package/dist/text.d.mts +6 -0
  33. package/dist/text.mjs +2 -0
  34. package/package.json +33 -7
  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,1485 +1,48 @@
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 isEmptyLinkHref(href) {
278
- let start = 0;
279
- while (start < href.length && href.charCodeAt(start) <= 32) start++;
280
- let end = href.length;
281
- while (end > start && href.charCodeAt(end - 1) <= 32) end--;
282
- switch (lowerAscii(href.charCodeAt(start))) {
283
- case 35: return end - start === 1;
284
- case 106: return schemeMatches(href, start, end, "javascript:");
285
- case 100: return schemeMatches(href, start, end, "data:");
286
- case 118: return schemeMatches(href, start, end, "vbscript:");
287
- default: return false;
288
- }
289
- }
290
- function isSafeHtmlUrl(href, image = false) {
291
- let start = 0;
292
- while (start < href.length && href.charCodeAt(start) <= 32) start++;
293
- let end = href.length;
294
- while (end > start && href.charCodeAt(end - 1) <= 32) end--;
295
- if (start === end) return false;
296
- for (let index = start; index < end; index++) {
297
- const code = href.charCodeAt(index);
298
- if (code === 9 || code === 10 || code === 13) continue;
299
- if (code === 58) switch (lowerAscii(href.charCodeAt(start))) {
300
- case 104: return schemeMatches(href, start, end, "http:") || schemeMatches(href, start, end, "https:");
301
- case 109: return !image && schemeMatches(href, start, end, "mailto:");
302
- case 116: return !image && schemeMatches(href, start, end, "tel:");
303
- case 102: return !image && schemeMatches(href, start, end, "ftp:");
304
- default: return false;
305
- }
306
- if (code === 47 || code === 63 || code === 35) return true;
307
- const lower = lowerAscii(code);
308
- if (!(lower >= 97 && lower <= 122 || code >= 48 && code <= 57 || code === 43 || code === 45 || code === 46)) return true;
309
- }
310
- return true;
311
- }
312
- function escapeHtml(value, attribute = false, protectMarkdown = false) {
313
- let escaped = "";
314
- let copiedUntil = 0;
315
- for (let index = 0; index < value.length; index++) {
316
- const code = value.charCodeAt(index);
317
- let replacement;
318
- if (code === 38) replacement = "&amp;";
319
- else if (code === 60) replacement = "&lt;";
320
- else if (code === 62) replacement = "&gt;";
321
- else if (attribute && code === 34) replacement = "&quot;";
322
- else if (protectMarkdown && code === 91) replacement = "&#91;";
323
- else if (protectMarkdown && code === 93) replacement = "&#93;";
324
- if (replacement !== void 0) {
325
- escaped += value.slice(copiedUntil, index) + replacement;
326
- copiedUntil = index + 1;
327
- }
328
- }
329
- return copiedUntil === 0 ? value : escaped + value.slice(copiedUntil);
330
- }
331
- function continuationPrefix(node, listIndentWidths, includeBlockquotes = true) {
332
- const chain = [];
333
- let current = node.parent;
334
- while (current) {
335
- chain.push(current);
336
- current = current.parent;
337
- }
338
- let prefix = "";
339
- let listIndex = 0;
340
- for (let i = chain.length - 1; i >= 0; i--) {
341
- const tagId = chain[i].tagId;
342
- if (tagId === 22 && includeBlockquotes) prefix += "> ";
343
- else if (tagId === 25) {
344
- prefix += " ".repeat(listIndentWidths[listIndex] ?? 2);
345
- listIndex++;
346
- }
347
- }
348
- return prefix;
349
- }
350
- const C1_REPLACEMENTS = "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ";
351
- function isAsciiAlphaNumeric(code) {
352
- return code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122;
353
- }
354
- function isHtmlAsciiWhitespace(code) {
355
- return code === 32 || code === 9 || code === 10 || code === 12 || code === 13;
356
- }
357
- const LANGUAGE_PREFIX = [
358
- 108,
359
- 97,
360
- 110,
361
- 103,
362
- 117,
363
- 97,
364
- 103,
365
- 101,
366
- 45
367
- ];
368
- function hasLanguagePrefix(value, start) {
369
- for (let offset = 0; offset < 9; offset++) if (value.charCodeAt(start + offset) !== LANGUAGE_PREFIX[offset]) return false;
370
- return true;
371
- }
372
- function isUnsafeFenceInfoCode(code) {
373
- if (code < 32 || code === 127) return true;
374
- return code === 34 || code === 39 || code === 38 || code === 60 || code === 62 || code === 96 || code === 126;
375
- }
376
- function getLanguageFromClass(className) {
377
- if (!className) return "";
378
- const length = className.length;
379
- let index = 0;
380
- while (index < length) {
381
- if (isHtmlAsciiWhitespace(className.charCodeAt(index))) {
382
- index++;
383
- continue;
384
- }
385
- const tokenStart = index;
386
- do
387
- index++;
388
- while (index < length && !isHtmlAsciiWhitespace(className.charCodeAt(index)));
389
- const tokenEnd = index;
390
- const languageStart = tokenStart + 9;
391
- if (languageStart >= tokenEnd || !hasLanguagePrefix(className, tokenStart)) continue;
392
- let valid = true;
393
- for (let cursor = languageStart; cursor < tokenEnd; cursor++) if (isUnsafeFenceInfoCode(className.charCodeAt(cursor))) {
394
- valid = false;
395
- break;
396
- }
397
- if (valid) return className.slice(languageStart, tokenEnd);
398
- }
399
- return "";
400
- }
401
- function parseUnsignedInteger(raw) {
402
- if (raw === void 0 || !/^[\t\n\f\r ]*\+?\d+[\t\n\f\r ]*$/.test(raw)) return void 0;
403
- const value = Number(raw);
404
- return value <= 4294967295 ? value : void 0;
405
- }
406
- function lastOutputChar(buffer, end = buffer.length) {
407
- for (let index = end - 1; index >= 0; index--) {
408
- const fragment = buffer[index];
409
- if (fragment.length > 0) return fragment.charCodeAt(fragment.length - 1);
410
- }
411
- return -1;
412
- }
413
- function blockOpenPrefix(buffer, prefix, end = buffer.length) {
414
- switch (lastOutputChar(buffer, end)) {
415
- case -1: return;
416
- case 32: {
417
- let fragment = end - 1;
418
- let index = buffer[fragment].length;
419
- for (;;) {
420
- if (index === 0) {
421
- if (--fragment < 0) return void 0;
422
- index = buffer[fragment].length;
423
- continue;
424
- }
425
- const code = buffer[fragment].charCodeAt(--index);
426
- if (code !== 32) return code === 10 || listMarkerLineStart(buffer, fragment, index) ? void 0 : `\n\n${prefix ?? ""}`;
427
- }
428
- }
429
- case 10: return prefix || void 0;
430
- default: return `\n\n${prefix ?? ""}`;
431
- }
432
- }
433
- function figcaptionOwnsBlockSpacing(node, plainText) {
434
- let parent = node.parent;
435
- while (parent) {
436
- if (parent.tagId === 32 || parent.tagId === 31) return false;
437
- if (!plainText && parent.tagId !== 37 && parent.tagHandler?.collapsesInnerWhiteSpace) return false;
438
- parent = parent.parent;
439
- }
440
- return true;
441
- }
442
- function listMarkerLineStart(buffer, fragmentIndex, markerIndex) {
443
- const marker = buffer[fragmentIndex].charCodeAt(markerIndex);
444
- const ordered = marker === 46 || marker === 41;
445
- if (!ordered && marker !== 45 && marker !== 42 && marker !== 43) return false;
446
- let digits = 0;
447
- let spaces = 0;
448
- let fragment = fragmentIndex;
449
- let cursor = markerIndex;
450
- for (;;) {
451
- if (cursor === 0) {
452
- if (--fragment < 0) return !ordered || digits > 0;
453
- cursor = buffer[fragment].length;
454
- continue;
455
- }
456
- const code = buffer[fragment].charCodeAt(--cursor);
457
- if (ordered && spaces === 0 && code >= 48 && code <= 57) {
458
- if (++digits > 9) return false;
459
- continue;
460
- }
461
- if (ordered && digits === 0) return false;
462
- if (code === 32) {
463
- if (++spaces > 3) return false;
464
- continue;
465
- }
466
- return code === 10;
467
- }
468
- }
469
- const MAX_ORDERED_START = 999999999;
470
- function orderedItemNumber(list, index) {
471
- const raw = list?.attributes?.start;
472
- if (raw === void 0) return index + 1;
473
- const start = parseUnsignedInteger(raw);
474
- if (start === void 0 || start > MAX_ORDERED_START) return Math.min(1 + index, MAX_ORDERED_START);
475
- return Math.min(start + index, MAX_ORDERED_START);
476
- }
477
- function numericReplacement(codePoint) {
478
- if (codePoint === 0 || codePoint > 1114111 || codePoint >= 55296 && codePoint <= 57343) return "�";
479
- if (codePoint >= 128 && codePoint <= 159) return C1_REPLACEMENTS[codePoint - 128];
480
- return String.fromCodePoint(codePoint);
481
- }
482
- function isCharacterReferenceTail(text, start) {
483
- let index = start;
484
- if (text.charCodeAt(index) === 35) {
485
- index++;
486
- const hex = text.charCodeAt(index) === 120 || text.charCodeAt(index) === 88;
487
- if (hex) index++;
488
- const digitStart = index;
489
- while (index < text.length) {
490
- const code = text.charCodeAt(index);
491
- if (!(code >= 48 && code <= 57) && !(hex && (code >= 65 && code <= 70 || code >= 97 && code <= 102))) break;
492
- index++;
493
- }
494
- return index > digitStart && text.charCodeAt(index) === 59;
495
- }
496
- const nameStart = index;
497
- while (index < text.length && isAsciiAlphaNumeric(text.charCodeAt(index))) index++;
498
- return index > nameStart && text.charCodeAt(index) === 59;
499
- }
500
- function decodedReference(replacement, text, next, protectDecodedEntityReferences) {
501
- return replacement === "&" && protectDecodedEntityReferences && isCharacterReferenceTail(text, next) ? "\\&" : replacement;
502
- }
503
- function decodeHTMLEntities(text, inAttribute = false, protectDecodedEntityReferences = false) {
504
- let result = "";
505
- let i = 0;
506
- const len = text.length;
507
- while (i < len) {
508
- if (text.charCodeAt(i) !== 38) {
509
- const plainStart = i;
510
- while (i < len && text.charCodeAt(i) !== 38) i++;
511
- result += text.slice(plainStart, i);
512
- continue;
513
- }
514
- if (i + 2 < len && text.charCodeAt(i + 1) === 35) {
515
- let end = i + 2;
516
- const isHex = text.charCodeAt(end) === 120 || text.charCodeAt(end) === 88;
517
- if (isHex) end++;
518
- const digitStart = end;
519
- let codePoint = 0;
520
- while (end < len) {
521
- const code = text.charCodeAt(end);
522
- let digit = -1;
523
- if (code >= 48 && code <= 57) digit = code - 48;
524
- else if (isHex && code >= 65 && code <= 70) digit = code - 55;
525
- else if (isHex && code >= 97 && code <= 102) digit = code - 87;
526
- if (digit < 0) break;
527
- codePoint = codePoint * (isHex ? 16 : 10) + digit;
528
- end++;
529
- }
530
- if (end > digitStart) {
531
- result += decodedReference(numericReplacement(codePoint), text, text.charCodeAt(end) === 59 ? end + 1 : end, protectDecodedEntityReferences);
532
- if (text.charCodeAt(end) === 59) end++;
533
- i = end;
534
- continue;
535
- }
536
- }
537
- const nameStart = i + 1;
538
- let nameEnd = nameStart;
539
- const scanEnd = Math.min(len, nameStart + 8);
540
- while (nameEnd < scanEnd && isAsciiAlphaNumeric(text.charCodeAt(nameEnd))) nameEnd++;
541
- if (nameEnd > nameStart && text.charCodeAt(nameEnd) === 59) {
542
- const name = text.slice(nameStart, nameEnd);
543
- const direct = HTML_ENTITIES[name];
544
- const replacement = typeof direct === "string" ? direct : HTML_ENTITIES[`$${name}`];
545
- if (replacement !== void 0) {
546
- result += decodedReference(replacement, text, nameEnd + 1, protectDecodedEntityReferences);
547
- i = nameEnd + 1;
548
- continue;
549
- }
550
- }
551
- let legacyEnd = Math.min(nameEnd, nameStart + 6);
552
- let decodedLegacy = false;
553
- while (legacyEnd > nameStart) {
554
- const name = text.slice(nameStart, legacyEnd);
555
- const replacement = HTML_ENTITIES[name];
556
- if (typeof replacement === "string") {
557
- const next = text.charCodeAt(legacyEnd);
558
- if (replacement !== void 0 && !(inAttribute && (next === 61 || isAsciiAlphaNumeric(next)))) {
559
- result += decodedReference(replacement, text, legacyEnd, protectDecodedEntityReferences);
560
- i = legacyEnd;
561
- decodedLegacy = true;
562
- }
563
- break;
564
- }
565
- legacyEnd--;
566
- }
567
- if (decodedLegacy) continue;
568
- result += "&";
569
- i++;
570
- }
571
- return result;
572
- }
573
- function isInlineNode(node) {
574
- const isInline = node.tagHandler?.isInline;
575
- return isInline === void 0 ? node.tagId === -1 : isInline;
576
- }
577
- function traverseUpToFirstBlockNode(node) {
578
- let firstBlockParent = node;
579
- const parentsToIncrement = [firstBlockParent];
580
- while (isInlineNode(firstBlockParent)) {
581
- if (!firstBlockParent.parent) break;
582
- firstBlockParent = firstBlockParent.parent;
583
- parentsToIncrement.push(firstBlockParent);
584
- }
585
- return parentsToIncrement;
586
- }
587
- function markRenderedChildContent(node) {
588
- let parent = node.parent;
589
- let anchorInScope = false;
590
- while (parent) {
591
- parent.childTextNodeIndex = (parent.childTextNodeIndex || 0) + 1;
592
- if (parent.tagId === 26) anchorInScope = true;
593
- if (!isInlineNode(parent)) break;
594
- parent = parent.parent;
595
- }
596
- if (anchorInScope) return;
597
- let anchorFound = false;
598
- while (parent?.parent) {
599
- parent = parent.parent;
600
- if (!anchorFound) {
601
- if (parent.tagId !== 26) continue;
602
- anchorFound = true;
603
- }
604
- parent.childTextNodeIndex = (parent.childTextNodeIndex || 0) + 1;
605
- if (!isInlineNode(parent)) return;
606
- }
607
- }
608
- const TRACKING_PARAM_RE = /^(?:utm_|fbclid|gclid|mc_eid|msclkid|oly_)/;
609
- const URL_SCHEME_RE = /^[A-Z][\dA-Z+.-]*:/i;
610
- const SLASH_CHAR$1 = 47;
611
- function stripTrackingParams(url) {
612
- const queryStart = url.indexOf("?");
613
- const fragmentStart = url.indexOf("#");
614
- if (queryStart === -1 || fragmentStart !== -1 && fragmentStart < queryStart) return url;
615
- const queryEnd = fragmentStart === -1 ? url.length : fragmentStart;
616
- const query = url.slice(queryStart + 1, queryEnd).split("&").filter((parameter) => !TRACKING_PARAM_RE.test(parameter)).join("&");
617
- return `${url.slice(0, queryStart)}${query ? `?${query}` : ""}${url.slice(queryEnd)}`;
618
- }
619
- function pathEnd(value, from) {
620
- const query = value.indexOf("?", from);
621
- const fragment = value.indexOf("#", from);
622
- if (query === -1) return fragment === -1 ? value.length : fragment;
623
- return fragment === -1 ? query : Math.min(query, fragment);
624
- }
625
- function hasDotSegment(path) {
626
- return path.includes(".") && (path === "." || path === ".." || path.startsWith("./") || path.startsWith("../") || path.includes("/./") || path.includes("/../") || path.endsWith("/.") || path.endsWith("/.."));
627
- }
628
- function mergeDotSegments(dir, rest) {
629
- let out = dir;
630
- let index = 0;
631
- for (;;) {
632
- let end = rest.indexOf("/", index);
633
- const last = end === -1;
634
- if (last) end = rest.length;
635
- const segment = rest.slice(index, end);
636
- if (segment === "..") out = out.slice(0, out.lastIndexOf("/", out.length - 2) + 1);
637
- else if (segment !== ".") out += last ? segment : `${segment}/`;
638
- if (last) return out;
639
- index = end + 1;
640
- }
641
- }
642
- let baseOrigin;
643
- let baseRoot = "";
644
- let basePath = "";
645
- let baseDir = "";
646
- function loadBase(origin) {
647
- if (origin !== baseOrigin) {
648
- baseOrigin = origin;
649
- baseRoot = "";
650
- const authority = origin.indexOf("://");
651
- if (authority !== -1) {
652
- const end = pathEnd(origin, authority + 3);
653
- const slash = origin.indexOf("/", authority + 3);
654
- const rootEnd = slash === -1 || slash > end ? end : slash;
655
- baseRoot = origin.slice(0, rootEnd);
656
- basePath = origin.slice(rootEnd, end);
657
- baseDir = basePath.slice(0, basePath.lastIndexOf("/") + 1) || "/";
658
- }
659
- }
660
- return baseRoot !== "";
661
- }
662
- function resolveAgainstBase(origin, url) {
663
- if (!loadBase(origin)) {
664
- let prefix = origin;
665
- while (prefix.endsWith("/")) prefix = prefix.slice(0, -1);
666
- const path = url.startsWith("./") ? url.slice(2) : url;
667
- return `${prefix}${path.charCodeAt(0) === SLASH_CHAR$1 ? "" : "/"}${path}`;
668
- }
669
- const end = pathEnd(url, 0);
670
- const path = url.slice(0, end);
671
- const suffix = end === url.length ? "" : url.slice(end);
672
- if (!path) return `${baseRoot}${basePath}${suffix}`;
673
- const dot = hasDotSegment(path);
674
- if (path.charCodeAt(0) === SLASH_CHAR$1) return `${baseRoot}${dot ? mergeDotSegments("/", path.slice(1)) : path}${suffix}`;
675
- return `${baseRoot}${dot ? mergeDotSegments(baseDir, path) : baseDir + path}${suffix}`;
676
- }
677
- function resolveUrl(url, origin, clean) {
678
- if (!url || url[0] === "#") return url;
679
- const isSlash = url.charCodeAt(0) === SLASH_CHAR$1;
680
- let resolved = url;
681
- if (isSlash && url.charCodeAt(1) === SLASH_CHAR$1) {
682
- let scheme = "https";
683
- if (origin && loadBase(origin)) scheme = baseRoot.slice(0, baseRoot.indexOf(":"));
684
- resolved = `${scheme}:${url}`;
685
- } else if (origin && (isSlash || !URL_SCHEME_RE.test(url))) resolved = resolveAgainstBase(origin, url);
686
- return (clean === true || !!clean && clean.urls === true) && resolved.includes("?") ? stripTrackingParams(resolved) : resolved;
687
- }
688
- function safeAnchorOutput(node, options, entering, protectMarkdown = false) {
689
- const href = node.attributes?.href;
690
- if (!href || !isSafeHtmlUrl(href)) return;
691
- const resolved = resolveUrl(href, options?.origin, options?.clean);
692
- if (!isSafeHtmlUrl(resolved)) return;
693
- if (!entering) return "</a>";
694
- return `<a href="${escapeHtml(resolved, true, protectMarkdown)}"${node.attributes?.title === void 0 ? "" : ` title="${escapeHtml(node.attributes.title, true, protectMarkdown)}"`}>`;
695
- }
696
- function serializeMarkdownDestination(destination) {
697
- if (!/[\t\n\f\r ()\\<>]/.test(destination)) return destination;
698
- return `<${/[\\<>]/.test(destination) ? destination.replace(/[\\<>]/g, "\\$&") : destination}>`;
699
- }
700
- function stripsEmptyLink(state, href) {
701
- const clean = state.options?.clean;
702
- if (!(clean === true || typeof clean === "object" && clean.emptyLinks)) return false;
703
- return isEmptyLinkHref(href);
704
- }
705
- function serializeMarkdownTitle(title) {
706
- return /[\\"]/.test(title) ? title.replace(/[\\"]/g, "\\$&") : title;
707
- }
708
- function serializeMarkdownResource(destination, title) {
709
- const serializedTitle = title ? ` "${serializeMarkdownTitle(title)}"` : "";
710
- return `(${serializeMarkdownDestination(destination)}${serializedTitle})`;
711
- }
712
- function serializeImageDescription(alt) {
713
- return /[\\[\]*_`~<&]/.test(alt) ? alt.replace(/[\\[\]*_`~<&]/g, "\\$&") : alt;
714
- }
715
- function isAutolinkUri(s) {
716
- if (!(s.startsWith("http://") || s.startsWith("https://") || s.startsWith("ftp://") || s.startsWith("mailto:"))) return false;
717
- for (let i = 0; i < s.length; i++) {
718
- const c = s.charCodeAt(i);
719
- if (c === 32 || c === 60 || c === 62 || c === 10 || c === 13 || c === 9) return false;
720
- }
721
- return true;
722
- }
723
- function renderBreak(node, state) {
724
- const depthMap = state.depthMap;
725
- if (isInsideTableCell(state) || isInsideRawHtmlBlock(depthMap) || isInsideHeading(depthMap)) return "<br>";
726
- if (depthMap[34] || depthMap[23]) return "\n";
727
- return ` \n${continuationPrefix(node, state.listIndentWidths || [], !state.bufferedBlockquoteDepth)}`;
728
- }
729
- const breakHandler = {
730
- enter: ({ node, state }) => renderBreak(node, state),
731
- isSelfClosing: true,
732
- spacing: NO_SPACING,
733
- collapsesInnerWhiteSpace: true,
734
- isInline: true
735
- };
736
- function escapeTrailingHeadingHashes(buffer) {
737
- let index = buffer.length - 1;
738
- while (index >= 0 && buffer[index] === "") index--;
739
- if (index < 0) return;
740
- const entry = buffer[index];
741
- let end = entry.length;
742
- while (end > 0 && (entry[end - 1] === " " || entry[end - 1] === " ")) end--;
743
- let run = end;
744
- while (run > 0 && entry[run - 1] === "#") run--;
745
- if (run === end) return;
746
- const previous = buffer[index - 1];
747
- const before = run > 0 ? entry[run - 1] : previous?.charAt(previous.length - 1);
748
- if (before !== " " && before !== " ") return;
749
- buffer[index] = `${entry.slice(0, run)}\\${entry.slice(run)}`;
750
- }
751
- const LINE_FRESH = -1;
752
- const LINE_OPEN = 0;
753
- const LINE_ROW = 1;
754
- const LINE_CONTENT = 2;
755
- function lineStateBeforeRow(buffer) {
756
- let fragment = buffer.length - 1;
757
- while (fragment >= 0 && buffer[fragment].length === 0) fragment--;
758
- if (fragment < 0) return LINE_OPEN;
759
- const tail = buffer[fragment];
760
- if (tail.charCodeAt(tail.length - 1) === 10) return LINE_FRESH;
761
- let firstNonSpace = -1;
762
- let markerFragment = -1;
763
- let markerIndex = -1;
764
- let cursor = tail.length;
765
- for (;;) {
766
- if (cursor === 0) {
767
- if (--fragment < 0) break;
768
- cursor = buffer[fragment].length;
769
- continue;
770
- }
771
- const code = buffer[fragment].charCodeAt(--cursor);
772
- if (code === 10) break;
773
- if (code !== 32 && code !== 9) {
774
- firstNonSpace = code;
775
- if (markerFragment < 0) {
776
- markerFragment = fragment;
777
- markerIndex = cursor;
778
- }
779
- }
780
- }
781
- if (firstNonSpace === -1) return LINE_OPEN;
782
- if (firstNonSpace === 124) return LINE_ROW;
783
- return listMarkerLineStart(buffer, markerFragment, markerIndex) ? LINE_OPEN : LINE_CONTENT;
784
- }
785
- function rowMarker(state) {
786
- const indent = state.listIndent;
787
- const lineState = lineStateBeforeRow(state.buffer);
788
- if (!indent) return lineState === LINE_ROW ? "\n| " : lineState === LINE_CONTENT ? "\n\n| " : "| ";
789
- switch (lineState) {
790
- case LINE_ROW: return `\n${indent}| `;
791
- case LINE_CONTENT: return `\n\n${indent}| `;
792
- case LINE_FRESH: return `${indent}| `;
793
- default: return "| ";
794
- }
795
- }
796
- const MAX_CELL_SPAN = 64;
797
- function cellEnter(node, state) {
798
- if (node.index === 0) return "";
799
- const header = state.tableHeaderCells || 0;
800
- return header > 0 && (state.tableCurrentRowCells || 0) >= header ? " " : " | ";
801
- }
802
- function cellExit(node, state) {
803
- const parsedSpan = parseUnsignedInteger(node.attributes?.colspan);
804
- const span = parsedSpan && parsedSpan < 256 ? Math.min(parsedSpan, MAX_CELL_SPAN) : 1;
805
- state.tableCurrentRowCells += span;
806
- return span > 1 ? " |".repeat(span - 1) : void 0;
807
- }
808
- function handleHeading(depth) {
809
- return {
810
- enter: ({ state }) => {
811
- if ((state.depthMap?.[26] || 0) > 0 || isInsideTableCell(state)) return `<h${depth}>`;
812
- return `${"#".repeat(depth)} `;
813
- },
814
- exit: ({ state }) => {
815
- if ((state.depthMap?.[26] || 0) > 0 || isInsideTableCell(state)) return `</h${depth}>`;
816
- escapeTrailingHeadingHashes(state.buffer);
817
- },
818
- collapsesInnerWhiteSpace: true
819
- };
820
- }
821
- const Strong = {
822
- enter: ({ state }) => {
823
- if ((state.depthMap?.[15] || 0) > 1) return "";
824
- return "**";
825
- },
826
- exit: ({ node, state }) => {
827
- if ((state.depthMap?.[15] || 0) + (node.tagId === 15 ? 1 : 0) > 1) return "";
828
- return "**";
829
- },
830
- collapsesInnerWhiteSpace: true,
831
- spacing: NO_SPACING,
832
- isInline: true
833
- };
834
- const Emphasis = {
835
- enter: ({ state }) => {
836
- if ((state.depthMap?.[17] || 0) > 1) return "";
837
- return "*";
838
- },
839
- exit: ({ node, state }) => {
840
- if ((state.depthMap?.[17] || 0) + (node.tagId === 17 ? 1 : 0) > 1) return "";
841
- return "*";
842
- },
843
- collapsesInnerWhiteSpace: true,
844
- spacing: NO_SPACING,
845
- isInline: true
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 = {
6
+ isNonNesting: true,
7
+ excludesTextNodes: true
846
8
  };
847
- const Strikethrough = {
848
- enter: () => "~~",
849
- exit: () => "~~",
850
- collapsesInnerWhiteSpace: true,
851
- spacing: NO_SPACING,
852
- isInline: true
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
853
41
  };
854
- const INERT_RAWTEXT = {
855
- isNonNesting: true,
856
- excludesTextNodes: true,
42
+ const UNKNOWN_TAG_HANDLER = {
43
+ isInline: true,
857
44
  spacing: NO_SPACING
858
45
  };
859
- const tagHandlers = {
860
- [1]: {
861
- spacing: NO_SPACING,
862
- collapsesInnerWhiteSpace: true
863
- },
864
- [2]: {
865
- enter: () => "<details>",
866
- exit: ({ state }) => isInsideTableCell(state) ? "</details>" : "</details>\n\n"
867
- },
868
- [3]: {
869
- enter: () => "<summary>",
870
- exit: ({ state }) => isInsideTableCell(state) ? "</summary>" : "</summary>\n\n"
871
- },
872
- [4]: {
873
- collapsesInnerWhiteSpace: true,
874
- isNonNesting: true,
875
- spacing: NO_SPACING
876
- },
877
- [52]: {
878
- excludesTextNodes: true,
879
- isNonNesting: true
880
- },
881
- [53]: {
882
- isNonNesting: true,
883
- excludesTextNodes: true
884
- },
885
- [5]: {
886
- collapsesInnerWhiteSpace: true,
887
- isSelfClosing: true,
888
- spacing: NO_SPACING
889
- },
890
- [6]: breakHandler,
891
- [7]: handleHeading(1),
892
- [8]: handleHeading(2),
893
- [9]: handleHeading(3),
894
- [10]: handleHeading(4),
895
- [11]: handleHeading(5),
896
- [12]: handleHeading(6),
897
- [13]: {
898
- enter: ({ node, state }) => {
899
- if (isInsideTableCell(state)) return "<hr>";
900
- if (!(state.depthMap?.[25] || state.bufferedBlockquoteDepth)) return "---";
901
- const prefix = continuationPrefix(node, state.listIndentWidths || [], !state.bufferedBlockquoteDepth);
902
- if (!prefix) return "---";
903
- if (state.depthMap?.[25]) state.listRulePending = prefix;
904
- const open = blockOpenPrefix(state.buffer, prefix);
905
- return open === void 0 ? "***" : `${open}---`;
906
- },
907
- isSelfClosing: true
908
- },
909
- [14]: Strong,
910
- [15]: Strong,
911
- [16]: Emphasis,
912
- [17]: Emphasis,
913
- [18]: Strikethrough,
914
- [110]: Strikethrough,
915
- [111]: Strikethrough,
916
- [19]: {
917
- enter: () => "<sub>",
918
- exit: () => "</sub>",
919
- collapsesInnerWhiteSpace: true,
920
- spacing: NO_SPACING,
921
- isInline: true
922
- },
923
- [20]: {
924
- enter: () => "<sup>",
925
- exit: () => "</sup>",
926
- collapsesInnerWhiteSpace: true,
927
- spacing: NO_SPACING,
928
- isInline: true
929
- },
930
- [21]: {
931
- enter: () => "<ins>",
932
- exit: () => "</ins>",
933
- collapsesInnerWhiteSpace: true,
934
- spacing: NO_SPACING,
935
- isInline: true
936
- },
937
- [22]: {
938
- enter: ({ state }) => {
939
- return {
940
- _tag: "BlockquoteEnter",
941
- output: (state.depthMap?.[25] || 0) > 0 ? "\n" : void 0
942
- };
943
- },
944
- exit: () => ({ _tag: "BlockquoteExit" }),
945
- spacing: BLOCKQUOTE_SPACING
946
- },
947
- [34]: {
948
- enter: ({ node, state }) => {
949
- if (isInsideTableCell(state)) return "<pre>";
950
- return {
951
- _tag: "PreEnter",
952
- language: getLanguageFromClass(node.attributes?.class)
953
- };
954
- },
955
- exit: ({ state }) => {
956
- if (isInsideTableCell(state)) return "</pre>";
957
- return { _tag: "PreExit" };
958
- }
959
- },
960
- [23]: {
961
- enter: ({ node, state }) => {
962
- if ((state.depthMap?.[34] || 0) > 0) {
963
- if (isInsideTableCell(state)) return "<code>";
964
- if (state.preFenceOpen) return;
965
- const language = getLanguageFromClass(node.attributes?.class);
966
- if ((state.depthMap?.[25] || 0) > 0) {
967
- const indent = state.listIndent;
968
- return {
969
- _tag: "CodeFenceEnter",
970
- language,
971
- output: `${blockOpenPrefix(state.buffer, indent) ?? ""}\`\`\`${language}\n`
972
- };
973
- }
974
- return {
975
- _tag: "CodeFenceEnter",
976
- language,
977
- output: `\`\`\`${language}\n`
978
- };
979
- }
980
- if (isInsideRawHtmlBlock(state.depthMap)) return "<code>";
981
- if ((state.depthMap?.[25] || 0) > 0) {
982
- const lastEntry = state.buffer.at(-1);
983
- const lastChar = lastEntry?.charAt(lastEntry.length - 1) || "";
984
- if (lastChar && lastChar !== " " && lastChar !== "\n" && lastChar !== " " && lastChar !== "*" && lastChar !== "_" && lastChar !== "~" && lastChar !== "[" && lastChar !== ">") return {
985
- _tag: "CodeSpanEnter",
986
- output: ` \``
987
- };
988
- }
989
- return {
990
- _tag: "CodeSpanEnter",
991
- output: "`"
992
- };
993
- },
994
- exit: ({ state }) => {
995
- if ((state.depthMap?.[34] || 0) > 0) {
996
- if (isInsideTableCell(state)) return "</code>";
997
- return;
998
- }
999
- if (isInsideRawHtmlBlock(state.depthMap)) return "</code>";
1000
- return { _tag: "CodeSpanExit" };
1001
- },
1002
- collapsesInnerWhiteSpace: true,
1003
- spacing: NO_SPACING,
1004
- isInline: true
1005
- },
1006
- [24]: {
1007
- enter: ({ state }) => isInsideTableCell(state) ? "<ul>" : void 0,
1008
- exit: ({ state }) => isInsideTableCell(state) ? "</ul>" : void 0
1009
- },
1010
- [33]: {
1011
- enter: ({ state }) => isInsideTableCell(state) ? "<ol>" : void 0,
1012
- exit: ({ state }) => isInsideTableCell(state) ? "</ol>" : void 0
1013
- },
1014
- [25]: {
1015
- enter: ({ node, state }) => {
1016
- if (isInsideTableCell(state)) return "<li>";
1017
- const marker = node.parent?.tagId === 33 ? `${orderedItemNumber(node.parent, node.index)}. ` : "- ";
1018
- return `${state.listIndent}${marker}`;
1019
- },
1020
- exit: ({ state }) => isInsideTableCell(state) ? "</li>" : void 0,
1021
- spacing: LIST_ITEM_SPACING
1022
- },
1023
- [26]: {
1024
- enter: ({ node, state }) => {
1025
- if (node.attributes?.href !== void 0) {
1026
- if (stripsEmptyLink(state, node.attributes.href)) return;
1027
- if (isInsideRawHtmlBlock(state.depthMap)) return safeAnchorOutput(node, state.options, true, true);
1028
- return "[";
1029
- }
1030
- },
1031
- exit: ({ node, state }) => {
1032
- if (node.attributes?.href === void 0) return "";
1033
- if (stripsEmptyLink(state, node.attributes.href)) return "";
1034
- if (isInsideRawHtmlBlock(state.depthMap) && !node.tagHandler?.literalEnter) return safeAnchorOutput(node, state.options, false, true);
1035
- const href = resolveUrl(node.attributes.href, state.options?.origin, state.options?.clean);
1036
- let title = node.attributes?.title;
1037
- if (state.lastContentCache === title) title = "";
1038
- if (!title && isAutolinkUri(href)) {
1039
- const buf = state.buffer;
1040
- let i = buf.length - 1;
1041
- let textLen = 0;
1042
- let captionBracket = -1;
1043
- let captionTextLen = 0;
1044
- while (i >= 0) {
1045
- const entry = buf[i];
1046
- if (entry === "[") break;
1047
- if (captionBracket < 0 && state.depthMap?.[106] && entry.endsWith("*[")) {
1048
- captionBracket = i;
1049
- captionTextLen = textLen;
1050
- }
1051
- textLen += entry.length;
1052
- i--;
1053
- }
1054
- const captionLink = i < 0 && captionBracket >= 0;
1055
- if (captionLink) {
1056
- i = captionBracket;
1057
- textLen = captionTextLen;
1058
- }
1059
- if (i >= 0 && textLen === href.length && buf.slice(i + 1).join("") === href) {
1060
- if (captionLink) buf[i] = buf[i].slice(0, -1);
1061
- buf.length = i + (captionLink ? 1 : 0);
1062
- const auto = `<${href}>`;
1063
- buf.push(auto);
1064
- state.lastContentCache = auto;
1065
- return "";
1066
- }
1067
- }
1068
- return `]${serializeMarkdownResource(href, title)}`;
1069
- },
1070
- collapsesInnerWhiteSpace: true,
1071
- spacing: NO_SPACING,
1072
- isInline: true
1073
- },
1074
- [27]: {
1075
- enter: ({ node, state }) => {
1076
- const alt = node.attributes?.alt || "";
1077
- const src = resolveUrl(node.attributes?.src || "", state.options?.origin, state.options?.clean);
1078
- const clean = state.options?.clean;
1079
- if ((clean === true || clean !== void 0 && clean !== false && clean.emptyImages === true) && !alt.trim()) {
1080
- if (state.depthMap?.[106]) return void 0;
1081
- } else markRenderedChildContent(node);
1082
- return `![${serializeImageDescription(alt)}]${serializeMarkdownResource(src, node.attributes?.title)}`;
1083
- },
1084
- collapsesInnerWhiteSpace: true,
1085
- isSelfClosing: true,
1086
- spacing: NO_SPACING,
1087
- isInline: true
1088
- },
1089
- [28]: {
1090
- enter: ({ state }) => {
1091
- if (isInsideTableCell(state)) return "<table>";
1092
- if ((state.depthMap?.[28] || 0) <= 1) state.tableRenderedTable = false;
1093
- state.tableColumnAlignments = [];
1094
- state.tableHeaderCells = 0;
1095
- },
1096
- exit: ({ state }) => isInsideTableCell(state) ? "</table>" : void 0
1097
- },
1098
- [107]: { enter: ({ state }) => {
1099
- if ((state.depthMap?.[25] || 0) === 0 || isInsideTableCell(state)) return void 0;
1100
- return blockOpenPrefix(state.buffer, state.listIndent);
1101
- } },
1102
- [29]: {
1103
- enter: ({ state }) => {
1104
- if (isInsideTableCell(state)) return "<thead>";
1105
- },
1106
- exit: ({ state }) => isInsideTableCell(state) ? "</thead>" : void 0,
1107
- spacing: TABLE_ROW_SPACING,
1108
- excludesTextNodes: true
1109
- },
1110
- [30]: {
1111
- enter: ({ state }) => {
1112
- if (isInsideTableCell(state)) return "<tr>";
1113
- state.tableCurrentRowCells = 0;
1114
- return rowMarker(state);
1115
- },
1116
- exit: ({ state }) => {
1117
- if (isInsideTableCell(state) || (state.depthMap?.[28] || 0) > 1) return "</tr>";
1118
- if (!state.tableRenderedTable) {
1119
- state.tableRenderedTable = true;
1120
- const alignments = state.tableColumnAlignments;
1121
- while (alignments.length < state.tableCurrentRowCells) alignments.push("");
1122
- const alignmentMarkers = alignments.map((align) => {
1123
- switch (align) {
1124
- case "left": return ":---";
1125
- case "center": return ":---:";
1126
- case "right": return "---:";
1127
- default: return "---";
1128
- }
1129
- });
1130
- state.tableHeaderCells = alignments.length;
1131
- return ` |\n${(state.depthMap?.[25] || 0) > 0 ? state.listIndent : ""}| ${alignmentMarkers.join(" | ")} |`;
1132
- }
1133
- return " |";
1134
- },
1135
- excludesTextNodes: true,
1136
- spacing: TABLE_ROW_SPACING
1137
- },
1138
- [31]: {
1139
- enter: ({ node, state }) => {
1140
- if ((state.depthMap?.[28] || 0) > 1) return "<th>";
1141
- const align = node.attributes?.align?.toLowerCase();
1142
- if (align) state.tableColumnAlignments.push(align);
1143
- else if (state.tableColumnAlignments.length <= state.tableCurrentRowCells) state.tableColumnAlignments.push("");
1144
- return cellEnter(node, state);
1145
- },
1146
- exit: ({ node, state }) => {
1147
- if ((state.depthMap?.[28] || 0) > 1) return "</th>";
1148
- return cellExit(node, state);
1149
- },
1150
- collapsesInnerWhiteSpace: true,
1151
- spacing: NO_SPACING
1152
- },
1153
- [32]: {
1154
- enter: ({ node, state }) => {
1155
- if ((state.depthMap?.[28] || 0) > 1) return "<td>";
1156
- return cellEnter(node, state);
1157
- },
1158
- exit: ({ node, state }) => {
1159
- if ((state.depthMap?.[28] || 0) > 1) return "</td>";
1160
- return cellExit(node, state);
1161
- },
1162
- collapsesInnerWhiteSpace: true,
1163
- spacing: NO_SPACING
1164
- },
1165
- [35]: { enter: ({ state }) => {
1166
- if ((state.depthMap?.[25] || 0) > 0 && !isInsideTableCell(state)) {
1167
- const lastEntry = state.buffer.at(-1);
1168
- const lastChar = lastEntry?.charAt(lastEntry.length - 1) || "";
1169
- if (lastChar && lastChar !== " " && lastChar !== "\n") return `\n\n${state.listIndent}`;
1170
- }
1171
- } },
1172
- [36]: {},
1173
- [37]: {
1174
- collapsesInnerWhiteSpace: true,
1175
- spacing: NO_SPACING,
1176
- isInline: true
1177
- },
1178
- [41]: {},
1179
- [42]: {
1180
- collapsesInnerWhiteSpace: true,
1181
- spacing: NO_SPACING,
1182
- isInline: true
1183
- },
1184
- [43]: {
1185
- collapsesInnerWhiteSpace: true,
1186
- spacing: NO_SPACING,
1187
- isInline: true
1188
- },
1189
- [44]: { spacing: NO_SPACING },
1190
- [45]: {
1191
- enter: ({ state }) => {
1192
- if ((state.depthMap?.[28] || 0) > 1) return "<center>";
1193
- },
1194
- exit: ({ state }) => {
1195
- if ((state.depthMap?.[28] || 0) > 1) return "</center>";
1196
- },
1197
- spacing: NO_SPACING
1198
- },
1199
- [38]: {
1200
- spacing: NO_SPACING,
1201
- excludesTextNodes: true
1202
- },
1203
- [39]: {
1204
- spacing: TABLE_ROW_SPACING,
1205
- excludesTextNodes: true
1206
- },
1207
- [46]: {
1208
- enter: () => "`",
1209
- exit: () => "`",
1210
- collapsesInnerWhiteSpace: true,
1211
- spacing: NO_SPACING,
1212
- isInline: true
1213
- },
1214
- [47]: { spacing: NO_SPACING },
1215
- [40]: { spacing: NO_SPACING },
1216
- [54]: {
1217
- isSelfClosing: true,
1218
- spacing: NO_SPACING,
1219
- collapsesInnerWhiteSpace: true,
1220
- isInline: true
1221
- },
1222
- [55]: {
1223
- isSelfClosing: true,
1224
- spacing: NO_SPACING,
1225
- isInline: true,
1226
- collapsesInnerWhiteSpace: true
1227
- },
1228
- [56]: {
1229
- isSelfClosing: true,
1230
- spacing: NO_SPACING,
1231
- isInline: true,
1232
- collapsesInnerWhiteSpace: true
1233
- },
1234
- [57]: {
1235
- isSelfClosing: true,
1236
- spacing: NO_SPACING
1237
- },
1238
- [58]: {
1239
- isSelfClosing: true,
1240
- spacing: NO_SPACING
1241
- },
1242
- [59]: {
1243
- isSelfClosing: true,
1244
- spacing: NO_SPACING,
1245
- isInline: true,
1246
- collapsesInnerWhiteSpace: true
1247
- },
1248
- [60]: {
1249
- isSelfClosing: true,
1250
- spacing: NO_SPACING,
1251
- isInline: true,
1252
- collapsesInnerWhiteSpace: true
1253
- },
1254
- [61]: {
1255
- isSelfClosing: true,
1256
- spacing: NO_SPACING
1257
- },
1258
- [62]: {
1259
- isSelfClosing: true,
1260
- spacing: NO_SPACING
1261
- },
1262
- [63]: {
1263
- isSelfClosing: true,
1264
- spacing: NO_SPACING
1265
- },
1266
- [64]: {
1267
- isSelfClosing: true,
1268
- spacing: NO_SPACING,
1269
- isInline: true,
1270
- collapsesInnerWhiteSpace: true
1271
- },
1272
- [49]: { spacing: NO_SPACING },
1273
- [65]: { spacing: NO_SPACING },
1274
- [66]: {
1275
- isNonNesting: true,
1276
- spacing: NO_SPACING
1277
- },
1278
- [67]: { spacing: NO_SPACING },
1279
- [109]: { spacing: NO_SPACING },
1280
- [68]: { spacing: NO_SPACING },
1281
- [69]: { spacing: NO_SPACING },
1282
- [70]: { spacing: NO_SPACING },
1283
- [71]: { spacing: NO_SPACING },
1284
- [72]: { spacing: NO_SPACING },
1285
- [73]: { ...INERT_RAWTEXT },
1286
- [74]: { spacing: NO_SPACING },
1287
- [75]: { spacing: NO_SPACING },
1288
- [76]: { spacing: NO_SPACING },
1289
- [77]: { spacing: NO_SPACING },
1290
- [78]: {
1291
- excludesTextNodes: true,
1292
- spacing: NO_SPACING
1293
- },
1294
- [79]: {
1295
- enter: () => "",
1296
- exit: () => "",
1297
- collapsesInnerWhiteSpace: true,
1298
- spacing: NO_SPACING,
1299
- isInline: true
1300
- },
1301
- [80]: {
1302
- enter: () => "<mark>",
1303
- exit: () => "</mark>",
1304
- collapsesInnerWhiteSpace: true,
1305
- spacing: NO_SPACING,
1306
- isInline: true
1307
- },
1308
- [81]: {
1309
- enter: () => "\"",
1310
- exit: () => "\"",
1311
- collapsesInnerWhiteSpace: true,
1312
- spacing: NO_SPACING,
1313
- isInline: true
1314
- },
1315
- [82]: {
1316
- enter: () => "`",
1317
- exit: () => "`",
1318
- collapsesInnerWhiteSpace: true,
1319
- spacing: NO_SPACING,
1320
- isInline: true
1321
- },
1322
- [83]: {
1323
- enter: () => "",
1324
- exit: () => "",
1325
- collapsesInnerWhiteSpace: true,
1326
- spacing: NO_SPACING,
1327
- isInline: true
1328
- },
1329
- [84]: { ...INERT_RAWTEXT },
1330
- [112]: { ...INERT_RAWTEXT },
1331
- [108]: {
1332
- isNonNesting: true,
1333
- excludesTextNodes: true,
1334
- spacing: NO_SPACING
1335
- },
1336
- [85]: { ...INERT_RAWTEXT },
1337
- [86]: {
1338
- isNonNesting: true,
1339
- spacing: NO_SPACING
1340
- },
1341
- [87]: {
1342
- isNonNesting: true,
1343
- spacing: NO_SPACING
1344
- },
1345
- [88]: { spacing: NO_SPACING },
1346
- [89]: {
1347
- enter: () => {
1348
- return "<u>";
1349
- },
1350
- exit: () => {
1351
- return "</u>";
1352
- },
1353
- collapsesInnerWhiteSpace: true,
1354
- spacing: NO_SPACING,
1355
- isInline: true
1356
- },
1357
- [90]: {
1358
- enter: () => "*",
1359
- exit: () => "*",
1360
- collapsesInnerWhiteSpace: true,
1361
- spacing: NO_SPACING,
1362
- isInline: true
1363
- },
1364
- [91]: {
1365
- enter: () => "**",
1366
- exit: () => "**",
1367
- collapsesInnerWhiteSpace: true,
1368
- spacing: NO_SPACING,
1369
- isInline: true
1370
- },
1371
- [92]: {
1372
- enter: () => "`",
1373
- exit: () => "`",
1374
- collapsesInnerWhiteSpace: true,
1375
- spacing: NO_SPACING,
1376
- isInline: true
1377
- },
1378
- [93]: {
1379
- enter: () => "",
1380
- exit: () => "",
1381
- collapsesInnerWhiteSpace: true,
1382
- spacing: NO_SPACING,
1383
- isInline: true
1384
- },
1385
- [94]: {
1386
- enter: () => "",
1387
- exit: () => "",
1388
- collapsesInnerWhiteSpace: true,
1389
- spacing: NO_SPACING,
1390
- isInline: true
1391
- },
1392
- [95]: {
1393
- enter: () => "",
1394
- exit: () => "",
1395
- collapsesInnerWhiteSpace: true,
1396
- spacing: NO_SPACING,
1397
- isInline: true
1398
- },
1399
- [96]: {
1400
- enter: () => "",
1401
- exit: () => "",
1402
- collapsesInnerWhiteSpace: true,
1403
- spacing: NO_SPACING,
1404
- isInline: true
1405
- },
1406
- [97]: {
1407
- enter: () => "",
1408
- exit: () => "",
1409
- collapsesInnerWhiteSpace: true,
1410
- spacing: NO_SPACING,
1411
- isInline: true
1412
- },
1413
- [100]: {
1414
- enter: () => "<address>",
1415
- exit: () => "</address>",
1416
- spacing: NO_SPACING,
1417
- collapsesInnerWhiteSpace: true
1418
- },
1419
- [101]: {
1420
- spacing: NO_SPACING,
1421
- enter: () => "<dl>",
1422
- exit: () => "</dl>"
1423
- },
1424
- [99]: {
1425
- enter: () => "<dt>",
1426
- exit: () => "</dt>",
1427
- collapsesInnerWhiteSpace: true,
1428
- spacing: [0, 1]
1429
- },
1430
- [98]: {
1431
- enter: () => "<dd>",
1432
- exit: () => "</dd>",
1433
- spacing: [0, 1]
1434
- },
1435
- [50]: {},
1436
- [51]: {},
1437
- [105]: {},
1438
- [104]: {},
1439
- [102]: {},
1440
- [106]: {
1441
- exit: () => "*",
1442
- collapsesInnerWhiteSpace: true,
1443
- isInline: true
1444
- }
1445
- };
1446
- function buildTagOverrideHandlers(overrides) {
1447
- const result = /* @__PURE__ */ new Map();
1448
- for (const tagName in overrides) {
1449
- const override = overrides[tagName];
1450
- if (!override) continue;
1451
- if (typeof override === "string") {
1452
- const targetId = TagIdMap[override];
1453
- if (targetId !== void 0) {
1454
- const baseHandler = tagHandlers[targetId];
1455
- if (baseHandler) result.set(tagName, {
1456
- ...baseHandler,
1457
- aliasTagId: targetId
1458
- });
1459
- }
1460
- } else {
1461
- const baseId = TagIdMap[tagName];
1462
- const baseHandler = baseId !== void 0 ? tagHandlers[baseId] : void 0;
1463
- const handler = baseHandler ? { ...baseHandler } : {};
1464
- if (override.enter !== void 0) {
1465
- const enterStr = override.enter;
1466
- handler.enter = () => enterStr;
1467
- handler.literalEnter = true;
1468
- }
1469
- if (override.exit !== void 0) {
1470
- const exitStr = override.exit;
1471
- handler.exit = () => exitStr;
1472
- handler.literalExit = true;
1473
- }
1474
- if (override.spacing !== void 0) handler.spacing = override.spacing;
1475
- if (override.isInline !== void 0) handler.isInline = override.isInline;
1476
- if (override.isSelfClosing !== void 0) handler.isSelfClosing = override.isSelfClosing;
1477
- if (override.collapsesInnerWhiteSpace !== void 0) handler.collapsesInnerWhiteSpace = override.collapsesInnerWhiteSpace;
1478
- result.set(tagName, handler);
1479
- }
1480
- }
1481
- return result;
1482
- }
1483
46
  const LT_CHAR = 60;
1484
47
  const GT_CHAR = 62;
1485
48
  const SLASH_CHAR = 47;
@@ -1787,10 +350,17 @@ function finalizeParse(leftover, state, handleEvent) {
1787
350
  const scriptText = takeScriptText(state);
1788
351
  if (scriptText) processTextBuffer(scriptText, state, handleEvent);
1789
352
  } else if (leftover.length > 0) {
1790
- const incompleteTagIndex = findIncompleteTagResidualIndex(leftover);
1791
- 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
+ }
1792
361
  if (text) processTextBuffer(text, state, handleEvent);
1793
362
  }
363
+ state.trailingText = void 0;
1794
364
  while (state.currentNode) closeNode(state.currentNode, state, handleEvent);
1795
365
  }
1796
366
  const EMPTY_ATTRIBUTES = Object.freeze({});
@@ -1904,7 +474,7 @@ function findScriptEndTag(html, start, parseState) {
1904
474
  return scriptScanResult(parseState, state, SCRIPT_SCAN_COMPLETE);
1905
475
  }
1906
476
  function pushScriptTextChunk(state, text) {
1907
- if (!text) return;
477
+ if (!text || state.discardExcludedText && state.currentNode?.tagHandler?.excludesTextNodes) return;
1908
478
  (state.scriptTextChunks ??= []).push(text);
1909
479
  state.textBufferContainsNonWhitespace = true;
1910
480
  state.lastCharWasWhitespace = false;
@@ -1912,6 +482,7 @@ function pushScriptTextChunk(state, text) {
1912
482
  }
1913
483
  function scanScriptChunk(html, start, state) {
1914
484
  const result = findScriptEndTag(html, start, state);
485
+ if (state.discardExcludedText && state.currentNode?.tagHandler?.excludesTextNodes) return result;
1915
486
  if (result === SCRIPT_SCAN_COMPLETE) pushScriptTextChunk(state, html.substring(start));
1916
487
  else if (result <= SCRIPT_SEQUENCE_INCOMPLETE) pushScriptTextChunk(state, html.substring(start, -result - 2));
1917
488
  else pushScriptTextChunk(state, html.substring(start, result));
@@ -1945,7 +516,8 @@ function parseHtml(html, options = {}) {
1945
516
  const state = {
1946
517
  depthMap: /* @__PURE__ */ new Uint16Array(113),
1947
518
  depth: 0,
1948
- resolvedPlugins: options.resolvedPlugins || []
519
+ resolvedPlugins: options.resolvedPlugins || [],
520
+ tagHandlers: options.tagHandlers
1949
521
  };
1950
522
  let remainingHtml = parseHtmlInternal(html, state, (event) => {
1951
523
  events.push(event);
@@ -1962,12 +534,14 @@ function parseHtmlStream(html, state, onEvent) {
1962
534
  function parseHtmlInternal(htmlChunk, state, handleEvent) {
1963
535
  let textBuffer = "";
1964
536
  let runStart = 0;
537
+ let declarationPending = false;
1965
538
  state.depthMap ??= /* @__PURE__ */ new Uint16Array(113);
1966
539
  state.depth ??= 0;
1967
540
  state.lastCharWasWhitespace ??= true;
1968
541
  state.justClosedTag ??= false;
1969
542
  state.isFirstTextInElement ??= false;
1970
543
  state.scriptDataState ??= SCRIPT_DATA;
544
+ state.rawtextEndTagPending = false;
1971
545
  let i = 0;
1972
546
  const chunkLength = htmlChunk.length;
1973
547
  if (state.currentNode && isScriptElement(state.currentNode)) {
@@ -1991,15 +565,26 @@ function parseHtmlInternal(htmlChunk, state, handleEvent) {
1991
565
  i++;
1992
566
  continue;
1993
567
  }
1994
- if (inPreTag) textBuffer += htmlChunk[i];
1995
- 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 += " ";
1996
573
  state.lastCharWasWhitespace = true;
1997
574
  state.textBufferContainsWhitespace = true;
1998
575
  } else {
1999
576
  state.textBufferContainsNonWhitespace = true;
2000
577
  state.lastCharWasWhitespace = false;
2001
578
  state.justClosedTag = false;
2002
- 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;
2003
588
  }
2004
589
  i++;
2005
590
  continue;
@@ -2031,10 +616,20 @@ function parseHtmlInternal(htmlChunk, state, handleEvent) {
2031
616
  }
2032
617
  }
2033
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;
2034
622
  if (htmlChunk.charCodeAt(i + 2) === OPEN_BRACKET_CHAR) {
2035
623
  if (htmlChunk.startsWith("<![CDATA[", i)) {
2036
624
  const end = htmlChunk.indexOf("]]>", i + 9);
2037
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;
2038
633
  textBuffer += htmlChunk.substring(i);
2039
634
  break;
2040
635
  }
@@ -2049,6 +644,7 @@ function parseHtmlInternal(htmlChunk, state, handleEvent) {
2049
644
  continue;
2050
645
  }
2051
646
  if (chunkLength - i < 9 && "<![CDATA[".startsWith(htmlChunk.substring(i))) {
647
+ declarationPending = true;
2052
648
  textBuffer += htmlChunk.substring(i);
2053
649
  break;
2054
650
  }
@@ -2063,6 +659,12 @@ function parseHtmlInternal(htmlChunk, state, handleEvent) {
2063
659
  i = result.newPosition;
2064
660
  runStart = i;
2065
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
+ }
2066
668
  textBuffer += result.remainingText;
2067
669
  break;
2068
670
  }
@@ -2074,6 +676,12 @@ function parseHtmlInternal(htmlChunk, state, handleEvent) {
2074
676
  if (c === GT_CHAR || c === SLASH_CHAR || isWhitespace(c)) break;
2075
677
  peekEnd++;
2076
678
  }
679
+ if (peekEnd === chunkLength) {
680
+ state.textBufferContainsNonWhitespace = true;
681
+ state.lastCharWasWhitespace = false;
682
+ textBuffer += htmlChunk.substring(i);
683
+ break;
684
+ }
2077
685
  const peekTagName = normalizeTagName(htmlChunk.substring(i + 2, peekEnd));
2078
686
  const peekHandler = state.tagOverrideHandlers?.get(peekTagName);
2079
687
  const peekTagId = effectiveTagId(peekTagName, TagIdMap[peekTagName] ?? -1, state);
@@ -2092,6 +700,7 @@ function parseHtmlInternal(htmlChunk, state, handleEvent) {
2092
700
  i = result.newPosition;
2093
701
  runStart = i;
2094
702
  } else {
703
+ state.rawtextEndTagPending = state.flattenedRawTagName !== void 0 || !!state.currentNode?.tagHandler?.isNonNesting;
2095
704
  textBuffer += result.remainingText;
2096
705
  break;
2097
706
  }
@@ -2167,8 +776,35 @@ function parseHtmlInternal(htmlChunk, state, handleEvent) {
2167
776
  }
2168
777
  }
2169
778
  }
2170
- 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
+ }
2171
806
  if (remainingHtml.length > 0 && isWhitespace(remainingHtml.charCodeAt(0))) state.lastCharWasWhitespace = false;
807
+ state.trailingText = textBuffer;
2172
808
  return remainingHtml;
2173
809
  }
2174
810
  function processTextBuffer(textBuffer, state, handleEvent) {
@@ -2192,6 +828,9 @@ function processTextBuffer(textBuffer, state, handleEvent) {
2192
828
  containsWhitespace,
2193
829
  excludedFromMarkdown: false
2194
830
  };
831
+ if (state.endTagClosedNothing) rootTextNode.joinsPrevious = true;
832
+ if (containsWhitespace) rootTextNode.trimsAtLineStart = true;
833
+ state.endTagClosedNothing = false;
2195
834
  handleEvent({
2196
835
  type: 0,
2197
836
  node: rootTextNode
@@ -2206,7 +845,9 @@ function processTextBuffer(textBuffer, state, handleEvent) {
2206
845
  if (text.length === 0) return;
2207
846
  const parentsToIncrement = traverseUpToFirstBlockNode(state.currentNode);
2208
847
  const firstBlockParent = parentsToIncrement.at(-1);
2209
- 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) {
2210
851
  let start = 0;
2211
852
  while (start < text.length && (inPreTag ? text.charCodeAt(start) === NEWLINE_CHAR || text.charCodeAt(start) === CARRIAGE_RETURN_CHAR : isWhitespace(text.charCodeAt(start)))) start++;
2212
853
  if (start > 0) text = text.substring(start);
@@ -2224,6 +865,9 @@ function processTextBuffer(textBuffer, state, handleEvent) {
2224
865
  containsWhitespace,
2225
866
  excludedFromMarkdown: excludesTextNodes
2226
867
  };
868
+ if (state.endTagClosedNothing) textNode.joinsPrevious = true;
869
+ if (inlineAtRoot) textNode.trimsAtLineStart = true;
870
+ state.endTagClosedNothing = false;
2227
871
  for (const parent of parentsToIncrement) parent.childTextNodeIndex = (parent.childTextNodeIndex || 0) + 1;
2228
872
  handleEvent({
2229
873
  type: 0,
@@ -2357,7 +1001,7 @@ function processClosingTag(htmlChunk, position, state, handleEvent) {
2357
1001
  if (curr) {
2358
1002
  while (state.currentNode && state.currentNode !== curr) closeNode(state.currentNode, state, handleEvent);
2359
1003
  closeNode(curr, state, handleEvent);
2360
- }
1004
+ } else state.endTagClosedNothing = true;
2361
1005
  state.justClosedTag = true;
2362
1006
  return {
2363
1007
  complete: true,
@@ -2387,6 +1031,7 @@ function closeNode(node, state, handleEvent) {
2387
1031
  const tagId = node.tagId;
2388
1032
  if (tagId !== void 0 && tagId >= 0 && tagId < 113) state.depthMap[tagId] = Math.max(0, (state.depthMap[tagId] || 0) - 1);
2389
1033
  state.depth--;
1034
+ state.endTagClosedNothing = false;
2390
1035
  handleEvent({
2391
1036
  type: 1,
2392
1037
  node
@@ -2507,7 +1152,7 @@ function processCdataSection(content, state, handleEvent) {
2507
1152
  function processOpeningTag(tagName, tagId, htmlChunk, i, state, handleEvent) {
2508
1153
  tagId = effectiveTagId(tagName, tagId, state);
2509
1154
  if (state.currentNode?.tagHandler?.isNonNesting) closeNode(state.currentNode, state, handleEvent);
2510
- const tagHandler = state.tagOverrideHandlers?.get(tagName) ?? tagHandlers[tagId];
1155
+ const tagHandler = state.tagOverrideHandlers?.get(tagName) ?? (tagId === -1 ? UNKNOWN_TAG_HANDLER : state.tagHandlers?.[tagId] ?? parserTagHandlers[tagId]);
2511
1156
  const result = scanTagAttributes(htmlChunk, i, tagHandler);
2512
1157
  if (result._tag === "incomplete") return {
2513
1158
  complete: false,
@@ -2611,6 +1256,7 @@ function processOpeningTag(tagName, tagId, htmlChunk, i, state, handleEvent) {
2611
1256
  const tag = new ParsedElementNode(tagName, result.attributes, state.currentNode, state.depth, currentWalkIndex, tagId, tagHandler);
2612
1257
  if (tagId === 78 || state.currentNode?.excludedFromMarkdown) tag.excludedFromMarkdown = true;
2613
1258
  state.lastTextNode = tag;
1259
+ state.endTagClosedNothing = false;
2614
1260
  handleEvent({
2615
1261
  type: 0,
2616
1262
  node: tag
@@ -2740,4 +1386,4 @@ function parseAttributes(attrStr) {
2740
1386
  if (result._tag === "incomplete") throw new Error("Isolated attribute scans always complete at EOF");
2741
1387
  return result.attributes === EMPTY_ATTRIBUTES ? {} : result.attributes;
2742
1388
  }
2743
- export { blockOpenPrefix, breakHandler, buildTagOverrideHandlers, continuationPrefix, escapeHtml, figcaptionOwnsBlockSpacing, finalizeParse, getLanguageFromClass, isCharacterReferenceTail, isEmptyLinkHref, isInsideHeading, isInsideTableCell, isSafeHtmlUrl, lastOutputChar, listMarkerLineStart, markRenderedChildContent, orderedItemNumber, parseAttributes, parseHtml, parseHtmlStream, parseUnsignedInteger, renderBreak, resolveUrl, safeAnchorOutput };
1389
+ export { finalizeParse, parseAttributes, parseHtml, parseHtmlStream, parserTagHandlers };