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 @@
1
+ {"version":3,"file":"markdown.cjs","names":[],"sources":["../src/core/errors.ts","../src/markdown/escape.ts","../src/markdown/url.ts","../src/markdown/inline.ts","../src/markdown/convert.ts","../src/markdown/paste.ts"],"sourcesContent":["import type { PasteSource } from './paste-reader';\n\n/**\n * Every way a clipboard operation can fail, as a closed union.\n *\n * `CopyError.message` is developer-facing (logs, telemetry). For user-facing\n * text use {@link describeCopyError} / {@link describePasteError}, or map\n * `type` through your own i18n layer.\n */\nexport type CopyErrorType =\n /** No Clipboard API (old browser, server, locked-down webview). Not retryable. */\n | 'unsupported'\n /** Page is not served over HTTPS/localhost. Not retryable. */\n | 'insecure-context'\n /** Browser or user blocked the operation. Also what Safari reports for a missing user gesture. */\n | 'permission-denied'\n /** The document lost focus mid-operation (Chromium). Retrying after refocus usually works. */\n | 'not-focused'\n /** Empty or malformed payload, or a lazy source that threw. Caught before touching the clipboard. */\n | 'invalid-payload'\n /** The browser cannot handle this MIME type (e.g. non-PNG image, HTML without ClipboardItem). */\n | 'unsupported-format'\n /** A lazy image source (or capture) threw, rejected or did not produce a Blob. */\n | 'blob-generation-failed'\n /** `retry()` was called after `maxRetries` was reached. Terminal. */\n | 'max-retries-exceeded'\n /** Paste: the clipboard held nothing matching `accept`. */\n | 'no-content'\n /** Content exceeded a configured safety limit (bytes, items or pixels). Not retryable. */\n | 'too-large'\n /** An operation did not settle within its deadline. Retryable. */\n | 'timeout'\n /** The caller aborted the operation through an `AbortSignal`. Not retryable. */\n | 'aborted'\n /** Anything the platform threw that we could not classify. */\n | 'unknown';\n\n/** Which clipboard direction failed; only changes developer-facing messages. */\nexport type ClipboardOperation = 'write' | 'read';\n\nexport interface CopyError {\n readonly type: CopyErrorType;\n readonly message: string;\n readonly cause?: unknown;\n}\n\nexport function createCopyError(type: CopyErrorType, message: string, cause?: unknown): CopyError {\n return cause === undefined ? { type, message } : { type, message, cause };\n}\n\nconst RETRYABLE_ERRORS: ReadonlySet<CopyErrorType> = /* @__PURE__ */ new Set<CopyErrorType>([\n 'permission-denied',\n 'not-focused',\n 'blob-generation-failed',\n 'timeout',\n 'unknown',\n]);\n\n/** Whether retrying the same payload could plausibly succeed. */\nexport function isRetryableError(error: CopyError): boolean {\n return RETRYABLE_ERRORS.has(error.type);\n}\n\n/**\n * Branded (not `instanceof`) so failures stay recognisable even when the core\n * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.\n */\nconst COPY_FAILURE_BRAND = Symbol.for('react-smart-copy.CopyFailure');\n\n/** Error thrown by adapters to carry a fully classified {@link CopyError}. */\nexport class CopyFailure extends Error {\n readonly copyError: CopyError;\n readonly [COPY_FAILURE_BRAND] = true;\n\n constructor(copyError: CopyError) {\n super(copyError.message);\n this.name = 'CopyFailure';\n this.copyError = copyError;\n }\n}\n\nexport function isCopyFailure(value: unknown): value is CopyFailure {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<PropertyKey, unknown>)[COPY_FAILURE_BRAND] === true\n );\n}\n\n/** Shorthand for throwing a classified failure. */\nexport function copyFailure(type: CopyErrorType, message: string, cause?: unknown): CopyFailure {\n return new CopyFailure(createCopyError(type, message, cause));\n}\n\nfunction readString(value: unknown, key: string): string | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const field = (value as Record<string, unknown>)[key];\n return typeof field === 'string' ? field : undefined;\n}\n\n/**\n * Classifies anything thrown by the platform or an adapter into a {@link CopyError}.\n * `operation` only tailors the developer-facing message.\n */\nexport function toCopyError(cause: unknown, operation: ClipboardOperation = 'write'): CopyError {\n if (isCopyFailure(cause)) return cause.copyError;\n\n const name = readString(cause, 'name');\n const message = readString(cause, 'message') ?? '';\n const verb = operation === 'read' ? 'read' : 'write';\n\n switch (name) {\n case 'NotAllowedError':\n return /focus/i.test(message)\n ? createCopyError('not-focused', `The document was not focused during the clipboard ${verb}.`, cause)\n : createCopyError('permission-denied', `Clipboard ${verb} permission was denied.`, cause);\n case 'SecurityError':\n return createCopyError('insecure-context', 'The clipboard is blocked in this context.', cause);\n case 'NotSupportedError':\n case 'DataError':\n return createCopyError('unsupported-format', 'The browser rejected this clipboard format.', cause);\n case 'AbortError':\n return createCopyError('aborted', `The clipboard ${verb} was aborted.`, cause);\n case 'TimeoutError':\n return createCopyError('timeout', `The clipboard ${verb} timed out.`, cause);\n default:\n return createCopyError('unknown', message || `The clipboard ${verb} failed for an unknown reason.`, cause);\n }\n}\n\nconst COPY_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Copying isn't supported in this browser.\",\n 'insecure-context': 'Copying requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while copying. Try again.',\n 'invalid-payload': 'There is nothing to copy.',\n 'unsupported-format': \"This content can't be copied in this browser.\",\n 'blob-generation-failed': \"The image couldn't be prepared for copying.\",\n 'max-retries-exceeded': 'Copying failed after several attempts.',\n 'no-content': 'There is nothing to copy.',\n 'too-large': 'This content is too large to copy.',\n timeout: 'Copying took too long. Try again.',\n aborted: 'Copying was cancelled.',\n unknown: \"Couldn't copy to the clipboard. Try again.\",\n};\n\nconst PASTE_DESCRIPTIONS: Readonly<Record<CopyErrorType, string>> = {\n unsupported: \"Pasting isn't supported in this browser.\",\n 'insecure-context': 'Pasting requires a secure (HTTPS) connection.',\n 'permission-denied': 'Clipboard access was blocked. Allow it and try again.',\n 'not-focused': 'The page lost focus while pasting. Try again.',\n 'invalid-payload': \"The clipboard content couldn't be read.\",\n 'unsupported-format': \"This clipboard content isn't supported here.\",\n 'blob-generation-failed': \"The pasted image couldn't be read.\",\n 'max-retries-exceeded': 'Pasting failed after several attempts.',\n 'no-content': \"The clipboard doesn't contain anything that can be pasted here.\",\n 'too-large': 'The clipboard content is too large to paste.',\n timeout: 'Pasting took too long. Try again.',\n aborted: 'Pasting was cancelled.',\n unknown: \"Couldn't read the clipboard. Try again.\",\n};\n\n/** Default English, user-facing sentence for a copy error. Replace for i18n. */\nexport function describeCopyError(error: CopyError): string {\n return COPY_DESCRIPTIONS[error.type];\n}\n\n/** Drops can only fail in these ways; the rest of the paste wording would mention the clipboard. */\nconst DROP_DESCRIPTIONS: Readonly<Partial<Record<CopyErrorType, string>>> = {\n 'invalid-payload': \"The dropped content couldn't be read.\",\n 'no-content': 'Nothing that was dropped can be used here.',\n 'too-large': 'The dropped content is too large.',\n unknown: \"Couldn't read the dropped content. Try again.\",\n};\n\n/**\n * Default English, user-facing sentence for a paste error. Pass the error\n * state's `source` to word drag-and-drop failures as drops. Replace for i18n.\n */\nexport function describePasteError(error: CopyError, source?: PasteSource): string {\n return (source === 'drop' ? DROP_DESCRIPTIONS[error.type] : undefined) ?? PASTE_DESCRIPTIONS[error.type];\n}\n","/**\n * CommonMark escaping. Pasted text must render as the same text, never as\n * Markdown syntax and never as raw HTML, so every character that can start a\n * construct is backslash-escaped. Backslash escapes are valid before any ASCII\n * punctuation, so over-escaping is always safe; under-escaping is not.\n */\n\n/**\n * Characters that are special anywhere in a line: emphasis, code spans,\n * links, strikethrough (GFM) and `<`, which starts raw HTML and autolinks.\n */\nconst INLINE = /[\\\\`*_[\\]<~]/g;\n\n/** `&` that would start an entity or numeric character reference. */\nconst ENTITY = /&(?=#?[A-Za-z0-9]+;)/g;\n\n/** Escapes text for use inside a line. With `pipes`, also `|`, for GFM table cells. */\nexport function escapeInline(text: string, pipes = false): string {\n const escaped = text.replace(INLINE, '\\\\$&').replace(ENTITY, '\\\\&');\n return pipes ? escaped.replace(/\\|/g, '\\\\|') : escaped;\n}\n\nconst ORDERED_MARKER = /^(\\d{1,9})([.)])/;\nconst BLOCK_START = /^[#>+=|-]/;\n\n/**\n * Escapes the start of already inline-escaped text that begins a line, where\n * `#`, `>`, `-`, `+`, `=`, `|` and `1.` / `1)` would start a block.\n */\nexport function escapeLineStart(text: string): string {\n const ordered = ORDERED_MARKER.exec(text);\n if (ordered) return `${ordered[1] as string}\\\\${text.slice((ordered[1] as string).length)}`;\n return BLOCK_START.test(text) ? `\\\\${text}` : text;\n}\n\n/**\n * Escapes plain text so Markdown renders it literally: no emphasis, links,\n * headings, lists, code or raw HTML. Line breaks are kept; leading whitespace\n * on each line is removed, since Markdown would read four spaces as code.\n *\n * @example\n * escapeMarkdown('1. *Not* a list <b>') // '1\\\\. \\\\*Not\\\\* a list \\\\<b>'\n */\nexport function escapeMarkdown(text: string): string {\n return text\n .split(/\\r\\n|\\r|\\n/)\n .map((line) => escapeLineStart(escapeInline(line.replace(/^[ \\t]+/, ''))))\n .join('\\n');\n}\n","/**\n * URL safety for pasted links and images. Only absolute URLs with an allowed\n * scheme survive; everything else (`javascript:`, `data:`, `vbscript:`,\n * relative links without a base, malformed URLs) is dropped and the visible\n * text is kept. Parsing uses the WHATWG URL parser, the same one the browser\n * uses when the link is clicked, so tricks like `java\\tscript:` are seen as\n * `javascript:`.\n */\n\nexport const DEFAULT_LINK_PROTOCOLS: readonly string[] = ['http:', 'https:', 'mailto:'];\nexport const DEFAULT_IMAGE_PROTOCOLS: readonly string[] = ['https:', 'http:'];\n\nfunction parse(raw: string, base: string | undefined): URL | null {\n try {\n return new URL(raw.trim(), base);\n } catch {\n return null;\n }\n}\n\n/**\n * Click-tracking redirects that pasted links often carry: Google (Docs,\n * Search, Gmail) and Outlook Safe Links. Unwrapped only to an http(s) target.\n */\nfunction unwrapRedirect(url: URL): URL {\n const host = url.hostname.toLowerCase();\n const param =\n /(^|\\.)google\\.[a-z.]+$/.test(host) && url.pathname === '/url'\n ? (url.searchParams.get('q') ?? url.searchParams.get('url'))\n : host.endsWith('.safelinks.protection.outlook.com')\n ? url.searchParams.get('url')\n : null;\n if (param === null) return url;\n const target = parse(param, undefined);\n return target !== null && (target.protocol === 'https:' || target.protocol === 'http:') ? target : url;\n}\n\n/** The normalised URL, or `null` when it is not absolute or its scheme is not allowed. */\nexport function safeUrl(raw: string, protocols: readonly string[], base: string | undefined): string | null {\n const parsed = parse(raw, base);\n if (parsed === null) return null;\n const url = unwrapRedirect(parsed);\n return protocols.includes(url.protocol) ? url.href : null;\n}\n\n/** `href` comes from the URL serialiser, which already percent-encodes every non-ASCII character. */\nconst percent = (char: string): string => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`;\n\n/**\n * A Markdown link destination. ASCII whitespace, `<`, `>` and controls are\n * percent-encoded (opaque URLs such as `mailto:` keep them otherwise),\n * backslashes too so they can't act as escapes, and parentheses are kept\n * exact by using the `<…>` form.\n */\nexport function linkDestination(href: string): string {\n // eslint-disable-next-line no-control-regex -- control characters are exactly what must be encoded\n const encoded = href.replace(/[ <>\\\\\\u0000-\\u001f\\u007f]/g, percent);\n return /[()]/.test(encoded) ? `<${encoded}>` : encoded;\n}\n","import { escapeInline, escapeLineStart } from './escape';\nimport { linkDestination } from './url';\n\n/**\n * Inline content is collected as style runs (text with a set of styles and an\n * optional link), the way rich-text editors model it, instead of being\n * translated tag by tag. That handles what pasted HTML really looks like:\n * bold set by CSS on spans (Google Docs, Word), one bold word split over three\n * spans, `<b>` used as a non-bold wrapper. Delimiters are then placed from the\n * runs, spaces are moved outside them, and any delimiter pair that CommonMark\n * would not recognise (its flanking rules) is dropped, so formatting can be\n * lost in rare spots but text never turns into literal `**`.\n */\n\nexport const STRONG = 1;\nexport const EM = 2;\nexport const STRIKE = 4;\nexport const CODE = 8;\n\nexport type Run =\n | { readonly kind: 'text'; readonly text: string; readonly style: number; readonly href: string | null }\n | { readonly kind: 'image'; readonly alt: string; readonly src: string; readonly style: number; readonly href: string | null }\n | { readonly kind: 'break' };\n\nexport interface InlineOptions {\n /** Escape `|` for a GFM table cell. */\n readonly pipes: boolean;\n /** The hard line break: `\\\\\\n` or ` \\n`. */\n readonly hardBreak: string;\n}\n\ninterface Delimiter {\n readonly marker: string;\n readonly pair: number;\n readonly open: boolean;\n}\n\n/** Delimiter tokens are rewritten in place when emphasis switches from `*` to `_`. */\ninterface DelimToken {\n readonly kind: 'delim';\n s: string;\n delim: Delimiter;\n}\n\n/** `text` tokens hold escaped text and can take line-start escaping; others are syntax. */\ntype Token =\n | { kind: 'text'; s: string }\n | { readonly kind: 'syntax'; readonly s: string }\n | DelimToken\n | { readonly kind: 'break'; readonly s: string };\n\n/** Outermost first: a style lower in the list is always nested inside the ones above it. */\nconst ORDER: readonly (readonly [bit: number, marker: string])[] = [\n [STRIKE, '~~'],\n [STRONG, '**'],\n [EM, '*'],\n];\n\n/** HTML's collapsible whitespace. A no-break space is content: HTML neither collapses nor trims it. */\nconst SPACE = /[ \\t\\n\\r\\f]+/g;\n/** CommonMark's Unicode whitespace: Zs, tab, LF, FF, CR (not U+2028, which JavaScript's `\\s` includes). */\nconst WHITESPACE = /[\\t\\n\\f\\r\\p{Zs}]/u;\nconst PUNCTUATION = /[\\p{P}\\p{S}]/u;\n\n/** Collapses HTML whitespace across runs and trims it at line starts and ends. */\nfunction normalize(runs: readonly Run[]): Run[] {\n const out: Run[] = [];\n let atStart = true;\n for (const run of runs) {\n if (run.kind === 'break') {\n out.push(run);\n atStart = true;\n continue;\n }\n if (run.kind === 'image') {\n out.push(run);\n atStart = false;\n continue;\n }\n let text = run.text.replace(SPACE, ' ');\n // Line edges lose all whitespace, no-break spaces included: renderers disagree on keeping it there.\n if (atStart) text = text.replace(/^\\s+/, '');\n else if (lastText(out).endsWith(' ')) text = text.replace(/^ /, '');\n if (text === '') continue;\n out.push({ ...run, text });\n atStart = false;\n }\n // Trim trailing spaces before every break and at the end; drop leading and trailing breaks.\n const trimmed: Run[] = [];\n for (const run of [...out, { kind: 'break' } as const]) {\n if (run.kind === 'break') {\n trimTrailingSpace(trimmed);\n if (trimmed.length > 0 && trimmed[trimmed.length - 1]?.kind !== 'break') trimmed.push(run);\n continue;\n }\n trimmed.push(run);\n }\n trimmed.pop(); // the sentinel (or a trailing break)\n return trimmed;\n}\n\nfunction lastText(runs: readonly Run[]): string {\n const last = runs[runs.length - 1];\n return last?.kind === 'text' ? last.text : '';\n}\n\nfunction trimTrailingSpace(runs: Run[]): void {\n for (let last = runs[runs.length - 1]; last?.kind === 'text'; last = runs[runs.length - 1]) {\n const text = last.text.replace(/\\s+$/, '');\n if (text !== '') {\n runs[runs.length - 1] = { ...last, text };\n return;\n }\n runs.pop();\n }\n}\n\n/** Splits text into leading spaces, content and trailing spaces. */\nfunction splitSpaces(text: string): [lead: string, core: string, trail: string] {\n const core = text.trim();\n if (core === '') return [text, '', ''];\n const start = text.indexOf(core);\n return [text.slice(0, start), core, text.slice(start + core.length)];\n}\n\nfunction codeSpan(text: string, pipes: boolean): string {\n let longest = 0;\n for (const match of text.matchAll(/`+/g)) longest = Math.max(longest, match[0].length);\n const fence = '`'.repeat(longest + 1);\n const body = pipes ? text.replace(/\\|/g, '\\\\|') : text;\n // A leading or trailing backtick would merge with the fence; a space on both sides is stripped once.\n const padded = /^`|`$/.test(body) || /^ .* $/.test(body) ? ` ${body} ` : body;\n return `${fence}${padded}${fence}`;\n}\n\n/** Serialises runs into tokens. */\nfunction tokenize(runs: readonly Run[], options: InlineOptions): Token[] {\n const tokens: Token[] = [];\n const stack: { bit: number; pair: number; marker: string }[] = [];\n let pairs = 0;\n let href: string | null = null;\n let linkStart = -1;\n let pending = '';\n\n const closeFrom = (index: number): void => {\n while (stack.length > index) {\n const top = stack.pop() as { bit: number; pair: number; marker: string };\n tokens.push({ kind: 'delim', s: top.marker, delim: { marker: top.marker, pair: top.pair, open: false } });\n }\n };\n const flushPending = (): void => {\n if (pending !== '') tokens.push({ kind: 'text', s: pending });\n pending = '';\n };\n const setStyle = (style: number, lead: string): void => {\n const keep = stack.findIndex((entry) => (style & entry.bit) === 0);\n closeFrom(keep === -1 ? stack.length : keep);\n pending += lead;\n flushPending();\n for (const [bit, marker] of ORDER) {\n if ((style & bit) !== 0 && !stack.some((entry) => entry.bit === bit)) {\n pairs += 1;\n stack.push({ bit, pair: pairs, marker });\n tokens.push({ kind: 'delim', s: marker, delim: { marker, pair: pairs, open: true } });\n }\n }\n };\n const closeLink = (): void => {\n closeFrom(0);\n if (href === null) return;\n if (tokens.length - 1 === linkStart) tokens.pop(); // a link with no content is dropped\n else tokens.push({ kind: 'syntax', s: `](${linkDestination(href)})` });\n href = null;\n };\n\n for (let index = 0; index < runs.length; index += 1) {\n const run = runs[index] as Run;\n if (run.kind === 'break') {\n closeLink();\n pending = '';\n tokens.push({ kind: 'break', s: options.hardBreak });\n continue;\n }\n if (run.href !== href) {\n closeLink();\n flushPending();\n if (run.href !== null) {\n href = run.href;\n linkStart = tokens.length;\n tokens.push({ kind: 'syntax', s: '[' });\n }\n }\n if (run.kind === 'image') {\n setStyle(run.style & ~CODE, '');\n tokens.push({ kind: 'syntax', s: `![${escapeInline(run.alt, options.pipes)}](${linkDestination(run.src)})` });\n continue;\n }\n // Consecutive code runs with the same style and link form one code span.\n let text = run.text;\n if ((run.style & CODE) !== 0) {\n for (let next = runs[index + 1]; next?.kind === 'text' && next.style === run.style && next.href === run.href; next = runs[index + 1]) {\n text += next.text;\n index += 1;\n }\n }\n const [lead, core, trail] = splitSpaces(text);\n if (core === '') {\n pending += lead; // whitespace keeps the current styles, so \"**a** **b**\" stays one span\n continue;\n }\n setStyle(run.style & ~CODE, lead);\n tokens.push((run.style & CODE) !== 0 ? { kind: 'syntax', s: codeSpan(core, options.pipes) } : { kind: 'text', s: escapeInline(core, options.pipes) });\n pending = trail;\n }\n closeLink();\n flushPending();\n return tokens;\n}\n\n/**\n * The character next to a delimiter run, at token `index` (the token just\n * outside the run). Line starts and ends count as whitespace. Runs are maximal,\n * so this token is never a delimiter of the same character.\n */\nfunction neighbour(tokens: readonly Token[], index: number, step: 1 | -1): string {\n const token = tokens[index];\n if (token === undefined || token.kind === 'break') return '\\n';\n // Whole code points (the `u` flag): an astral symbol is punctuation to CommonMark, half of one is not.\n return ((step === 1 ? FIRST_CHAR : LAST_CHAR).exec(token.s) as RegExpExecArray)[0];\n}\n\nconst FIRST_CHAR = /^[\\s\\S]/u;\nconst LAST_CHAR = /[\\s\\S]$/u;\n\nconst leftFlanking = (before: string, after: string): boolean =>\n !WHITESPACE.test(after) && (!PUNCTUATION.test(after) || WHITESPACE.test(before) || PUNCTUATION.test(before));\nconst rightFlanking = (before: string, after: string): boolean =>\n !WHITESPACE.test(before) && (!PUNCTUATION.test(before) || WHITESPACE.test(after) || PUNCTUATION.test(after));\n\n/** GFM strikethrough: can this `~~` open (left-flanking) or close (right-flanking)? */\nfunction strikeFlanks(tokens: readonly Token[], index: number, delim: Delimiter): boolean {\n const before = neighbour(tokens, index - 1, -1);\n const after = neighbour(tokens, index + 1, 1);\n return delim.open ? leftFlanking(before, after) : rightFlanking(before, after);\n}\n\n/**\n * Adjacent `*` delimiters form one delimiter run. When a run both closes one span\n * and opens another (`*a***b**`), CommonMark can pair them differently than meant,\n * so the emphasis (`*`) pairs in such a run switch to `_`, which is a separate run.\n */\nfunction separateMixedRuns(tokens: readonly Token[]): void {\n let group: DelimToken[] = [];\n const settle = (): void => {\n const opens = group.filter((token) => token.delim.open);\n const closes = group.filter((token) => !token.delim.open);\n if (opens.length > 0 && closes.length > 0) {\n // Switch the emphasis that opens here; if only strong opens, the emphasis that closes.\n const emphasisOpens = opens.filter((token) => token.delim.marker === '*');\n const switching = emphasisOpens.length > 0 ? emphasisOpens : closes.filter((token) => token.delim.marker === '*');\n const pairs = new Set(switching.map((token) => token.delim.pair));\n for (const token of tokens) {\n if (token.kind === 'delim' && pairs.has(token.delim.pair)) {\n token.s = '_';\n token.delim = { ...token.delim, marker: '_' };\n }\n }\n }\n group = [];\n };\n for (const token of tokens) {\n if (token.kind === 'delim' && token.delim.marker[0] === '*') group.push(token);\n else settle();\n }\n settle();\n}\n\ninterface DelimiterChar {\n readonly pair: number;\n readonly open: boolean;\n matched: boolean;\n}\n\n/** One delimiter run on CommonMark's delimiter stack. `front`/`len`: the characters not yet used. */\ninterface StackEntry {\n readonly char: string;\n readonly orig: number;\n readonly canOpen: boolean;\n readonly canClose: boolean;\n readonly chars: DelimiterChar[];\n front: number;\n len: number;\n}\n\n/** Groups the delimiter tokens at `indexes` into runs (adjacent `*` or adjacent `_`). */\nfunction runsOf(tokens: readonly Token[], indexes: readonly number[]): StackEntry[] {\n const entries: StackEntry[] = [];\n let run: number[] = [];\n const close = (): void => {\n if (run.length === 0) return;\n const firstIndex = run[0] as number;\n const lastIndex = run[run.length - 1] as number;\n const char = ((tokens[firstIndex] as DelimToken).delim.marker[0]) as string;\n const before = neighbour(tokens, firstIndex - 1, -1);\n const after = neighbour(tokens, lastIndex + 1, 1);\n const left = leftFlanking(before, after);\n const right = rightFlanking(before, after);\n const chars = run.flatMap((index) => {\n const { delim } = tokens[index] as DelimToken;\n return Array.from(delim.marker, () => ({ pair: delim.pair, open: delim.open, matched: false }));\n });\n entries.push({\n char,\n orig: chars.length,\n canOpen: char === '_' ? left && (!right || PUNCTUATION.test(before)) : left,\n canClose: char === '_' ? right && (!left || PUNCTUATION.test(after)) : right,\n chars,\n front: 0,\n len: chars.length,\n });\n run = [];\n };\n let previous = -1;\n for (const index of indexes) {\n const token = tokens[index] as Token;\n const emphasis = token.kind === 'delim' && token.delim.marker[0] !== '~';\n const adjacent = previous === index - 1;\n const sameChar = run.length > 0 && emphasis && (tokens[run[0] as number] as DelimToken).delim.marker[0] === (token).delim.marker[0];\n if (!emphasis || !adjacent || !sameChar) close();\n if (emphasis) run.push(index);\n previous = index;\n }\n close();\n return entries;\n}\n\n/**\n * CommonMark's \"process emphasis\" algorithm, run on our own output: it pairs\n * delimiter characters exactly as a Markdown renderer will. Returns the pairs\n * whose characters would not be paired as intended (they would render as\n * literal asterisks or pair with the wrong span).\n */\nfunction misread(tokens: readonly Token[], indexes: readonly number[]): Set<number> {\n const stack = runsOf(tokens, indexes);\n const failed = new Set<number>();\n let current = 0;\n while (current < stack.length) {\n const closer = stack[current] as StackEntry;\n if (!closer.canClose || closer.len === 0) {\n current += 1;\n continue;\n }\n let openerIndex = current - 1;\n for (; openerIndex >= 0; openerIndex -= 1) {\n const opener = stack[openerIndex] as StackEntry;\n if (opener.char !== closer.char || !opener.canOpen || opener.len === 0) continue;\n const oddMatch = (closer.canOpen || opener.canClose) && closer.orig % 3 !== 0 && (opener.orig + closer.orig) % 3 === 0;\n if (!oddMatch) break;\n }\n if (openerIndex < 0) {\n current += 1;\n continue;\n }\n const opener = stack[openerIndex] as StackEntry;\n const use = closer.len >= 2 && opener.len >= 2 ? 2 : 1;\n for (let k = 0; k < use; k += 1) {\n const open = opener.chars[opener.front + opener.len - 1] as DelimiterChar;\n const shut = closer.chars[closer.front] as DelimiterChar;\n opener.len -= 1;\n closer.front += 1;\n closer.len -= 1;\n open.matched = true;\n shut.matched = true;\n if (open.pair !== shut.pair || !open.open || shut.open) {\n failed.add(open.pair);\n failed.add(shut.pair);\n }\n }\n // Delimiters between the opener and the closer can no longer match anything.\n for (let between = openerIndex + 1; between < current; between += 1) (stack[between] as StackEntry).len = 0;\n }\n for (const entry of stack) for (const char of entry.chars) if (!char.matched) failed.add(char.pair);\n return failed;\n}\n\n/** The delimiter token indexes inside each link's text, and those outside every link. */\nfunction scopes(tokens: readonly Token[]): number[][] {\n const outside: number[] = [];\n const links: number[][] = [];\n let inside: number[] | null = null;\n tokens.forEach((token, index) => {\n if (token.kind === 'syntax' && token.s === '[') inside = [];\n else if (token.kind === 'syntax' && token.s.startsWith('](') && inside !== null) {\n links.push(inside);\n inside = null;\n } else if (token.kind === 'delim') (inside ?? outside).push(index);\n });\n return [...links, outside];\n}\n\n/**\n * Drops delimiter pairs CommonMark would not read as intended, until every\n * remaining pair renders exactly as meant: emphasis is checked by running\n * CommonMark's own pairing algorithm (link text first, as the spec does),\n * strikethrough by its flanking rules.\n */\nfunction resolve(tokens: Token[]): Token[] {\n let current = tokens;\n for (;;) {\n const invalid = new Set<number>();\n current.forEach((token, index) => {\n if (token.kind === 'delim' && token.delim.marker[0] === '~' && !strikeFlanks(current, index, token.delim)) invalid.add(token.delim.pair);\n });\n for (const scope of scopes(current)) for (const pair of misread(current, scope)) invalid.add(pair);\n if (invalid.size === 0) return current;\n current = joinTouching(current.filter((token) => token.kind !== 'delim' || !invalid.has(token.delim.pair)));\n }\n}\n\n/**\n * Dropping a pair can leave one span's closing delimiter right before the next\n * span's opening one, with the same marker (`~~a~~~~b~~`). Those two cancel\n * out: the spans join into one, which is what the text looked like anyway.\n */\nfunction joinTouching(tokens: readonly Token[]): Token[] {\n const out: Token[] = [];\n for (const token of tokens) {\n const last = out[out.length - 1];\n if (token.kind === 'delim' && token.delim.open && last?.kind === 'delim' && !last.delim.open && last.s === token.s) {\n out.pop();\n // The joined span keeps the earlier opener and the later closer: relabel the closer.\n const closer = tokens.find((candidate) => candidate.kind === 'delim' && !candidate.delim.open && candidate.delim.pair === token.delim.pair) as DelimToken;\n closer.delim = { ...closer.delim, pair: last.delim.pair };\n continue;\n }\n out.push(token);\n }\n return out;\n}\n\n/** Escapes the first text of every line, once delimiters are final. */\nfunction escapeLineStarts(tokens: Token[]): void {\n let lineStart = true;\n for (const token of tokens) {\n if (token.kind === 'break') {\n lineStart = true;\n } else {\n if (lineStart && token.kind === 'text') token.s = escapeLineStart(token.s);\n lineStart = false;\n }\n }\n}\n\n/** Inline Markdown for runs: one line, or several joined by hard breaks. Empty when there is no content. */\nexport function renderInline(runs: readonly Run[], options: InlineOptions): string {\n const raw = tokenize(normalize(runs), options);\n separateMixedRuns(raw);\n const tokens = resolve(raw);\n escapeLineStarts(tokens);\n const markdown = tokens.map((token) => token.s).join('');\n // Only whitespace (an editor's `<p>&nbsp;</p>`): nothing to keep.\n return markdown.trim() === '' ? '' : markdown;\n}\n","import { copyFailure } from '../core/errors';\nimport { CODE, EM, STRIKE, STRONG, renderInline, type InlineOptions, type Run } from './inline';\nimport { DEFAULT_IMAGE_PROTOCOLS, DEFAULT_LINK_PROTOCOLS, safeUrl } from './url';\n\n/* ------------------------------------------------------------------ Types */\n\nexport interface MarkdownOptions {\n /**\n * Images: `'alt'` (default) keeps their alt text, so nothing is fetched when the\n * Markdown is rendered (pasted images are often tracking pixels or expiring URLs);\n * `'keep'` writes `![alt](src)` for allowed URLs; `'drop'` removes them.\n */\n readonly images?: 'alt' | 'keep' | 'drop';\n /** Links: `'keep'` (default) writes `[text](url)` for allowed URLs; `'text'` keeps only their text. */\n readonly links?: 'keep' | 'text';\n /** URL schemes allowed in links. Default `['http:', 'https:', 'mailto:']`. */\n readonly linkProtocols?: readonly string[];\n /** URL schemes allowed in images. Default `['https:', 'http:']`; `data:` is never allowed by default. */\n readonly imageProtocols?: readonly string[];\n /** Resolves relative links and images. Without it, they keep only their text. */\n readonly baseUrl?: string;\n /** List marker for bullet lists. Default `'-'`. */\n readonly bullet?: '-' | '*' | '+';\n /** Hard line breaks as a trailing backslash (default, survives editors that trim spaces) or two spaces. */\n readonly hardBreak?: 'backslash' | 'spaces';\n /** Input size cap in characters; longer HTML is cut and `truncated` is set. Default 16 MiB. */\n readonly maxLength?: number;\n /** Elements and text nodes visited; the rest is left out and `truncated` is set. Default 200,000. */\n readonly maxNodes?: number;\n /** Nesting depth; deeper content keeps its text but loses its formatting. Default 200. */\n readonly maxDepth?: number;\n}\n\nexport interface MarkdownResult {\n readonly markdown: string;\n /** Whether content was left out because a limit was reached. */\n readonly truncated: boolean;\n}\n\nexport const DEFAULT_MARKDOWN_MAX_LENGTH = 16 * 1024 * 1024;\nexport const DEFAULT_MARKDOWN_MAX_NODES = 200_000;\nexport const DEFAULT_MARKDOWN_MAX_DEPTH = 200;\n\n/** Merged-cell expansion cap for one table, so a tiny table can't claim millions of cells. */\nconst MAX_TABLE_CELLS = 100_000;\nconst MAX_COLSPAN = 1000;\n\nexport interface Resolved {\n readonly images: 'alt' | 'keep' | 'drop';\n readonly links: 'keep' | 'text';\n readonly linkProtocols: readonly string[];\n readonly imageProtocols: readonly string[];\n readonly baseUrl: string | undefined;\n readonly bullet: string;\n readonly hardBreak: string;\n readonly maxLength: number;\n readonly maxNodes: number;\n readonly maxDepth: number;\n}\n\nfunction limit(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (value === Infinity || (Number.isInteger(value) && value > 0)) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer or Infinity (received ${String(value)}).`);\n}\n\nexport function resolveOptions(options: MarkdownOptions): Resolved {\n return {\n images: options.images ?? 'alt',\n links: options.links ?? 'keep',\n linkProtocols: options.linkProtocols ?? DEFAULT_LINK_PROTOCOLS,\n imageProtocols: options.imageProtocols ?? DEFAULT_IMAGE_PROTOCOLS,\n baseUrl: options.baseUrl,\n bullet: options.bullet ?? '-',\n hardBreak: options.hardBreak === 'spaces' ? ' \\n' : '\\\\\\n',\n maxLength: limit(options.maxLength, DEFAULT_MARKDOWN_MAX_LENGTH, 'maxLength'),\n maxNodes: limit(options.maxNodes, DEFAULT_MARKDOWN_MAX_NODES, 'maxNodes'),\n maxDepth: limit(options.maxDepth, DEFAULT_MARKDOWN_MAX_DEPTH, 'maxDepth'),\n };\n}\n\n/* ------------------------------------------------------------- Elements */\n\n/** Never rendered: scripts, metadata, embedded documents, media and form controls. */\nconst SKIP = new Set([\n 'script', 'style', 'template', 'noscript', 'head', 'title', 'meta', 'link', 'base', 'xml',\n 'iframe', 'frame', 'frameset', 'object', 'embed', 'applet', 'svg', 'math', 'canvas',\n 'video', 'audio', 'source', 'track', 'map', 'area',\n 'input', 'button', 'select', 'option', 'optgroup', 'textarea', 'datalist', 'output', 'progress', 'meter', 'dialog',\n 'o:p',\n]);\n\n/** Blocks without margins in the browser: their inline content forms lines, not paragraphs. */\nconst DIV_LIKE = new Set([\n 'address', 'article', 'aside', 'center', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'fieldset', 'figcaption',\n 'figure', 'footer', 'form', 'header', 'hgroup', 'legend', 'li', 'main', 'nav', 'search', 'section', 'summary',\n 'caption', 'tbody', 'thead', 'tfoot', 'tr', 'td', 'th', 'colgroup', 'col',\n]);\n\nconst HEADINGS = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n/** Div-like blocks the browser gives vertical margins: their content is set apart as paragraphs. */\nconst SPACED = new Set(['dl', 'figure', 'fieldset']);\nconst OTHER_BLOCKS = new Set(['p', 'ul', 'ol', 'menu', 'pre', 'blockquote', 'table', 'hr']);\n\nconst isBlock = (tag: string): boolean => DIV_LIKE.has(tag) || HEADINGS.has(tag) || OTHER_BLOCKS.has(tag);\n\n/** Inline CSS, lower-cased: only what changes the Markdown. */\nfunction styleOf(element: Element): ReadonlyMap<string, string> {\n const map = new Map<string, string>();\n const attribute = element.getAttribute('style');\n if (attribute === null) return map;\n for (const declaration of attribute.split(';')) {\n const colon = declaration.indexOf(':');\n if (colon > 0) map.set(declaration.slice(0, colon).trim().toLowerCase(), declaration.slice(colon + 1).trim().toLowerCase());\n }\n return map;\n}\n\nconst MONOSPACE =\n /\\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/;\n\nfunction isHidden(element: Element, style: ReadonlyMap<string, string>): boolean {\n return (\n element.hasAttribute('hidden') ||\n style.get('display') === 'none' ||\n style.get('visibility') === 'hidden' ||\n style.get('mso-list') === 'ignore' // Word's list markers: the list itself carries them\n );\n}\n\n/** Style bits after this element: semantic tags first, then inline CSS, which wins (Google Docs, Word). */\nfunction applyStyle(bits: number, tag: string, style: ReadonlyMap<string, string>): number {\n let next = bits;\n if (tag === 'b' || tag === 'strong') next |= STRONG;\n else if (tag === 'i' || tag === 'em') next |= EM;\n else if (tag === 's' || tag === 'strike' || tag === 'del') next |= STRIKE;\n else if (tag === 'code' || tag === 'kbd' || tag === 'samp' || tag === 'tt') next |= CODE;\n\n const weight = style.get('font-weight');\n if (weight !== undefined) {\n const numeric = Number.parseInt(weight, 10);\n if (weight === 'bold' || weight === 'bolder' || numeric >= 600) next |= STRONG;\n else if (weight === 'normal' || weight === 'lighter' || numeric > 0) next &= ~STRONG;\n }\n const fontStyle = style.get('font-style');\n if (fontStyle === 'italic' || fontStyle === 'oblique') next |= EM;\n else if (fontStyle === 'normal') next &= ~EM;\n const decoration = style.get('text-decoration-line') ?? style.get('text-decoration');\n if (decoration?.includes('line-through')) next |= STRIKE;\n const family = style.get('font-family');\n if (family !== undefined && MONOSPACE.test(family)) next |= CODE;\n return next;\n}\n\n/** A `<div style=\"white-space: pre; font-family: monospace\">`, as code editors (VS Code) write. */\nfunction isCodeContainer(tag: string, style: ReadonlyMap<string, string>): boolean {\n const whiteSpace = style.get('white-space');\n const family = style.get('font-family');\n return tag === 'div' && whiteSpace !== undefined && whiteSpace.startsWith('pre') && family !== undefined && MONOSPACE.test(family);\n}\n\n/* --------------------------------------------------------------- Blocks */\n\n/** How a block joins its neighbours: `line` blocks next to each other join with a line break. */\ninterface Block {\n readonly md: string;\n readonly before: 'line' | 'para';\n readonly after: 'line' | 'para';\n /** A list's top-level marker (`-`, `*`, `.`, `)`): two lists in a row need different ones, or they merge. */\n readonly list?: string;\n}\n\nconst PARA = { before: 'para', after: 'para' } as const;\n\ninterface Ctx {\n readonly style: number;\n /** Style bits that never apply here (bold inside headings and header cells). */\n readonly mask: number;\n readonly href: string | null;\n readonly depth: number;\n}\n\n/** Where block elements go. `null` while collecting one line (headings, table cells): blocks become spaces. */\ninterface BlockSink {\n readonly blocks: Block[];\n /** Turns the inline runs collected so far into paragraphs. */\n readonly flush: () => void;\n}\n\ninterface VItem {\n readonly blocks: Block[];\n readonly check: boolean | null;\n /** Lists nested under this item (Word lists, built level by level). */\n readonly nested: VList[];\n}\n\ninterface VList {\n readonly ordered: boolean;\n readonly start: number;\n readonly items: VItem[];\n}\n\nconst WORD_LIST = /mso-list\\s*:\\s*(l\\d+)\\s+level(\\d+)/i;\nconst ORDERED_WORD_MARKER = /^\\(?(\\d+|[a-z]|[ivxlcdm]+)[.)]/i;\n\nclass Converter {\n private nodes = 0;\n truncated = false;\n\n constructor(private readonly options: Resolved) {}\n\n private inlineOptions(pipes = false): InlineOptions {\n return { pipes, hardBreak: this.options.hardBreak };\n }\n\n /** Converts nodes (usually an element's children) into blocks. `kind`: how loose inline content joins. */\n blocks(nodes: readonly Node[], ctx: Ctx, kind: 'line' | 'para'): Block[] {\n const blocks: Block[] = [];\n const runs: Run[] = [];\n // Cleared in place: nested visits hold on to this array.\n const sink: BlockSink = { blocks, flush: () => blocks.push(...this.paragraphs(runs.splice(0), kind)) };\n for (let index = 0; index < nodes.length; index += 1) {\n const node = nodes[index] as Node;\n if (isWordListParagraph(node)) {\n sink.flush();\n const [list, consumed] = this.wordList(nodes, index, ctx);\n blocks.push(...list);\n index += consumed - 1;\n continue;\n }\n this.visit(node, ctx, runs, sink);\n }\n sink.flush();\n return blocks;\n }\n\n /** Visits one node: inline content goes into `runs`; block elements flush them into the sink. */\n private visit(node: Node, ctx: Ctx, runs: Run[], sink: BlockSink | null): void {\n if (this.nodes >= this.options.maxNodes) {\n this.truncated = true;\n return;\n }\n this.nodes += 1;\n if (node.nodeType === 3) {\n runs.push({ kind: 'text', text: (node as Text).data, style: ctx.style & ~ctx.mask, href: ctx.href });\n return;\n }\n if (node.nodeType !== 1) return;\n const element = node as Element;\n const tag = element.localName.toLowerCase();\n const style = styleOf(element);\n if (SKIP.has(tag) || isHidden(element, style)) return;\n if (ctx.depth >= this.options.maxDepth) {\n // Too deep to keep formatting: keep the text, so nothing is lost.\n runs.push({ kind: 'text', text: ` ${element.textContent} `, style: 0, href: ctx.href });\n return;\n }\n if (tag === 'br') {\n runs.push(sink === null ? { kind: 'text', text: ' ', style: 0, href: null } : { kind: 'break' });\n return;\n }\n if (tag === 'img') {\n this.image(element, ctx, runs);\n return;\n }\n\n const inner: Ctx = { ...ctx, style: applyStyle(ctx.style, tag, style), href: this.link(element, tag, ctx), depth: ctx.depth + 1 };\n if (!isBlock(tag) && !isCodeContainer(tag, style)) {\n for (let child = element.firstChild; child !== null; child = child.nextSibling) this.visit(child, inner, runs, sink);\n return;\n }\n if (sink === null) {\n // Headings and table cells: blocks inside become spaces.\n runs.push({ kind: 'text', text: ' ', style: 0, href: null });\n const flat = tag === 'pre' ? { ...inner, style: inner.style | CODE } : inner;\n for (let child = element.firstChild; child !== null; child = child.nextSibling) this.visit(child, flat, runs, null);\n runs.push({ kind: 'text', text: ' ', style: 0, href: null });\n return;\n }\n sink.flush();\n sink.blocks.push(...this.block(element, tag, style, inner));\n }\n\n private block(element: Element, tag: string, style: ReadonlyMap<string, string>, ctx: Ctx): Block[] {\n if (tag === 'pre' || isCodeContainer(tag, style)) return this.code(element, ctx);\n if (HEADINGS.has(tag)) return this.heading(element, Number(tag.slice(1)), ctx);\n switch (tag) {\n case 'p':\n return this.blocks(children(element), ctx, 'para');\n case 'ul':\n case 'ol':\n case 'menu':\n return [this.listBlock(this.htmlList(element, tag === 'ol', ctx))];\n case 'blockquote': {\n const inner = join(this.blocks(children(element), ctx, 'para'), this.options.hardBreak);\n return inner === '' ? [] : [{ md: inner.split('\\n').map((line) => (line === '' ? '>' : `> ${line}`)).join('\\n'), ...PARA }];\n }\n case 'table':\n return this.table(element as HTMLTableElement, ctx);\n case 'hr':\n return [{ md: '---', ...PARA }];\n default: {\n const blocks = this.blocks(children(element), ctx, 'line');\n return SPACED.has(tag) ? spaced(blocks) : blocks;\n }\n }\n }\n\n /** Inline runs → paragraphs. Two or more line breaks in a row end a paragraph. */\n private paragraphs(runs: readonly Run[], kind: 'line' | 'para'): Block[] {\n const chunks: Run[][] = [[]];\n let breaks = 0;\n for (const run of runs) {\n if (run.kind === 'break') breaks += 1;\n else if (run.kind === 'text' && run.text.trim() === '') {\n // whitespace between breaks doesn't separate them\n } else if (breaks >= 2) {\n chunks.push([]);\n breaks = 0;\n } else breaks = 0;\n (chunks[chunks.length - 1] as Run[]).push(run);\n }\n const rendered = chunks.map((chunk) => renderInline(chunk, this.inlineOptions()));\n const blocks: Block[] = [];\n rendered.forEach((md, index) => {\n if (md === '') return;\n const first = index === 0;\n const last = index === rendered.length - 1;\n blocks.push({ md, before: first ? kind : 'para', after: last ? kind : 'para' });\n });\n // A `line` container with no content (`<div><br></div>`) is a blank line: it separates its neighbours.\n if (blocks.length === 0 && kind === 'line' && runs.some((run) => run.kind === 'break')) blocks.push({ md: '', ...PARA });\n return blocks;\n }\n\n private heading(element: Element, level: number, ctx: Ctx): Block[] {\n const md = this.inline(element, { ...ctx, mask: ctx.mask | STRONG });\n if (md === '') return [];\n // A trailing `#` would be read as the heading's closing sequence, unless it is already escaped.\n const escaped = /(^|[^\\\\])(\\\\\\\\)*#$/.test(md) ? `${md.slice(0, -1)}\\\\#` : md;\n return [{ md: `${'#'.repeat(level)} ${escaped}`, ...PARA }];\n }\n\n /** An element's content as one line of inline Markdown. */\n private inline(element: Element, ctx: Ctx, pipes = false): string {\n const runs: Run[] = [];\n for (let child = element.firstChild; child !== null; child = child.nextSibling) this.visit(child, ctx, runs, null);\n return renderInline(runs, this.inlineOptions(pipes));\n }\n\n private image(element: Element, ctx: Ctx, runs: Run[]): void {\n const { images, imageProtocols, baseUrl } = this.options;\n if (images === 'drop') return;\n const alt = (element.getAttribute('alt') ?? '').replace(/\\s+/g, ' ').trim();\n const src = images === 'keep' ? safeUrl(element.getAttribute('src') ?? '', imageProtocols, baseUrl) : null;\n const style = ctx.style & ~ctx.mask;\n if (src !== null) runs.push({ kind: 'image', alt, src, style, href: ctx.href });\n else if (alt !== '') runs.push({ kind: 'text', text: alt, style, href: ctx.href });\n }\n\n private link(element: Element, tag: string, ctx: Ctx): string | null {\n if (tag !== 'a' || ctx.href !== null || this.options.links === 'text') return ctx.href;\n const href = element.getAttribute('href');\n return href === null ? null : safeUrl(href, this.options.linkProtocols, this.options.baseUrl);\n }\n\n /* ---------------------------------------------------------------- Code */\n\n private code(element: Element, ctx: Ctx): Block[] {\n const text = this.codeText(element, ctx.depth)\n .replace(/\\r\\n?/g, '\\n')\n .replace(/\\u00a0/g, ' ')\n .replace(/^\\n/, '')\n .replace(/\\s+$/, '');\n if (text.trim() === '') return [];\n let longest = 0;\n for (const match of text.matchAll(/`+/g)) longest = Math.max(longest, match[0].length);\n const fence = '`'.repeat(Math.max(3, longest + 1));\n return [{ md: `${fence}${language(element)}\\n${text}\\n${fence}`, ...PARA }];\n }\n\n /** Text of a code block: line breaks and line-shaped elements (`<div>` per line) become newlines. */\n private codeText(element: Element, depth: number): string {\n let out = '';\n const walk = (node: Node, level: number): void => {\n for (let child = node.firstChild; child !== null; child = child.nextSibling) {\n if (this.nodes >= this.options.maxNodes) {\n this.truncated = true;\n return;\n }\n this.nodes += 1;\n if (child.nodeType === 3) out += (child as Text).data;\n if (child.nodeType !== 1) continue;\n const el = child as Element;\n const tag = el.localName.toLowerCase();\n if (SKIP.has(tag) || isHidden(el, styleOf(el))) continue;\n if (tag === 'br') {\n out += '\\n';\n continue;\n }\n const lineShaped = isBlock(tag);\n if (lineShaped && out !== '' && !out.endsWith('\\n')) out += '\\n';\n if (level >= this.options.maxDepth) out += el.textContent;\n else walk(el, level + 1);\n if (lineShaped && !out.endsWith('\\n')) out += '\\n';\n }\n };\n walk(element, depth);\n return out;\n }\n\n /* --------------------------------------------------------------- Lists */\n\n private listBlock(list: VList): Block {\n const { bullet } = this.options;\n const lines = list.items.map((item, index) => {\n const marker = list.ordered ? `${String(list.start + index)}.` : bullet;\n const check = item.check === null ? '' : item.check ? '[x] ' : '[ ] ';\n const nested = item.nested.map((child) => this.listBlock(child));\n const body = join([...item.blocks, ...nested], this.options.hardBreak, true);\n const indent = ' '.repeat(marker.length + 1);\n const [first = '', ...rest] = body.split('\\n');\n const head = `${marker} ${check}${first}`.trimEnd();\n return [head, ...rest.map((line) => (line === '' ? '' : indent + line))].join('\\n');\n });\n return { md: lines.join('\\n'), ...PARA, list: list.ordered ? '.' : bullet };\n }\n\n private htmlList(element: Element, ordered: boolean, ctx: Ctx): VList {\n const start = ordered ? Number.parseInt(element.getAttribute('start') ?? '1', 10) : 1;\n const list: VList = { ordered, start: Number.isSafeInteger(start) && start >= 0 && start <= 999_999_999 ? start : 1, items: [] };\n for (let child = element.firstChild; child !== null; child = child.nextSibling) {\n if (child.nodeType === 3 && (child as Text).data.trim() === '') continue;\n const tag = child.nodeType === 1 ? (child as Element).localName.toLowerCase() : '';\n const previous = list.items[list.items.length - 1];\n if ((tag === 'ul' || tag === 'ol' || tag === 'menu') && previous !== undefined) {\n // Google Docs nests lists as siblings of the items: attach to the item before.\n previous.blocks.push(...this.block(child as Element, tag, styleOf(child as Element), { ...ctx, depth: ctx.depth + 1 }));\n continue;\n }\n const nodes = tag === 'li' ? children(child) : [child];\n list.items.push({ blocks: this.blocks(nodes, { ...ctx, depth: ctx.depth + 1 }, 'line'), check: tag === 'li' ? checkState(child as Element) : null, nested: [] });\n }\n return list;\n }\n\n /**\n * Word writes lists as paragraphs with `mso-list: l0 level2`, and the marker\n * (`1.`, `·`) as text inside a span hidden with `mso-list: Ignore`. Collects\n * the consecutive list paragraphs from `nodes[start]` into nested lists.\n * Returns the list blocks and how many nodes they consumed.\n */\n private wordList(nodes: readonly Node[], start: number, ctx: Ctx): [Block[], number] {\n const roots: VList[] = [];\n const stack: { level: number; list: VList }[] = [];\n let consumed = 0;\n for (let index = start; index < nodes.length; index += 1) {\n const node = nodes[index] as Node;\n if (node.nodeType === 8 || (node.nodeType === 3 && (node as Text).data.trim() === '')) continue;\n if (!isWordListParagraph(node)) break;\n consumed = index - start + 1;\n const paragraph = node as Element;\n const level = Number(WORD_LIST.exec(paragraph.getAttribute('style') as string)?.[2]);\n const marker = (paragraph.querySelector('[style*=\"mso-list\"][style*=\"gnore\"]')?.textContent ?? '').replace(/\\s+/g, '');\n const ordered = ORDERED_WORD_MARKER.exec(marker);\n const first = ordered && /^\\d+$/.test(ordered[1] as string) ? Number(ordered[1]) : 1;\n while (stack.length > 0 && (stack[stack.length - 1] as { level: number }).level > level) stack.pop();\n let top = stack[stack.length - 1];\n if (top !== undefined && top.level === level && top.list.ordered !== (ordered !== null)) {\n stack.pop(); // the list type changed: a new list at this level\n top = stack[stack.length - 1];\n }\n if (top === undefined || top.level < level) {\n const list: VList = { ordered: ordered !== null, start: first, items: [] };\n const parent = top?.list.items[top.list.items.length - 1];\n if (parent === undefined) roots.push(list);\n else parent.nested.push(list);\n top = { level, list };\n stack.push(top);\n }\n top.list.items.push({ blocks: this.blocks(children(paragraph), { ...ctx, depth: ctx.depth + 1 }, 'line'), check: null, nested: [] });\n }\n return [roots.map((list) => this.listBlock(list)), consumed];\n }\n\n /* -------------------------------------------------------------- Tables */\n\n private table(table: HTMLTableElement, ctx: Ctx): Block[] {\n const rows = Array.from(table.rows);\n const caption = table.caption ? this.blocks(children(table.caption), ctx, 'para') : [];\n const role = table.getAttribute('role');\n const layout =\n role === 'presentation' ||\n role === 'none' ||\n rows.some((row) => Array.from(row.cells).some((cell) => cell.querySelector('table, ul, ol, pre, blockquote, h1, h2, h3, h4, h5, h6') !== null)) ||\n (rows.length === 1 && rows[0]?.cells.length === 1);\n if (layout) {\n // A table used for layout (mail, old pages): its cells are just content, in reading order.\n return [...caption, ...rows.flatMap((row) => Array.from(row.cells).flatMap((cell) => this.blocks(children(cell), ctx, 'line')))];\n }\n\n const grid: string[][] = [];\n const align: string[] = [];\n let cells = 0;\n let expand = true;\n rows.forEach((row, r) => {\n const line = (grid[r] ??= []);\n let c = 0;\n for (const cell of Array.from(row.cells)) {\n while (line[c] !== undefined) c += 1;\n let span = Math.min(Math.max(cell.colSpan, 1), MAX_COLSPAN);\n let down = Math.min(Math.max(cell.rowSpan || rows.length - r, 1), rows.length - r);\n if (!expand || cells + span * down > MAX_TABLE_CELLS) {\n // Merged cells would exceed the budget: keep the content, drop merging from here on.\n this.truncated = true;\n expand = false;\n span = 1;\n down = 1;\n }\n cells += span * down;\n const content = this.inline(cell, { ...ctx, mask: cell.localName === 'th' ? ctx.mask | STRONG : ctx.mask }, true);\n // Renderers trim cells, Unicode spaces included, so the cell is written trimmed.\n const md = content.trim();\n if (r === 0) align[c] = alignment(cell);\n for (let dr = 0; dr < down; dr += 1) {\n const target = (grid[r + dr] ??= []);\n for (let dc = 0; dc < span; dc += 1) target[c + dc] = dr === 0 && dc === 0 ? md : '';\n }\n c += span;\n }\n });\n const width = grid.reduce((max, line) => Math.max(max, line.length), 0);\n if (width === 0 || grid.every((line) => line.every((cell) => cell === ''))) return caption;\n const format = (line: readonly (string | undefined)[]): string =>\n `| ${Array.from({ length: width }, (_, index) => line[index] ?? '').join(' | ')} |`;\n const [head = [], ...body] = grid;\n const delimiter = `| ${Array.from({ length: width }, (_, index) => align[index] ?? '---').join(' | ')} |`;\n return [...caption, { md: [format(head), delimiter, ...body.map(format)].join('\\n'), ...PARA }];\n }\n}\n\n/* -------------------------------------------------------------- Helpers */\n\n/**\n * Joins blocks: `line` blocks next to each other with a hard break, others with\n * a blank line. Inside a list item, a nested list follows its text directly so\n * the list stays tight. An empty block is a blank line between its neighbours.\n */\nfunction join(blocks: readonly Block[], hardBreak: string, inItem = false): string {\n let out = '';\n let separate = false;\n let previous: Block | null = null;\n for (const original of blocks) {\n if (original.md === '') {\n separate = true;\n continue;\n }\n // Two lists in a row with the same marker would merge into one: switch the marker.\n const block: Block = original.list !== undefined && previous?.list === original.list ? switchMarker(original) : original;\n if (previous !== null) {\n if (inItem && block.list !== undefined && previous.list === undefined && !separate) out += '\\n';\n else out += !separate && previous.after === 'line' && block.before === 'line' ? hardBreak : '\\n\\n';\n }\n out += block.md;\n previous = block;\n separate = false;\n }\n return out;\n}\n\nconst OTHER_MARKER: Readonly<Record<string, string>> = { '-': '*', '*': '-', '+': '-', '.': ')', ')': '.' };\n\n/** The same list with its top-level marker switched. Item lines are the only lines at column 0. */\nfunction switchMarker(block: Block): Block {\n const from = block.list as string;\n const to = OTHER_MARKER[from] as string;\n const md = block.md\n .split('\\n')\n .map((line) => {\n if (line === '' || line.startsWith(' ')) return line;\n return from === '.' || from === ')' ? line.replace(/^(\\d+)[.)]/, `$1${to}`) : `${to}${line.slice(1)}`;\n })\n .join('\\n');\n return { ...block, md, list: to };\n}\n\nfunction checkState(item: Element): boolean | null {\n const aria = item.getAttribute('aria-checked');\n if (item.getAttribute('role') === 'checkbox' && (aria === 'true' || aria === 'false')) return aria === 'true';\n for (const input of Array.from(item.querySelectorAll('input[type=\"checkbox\" i]'))) {\n if (input.closest('li') === item) return input.hasAttribute('checked');\n }\n return null;\n}\n\nconst children = (node: Node): Node[] => Array.from(node.childNodes);\n\n/** The blocks with paragraph breaks at both ends. */\nfunction spaced(blocks: Block[]): Block[] {\n const first = blocks[0];\n if (first !== undefined) blocks[0] = { ...first, before: 'para' };\n const last = blocks[blocks.length - 1];\n if (last !== undefined) blocks[blocks.length - 1] = { ...last, after: 'para' };\n return blocks;\n}\n\nfunction isWordListParagraph(node: Node): boolean {\n return node.nodeType === 1 && WORD_LIST.test((node as Element).getAttribute('style') ?? '');\n}\n\nfunction language(element: Element): string {\n const candidates = [element, element.querySelector('code'), element.parentElement];\n for (const candidate of candidates) {\n if (candidate === null) continue;\n const data = candidate.getAttribute('data-language') ?? candidate.getAttribute('data-lang');\n const named = data ?? /(?:^|\\s)(?:language|lang|highlight-source)-(\\S+)/.exec(candidate.getAttribute('class') ?? '')?.[1];\n if (named !== undefined && /^[A-Za-z0-9_+#.-]{1,30}$/.test(named)) return named;\n }\n return '';\n}\n\nfunction alignment(cell: Element): string {\n const value = (cell.getAttribute('align') ?? styleOf(cell).get('text-align') ?? '').toLowerCase();\n return value === 'center' ? ':---:' : value === 'right' ? '---:' : value === 'left' ? ':---' : '---';\n}\n\n/* --------------------------------------------------------------- Public */\n\n/**\n * Converts HTML to CommonMark with GFM tables, strikethrough and task lists.\n *\n * Strings are parsed in an inert document (scripts never run, nothing is\n * fetched), so pasted HTML is safe to pass. The output never contains raw HTML:\n * text that looks like Markdown or HTML is escaped, links and images keep only\n * allowed URL schemes, and images default to their alt text.\n *\n * Handles what real clipboards contain: Google Docs (bold and italic set by CSS,\n * the non-bold `<b>` wrapper, redirect links), Word (`mso-list` lists, hidden\n * markers), GitHub, Notion, code editors and mail layout tables.\n *\n * Needs `DOMParser` for strings (any browser, or jsdom); pass a `Node` to use\n * your own DOM. Throws an `unsupported` `CopyFailure` for a string without one.\n */\nexport function htmlToMarkdown(source: string | Node, options: MarkdownOptions = {}): MarkdownResult {\n const resolved = resolveOptions(options);\n if (typeof source !== 'string') {\n // A document converts its body (an XML document, which has none, its root element).\n const body = source.nodeType === 9 ? ((source as Document).body as HTMLElement | null) : null;\n return convert(body ?? (source.nodeType === 9 ? (source as Document).documentElement : source), resolved, false);\n }\n const { body, truncated } = parseHtml(source, resolved);\n return convert(body, resolved, truncated);\n}\n\n/** Parses HTML in an inert document, cut to `maxLength`. Throws `unsupported` without `DOMParser`. */\nexport function parseHtml(html: string, resolved: Resolved): { readonly body: HTMLElement; readonly truncated: boolean } {\n if (typeof DOMParser === 'undefined') {\n throw copyFailure('unsupported', 'htmlToMarkdown needs DOMParser to read an HTML string; pass a DOM node instead.');\n }\n // A parsed document is inert: scripts never run and nothing (not even an image) is fetched.\n const body = new DOMParser().parseFromString(html.slice(0, resolved.maxLength), 'text/html').body;\n return { body, truncated: html.length > resolved.maxLength };\n}\n\n/** Converts a node: an element with itself included (its heading, list or table), a body or fragment by its children. */\nexport function convert(root: Node, resolved: Resolved, truncated: boolean): MarkdownResult {\n const converter = new Converter(resolved);\n const ctx: Ctx = { style: 0, mask: 0, href: null, depth: 0 };\n const nodes = root.nodeType === 1 && root.nodeName !== 'BODY' ? [root] : children(root);\n const blocks = converter.blocks(nodes, ctx, 'para');\n return { markdown: join(blocks, resolved.hardBreak).trim(), truncated: truncated || converter.truncated };\n}\n","import { convert, parseHtml, resolveOptions, type MarkdownOptions } from './convert';\n\nexport interface PasteToMarkdownOptions extends MarkdownOptions {\n /**\n * When the HTML is only code (a code editor such as VS Code or a JetBrains IDE,\n * or a single `<pre>`), return the plain text as it is, like a native paste.\n * Default `true`; `false` converts it to a fenced code block.\n */\n readonly codeAsText?: boolean;\n}\n\nexport interface PasteMarkdown {\n readonly markdown: string;\n /** `html` when converted from rich content; `text` when the plain text was kept as it is. */\n readonly source: 'html' | 'text';\n readonly truncated: boolean;\n}\n\n/** The clipboard flavours: a `PasteResult` from `usePaste`, or anything with `html` / `text`. */\nexport interface MarkdownPasteSource {\n readonly html?: string | null;\n readonly text?: string | null;\n}\n\nconst MONOSPACE_PRE = /white-space\\s*:\\s*pre/i;\nconst MONOSPACE_FONT = /font-family\\s*:[^;]*\\b(monospace|courier|consolas|menlo|monaco|mono)\\b/i;\n\n/** Every visible character sits inside a `<pre>` or a monospace `white-space: pre` box. */\nfunction isCodeOnly(body: HTMLElement): boolean {\n const walker = body.ownerDocument.createTreeWalker(body, 4 /* NodeFilter.SHOW_TEXT */);\n let seen = false;\n for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {\n if ((node as Text).data.trim() === '') continue;\n seen = true;\n let code = false;\n for (let element = node.parentElement; element !== null && element !== body; element = element.parentElement) {\n const style = element.getAttribute('style') ?? '';\n if (element.localName === 'pre' || (MONOSPACE_PRE.test(style) && MONOSPACE_FONT.test(style))) {\n code = true;\n break;\n }\n }\n if (!code) return false;\n }\n return seen;\n}\n\n/**\n * Markdown for what was pasted. Rich content (the HTML flavour) is converted;\n * plain text is returned as it is, because plain text pasted into a Markdown\n * editor is usually Markdown already (copied from another `.md` file or editor),\n * and escaping it would break it. Returns `null` when there is nothing to paste.\n *\n * Never throws for clipboard content: on a server without `DOMParser`, or when\n * the HTML holds nothing to convert, it falls back to the text.\n *\n * @example\n * usePaste({ accept: ['html', 'text'], onPaste: (result) => {\n * const pasted = pasteToMarkdown(result);\n * if (pasted) insertText(textarea, pasted.markdown);\n * } });\n */\nexport function pasteToMarkdown(source: MarkdownPasteSource, options: PasteToMarkdownOptions = {}): PasteMarkdown | null {\n const resolved = resolveOptions(options); // invalid options are a programming error: they throw\n const text = source.text ?? null;\n const html = source.html ?? null;\n if (html !== null && html.trim() !== '' && typeof DOMParser !== 'undefined') {\n const { body, truncated } = parseHtml(html, resolved);\n if (!(options.codeAsText !== false && text !== null && text !== '' && isCodeOnly(body))) {\n const converted = convert(body, resolved, truncated);\n if (converted.markdown !== '') return { ...converted, source: 'html' };\n }\n }\n return text === null || text === '' ? null : { markdown: text.replace(/\\r\\n?/g, '\\n'), source: 'text', truncated: false };\n}\n\n/** Text fields `setRangeText` and `execCommand('insertText')` both support. */\ntype TextField = HTMLTextAreaElement | HTMLInputElement;\n\nconst TEXT_INPUTS = new Set(['text', 'search', 'url', 'tel', 'password']);\n\nfunction asTextField(target: EventTarget | null): TextField | null {\n if (typeof target !== 'object' || target === null) return null;\n const element = target as Partial<Element> & { type?: unknown };\n if (element.nodeName === 'TEXTAREA') return target as HTMLTextAreaElement;\n if (element.nodeName === 'INPUT' && typeof element.type === 'string' && TEXT_INPUTS.has(element.type)) return target as HTMLInputElement;\n return null;\n}\n\n/**\n * Inserts text at the cursor of a `<textarea>` or text `<input>`, replacing the\n * selection, as typing or pasting would: the browser's undo (Ctrl/⌘+Z) still\n * works, `input` events fire (so React and other frameworks see the change),\n * and `maxlength` is respected. Returns `false` for disabled or read-only fields.\n */\nexport function insertText(field: TextField, text: string): boolean {\n if (field.disabled || field.readOnly) return false;\n // An <input> holds one line: each run of line breaks (a paragraph break too) becomes one space.\n const value = field.nodeName === 'INPUT' ? text.replace(/[ \\t]*(?:\\r\\n|\\r|\\n)+[ \\t]*/g, ' ') : text;\n const doc = field.ownerDocument;\n field.focus();\n // `null` for inputs without a selection API (email, number): the text is appended.\n const start = field.selectionStart;\n const end = field.selectionEnd;\n try {\n // Re-applying the selection ends the current typing run, so the paste gets its own undo step\n // (as a native paste does) instead of merging with what was typed just before.\n if (start !== null && end !== null) field.setSelectionRange(start, end);\n // The only way to keep the native undo stack; supported for text fields in every current browser.\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- no replacement keeps undo history\n if (doc.activeElement === field && doc.execCommand('insertText', false, value)) return true;\n } catch {\n // Fall through to the manual insertion.\n }\n const from = start ?? field.value.length;\n const to = end ?? from;\n let insert = value;\n if (field.maxLength >= 0) {\n const room = Math.max(0, field.maxLength - (field.value.length - (to - from)));\n insert = insert.slice(0, room);\n // Never leave half of a surrogate pair (an emoji) behind.\n if (/[\\ud800-\\udbff]$/.test(insert)) insert = insert.slice(0, -1);\n }\n if (start === null) setNativeValue(field, field.value + insert);\n else field.setRangeText(insert, from, to, 'end');\n const view = doc.defaultView;\n const event =\n view !== null && typeof view.InputEvent === 'function'\n ? new view.InputEvent('input', { bubbles: true, inputType: 'insertFromPaste', data: insert })\n : new Event('input', { bubbles: true });\n field.dispatchEvent(event);\n return true;\n}\n\n/**\n * Sets a field's value through the prototype's setter. React tracks the value\n * set on the element itself; going around it lets React see the change and\n * call `onChange` for the `input` event that follows.\n */\nfunction setNativeValue(field: TextField, next: string): void {\n const descriptor = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(field) as object, 'value');\n // eslint-disable-next-line @typescript-eslint/unbound-method -- it is called right below with the field as `this`\n const setter = descriptor?.set;\n if (setter) setter.call(field, next);\n else field.value = next;\n}\n\n/** Structural paste event: a DOM `ClipboardEvent` and React's `onPaste` event both fit. */\nexport interface MarkdownPasteEvent {\n readonly clipboardData: { getData(format: string): string } | null;\n readonly currentTarget: EventTarget | null;\n readonly target: EventTarget | null;\n readonly defaultPrevented: boolean;\n preventDefault(): void;\n}\n\n/**\n * A paste handler for Markdown text fields: when the clipboard holds rich\n * content (Google Docs, Word, a web page), it is inserted as Markdown; plain\n * text and code pastes are left to the browser, untouched. Returns whether it\n * handled the paste.\n *\n * @example\n * <textarea onPaste={pasteAsMarkdown} />\n * <textarea onPaste={(event) => pasteAsMarkdown(event, { images: 'keep' })} />\n */\nexport function pasteAsMarkdown(event: MarkdownPasteEvent, options?: PasteToMarkdownOptions): boolean {\n if (event.defaultPrevented || event.clipboardData === null) return false;\n const field = asTextField(event.currentTarget) ?? asTextField(event.target);\n if (field === null || field.disabled || field.readOnly) return false;\n const html = event.clipboardData.getData('text/html');\n if (html === '') return false;\n let pasted: PasteMarkdown | null;\n try {\n pasted = pasteToMarkdown({ html, text: event.clipboardData.getData('text/plain') }, options);\n } catch {\n return false; // Invalid options or an unexpected failure: the native paste still happens.\n }\n if (pasted?.source !== 'html') return false;\n event.preventDefault();\n return insertText(field, pasted.markdown);\n}\n"],"mappings":";;AA8CA,SAAgB,gBAAgB,MAAqB,SAAiB,OAA4B;CAChG,OAAO,UAAU,KAAA,IAAY;EAAE;EAAM;CAAQ,IAAI;EAAE;EAAM;EAAS;CAAM;AAC1E;;;;;AAmBA,MAAM,qBAAqB,OAAO,IAAI,8BAA8B;;AAGpE,IAAa,cAAb,cAAiC,MAAM;CAIrC,YAAY,WAAsB;EAChC,MAAM,UAAU,OAAO;EAHzB,KAAU,sBAAsB;EAI9B,KAAK,OAAO;EACZ,KAAK,YAAY;CACnB;AACF;;AAWA,SAAgB,YAAY,MAAqB,SAAiB,OAA8B;CAC9F,OAAO,IAAI,YAAY,gBAAgB,MAAM,SAAS,KAAK,CAAC;AAC9D;;;;;;;;;;;;;ACjFA,MAAM,SAAS;;AAGf,MAAM,SAAS;;AAGf,SAAgB,aAAa,MAAc,QAAQ,OAAe;CAChE,MAAM,UAAU,KAAK,QAAQ,QAAQ,MAAM,CAAC,CAAC,QAAQ,QAAQ,KAAK;CAClE,OAAO,QAAQ,QAAQ,QAAQ,OAAO,KAAK,IAAI;AACjD;AAEA,MAAM,iBAAiB;AACvB,MAAM,cAAc;;;;;AAMpB,SAAgB,gBAAgB,MAAsB;CACpD,MAAM,UAAU,eAAe,KAAK,IAAI;CACxC,IAAI,SAAS,OAAO,GAAG,QAAQ,GAAa,IAAI,KAAK,MAAO,QAAQ,EAAE,CAAY,MAAM;CACxF,OAAO,YAAY,KAAK,IAAI,IAAI,KAAK,SAAS;AAChD;;;;;;;;;AAUA,SAAgB,eAAe,MAAsB;CACnD,OAAO,KACJ,MAAM,YAAY,CAAC,CACnB,KAAK,SAAS,gBAAgB,aAAa,KAAK,QAAQ,WAAW,EAAE,CAAC,CAAC,CAAC,CAA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AAQ,YAAY;EAAE,GAAG,OAAO;CAC7F,QAAQ;EACN,OAAO;CACT;CACA,IAAI,QAAQ,WAAW,QAAQ,OAAO;CACtC,MAAM,eAAe;CACrB,OAAO,WAAW,OAAO,OAAO,QAAQ;AAC1C"}
@@ -0,0 +1,144 @@
1
+ //#region src/markdown/convert.d.ts
2
+ interface MarkdownOptions {
3
+ /**
4
+ * Images: `'alt'` (default) keeps their alt text, so nothing is fetched when the
5
+ * Markdown is rendered (pasted images are often tracking pixels or expiring URLs);
6
+ * `'keep'` writes `![alt](src)` for allowed URLs; `'drop'` removes them.
7
+ */
8
+ readonly images?: 'alt' | 'keep' | 'drop';
9
+ /** Links: `'keep'` (default) writes `[text](url)` for allowed URLs; `'text'` keeps only their text. */
10
+ readonly links?: 'keep' | 'text';
11
+ /** URL schemes allowed in links. Default `['http:', 'https:', 'mailto:']`. */
12
+ readonly linkProtocols?: readonly string[];
13
+ /** URL schemes allowed in images. Default `['https:', 'http:']`; `data:` is never allowed by default. */
14
+ readonly imageProtocols?: readonly string[];
15
+ /** Resolves relative links and images. Without it, they keep only their text. */
16
+ readonly baseUrl?: string;
17
+ /** List marker for bullet lists. Default `'-'`. */
18
+ readonly bullet?: '-' | '*' | '+';
19
+ /** Hard line breaks as a trailing backslash (default, survives editors that trim spaces) or two spaces. */
20
+ readonly hardBreak?: 'backslash' | 'spaces';
21
+ /** Input size cap in characters; longer HTML is cut and `truncated` is set. Default 16 MiB. */
22
+ readonly maxLength?: number;
23
+ /** Elements and text nodes visited; the rest is left out and `truncated` is set. Default 200,000. */
24
+ readonly maxNodes?: number;
25
+ /** Nesting depth; deeper content keeps its text but loses its formatting. Default 200. */
26
+ readonly maxDepth?: number;
27
+ }
28
+ interface MarkdownResult {
29
+ readonly markdown: string;
30
+ /** Whether content was left out because a limit was reached. */
31
+ readonly truncated: boolean;
32
+ }
33
+ export declare const DEFAULT_MARKDOWN_MAX_LENGTH: number;
34
+ export declare const DEFAULT_MARKDOWN_MAX_NODES = 200000;
35
+ export declare const DEFAULT_MARKDOWN_MAX_DEPTH = 200;
36
+ /**
37
+ * Converts HTML to CommonMark with GFM tables, strikethrough and task lists.
38
+ *
39
+ * Strings are parsed in an inert document (scripts never run, nothing is
40
+ * fetched), so pasted HTML is safe to pass. The output never contains raw HTML:
41
+ * text that looks like Markdown or HTML is escaped, links and images keep only
42
+ * allowed URL schemes, and images default to their alt text.
43
+ *
44
+ * Handles what real clipboards contain: Google Docs (bold and italic set by CSS,
45
+ * the non-bold `<b>` wrapper, redirect links), Word (`mso-list` lists, hidden
46
+ * markers), GitHub, Notion, code editors and mail layout tables.
47
+ *
48
+ * Needs `DOMParser` for strings (any browser, or jsdom); pass a `Node` to use
49
+ * your own DOM. Throws an `unsupported` `CopyFailure` for a string without one.
50
+ */
51
+ export declare function htmlToMarkdown(source: string | Node, options?: MarkdownOptions): MarkdownResult;
52
+ //#endregion
53
+ //#region src/markdown/escape.d.ts
54
+ /**
55
+ * Escapes plain text so Markdown renders it literally: no emphasis, links,
56
+ * headings, lists, code or raw HTML. Line breaks are kept; leading whitespace
57
+ * on each line is removed, since Markdown would read four spaces as code.
58
+ *
59
+ * @example
60
+ * escapeMarkdown('1. *Not* a list <b>') // '1\\. \\*Not\\* a list \\<b>'
61
+ */
62
+ export declare function escapeMarkdown(text: string): string;
63
+ //#endregion
64
+ //#region src/markdown/paste.d.ts
65
+ interface PasteToMarkdownOptions extends MarkdownOptions {
66
+ /**
67
+ * When the HTML is only code (a code editor such as VS Code or a JetBrains IDE,
68
+ * or a single `<pre>`), return the plain text as it is, like a native paste.
69
+ * Default `true`; `false` converts it to a fenced code block.
70
+ */
71
+ readonly codeAsText?: boolean;
72
+ }
73
+ interface PasteMarkdown {
74
+ readonly markdown: string;
75
+ /** `html` when converted from rich content; `text` when the plain text was kept as it is. */
76
+ readonly source: 'html' | 'text';
77
+ readonly truncated: boolean;
78
+ }
79
+ /** The clipboard flavours: a `PasteResult` from `usePaste`, or anything with `html` / `text`. */
80
+ interface MarkdownPasteSource {
81
+ readonly html?: string | null;
82
+ readonly text?: string | null;
83
+ }
84
+ /**
85
+ * Markdown for what was pasted. Rich content (the HTML flavour) is converted;
86
+ * plain text is returned as it is, because plain text pasted into a Markdown
87
+ * editor is usually Markdown already (copied from another `.md` file or editor),
88
+ * and escaping it would break it. Returns `null` when there is nothing to paste.
89
+ *
90
+ * Never throws for clipboard content: on a server without `DOMParser`, or when
91
+ * the HTML holds nothing to convert, it falls back to the text.
92
+ *
93
+ * @example
94
+ * usePaste({ accept: ['html', 'text'], onPaste: (result) => {
95
+ * const pasted = pasteToMarkdown(result);
96
+ * if (pasted) insertText(textarea, pasted.markdown);
97
+ * } });
98
+ */
99
+ export declare function pasteToMarkdown(source: MarkdownPasteSource, options?: PasteToMarkdownOptions): PasteMarkdown | null;
100
+ /** Text fields `setRangeText` and `execCommand('insertText')` both support. */
101
+ type TextField = HTMLTextAreaElement | HTMLInputElement;
102
+ /**
103
+ * Inserts text at the cursor of a `<textarea>` or text `<input>`, replacing the
104
+ * selection, as typing or pasting would: the browser's undo (Ctrl/⌘+Z) still
105
+ * works, `input` events fire (so React and other frameworks see the change),
106
+ * and `maxlength` is respected. Returns `false` for disabled or read-only fields.
107
+ */
108
+ export declare function insertText(field: TextField, text: string): boolean;
109
+ /** Structural paste event: a DOM `ClipboardEvent` and React's `onPaste` event both fit. */
110
+ interface MarkdownPasteEvent {
111
+ readonly clipboardData: {
112
+ getData(format: string): string;
113
+ } | null;
114
+ readonly currentTarget: EventTarget | null;
115
+ readonly target: EventTarget | null;
116
+ readonly defaultPrevented: boolean;
117
+ preventDefault(): void;
118
+ }
119
+ /**
120
+ * A paste handler for Markdown text fields: when the clipboard holds rich
121
+ * content (Google Docs, Word, a web page), it is inserted as Markdown; plain
122
+ * text and code pastes are left to the browser, untouched. Returns whether it
123
+ * handled the paste.
124
+ *
125
+ * @example
126
+ * <textarea onPaste={pasteAsMarkdown} />
127
+ * <textarea onPaste={(event) => pasteAsMarkdown(event, { images: 'keep' })} />
128
+ */
129
+ export declare function pasteAsMarkdown(event: MarkdownPasteEvent, options?: PasteToMarkdownOptions): boolean;
130
+ //#endregion
131
+ //#region src/markdown/url.d.ts
132
+ /**
133
+ * URL safety for pasted links and images. Only absolute URLs with an allowed
134
+ * scheme survive; everything else (`javascript:`, `data:`, `vbscript:`,
135
+ * relative links without a base, malformed URLs) is dropped and the visible
136
+ * text is kept. Parsing uses the WHATWG URL parser, the same one the browser
137
+ * uses when the link is clicked, so tricks like `java\tscript:` are seen as
138
+ * `javascript:`.
139
+ */
140
+ export declare const DEFAULT_LINK_PROTOCOLS: readonly string[];
141
+ export declare const DEFAULT_IMAGE_PROTOCOLS: readonly string[];
142
+ //#endregion
143
+ export type { MarkdownOptions, MarkdownPasteEvent, MarkdownPasteSource, MarkdownResult, PasteMarkdown, PasteToMarkdownOptions };
144
+ //# sourceMappingURL=markdown.d.cts.map
@@ -0,0 +1,144 @@
1
+ //#region src/markdown/convert.d.ts
2
+ interface MarkdownOptions {
3
+ /**
4
+ * Images: `'alt'` (default) keeps their alt text, so nothing is fetched when the
5
+ * Markdown is rendered (pasted images are often tracking pixels or expiring URLs);
6
+ * `'keep'` writes `![alt](src)` for allowed URLs; `'drop'` removes them.
7
+ */
8
+ readonly images?: 'alt' | 'keep' | 'drop';
9
+ /** Links: `'keep'` (default) writes `[text](url)` for allowed URLs; `'text'` keeps only their text. */
10
+ readonly links?: 'keep' | 'text';
11
+ /** URL schemes allowed in links. Default `['http:', 'https:', 'mailto:']`. */
12
+ readonly linkProtocols?: readonly string[];
13
+ /** URL schemes allowed in images. Default `['https:', 'http:']`; `data:` is never allowed by default. */
14
+ readonly imageProtocols?: readonly string[];
15
+ /** Resolves relative links and images. Without it, they keep only their text. */
16
+ readonly baseUrl?: string;
17
+ /** List marker for bullet lists. Default `'-'`. */
18
+ readonly bullet?: '-' | '*' | '+';
19
+ /** Hard line breaks as a trailing backslash (default, survives editors that trim spaces) or two spaces. */
20
+ readonly hardBreak?: 'backslash' | 'spaces';
21
+ /** Input size cap in characters; longer HTML is cut and `truncated` is set. Default 16 MiB. */
22
+ readonly maxLength?: number;
23
+ /** Elements and text nodes visited; the rest is left out and `truncated` is set. Default 200,000. */
24
+ readonly maxNodes?: number;
25
+ /** Nesting depth; deeper content keeps its text but loses its formatting. Default 200. */
26
+ readonly maxDepth?: number;
27
+ }
28
+ interface MarkdownResult {
29
+ readonly markdown: string;
30
+ /** Whether content was left out because a limit was reached. */
31
+ readonly truncated: boolean;
32
+ }
33
+ export declare const DEFAULT_MARKDOWN_MAX_LENGTH: number;
34
+ export declare const DEFAULT_MARKDOWN_MAX_NODES = 200000;
35
+ export declare const DEFAULT_MARKDOWN_MAX_DEPTH = 200;
36
+ /**
37
+ * Converts HTML to CommonMark with GFM tables, strikethrough and task lists.
38
+ *
39
+ * Strings are parsed in an inert document (scripts never run, nothing is
40
+ * fetched), so pasted HTML is safe to pass. The output never contains raw HTML:
41
+ * text that looks like Markdown or HTML is escaped, links and images keep only
42
+ * allowed URL schemes, and images default to their alt text.
43
+ *
44
+ * Handles what real clipboards contain: Google Docs (bold and italic set by CSS,
45
+ * the non-bold `<b>` wrapper, redirect links), Word (`mso-list` lists, hidden
46
+ * markers), GitHub, Notion, code editors and mail layout tables.
47
+ *
48
+ * Needs `DOMParser` for strings (any browser, or jsdom); pass a `Node` to use
49
+ * your own DOM. Throws an `unsupported` `CopyFailure` for a string without one.
50
+ */
51
+ export declare function htmlToMarkdown(source: string | Node, options?: MarkdownOptions): MarkdownResult;
52
+ //#endregion
53
+ //#region src/markdown/escape.d.ts
54
+ /**
55
+ * Escapes plain text so Markdown renders it literally: no emphasis, links,
56
+ * headings, lists, code or raw HTML. Line breaks are kept; leading whitespace
57
+ * on each line is removed, since Markdown would read four spaces as code.
58
+ *
59
+ * @example
60
+ * escapeMarkdown('1. *Not* a list <b>') // '1\\. \\*Not\\* a list \\<b>'
61
+ */
62
+ export declare function escapeMarkdown(text: string): string;
63
+ //#endregion
64
+ //#region src/markdown/paste.d.ts
65
+ interface PasteToMarkdownOptions extends MarkdownOptions {
66
+ /**
67
+ * When the HTML is only code (a code editor such as VS Code or a JetBrains IDE,
68
+ * or a single `<pre>`), return the plain text as it is, like a native paste.
69
+ * Default `true`; `false` converts it to a fenced code block.
70
+ */
71
+ readonly codeAsText?: boolean;
72
+ }
73
+ interface PasteMarkdown {
74
+ readonly markdown: string;
75
+ /** `html` when converted from rich content; `text` when the plain text was kept as it is. */
76
+ readonly source: 'html' | 'text';
77
+ readonly truncated: boolean;
78
+ }
79
+ /** The clipboard flavours: a `PasteResult` from `usePaste`, or anything with `html` / `text`. */
80
+ interface MarkdownPasteSource {
81
+ readonly html?: string | null;
82
+ readonly text?: string | null;
83
+ }
84
+ /**
85
+ * Markdown for what was pasted. Rich content (the HTML flavour) is converted;
86
+ * plain text is returned as it is, because plain text pasted into a Markdown
87
+ * editor is usually Markdown already (copied from another `.md` file or editor),
88
+ * and escaping it would break it. Returns `null` when there is nothing to paste.
89
+ *
90
+ * Never throws for clipboard content: on a server without `DOMParser`, or when
91
+ * the HTML holds nothing to convert, it falls back to the text.
92
+ *
93
+ * @example
94
+ * usePaste({ accept: ['html', 'text'], onPaste: (result) => {
95
+ * const pasted = pasteToMarkdown(result);
96
+ * if (pasted) insertText(textarea, pasted.markdown);
97
+ * } });
98
+ */
99
+ export declare function pasteToMarkdown(source: MarkdownPasteSource, options?: PasteToMarkdownOptions): PasteMarkdown | null;
100
+ /** Text fields `setRangeText` and `execCommand('insertText')` both support. */
101
+ type TextField = HTMLTextAreaElement | HTMLInputElement;
102
+ /**
103
+ * Inserts text at the cursor of a `<textarea>` or text `<input>`, replacing the
104
+ * selection, as typing or pasting would: the browser's undo (Ctrl/⌘+Z) still
105
+ * works, `input` events fire (so React and other frameworks see the change),
106
+ * and `maxlength` is respected. Returns `false` for disabled or read-only fields.
107
+ */
108
+ export declare function insertText(field: TextField, text: string): boolean;
109
+ /** Structural paste event: a DOM `ClipboardEvent` and React's `onPaste` event both fit. */
110
+ interface MarkdownPasteEvent {
111
+ readonly clipboardData: {
112
+ getData(format: string): string;
113
+ } | null;
114
+ readonly currentTarget: EventTarget | null;
115
+ readonly target: EventTarget | null;
116
+ readonly defaultPrevented: boolean;
117
+ preventDefault(): void;
118
+ }
119
+ /**
120
+ * A paste handler for Markdown text fields: when the clipboard holds rich
121
+ * content (Google Docs, Word, a web page), it is inserted as Markdown; plain
122
+ * text and code pastes are left to the browser, untouched. Returns whether it
123
+ * handled the paste.
124
+ *
125
+ * @example
126
+ * <textarea onPaste={pasteAsMarkdown} />
127
+ * <textarea onPaste={(event) => pasteAsMarkdown(event, { images: 'keep' })} />
128
+ */
129
+ export declare function pasteAsMarkdown(event: MarkdownPasteEvent, options?: PasteToMarkdownOptions): boolean;
130
+ //#endregion
131
+ //#region src/markdown/url.d.ts
132
+ /**
133
+ * URL safety for pasted links and images. Only absolute URLs with an allowed
134
+ * scheme survive; everything else (`javascript:`, `data:`, `vbscript:`,
135
+ * relative links without a base, malformed URLs) is dropped and the visible
136
+ * text is kept. Parsing uses the WHATWG URL parser, the same one the browser
137
+ * uses when the link is clicked, so tricks like `java\tscript:` are seen as
138
+ * `javascript:`.
139
+ */
140
+ export declare const DEFAULT_LINK_PROTOCOLS: readonly string[];
141
+ export declare const DEFAULT_IMAGE_PROTOCOLS: readonly string[];
142
+ //#endregion
143
+ export type { MarkdownOptions, MarkdownPasteEvent, MarkdownPasteSource, MarkdownResult, PasteMarkdown, PasteToMarkdownOptions };
144
+ //# sourceMappingURL=markdown.d.ts.map