@viveeditor/sanitize 0.0.0-stage → 1.0.0-rc.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,1425 @@
1
+ import { Parser, defaultTreeAdapter, html, serialize } from "parse5";
2
+ // src/profile.ts
3
+ const VIVE_PROFILE = {
4
+ version: 1,
5
+ limits: {
6
+ "maxBytes": 2e6,
7
+ "maxDepth": 64,
8
+ "maxAttributeLength": 2048,
9
+ "maxTextAttributeLength": 1e3,
10
+ "maxStyleValueLength": 64,
11
+ "minFontSizePt": 6,
12
+ "maxFontSizePt": 96,
13
+ "maxSpan": 100,
14
+ "maxImageSize": 1e4,
15
+ "maxListStart": 99999,
16
+ "maxTableWidth": 99999,
17
+ "maxRowHeight": 2e3,
18
+ "maxEmbedStart": 86400,
19
+ "maxEmbedTitle": 200,
20
+ "maxImageSrcLength": 15e5,
21
+ "maxUrlLength": 4096,
22
+ "maxMentionId": 128,
23
+ "maxMentionLabel": 100,
24
+ "maxCommentId": 64,
25
+ "maxChangeId": 64,
26
+ "maxAuthorId": 128,
27
+ "maxAuthorName": 100,
28
+ "maxMathLength": 2e3,
29
+ "maxMathDepth": 64,
30
+ "maxFootnoteLength": 5e3,
31
+ "maxAttributes": 64,
32
+ "maxNesting": 512,
33
+ "maxExtraElements": 2048,
34
+ "maxTags": 1e5
35
+ },
36
+ dropWithContent: [
37
+ "script",
38
+ "style",
39
+ "textarea",
40
+ "title",
41
+ "xmp",
42
+ "noscript",
43
+ "noembed",
44
+ "noframes",
45
+ "plaintext",
46
+ "template",
47
+ "iframe",
48
+ "svg",
49
+ "math",
50
+ "object",
51
+ "embed",
52
+ "select",
53
+ "option",
54
+ "button",
55
+ "head",
56
+ "frameset",
57
+ "frame"
58
+ ],
59
+ elements: {
60
+ "p": {
61
+ "styles": [
62
+ "text-align",
63
+ "margin-inline-start",
64
+ "line-height"
65
+ ],
66
+ "attributes": [
67
+ "data-vive-break",
68
+ "data-vive-change",
69
+ "data-author",
70
+ "data-name",
71
+ "data-time"
72
+ ]
73
+ },
74
+ "h1": {
75
+ "styles": [
76
+ "text-align",
77
+ "margin-inline-start",
78
+ "line-height"
79
+ ],
80
+ "attributes": [
81
+ "data-vive-break",
82
+ "data-vive-change",
83
+ "data-author",
84
+ "data-name",
85
+ "data-time"
86
+ ]
87
+ },
88
+ "h2": {
89
+ "styles": [
90
+ "text-align",
91
+ "margin-inline-start",
92
+ "line-height"
93
+ ],
94
+ "attributes": [
95
+ "data-vive-break",
96
+ "data-vive-change",
97
+ "data-author",
98
+ "data-name",
99
+ "data-time"
100
+ ]
101
+ },
102
+ "h3": {
103
+ "styles": [
104
+ "text-align",
105
+ "margin-inline-start",
106
+ "line-height"
107
+ ],
108
+ "attributes": [
109
+ "data-vive-break",
110
+ "data-vive-change",
111
+ "data-author",
112
+ "data-name",
113
+ "data-time"
114
+ ]
115
+ },
116
+ "h4": {
117
+ "styles": [
118
+ "text-align",
119
+ "margin-inline-start",
120
+ "line-height"
121
+ ],
122
+ "attributes": [
123
+ "data-vive-break",
124
+ "data-vive-change",
125
+ "data-author",
126
+ "data-name",
127
+ "data-time"
128
+ ]
129
+ },
130
+ "h5": {
131
+ "styles": [
132
+ "text-align",
133
+ "margin-inline-start",
134
+ "line-height"
135
+ ],
136
+ "attributes": [
137
+ "data-vive-break",
138
+ "data-vive-change",
139
+ "data-author",
140
+ "data-name",
141
+ "data-time"
142
+ ]
143
+ },
144
+ "h6": {
145
+ "styles": [
146
+ "text-align",
147
+ "margin-inline-start",
148
+ "line-height"
149
+ ],
150
+ "attributes": [
151
+ "data-vive-break",
152
+ "data-vive-change",
153
+ "data-author",
154
+ "data-name",
155
+ "data-time"
156
+ ]
157
+ },
158
+ "blockquote": {},
159
+ "hr": {},
160
+ "br": {},
161
+ "strong": {},
162
+ "em": {},
163
+ "u": {},
164
+ "s": {},
165
+ "ins": { "attributes": [
166
+ "data-vive-change",
167
+ "data-author",
168
+ "data-name",
169
+ "data-time"
170
+ ] },
171
+ "del": { "attributes": [
172
+ "data-vive-change",
173
+ "data-author",
174
+ "data-name",
175
+ "data-time"
176
+ ] },
177
+ "code": { "attributes": ["class"] },
178
+ "a": { "attributes": [
179
+ "href",
180
+ "title",
181
+ "target"
182
+ ] },
183
+ "ul": {
184
+ "attributes": ["data-type"],
185
+ "styles": ["list-style-type"]
186
+ },
187
+ "ol": { "attributes": ["start", "type"] },
188
+ "li": { "attributes": ["data-type", "data-checked"] },
189
+ "input": { "attributes": [
190
+ "type",
191
+ "checked",
192
+ "disabled"
193
+ ] },
194
+ "div": { "attributes": [
195
+ "class",
196
+ "data-embed",
197
+ "data-id",
198
+ "data-hash",
199
+ "data-start",
200
+ "data-title",
201
+ "data-math"
202
+ ] },
203
+ "pre": { "attributes": ["data-language"] },
204
+ "table": {
205
+ "styles": [
206
+ "width",
207
+ "min-width",
208
+ "--vive-table-border-color"
209
+ ],
210
+ "attributes": [
211
+ "data-width",
212
+ "data-align",
213
+ "data-border",
214
+ "data-striped"
215
+ ]
216
+ },
217
+ "colgroup": {},
218
+ "col": { "styles": ["width"] },
219
+ "tbody": {},
220
+ "tr": { "styles": ["height"] },
221
+ "td": {
222
+ "attributes": [
223
+ "colspan",
224
+ "rowspan",
225
+ "data-colwidth"
226
+ ],
227
+ "styles": [
228
+ "background-color",
229
+ "vertical-align",
230
+ "text-align"
231
+ ]
232
+ },
233
+ "th": {
234
+ "attributes": [
235
+ "colspan",
236
+ "rowspan",
237
+ "data-colwidth"
238
+ ],
239
+ "styles": [
240
+ "background-color",
241
+ "vertical-align",
242
+ "text-align"
243
+ ]
244
+ },
245
+ "span": {
246
+ "styles": [
247
+ "color",
248
+ "font-size",
249
+ "font-family"
250
+ ],
251
+ "attributes": [
252
+ "class",
253
+ "data-mention",
254
+ "data-math",
255
+ "data-vive-comment"
256
+ ]
257
+ },
258
+ "mark": { "styles": ["background-color"] },
259
+ "img": { "attributes": [
260
+ "src",
261
+ "alt",
262
+ "title",
263
+ "width",
264
+ "height",
265
+ "loading",
266
+ "decoding",
267
+ "referrerpolicy"
268
+ ] },
269
+ "figure": { "attributes": ["data-align"] },
270
+ "figcaption": {},
271
+ "sub": {},
272
+ "sup": { "attributes": ["data-footnote"] }
273
+ },
274
+ mentionClass: "vive-mention",
275
+ footnoteElements: [
276
+ "strong",
277
+ "em",
278
+ "a"
279
+ ],
280
+ textAlign: [
281
+ "left",
282
+ "center",
283
+ "right",
284
+ "justify"
285
+ ],
286
+ fontSizes: [
287
+ "0.75em",
288
+ "0.875em",
289
+ "1.25em",
290
+ "1.5em"
291
+ ],
292
+ indents: [
293
+ "2em",
294
+ "4em",
295
+ "6em",
296
+ "8em",
297
+ "10em",
298
+ "12em",
299
+ "14em",
300
+ "16em"
301
+ ],
302
+ imageAlign: [
303
+ "left",
304
+ "center",
305
+ "right"
306
+ ],
307
+ verticalAlign: ["middle", "bottom"],
308
+ lineHeights: [
309
+ "1",
310
+ "1.15",
311
+ "1.5",
312
+ "2"
313
+ ],
314
+ orderedListTypes: [
315
+ "a",
316
+ "A",
317
+ "i",
318
+ "I"
319
+ ],
320
+ bulletStyles: [
321
+ "disc",
322
+ "circle",
323
+ "square"
324
+ ],
325
+ tableWidths: ["full"],
326
+ tableAlign: ["center"],
327
+ tableBorders: ["rows", "none"],
328
+ fontFamilies: [
329
+ "serif",
330
+ "sans-serif",
331
+ "monospace",
332
+ "Arial, Helvetica, sans-serif",
333
+ "Georgia, serif",
334
+ "'Times New Roman', Times, serif",
335
+ "'Courier New', Courier, monospace",
336
+ "Verdana, Geneva, sans-serif"
337
+ ],
338
+ linkProtocols: [
339
+ "http",
340
+ "https",
341
+ "mailto",
342
+ "tel"
343
+ ],
344
+ linkRel: "noopener noreferrer nofollow",
345
+ image: {
346
+ "loading": "lazy",
347
+ "decoding": "async",
348
+ "referrerpolicy": "no-referrer",
349
+ "base64Types": [
350
+ "png",
351
+ "jpeg",
352
+ "gif",
353
+ "webp",
354
+ "avif"
355
+ ]
356
+ },
357
+ embedProviders: {
358
+ "youtube": {
359
+ "label": "YouTube",
360
+ "host": "www.youtube-nocookie.com",
361
+ "width": 560,
362
+ "sandbox": "allow-scripts allow-same-origin allow-presentation allow-popups allow-popups-to-escape-sandbox",
363
+ "allow": "fullscreen; picture-in-picture; encrypted-media",
364
+ "height": 315,
365
+ "fluid": true
366
+ },
367
+ "vimeo": {
368
+ "label": "Vimeo",
369
+ "host": "player.vimeo.com",
370
+ "width": 640,
371
+ "sandbox": "allow-scripts allow-same-origin allow-presentation allow-popups allow-popups-to-escape-sandbox",
372
+ "allow": "fullscreen; picture-in-picture; encrypted-media",
373
+ "height": 360,
374
+ "fluid": true
375
+ },
376
+ "spotify": {
377
+ "label": "Spotify",
378
+ "host": "open.spotify.com",
379
+ "width": 560,
380
+ "sandbox": "allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox",
381
+ "allow": "fullscreen; encrypted-media",
382
+ "height": 352,
383
+ "compactHeight": 152,
384
+ "compactTypes": ["track", "episode"],
385
+ "fluid": false
386
+ }
387
+ },
388
+ colorKeywordsRejected: [
389
+ "inherit",
390
+ "initial",
391
+ "unset",
392
+ "revert",
393
+ "currentcolor",
394
+ "transparent",
395
+ "auto",
396
+ "none",
397
+ "windowtext"
398
+ ],
399
+ namedColors: [
400
+ "aliceblue",
401
+ "antiquewhite",
402
+ "aqua",
403
+ "aquamarine",
404
+ "azure",
405
+ "beige",
406
+ "bisque",
407
+ "black",
408
+ "blanchedalmond",
409
+ "blue",
410
+ "blueviolet",
411
+ "brown",
412
+ "burlywood",
413
+ "cadetblue",
414
+ "chartreuse",
415
+ "chocolate",
416
+ "coral",
417
+ "cornflowerblue",
418
+ "cornsilk",
419
+ "crimson",
420
+ "cyan",
421
+ "darkblue",
422
+ "darkcyan",
423
+ "darkgoldenrod",
424
+ "darkgray",
425
+ "darkgreen",
426
+ "darkgrey",
427
+ "darkkhaki",
428
+ "darkmagenta",
429
+ "darkolivegreen",
430
+ "darkorange",
431
+ "darkorchid",
432
+ "darkred",
433
+ "darksalmon",
434
+ "darkseagreen",
435
+ "darkslateblue",
436
+ "darkslategray",
437
+ "darkslategrey",
438
+ "darkturquoise",
439
+ "darkviolet",
440
+ "deeppink",
441
+ "deepskyblue",
442
+ "dimgray",
443
+ "dimgrey",
444
+ "dodgerblue",
445
+ "firebrick",
446
+ "floralwhite",
447
+ "forestgreen",
448
+ "fuchsia",
449
+ "gainsboro",
450
+ "ghostwhite",
451
+ "gold",
452
+ "goldenrod",
453
+ "gray",
454
+ "green",
455
+ "greenyellow",
456
+ "grey",
457
+ "honeydew",
458
+ "hotpink",
459
+ "indianred",
460
+ "indigo",
461
+ "ivory",
462
+ "khaki",
463
+ "lavender",
464
+ "lavenderblush",
465
+ "lawngreen",
466
+ "lemonchiffon",
467
+ "lightblue",
468
+ "lightcoral",
469
+ "lightcyan",
470
+ "lightgoldenrodyellow",
471
+ "lightgray",
472
+ "lightgreen",
473
+ "lightgrey",
474
+ "lightpink",
475
+ "lightsalmon",
476
+ "lightseagreen",
477
+ "lightskyblue",
478
+ "lightslategray",
479
+ "lightslategrey",
480
+ "lightsteelblue",
481
+ "lightyellow",
482
+ "lime",
483
+ "limegreen",
484
+ "linen",
485
+ "magenta",
486
+ "maroon",
487
+ "mediumaquamarine",
488
+ "mediumblue",
489
+ "mediumorchid",
490
+ "mediumpurple",
491
+ "mediumseagreen",
492
+ "mediumslateblue",
493
+ "mediumspringgreen",
494
+ "mediumturquoise",
495
+ "mediumvioletred",
496
+ "midnightblue",
497
+ "mintcream",
498
+ "mistyrose",
499
+ "moccasin",
500
+ "navajowhite",
501
+ "navy",
502
+ "oldlace",
503
+ "olive",
504
+ "olivedrab",
505
+ "orange",
506
+ "orangered",
507
+ "orchid",
508
+ "palegoldenrod",
509
+ "palegreen",
510
+ "paleturquoise",
511
+ "palevioletred",
512
+ "papayawhip",
513
+ "peachpuff",
514
+ "peru",
515
+ "pink",
516
+ "plum",
517
+ "powderblue",
518
+ "purple",
519
+ "rebeccapurple",
520
+ "red",
521
+ "rosybrown",
522
+ "royalblue",
523
+ "saddlebrown",
524
+ "salmon",
525
+ "sandybrown",
526
+ "seagreen",
527
+ "seashell",
528
+ "sienna",
529
+ "silver",
530
+ "skyblue",
531
+ "slateblue",
532
+ "slategray",
533
+ "slategrey",
534
+ "snow",
535
+ "springgreen",
536
+ "steelblue",
537
+ "tan",
538
+ "teal",
539
+ "thistle",
540
+ "tomato",
541
+ "turquoise",
542
+ "violet",
543
+ "wheat",
544
+ "white",
545
+ "whitesmoke",
546
+ "yellow",
547
+ "yellowgreen"
548
+ ],
549
+ spotifyTypes: [
550
+ "track",
551
+ "album",
552
+ "playlist",
553
+ "episode",
554
+ "show",
555
+ "artist"
556
+ ]
557
+ };
558
+ // src/values.ts
559
+ const { limits: limits$1 } = VIVE_PROFILE;
560
+ const SCHEME = /^([a-z][a-z0-9+.-]*):/i;
561
+ const HEX = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
562
+ const RGB = /^rgba?\([\t\n\f\r ]*([0-9]{1,3})[\t\n\f\r ]*,[\t\n\f\r ]*([0-9]{1,3})[\t\n\f\r ]*,[\t\n\f\r ]*([0-9]{1,3})[\t\n\f\r ]*(?:,[\t\n\f\r ]*([0-9.]+%?)[\t\n\f\r ]*)?\)$/i;
563
+ const HSL = /^hsla?\([\t\n\f\r ]*[0-9]{1,3}(?:\.[0-9]+)?(?:deg)?[\t\n\f\r ]*,?[\t\n\f\r ]*[0-9]{1,3}(?:\.[0-9]+)?%[\t\n\f\r ]*,?[\t\n\f\r ]*[0-9]{1,3}(?:\.[0-9]+)?%[\t\n\f\r ]*(?:[,/][\t\n\f\r ]*([0-9.]+%?)[\t\n\f\r ]*)?\)$/i;
564
+ const PIXELS = /^([0-9]{1,5})px$/;
565
+ const POINTS = /^([0-9]{1,2})(?:\.([05]))?pt$/;
566
+ const FAMILY_PART = /^(?:'[A-Za-z][A-Za-z0-9 -]*'|[A-Za-z][A-Za-z0-9 -]*)$/;
567
+ const MAX_FAMILY_BYTES = 64;
568
+ const DIGITS = /^[0-9]{1,5}$/;
569
+ const LANGUAGE = /^[a-z0-9][a-z0-9+#.-]{0,31}$/i;
570
+ const HTTPS_URL = /^https:\/\/[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[0-9]{1,5})?(?:[/?#][\x21-\x7e]*)?$/i;
571
+ const BASE64_IMAGE = /^data:image\/([a-z]+);base64,[A-Za-z0-9+/]+={0,2}$/;
572
+ const URL_FORBIDDEN = /["'<>\\`]/;
573
+ const BANNED_STYLE = [
574
+ "\\",
575
+ "/*",
576
+ "url(",
577
+ "expression",
578
+ "@",
579
+ "!important"
580
+ ];
581
+ const NAMED_COLORS = new Set(VIVE_PROFILE.namedColors);
582
+ const REJECTED_COLORS = new Set(VIVE_PROFILE.colorKeywordsRejected);
583
+ const SPACE = /[\t\n\f\r ]+/g;
584
+ const MENTION_ID = new RegExp(`^(?!.*\\.\\.)[A-Za-z0-9_][A-Za-z0-9_.:@-]{0,${limits$1.maxMentionId - 1}}$`);
585
+ const COMMENT_ID = new RegExp(`^[A-Za-z0-9_-]{1,${limits$1.maxCommentId}}$`);
586
+ const CHANGE_ID = new RegExp(`^[A-Za-z0-9_-]{1,${limits$1.maxChangeId}}$`);
587
+ const CHANGE_TIME = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{3})?Z$/;
588
+ const BLANK = /^[\t\n\r \u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*$/;
589
+ const byteLength = (value) => Buffer.byteLength(value, "utf8");
590
+ const lowerAscii = (value) => value.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
591
+ const trimAscii = (value) => value.replace(/^[\t\n\f\r ]+|[\t\n\f\r ]+$/g, "");
592
+ function cleanText(value, max = limits$1.maxTextAttributeLength) {
593
+ const result = [];
594
+ for (const character of value) {
595
+ if (result.length >= max) break;
596
+ const code = character.codePointAt(0) ?? 0;
597
+ result.push(code < 32 || code >= 127 && code <= 159 ? " " : character);
598
+ }
599
+ return result.join("");
600
+ }
601
+ const isHidden = (code) => code <= 31 || code >= 127 && code <= 159 || code >= 8203 && code <= 8207 || code >= 8234 && code <= 8238 || code >= 8294 && code <= 8297 || code === 65279;
602
+ const isMentionId = (value) => MENTION_ID.test(value);
603
+ const isCommentId = (value) => COMMENT_ID.test(value);
604
+ const isChangeId = (value) => CHANGE_ID.test(value);
605
+ const isLineBreaker = (code) => code < 32 || code === 127 || code >= 8234 && code <= 8238 || code >= 8294 && code <= 8297 || code >= 55296 && code <= 57343;
606
+ function isChangeLine(value, max) {
607
+ let count = 0;
608
+ for (const character of value) {
609
+ if (isLineBreaker(character.codePointAt(0) ?? 0)) return false;
610
+ count++;
611
+ }
612
+ return count <= max && !BLANK.test(value);
613
+ }
614
+ const isAuthorId = (value) => isChangeLine(value, limits$1.maxAuthorId);
615
+ const isAuthorName = (value) => isChangeLine(value, limits$1.maxAuthorName);
616
+ function isChangeTime(value) {
617
+ const match = CHANGE_TIME.exec(value);
618
+ if (!match) return false;
619
+ const [year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0] = match.slice(1).map(Number);
620
+ const date = new Date(Date.UTC(year, month - 1, day));
621
+ date.setUTCFullYear(year);
622
+ return year >= 1 && date.getUTCMonth() === month - 1 && date.getUTCDate() === day && hour <= 23 && minute <= 59 && second <= 59;
623
+ }
624
+ function cleanMentionLabel(value) {
625
+ let result = "";
626
+ for (const character of value) {
627
+ const code = character.codePointAt(0) ?? 0;
628
+ if (code === 9 || code === 10 || code === 13) result += " ";
629
+ else if (!isHidden(code)) result += character;
630
+ }
631
+ const label = trimAscii(trimAscii(result.replace(SPACE, " ")).replace(/^@+/, ""));
632
+ return trimAscii(Array.from(label).slice(0, limits$1.maxMentionLabel).join(""));
633
+ }
634
+ function cleanLatex(value) {
635
+ let result = "";
636
+ for (const character of value) {
637
+ const code = character.codePointAt(0) ?? 0;
638
+ if (code === 9 || code === 10 || !isHidden(code)) result += character;
639
+ }
640
+ const latex = trimAscii(result);
641
+ if (latex === "" || Array.from(latex).length > limits$1.maxMathLength) return null;
642
+ let depth = 0;
643
+ for (const character of latex) {
644
+ if (character === "{") depth++;
645
+ else if (character === "}") depth = Math.max(0, depth - 1);
646
+ if (depth > limits$1.maxMathDepth) return null;
647
+ }
648
+ return latex;
649
+ }
650
+ function takeCodePoints(value, budget) {
651
+ if (budget.left <= 0) return "";
652
+ const kept = Array.from(value).slice(0, budget.left);
653
+ budget.left -= kept.length;
654
+ return kept.join("");
655
+ }
656
+ function cleanInteger(value, min, max) {
657
+ if (value === void 0 || !DIGITS.test(value)) return null;
658
+ const number = Number(value);
659
+ return number >= min && number <= max ? number : null;
660
+ }
661
+ function cleanLanguage(value) {
662
+ return value !== void 0 && LANGUAGE.test(value) ? lowerAscii(value) : null;
663
+ }
664
+ function cleanColWidth(value) {
665
+ if (value === void 0) return null;
666
+ const parts = value.split(",");
667
+ if (parts.length > limits$1.maxSpan) return null;
668
+ return parts.every((part) => cleanInteger(part, 1, 9999) !== null) ? value : null;
669
+ }
670
+ const hexPair = (value) => Math.min(255, value).toString(16).padStart(2, "0");
671
+ function expandHex(hex) {
672
+ const digits = lowerAscii(hex.slice(1));
673
+ if (digits.length > 4) return `#${digits}`;
674
+ return `#${[...digits].map((digit) => digit + digit).join("")}`;
675
+ }
676
+ function alphaOf(raw) {
677
+ if (raw === void 0) return 1;
678
+ const value = Number.parseFloat(raw);
679
+ return raw.endsWith("%") ? value / 100 : value;
680
+ }
681
+ function cleanColor(input) {
682
+ const value = trimAscii(input);
683
+ const lower = lowerAscii(value);
684
+ if (value === "" || REJECTED_COLORS.has(lower)) return null;
685
+ if (HEX.test(value)) {
686
+ const hex = expandHex(value);
687
+ return hex.length === 9 && hex.endsWith("00") ? null : hex;
688
+ }
689
+ const rgb = RGB.exec(value);
690
+ if (rgb) {
691
+ const alpha = alphaOf(rgb[4]);
692
+ if (!(alpha > 0)) return null;
693
+ const [red, green, blue] = [
694
+ rgb[1],
695
+ rgb[2],
696
+ rgb[3]
697
+ ].map((part) => Number(part));
698
+ const hex = `#${hexPair(red ?? 0)}${hexPair(green ?? 0)}${hexPair(blue ?? 0)}`;
699
+ return alpha >= 1 ? hex : `${hex}${hexPair(Math.round(alpha * 255))}`;
700
+ }
701
+ const hsl = HSL.exec(value);
702
+ if (hsl) return alphaOf(hsl[1]) > 0 ? lower.replace(SPACE, " ") : null;
703
+ return NAMED_COLORS.has(lower) ? lower : null;
704
+ }
705
+ const familyKey = (value) => lowerAscii(value).replace(/["']/g, "").split(",").map((part) => trimAscii(part).replace(SPACE, " ")).join(",");
706
+ const leadKey = (key) => `\n${key.split(",")[0] ?? ""}`;
707
+ const findFamily = (fonts, value) => {
708
+ const key = familyKey(value);
709
+ return fonts.get(key) ?? fonts.get(leadKey(key)) ?? null;
710
+ };
711
+ function fontFamilyMap(list) {
712
+ const map = /* @__PURE__ */ new Map();
713
+ for (const entry of list) {
714
+ const parts = typeof entry === "string" ? entry.split(",").map(trimAscii) : [];
715
+ if (parts.length === 0 || byteLength(entry) > MAX_FAMILY_BYTES || !parts.every((part) => FAMILY_PART.test(part))) throw new TypeError("Each font family must be a comma-separated list of plain family names.");
716
+ const canonical = parts.join(", ");
717
+ const key = familyKey(canonical);
718
+ map.set(key, canonical);
719
+ const first = leadKey(key);
720
+ if (!map.has(first)) map.set(first, canonical);
721
+ }
722
+ return map;
723
+ }
724
+ const DEFAULT_FONT_FAMILIES = fontFamilyMap(VIVE_PROFILE.fontFamilies);
725
+ function cleanFontSize(value) {
726
+ const step = lowerAscii(value);
727
+ if (VIVE_PROFILE.fontSizes.includes(step)) return step;
728
+ const points = POINTS.exec(step);
729
+ if (!points) return null;
730
+ const halves = Number(points[1]) * 2 + (points[2] === "5" ? 1 : 0);
731
+ if (halves < limits$1.minFontSizePt * 2 || halves > limits$1.maxFontSizePt * 2) return null;
732
+ return `${Math.floor(halves / 2)}${halves % 2 === 1 ? ".5" : ""}pt`;
733
+ }
734
+ function styleValue(property, value, fonts) {
735
+ if (property === "text-align") {
736
+ const align = lowerAscii(value);
737
+ return VIVE_PROFILE.textAlign.includes(align) ? align : null;
738
+ }
739
+ if (property === "vertical-align") {
740
+ const align = lowerAscii(value);
741
+ return VIVE_PROFILE.verticalAlign.includes(align) ? align : null;
742
+ }
743
+ if (property === "color" || property === "background-color" || property === "--vive-table-border-color") return cleanColor(value);
744
+ if (property === "font-size") return cleanFontSize(value);
745
+ if (property === "margin-inline-start") {
746
+ const step = lowerAscii(value);
747
+ return VIVE_PROFILE.indents.includes(step) ? step : null;
748
+ }
749
+ if (property === "line-height") return VIVE_PROFILE.lineHeights.includes(value) ? value : null;
750
+ if (property === "list-style-type") {
751
+ const style = lowerAscii(value);
752
+ return VIVE_PROFILE.bulletStyles.includes(style) ? style : null;
753
+ }
754
+ if (property === "font-family") return findFamily(fonts, value);
755
+ const pixels = PIXELS.exec(value);
756
+ const number = pixels ? Number(pixels[1]) : 0;
757
+ const max = property === "height" ? limits$1.maxRowHeight : limits$1.maxTableWidth;
758
+ return number > 0 && number <= max ? `${number}px` : null;
759
+ }
760
+ function cleanStyle(value, allowed, fonts = DEFAULT_FONT_FAMILIES) {
761
+ if (byteLength(value) > allowed.length * (limits$1.maxStyleValueLength + 32)) return null;
762
+ const lower = lowerAscii(value);
763
+ if (BANNED_STYLE.some((banned) => lower.includes(banned))) return null;
764
+ const result = /* @__PURE__ */ new Map();
765
+ for (const declaration of value.split(";")) {
766
+ const colon = declaration.indexOf(":");
767
+ if (colon < 0) continue;
768
+ const property = lowerAscii(trimAscii(declaration.slice(0, colon)));
769
+ const raw = trimAscii(declaration.slice(colon + 1));
770
+ if (!allowed.includes(property) || result.has(property)) continue;
771
+ if (byteLength(raw) > limits$1.maxStyleValueLength) continue;
772
+ const clean = styleValue(property, raw, fonts);
773
+ if (clean !== null) result.set(property, clean);
774
+ }
775
+ return result.size > 0 ? [...result].map(([property, clean]) => `${property}: ${clean}`).join("; ") : null;
776
+ }
777
+ function trimEdges(value) {
778
+ let start = 0;
779
+ let end = value.length;
780
+ while (start < end && value.charCodeAt(start) <= 32) start++;
781
+ while (end > start && value.charCodeAt(end - 1) <= 32) end--;
782
+ return value.slice(start, end);
783
+ }
784
+ const hasControl = (value) => {
785
+ for (let index = 0; index < value.length; index++) {
786
+ const code = value.charCodeAt(index);
787
+ if (code < 32 || code >= 127 && code <= 159) return true;
788
+ }
789
+ return false;
790
+ };
791
+ function cleanHref(input) {
792
+ if (byteLength(input) > limits$1.maxAttributeLength) return null;
793
+ const value = trimEdges(input.replace(/[\t\n\r]/g, ""));
794
+ if (value === "" || hasControl(value) || value.includes("\\") || value.startsWith("//")) return null;
795
+ const found = SCHEME.exec(value)?.[1];
796
+ if (found === void 0) return value;
797
+ const scheme = lowerAscii(found);
798
+ if (!VIVE_PROFILE.linkProtocols.includes(scheme)) return null;
799
+ if ((scheme === "http" || scheme === "https") && !/^https?:\/\/[^/]/i.test(value)) return null;
800
+ return value;
801
+ }
802
+ function cleanImageSrc(input, policy) {
803
+ const value = trimEdges(input.replace(/[\t\n\r]/g, ""));
804
+ if (value === "" || hasControl(value)) return null;
805
+ const base64 = BASE64_IMAGE.exec(value);
806
+ if (base64) return policy.allowBase64 && byteLength(value) <= limits$1.maxImageSrcLength && VIVE_PROFILE.image.base64Types.includes(base64[1] ?? "") ? value : null;
807
+ if (byteLength(value) > limits$1.maxUrlLength || URL_FORBIDDEN.test(value)) return null;
808
+ const candidate = value.startsWith("//") ? `https:${value}` : /^http:\/\//i.test(value) ? `https://${value.slice(7)}` : value;
809
+ if (HTTPS_URL.test(candidate)) return candidate;
810
+ if (SCHEME.exec(value) || value.startsWith("//") || !policy.allowRelative) return null;
811
+ return /^[\x21-\x7e ]+$/.test(value) ? value.replaceAll(" ", "%20") : null;
812
+ }
813
+ // src/embed.ts
814
+ const IDS = {
815
+ youtube: /^[A-Za-z0-9_-]{11}$/,
816
+ vimeo: /^[1-9][0-9]{0,11}$/,
817
+ spotify: new RegExp(`^(?:${VIVE_PROFILE.spotifyTypes.join("|")}):[A-Za-z0-9]{22}$`)
818
+ };
819
+ const VIMEO_HASH = /^[0-9a-f]{8,20}$/;
820
+ function cleanEmbed(attributes) {
821
+ const provider = attributes.get("data-embed") ?? "";
822
+ const rule = Object.hasOwn(VIVE_PROFILE.embedProviders, provider) ? VIVE_PROFILE.embedProviders[provider] : void 0;
823
+ const pattern = IDS[provider];
824
+ const id = attributes.get("data-id") ?? "";
825
+ if (!rule || !pattern?.test(id)) return null;
826
+ const hash = attributes.get("data-hash");
827
+ const title = attributes.get("data-title");
828
+ const cleanTitle = title === void 0 ? null : cleanText(trimAscii(cleanText(title, Number.POSITIVE_INFINITY)), VIVE_PROFILE.limits.maxEmbedTitle) || null;
829
+ return {
830
+ provider,
831
+ rule,
832
+ id,
833
+ hash: provider === "vimeo" && hash !== void 0 && VIMEO_HASH.test(hash) ? hash : null,
834
+ start: provider === "spotify" ? null : cleanInteger(attributes.get("data-start"), 1, VIVE_PROFILE.limits.maxEmbedStart),
835
+ title: cleanTitle
836
+ };
837
+ }
838
+ function embedSrc(embed) {
839
+ const base = `https://${embed.rule.host}`;
840
+ if (embed.provider === "youtube") return `${base}/embed/${embed.id}${embed.start ? `?start=${embed.start}` : ""}`;
841
+ if (embed.provider === "vimeo") {
842
+ const hash = embed.hash ? `&h=${embed.hash}` : "";
843
+ const start = embed.start ? `#t=${embed.start}s` : "";
844
+ return `${base}/video/${embed.id}?dnt=1${hash}${start}`;
845
+ }
846
+ return `${base}/embed/${embed.id.replace(":", "/")}`;
847
+ }
848
+ function embedWatchUrl(embed) {
849
+ if (embed.provider === "youtube") return `https://www.youtube.com/watch?v=${embed.id}${embed.start ? `&t=${embed.start}s` : ""}`;
850
+ if (embed.provider === "vimeo") {
851
+ const hash = embed.hash ? `/${embed.hash}` : "";
852
+ return `https://vimeo.com/${embed.id}${hash}${embed.start ? `#t=${embed.start}s` : ""}`;
853
+ }
854
+ return `https://open.spotify.com/${embed.id.replace(":", "/")}`;
855
+ }
856
+ function wrapperAttributes(embed) {
857
+ const result = [
858
+ ["class", "vive-embed"],
859
+ ["data-embed", embed.provider],
860
+ ["data-id", embed.id]
861
+ ];
862
+ if (embed.hash) result.push(["data-hash", embed.hash]);
863
+ if (embed.start) result.push(["data-start", String(embed.start)]);
864
+ if (embed.title) result.push(["data-title", embed.title]);
865
+ return result;
866
+ }
867
+ function iframeAttributes(embed) {
868
+ const { rule } = embed;
869
+ const height = (rule.compactTypes?.some((type) => embed.id.startsWith(`${type}:`)) ?? false) && rule.compactHeight ? rule.compactHeight : rule.height;
870
+ return [
871
+ ["src", embedSrc(embed)],
872
+ ["title", embed.title ?? rule.label],
873
+ ["width", String(rule.width)],
874
+ ["height", String(height)],
875
+ ["style", rule.fluid ? `width: 100%; height: auto; aspect-ratio: ${rule.width} / ${height}; border: 0` : `width: 100%; height: ${height}px; border: 0`],
876
+ ["loading", "lazy"],
877
+ ["referrerpolicy", "strict-origin-when-cross-origin"],
878
+ ["sandbox", rule.sandbox],
879
+ ["allow", rule.allow],
880
+ ["allowfullscreen", ""]
881
+ ];
882
+ }
883
+ // src/guard.ts
884
+ const STATES = 10;
885
+ const END = -1;
886
+ function isSpace(code) {
887
+ return code === 32 || code === 9 || code === 10 || code === 12 || code === 13;
888
+ }
889
+ function isAsciiLetter(code) {
890
+ return code >= 65 && code <= 90 || code >= 97 && code <= 122;
891
+ }
892
+ const move = (state, added = 0) => state * 2 + added;
893
+ function transition(state, code) {
894
+ switch (state) {
895
+ case 0:
896
+ if (isSpace(code)) return move(1);
897
+ if (code === 47) return move(9);
898
+ return code === 62 ? END : move(0);
899
+ case 1:
900
+ if (isSpace(code)) return move(1);
901
+ if (code === 47 || code === 62) return transition(3, code);
902
+ return move(2, 1);
903
+ case 2:
904
+ if (isSpace(code) || code === 47 || code === 62) return transition(3, code);
905
+ return code === 61 ? move(4) : move(2);
906
+ case 3:
907
+ if (isSpace(code)) return move(3);
908
+ if (code === 47) return move(9);
909
+ if (code === 61) return move(4);
910
+ return code === 62 ? END : move(2, 1);
911
+ case 4:
912
+ if (isSpace(code)) return move(4);
913
+ if (code === 34) return move(5);
914
+ if (code === 39) return move(6);
915
+ return code === 62 ? END : move(7);
916
+ case 5: return move(code === 34 ? 8 : 5);
917
+ case 6: return move(code === 39 ? 8 : 6);
918
+ case 7:
919
+ if (isSpace(code)) return move(1);
920
+ return code === 62 ? END : move(7);
921
+ case 8:
922
+ if (isSpace(code)) return move(1);
923
+ if (code === 47) return move(9);
924
+ return code === 62 ? END : transition(1, code);
925
+ case 9: return code === 62 ? END : transition(1, code);
926
+ }
927
+ }
928
+ function opensTag(input, index) {
929
+ if (!isAsciiLetter(input.charCodeAt(index))) return false;
930
+ const previous = input.charCodeAt(index - 1);
931
+ return previous === 60 || previous === 47 && input.charCodeAt(index - 2) === 60;
932
+ }
933
+ function hasCrowdedTag(input, maxAttributes) {
934
+ let counts = new Int32Array(STATES).fill(END);
935
+ let next = new Int32Array(STATES);
936
+ const ahead = (/* @__PURE__ */ new Int32Array(3)).fill(-1);
937
+ let active = false;
938
+ for (let index = 0; index < input.length; index++) {
939
+ if (!active) {
940
+ const open = input.indexOf("<", index);
941
+ if (open === -1) return false;
942
+ index = open;
943
+ }
944
+ const code = input.charCodeAt(index);
945
+ if (opensTag(input, index)) counts[0] = Math.max(counts[0] ?? END, 0);
946
+ next.fill(END);
947
+ for (let state = 0; state < STATES; state++) {
948
+ const count = counts[state] ?? END;
949
+ if (count === END) continue;
950
+ const target = transition(state, code);
951
+ if (target === END) continue;
952
+ const total = count + (target & 1);
953
+ if (total > maxAttributes) return true;
954
+ const reached = target >> 1;
955
+ if (total > (next[reached] ?? END)) next[reached] = total;
956
+ }
957
+ [counts, next] = [next, counts];
958
+ active = counts.some((count) => count !== END) || code === 60 || code === 47 && input.charCodeAt(index - 1) === 60;
959
+ const skip = quotedSkip(input, index, code, counts, ahead);
960
+ if (skip === null) return false;
961
+ index = skip;
962
+ }
963
+ return false;
964
+ }
965
+ function nextAt(input, char, from, ahead, slot) {
966
+ if ((ahead[slot] ?? -1) < from) {
967
+ const found = input.indexOf(char, from);
968
+ ahead[slot] = found === -1 ? input.length : found;
969
+ }
970
+ return ahead[slot] ?? input.length;
971
+ }
972
+ function quotedSkip(input, index, code, counts, ahead) {
973
+ if (code === 60 || code === 47) return index;
974
+ let quote = null;
975
+ for (let state = 0; state < STATES; state++) {
976
+ if ((counts[state] ?? END) === END) continue;
977
+ if (quote !== null || state !== 5 && state !== 6) return index;
978
+ quote = state === 5 ? "\"" : "'";
979
+ }
980
+ if (quote === null) return index;
981
+ const close = nextAt(input, quote, index + 1, ahead, quote === "\"" ? 0 : 1);
982
+ const open = nextAt(input, "<", index + 1, ahead, 2);
983
+ if (close === input.length && open === input.length) return null;
984
+ return Math.min(close, open) - 1;
985
+ }
986
+ function guardedTreeAdapter(maxElements, maxNesting, onLimit) {
987
+ let created = 0;
988
+ const owners = /* @__PURE__ */ new WeakMap();
989
+ const checkDepth = (node) => {
990
+ if (!defaultTreeAdapter.isElementNode(node)) return;
991
+ let depth = 0;
992
+ let current = node;
993
+ while (current) {
994
+ depth++;
995
+ if (depth > maxNesting) onLimit();
996
+ current = ("parentNode" in current ? current.parentNode : null) ?? owners.get(current) ?? null;
997
+ }
998
+ };
999
+ const insertBefore = (parentNode, newNode, referenceNode) => {
1000
+ const children = parentNode.childNodes;
1001
+ children.splice(children.lastIndexOf(referenceNode), 0, newNode);
1002
+ newNode.parentNode = parentNode;
1003
+ checkDepth(newNode);
1004
+ };
1005
+ return {
1006
+ ...defaultTreeAdapter,
1007
+ createElement(tagName, namespaceURI, attrs) {
1008
+ created++;
1009
+ if (created > maxElements) onLimit();
1010
+ return defaultTreeAdapter.createElement(tagName, namespaceURI, attrs);
1011
+ },
1012
+ appendChild(parentNode, newNode) {
1013
+ defaultTreeAdapter.appendChild(parentNode, newNode);
1014
+ checkDepth(newNode);
1015
+ },
1016
+ insertBefore,
1017
+ insertTextBefore(parentNode, text, referenceNode) {
1018
+ const children = parentNode.childNodes;
1019
+ const previous = children[children.lastIndexOf(referenceNode) - 1];
1020
+ if (previous && defaultTreeAdapter.isTextNode(previous)) previous.value += text;
1021
+ else insertBefore(parentNode, {
1022
+ nodeName: "#text",
1023
+ value: text,
1024
+ parentNode: null
1025
+ }, referenceNode);
1026
+ },
1027
+ setTemplateContent(templateElement, contentElement) {
1028
+ defaultTreeAdapter.setTemplateContent(templateElement, contentElement);
1029
+ owners.set(contentElement, templateElement);
1030
+ }
1031
+ };
1032
+ }
1033
+ // src/sanitize.ts
1034
+ var SanitizeError = class extends Error {
1035
+ code;
1036
+ constructor(code, message) {
1037
+ super(message);
1038
+ this.name = "SanitizeError";
1039
+ this.code = code;
1040
+ }
1041
+ };
1042
+ const { limits } = VIVE_PROFILE;
1043
+ const DROP = new Set(VIVE_PROFILE.dropWithContent);
1044
+ const FOOTNOTE_ELEMENTS = new Set(VIVE_PROFILE.footnoteElements);
1045
+ const BREAK_BLOCKS = /* @__PURE__ */ new Set([
1046
+ "p",
1047
+ "h1",
1048
+ "h2",
1049
+ "h3",
1050
+ "h4",
1051
+ "h5",
1052
+ "h6"
1053
+ ]);
1054
+ const ROOT = {
1055
+ parent: "",
1056
+ taskList: false,
1057
+ taskItem: false,
1058
+ inLink: false,
1059
+ inScript: false,
1060
+ inFontSize: false,
1061
+ footnote: null
1062
+ };
1063
+ const BODY = defaultTreeAdapter.createElement("body", html.NS.HTML, []);
1064
+ function attributesOf(element) {
1065
+ const result = /* @__PURE__ */ new Map();
1066
+ for (const attribute of element.attrs) {
1067
+ const max = element.tagName === "img" && attribute.name === "src" ? limits.maxImageSrcLength : limits.maxAttributeLength;
1068
+ if (attribute.namespace || byteLength(attribute.value) > max) continue;
1069
+ if (!result.has(attribute.name)) result.set(attribute.name, attribute.value);
1070
+ }
1071
+ return result;
1072
+ }
1073
+ function append(target, tag, attributes) {
1074
+ const element = defaultTreeAdapter.createElement(tag, html.NS.HTML, attributes.map(([name, value]) => ({
1075
+ name,
1076
+ value
1077
+ })));
1078
+ defaultTreeAdapter.appendChild(target, element);
1079
+ return element;
1080
+ }
1081
+ function styleOf(tag, source, fonts, without = null) {
1082
+ const allowed = VIVE_PROFILE.elements[tag]?.styles?.filter((style) => style !== without);
1083
+ const style = source.get("style");
1084
+ if (!allowed || style === void 0) return [];
1085
+ const clean = cleanStyle(style, allowed, fonts);
1086
+ return clean === null ? [] : [["style", clean]];
1087
+ }
1088
+ function hasStyle(attributes, property) {
1089
+ return attributes?.some(([name, value]) => name === "style" && value.includes(`${property}:`)) ?? false;
1090
+ }
1091
+ function textAttribute(source, name) {
1092
+ const value = source.get(name);
1093
+ return value === void 0 ? [] : [[name, cleanText(value)]];
1094
+ }
1095
+ function linkAttributes(source) {
1096
+ const result = [["rel", VIVE_PROFILE.linkRel]];
1097
+ const href = source.get("href");
1098
+ const clean = href === void 0 ? null : cleanHref(href);
1099
+ if (clean !== null) result.push(["href", clean]);
1100
+ result.push(...textAttribute(source, "title"));
1101
+ if (source.get("target") === "_blank") result.push(["target", "_blank"]);
1102
+ return result;
1103
+ }
1104
+ function imageAttributes(source, policy) {
1105
+ const raw = source.get("src");
1106
+ const src = raw === void 0 ? null : cleanImageSrc(raw, policy);
1107
+ if (src === null) return null;
1108
+ const result = [["src", src]];
1109
+ result.push(...textAttribute(source, "alt"), ...textAttribute(source, "title"));
1110
+ for (const name of ["width", "height"]) {
1111
+ const size = cleanInteger(source.get(name), 1, limits.maxImageSize);
1112
+ if (size !== null) result.push([name, String(size)]);
1113
+ }
1114
+ const { loading, decoding, referrerpolicy } = VIVE_PROFILE.image;
1115
+ result.push(["loading", loading], ["decoding", decoding], ["referrerpolicy", referrerpolicy]);
1116
+ return result;
1117
+ }
1118
+ function cellAttributes(tag, source, fonts) {
1119
+ const result = [];
1120
+ for (const name of ["colspan", "rowspan"]) {
1121
+ const span = cleanInteger(source.get(name), 2, limits.maxSpan);
1122
+ if (span !== null) result.push([name, String(span)]);
1123
+ }
1124
+ const widths = cleanColWidth(source.get("data-colwidth"));
1125
+ if (widths !== null) result.push(["data-colwidth", widths]);
1126
+ result.push(...styleOf(tag, source, fonts));
1127
+ return result;
1128
+ }
1129
+ function enumAttribute(source, name, allowed) {
1130
+ const value = lowerAscii(trimAscii(source.get(name) ?? ""));
1131
+ return allowed.includes(value) ? [[name, value]] : [];
1132
+ }
1133
+ function tableAttributes(source, fonts) {
1134
+ const width = enumAttribute(source, "data-width", VIVE_PROFILE.tableWidths);
1135
+ const striped = lowerAscii(trimAscii(source.get("data-striped") ?? "")) === "true";
1136
+ return [
1137
+ ...width,
1138
+ ...enumAttribute(source, "data-align", VIVE_PROFILE.tableAlign),
1139
+ ...enumAttribute(source, "data-border", VIVE_PROFILE.tableBorders),
1140
+ ...striped ? [["data-striped", "true"]] : [],
1141
+ ...styleOf("table", source, fonts, width.length > 0 ? "width" : null)
1142
+ ];
1143
+ }
1144
+ function embed(source, node, target) {
1145
+ const data = cleanEmbed(source);
1146
+ if (!data) return;
1147
+ const wrapper = append(target, "div", wrapperAttributes(data));
1148
+ if (node.childNodes.some((child) => defaultTreeAdapter.isElementNode(child) && child.tagName === "a")) {
1149
+ const link = append(wrapper, "a", [["href", embedWatchUrl(data)], ["rel", "noopener noreferrer"]]);
1150
+ defaultTreeAdapter.insertText(link, data.title ?? data.rule.label);
1151
+ } else append(wrapper, "iframe", iframeAttributes(data));
1152
+ }
1153
+ function insertText(target, value, context) {
1154
+ const text = context.footnote ? takeCodePoints(value, context.footnote) : value;
1155
+ if (text) defaultTreeAdapter.insertText(target, text);
1156
+ }
1157
+ function textOf(node, depth) {
1158
+ let text = "";
1159
+ for (const child of node.childNodes) if (defaultTreeAdapter.isTextNode(child)) text += child.value;
1160
+ else if (defaultTreeAdapter.isElementNode(child) && depth < limits.maxDepth && child.namespaceURI === html.NS.HTML && !DROP.has(child.tagName)) text += textOf(child, depth + 1);
1161
+ return text;
1162
+ }
1163
+ function mention(id, node, target, depth, context) {
1164
+ const text = textOf(node, depth);
1165
+ if (context.inLink || context.footnote || !isMentionId(id)) {
1166
+ insertText(target, text, context);
1167
+ return;
1168
+ }
1169
+ const created = append(target, "span", [["class", VIVE_PROFILE.mentionClass], ["data-mention", id]]);
1170
+ defaultTreeAdapter.insertText(created, `@${cleanMentionLabel(text) || id}`);
1171
+ }
1172
+ function math(tag, node, target, depth, context) {
1173
+ const text = textOf(node, depth);
1174
+ const latex = context.inLink || context.footnote ? null : cleanLatex(text);
1175
+ if (latex === null) {
1176
+ insertText(target, text, context);
1177
+ return;
1178
+ }
1179
+ const created = append(target, tag, [["data-math", tag === "span" ? "inline" : "block"]]);
1180
+ defaultTreeAdapter.insertText(created, latex);
1181
+ }
1182
+ function footnote(node, target, depth, context, settings) {
1183
+ if (context.inLink || context.footnote) {
1184
+ walk(node, target, depth, context, settings);
1185
+ return;
1186
+ }
1187
+ walk(node, append(target, "sup", [["data-footnote", ""]]), depth, {
1188
+ ...ROOT,
1189
+ parent: "sup",
1190
+ footnote: { left: limits.maxFootnoteLength }
1191
+ }, settings);
1192
+ }
1193
+ function changeAttributes(source) {
1194
+ const id = source.get("data-vive-change") ?? "";
1195
+ const author = source.get("data-author") ?? "";
1196
+ const name = source.get("data-name") ?? "";
1197
+ const time = source.get("data-time") ?? "";
1198
+ return isChangeId(id) && isAuthorId(author) && isAuthorName(name) && isChangeTime(time) ? [
1199
+ ["data-vive-change", id],
1200
+ ["data-author", author],
1201
+ ["data-name", name],
1202
+ ["data-time", time]
1203
+ ] : null;
1204
+ }
1205
+ function breakAttributes(source) {
1206
+ const kind = source.get("data-vive-break");
1207
+ const change = kind === "insert" || kind === "delete" ? changeAttributes(source) : null;
1208
+ return change ? [["data-vive-break", kind], ...change] : [];
1209
+ }
1210
+ function suggestion(tag, source, node, target, depth, context, settings) {
1211
+ const change = settings.suggestions === "keep" && !context.footnote ? changeAttributes(source) : null;
1212
+ if (change) {
1213
+ walk(node, append(target, tag, change), depth, {
1214
+ ...context,
1215
+ parent: tag,
1216
+ taskList: false,
1217
+ taskItem: false
1218
+ }, settings);
1219
+ return;
1220
+ }
1221
+ if (tag === "ins" === (settings.suggestions === "accept" && !context.footnote)) walk(node, target, depth, context, settings);
1222
+ }
1223
+ function walk(source, target, depth, context, settings) {
1224
+ for (const child of source.childNodes) if (defaultTreeAdapter.isTextNode(child)) insertText(target, child.value, context);
1225
+ else if (defaultTreeAdapter.isElementNode(child)) element(child, target, depth + 1, context, settings);
1226
+ }
1227
+ function element(node, target, depth, context, settings) {
1228
+ if (depth > limits.maxDepth || node.namespaceURI !== html.NS.HTML) return;
1229
+ const tag = node.tagName;
1230
+ if (DROP.has(tag)) return;
1231
+ const source = attributesOf(node);
1232
+ if ((tag === "ins" || tag === "del") && source.has("data-vive-change")) {
1233
+ suggestion(tag, source, node, target, depth, context, settings);
1234
+ return;
1235
+ }
1236
+ if (context.footnote && !FOOTNOTE_ELEMENTS.has(tag)) {
1237
+ walk(node, target, depth, context, settings);
1238
+ return;
1239
+ }
1240
+ const mentionId = source.get("data-mention");
1241
+ if (tag === "span" && mentionId !== void 0 && source.get("class") === VIVE_PROFILE.mentionClass) {
1242
+ mention(mentionId, node, target, depth, context);
1243
+ return;
1244
+ }
1245
+ const mathType = source.get("data-math");
1246
+ if (tag === "span" && mathType === "inline" || tag === "div" && mathType === "block") {
1247
+ math(tag, node, target, depth, context);
1248
+ return;
1249
+ }
1250
+ if (tag === "sup" && source.has("data-footnote")) {
1251
+ footnote(node, target, depth, context, settings);
1252
+ return;
1253
+ }
1254
+ const next = {
1255
+ parent: tag,
1256
+ taskList: false,
1257
+ taskItem: false,
1258
+ inLink: context.inLink || tag === "a",
1259
+ inScript: context.inScript,
1260
+ inFontSize: context.inFontSize,
1261
+ footnote: context.footnote
1262
+ };
1263
+ let attributes = null;
1264
+ switch (tag) {
1265
+ case "div":
1266
+ if (source.get("class") === "vive-embed" && source.has("data-embed")) {
1267
+ if (settings.embeds) embed(source, node, target);
1268
+ return;
1269
+ }
1270
+ if (source.has("data-embed-invalid")) return;
1271
+ attributes = context.taskItem ? [] : null;
1272
+ break;
1273
+ case "input":
1274
+ if (!context.taskItem || source.get("type") !== "checkbox") return;
1275
+ append(target, "input", [
1276
+ ["type", "checkbox"],
1277
+ ["disabled", ""],
1278
+ ...source.has("checked") ? [["checked", ""]] : []
1279
+ ]);
1280
+ return;
1281
+ case "ul":
1282
+ next.taskList = source.get("data-type") === "taskList";
1283
+ attributes = next.taskList ? [["data-type", "taskList"]] : styleOf("ul", source, settings.fonts);
1284
+ break;
1285
+ case "li":
1286
+ next.taskItem = context.taskList && source.get("data-type") === "taskItem";
1287
+ attributes = next.taskItem ? [["data-type", "taskItem"], ["data-checked", source.get("data-checked") === "true" ? "true" : "false"]] : [];
1288
+ break;
1289
+ case "ol": {
1290
+ const start = cleanInteger(source.get("start"), 0, limits.maxListStart);
1291
+ const type = trimAscii(source.get("type") ?? "");
1292
+ attributes = [...start !== null && start !== 1 ? [["start", String(start)]] : [], ...VIVE_PROFILE.orderedListTypes.includes(type) ? [["type", type]] : []];
1293
+ break;
1294
+ }
1295
+ case "pre": {
1296
+ const language = cleanLanguage(source.get("data-language"));
1297
+ attributes = language ? [["data-language", language]] : [];
1298
+ break;
1299
+ }
1300
+ case "code": {
1301
+ const match = /^language-(.+)$/.exec(source.get("class") ?? "");
1302
+ const language = context.parent === "pre" ? cleanLanguage(match?.[1]) : null;
1303
+ attributes = language ? [["class", `language-${language}`]] : [];
1304
+ break;
1305
+ }
1306
+ case "a":
1307
+ attributes = context.inLink ? null : linkAttributes(source);
1308
+ break;
1309
+ case "sup":
1310
+ case "sub":
1311
+ attributes = context.inScript ? null : [];
1312
+ next.inScript = true;
1313
+ break;
1314
+ case "img": {
1315
+ const image = imageAttributes(source, settings.image);
1316
+ if (image) append(target, "img", image);
1317
+ return;
1318
+ }
1319
+ case "td":
1320
+ case "th":
1321
+ attributes = cellAttributes(tag, source, settings.fonts);
1322
+ break;
1323
+ case "table":
1324
+ attributes = tableAttributes(source, settings.fonts);
1325
+ break;
1326
+ case "ins":
1327
+ case "del": break;
1328
+ case "figure": {
1329
+ const align = lowerAscii(source.get("data-align") ?? "");
1330
+ attributes = VIVE_PROFILE.imageAlign.includes(align) ? [["data-align", align]] : [];
1331
+ break;
1332
+ }
1333
+ default:
1334
+ attributes = Object.hasOwn(VIVE_PROFILE.elements, tag) ? styleOf(tag, source, settings.fonts, context.inFontSize ? "font-size" : null) : null;
1335
+ next.inFontSize ||= tag === "span" && hasStyle(attributes, "font-size");
1336
+ if (BREAK_BLOCKS.has(tag) && attributes !== null && settings.suggestions === "keep") attributes = [...breakAttributes(source), ...attributes];
1337
+ if (tag === "span" && attributes !== null && settings.comments) {
1338
+ const comment = source.get("data-vive-comment");
1339
+ if (comment !== void 0 && isCommentId(comment)) attributes = [["data-vive-comment", comment], ...attributes];
1340
+ }
1341
+ }
1342
+ if (attributes === null) {
1343
+ walk(node, target, depth, context, settings);
1344
+ return;
1345
+ }
1346
+ walk(node, append(target, tag, attributes), depth, next, settings);
1347
+ }
1348
+ const MAX_ROUNDS = 3;
1349
+ function scrub(input) {
1350
+ return input.toWellFormed().replaceAll("\0", "");
1351
+ }
1352
+ function tooComplex() {
1353
+ throw new SanitizeError("TOO_COMPLEX", "HTML has too many attributes, elements or nesting levels.");
1354
+ }
1355
+ function tagCount(input) {
1356
+ let count = 0;
1357
+ for (let index = input.indexOf("<"); index !== -1; index = input.indexOf("<", index + 1)) count++;
1358
+ return count;
1359
+ }
1360
+ const TEMPLATE = /<template(?:[\t\n\f\r />]|$)/i;
1361
+ const START_TAG = /<[A-Za-z]/g;
1362
+ function startTagCount(input) {
1363
+ return input.match(START_TAG)?.length ?? 0;
1364
+ }
1365
+ const PARSE_WORK_PER_TAG = 50;
1366
+ function countParseWork(parser, budget) {
1367
+ let work = 0;
1368
+ const charge = () => {
1369
+ work += parser.openElements.stackTop + 1;
1370
+ if (work > budget) tooComplex();
1371
+ };
1372
+ const onStartTag = parser.onStartTag.bind(parser);
1373
+ const onEndTag = parser.onEndTag.bind(parser);
1374
+ parser.onStartTag = (token) => {
1375
+ charge();
1376
+ onStartTag(token);
1377
+ };
1378
+ parser.onEndTag = (token) => {
1379
+ charge();
1380
+ onEndTag(token);
1381
+ };
1382
+ }
1383
+ function cleanOnce(input, settings, maxTags) {
1384
+ if (hasCrowdedTag(input, limits.maxAttributes)) tooComplex();
1385
+ const treeAdapter = guardedTreeAdapter(Math.min(tagCount(input), maxTags) + limits.maxExtraElements, limits.maxNesting, tooComplex);
1386
+ const parser = Parser.getFragmentParser(BODY, {
1387
+ scriptingEnabled: false,
1388
+ treeAdapter
1389
+ });
1390
+ countParseWork(parser, Math.max(maxTags, limits.maxTags) * PARSE_WORK_PER_TAG);
1391
+ parser.tokenizer.write(input, true);
1392
+ const root = treeAdapter.getFirstChild(parser.document);
1393
+ const output = defaultTreeAdapter.createDocumentFragment();
1394
+ if (root && defaultTreeAdapter.isElementNode(root)) walk(root, output, 0, ROOT, settings);
1395
+ return serialize(output);
1396
+ }
1397
+ function sanitizeHtml(input, options = {}) {
1398
+ if (typeof input !== "string") return "";
1399
+ const maxBytes = options.maxBytes ?? limits.maxBytes;
1400
+ if (byteLength(input) > maxBytes) throw new SanitizeError("TOO_LARGE", `HTML is larger than ${maxBytes} bytes.`);
1401
+ const settings = {
1402
+ embeds: options.embeds === true,
1403
+ comments: options.comments === "keep",
1404
+ suggestions: options.suggestions === "accept" || options.suggestions === "keep" ? options.suggestions : "reject",
1405
+ image: {
1406
+ allowBase64: options.allowBase64 === true,
1407
+ allowRelative: options.allowRelativeImages === true
1408
+ },
1409
+ fonts: options.fontFamilies === void 0 ? DEFAULT_FONT_FAMILIES : fontFamilyMap(options.fontFamilies)
1410
+ };
1411
+ const html = scrub(input);
1412
+ const maxTags = options.maxTags ?? limits.maxTags;
1413
+ if (TEMPLATE.test(html)) tooComplex();
1414
+ if (startTagCount(html) > maxTags) throw new SanitizeError("TOO_COMPLEX", `HTML has more than ${maxTags} tags.`);
1415
+ let clean = cleanOnce(html, settings, maxTags);
1416
+ for (let round = 1; round < MAX_ROUNDS; round++) {
1417
+ const again = cleanOnce(clean, settings, maxTags);
1418
+ if (again === clean) break;
1419
+ clean = again;
1420
+ }
1421
+ return clean;
1422
+ }
1423
+ export { SanitizeError, VIVE_PROFILE, sanitizeHtml };
1424
+
1425
+ //# sourceMappingURL=index.mjs.map