react-smart-copy 1.9.0 → 1.11.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.
@@ -0,0 +1,1395 @@
1
+ //#region src/core/errors.ts
2
+ function createCopyError(type, message, cause) {
3
+ return cause === void 0 ? {
4
+ type,
5
+ message
6
+ } : {
7
+ type,
8
+ message,
9
+ cause
10
+ };
11
+ }
12
+ /**
13
+ * Branded (not `instanceof`) so failures stay recognisable even when the core
14
+ * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
15
+ */
16
+ const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
17
+ /** Error thrown by adapters to carry a fully classified {@link CopyError}. */
18
+ var CopyFailure = class extends Error {
19
+ constructor(copyError) {
20
+ super(copyError.message);
21
+ this[COPY_FAILURE_BRAND] = true;
22
+ this.name = "CopyFailure";
23
+ this.copyError = copyError;
24
+ }
25
+ };
26
+ /** Shorthand for throwing a classified failure. */
27
+ function copyFailure(type, message, cause) {
28
+ return new CopyFailure(createCopyError(type, message, cause));
29
+ }
30
+ //#endregion
31
+ //#region src/markdown/escape.ts
32
+ /**
33
+ * CommonMark escaping. Pasted text must render as the same text, never as
34
+ * Markdown syntax and never as raw HTML, so every character that can start a
35
+ * construct is backslash-escaped. Backslash escapes are valid before any ASCII
36
+ * punctuation, so over-escaping is always safe; under-escaping is not.
37
+ */
38
+ /**
39
+ * Characters that are special anywhere in a line: emphasis, code spans,
40
+ * links, strikethrough (GFM) and `<`, which starts raw HTML and autolinks.
41
+ */
42
+ const INLINE = /[\\`*_[\]<~]/g;
43
+ /** `&` that would start an entity or numeric character reference. */
44
+ const ENTITY = /&(?=#?[A-Za-z0-9]+;)/g;
45
+ /** Escapes text for use inside a line. With `pipes`, also `|`, for GFM table cells. */
46
+ function escapeInline(text, pipes = false) {
47
+ const escaped = text.replace(INLINE, "\\$&").replace(ENTITY, "\\&");
48
+ return pipes ? escaped.replace(/\|/g, "\\|") : escaped;
49
+ }
50
+ const ORDERED_MARKER = /^(\d{1,9})([.)])/;
51
+ const BLOCK_START = /^[#>+=|-]/;
52
+ /**
53
+ * Escapes the start of already inline-escaped text that begins a line, where
54
+ * `#`, `>`, `-`, `+`, `=`, `|` and `1.` / `1)` would start a block.
55
+ */
56
+ function escapeLineStart(text) {
57
+ const ordered = ORDERED_MARKER.exec(text);
58
+ if (ordered) return `${ordered[1]}\\${text.slice(ordered[1].length)}`;
59
+ return BLOCK_START.test(text) ? `\\${text}` : text;
60
+ }
61
+ /**
62
+ * Escapes plain text so Markdown renders it literally: no emphasis, links,
63
+ * headings, lists, code or raw HTML. Line breaks are kept; leading whitespace
64
+ * on each line is removed, since Markdown would read four spaces as code.
65
+ *
66
+ * @example
67
+ * escapeMarkdown('1. *Not* a list <b>') // '1\\. \\*Not\\* a list \\<b>'
68
+ */
69
+ function escapeMarkdown(text) {
70
+ return text.split(/\r\n|\r|\n/).map((line) => escapeLineStart(escapeInline(line.replace(/^[ \t]+/, "")))).join("\n");
71
+ }
72
+ //#endregion
73
+ //#region src/markdown/url.ts
74
+ /**
75
+ * URL safety for pasted links and images. Only absolute URLs with an allowed
76
+ * scheme survive; everything else (`javascript:`, `data:`, `vbscript:`,
77
+ * relative links without a base, malformed URLs) is dropped and the visible
78
+ * text is kept. Parsing uses the WHATWG URL parser, the same one the browser
79
+ * uses when the link is clicked, so tricks like `java\tscript:` are seen as
80
+ * `javascript:`.
81
+ */
82
+ const DEFAULT_LINK_PROTOCOLS = [
83
+ "http:",
84
+ "https:",
85
+ "mailto:"
86
+ ];
87
+ const DEFAULT_IMAGE_PROTOCOLS = ["https:", "http:"];
88
+ function parse(raw, base) {
89
+ try {
90
+ return new URL(raw.trim(), base);
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+ /**
96
+ * Click-tracking redirects that pasted links often carry: Google (Docs,
97
+ * Search, Gmail) and Outlook Safe Links. Unwrapped only to an http(s) target.
98
+ */
99
+ function unwrapRedirect(url) {
100
+ const host = url.hostname.toLowerCase();
101
+ const param = /(^|\.)google\.[a-z.]+$/.test(host) && url.pathname === "/url" ? url.searchParams.get("q") ?? url.searchParams.get("url") : host.endsWith(".safelinks.protection.outlook.com") ? url.searchParams.get("url") : null;
102
+ if (param === null) return url;
103
+ const target = parse(param, void 0);
104
+ return target !== null && (target.protocol === "https:" || target.protocol === "http:") ? target : url;
105
+ }
106
+ /** The normalised URL, or `null` when it is not absolute or its scheme is not allowed. */
107
+ function safeUrl(raw, protocols, base) {
108
+ const parsed = parse(raw, base);
109
+ if (parsed === null) return null;
110
+ const url = unwrapRedirect(parsed);
111
+ return protocols.includes(url.protocol) ? url.href : null;
112
+ }
113
+ /** `href` comes from the URL serialiser, which already percent-encodes every non-ASCII character. */
114
+ const percent = (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`;
115
+ /**
116
+ * A Markdown link destination. ASCII whitespace, `<`, `>` and controls are
117
+ * percent-encoded (opaque URLs such as `mailto:` keep them otherwise),
118
+ * backslashes too so they can't act as escapes, and parentheses are kept
119
+ * exact by using the `<…>` form.
120
+ */
121
+ function linkDestination(href) {
122
+ const encoded = href.replace(/[ <>\\\u0000-\u001f\u007f]/g, percent);
123
+ return /[()]/.test(encoded) ? `<${encoded}>` : encoded;
124
+ }
125
+ /** Outermost first: a style lower in the list is always nested inside the ones above it. */
126
+ const ORDER = [
127
+ [4, "~~"],
128
+ [1, "**"],
129
+ [2, "*"]
130
+ ];
131
+ /** HTML's collapsible whitespace. A no-break space is content: HTML neither collapses nor trims it. */
132
+ const SPACE = /[ \t\n\r\f]+/g;
133
+ /** CommonMark's Unicode whitespace: Zs, tab, LF, FF, CR (not U+2028, which JavaScript's `\s` includes). */
134
+ const WHITESPACE = /[\t\n\f\r\p{Zs}]/u;
135
+ const PUNCTUATION = /[\p{P}\p{S}]/u;
136
+ /** Collapses HTML whitespace across runs and trims it at line starts and ends. */
137
+ function normalize(runs) {
138
+ const out = [];
139
+ let atStart = true;
140
+ for (const run of runs) {
141
+ if (run.kind === "break") {
142
+ out.push(run);
143
+ atStart = true;
144
+ continue;
145
+ }
146
+ if (run.kind === "image") {
147
+ out.push(run);
148
+ atStart = false;
149
+ continue;
150
+ }
151
+ let text = run.text.replace(SPACE, " ");
152
+ if (atStart) text = text.replace(/^\s+/, "");
153
+ else if (lastText(out).endsWith(" ")) text = text.replace(/^ /, "");
154
+ if (text === "") continue;
155
+ out.push({
156
+ ...run,
157
+ text
158
+ });
159
+ atStart = false;
160
+ }
161
+ const trimmed = [];
162
+ for (const run of [...out, { kind: "break" }]) {
163
+ if (run.kind === "break") {
164
+ trimTrailingSpace(trimmed);
165
+ if (trimmed.length > 0 && trimmed[trimmed.length - 1]?.kind !== "break") trimmed.push(run);
166
+ continue;
167
+ }
168
+ trimmed.push(run);
169
+ }
170
+ trimmed.pop();
171
+ return trimmed;
172
+ }
173
+ function lastText(runs) {
174
+ const last = runs[runs.length - 1];
175
+ return last?.kind === "text" ? last.text : "";
176
+ }
177
+ function trimTrailingSpace(runs) {
178
+ for (let last = runs[runs.length - 1]; last?.kind === "text"; last = runs[runs.length - 1]) {
179
+ const text = last.text.replace(/\s+$/, "");
180
+ if (text !== "") {
181
+ runs[runs.length - 1] = {
182
+ ...last,
183
+ text
184
+ };
185
+ return;
186
+ }
187
+ runs.pop();
188
+ }
189
+ }
190
+ /** Splits text into leading spaces, content and trailing spaces. */
191
+ function splitSpaces(text) {
192
+ const core = text.trim();
193
+ if (core === "") return [
194
+ text,
195
+ "",
196
+ ""
197
+ ];
198
+ const start = text.indexOf(core);
199
+ return [
200
+ text.slice(0, start),
201
+ core,
202
+ text.slice(start + core.length)
203
+ ];
204
+ }
205
+ function codeSpan(text, pipes) {
206
+ let longest = 0;
207
+ for (const match of text.matchAll(/`+/g)) longest = Math.max(longest, match[0].length);
208
+ const fence = "`".repeat(longest + 1);
209
+ const body = pipes ? text.replace(/\|/g, "\\|") : text;
210
+ return `${fence}${/^`|`$/.test(body) || /^ .* $/.test(body) ? ` ${body} ` : body}${fence}`;
211
+ }
212
+ /** Serialises runs into tokens. */
213
+ function tokenize(runs, options) {
214
+ const tokens = [];
215
+ const stack = [];
216
+ let pairs = 0;
217
+ let href = null;
218
+ let linkStart = -1;
219
+ let pending = "";
220
+ const closeFrom = (index) => {
221
+ while (stack.length > index) {
222
+ const top = stack.pop();
223
+ tokens.push({
224
+ kind: "delim",
225
+ s: top.marker,
226
+ delim: {
227
+ marker: top.marker,
228
+ pair: top.pair,
229
+ open: false
230
+ }
231
+ });
232
+ }
233
+ };
234
+ const flushPending = () => {
235
+ if (pending !== "") tokens.push({
236
+ kind: "text",
237
+ s: pending
238
+ });
239
+ pending = "";
240
+ };
241
+ const setStyle = (style, lead) => {
242
+ const keep = stack.findIndex((entry) => (style & entry.bit) === 0);
243
+ closeFrom(keep === -1 ? stack.length : keep);
244
+ pending += lead;
245
+ flushPending();
246
+ for (const [bit, marker] of ORDER) if ((style & bit) !== 0 && !stack.some((entry) => entry.bit === bit)) {
247
+ pairs += 1;
248
+ stack.push({
249
+ bit,
250
+ pair: pairs,
251
+ marker
252
+ });
253
+ tokens.push({
254
+ kind: "delim",
255
+ s: marker,
256
+ delim: {
257
+ marker,
258
+ pair: pairs,
259
+ open: true
260
+ }
261
+ });
262
+ }
263
+ };
264
+ const closeLink = () => {
265
+ closeFrom(0);
266
+ if (href === null) return;
267
+ if (tokens.length - 1 === linkStart) tokens.pop();
268
+ else tokens.push({
269
+ kind: "syntax",
270
+ s: `](${linkDestination(href)})`
271
+ });
272
+ href = null;
273
+ };
274
+ for (let index = 0; index < runs.length; index += 1) {
275
+ const run = runs[index];
276
+ if (run.kind === "break") {
277
+ closeLink();
278
+ pending = "";
279
+ tokens.push({
280
+ kind: "break",
281
+ s: options.hardBreak
282
+ });
283
+ continue;
284
+ }
285
+ if (run.href !== href) {
286
+ closeLink();
287
+ flushPending();
288
+ if (run.href !== null) {
289
+ href = run.href;
290
+ linkStart = tokens.length;
291
+ tokens.push({
292
+ kind: "syntax",
293
+ s: "["
294
+ });
295
+ }
296
+ }
297
+ if (run.kind === "image") {
298
+ setStyle(run.style & -9, "");
299
+ tokens.push({
300
+ kind: "syntax",
301
+ s: `![${escapeInline(run.alt, options.pipes)}](${linkDestination(run.src)})`
302
+ });
303
+ continue;
304
+ }
305
+ let text = run.text;
306
+ if ((run.style & 8) !== 0) for (let next = runs[index + 1]; next?.kind === "text" && next.style === run.style && next.href === run.href; next = runs[index + 1]) {
307
+ text += next.text;
308
+ index += 1;
309
+ }
310
+ const [lead, core, trail] = splitSpaces(text);
311
+ if (core === "") {
312
+ pending += lead;
313
+ continue;
314
+ }
315
+ setStyle(run.style & -9, lead);
316
+ tokens.push((run.style & 8) !== 0 ? {
317
+ kind: "syntax",
318
+ s: codeSpan(core, options.pipes)
319
+ } : {
320
+ kind: "text",
321
+ s: escapeInline(core, options.pipes)
322
+ });
323
+ pending = trail;
324
+ }
325
+ closeLink();
326
+ flushPending();
327
+ return tokens;
328
+ }
329
+ /**
330
+ * The character next to a delimiter run, at token `index` (the token just
331
+ * outside the run). Line starts and ends count as whitespace. Runs are maximal,
332
+ * so this token is never a delimiter of the same character.
333
+ */
334
+ function neighbour(tokens, index, step) {
335
+ const token = tokens[index];
336
+ if (token === void 0 || token.kind === "break") return "\n";
337
+ return (step === 1 ? FIRST_CHAR : LAST_CHAR).exec(token.s)[0];
338
+ }
339
+ const FIRST_CHAR = /^[\s\S]/u;
340
+ const LAST_CHAR = /[\s\S]$/u;
341
+ const leftFlanking = (before, after) => !WHITESPACE.test(after) && (!PUNCTUATION.test(after) || WHITESPACE.test(before) || PUNCTUATION.test(before));
342
+ const rightFlanking = (before, after) => !WHITESPACE.test(before) && (!PUNCTUATION.test(before) || WHITESPACE.test(after) || PUNCTUATION.test(after));
343
+ /** GFM strikethrough: can this `~~` open (left-flanking) or close (right-flanking)? */
344
+ function strikeFlanks(tokens, index, delim) {
345
+ const before = neighbour(tokens, index - 1, -1);
346
+ const after = neighbour(tokens, index + 1, 1);
347
+ return delim.open ? leftFlanking(before, after) : rightFlanking(before, after);
348
+ }
349
+ /**
350
+ * Adjacent `*` delimiters form one delimiter run. When a run both closes one span
351
+ * and opens another (`*a***b**`), CommonMark can pair them differently than meant,
352
+ * so the emphasis (`*`) pairs in such a run switch to `_`, which is a separate run.
353
+ */
354
+ function separateMixedRuns(tokens) {
355
+ let group = [];
356
+ const settle = () => {
357
+ const opens = group.filter((token) => token.delim.open);
358
+ const closes = group.filter((token) => !token.delim.open);
359
+ if (opens.length > 0 && closes.length > 0) {
360
+ const emphasisOpens = opens.filter((token) => token.delim.marker === "*");
361
+ const switching = emphasisOpens.length > 0 ? emphasisOpens : closes.filter((token) => token.delim.marker === "*");
362
+ const pairs = new Set(switching.map((token) => token.delim.pair));
363
+ for (const token of tokens) if (token.kind === "delim" && pairs.has(token.delim.pair)) {
364
+ token.s = "_";
365
+ token.delim = {
366
+ ...token.delim,
367
+ marker: "_"
368
+ };
369
+ }
370
+ }
371
+ group = [];
372
+ };
373
+ for (const token of tokens) if (token.kind === "delim" && token.delim.marker[0] === "*") group.push(token);
374
+ else settle();
375
+ settle();
376
+ }
377
+ /** Groups the delimiter tokens at `indexes` into runs (adjacent `*` or adjacent `_`). */
378
+ function runsOf(tokens, indexes) {
379
+ const entries = [];
380
+ let run = [];
381
+ const close = () => {
382
+ if (run.length === 0) return;
383
+ const firstIndex = run[0];
384
+ const lastIndex = run[run.length - 1];
385
+ const char = tokens[firstIndex].delim.marker[0];
386
+ const before = neighbour(tokens, firstIndex - 1, -1);
387
+ const after = neighbour(tokens, lastIndex + 1, 1);
388
+ const left = leftFlanking(before, after);
389
+ const right = rightFlanking(before, after);
390
+ const chars = run.flatMap((index) => {
391
+ const { delim } = tokens[index];
392
+ return Array.from(delim.marker, () => ({
393
+ pair: delim.pair,
394
+ open: delim.open,
395
+ matched: false
396
+ }));
397
+ });
398
+ entries.push({
399
+ char,
400
+ orig: chars.length,
401
+ canOpen: char === "_" ? left && (!right || PUNCTUATION.test(before)) : left,
402
+ canClose: char === "_" ? right && (!left || PUNCTUATION.test(after)) : right,
403
+ chars,
404
+ front: 0,
405
+ len: chars.length
406
+ });
407
+ run = [];
408
+ };
409
+ let previous = -1;
410
+ for (const index of indexes) {
411
+ const token = tokens[index];
412
+ const emphasis = token.kind === "delim" && token.delim.marker[0] !== "~";
413
+ const adjacent = previous === index - 1;
414
+ const sameChar = run.length > 0 && emphasis && tokens[run[0]].delim.marker[0] === token.delim.marker[0];
415
+ if (!emphasis || !adjacent || !sameChar) close();
416
+ if (emphasis) run.push(index);
417
+ previous = index;
418
+ }
419
+ close();
420
+ return entries;
421
+ }
422
+ /**
423
+ * CommonMark's "process emphasis" algorithm, run on our own output: it pairs
424
+ * delimiter characters exactly as a Markdown renderer will. Returns the pairs
425
+ * whose characters would not be paired as intended (they would render as
426
+ * literal asterisks or pair with the wrong span).
427
+ */
428
+ function misread(tokens, indexes) {
429
+ const stack = runsOf(tokens, indexes);
430
+ const failed = /* @__PURE__ */ new Set();
431
+ let current = 0;
432
+ while (current < stack.length) {
433
+ const closer = stack[current];
434
+ if (!closer.canClose || closer.len === 0) {
435
+ current += 1;
436
+ continue;
437
+ }
438
+ let openerIndex = current - 1;
439
+ for (; openerIndex >= 0; openerIndex -= 1) {
440
+ const opener = stack[openerIndex];
441
+ if (opener.char !== closer.char || !opener.canOpen || opener.len === 0) continue;
442
+ if (!((closer.canOpen || opener.canClose) && closer.orig % 3 !== 0 && (opener.orig + closer.orig) % 3 === 0)) break;
443
+ }
444
+ if (openerIndex < 0) {
445
+ current += 1;
446
+ continue;
447
+ }
448
+ const opener = stack[openerIndex];
449
+ const use = closer.len >= 2 && opener.len >= 2 ? 2 : 1;
450
+ for (let k = 0; k < use; k += 1) {
451
+ const open = opener.chars[opener.front + opener.len - 1];
452
+ const shut = closer.chars[closer.front];
453
+ opener.len -= 1;
454
+ closer.front += 1;
455
+ closer.len -= 1;
456
+ open.matched = true;
457
+ shut.matched = true;
458
+ if (open.pair !== shut.pair || !open.open || shut.open) {
459
+ failed.add(open.pair);
460
+ failed.add(shut.pair);
461
+ }
462
+ }
463
+ for (let between = openerIndex + 1; between < current; between += 1) stack[between].len = 0;
464
+ }
465
+ for (const entry of stack) for (const char of entry.chars) if (!char.matched) failed.add(char.pair);
466
+ return failed;
467
+ }
468
+ /** The delimiter token indexes inside each link's text, and those outside every link. */
469
+ function scopes(tokens) {
470
+ const outside = [];
471
+ const links = [];
472
+ let inside = null;
473
+ tokens.forEach((token, index) => {
474
+ if (token.kind === "syntax" && token.s === "[") inside = [];
475
+ else if (token.kind === "syntax" && token.s.startsWith("](") && inside !== null) {
476
+ links.push(inside);
477
+ inside = null;
478
+ } else if (token.kind === "delim") (inside ?? outside).push(index);
479
+ });
480
+ return [...links, outside];
481
+ }
482
+ /**
483
+ * Drops delimiter pairs CommonMark would not read as intended, until every
484
+ * remaining pair renders exactly as meant: emphasis is checked by running
485
+ * CommonMark's own pairing algorithm (link text first, as the spec does),
486
+ * strikethrough by its flanking rules.
487
+ */
488
+ function resolve(tokens) {
489
+ let current = tokens;
490
+ for (;;) {
491
+ const invalid = /* @__PURE__ */ new Set();
492
+ current.forEach((token, index) => {
493
+ if (token.kind === "delim" && token.delim.marker[0] === "~" && !strikeFlanks(current, index, token.delim)) invalid.add(token.delim.pair);
494
+ });
495
+ for (const scope of scopes(current)) for (const pair of misread(current, scope)) invalid.add(pair);
496
+ if (invalid.size === 0) return current;
497
+ current = joinTouching(current.filter((token) => token.kind !== "delim" || !invalid.has(token.delim.pair)));
498
+ }
499
+ }
500
+ /**
501
+ * Dropping a pair can leave one span's closing delimiter right before the next
502
+ * span's opening one, with the same marker (`~~a~~~~b~~`). Those two cancel
503
+ * out: the spans join into one, which is what the text looked like anyway.
504
+ */
505
+ function joinTouching(tokens) {
506
+ const out = [];
507
+ for (const token of tokens) {
508
+ const last = out[out.length - 1];
509
+ if (token.kind === "delim" && token.delim.open && last?.kind === "delim" && !last.delim.open && last.s === token.s) {
510
+ out.pop();
511
+ const closer = tokens.find((candidate) => candidate.kind === "delim" && !candidate.delim.open && candidate.delim.pair === token.delim.pair);
512
+ closer.delim = {
513
+ ...closer.delim,
514
+ pair: last.delim.pair
515
+ };
516
+ continue;
517
+ }
518
+ out.push(token);
519
+ }
520
+ return out;
521
+ }
522
+ /** Escapes the first text of every line, once delimiters are final. */
523
+ function escapeLineStarts(tokens) {
524
+ let lineStart = true;
525
+ for (const token of tokens) if (token.kind === "break") lineStart = true;
526
+ else {
527
+ if (lineStart && token.kind === "text") token.s = escapeLineStart(token.s);
528
+ lineStart = false;
529
+ }
530
+ }
531
+ /** Inline Markdown for runs: one line, or several joined by hard breaks. Empty when there is no content. */
532
+ function renderInline(runs, options) {
533
+ const raw = tokenize(normalize(runs), options);
534
+ separateMixedRuns(raw);
535
+ const tokens = resolve(raw);
536
+ escapeLineStarts(tokens);
537
+ const markdown = tokens.map((token) => token.s).join("");
538
+ return markdown.trim() === "" ? "" : markdown;
539
+ }
540
+ //#endregion
541
+ //#region src/markdown/convert.ts
542
+ const DEFAULT_MARKDOWN_MAX_LENGTH = 16777216;
543
+ const DEFAULT_MARKDOWN_MAX_NODES = 2e5;
544
+ const DEFAULT_MARKDOWN_MAX_DEPTH = 200;
545
+ /** Merged-cell expansion cap for one table, so a tiny table can't claim millions of cells. */
546
+ const MAX_TABLE_CELLS = 1e5;
547
+ const MAX_COLSPAN = 1e3;
548
+ function limit(value, fallback, name) {
549
+ if (value === void 0) return fallback;
550
+ if (value === Infinity || Number.isInteger(value) && value > 0) return value;
551
+ throw copyFailure("invalid-payload", `\`${name}\` must be a positive integer or Infinity (received ${String(value)}).`);
552
+ }
553
+ function resolveOptions(options) {
554
+ return {
555
+ images: options.images ?? "alt",
556
+ links: options.links ?? "keep",
557
+ linkProtocols: options.linkProtocols ?? DEFAULT_LINK_PROTOCOLS,
558
+ imageProtocols: options.imageProtocols ?? DEFAULT_IMAGE_PROTOCOLS,
559
+ baseUrl: options.baseUrl,
560
+ bullet: options.bullet ?? "-",
561
+ hardBreak: options.hardBreak === "spaces" ? " \n" : "\\\n",
562
+ maxLength: limit(options.maxLength, DEFAULT_MARKDOWN_MAX_LENGTH, "maxLength"),
563
+ maxNodes: limit(options.maxNodes, DEFAULT_MARKDOWN_MAX_NODES, "maxNodes"),
564
+ maxDepth: limit(options.maxDepth, 200, "maxDepth")
565
+ };
566
+ }
567
+ /** Never rendered: scripts, metadata, embedded documents, media and form controls. */
568
+ const SKIP = /* @__PURE__ */ new Set([
569
+ "script",
570
+ "style",
571
+ "template",
572
+ "noscript",
573
+ "head",
574
+ "title",
575
+ "meta",
576
+ "link",
577
+ "base",
578
+ "xml",
579
+ "iframe",
580
+ "frame",
581
+ "frameset",
582
+ "object",
583
+ "embed",
584
+ "applet",
585
+ "svg",
586
+ "math",
587
+ "canvas",
588
+ "video",
589
+ "audio",
590
+ "source",
591
+ "track",
592
+ "map",
593
+ "area",
594
+ "input",
595
+ "button",
596
+ "select",
597
+ "option",
598
+ "optgroup",
599
+ "textarea",
600
+ "datalist",
601
+ "output",
602
+ "progress",
603
+ "meter",
604
+ "dialog",
605
+ "o:p"
606
+ ]);
607
+ /** Blocks without margins in the browser: their inline content forms lines, not paragraphs. */
608
+ const DIV_LIKE = /* @__PURE__ */ new Set([
609
+ "address",
610
+ "article",
611
+ "aside",
612
+ "center",
613
+ "dd",
614
+ "details",
615
+ "dir",
616
+ "div",
617
+ "dl",
618
+ "dt",
619
+ "fieldset",
620
+ "figcaption",
621
+ "figure",
622
+ "footer",
623
+ "form",
624
+ "header",
625
+ "hgroup",
626
+ "legend",
627
+ "li",
628
+ "main",
629
+ "nav",
630
+ "search",
631
+ "section",
632
+ "summary",
633
+ "caption",
634
+ "tbody",
635
+ "thead",
636
+ "tfoot",
637
+ "tr",
638
+ "td",
639
+ "th",
640
+ "colgroup",
641
+ "col"
642
+ ]);
643
+ const HEADINGS = /* @__PURE__ */ new Set([
644
+ "h1",
645
+ "h2",
646
+ "h3",
647
+ "h4",
648
+ "h5",
649
+ "h6"
650
+ ]);
651
+ /** Div-like blocks the browser gives vertical margins: their content is set apart as paragraphs. */
652
+ const SPACED = /* @__PURE__ */ new Set([
653
+ "dl",
654
+ "figure",
655
+ "fieldset"
656
+ ]);
657
+ const OTHER_BLOCKS = /* @__PURE__ */ new Set([
658
+ "p",
659
+ "ul",
660
+ "ol",
661
+ "menu",
662
+ "pre",
663
+ "blockquote",
664
+ "table",
665
+ "hr"
666
+ ]);
667
+ const isBlock = (tag) => DIV_LIKE.has(tag) || HEADINGS.has(tag) || OTHER_BLOCKS.has(tag);
668
+ /** Inline CSS, lower-cased: only what changes the Markdown. */
669
+ function styleOf(element) {
670
+ const map = /* @__PURE__ */ new Map();
671
+ const attribute = element.getAttribute("style");
672
+ if (attribute === null) return map;
673
+ for (const declaration of attribute.split(";")) {
674
+ const colon = declaration.indexOf(":");
675
+ if (colon > 0) map.set(declaration.slice(0, colon).trim().toLowerCase(), declaration.slice(colon + 1).trim().toLowerCase());
676
+ }
677
+ return map;
678
+ }
679
+ const MONOSPACE = /\b(monospace|courier|consolas|menlo|monaco|source code pro|roboto mono|fira (code|mono)|jetbrains mono|sf mono|cascadia|ubuntu mono|lucida console|inconsolata)\b/;
680
+ function isHidden(element, style) {
681
+ return element.hasAttribute("hidden") || style.get("display") === "none" || style.get("visibility") === "hidden" || style.get("mso-list") === "ignore";
682
+ }
683
+ /** Style bits after this element: semantic tags first, then inline CSS, which wins (Google Docs, Word). */
684
+ function applyStyle(bits, tag, style) {
685
+ let next = bits;
686
+ if (tag === "b" || tag === "strong") next |= 1;
687
+ else if (tag === "i" || tag === "em") next |= 2;
688
+ else if (tag === "s" || tag === "strike" || tag === "del") next |= 4;
689
+ else if (tag === "code" || tag === "kbd" || tag === "samp" || tag === "tt") next |= 8;
690
+ const weight = style.get("font-weight");
691
+ if (weight !== void 0) {
692
+ const numeric = Number.parseInt(weight, 10);
693
+ if (weight === "bold" || weight === "bolder" || numeric >= 600) next |= 1;
694
+ else if (weight === "normal" || weight === "lighter" || numeric > 0) next &= -2;
695
+ }
696
+ const fontStyle = style.get("font-style");
697
+ if (fontStyle === "italic" || fontStyle === "oblique") next |= 2;
698
+ else if (fontStyle === "normal") next &= -3;
699
+ if ((style.get("text-decoration-line") ?? style.get("text-decoration"))?.includes("line-through")) next |= 4;
700
+ const family = style.get("font-family");
701
+ if (family !== void 0 && MONOSPACE.test(family)) next |= 8;
702
+ return next;
703
+ }
704
+ /** A `<div style="white-space: pre; font-family: monospace">`, as code editors (VS Code) write. */
705
+ function isCodeContainer(tag, style) {
706
+ const whiteSpace = style.get("white-space");
707
+ const family = style.get("font-family");
708
+ return tag === "div" && whiteSpace !== void 0 && whiteSpace.startsWith("pre") && family !== void 0 && MONOSPACE.test(family);
709
+ }
710
+ const PARA = {
711
+ before: "para",
712
+ after: "para"
713
+ };
714
+ const WORD_LIST = /mso-list\s*:\s*(l\d+)\s+level(\d+)/i;
715
+ const ORDERED_WORD_MARKER = /^\(?(\d+|[a-z]|[ivxlcdm]+)[.)]/i;
716
+ var Converter = class {
717
+ constructor(options) {
718
+ this.options = options;
719
+ this.nodes = 0;
720
+ this.truncated = false;
721
+ }
722
+ inlineOptions(pipes = false) {
723
+ return {
724
+ pipes,
725
+ hardBreak: this.options.hardBreak
726
+ };
727
+ }
728
+ /** Converts nodes (usually an element's children) into blocks. `kind`: how loose inline content joins. */
729
+ blocks(nodes, ctx, kind) {
730
+ const blocks = [];
731
+ const runs = [];
732
+ const sink = {
733
+ blocks,
734
+ flush: () => blocks.push(...this.paragraphs(runs.splice(0), kind))
735
+ };
736
+ for (let index = 0; index < nodes.length; index += 1) {
737
+ const node = nodes[index];
738
+ if (isWordListParagraph(node)) {
739
+ sink.flush();
740
+ const [list, consumed] = this.wordList(nodes, index, ctx);
741
+ blocks.push(...list);
742
+ index += consumed - 1;
743
+ continue;
744
+ }
745
+ this.visit(node, ctx, runs, sink);
746
+ }
747
+ sink.flush();
748
+ return blocks;
749
+ }
750
+ /** Visits one node: inline content goes into `runs`; block elements flush them into the sink. */
751
+ visit(node, ctx, runs, sink) {
752
+ if (this.nodes >= this.options.maxNodes) {
753
+ this.truncated = true;
754
+ return;
755
+ }
756
+ this.nodes += 1;
757
+ if (node.nodeType === 3) {
758
+ runs.push({
759
+ kind: "text",
760
+ text: node.data,
761
+ style: ctx.style & ~ctx.mask,
762
+ href: ctx.href
763
+ });
764
+ return;
765
+ }
766
+ if (node.nodeType !== 1) return;
767
+ const element = node;
768
+ const tag = element.localName.toLowerCase();
769
+ const style = styleOf(element);
770
+ if (SKIP.has(tag) || isHidden(element, style)) return;
771
+ if (ctx.depth >= this.options.maxDepth) {
772
+ runs.push({
773
+ kind: "text",
774
+ text: ` ${element.textContent} `,
775
+ style: 0,
776
+ href: ctx.href
777
+ });
778
+ return;
779
+ }
780
+ if (tag === "br") {
781
+ runs.push(sink === null ? {
782
+ kind: "text",
783
+ text: " ",
784
+ style: 0,
785
+ href: null
786
+ } : { kind: "break" });
787
+ return;
788
+ }
789
+ if (tag === "img") {
790
+ this.image(element, ctx, runs);
791
+ return;
792
+ }
793
+ const inner = {
794
+ ...ctx,
795
+ style: applyStyle(ctx.style, tag, style),
796
+ href: this.link(element, tag, ctx),
797
+ depth: ctx.depth + 1
798
+ };
799
+ if (!isBlock(tag) && !isCodeContainer(tag, style)) {
800
+ for (let child = element.firstChild; child !== null; child = child.nextSibling) this.visit(child, inner, runs, sink);
801
+ return;
802
+ }
803
+ if (sink === null) {
804
+ runs.push({
805
+ kind: "text",
806
+ text: " ",
807
+ style: 0,
808
+ href: null
809
+ });
810
+ const flat = tag === "pre" ? {
811
+ ...inner,
812
+ style: inner.style | 8
813
+ } : inner;
814
+ for (let child = element.firstChild; child !== null; child = child.nextSibling) this.visit(child, flat, runs, null);
815
+ runs.push({
816
+ kind: "text",
817
+ text: " ",
818
+ style: 0,
819
+ href: null
820
+ });
821
+ return;
822
+ }
823
+ sink.flush();
824
+ sink.blocks.push(...this.block(element, tag, style, inner));
825
+ }
826
+ block(element, tag, style, ctx) {
827
+ if (tag === "pre" || isCodeContainer(tag, style)) return this.code(element, ctx);
828
+ if (HEADINGS.has(tag)) return this.heading(element, Number(tag.slice(1)), ctx);
829
+ switch (tag) {
830
+ case "p": return this.blocks(children(element), ctx, "para");
831
+ case "ul":
832
+ case "ol":
833
+ case "menu": return [this.listBlock(this.htmlList(element, tag === "ol", ctx))];
834
+ case "blockquote": {
835
+ const inner = join(this.blocks(children(element), ctx, "para"), this.options.hardBreak);
836
+ return inner === "" ? [] : [{
837
+ md: inner.split("\n").map((line) => line === "" ? ">" : `> ${line}`).join("\n"),
838
+ ...PARA
839
+ }];
840
+ }
841
+ case "table": return this.table(element, ctx);
842
+ case "hr": return [{
843
+ md: "---",
844
+ ...PARA
845
+ }];
846
+ default: {
847
+ const blocks = this.blocks(children(element), ctx, "line");
848
+ return SPACED.has(tag) ? spaced(blocks) : blocks;
849
+ }
850
+ }
851
+ }
852
+ /** Inline runs → paragraphs. Two or more line breaks in a row end a paragraph. */
853
+ paragraphs(runs, kind) {
854
+ const chunks = [[]];
855
+ let breaks = 0;
856
+ for (const run of runs) {
857
+ if (run.kind === "break") breaks += 1;
858
+ else if (run.kind === "text" && run.text.trim() === "") {} else if (breaks >= 2) {
859
+ chunks.push([]);
860
+ breaks = 0;
861
+ } else breaks = 0;
862
+ chunks[chunks.length - 1].push(run);
863
+ }
864
+ const rendered = chunks.map((chunk) => renderInline(chunk, this.inlineOptions()));
865
+ const blocks = [];
866
+ rendered.forEach((md, index) => {
867
+ if (md === "") return;
868
+ const first = index === 0;
869
+ const last = index === rendered.length - 1;
870
+ blocks.push({
871
+ md,
872
+ before: first ? kind : "para",
873
+ after: last ? kind : "para"
874
+ });
875
+ });
876
+ if (blocks.length === 0 && kind === "line" && runs.some((run) => run.kind === "break")) blocks.push({
877
+ md: "",
878
+ ...PARA
879
+ });
880
+ return blocks;
881
+ }
882
+ heading(element, level, ctx) {
883
+ const md = this.inline(element, {
884
+ ...ctx,
885
+ mask: ctx.mask | 1
886
+ });
887
+ if (md === "") return [];
888
+ const escaped = /(^|[^\\])(\\\\)*#$/.test(md) ? `${md.slice(0, -1)}\\#` : md;
889
+ return [{
890
+ md: `${"#".repeat(level)} ${escaped}`,
891
+ ...PARA
892
+ }];
893
+ }
894
+ /** An element's content as one line of inline Markdown. */
895
+ inline(element, ctx, pipes = false) {
896
+ const runs = [];
897
+ for (let child = element.firstChild; child !== null; child = child.nextSibling) this.visit(child, ctx, runs, null);
898
+ return renderInline(runs, this.inlineOptions(pipes));
899
+ }
900
+ image(element, ctx, runs) {
901
+ const { images, imageProtocols, baseUrl } = this.options;
902
+ if (images === "drop") return;
903
+ const alt = (element.getAttribute("alt") ?? "").replace(/\s+/g, " ").trim();
904
+ const src = images === "keep" ? safeUrl(element.getAttribute("src") ?? "", imageProtocols, baseUrl) : null;
905
+ const style = ctx.style & ~ctx.mask;
906
+ if (src !== null) runs.push({
907
+ kind: "image",
908
+ alt,
909
+ src,
910
+ style,
911
+ href: ctx.href
912
+ });
913
+ else if (alt !== "") runs.push({
914
+ kind: "text",
915
+ text: alt,
916
+ style,
917
+ href: ctx.href
918
+ });
919
+ }
920
+ link(element, tag, ctx) {
921
+ if (tag !== "a" || ctx.href !== null || this.options.links === "text") return ctx.href;
922
+ const href = element.getAttribute("href");
923
+ return href === null ? null : safeUrl(href, this.options.linkProtocols, this.options.baseUrl);
924
+ }
925
+ code(element, ctx) {
926
+ const text = this.codeText(element, ctx.depth).replace(/\r\n?/g, "\n").replace(/\u00a0/g, " ").replace(/^\n/, "").replace(/\s+$/, "");
927
+ if (text.trim() === "") return [];
928
+ let longest = 0;
929
+ for (const match of text.matchAll(/`+/g)) longest = Math.max(longest, match[0].length);
930
+ const fence = "`".repeat(Math.max(3, longest + 1));
931
+ return [{
932
+ md: `${fence}${language(element)}\n${text}\n${fence}`,
933
+ ...PARA
934
+ }];
935
+ }
936
+ /** Text of a code block: line breaks and line-shaped elements (`<div>` per line) become newlines. */
937
+ codeText(element, depth) {
938
+ let out = "";
939
+ const walk = (node, level) => {
940
+ for (let child = node.firstChild; child !== null; child = child.nextSibling) {
941
+ if (this.nodes >= this.options.maxNodes) {
942
+ this.truncated = true;
943
+ return;
944
+ }
945
+ this.nodes += 1;
946
+ if (child.nodeType === 3) out += child.data;
947
+ if (child.nodeType !== 1) continue;
948
+ const el = child;
949
+ const tag = el.localName.toLowerCase();
950
+ if (SKIP.has(tag) || isHidden(el, styleOf(el))) continue;
951
+ if (tag === "br") {
952
+ out += "\n";
953
+ continue;
954
+ }
955
+ const lineShaped = isBlock(tag);
956
+ if (lineShaped && out !== "" && !out.endsWith("\n")) out += "\n";
957
+ if (level >= this.options.maxDepth) out += el.textContent;
958
+ else walk(el, level + 1);
959
+ if (lineShaped && !out.endsWith("\n")) out += "\n";
960
+ }
961
+ };
962
+ walk(element, depth);
963
+ return out;
964
+ }
965
+ listBlock(list) {
966
+ const { bullet } = this.options;
967
+ return {
968
+ md: list.items.map((item, index) => {
969
+ const marker = list.ordered ? `${String(list.start + index)}.` : bullet;
970
+ const check = item.check === null ? "" : item.check ? "[x] " : "[ ] ";
971
+ const nested = item.nested.map((child) => this.listBlock(child));
972
+ const body = join([...item.blocks, ...nested], this.options.hardBreak, true);
973
+ const indent = " ".repeat(marker.length + 1);
974
+ const [first = "", ...rest] = body.split("\n");
975
+ return [`${marker} ${check}${first}`.trimEnd(), ...rest.map((line) => line === "" ? "" : indent + line)].join("\n");
976
+ }).join("\n"),
977
+ ...PARA,
978
+ list: list.ordered ? "." : bullet
979
+ };
980
+ }
981
+ htmlList(element, ordered, ctx) {
982
+ const start = ordered ? Number.parseInt(element.getAttribute("start") ?? "1", 10) : 1;
983
+ const list = {
984
+ ordered,
985
+ start: Number.isSafeInteger(start) && start >= 0 && start <= 999999999 ? start : 1,
986
+ items: []
987
+ };
988
+ for (let child = element.firstChild; child !== null; child = child.nextSibling) {
989
+ if (child.nodeType === 3 && child.data.trim() === "") continue;
990
+ const tag = child.nodeType === 1 ? child.localName.toLowerCase() : "";
991
+ const previous = list.items[list.items.length - 1];
992
+ if ((tag === "ul" || tag === "ol" || tag === "menu") && previous !== void 0) {
993
+ previous.blocks.push(...this.block(child, tag, styleOf(child), {
994
+ ...ctx,
995
+ depth: ctx.depth + 1
996
+ }));
997
+ continue;
998
+ }
999
+ const nodes = tag === "li" ? children(child) : [child];
1000
+ list.items.push({
1001
+ blocks: this.blocks(nodes, {
1002
+ ...ctx,
1003
+ depth: ctx.depth + 1
1004
+ }, "line"),
1005
+ check: tag === "li" ? checkState(child) : null,
1006
+ nested: []
1007
+ });
1008
+ }
1009
+ return list;
1010
+ }
1011
+ /**
1012
+ * Word writes lists as paragraphs with `mso-list: l0 level2`, and the marker
1013
+ * (`1.`, `·`) as text inside a span hidden with `mso-list: Ignore`. Collects
1014
+ * the consecutive list paragraphs from `nodes[start]` into nested lists.
1015
+ * Returns the list blocks and how many nodes they consumed.
1016
+ */
1017
+ wordList(nodes, start, ctx) {
1018
+ const roots = [];
1019
+ const stack = [];
1020
+ let consumed = 0;
1021
+ for (let index = start; index < nodes.length; index += 1) {
1022
+ const node = nodes[index];
1023
+ if (node.nodeType === 8 || node.nodeType === 3 && node.data.trim() === "") continue;
1024
+ if (!isWordListParagraph(node)) break;
1025
+ consumed = index - start + 1;
1026
+ const paragraph = node;
1027
+ const level = Number(WORD_LIST.exec(paragraph.getAttribute("style"))?.[2]);
1028
+ const marker = (paragraph.querySelector("[style*=\"mso-list\"][style*=\"gnore\"]")?.textContent ?? "").replace(/\s+/g, "");
1029
+ const ordered = ORDERED_WORD_MARKER.exec(marker);
1030
+ const first = ordered && /^\d+$/.test(ordered[1]) ? Number(ordered[1]) : 1;
1031
+ while (stack.length > 0 && stack[stack.length - 1].level > level) stack.pop();
1032
+ let top = stack[stack.length - 1];
1033
+ if (top !== void 0 && top.level === level && top.list.ordered !== (ordered !== null)) {
1034
+ stack.pop();
1035
+ top = stack[stack.length - 1];
1036
+ }
1037
+ if (top === void 0 || top.level < level) {
1038
+ const list = {
1039
+ ordered: ordered !== null,
1040
+ start: first,
1041
+ items: []
1042
+ };
1043
+ const parent = top?.list.items[top.list.items.length - 1];
1044
+ if (parent === void 0) roots.push(list);
1045
+ else parent.nested.push(list);
1046
+ top = {
1047
+ level,
1048
+ list
1049
+ };
1050
+ stack.push(top);
1051
+ }
1052
+ top.list.items.push({
1053
+ blocks: this.blocks(children(paragraph), {
1054
+ ...ctx,
1055
+ depth: ctx.depth + 1
1056
+ }, "line"),
1057
+ check: null,
1058
+ nested: []
1059
+ });
1060
+ }
1061
+ return [roots.map((list) => this.listBlock(list)), consumed];
1062
+ }
1063
+ table(table, ctx) {
1064
+ const rows = Array.from(table.rows);
1065
+ const caption = table.caption ? this.blocks(children(table.caption), ctx, "para") : [];
1066
+ const role = table.getAttribute("role");
1067
+ if (role === "presentation" || role === "none" || rows.some((row) => Array.from(row.cells).some((cell) => cell.querySelector("table, ul, ol, pre, blockquote, h1, h2, h3, h4, h5, h6") !== null)) || rows.length === 1 && rows[0]?.cells.length === 1) return [...caption, ...rows.flatMap((row) => Array.from(row.cells).flatMap((cell) => this.blocks(children(cell), ctx, "line")))];
1068
+ const grid = [];
1069
+ const align = [];
1070
+ let cells = 0;
1071
+ let expand = true;
1072
+ rows.forEach((row, r) => {
1073
+ const line = grid[r] ?? (grid[r] = []);
1074
+ let c = 0;
1075
+ for (const cell of Array.from(row.cells)) {
1076
+ while (line[c] !== void 0) c += 1;
1077
+ let span = Math.min(Math.max(cell.colSpan, 1), MAX_COLSPAN);
1078
+ let down = Math.min(Math.max(cell.rowSpan || rows.length - r, 1), rows.length - r);
1079
+ if (!expand || cells + span * down > MAX_TABLE_CELLS) {
1080
+ this.truncated = true;
1081
+ expand = false;
1082
+ span = 1;
1083
+ down = 1;
1084
+ }
1085
+ cells += span * down;
1086
+ const md = this.inline(cell, {
1087
+ ...ctx,
1088
+ mask: cell.localName === "th" ? ctx.mask | 1 : ctx.mask
1089
+ }, true).trim();
1090
+ if (r === 0) align[c] = alignment(cell);
1091
+ for (let dr = 0; dr < down; dr += 1) {
1092
+ var _ref;
1093
+ const target = grid[_ref = r + dr] ?? (grid[_ref] = []);
1094
+ for (let dc = 0; dc < span; dc += 1) target[c + dc] = dr === 0 && dc === 0 ? md : "";
1095
+ }
1096
+ c += span;
1097
+ }
1098
+ });
1099
+ const width = grid.reduce((max, line) => Math.max(max, line.length), 0);
1100
+ if (width === 0 || grid.every((line) => line.every((cell) => cell === ""))) return caption;
1101
+ const format = (line) => `| ${Array.from({ length: width }, (_, index) => line[index] ?? "").join(" | ")} |`;
1102
+ const [head = [], ...body] = grid;
1103
+ const delimiter = `| ${Array.from({ length: width }, (_, index) => align[index] ?? "---").join(" | ")} |`;
1104
+ return [...caption, {
1105
+ md: [
1106
+ format(head),
1107
+ delimiter,
1108
+ ...body.map(format)
1109
+ ].join("\n"),
1110
+ ...PARA
1111
+ }];
1112
+ }
1113
+ };
1114
+ /**
1115
+ * Joins blocks: `line` blocks next to each other with a hard break, others with
1116
+ * a blank line. Inside a list item, a nested list follows its text directly so
1117
+ * the list stays tight. An empty block is a blank line between its neighbours.
1118
+ */
1119
+ function join(blocks, hardBreak, inItem = false) {
1120
+ let out = "";
1121
+ let separate = false;
1122
+ let previous = null;
1123
+ for (const original of blocks) {
1124
+ if (original.md === "") {
1125
+ separate = true;
1126
+ continue;
1127
+ }
1128
+ const block = original.list !== void 0 && previous?.list === original.list ? switchMarker(original) : original;
1129
+ if (previous !== null) {
1130
+ if (inItem && block.list !== void 0 && previous.list === void 0 && !separate) out += "\n";
1131
+ else out += !separate && previous.after === "line" && block.before === "line" ? hardBreak : "\n\n";
1132
+ }
1133
+ out += block.md;
1134
+ previous = block;
1135
+ separate = false;
1136
+ }
1137
+ return out;
1138
+ }
1139
+ const OTHER_MARKER = {
1140
+ "-": "*",
1141
+ "*": "-",
1142
+ "+": "-",
1143
+ ".": ")",
1144
+ ")": "."
1145
+ };
1146
+ /** The same list with its top-level marker switched. Item lines are the only lines at column 0. */
1147
+ function switchMarker(block) {
1148
+ const from = block.list;
1149
+ const to = OTHER_MARKER[from];
1150
+ const md = block.md.split("\n").map((line) => {
1151
+ if (line === "" || line.startsWith(" ")) return line;
1152
+ return from === "." || from === ")" ? line.replace(/^(\d+)[.)]/, `$1${to}`) : `${to}${line.slice(1)}`;
1153
+ }).join("\n");
1154
+ return {
1155
+ ...block,
1156
+ md,
1157
+ list: to
1158
+ };
1159
+ }
1160
+ function checkState(item) {
1161
+ const aria = item.getAttribute("aria-checked");
1162
+ if (item.getAttribute("role") === "checkbox" && (aria === "true" || aria === "false")) return aria === "true";
1163
+ for (const input of Array.from(item.querySelectorAll("input[type=\"checkbox\" i]"))) if (input.closest("li") === item) return input.hasAttribute("checked");
1164
+ return null;
1165
+ }
1166
+ const children = (node) => Array.from(node.childNodes);
1167
+ /** The blocks with paragraph breaks at both ends. */
1168
+ function spaced(blocks) {
1169
+ const first = blocks[0];
1170
+ if (first !== void 0) blocks[0] = {
1171
+ ...first,
1172
+ before: "para"
1173
+ };
1174
+ const last = blocks[blocks.length - 1];
1175
+ if (last !== void 0) blocks[blocks.length - 1] = {
1176
+ ...last,
1177
+ after: "para"
1178
+ };
1179
+ return blocks;
1180
+ }
1181
+ function isWordListParagraph(node) {
1182
+ return node.nodeType === 1 && WORD_LIST.test(node.getAttribute("style") ?? "");
1183
+ }
1184
+ function language(element) {
1185
+ const candidates = [
1186
+ element,
1187
+ element.querySelector("code"),
1188
+ element.parentElement
1189
+ ];
1190
+ for (const candidate of candidates) {
1191
+ if (candidate === null) continue;
1192
+ const named = candidate.getAttribute("data-language") ?? candidate.getAttribute("data-lang") ?? /(?:^|\s)(?:language|lang|highlight-source)-(\S+)/.exec(candidate.getAttribute("class") ?? "")?.[1];
1193
+ if (named !== void 0 && /^[A-Za-z0-9_+#.-]{1,30}$/.test(named)) return named;
1194
+ }
1195
+ return "";
1196
+ }
1197
+ function alignment(cell) {
1198
+ const value = (cell.getAttribute("align") ?? styleOf(cell).get("text-align") ?? "").toLowerCase();
1199
+ return value === "center" ? ":---:" : value === "right" ? "---:" : value === "left" ? ":---" : "---";
1200
+ }
1201
+ /**
1202
+ * Converts HTML to CommonMark with GFM tables, strikethrough and task lists.
1203
+ *
1204
+ * Strings are parsed in an inert document (scripts never run, nothing is
1205
+ * fetched), so pasted HTML is safe to pass. The output never contains raw HTML:
1206
+ * text that looks like Markdown or HTML is escaped, links and images keep only
1207
+ * allowed URL schemes, and images default to their alt text.
1208
+ *
1209
+ * Handles what real clipboards contain: Google Docs (bold and italic set by CSS,
1210
+ * the non-bold `<b>` wrapper, redirect links), Word (`mso-list` lists, hidden
1211
+ * markers), GitHub, Notion, code editors and mail layout tables.
1212
+ *
1213
+ * Needs `DOMParser` for strings (any browser, or jsdom); pass a `Node` to use
1214
+ * your own DOM. Throws an `unsupported` `CopyFailure` for a string without one.
1215
+ */
1216
+ function htmlToMarkdown(source, options = {}) {
1217
+ const resolved = resolveOptions(options);
1218
+ if (typeof source !== "string") return convert((source.nodeType === 9 ? source.body : null) ?? (source.nodeType === 9 ? source.documentElement : source), resolved, false);
1219
+ const { body, truncated } = parseHtml(source, resolved);
1220
+ return convert(body, resolved, truncated);
1221
+ }
1222
+ /** Parses HTML in an inert document, cut to `maxLength`. Throws `unsupported` without `DOMParser`. */
1223
+ function parseHtml(html, resolved) {
1224
+ if (typeof DOMParser === "undefined") throw copyFailure("unsupported", "htmlToMarkdown needs DOMParser to read an HTML string; pass a DOM node instead.");
1225
+ return {
1226
+ body: new DOMParser().parseFromString(html.slice(0, resolved.maxLength), "text/html").body,
1227
+ truncated: html.length > resolved.maxLength
1228
+ };
1229
+ }
1230
+ /** Converts a node: an element with itself included (its heading, list or table), a body or fragment by its children. */
1231
+ function convert(root, resolved, truncated) {
1232
+ const converter = new Converter(resolved);
1233
+ const ctx = {
1234
+ style: 0,
1235
+ mask: 0,
1236
+ href: null,
1237
+ depth: 0
1238
+ };
1239
+ const nodes = root.nodeType === 1 && root.nodeName !== "BODY" ? [root] : children(root);
1240
+ return {
1241
+ markdown: join(converter.blocks(nodes, ctx, "para"), resolved.hardBreak).trim(),
1242
+ truncated: truncated || converter.truncated
1243
+ };
1244
+ }
1245
+ //#endregion
1246
+ //#region src/markdown/paste.ts
1247
+ const MONOSPACE_PRE = /white-space\s*:\s*pre/i;
1248
+ const MONOSPACE_FONT = /font-family\s*:[^;]*\b(monospace|courier|consolas|menlo|monaco|mono)\b/i;
1249
+ /** Every visible character sits inside a `<pre>` or a monospace `white-space: pre` box. */
1250
+ function isCodeOnly(body) {
1251
+ const walker = body.ownerDocument.createTreeWalker(body, 4);
1252
+ let seen = false;
1253
+ for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
1254
+ if (node.data.trim() === "") continue;
1255
+ seen = true;
1256
+ let code = false;
1257
+ for (let element = node.parentElement; element !== null && element !== body; element = element.parentElement) {
1258
+ const style = element.getAttribute("style") ?? "";
1259
+ if (element.localName === "pre" || MONOSPACE_PRE.test(style) && MONOSPACE_FONT.test(style)) {
1260
+ code = true;
1261
+ break;
1262
+ }
1263
+ }
1264
+ if (!code) return false;
1265
+ }
1266
+ return seen;
1267
+ }
1268
+ /**
1269
+ * Markdown for what was pasted. Rich content (the HTML flavour) is converted;
1270
+ * plain text is returned as it is, because plain text pasted into a Markdown
1271
+ * editor is usually Markdown already (copied from another `.md` file or editor),
1272
+ * and escaping it would break it. Returns `null` when there is nothing to paste.
1273
+ *
1274
+ * Never throws for clipboard content: on a server without `DOMParser`, or when
1275
+ * the HTML holds nothing to convert, it falls back to the text.
1276
+ *
1277
+ * @example
1278
+ * usePaste({ accept: ['html', 'text'], onPaste: (result) => {
1279
+ * const pasted = pasteToMarkdown(result);
1280
+ * if (pasted) insertText(textarea, pasted.markdown);
1281
+ * } });
1282
+ */
1283
+ function pasteToMarkdown(source, options = {}) {
1284
+ const resolved = resolveOptions(options);
1285
+ const text = source.text ?? null;
1286
+ const html = source.html ?? null;
1287
+ if (html !== null && html.trim() !== "" && typeof DOMParser !== "undefined") {
1288
+ const { body, truncated } = parseHtml(html, resolved);
1289
+ if (!(options.codeAsText !== false && text !== null && text !== "" && isCodeOnly(body))) {
1290
+ const converted = convert(body, resolved, truncated);
1291
+ if (converted.markdown !== "") return {
1292
+ ...converted,
1293
+ source: "html"
1294
+ };
1295
+ }
1296
+ }
1297
+ return text === null || text === "" ? null : {
1298
+ markdown: text.replace(/\r\n?/g, "\n"),
1299
+ source: "text",
1300
+ truncated: false
1301
+ };
1302
+ }
1303
+ const TEXT_INPUTS = /* @__PURE__ */ new Set([
1304
+ "text",
1305
+ "search",
1306
+ "url",
1307
+ "tel",
1308
+ "password"
1309
+ ]);
1310
+ function asTextField(target) {
1311
+ if (typeof target !== "object" || target === null) return null;
1312
+ const element = target;
1313
+ if (element.nodeName === "TEXTAREA") return target;
1314
+ if (element.nodeName === "INPUT" && typeof element.type === "string" && TEXT_INPUTS.has(element.type)) return target;
1315
+ return null;
1316
+ }
1317
+ /**
1318
+ * Inserts text at the cursor of a `<textarea>` or text `<input>`, replacing the
1319
+ * selection, as typing or pasting would: the browser's undo (Ctrl/⌘+Z) still
1320
+ * works, `input` events fire (so React and other frameworks see the change),
1321
+ * and `maxlength` is respected. Returns `false` for disabled or read-only fields.
1322
+ */
1323
+ function insertText(field, text) {
1324
+ if (field.disabled || field.readOnly) return false;
1325
+ const value = field.nodeName === "INPUT" ? text.replace(/[ \t]*(?:\r\n|\r|\n)+[ \t]*/g, " ") : text;
1326
+ const doc = field.ownerDocument;
1327
+ field.focus();
1328
+ const start = field.selectionStart;
1329
+ const end = field.selectionEnd;
1330
+ try {
1331
+ if (start !== null && end !== null) field.setSelectionRange(start, end);
1332
+ if (doc.activeElement === field && doc.execCommand("insertText", false, value)) return true;
1333
+ } catch {}
1334
+ const from = start ?? field.value.length;
1335
+ const to = end ?? from;
1336
+ let insert = value;
1337
+ if (field.maxLength >= 0) {
1338
+ const room = Math.max(0, field.maxLength - (field.value.length - (to - from)));
1339
+ insert = insert.slice(0, room);
1340
+ if (/[\ud800-\udbff]$/.test(insert)) insert = insert.slice(0, -1);
1341
+ }
1342
+ if (start === null) setNativeValue(field, field.value + insert);
1343
+ else field.setRangeText(insert, from, to, "end");
1344
+ const view = doc.defaultView;
1345
+ const event = view !== null && typeof view.InputEvent === "function" ? new view.InputEvent("input", {
1346
+ bubbles: true,
1347
+ inputType: "insertFromPaste",
1348
+ data: insert
1349
+ }) : new Event("input", { bubbles: true });
1350
+ field.dispatchEvent(event);
1351
+ return true;
1352
+ }
1353
+ /**
1354
+ * Sets a field's value through the prototype's setter. React tracks the value
1355
+ * set on the element itself; going around it lets React see the change and
1356
+ * call `onChange` for the `input` event that follows.
1357
+ */
1358
+ function setNativeValue(field, next) {
1359
+ const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(field), "value")?.set;
1360
+ if (setter) setter.call(field, next);
1361
+ else field.value = next;
1362
+ }
1363
+ /**
1364
+ * A paste handler for Markdown text fields: when the clipboard holds rich
1365
+ * content (Google Docs, Word, a web page), it is inserted as Markdown; plain
1366
+ * text and code pastes are left to the browser, untouched. Returns whether it
1367
+ * handled the paste.
1368
+ *
1369
+ * @example
1370
+ * <textarea onPaste={pasteAsMarkdown} />
1371
+ * <textarea onPaste={(event) => pasteAsMarkdown(event, { images: 'keep' })} />
1372
+ */
1373
+ function pasteAsMarkdown(event, options) {
1374
+ if (event.defaultPrevented || event.clipboardData === null) return false;
1375
+ const field = asTextField(event.currentTarget) ?? asTextField(event.target);
1376
+ if (field === null || field.disabled || field.readOnly) return false;
1377
+ const html = event.clipboardData.getData("text/html");
1378
+ if (html === "") return false;
1379
+ let pasted;
1380
+ try {
1381
+ pasted = pasteToMarkdown({
1382
+ html,
1383
+ text: event.clipboardData.getData("text/plain")
1384
+ }, options);
1385
+ } catch {
1386
+ return false;
1387
+ }
1388
+ if (pasted?.source !== "html") return false;
1389
+ event.preventDefault();
1390
+ return insertText(field, pasted.markdown);
1391
+ }
1392
+ //#endregion
1393
+ export { DEFAULT_IMAGE_PROTOCOLS, DEFAULT_LINK_PROTOCOLS, DEFAULT_MARKDOWN_MAX_DEPTH, DEFAULT_MARKDOWN_MAX_LENGTH, DEFAULT_MARKDOWN_MAX_NODES, escapeMarkdown, htmlToMarkdown, insertText, pasteAsMarkdown, pasteToMarkdown };
1394
+
1395
+ //# sourceMappingURL=markdown.js.map