react-smart-copy 1.23.0 → 1.24.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +130 -1806
- package/dist/capture.cjs +3 -3
- package/dist/capture.d.cts +1 -1
- package/dist/capture.d.ts +1 -1
- package/dist/capture.js +3 -3
- package/dist/chunks/{clipboard-adapter-CtH4VELE.d.cts → clipboard-adapter-CfaIbZpv.d.cts} +2 -2
- package/dist/chunks/{clipboard-adapter-Ds0irroN.d.ts → clipboard-adapter-Chm6zq60.d.ts} +2 -2
- package/dist/chunks/{clipboard-adapter-DEXkXxwV.js → clipboard-adapter-CmKDTFdO.js} +3 -3
- package/dist/chunks/{clipboard-adapter-DEXkXxwV.js.map → clipboard-adapter-CmKDTFdO.js.map} +1 -1
- package/dist/chunks/{clipboard-adapter-Cfz-rzw3.cjs → clipboard-adapter-UIFc_Qso.cjs} +3 -3
- package/dist/chunks/{clipboard-adapter-Cfz-rzw3.cjs.map → clipboard-adapter-UIFc_Qso.cjs.map} +1 -1
- package/dist/chunks/{contrast-C6CVklEI.cjs → contrast-C9d8QuaF.cjs} +2 -2
- package/dist/chunks/{contrast-C6CVklEI.cjs.map → contrast-C9d8QuaF.cjs.map} +1 -1
- package/dist/chunks/{contrast-DpK2JIVu.js → contrast-DUaZq5SA.js} +2 -2
- package/dist/chunks/{contrast-DpK2JIVu.js.map → contrast-DUaZq5SA.js.map} +1 -1
- package/dist/chunks/{copy-interceptor-CZWzGOkL.d.cts → copy-interceptor-BClcHS_P.d.cts} +2 -2
- package/dist/chunks/{copy-interceptor-C6NABy1l.d.ts → copy-interceptor-D8c9EDnO.d.ts} +2 -2
- package/dist/chunks/{core-Cp2HSpaz.js → core-BH2uIumi.js} +5 -5
- package/dist/chunks/{core-Cp2HSpaz.js.map → core-BH2uIumi.js.map} +1 -1
- package/dist/chunks/{core-DYf_Lhbe.cjs → core-DmncxMt3.cjs} +5 -5
- package/dist/chunks/{core-DYf_Lhbe.cjs.map → core-DmncxMt3.cjs.map} +1 -1
- package/dist/chunks/{deadline-C29AlS_Q.js → deadline-CbwnZ3Oq.js} +2 -2
- package/dist/chunks/{deadline-C29AlS_Q.js.map → deadline-CbwnZ3Oq.js.map} +1 -1
- package/dist/chunks/{deadline-DkiB8ZHE.cjs → deadline-j2hD7JKz.cjs} +2 -2
- package/dist/chunks/{deadline-DkiB8ZHE.cjs.map → deadline-j2hD7JKz.cjs.map} +1 -1
- package/dist/chunks/{errors-9h8sdFFX.js → errors-CT-FfUtU.js} +2 -2
- package/dist/chunks/errors-CT-FfUtU.js.map +1 -0
- package/dist/chunks/{errors-BwOF6T_M.cjs → errors-DFmEAC4E.cjs} +2 -2
- package/dist/chunks/errors-DFmEAC4E.cjs.map +1 -0
- package/dist/chunks/{field-BHo5y-t_.js → field-CK3NxfkM.js} +43 -14
- package/dist/chunks/field-CK3NxfkM.js.map +1 -0
- package/dist/chunks/{field-Bytz2WfN.cjs → field-CNEcZqa9.cjs} +43 -14
- package/dist/chunks/field-CNEcZqa9.cjs.map +1 -0
- package/dist/chunks/{index-vz0iW5V2.d.cts → index-CqYzvxSN.d.cts} +4 -4
- package/dist/chunks/{index-mr7sSAgP.d.ts → index-Q_QeSwGr.d.ts} +4 -4
- package/dist/chunks/{paste-adapter--SPL4PRE.d.cts → paste-adapter-B6eucH3E.d.cts} +2 -2
- package/dist/chunks/{paste-adapter-uahXnTYk.d.ts → paste-adapter-CfIDT3mp.d.ts} +2 -2
- package/dist/chunks/{paste-reader-Bo01IMC_.cjs → paste-reader-BWQaYNaV.cjs} +2 -2
- package/dist/chunks/paste-reader-BWQaYNaV.cjs.map +1 -0
- package/dist/chunks/{paste-reader-D9i7yMXF.js → paste-reader-D6uOTDBM.js} +2 -2
- package/dist/chunks/paste-reader-D6uOTDBM.js.map +1 -0
- package/dist/chunks/{payload-DI5AorDz.js → payload-BWQ6sPtS.js} +3 -3
- package/dist/chunks/{payload-DI5AorDz.js.map → payload-BWQ6sPtS.js.map} +1 -1
- package/dist/chunks/{payload-DGw-JOo7.js → payload-BrQWGwyx.js} +2 -2
- package/dist/chunks/{payload-DGw-JOo7.js.map → payload-BrQWGwyx.js.map} +1 -1
- package/dist/chunks/{payload-Cl_8hCI5.d.ts → payload-CcvSx_Hq.d.ts} +4 -2
- package/dist/chunks/{payload-CcwKJ_bU.d.cts → payload-qkAWVXWA.d.cts} +4 -2
- package/dist/chunks/{payload-CUymxwim.cjs → payload-sBxkG7jH.cjs} +2 -2
- package/dist/chunks/{payload-CUymxwim.cjs.map → payload-sBxkG7jH.cjs.map} +1 -1
- package/dist/chunks/{payload-J6GjHuh3.cjs → payload-tTK6REua.cjs} +3 -3
- package/dist/chunks/{payload-J6GjHuh3.cjs.map → payload-tTK6REua.cjs.map} +1 -1
- package/dist/chunks/{share-Bop47Znn.js → share-CU91L4EK.js} +6 -6
- package/dist/chunks/{share-Bop47Znn.js.map → share-CU91L4EK.js.map} +1 -1
- package/dist/chunks/{share-e7FenIr2.d.ts → share-DVR_DhHc.d.ts} +3 -3
- package/dist/chunks/{share-C0esXvRK.d.cts → share-hIwth7Dh.d.cts} +3 -3
- package/dist/chunks/{share-ayDz974N.cjs → share-nx7M4Z0t.cjs} +6 -6
- package/dist/chunks/{share-ayDz974N.cjs.map → share-nx7M4Z0t.cjs.map} +1 -1
- package/dist/chunks/{url-D4PGsRm8.cjs → url-BrhVUwn7.cjs} +2 -2
- package/dist/chunks/{url-D4PGsRm8.cjs.map → url-BrhVUwn7.cjs.map} +1 -1
- package/dist/chunks/{url-BcMYVCXQ.js → url-COID0BLY.js} +2 -2
- package/dist/chunks/{url-BcMYVCXQ.js.map → url-COID0BLY.js.map} +1 -1
- package/dist/code.cjs +1 -1
- package/dist/code.cjs.map +1 -1
- package/dist/code.d.cts +1 -1
- package/dist/code.d.ts +1 -1
- package/dist/code.js +1 -1
- package/dist/code.js.map +1 -1
- package/dist/color.cjs +2 -2
- package/dist/color.d.cts +1 -1
- package/dist/color.d.ts +1 -1
- package/dist/color.js +2 -2
- package/dist/core.cjs +5 -5
- package/dist/core.d.cts +5 -5
- package/dist/core.d.ts +5 -5
- package/dist/core.js +5 -5
- package/dist/email.cjs +357 -0
- package/dist/email.cjs.map +1 -0
- package/dist/email.d.cts +163 -0
- package/dist/email.d.ts +163 -0
- package/dist/email.js +351 -0
- package/dist/email.js.map +1 -0
- package/dist/files.cjs +1 -1
- package/dist/files.cjs.map +1 -1
- package/dist/files.d.cts +3 -59
- package/dist/files.d.ts +3 -59
- package/dist/files.js +1 -1
- package/dist/files.js.map +1 -1
- package/dist/image.cjs +2 -2
- package/dist/image.cjs.map +1 -1
- package/dist/image.js +2 -2
- package/dist/image.js.map +1 -1
- package/dist/index.cjs +7 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +43 -19
- package/dist/index.d.ts +43 -19
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/dist/link.cjs +3 -3
- package/dist/link.d.cts +1 -1
- package/dist/link.d.ts +1 -1
- package/dist/link.js +3 -3
- package/dist/markdown.cjs +1 -1
- package/dist/markdown.cjs.map +1 -1
- package/dist/markdown.js +1 -1
- package/dist/markdown.js.map +1 -1
- package/dist/number.cjs +1 -1
- package/dist/number.d.cts +1 -1
- package/dist/number.d.ts +1 -1
- package/dist/number.js +1 -1
- package/dist/otp.cjs +1 -1
- package/dist/otp.js +1 -1
- package/dist/rich.cjs +3 -3
- package/dist/rich.cjs.map +1 -1
- package/dist/rich.d.cts +2 -2
- package/dist/rich.d.ts +2 -2
- package/dist/rich.js +3 -3
- package/dist/rich.js.map +1 -1
- package/dist/secrets.cjs +1 -1
- package/dist/secrets.cjs.map +1 -1
- package/dist/secrets.d.cts +1 -1
- package/dist/secrets.d.ts +1 -1
- package/dist/secrets.js +1 -1
- package/dist/secrets.js.map +1 -1
- package/dist/share.cjs +1 -1
- package/dist/share.d.cts +1 -1
- package/dist/share.d.ts +1 -1
- package/dist/share.js +1 -1
- package/dist/structured.cjs +2 -2
- package/dist/structured.cjs.map +1 -1
- package/dist/structured.js +2 -2
- package/dist/structured.js.map +1 -1
- package/dist/table.cjs +1 -1
- package/dist/table.cjs.map +1 -1
- package/dist/table.d.cts +1 -1
- package/dist/table.d.ts +1 -1
- package/dist/table.js +1 -1
- package/dist/table.js.map +1 -1
- package/dist/testing.cjs +2 -2
- package/dist/testing.d.cts +3 -3
- package/dist/testing.d.ts +3 -3
- package/dist/testing.js +2 -2
- package/package.json +35 -6
- package/dist/chunks/errors-9h8sdFFX.js.map +0 -1
- package/dist/chunks/errors-BwOF6T_M.cjs.map +0 -1
- package/dist/chunks/field-BHo5y-t_.js.map +0 -1
- package/dist/chunks/field-Bytz2WfN.cjs.map +0 -1
- package/dist/chunks/paste-reader-Bo01IMC_.cjs.map +0 -1
- package/dist/chunks/paste-reader-D9i7yMXF.js.map +0 -1
package/dist/rich.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rich.js","names":["HEADINGS","rgb","positive","HEADINGS"],"sources":["../src/rich/policy.ts","../src/rich/style.ts","../src/rich/text.ts","../src/rich/walk.ts","../src/rich/payload.ts","../src/rich/paste.ts"],"sourcesContent":["/**\n * What portable rich text may contain: the elements, attributes and CSS that Gmail,\n * Outlook, Apple Mail, Google Docs, Word, Notion and Slack keep, and nothing that\n * can run, load or track. Everything not listed here is left out.\n */\n\n/** Elements written as they are. */\nexport const KEEP: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'a', 'abbr', 'b', 'bdi', 'bdo', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'div', 'dl', 'dt',\n 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 's',\n 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time', 'tr', 'u', 'ul', 'var',\n]);\n\n/** Elements left out with everything inside them: they run, load, embed, or are page chrome. */\nexport const DROP: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'applet', 'audio', 'base', 'button', 'canvas', 'datalist', 'dialog', 'embed', 'frame', 'frameset', 'head', 'iframe', 'input', 'link',\n 'map', 'math', 'meta', 'meter', 'noembed', 'noframes', 'noscript', 'object', 'option', 'optgroup', 'output', 'param', 'portal',\n 'progress', 'script', 'select', 'slot', 'source', 'style', 'svg', 'template', 'textarea', 'title', 'track', 'video',\n]);\n\n/** Elements that become a `<div>`: blocks without an email-safe equivalent. */\nexport const AS_BLOCK: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'address', 'article', 'aside', 'body', 'center', 'details', 'fieldset', 'footer', 'form', 'header', 'hgroup', 'html', 'legend',\n 'listing', 'main', 'menu', 'nav', 'plaintext', 'search', 'section', 'summary', 'xmp',\n]);\n\n/** Elements whose children are block-level text in the plain-text version. */\nexport const TEXT_BLOCKS: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'blockquote', 'caption', 'dd', 'div', 'dl', 'dt', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'li', 'ol', 'p',\n 'pre', 'table', 'tbody', 'tfoot', 'thead', 'tr', 'ul',\n]);\n\n/** What table parts may contain: anything else is moved out of the table by every HTML parser. */\nexport const TABLE_CHILDREN: Readonly<Record<string, ReadonlySet<string>>> = {\n table: /* @__PURE__ */ new Set(['caption', 'colgroup', 'thead', 'tbody', 'tfoot', 'tr']),\n thead: /* @__PURE__ */ new Set(['tr']),\n tbody: /* @__PURE__ */ new Set(['tr']),\n tfoot: /* @__PURE__ */ new Set(['tr']),\n tr: /* @__PURE__ */ new Set(['td', 'th']),\n colgroup: /* @__PURE__ */ new Set(['col']),\n};\n\n/** Elements that hold only text-level content: a block inside one would be split out by HTML parsers. */\nexport const PHRASING: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'a', 'abbr', 'b', 'bdi', 'bdo', 'cite', 'code', 'del', 'dfn', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'i', 'ins', 'kbd', 'mark', 'p', 'q',\n 's', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'time', 'u', 'var',\n]);\n\n/** Table parts: outside their own parent, HTML parsers ignore their tags. */\nexport const TABLE_PARTS: ReadonlySet<string> = /* @__PURE__ */ new Set(['caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr']);\n\nexport const HEADINGS: ReadonlySet<string> = /* @__PURE__ */ new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n\n/** Elements whose start tag closes an open `<p>`: a paragraph holding one is split in two by HTML parsers. */\nexport const CLOSES_P: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'blockquote', 'dd', 'dl', 'dt', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'li', 'ol', 'p', 'pre', 'table', 'ul',\n]);\n\n/** Where HTML parsers stop looking for an open list item to close: their \"special\" elements, less address, div and p. */\nconst ITEM_SCOPE: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'blockquote', 'br', 'caption', 'col', 'colgroup', 'dd', 'dl', 'dt', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'img',\n 'li', 'ol', 'pre', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'ul',\n]);\n\n/** Whether a new `li` (or `dd`, `dt`) under `parent` would close an open one, as HTML parsers do with `<li>` in `<li>`. */\nexport function closesItem(name: 'li' | 'dd' | 'dt', parent: Node | null): boolean {\n const group = name === 'li' ? ['li'] : ['dd', 'dt'];\n for (let node = parent; node !== null && node.nodeType === 1; node = node.parentNode) {\n const tag = (node as Element).localName;\n if (group.includes(tag)) return true;\n if (ITEM_SCOPE.has(tag)) return false;\n }\n return false;\n}\n\nconst INTEGER = /^\\d{1,4}$/;\n\n/** Attributes kept per element (after `href` and `src`, which are checked as URLs). */\nexport function attributeAllowed(tag: string, name: string, value: string): boolean {\n switch (name) {\n case 'dir':\n return /^(?:ltr|rtl|auto)$/i.test(value);\n case 'lang':\n return /^[a-z]{2,3}(?:-[a-z\\d]{1,8})*$/i.test(value);\n case 'title':\n // Images write their own title, alt, size and source.\n return ['a', 'abbr', 'dfn'].includes(tag);\n case 'colspan':\n case 'rowspan':\n return (tag === 'td' || tag === 'th') && INTEGER.test(value) && Number(value) >= 1 && Number(value) <= 1000;\n case 'scope':\n return tag === 'th' && /^(?:row|col|rowgroup|colgroup)$/i.test(value);\n case 'span':\n return (tag === 'col' || tag === 'colgroup') && INTEGER.test(value);\n case 'start':\n return tag === 'ol' && /^-?\\d{1,9}$/.test(value);\n case 'reversed':\n return tag === 'ol';\n case 'type':\n return tag === 'ol' && /^[1aAiI]$/.test(value);\n case 'value':\n return tag === 'li' && /^-?\\d{1,9}$/.test(value);\n case 'datetime':\n return tag === 'time' && /^[\\d\\-:T.+ Z]{1,40}$/.test(value);\n default:\n return false;\n }\n}\n","import { contrastRatio } from '../color/contrast';\nimport { color as rgb, toGamut, type Color } from '../color/convert';\nimport { formatColor } from '../color/format';\nimport { parseColor } from '../color/parse';\n\n/** Where styles come from: `getComputedStyle` for a live element, the `style` attribute otherwise. */\nexport interface StyleSource {\n getPropertyValue(name: string): string;\n}\n\n/**\n * How colours are copied:\n * - `readable` (default): every colour, made opaque, except text that would be hard to\n * read where it lands (contrast under 3:1 on its background, or on white), such as\n * light text from a dark theme\n * - `keep`: every colour, made opaque\n * - `none`: no colours: the destination's own text colour and background\n */\nexport type RichColors = 'readable' | 'keep' | 'none';\n\nexport const INHERITED = ['color', 'font-family', 'font-size', 'font-style', 'font-weight', 'text-align', 'white-space', 'text-transform', 'list-style-type', 'border-collapse'] as const;\nconst SIDES = ['top', 'right', 'bottom', 'left'] as const;\nconst OWN = [\n 'background-color',\n 'text-decoration-line',\n 'vertical-align',\n 'border-top-width', 'border-top-style', 'border-top-color', 'padding-top',\n 'border-right-width', 'border-right-style', 'border-right-color', 'padding-right',\n 'border-bottom-width', 'border-bottom-style', 'border-bottom-color', 'padding-bottom',\n 'border-left-width', 'border-left-style', 'border-left-color', 'padding-left',\n] as const;\nexport const PROPERTIES = [...INHERITED, ...OWN] as const;\nexport type Property = (typeof PROPERTIES)[number];\nconst INHERITED_SET: ReadonlySet<Property> = /* @__PURE__ */ new Set<Property>(INHERITED);\n\n/**\n * What an element gets from its parent: the inherited values, with its own declared\n * ones on top. Lists set their own marker, as browsers' default styles do, so a list\n * doesn't inherit its parent list's marker.\n */\nexport function inherit(parent: Values, own?: Values, tag = ''): Values {\n const merged = {} as Record<Property, string>;\n for (const name of PROPERTIES) {\n const value = own === undefined ? '' : own[name];\n const inherits = INHERITED_SET.has(name) && !(name === 'list-style-type' && (tag === 'ul' || tag === 'ol'));\n merged[name] = value !== '' ? value : inherits ? parent[name] : '';\n }\n return merged;\n}\n\n/** Raw values of every property above, as the source reports them (`''` when unset), and the display type. */\nexport type Values = Readonly<Record<Property, string>> & { readonly display?: string };\n\nexport function readValues(source: StyleSource): Values {\n const values = {} as Record<Property, string>;\n for (const name of PROPERTIES) values[name] = source.getPropertyValue(name).trim().toLowerCase();\n return values;\n}\n\n/** Inherited values every rendering starts from: an empty parent for the root. */\nexport const ROOT_PARENT: Values = /* @__PURE__ */ Object.freeze({\n ...(Object.fromEntries(PROPERTIES.map((name) => [name, ''])) as Record<Property, string>),\n 'font-style': 'normal',\n 'font-weight': '400',\n 'text-align': 'start',\n 'white-space': 'normal',\n 'text-transform': 'none',\n 'border-collapse': 'separate',\n});\n\nconst KEYWORDS: Readonly<Record<string, RegExp>> = {\n 'font-style': /^(?:normal|italic|oblique)$/,\n 'text-align': /^(?:left|right|center|justify)$/,\n 'white-space': /^(?:normal|pre|pre-wrap|pre-line|nowrap|break-spaces)$/,\n 'text-transform': /^(?:none|uppercase|lowercase|capitalize)$/,\n 'list-style-type': /^(?:none|disc|circle|square|decimal|decimal-leading-zero|lower-alpha|upper-alpha|lower-latin|upper-latin|lower-roman|upper-roman|lower-greek)$/,\n 'border-collapse': /^(?:collapse|separate)$/,\n 'vertical-align': /^(?:top|bottom)$/,\n};\nconst LENGTH = /^(?:0|\\d{1,4}(?:\\.\\d+)?(?:px|pt|em|%))$/;\nconst FONT_FAMILY = /^[\\w\\s,'\"-]{1,200}$/;\n\n/** Elements whose default style already shows a value: writing it again adds nothing. */\nconst TAG_DEFAULTS: Readonly<Record<string, Readonly<Partial<Record<Property, string>>>>> = {\n b: { 'font-weight': '700' },\n strong: { 'font-weight': '700' },\n th: { 'font-weight': '700', 'text-align': 'center' },\n h1: { 'font-weight': '700' },\n h2: { 'font-weight': '700' },\n h3: { 'font-weight': '700' },\n h4: { 'font-weight': '700' },\n h5: { 'font-weight': '700' },\n h6: { 'font-weight': '700' },\n em: { 'font-style': 'italic' },\n i: { 'font-style': 'italic' },\n cite: { 'font-style': 'italic' },\n dfn: { 'font-style': 'italic' },\n var: { 'font-style': 'italic' },\n pre: { 'white-space': 'pre' },\n ol: { 'list-style-type': 'decimal' },\n ul: { 'list-style-type': 'disc' },\n li: { 'list-style-type': '' },\n a: { 'text-decoration-line': 'underline' },\n u: { 'text-decoration-line': 'underline' },\n ins: { 'text-decoration-line': 'underline' },\n s: { 'text-decoration-line': 'line-through' },\n del: { 'text-decoration-line': 'line-through' },\n};\n\nconst weight = (value: string): string => (value === 'bold' ? '700' : value === 'normal' ? '400' : /^[1-9]00$/.test(value) ? value : '');\n/** `start` and `end` as the left and right they mean in left-to-right text. */\nconst align = (value: string): string => {\n if (value === 'start') return 'left';\n if (value === 'end') return 'right';\n // Engines' internal names for the default centring of table headers.\n return value === '-webkit-center' || value === '-internal-center' || value === '-moz-center' ? 'center' : value;\n};\n\n/** A colour as an opaque hex value, drawn over `under`; `null` for none or invisible. */\nfunction opaque(value: string, under: Color): Color | null {\n const c = parseColor(value);\n if (c === null || c.alpha === 0) return null;\n const mapped = toGamut(c);\n const mix = (top: number, bottom: number) => top * c.alpha + bottom * (1 - c.alpha);\n return rgb(mix(mapped.r, under.r), mix(mapped.g, under.g), mix(mapped.b, under.b));\n}\n\nexport const WHITE: Color = /* @__PURE__ */ rgb(1, 1, 1);\n\n/** Pixel lengths rounded to 2 decimals; other units kept as written. */\nfunction length(value: string): string | null {\n if (!LENGTH.test(value)) return null;\n return value.endsWith('px') ? `${String(Math.round(parseFloat(value) * 100) / 100)}px` : value;\n}\n\nexport interface StyleResult {\n /** The `style` attribute to write, or `''`. */\n readonly css: string;\n /** The background the element's content is drawn on, for its children's contrast checks. */\n readonly background: Color;\n /** Whether a text colour was left out to stay readable. */\n readonly droppedColor: boolean;\n}\n\n/**\n * The declarations to write for an element: inherited properties where they differ\n * from the parent (all of them at the root), and the element's own box and decoration.\n */\nexport function declarations(tag: string, values: Values, parent: Values, background: Color, colors: RichColors): StyleResult {\n const out: string[] = [];\n const defaults = TAG_DEFAULTS[tag] ?? {};\n const changed = (name: Property, value: string) => value !== '' && value !== parent[name] && value !== defaults[name];\n let droppedColor = false;\n let own = background;\n\n // Background first: the text colour's contrast is checked against it.\n if (colors !== 'none') {\n const bg = opaque(values['background-color'], background);\n if (bg !== null) {\n own = bg;\n out.push(`background-color:${formatColor(bg)}`);\n }\n }\n const family = values['font-family'];\n if (changed('font-family', family) && FONT_FAMILY.test(family)) out.push(`font-family:${family}`);\n const size = length(values['font-size']);\n if (size !== null && changed('font-size', values['font-size'])) out.push(`font-size:${size}`);\n const fontWeight = weight(values['font-weight']);\n if (fontWeight !== weight(parent['font-weight']) && changed('font-weight', fontWeight)) out.push(`font-weight:${fontWeight}`);\n for (const name of ['font-style', 'white-space', 'text-transform', 'border-collapse'] as const) {\n const value = values[name];\n if (changed(name, value) && (KEYWORDS[name] as RegExp).test(value)) out.push(`${name}:${value}`);\n }\n const textAlign = align(values['text-align']);\n if (textAlign !== align(parent['text-align']) && textAlign !== defaults['text-align'] && (KEYWORDS['text-align'] as RegExp).test(textAlign)) {\n out.push(`text-align:${textAlign}`);\n }\n if (tag === 'ul' || tag === 'ol') {\n const list = values['list-style-type'];\n if (list !== defaults['list-style-type'] && list !== 'circle' && list !== 'square' && (KEYWORDS['list-style-type'] as RegExp).test(list)) out.push(`list-style-type:${list}`);\n }\n if (colors !== 'none' && changed('color', values['color'])) {\n const text = opaque(values['color'], own);\n if (text !== null) {\n if (colors === 'readable' && contrastRatio(text, own) < 3) droppedColor = true;\n else out.push(`color:${formatColor(text)}`);\n }\n }\n const decoration = values['text-decoration-line'];\n if (decoration !== '' && decoration !== defaults['text-decoration-line'] && /^(?:none|(?:underline|overline|line-through)(?: (?:underline|overline|line-through))*)$/.test(decoration)) {\n // Links are underlined by default in mail: a link drawn without one says so.\n if (decoration !== 'none' || tag === 'a') out.push(`text-decoration:${decoration}`);\n }\n const vertical = values['vertical-align'];\n if ((tag === 'td' || tag === 'th') && (KEYWORDS['vertical-align'] as RegExp).test(vertical)) out.push(`vertical-align:${vertical}`);\n out.push(...box(values, own, colors));\n return { css: out.join(';'), background: own, droppedColor };\n}\n\n/** Borders and padding, as shorthands where every side is the same. */\nfunction box(values: Values, background: Color, colors: RichColors): string[] {\n const borders = SIDES.map((side) => {\n const width = length(values[`border-${side}-width`]);\n const style = values[`border-${side}-style`];\n if (width === null || width === '0' || width === '0px' || !/^(?:solid|dashed|dotted|double)$/.test(style)) return null;\n const lineColor = colors === 'none' ? null : opaque(values[`border-${side}-color`], background);\n return `${width} ${style}${lineColor === null ? '' : ` ${formatColor(lineColor)}`}`;\n });\n const out: string[] = [];\n if (borders.every((border) => border !== null && border === borders[0])) out.push(`border:${borders[0] as string}`);\n else borders.forEach((border, index) => {\n if (border !== null) out.push(`border-${SIDES[index] as string}:${border}`);\n });\n const padding = SIDES.map((side) => length(values[`padding-${side}`]) ?? '0');\n if (padding.some((value) => value !== '0' && value !== '0px')) {\n out.push(`padding:${padding.map((value) => (value === '0px' ? '0' : value)).join(' ')}`);\n }\n return out;\n}\n","import { TEXT_BLOCKS } from './policy';\n\n/**\n * Readable plain text for sanitized rich content: blocks on their own lines, list\n * items with bullets or numbers (indented when nested), table cells separated by tabs,\n * images by their alt text, and preformatted text as it is.\n */\nexport function plainText(root: HTMLElement): string {\n const lines: string[] = [];\n let line = '';\n const flush = () => {\n const trimmed = line.replace(/[ \\t\\u00A0]+$/, '');\n if (trimmed !== '' || (lines.length > 0 && lines[lines.length - 1] !== '')) lines.push(trimmed);\n line = '';\n };\n const breakBlock = () => {\n if (line.trim() !== '') flush();\n else line = '';\n };\n\n const walk = (node: Node, pre: boolean, depth: number): void => {\n if (node.nodeType === 3) {\n const data = (node as Text).data;\n if (pre) line += data.replace(/\\r\\n?/g, '\\n');\n else {\n // Whitespace collapses across text nodes too, as it does when a browser renders it.\n const collapsed = data.replace(/\\s+/g, ' ');\n // A space at the start of a line or a cell shows nothing.\n line += /(?:^|[ \\t])$/.test(line) && collapsed.startsWith(' ') ? collapsed.slice(1) : collapsed;\n }\n if (pre && line.includes('\\n')) {\n const parts = line.split('\\n');\n line = parts.pop() as string;\n for (const part of parts) lines.push(part);\n }\n if (!pre && line.trimStart() === '') line = '';\n return;\n }\n if (node.nodeType !== 1) return;\n const element = node as HTMLElement;\n const tag = element.localName;\n switch (tag) {\n case 'br':\n flush();\n return;\n case 'img':\n line += element.getAttribute('alt') ?? '';\n return;\n case 'hr':\n breakBlock();\n lines.push('\\u2014'.repeat(3));\n return;\n case 'td':\n case 'th':\n if (element.previousElementSibling !== null) line += '\\t';\n element.childNodes.forEach((child) => {\n walk(child, pre, depth);\n });\n return;\n case 'li': {\n breakBlock();\n const list = element.parentElement;\n const ordered = list?.localName === 'ol';\n let marker = '\\u2022';\n if (ordered) {\n const items = Array.from(list.children).filter((child) => child.localName === 'li');\n const start = Number(list.getAttribute('start') ?? '1');\n const own = element.getAttribute('value');\n marker = `${String(own === null ? start + items.indexOf(element) : Number(own))}.`;\n }\n line = `${' '.repeat(Math.max(0, depth - 1))}${marker} `;\n element.childNodes.forEach((child) => {\n walk(child, pre, depth);\n });\n breakBlock();\n return;\n }\n default: {\n const block = TEXT_BLOCKS.has(tag);\n const list = tag === 'ul' || tag === 'ol';\n if (block) breakBlock();\n const keep = pre || tag === 'pre' || /white-space:\\s*pre/.test(element.getAttribute('style') ?? '');\n element.childNodes.forEach((child) => {\n walk(child, keep, list ? depth + 1 : depth);\n });\n if (block) breakBlock();\n }\n }\n };\n walk(root, false, 0);\n flush();\n return lines\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n}\n","import type { Color } from '../color/convert';\nimport { copyFailure } from '../core/errors';\nimport { linkUrlResolver, type LinkUrlOptions } from '../link/url';\nimport { AS_BLOCK, attributeAllowed, closesItem, CLOSES_P, DROP, HEADINGS, KEEP, PHRASING, TABLE_CHILDREN, TABLE_PARTS } from './policy';\nimport { parseColor } from '../color/parse';\nimport { declarations, inherit, readValues, ROOT_PARENT, WHITE, type RichColors, type StyleSource, type Values } from './style';\nimport { plainText } from './text';\nimport { parseInertHtml } from '../core/inert-html';\n\nexport interface RichOptions extends Pick<LinkUrlOptions, 'protocols'> {\n /** Resolves relative links and images. Default: the source document's address. */\n readonly base?: string | URL;\n /** Default `\"readable\"`. See {@link RichColors}. */\n readonly colors?: RichColors;\n /**\n * Images: `\"keep\"` (default) with absolute `https:` and `http:` addresses and their\n * displayed size; `\"alt\"` writes their alt text instead; `\"drop\"` leaves them out.\n */\n readonly images?: 'keep' | 'alt' | 'drop';\n /** Also keep `data:` images (PNG, JPEG, GIF, WebP, up to 2 MB each). Many mail clients block them. Default `false`. */\n readonly dataImages?: boolean;\n /**\n * Where styles come from: `\"computed\"` (default for elements and selections on the\n * page: what the reader sees), `\"inline\"` (only `style` attributes: the default for\n * HTML strings and detached nodes), or `\"none\"`.\n */\n readonly styles?: 'computed' | 'inline' | 'none';\n /** More elements to leave out, as a CSS selector. `[data-copy-ignore]`, `[hidden]` and `[aria-hidden=\"true\"]` always are. */\n readonly ignore?: string;\n /** The background the content is pasted on, for readability checks. Default `\"#ffffff\"`. */\n readonly background?: string;\n /** Most elements written; the rest is left out and `truncated` is set. Default 10,000. */\n readonly maxElements?: number;\n /** Most characters of HTML written, roughly. Default 1,000,000. */\n readonly maxLength?: number;\n /** The plain-text version. Default: readable text with lists, tables and line breaks. Pass `htmlToMarkdown` for Markdown. */\n readonly text?: (root: HTMLElement) => string;\n /** Reads an element's computed style. Default `getComputedStyle`; set it for DOMs that lack one. */\n readonly computedStyle?: (element: Element) => StyleSource | null;\n}\n\n/**\n * Why something was left out: `unsafe-element` (scripts, embeds, forms, SVG, media),\n * `hidden`, `ignored`, `unsafe-link`, `unsafe-image`, `image` (by the `images` option),\n * `unreadable-color` (by `colors: \"readable\"`), or `misplaced` (content a table can't\n * hold where it is, which every HTML parser would move out of the table).\n */\nexport type RichRemovalReason = 'unsafe-element' | 'hidden' | 'ignored' | 'unsafe-link' | 'unsafe-image' | 'image' | 'unreadable-color' | 'misplaced';\n\nexport interface RichRemoval {\n readonly reason: RichRemovalReason;\n /** The element name, or the URL scheme for links and images. */\n readonly name: string;\n readonly count: number;\n}\n\nexport interface RichResult {\n /** Portable HTML: allowlisted elements and attributes, inline styles, absolute URLs. */\n readonly html: string;\n /** The same content as plain text. */\n readonly text: string;\n /** What was left out, and why: for logs and audits. */\n readonly removed: readonly RichRemoval[];\n /** The content went past `maxElements` or `maxLength` and was cut there. */\n readonly truncated: boolean;\n}\n\n/** What can be copied: an element, a selection range, a fragment, or HTML text. */\nexport type RichSource = Element | DocumentFragment | Range | string;\n\nconst VOID = new Set(['br', 'hr', 'img', 'col']);\nconst BLOCK_DISPLAY = /^(?:block|flex|grid|flow-root|list-item|table)$/;\nconst DATA_IMAGE = /^data:image\\/(?:png|jpeg|gif|webp);base64,[a-z\\d+/]+=*$/i;\n\nfunction positive(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (Number.isInteger(value) && value > 0) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer.`);\n}\n\n/** Whether `source` holds an element that would close a paragraph around it. */\nfunction holdsBlocks(source: Element): boolean {\n for (let child = source.firstElementChild; child !== null; child = child.nextElementSibling) {\n if (CLOSES_P.has(child.localName) || holdsBlocks(child)) return true;\n }\n return false;\n}\n\n/** Whether `node` is (inside) a link in the output. */\nfunction insideLink(node: Node | null): boolean {\n for (let current = node; current !== null; current = current.parentNode) if ((current as Element).localName === 'a') return true;\n return false;\n}\n\nconst isRange = (value: unknown): value is Range =>\n typeof value === 'object' && value !== null && 'commonAncestorContainer' in value && typeof (value as Range).intersectsNode === 'function';\n\nclass Builder {\n readonly removals = new Map<string, RichRemoval>();\n truncated = false;\n private elements = 0;\n private size = 0;\n /** Table parts added around misplaced cells and rows, which later cells and rows share. */\n private readonly implied = new WeakSet<Node>();\n private readonly resolveLink: (url: string) => string;\n private readonly resolveImage: (url: string) => string;\n\n constructor(\n readonly out: Document,\n private readonly options: RichOptions,\n private readonly mode: 'computed' | 'inline' | 'none',\n private readonly computed: (element: Element) => StyleSource | null,\n private readonly colors: RichColors,\n private readonly ignore: string | null,\n private readonly maxElements: number,\n private readonly maxLength: number,\n base: string | URL | undefined,\n ) {\n const baseOption = base === undefined ? {} : { base };\n this.resolveLink = linkUrlResolver({ ...baseOption, ...(options.protocols === undefined ? {} : { protocols: options.protocols }) });\n this.resolveImage = linkUrlResolver({ ...baseOption, protocols: options.dataImages === true ? ['https:', 'http:', 'data:'] : ['https:', 'http:'] });\n }\n\n remove(reason: RichRemovalReason, name: string): void {\n const key = `${reason} ${name}`;\n const known = this.removals.get(key);\n this.removals.set(key, { reason, name, count: (known?.count ?? 0) + 1 });\n }\n\n /** The style values to use for an element, or `null` when it is hidden. */\n private values(element: Element, parent: Values): Values | null {\n if (this.mode === 'computed') {\n const style = this.computed(element);\n if (style === null) return inherit(parent, undefined, element.localName);\n const display = style.getPropertyValue('display').trim();\n const visibility = style.getPropertyValue('visibility').trim();\n if (display === 'none' || visibility === 'hidden' || visibility === 'collapse') return null;\n return { ...readValues(style), display };\n }\n const declared = (element as Partial<HTMLElement>).style;\n if (declared?.getPropertyValue('display').trim() === 'none') return null;\n // Declared values on top of the inherited ones, as the browser would compute them.\n const tag = element.localName;\n return this.mode === 'none' || declared === undefined ? inherit(parent, undefined, tag) : inherit(parent, readValues(declared), tag);\n }\n\n private url(raw: string | null, resolve: (url: string) => string): string | null {\n if (raw === null || raw.trim() === '') return null;\n try {\n return resolve(raw);\n } catch {\n return null;\n }\n }\n\n private budget(cost: number): boolean {\n if (this.elements >= this.maxElements || this.size + cost > this.maxLength) {\n this.truncated = true;\n return false;\n }\n this.size += cost;\n return true;\n }\n\n /** A URL's scheme for reports, read as the URL parser reads it: tabs and line breaks inside it don't count. */\n private scheme = (raw: string | null): string => /^\\s*([a-z][a-z\\d+.-]*):/i.exec((raw ?? '').replace(/[\\t\\n\\r]/g, ''))?.[1]?.toLowerCase() ?? 'relative';\n\n /** Converts `source` into `parent`, keeping only what lies inside `range` when given. */\n node(source: Node, parent: Node, inherited: Values, background: Color, range: Range | null, root = false): void {\n if (source.nodeType === 3) {\n let text = (source as Text).data;\n if (range !== null) {\n const end = source === range.endContainer ? range.endOffset : text.length;\n text = text.slice(source === range.startContainer ? range.startOffset : 0, end);\n }\n if (TABLE_CHILDREN[(parent as Element).localName] !== undefined && text.trim() !== '') {\n this.remove('misplaced', '#text');\n return;\n }\n if (text !== '' && this.budget(text.length)) parent.appendChild(this.out.createTextNode(text));\n return;\n }\n if (source.nodeType === 11 || source.nodeType === 9) {\n this.children(source, parent, inherited, background, range);\n return;\n }\n if (source.nodeType !== 1) return;\n this.element(source as Element, parent, inherited, background, range, root);\n }\n\n children(source: Node, parent: Node, inherited: Values, background: Color, range: Range | null): void {\n for (let child = source.firstChild; child !== null && !this.truncated; child = child.nextSibling) {\n if (range === null || range.intersectsNode(child)) this.node(child, parent, inherited, background, range);\n }\n }\n\n private element(source: Element, parent: Node, inherited: Values, background: Color, range: Range | null, root: boolean): void {\n const tag = source.localName.toLowerCase();\n if (DROP.has(tag) || source.namespaceURI !== 'http://www.w3.org/1999/xhtml') {\n this.remove('unsafe-element', tag);\n return;\n }\n // Attribute checks, not a selector: selector engines are slow to start in DOMs like jsdom.\n if (\n source.hasAttribute('data-copy-ignore') ||\n source.hasAttribute('hidden') ||\n source.getAttribute('aria-hidden') === 'true' ||\n (this.ignore !== null && source.matches(this.ignore))\n ) {\n this.remove('ignored', tag);\n return;\n }\n let values = this.values(source, inherited);\n if (values === null) {\n this.remove('hidden', tag);\n return;\n }\n // A selection's container is page chrome: only its inherited text style is kept.\n if (root && range !== null) values = { ...values, 'background-color': '', 'border-top-style': '', 'border-right-style': '', 'border-bottom-style': '', 'border-left-style': '', 'padding-top': '', 'padding-right': '', 'padding-bottom': '', 'padding-left': '' };\n if (tag === 'img') {\n this.image(source as HTMLImageElement, parent);\n return;\n }\n let name = KEEP.has(tag) ? tag : AS_BLOCK.has(tag) || BLOCK_DISPLAY.test(values.display ?? '') ? 'div' : 'span';\n let href: string | null = null;\n if (tag === 'a') {\n const raw = source.getAttribute('href');\n href = this.url(raw, this.resolveLink);\n if (href === null) {\n if (raw !== null && raw.trim() !== '') this.remove('unsafe-link', this.scheme(raw));\n name = 'span';\n }\n }\n let target = parent;\n let parentTag = (parent as Element).localName;\n // Outside a table, HTML parsers ignore table tags: a selection inside a table gets its table, anything else is a block.\n if (TABLE_PARTS.has(name) && TABLE_CHILDREN[parentTag] === undefined) {\n if (root) {\n target = parent.appendChild(this.out.createElement('table'));\n parentTag = 'table';\n } else if (name === 'col') {\n this.remove('misplaced', tag);\n return;\n } else name = 'div';\n }\n // The table parts that HTML parsers add around cells, rows and columns.\n const implied: string[] = [];\n if (parentTag === 'table' && (name === 'tr' || name === 'td' || name === 'th')) implied.push('tbody');\n if ((name === 'td' || name === 'th') && (implied.length > 0 || parentTag === 'tbody' || parentTag === 'thead' || parentTag === 'tfoot')) implied.push('tr');\n if (parentTag === 'table' && name === 'col') implied.push('colgroup');\n // A table part can hold only its own parts: anything else is left out, not moved around.\n const allowed = TABLE_CHILDREN[implied.at(-1) ?? parentTag];\n if (allowed !== undefined && !allowed.has(name)) {\n this.remove('misplaced', tag);\n return;\n }\n // What HTML parsers would split apart: a paragraph around blocks, a heading in a heading, a list item in a list item.\n if (name === 'p' && holdsBlocks(source)) name = 'div';\n if (HEADINGS.has(name) && HEADINGS.has(parentTag)) name = 'span';\n if ((name === 'li' || name === 'dd' || name === 'dt') && closesItem(name, parent)) name = 'div';\n // Inside text-level content, a block becomes inline and a link inside a link loses its link.\n if (name === 'div' && PHRASING.has(parentTag)) name = 'span';\n if (name === 'a' && insideLink(parent)) name = 'span';\n if (!this.budget(name.length * 2 + 5)) return;\n for (const wrapper of implied) {\n const last = (target as Element).lastElementChild;\n target = last !== null && this.implied.has(last) && last.localName === wrapper ? last : target.appendChild(this.out.createElement(wrapper));\n this.implied.add(target);\n }\n this.elements += 1;\n const out = this.out.createElement(name);\n if (href !== null && name === 'a') out.setAttribute('href', href);\n for (const attribute of Array.from(source.attributes)) {\n const key = attribute.name.toLowerCase();\n if (name === tag && attributeAllowed(tag, key, attribute.value)) out.setAttribute(key, attribute.value);\n }\n const style = declarations(name, values, root ? ROOT_PARENT : inherited, background, this.colors);\n if (style.droppedColor) this.remove('unreadable-color', tag);\n if (style.css !== '' && this.budget(style.css.length)) out.setAttribute('style', style.css);\n target.appendChild(out);\n if (!VOID.has(name)) this.children(source, out, values, style.background, range);\n }\n\n private image(source: HTMLImageElement, parent: Node): void {\n const alt = source.getAttribute('alt') ?? '';\n const policy = this.options.images ?? 'keep';\n if (policy === 'drop') {\n this.remove('image', 'img');\n return;\n }\n const raw = this.mode === 'computed' && source.currentSrc !== '' ? source.currentSrc : source.getAttribute('src');\n const src = policy === 'keep' ? this.url(raw, this.resolveImage) : null;\n const safe = src !== null && (!src.startsWith('data:') || (DATA_IMAGE.test(src) && src.length <= 2_000_000));\n if (!safe) {\n this.remove(policy === 'keep' ? 'unsafe-image' : 'image', policy === 'keep' ? this.scheme(raw) : 'img');\n if (alt !== '' && this.budget(alt.length)) parent.appendChild(this.out.createTextNode(alt));\n return;\n }\n if (!this.budget(src.length + alt.length + 40)) return;\n this.elements += 1;\n const out = this.out.createElement('img');\n out.setAttribute('src', src);\n if (alt !== '') out.setAttribute('alt', alt);\n // Mail clients size images by their attributes: write the displayed size.\n for (const side of ['width', 'height'] as const) {\n const shown = this.mode === 'computed' ? Math.round(source[side]) : NaN;\n const declared = source.getAttribute(side) ?? '';\n const value = shown > 0 ? String(shown) : /^\\d{1,5}$/.test(declared) ? declared : '';\n if (value !== '') out.setAttribute(side, value);\n }\n const title = source.getAttribute('title');\n if (title !== null) out.setAttribute('title', title);\n parent.appendChild(out);\n }\n}\n\n/** The DOM document to read and write with, or a typed error outside a browser. */\nfunction domFor(source: RichSource): { readonly doc: Document; readonly root: Node; readonly range: Range | null; readonly live: boolean } {\n if (typeof source === 'string') {\n if (typeof DOMParser === 'undefined') throw copyFailure('unsupported', 'Reading HTML text needs a DOM (DOMParser); pass a DOM node, or use a browser or jsdom.');\n // Inert: scripts never run and nothing is fetched. In standards mode, as pages and mail clients\n // read HTML (not quirks mode, which keeps a table inside a paragraph).\n const doc = parseInertHtml(`<!doctype html><body>${source}`);\n return { doc, root: doc.body, range: null, live: false };\n }\n if (isRange(source)) {\n const container = source.commonAncestorContainer;\n const element = container.nodeType === 1 ? container : container.parentNode;\n if (element === null || container.ownerDocument === null) throw copyFailure('invalid-payload', 'The range is not in a document.');\n return { doc: container.ownerDocument, root: element, range: source, live: container.isConnected };\n }\n const value: unknown = source;\n if (typeof value !== 'object' || value === null || !('nodeType' in value) || ((value as Node).nodeType !== 1 && (value as Node).nodeType !== 11)) {\n throw copyFailure('invalid-payload', 'Rich content must be an element, a fragment, a range or HTML text.');\n }\n const node = value as Node;\n return { doc: node.ownerDocument as Document, root: node, range: null, live: node.isConnected };\n}\n\n/**\n * Converts content into portable rich text: the HTML that mail clients, Google Docs,\n * Word, Notion and Slack paste as it looks, plus a plain-text version.\n *\n * - Only safe, widely supported elements and attributes are kept: never scripts,\n * event handlers, embeds, forms or tracking pixels from `data:` or `blob:` URLs.\n * - Styles are inline, from what the reader sees (computed styles) for content on\n * the page. Classes, stylesheets and CSS variables can't travel; their result can.\n * - Every colour becomes an opaque hex value, which every mail client understands\n * (not `oklch()` or `rgb(r g b / 50%)`). Text that would be unreadable on a white\n * page, such as light text from a dark theme, keeps the destination's colour.\n * - Links and images get absolute, scheme-checked URLs; images get their displayed size.\n *\n * Never inserts anything into the page: the output is built in a separate, inert document.\n *\n * @example\n * const { html, text, removed } = prepareRich(articleRef.current);\n */\nexport function prepareRich(source: RichSource, options: RichOptions = {}): RichResult {\n const { doc, root, range, live } = domFor(source);\n // Computed styles need content on a page with a window; anything else has only its style attributes.\n const mode = options.styles ?? (live && doc.defaultView !== null ? 'computed' : 'inline');\n const modeValue: unknown = mode; // Plain-JS callers can pass anything.\n if (modeValue !== 'computed' && modeValue !== 'inline' && modeValue !== 'none') throw copyFailure('invalid-payload', '`styles` must be \"computed\", \"inline\" or \"none\".');\n const colors = options.colors ?? 'readable';\n const colorsValue: unknown = colors;\n if (colorsValue !== 'readable' && colorsValue !== 'keep' && colorsValue !== 'none') throw copyFailure('invalid-payload', '`colors` must be \"readable\", \"keep\" or \"none\".');\n const images: unknown = options.images ?? 'keep';\n if (images !== 'keep' && images !== 'alt' && images !== 'drop') throw copyFailure('invalid-payload', '`images` must be \"keep\", \"alt\" or \"drop\".');\n const view = doc.defaultView;\n const computed = options.computedStyle ?? ((element: Element) => (view === null ? null : view.getComputedStyle(element)));\n const page = options.background === undefined ? WHITE : declarationsBackground(options.background);\n if (options.ignore !== undefined) {\n // An invalid selector is a programming error: it throws a typed error here, not mid-copy.\n try {\n doc.createElement('div').matches(options.ignore);\n } catch (cause) {\n throw copyFailure('invalid-payload', `\\`ignore\\` is not a valid CSS selector: ${options.ignore}`, cause);\n }\n }\n const out = doc.implementation.createHTMLDocument('');\n const builder = new Builder(\n out,\n options,\n mode,\n computed,\n colors,\n options.ignore ?? null,\n positive(options.maxElements, 10_000, 'maxElements'),\n positive(options.maxLength, 1_000_000, 'maxLength'),\n options.base ?? (doc.baseURI === 'about:blank' ? undefined : doc.baseURI),\n );\n const container = out.createElement('div');\n // HTML text is its body's content; anything else is converted with its root element.\n if (typeof source === 'string') builder.children(root, container, ROOT_PARENT, page, null);\n else builder.node(root, container, ROOT_PARENT, page, range, true);\n // Left-out nodes can leave text in pieces: join them, as reading the HTML back would.\n container.normalize();\n const text = (options.text ?? plainText)(container);\n if (typeof text !== 'string') throw copyFailure('invalid-payload', '`text` must return a string.');\n // Whitespace at the very edges shows nothing, and HTML parsers drop it when reading the copy.\n const first = container.firstChild;\n if (first?.nodeType === 3) (first as Text).data = (first as Text).data.replace(/^\\s+/, '');\n const last = container.lastChild;\n if (last?.nodeType === 3) (last as Text).data = (last as Text).data.replace(/\\s+$/, '');\n // Only whitespace is no content: nothing to copy.\n const empty = container.textContent.trim() === '' && container.querySelector('img, br, hr') === null;\n return { html: empty ? '' : container.innerHTML, text: empty ? '' : text, removed: [...builder.removals.values()], truncated: builder.truncated };\n}\n\n/** The destination background as an opaque colour; a typed error for anything else. */\nfunction declarationsBackground(value: string): Color {\n const parsed: Color | null = typeof value === 'string' ? parseColor(value) : null;\n if (parsed === null || parsed.alpha !== 1) throw copyFailure('invalid-payload', '`background` must be an opaque CSS colour.');\n return parsed;\n}\n","import type { CopyInterceptTransform, CopySelection, SyncCopyPayload } from '../core/copy-interceptor';\nimport { copyFailure } from '../core/errors';\nimport type { HtmlPayload } from '../core/payload';\nimport { prepareRich, type RichOptions, type RichSource } from './walk';\n\n/**\n * Content to copy as portable rich text: the sanitized HTML, and its plain text for\n * editors and plain fields. A typed `invalid-payload` error when nothing is left to copy.\n *\n * @example\n * const { copy } = useCopy();\n * <button onClick={() => copy(() => richPayload(noteRef.current))}>Copy note</button>\n */\nexport function richPayload(source: RichSource, options: RichOptions = {}): HtmlPayload {\n const { html, text } = prepareRich(source, options);\n if (html === '' || text === '') throw copyFailure('invalid-payload', 'There is nothing to copy: the content is empty, hidden or entirely left out.');\n return { kind: 'html', html, text };\n}\n\n/**\n * A copy interceptor transform that makes Ctrl/Cmd+C (and cut) of a selection in your\n * page portable: what the reader selected, with the styles they see, sanitized. The\n * plain text stays the browser's own. Selections in text fields are left alone.\n *\n * @example\n * useCopyInterceptor(articleRef, { transform: richTransform() });\n */\nexport function richTransform(options: RichOptions = {}): CopyInterceptTransform {\n return (selection: CopySelection): SyncCopyPayload | undefined => {\n if (selection.field !== null || typeof document === 'undefined') return undefined;\n const live = document.getSelection();\n if (live === null || live.rangeCount === 0) return undefined;\n const parts: string[] = [];\n for (let index = 0; index < live.rangeCount; index += 1) {\n const { html, text } = prepareRich(live.getRangeAt(index), options);\n // Nothing visible left (only scripts or hidden content, say): not worth a paste.\n if (text !== '' || html.includes('<img')) parts.push(html);\n }\n const html = parts.join('');\n return html === '' ? undefined : { kind: 'html', html, text: selection.text };\n };\n}\n","import { copyFailure } from '../core/errors';\nimport { linkUrlResolver } from '../link/url';\nimport { unwrapRedirect } from '../markdown/url';\nimport { DROP } from './policy';\nimport { prepareRich, type RichOptions, type RichRemoval, type RichRemovalReason, type RichResult } from './walk';\nimport { parseInertHtml } from '../core/inert-html';\n\n/**\n * What a destination can hold. A format left out of `formats` is written as the closest thing\n * that is allowed, and its text is always kept:\n *\n * - `bold`, `italic`, `underline`, `strike`, `code`, `superscript`, `subscript`: the text, unformatted.\n * - `link`: the link text. `image`: the image's alt text.\n * - `heading`: a paragraph, in bold when `bold` is allowed.\n * - `list`: a paragraph per item, after its marker (`\\u2022`, `1.`).\n * - `quote`: its paragraphs. `table`: a paragraph per cell, in reading order.\n * - `codeBlock`: a paragraph per line, as inline code when `code` is allowed.\n * - `rule`: nothing.\n */\nexport type RichPasteFormat =\n | 'bold'\n | 'italic'\n | 'underline'\n | 'strike'\n | 'code'\n | 'superscript'\n | 'subscript'\n | 'link'\n | 'image'\n | 'heading'\n | 'list'\n | 'quote'\n | 'codeBlock'\n | 'table'\n | 'rule';\n\n/** Every format, in the order the docs list them. */\nexport const RICH_PASTE_FORMATS: readonly RichPasteFormat[] = [\n 'bold', 'italic', 'underline', 'strike', 'code', 'superscript', 'subscript', 'link', 'image',\n 'heading', 'list', 'quote', 'codeBlock', 'table', 'rule',\n];\n\nexport interface PasteToRichOptions extends Pick<RichOptions, 'protocols' | 'dataImages' | 'maxElements' | 'maxLength' | 'text'> {\n /**\n * What the destination can hold, such as an editor's schema or a comment box's toolbar.\n * Default: every format. See {@link RichPasteFormat} for what happens to the rest.\n */\n readonly formats?: readonly RichPasteFormat[];\n /**\n * Resolves relative links and images, when you know where the content was copied from\n * (your own site, say). Default: none, so relative links keep only their text: a pasted\n * `/docs` would otherwise point into your site, not the one it came from.\n */\n readonly base?: string | URL;\n /** Most nodes of the pasted HTML read; the rest is left out and `truncated` is set. Default 200,000. */\n readonly maxNodes?: number;\n}\n\n/** Cleaned rich content: semantic HTML, its plain text, and what was left out. */\nexport interface RichPaste extends RichResult {\n /** `html` when cleaned from the rich flavour; `text` when built from plain text (paragraphs and line breaks). */\n readonly source: 'html' | 'text';\n}\n\n/** The clipboard flavours: a `PasteResult` from `usePaste`, or anything with `html` / `text`. */\nexport interface RichPasteSource {\n readonly html?: string | null;\n readonly text?: string | null;\n}\n\n/* ---------------------------------------------------------------- Inline */\n\nconst STRONG = 1;\nconst EM = 2;\nconst UNDERLINE = 4;\nconst STRIKE = 8;\nconst CODE = 16;\nconst SUP = 32;\nconst SUB = 64;\n\n/** Inline formats, outermost first: the fixed order makes the output canonical. */\nconst INLINE: readonly (readonly [bit: number, tag: string, format: RichPasteFormat])[] = [\n [STRONG, 'strong', 'bold'],\n [EM, 'em', 'italic'],\n [UNDERLINE, 'u', 'underline'],\n [STRIKE, 's', 'strike'],\n [CODE, 'code', 'code'],\n [SUP, 'sup', 'superscript'],\n [SUB, 'sub', 'subscript'],\n];\n\nconst TAG_BITS: Readonly<Record<string, number>> = {\n b: STRONG, strong: STRONG,\n i: EM, em: EM, cite: EM, dfn: EM, var: EM,\n u: UNDERLINE, ins: UNDERLINE,\n s: STRIKE, strike: STRIKE, del: STRIKE,\n code: CODE, kbd: CODE, samp: CODE, tt: CODE,\n sup: SUP, sub: SUB,\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\ntype Run =\n | { readonly kind: 'text'; readonly text: string; readonly bits: number; readonly href: string | null }\n | { readonly kind: 'break'; readonly bits: number; readonly href: string | null }\n | { readonly kind: 'image'; readonly image: Element; readonly bits: number; readonly href: string | null };\n\n/** Inline CSS, lower-cased. */\nfunction styleOf(element: Element): ReadonlyMap<string, string> {\n const map = new Map<string, string>();\n for (const declaration of (element.getAttribute('style') ?? '').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\n/** Formats after this element: its tag first, then its inline CSS, which wins (Google Docs, Word). */\nfunction bitsOf(bits: number, tag: string, style: ReadonlyMap<string, string>): number {\n let next = bits | (TAG_BITS[tag] ?? 0);\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 !== undefined) {\n if (decoration.includes('underline')) next |= UNDERLINE;\n if (decoration.includes('line-through')) next |= STRIKE;\n if (decoration === 'none') next &= ~(UNDERLINE | STRIKE);\n }\n const vertical = style.get('vertical-align');\n if (vertical === 'super') next = (next | SUP) & ~SUB;\n else if (vertical === 'sub') next = (next | SUB) & ~SUP;\n else if (vertical === 'baseline') next &= ~(SUP | SUB);\n const family = style.get('font-family');\n if (family !== undefined && MONOSPACE.test(family)) next |= CODE;\n return next;\n}\n\n/* ---------------------------------------------------------------- Blocks */\n\n/** Never content: scripts, metadata, embeds, media, controls, and Word's `<o:p>` spacers. */\nconst SKIP: ReadonlySet<string> = /* @__PURE__ */ new Set([...DROP, 'xml', 'o:p', 'area', 'menuitem']);\n\n/** Left out without a report: what every clipboard document carries (its head, Office markup), not content. */\nconst QUIET: ReadonlySet<string> = /* @__PURE__ */ new Set(['head', 'meta', 'title', 'link', 'base', 'style', 'xml', 'o:p']);\n\nconst HEADINGS: ReadonlySet<string> = /* @__PURE__ */ new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n\n/** Elements that start a new block. Anything else is inline: its content joins the current line. */\nconst BLOCKS: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'address', 'article', 'aside', 'blockquote', 'body', 'caption', 'center', 'dd', 'details', 'dialog', 'dir', 'div', 'dl', 'dt',\n 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'legend',\n 'li', 'listing', 'main', 'menu', 'nav', 'ol', 'p', 'pre', 'search', 'section', 'summary', 'table', 'tbody', 'td', 'tfoot',\n 'th', 'thead', 'tr', 'ul', 'xmp',\n]);\n\n/** What ends a line in an item already: a line break, or a block written into it. */\nconst LINE_ENDS: ReadonlySet<string> = /* @__PURE__ */ new Set(['br', 'ul', 'ol', 'table', 'pre', 'blockquote', 'hr', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n\n/** Containers that hold their own lines: inline content goes straight into them, not into a paragraph. */\nconst ITEMS: ReadonlySet<string> = /* @__PURE__ */ new Set(['li', 'td', 'th', 'dt', 'dd', 'caption']);\n\nconst BLOCK_SELECTOR = /* @__PURE__ */ [...BLOCKS].join(',');\n\nconst WORD_LIST = /mso-list\\s*:\\s*l\\d+\\s+level(\\d+)/i;\nconst ORDERED_MARKER = /^\\(?(\\d+|[a-z]|[ivxlcdm]+)[.)]/i;\n\n/** Deeper than this, content is kept as plain text: nothing is lost, and nothing overflows the stack. */\nconst MAX_DEPTH = 200;\n/** Most characters of pasted HTML read. */\nconst MAX_INPUT = 16 * 1024 * 1024;\n\nfunction isHidden(element: Element, style: ReadonlyMap<string, string>): boolean {\n return (\n element.hasAttribute('hidden') ||\n element.getAttribute('aria-hidden') === 'true' ||\n style.get('display') === 'none' ||\n style.get('visibility') === 'hidden' ||\n style.get('mso-list') === 'ignore' // Word's list markers: the list carries them\n );\n}\n\nconst isWordListParagraph = (node: Node): node is Element => node.nodeType === 1 && WORD_LIST.test((node as Element).getAttribute('style') ?? '');\n\n/**\n * The text of a code block, with its lines: line breaks, and one per block (as code editors put each\n * line in a `<div>`). `skipped` hears of each element left out.\n */\nfunction codeText(element: Element, skipped: (tag: string) => void): string {\n let text = '';\n const walk = (node: Node): void => {\n if (node.nodeType === 3) {\n text += (node as Text).data.replace(/\\u00A0/g, ' ');\n return;\n }\n if (node.nodeType !== 1) return;\n const child = node as Element;\n const tag = child.localName;\n if (SKIP.has(tag)) {\n skipped(tag);\n return;\n }\n if (isHidden(child, styleOf(child))) return;\n if (tag === 'br') {\n text += '\\n';\n return;\n }\n const block = BLOCKS.has(tag);\n if (block && text !== '' && !text.endsWith('\\n')) text += '\\n';\n child.childNodes.forEach(walk);\n if (block && text !== '' && !text.endsWith('\\n')) text += '\\n';\n };\n element.childNodes.forEach(walk);\n return text.replace(/\\r\\n?/g, '\\n').replace(/\\n$/, '');\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/** A table used for layout (mail, old pages): its cells are just content, in reading order. */\nfunction isLayoutTable(table: Element): boolean {\n const role = table.getAttribute('role');\n if (role === 'presentation' || role === 'none') return true;\n const cells = table.querySelectorAll('td, th');\n return cells.length === 1 || table.querySelector('td table, th table') !== null;\n}\n\ninterface WordList {\n readonly ordered: boolean;\n readonly start: number;\n readonly items: { readonly runs: readonly Run[]; readonly nested: WordList[] }[];\n}\n\ninterface Ctx {\n readonly bits: number;\n readonly href: string | null;\n readonly depth: number;\n}\n\n/** A URL's scheme for reports, read as the URL parser reads it: tabs and line breaks inside it don't count. */\nfunction positive(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (Number.isInteger(value) && value > 0) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer.`);\n}\n\nconst scheme = (raw: string): string => /^\\s*([a-z][a-z\\d+.-]*):/i.exec(raw.replace(/[\\t\\n\\r]/g, ''))?.[1]?.toLowerCase() ?? 'relative';\n\nclass Cleaner {\n private nodes = 0;\n truncated = false;\n readonly removals = new Map<string, RichRemoval>();\n private readonly allowedBits: number;\n private readonly resolveLink: (url: string) => string;\n private readonly resolveImage: (url: string) => string;\n /** Pasted content has no address of its own: relative URLs resolve only against `base`, never the page's. */\n private readonly absolute: (raw: string) => string;\n private readonly maxNodes: number;\n\n constructor(\n private readonly out: Document,\n private readonly formats: ReadonlySet<RichPasteFormat>,\n options: PasteToRichOptions,\n ) {\n this.allowedBits = INLINE.reduce((bits, [bit, , format]) => (formats.has(format) ? bits | bit : bits), 0);\n // The sanitizer's own checks, run here so a rejected link keeps only its text and a rejected image its alt text.\n const base = options.base === undefined ? {} : { base: options.base };\n this.resolveLink = linkUrlResolver({ ...base, ...(options.protocols === undefined ? {} : { protocols: options.protocols }) });\n this.resolveImage = linkUrlResolver({ ...base, protocols: options.dataImages === true ? ['https:', 'http:', 'data:'] : ['https:', 'http:'] });\n this.absolute = options.base === undefined ? (raw) => new URL(raw.trim()).href : (raw) => raw;\n this.maxNodes = positive(options.maxNodes, 200_000, 'maxNodes');\n }\n\n private remove(reason: RichRemovalReason, name: string): void {\n const key = `${reason} ${name}`;\n this.removals.set(key, { reason, name, count: (this.removals.get(key)?.count ?? 0) + 1 });\n }\n\n /** A link's address, absolute and scheme-checked, with click-tracking redirects (Google, Outlook Safe Links) unwrapped; `null` when unsafe. */\n private link(element: Element): string | null {\n const raw = (element.getAttribute('href') ?? '').trim();\n if (raw === '') return null;\n try {\n return unwrapRedirect(new URL(this.resolveLink(this.absolute(raw)))).href;\n } catch {\n this.remove('unsafe-link', scheme(raw));\n return null;\n }\n }\n\n /** Whether an image may be kept: an absolute, scheme-checked address. */\n private safeImage(image: Element): boolean {\n const raw = image.getAttribute('src') ?? '';\n try {\n this.resolveImage(this.absolute(raw));\n return true;\n } catch {\n this.remove('unsafe-image', scheme(raw));\n return false;\n }\n }\n\n private el(tag: string, ...children: Node[]): HTMLElement {\n const element = this.out.createElement(tag);\n element.append(...children);\n return element;\n }\n\n /** Whether reading may go on: a budget on source nodes, so huge or hostile input stays bounded. */\n private count(): boolean {\n if (this.nodes >= this.maxNodes) {\n this.truncated = true;\n return false;\n }\n this.nodes += 1;\n return true;\n }\n\n /**\n * Converts `nodes` into blocks inside `parent`. Inline content goes straight into `parent` when it is an\n * item (a list item, a table cell), or into paragraphs otherwise.\n */\n blocks(nodes: readonly Node[], parent: HTMLElement | DocumentFragment, ctx: Ctx): void {\n const item = parent.nodeType === 1 && ITEMS.has((parent as Element).localName);\n let runs: Run[] = [];\n const flush = (): void => {\n if (item) {\n // Paragraphs in a list item or a cell (Google Docs writes them) are its lines.\n this.line(runs, parent as HTMLElement);\n } else {\n const paragraph = this.out.createElement('p');\n if (this.emit(runs, paragraph)) parent.append(paragraph);\n }\n runs = [];\n };\n for (let index = 0; index < nodes.length; index += 1) {\n const node = nodes[index] as Node;\n if (isWordListParagraph(node)) {\n flush();\n index += this.wordList(nodes, index, parent, ctx) - 1;\n continue;\n }\n if (node.nodeType !== 1 || !BLOCKS.has((node as Element).localName)) {\n const wrapper = node.nodeType === 1 ? this.wrapper(node as Element, ctx) : null;\n if (wrapper === null) this.inline(node, ctx, runs);\n else {\n // An inline element around blocks (Google Docs wraps the whole document in a <b>): its formats\n // and link carry over, and its blocks stay blocks.\n flush();\n this.blocks(Array.from(node.childNodes), parent, wrapper);\n }\n continue;\n }\n const element = node as Element;\n const tag = element.localName;\n const style = styleOf(element);\n if (isHidden(element, style) || !this.count()) continue;\n if (item && (tag === 'p' || (tag === 'div' && !isCodeContainer(tag, style)))) {\n // A paragraph in an item: a line of the item.\n flush();\n runs = this.runsOf(element, ctx);\n flush();\n continue;\n }\n flush();\n this.block(element, tag, style, parent, ctx);\n }\n flush();\n }\n\n /** The context inside an inline element that holds blocks, or `null` for one that holds only inline content. */\n private wrapper(element: Element, ctx: Ctx): Ctx | null {\n if (ctx.depth >= MAX_DEPTH || element.querySelector(BLOCK_SELECTOR) === null) return null;\n const tag = element.localName;\n const style = styleOf(element);\n if (SKIP.has(tag) || element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || isHidden(element, style)) return null;\n return this.inner(element, tag, style, ctx);\n }\n\n /** The formats and link inside an inline element. */\n private inner(element: Element, tag: string, style: ReadonlyMap<string, string>, ctx: Ctx): Ctx {\n const href = tag === 'a' && ctx.href === null && this.formats.has('link') ? this.link(element) : ctx.href;\n // CSS wins over the tag, so Google Docs' wrapper, a `<b style=\"font-weight:normal\">`, is not bold.\n return { bits: bitsOf(ctx.bits, tag, style), href, depth: ctx.depth + 1 };\n }\n\n private block(element: Element, tag: string, style: ReadonlyMap<string, string>, parent: HTMLElement | DocumentFragment, ctx: Ctx): void {\n const deeper: Ctx = { ...ctx, depth: ctx.depth + 1 };\n if (ctx.depth >= MAX_DEPTH) {\n this.paragraph([{ kind: 'text', text: element.textContent, bits: 0, href: null }], parent);\n return;\n }\n if (tag === 'pre' || tag === 'listing' || tag === 'xmp' || isCodeContainer(tag, style)) {\n this.codeBlock(codeText(element, (skipped) => { if (!QUIET.has(skipped)) this.remove('unsafe-element', skipped); }), parent);\n return;\n }\n if (HEADINGS.has(tag)) {\n // Headings are bold already: bold inside one is noise.\n const runs = this.runsOf(element, deeper).map((run) => ({ ...run, bits: run.bits & ~STRONG }));\n if (this.formats.has('heading')) {\n const heading = this.out.createElement(tag);\n if (this.emit(runs, heading)) parent.append(heading);\n } else this.paragraph(runs.map((run) => ({ ...run, bits: run.bits | STRONG })), parent);\n return;\n }\n if (tag === 'ul' || tag === 'ol' || tag === 'menu' || tag === 'dir') {\n this.list(element, tag === 'ol', parent, deeper);\n return;\n }\n if (tag === 'li') {\n // A list item outside a list: the list is implied.\n this.list(element, false, parent, deeper, [element]);\n return;\n }\n if (tag === 'blockquote') {\n if (!this.formats.has('quote')) {\n this.blocks(Array.from(element.childNodes), parent, deeper);\n return;\n }\n const quote = this.out.createElement('blockquote');\n this.blocks(Array.from(element.childNodes), quote, deeper);\n if (quote.firstChild !== null) parent.append(quote);\n return;\n }\n if (tag === 'table') {\n this.table(element, parent, deeper);\n return;\n }\n if (tag === 'hr') {\n if (this.formats.has('rule')) parent.append(this.out.createElement('hr'));\n return;\n }\n if (tag === 'dl') {\n // A description list keeps its terms and details as paragraphs: few editors have one.\n this.blocks(Array.from(element.childNodes), parent, deeper);\n return;\n }\n // Paragraphs, divisions and sections: their inline content forms paragraphs, their blocks stay blocks.\n this.blocks(Array.from(element.childNodes), parent, deeper);\n }\n\n /** A new line of an item: after a line break when the item already ends in text. */\n private line(runs: readonly Run[], item: HTMLElement): void {\n const last = item.lastChild;\n if (last !== null && hasContent(runs) && (last.nodeType !== 1 || !LINE_ENDS.has((last as Element).localName))) item.append(this.out.createElement('br'));\n this.emit(runs, item);\n }\n\n /** A paragraph for `runs` (or the item's own line), when they hold anything. */\n private paragraph(runs: readonly Run[], parent: HTMLElement | DocumentFragment): void {\n if (parent.nodeType === 1 && ITEMS.has((parent as Element).localName)) {\n this.line(runs, parent as HTMLElement);\n return;\n }\n const paragraph = this.out.createElement('p');\n if (this.emit(runs, paragraph)) parent.append(paragraph);\n }\n\n private codeBlock(text: string, parent: HTMLElement | DocumentFragment): void {\n if (text.trim() === '') return;\n if (this.formats.has('codeBlock')) {\n parent.append(this.el('pre', this.el('code', this.out.createTextNode(text))));\n return;\n }\n // A line per paragraph, its spaces kept as no-break spaces so indentation survives.\n for (const line of text.split('\\n')) {\n this.paragraph([{ kind: 'text', text: line.replace(/ /g, '\\u00A0'), bits: CODE, href: null }], parent);\n }\n }\n\n private list(element: Element, ordered: boolean, parent: HTMLElement | DocumentFragment, ctx: Ctx, items?: readonly Element[]): void {\n const start = ordered ? Number.parseInt(element.getAttribute('start') ?? '1', 10) : 1;\n const first = Number.isFinite(start) ? start : 1;\n if (!this.formats.has('list')) {\n // Each item a paragraph after its marker, nested lists after their item.\n let number = first;\n for (const child of items ?? Array.from(element.childNodes)) {\n if (child.nodeType !== 1 || (child as Element).localName !== 'li') {\n this.blocks([child], parent, ctx);\n continue;\n }\n const marker: Run = { kind: 'text', text: ordered ? `${String(number)}. ` : '\\u2022 ', bits: 0, href: null };\n number += 1;\n const own = Array.from(child.childNodes).filter((node) => !(node.nodeType === 1 && /^(?:ul|ol|menu|dir)$/.test((node as Element).localName)));\n const runs = own.flatMap((node) => (node.nodeType === 1 && BLOCKS.has((node as Element).localName) ? [...this.runsOf(node as Element, ctx), BREAK] : this.inlineRuns(node, ctx)));\n this.paragraph([marker, ...trimBreaks(runs)], parent);\n for (const nested of Array.from((child as Element).children)) if (/^(?:ul|ol|menu|dir)$/.test(nested.localName)) this.list(nested, nested.localName === 'ol', parent, ctx);\n }\n return;\n }\n const list = this.out.createElement(ordered ? 'ol' : 'ul');\n if (ordered && first !== 1) list.setAttribute('start', String(first));\n for (const child of items ?? Array.from(element.childNodes)) {\n if (child.nodeType === 1 && (child as Element).localName === 'li') {\n const li = this.out.createElement('li');\n this.blocks(Array.from(child.childNodes), li, ctx);\n list.append(li);\n continue;\n }\n // Google Docs nests a list as the sibling of its item, not inside it; text between items is an item.\n const host = list.lastElementChild ?? list.appendChild(this.out.createElement('li'));\n this.blocks([child], host as HTMLElement, ctx);\n }\n // Items with nothing in them are left out; a list with no items is too.\n for (const li of Array.from(list.children)) if (li.firstChild === null) li.remove();\n if (list.firstChild !== null) parent.append(list);\n }\n\n /**\n * Word writes lists as paragraphs with `mso-list: l0 level2`, and each marker (`1.`, `·`) as\n * text in a span hidden with `mso-list: Ignore`. Rebuilds the consecutive list paragraphs\n * from `nodes[start]` as nested lists. Returns how many nodes they took.\n */\n private wordList(nodes: readonly Node[], start: number, parent: HTMLElement | DocumentFragment, ctx: Ctx): number {\n const roots: WordList[] = [];\n const stack: { level: number; list: WordList }[] = [];\n let consumed = 0;\n const flat = !this.formats.has('list');\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 // Taken even past the node budget, so the caller always moves on.\n consumed = index - start + 1;\n if (!this.count()) break;\n const level = Number(WORD_LIST.exec(node.getAttribute('style') as string)?.[1]);\n const marker = (node.querySelector('[style*=\"mso-list\"][style*=\"gnore\"]')?.textContent ?? '').replace(/\\s+/g, '');\n const ordered = ORDERED_MARKER.exec(marker);\n const runs = this.runsOf(node, ctx);\n if (flat) {\n // Word's own marker, as Word shows it.\n const shown = ordered !== null ? `${marker} ` : '\\u2022 ';\n this.paragraph([{ kind: 'text', text: shown, bits: 0, href: null }, ...runs], parent);\n continue;\n }\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 number = ordered !== null && /^\\d+$/.test(ordered[1] as string) ? Number(ordered[1]) : 1;\n const list: WordList = { ordered: ordered !== null, start: number, items: [] };\n const host = top?.list.items[top.list.items.length - 1];\n if (host === undefined) roots.push(list);\n else host.nested.push(list);\n top = { level, list };\n stack.push(top);\n }\n top.list.items.push({ runs, nested: [] });\n }\n for (const list of roots) this.writeWordList(list, parent);\n return consumed;\n }\n\n /** Writes a rebuilt Word list. An item with nothing in it is left out, unless it holds a nested list. */\n private writeWordList(list: WordList, parent: Node): void {\n const element = this.out.createElement(list.ordered ? 'ol' : 'ul');\n if (list.ordered && list.start !== 1) element.setAttribute('start', String(list.start));\n for (const item of list.items) {\n const li = this.out.createElement('li');\n this.emit(item.runs, li);\n for (const nested of item.nested) this.writeWordList(nested, li);\n if (li.firstChild !== null) element.append(li);\n }\n if (element.firstChild !== null) parent.appendChild(element);\n }\n\n private table(table: Element, parent: HTMLElement | DocumentFragment, ctx: Ctx): void {\n const rows = Array.from(table.querySelectorAll('tr')).filter((row) => row.closest('table') === table);\n const caption = Array.from(table.children).find((child) => child.localName === 'caption');\n if (!this.formats.has('table') || isLayoutTable(table)) {\n // Its content in reading order: the caption, then each cell's blocks.\n if (caption !== undefined) this.blocks(Array.from(caption.childNodes), parent, ctx);\n for (const row of rows) for (const cell of Array.from(row.children)) if (cell.localName === 'td' || cell.localName === 'th') this.blocks(Array.from(cell.childNodes), parent, ctx);\n return;\n }\n const out = this.out.createElement('table');\n if (caption !== undefined) {\n const element = this.out.createElement('caption');\n this.blocks(Array.from(caption.childNodes), element, ctx);\n if (element.firstChild !== null) out.append(element);\n }\n const sections = new Map<Element, HTMLElement>();\n for (const row of rows) {\n if (!this.count()) break;\n // The HTML parser puts every row in a section (a <tbody> when none is written).\n const group = row.parentElement as Element;\n let section = sections.get(group);\n if (section === undefined) {\n section = this.out.createElement(group.localName === 'thead' || group.localName === 'tfoot' ? group.localName : 'tbody');\n sections.set(group, section);\n out.append(section);\n }\n const tr = this.out.createElement('tr');\n for (const cell of Array.from(row.children)) {\n if (cell.localName !== 'td' && cell.localName !== 'th') continue;\n const element = this.out.createElement(cell.localName);\n for (const attribute of ['colspan', 'rowspan', 'scope']) {\n const value = cell.getAttribute(attribute);\n if (value !== null) element.setAttribute(attribute, value);\n }\n // Header cells are bold already.\n this.blocks(Array.from(cell.childNodes), element, cell.localName === 'th' ? { ...ctx, bits: ctx.bits & ~STRONG } : ctx);\n if (cell.localName === 'th') stripBold(element);\n tr.append(element);\n }\n section.append(tr);\n }\n if (rows.length > 0) parent.append(out);\n }\n\n /** The inline content of `element` as runs: its blocks become lines, separated by line breaks. */\n private runsOf(element: Element, ctx: Ctx): Run[] {\n const runs: Run[] = [];\n const inner = { ...ctx, bits: bitsOf(ctx.bits, element.localName, styleOf(element)) };\n for (const child of Array.from(element.childNodes)) {\n if (child.nodeType === 1 && BLOCKS.has((child as Element).localName) && (child as Element).localName !== 'br') {\n const element = child as Element;\n if (isHidden(element, styleOf(element))) continue;\n if (runs.length > 0) runs.push(BREAK);\n runs.push(...this.runsOf(element, { ...inner, depth: inner.depth + 1 }));\n runs.push(BREAK);\n continue;\n }\n this.inline(child, inner, runs);\n }\n return trimBreaks(runs);\n }\n\n private inlineRuns(node: Node, ctx: Ctx): Run[] {\n const runs: Run[] = [];\n this.inline(node, ctx, runs);\n return runs;\n }\n\n /** Inline content into runs: text with its formats and link, line breaks and images. */\n private inline(node: Node, ctx: Ctx, runs: Run[]): void {\n if (!this.count()) return;\n if (node.nodeType === 3) {\n runs.push({ kind: 'text', text: (node as Text).data, bits: ctx.bits, href: ctx.href });\n return;\n }\n if (node.nodeType !== 1) return;\n const element = node as Element;\n const tag = element.localName;\n const style = styleOf(element);\n if (SKIP.has(tag) || element.namespaceURI !== 'http://www.w3.org/1999/xhtml') {\n if (!QUIET.has(tag)) this.remove('unsafe-element', tag);\n return;\n }\n if (isHidden(element, style)) return;\n if (tag === 'br') {\n runs.push({ kind: 'break', bits: ctx.bits, href: ctx.href });\n return;\n }\n if (tag === 'img') {\n if (!this.formats.has('image') || this.safeImage(element)) runs.push({ kind: 'image', image: element, bits: ctx.bits, href: ctx.href });\n else runs.push({ kind: 'text', text: element.getAttribute('alt') ?? '', bits: ctx.bits, href: ctx.href });\n return;\n }\n if (ctx.depth >= MAX_DEPTH) {\n runs.push({ kind: 'text', text: element.textContent, bits: ctx.bits, href: ctx.href });\n return;\n }\n const inner = this.inner(element, tag, style, ctx);\n if (BLOCKS.has(tag)) {\n // A block inside inline content (a heading's paragraphs, a link around a division): a line of its own.\n runs.push(BREAK, ...this.runsOf(element, inner), BREAK);\n return;\n }\n for (const child of Array.from(element.childNodes)) this.inline(child, inner, runs);\n }\n\n /**\n * Writes `runs` into `target` as minimal, canonical markup: links outermost, then the formats in a\n * fixed order, each over the longest stretch it covers. Whitespace collapses as the browser shows it.\n * Returns whether anything was written.\n */\n emit(runs: readonly Run[], target: Node): boolean {\n const cleaned = collapse(\n runs.map((run) => {\n const bits = run.bits & this.allowedBits;\n const href = this.formats.has('link') ? run.href : null;\n return run.kind === 'image' && !this.formats.has('image')\n ? ({ kind: 'text', text: run.image.getAttribute('alt') ?? '', bits, href } as const)\n : { ...run, bits, href };\n }),\n );\n if (cleaned.length === 0) return false;\n this.write(cleaned, target, 0);\n return true;\n }\n\n private write(runs: readonly Run[], target: Node, level: number): void {\n if (level === 0) {\n for (const group of groups(runs, (run) => run.href)) {\n const href = (group[0] as Run).href;\n if (href === null) this.write(group, target, 1);\n else {\n const link = this.out.createElement('a');\n link.setAttribute('href', href);\n this.write(group, link, 1);\n target.appendChild(link);\n }\n }\n return;\n }\n const format = INLINE[level - 1];\n if (format === undefined) {\n for (const run of runs) {\n if (run.kind === 'text') target.appendChild(this.out.createTextNode(run.text));\n else if (run.kind === 'break') target.appendChild(this.out.createElement('br'));\n else target.appendChild(copyImage(this.out, run.image));\n }\n return;\n }\n const [bit, tag] = format;\n for (const group of groups(runs, (run) => (run.bits & bit) !== 0)) {\n if (((group[0] as Run).bits & bit) === 0) this.write(group, target, level + 1);\n else {\n const element = this.out.createElement(tag);\n this.write(group, element, level + 1);\n target.appendChild(element);\n }\n }\n }\n}\n\nconst BREAK: Run = { kind: 'break', bits: 0, href: null };\n\nconst hasContent = (runs: readonly Run[]): boolean => runs.some((run) => run.kind === 'image' || (run.kind === 'text' && /[^\\s]/.test(run.text)));\n\nfunction trimBreaks(runs: Run[]): Run[] {\n let start = 0;\n let end = runs.length;\n while (start < end && (runs[start] as Run).kind === 'break') start += 1;\n while (end > start && (runs[end - 1] as Run).kind === 'break') end -= 1;\n return runs.slice(start, end);\n}\n\n/** Maximal stretches of runs with the same key. */\nfunction groups(runs: readonly Run[], key: (run: Run) => unknown): Run[][] {\n const out: Run[][] = [];\n let last: unknown;\n for (const run of runs) {\n const value = key(run);\n const current = out[out.length - 1];\n if (current !== undefined && value === last) current.push(run);\n else out.push([run]);\n last = value;\n }\n return out;\n}\n\n/**\n * Whitespace as the browser shows it: runs of it are one space, none at the start or end of a line,\n * and line breaks without text after them (or several in a row at the edges) are left out.\n * Spaces take no formats, so formatting never starts or ends with one.\n */\nfunction collapse(runs: readonly Run[]): Run[] {\n const out: Run[] = [];\n let lineStart = true;\n let pendingSpace = false;\n for (const run of runs) {\n if (run.kind === 'break') {\n pendingSpace = false;\n out.push(run);\n lineStart = true;\n continue;\n }\n if (run.kind === 'image') {\n if (pendingSpace) out.push({ kind: 'text', text: ' ', bits: 0, href: null });\n pendingSpace = false;\n out.push(run);\n lineStart = false;\n continue;\n }\n const parts = run.text.split(/[ \\t\\n\\r\\f]+/);\n for (let index = 0; index < parts.length; index += 1) {\n const part = parts[index] as string;\n if (index > 0 && !lineStart) pendingSpace = true;\n if (part === '') continue;\n if (pendingSpace) {\n // A space takes the formats and link on both sides of it, so \"<b>on</b> <b>Friday</b>\" stays one bold run.\n // A pending space always follows text or an image on the same line.\n const last = out[out.length - 1] as Run;\n out.push({ kind: 'text', text: ' ', bits: last.bits & run.bits, href: last.href === run.href ? run.href : null });\n }\n pendingSpace = false;\n out.push({ kind: 'text', text: part, bits: run.bits, href: run.href });\n lineStart = false;\n }\n }\n // Join neighbouring text with the same formats and link, so the output is canonical.\n const merged: Run[] = [];\n for (const run of trimBreaks(out)) {\n const last = merged[merged.length - 1];\n if (run.kind === 'text' && last?.kind === 'text' && last.bits === run.bits && last.href === run.href) merged[merged.length - 1] = { ...last, text: last.text + run.text };\n else merged.push(run);\n }\n return hasContent(merged) ? merged : [];\n}\n\n/** An image with what describes it, never its styles or event handlers. */\nfunction copyImage(doc: Document, image: Element): HTMLElement {\n const out = doc.createElement('img');\n for (const name of ['src', 'alt', 'title', 'width', 'height']) {\n const value = image.getAttribute(name);\n if (value !== null) out.setAttribute(name, value);\n }\n return out;\n}\n\n/** Bold inside a header cell is noise: the cell is bold already. */\nfunction stripBold(cell: Element): void {\n for (const strong of Array.from(cell.querySelectorAll('strong'))) strong.replaceWith(...Array.from(strong.childNodes));\n cell.normalize();\n}\n\n/* ---------------------------------------------------------------- Public */\n\nfunction resolveFormats(formats: readonly RichPasteFormat[] | undefined): ReadonlySet<RichPasteFormat> {\n if (formats === undefined) return new Set(RICH_PASTE_FORMATS);\n const value: unknown = formats;\n if (!Array.isArray(value) || !value.every((format) => (RICH_PASTE_FORMATS as readonly unknown[]).includes(format))) {\n throw copyFailure('invalid-payload', `\\`formats\\` must be an array of: ${RICH_PASTE_FORMATS.join(', ')}.`);\n }\n return new Set(formats);\n}\n\nconst escapeHtml = (text: string): string => text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\n/** Plain text as rich content: a paragraph per block of lines, a line break per line. Needs no DOM. */\nfunction fromText(text: string, maxLength: number): RichPaste {\n const normalized = text.replace(/\\r\\n?/g, '\\n');\n const paragraphs = normalized\n .split(/\\n[ \\t]*\\n+/)\n .map((block) => block.split('\\n').map((line) => escapeHtml(line.trim())).filter((line) => line !== ''))\n .filter((lines) => lines.length > 0);\n let html = '';\n let truncated = false;\n for (const lines of paragraphs) {\n const paragraph = `<p>${lines.join('<br>')}</p>`;\n if (html.length + paragraph.length > maxLength) {\n truncated = true;\n break;\n }\n html += paragraph;\n }\n return { html, text: normalized.trim(), removed: [], truncated, source: 'text' };\n}\n\n/**\n * Cleans what was pasted into semantic, safe HTML for a rich-text editor: the HTML Google Docs,\n * Word, Outlook, Gmail, Notion and web pages put on the clipboard becomes paragraphs, headings,\n * lists, quotes, code blocks, tables, links and images, with bold, italic, underline,\n * strikethrough, code, superscript and subscript as tags (`<strong>`, `<em>`, ...).\n *\n * - Formatting set by CSS (`font-weight: 700`, `font-style: italic`) becomes tags, and every\n * style, class and id is left out: pasted content takes the editor's look, not the source's.\n * - Word's paragraph lists become real lists; Google Docs' wrappers, empty spacers and hidden\n * markers go. Layout tables (mail) become their content.\n * - The output is canonical (the same content always gives the same HTML) and goes through the\n * same sanitizer as {@link prepareRich}: only allowlisted elements and attributes, links and\n * images with absolute, scheme-checked URLs. `removed` says what was left out.\n * - `formats` limits the output to what your editor holds, keeping all of the text.\n *\n * Plain text (no HTML on the clipboard) becomes paragraphs and line breaks. Returns `null` when\n * there is nothing to paste. HTML needs `DOMParser` (any browser, or jsdom); without one, the\n * plain text is used.\n *\n * @example\n * // TipTap / ProseMirror\n * editorProps: { transformPastedHTML: (html) => pasteToRich({ html })?.html ?? '' }\n */\nexport function pasteToRich(source: RichPasteSource, options: PasteToRichOptions = {}): RichPaste | null {\n const formats = resolveFormats(options.formats); // invalid options are a programming error: they throw\n const maxLength = options.maxLength ?? 1_000_000;\n const html = source.html ?? null;\n const text = source.text ?? null;\n if (html !== null && html.trim() !== '' && typeof DOMParser !== 'undefined') {\n // Inert: scripts never run and nothing is fetched. Its nodes are only read.\n const parsed = parseInertHtml(`<!doctype html><body>${html.slice(0, MAX_INPUT)}`);\n // Built in a document with no address, so relative links resolve only against `base`.\n const out = parsed.implementation.createHTMLDocument('');\n const cleaner = new Cleaner(out, formats, options);\n const fragment = out.createDocumentFragment();\n cleaner.blocks(Array.from(parsed.body.childNodes), fragment, { bits: 0, href: null, depth: 0 });\n const result = prepareRich(fragment, {\n styles: 'none',\n images: formats.has('image') ? 'keep' : 'alt',\n ...(options.base === undefined ? {} : { base: options.base }),\n ...(options.protocols === undefined ? {} : { protocols: options.protocols }),\n ...(options.dataImages === undefined ? {} : { dataImages: options.dataImages }),\n ...(options.maxElements === undefined ? {} : { maxElements: options.maxElements }),\n maxLength,\n ...(options.text === undefined ? {} : { text: options.text }),\n });\n if (result.html !== '') {\n // Never the same entry twice: the sanitizer only sees what the cleaner kept.\n const removed = [...cleaner.removals.values(), ...result.removed];\n return { ...result, removed, truncated: result.truncated || cleaner.truncated || html.length > MAX_INPUT, source: 'html' };\n }\n }\n if (text === null || text.trim() === '') return null;\n const value: unknown = maxLength;\n if (!(Number.isInteger(value) && maxLength > 0)) throw copyFailure('invalid-payload', '`maxLength` must be a positive integer.');\n return fromText(text, maxLength);\n}\n\n/** Structural paste event: a DOM `ClipboardEvent` and React's `onPaste` event both fit. */\nexport interface RichPasteEvent {\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\nexport interface PasteAsRichOptions extends PasteToRichOptions {\n /**\n * Called with the cleaned content before it is inserted. Return `false` to insert it yourself\n * (through your editor's API, say): the browser's paste is still prevented.\n */\n readonly onPaste?: (pasted: RichPaste) => boolean | undefined;\n}\n\n/** The editable element a paste lands in: the handler's element when it is `contenteditable`. */\nfunction editableHost(event: RichPasteEvent): HTMLElement | null {\n const target: unknown = event.currentTarget ?? event.target;\n if (typeof target !== 'object' || target === null || (target as Partial<Node>).nodeType !== 1) return null;\n const element = target as HTMLElement;\n return element.isContentEditable ? element : null;\n}\n\n/**\n * Inserts HTML at the selection in an editable element, as a paste would: the browser's undo\n * (Ctrl/Cmd+Z) still works and `input` events fire. Without a selection inside the element,\n * the HTML goes at its end.\n */\nfunction insertHtml(host: HTMLElement, html: string): void {\n const doc = host.ownerDocument;\n const selection = doc.getSelection();\n const current = selection !== null && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;\n // Where it goes: the selection in the element, or its end. Kept across focusing, which can move the\n // caret, and insertHTML acts in the focused editing host.\n let range: Range;\n if (current !== null && host.contains(current.commonAncestorContainer)) range = current.cloneRange();\n else {\n range = doc.createRange();\n range.selectNodeContents(host);\n range.collapse(false);\n }\n if (doc.activeElement !== host) host.focus();\n selection?.removeAllRanges();\n selection?.addRange(range);\n try {\n // The only way to keep the native undo stack. The HTML is sanitized: allowlisted elements and\n // attributes only, scheme-checked URLs, no styles, scripts or event handlers.\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- no replacement keeps undo history\n if (doc.activeElement === host && doc.execCommand('insertHTML', false, html)) return;\n } catch {\n // Fall through to the manual insertion.\n }\n range.deleteContents();\n // codeql[js/xss] Sanitized above: allowlisted elements and attributes, scheme-checked URLs.\n const fragment = range.createContextualFragment(html);\n // Never empty: an empty cleaning result is not inserted.\n const last = fragment.lastChild as Node;\n range.insertNode(fragment);\n range.setStartAfter(last);\n range.collapse(true);\n const view = doc.defaultView;\n host.dispatchEvent(\n view !== null && typeof view.InputEvent === 'function'\n ? new view.InputEvent('input', { bubbles: true, inputType: 'insertFromPaste' })\n : new Event('input', { bubbles: true }),\n );\n}\n\n/**\n * A paste handler for `contenteditable` elements: what is pasted from Google Docs, Word, mail or\n * a web page goes in as clean, semantic HTML (see {@link pasteToRich}), with undo intact. Plain-text\n * pastes are left to the browser. Returns whether it handled the paste.\n *\n * Rich-text editors (TipTap, ProseMirror, Lexical, Quill) have their own paste pipelines: use\n * {@link pasteToRich} in their hook instead, so the editor keeps its document model.\n *\n * @example\n * <div contentEditable onPaste={pasteAsRich} />\n * <div contentEditable onPaste={(event) => pasteAsRich(event, { formats: ['bold', 'italic', 'link', 'list'] })} />\n */\nexport function pasteAsRich(event: RichPasteEvent, options?: PasteAsRichOptions): boolean {\n if (event.defaultPrevented || event.clipboardData === null) return false;\n const host = editableHost(event);\n if (host === null) return false;\n const html = event.clipboardData.getData('text/html');\n if (html === '') return false;\n let pasted: RichPaste | null;\n try {\n pasted = pasteToRich({ 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 if (options?.onPaste?.(pasted) === false) return true;\n insertHtml(host, pasted.html);\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;AAOA,MAAa,uBAA4C,IAAI,IAAI;CAC/D;CAAK;CAAQ;CAAK;CAAO;CAAO;CAAc;CAAM;CAAW;CAAQ;CAAQ;CAAO;CAAY;CAAM;CAAO;CAAO;CAAO;CAAM;CACnI;CAAM;CAAc;CAAU;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAK;CAAO;CAAO;CAAO;CAAM;CAAQ;CAAM;CAAK;CAAO;CAAK;CACvI;CAAQ;CAAS;CAAQ;CAAU;CAAO;CAAO;CAAS;CAAS;CAAM;CAAS;CAAM;CAAS;CAAQ;CAAM;CAAK;CAAM;AAC5H,CAAC;;AAGD,MAAa,uBAA4C,IAAI,IAAI;CAC/D;CAAU;CAAS;CAAQ;CAAU;CAAU;CAAY;CAAU;CAAS;CAAS;CAAY;CAAQ;CAAU;CAAS;CAC9H;CAAO;CAAQ;CAAQ;CAAS;CAAW;CAAY;CAAY;CAAU;CAAU;CAAY;CAAU;CAAS;CACtH;CAAY;CAAU;CAAU;CAAQ;CAAU;CAAS;CAAO;CAAY;CAAY;CAAS;CAAS;AAC9G,CAAC;;AAGD,MAAa,2BAAgD,IAAI,IAAI;CACnE;CAAW;CAAW;CAAS;CAAQ;CAAU;CAAW;CAAY;CAAU;CAAQ;CAAU;CAAU;CAAQ;CACtH;CAAW;CAAQ;CAAQ;CAAO;CAAa;CAAU;CAAW;CAAW;AACjF,CAAC;;AAGD,MAAa,8BAAmD,IAAI,IAAI;CACtE;CAAc;CAAW;CAAM;CAAO;CAAM;CAAM;CAAc;CAAU;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAChI;CAAO;CAA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}
|
|
1
|
+
{"version":3,"file":"rich.js","names":["HEADINGS","rgb","positive","HEADINGS"],"sources":["../src/rich/policy.ts","../src/rich/style.ts","../src/rich/text.ts","../src/rich/walk.ts","../src/rich/payload.ts","../src/rich/paste.ts"],"sourcesContent":["/**\n * What portable rich text may contain: the elements, attributes and CSS that Gmail,\n * Outlook, Apple Mail, Google Docs, Word, Notion and Slack keep, and nothing that\n * can run, load or track. Everything not listed here is left out.\n */\n\n/** Elements written as they are. */\nexport const KEEP: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'a', 'abbr', 'b', 'bdi', 'bdo', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'div', 'dl', 'dt',\n 'em', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'ol', 'p', 'pre', 'q', 's',\n 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time', 'tr', 'u', 'ul', 'var',\n]);\n\n/** Elements left out with everything inside them: they run, load, embed, or are page chrome. */\nexport const DROP: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'applet', 'audio', 'base', 'button', 'canvas', 'datalist', 'dialog', 'embed', 'frame', 'frameset', 'head', 'iframe', 'input', 'link',\n 'map', 'math', 'meta', 'meter', 'noembed', 'noframes', 'noscript', 'object', 'option', 'optgroup', 'output', 'param', 'portal',\n 'progress', 'script', 'select', 'slot', 'source', 'style', 'svg', 'template', 'textarea', 'title', 'track', 'video',\n]);\n\n/** Elements that become a `<div>`: blocks without an email-safe equivalent. */\nexport const AS_BLOCK: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'address', 'article', 'aside', 'body', 'center', 'details', 'fieldset', 'footer', 'form', 'header', 'hgroup', 'html', 'legend',\n 'listing', 'main', 'menu', 'nav', 'plaintext', 'search', 'section', 'summary', 'xmp',\n]);\n\n/** Elements whose children are block-level text in the plain-text version. */\nexport const TEXT_BLOCKS: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'blockquote', 'caption', 'dd', 'div', 'dl', 'dt', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'li', 'ol', 'p',\n 'pre', 'table', 'tbody', 'tfoot', 'thead', 'tr', 'ul',\n]);\n\n/** What table parts may contain: anything else is moved out of the table by every HTML parser. */\nexport const TABLE_CHILDREN: Readonly<Record<string, ReadonlySet<string>>> = {\n table: /* @__PURE__ */ new Set(['caption', 'colgroup', 'thead', 'tbody', 'tfoot', 'tr']),\n thead: /* @__PURE__ */ new Set(['tr']),\n tbody: /* @__PURE__ */ new Set(['tr']),\n tfoot: /* @__PURE__ */ new Set(['tr']),\n tr: /* @__PURE__ */ new Set(['td', 'th']),\n colgroup: /* @__PURE__ */ new Set(['col']),\n};\n\n/** Elements that hold only text-level content: a block inside one would be split out by HTML parsers. */\nexport const PHRASING: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'a', 'abbr', 'b', 'bdi', 'bdo', 'cite', 'code', 'del', 'dfn', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'i', 'ins', 'kbd', 'mark', 'p', 'q',\n 's', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'time', 'u', 'var',\n]);\n\n/** Table parts: outside their own parent, HTML parsers ignore their tags. */\nexport const TABLE_PARTS: ReadonlySet<string> = /* @__PURE__ */ new Set(['caption', 'col', 'colgroup', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr']);\n\nexport const HEADINGS: ReadonlySet<string> = /* @__PURE__ */ new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n\n/** Elements whose start tag closes an open `<p>`: a paragraph holding one is split in two by HTML parsers. */\nexport const CLOSES_P: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'blockquote', 'dd', 'dl', 'dt', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'li', 'ol', 'p', 'pre', 'table', 'ul',\n]);\n\n/** Where HTML parsers stop looking for an open list item to close: their \"special\" elements, less address, div and p. */\nconst ITEM_SCOPE: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'blockquote', 'br', 'caption', 'col', 'colgroup', 'dd', 'dl', 'dt', 'figcaption', 'figure', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'img',\n 'li', 'ol', 'pre', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'ul',\n]);\n\n/** Whether a new `li` (or `dd`, `dt`) under `parent` would close an open one, as HTML parsers do with `<li>` in `<li>`. */\nexport function closesItem(name: 'li' | 'dd' | 'dt', parent: Node | null): boolean {\n const group = name === 'li' ? ['li'] : ['dd', 'dt'];\n for (let node = parent; node !== null && node.nodeType === 1; node = node.parentNode) {\n const tag = (node as Element).localName;\n if (group.includes(tag)) return true;\n if (ITEM_SCOPE.has(tag)) return false;\n }\n return false;\n}\n\nconst INTEGER = /^\\d{1,4}$/;\n\n/** Attributes kept per element (after `href` and `src`, which are checked as URLs). */\nexport function attributeAllowed(tag: string, name: string, value: string): boolean {\n switch (name) {\n case 'dir':\n return /^(?:ltr|rtl|auto)$/i.test(value);\n case 'lang':\n return /^[a-z]{2,3}(?:-[a-z\\d]{1,8})*$/i.test(value);\n case 'title':\n // Images write their own title, alt, size and source.\n return ['a', 'abbr', 'dfn'].includes(tag);\n case 'colspan':\n case 'rowspan':\n return (tag === 'td' || tag === 'th') && INTEGER.test(value) && Number(value) >= 1 && Number(value) <= 1000;\n case 'scope':\n return tag === 'th' && /^(?:row|col|rowgroup|colgroup)$/i.test(value);\n case 'span':\n return (tag === 'col' || tag === 'colgroup') && INTEGER.test(value);\n case 'start':\n return tag === 'ol' && /^-?\\d{1,9}$/.test(value);\n case 'reversed':\n return tag === 'ol';\n case 'type':\n return tag === 'ol' && /^[1aAiI]$/.test(value);\n case 'value':\n return tag === 'li' && /^-?\\d{1,9}$/.test(value);\n case 'datetime':\n return tag === 'time' && /^[\\d\\-:T.+ Z]{1,40}$/.test(value);\n default:\n return false;\n }\n}\n","import { contrastRatio } from '../color/contrast';\nimport { color as rgb, toGamut, type Color } from '../color/convert';\nimport { formatColor } from '../color/format';\nimport { parseColor } from '../color/parse';\n\n/** Where styles come from: `getComputedStyle` for a live element, the `style` attribute otherwise. */\nexport interface StyleSource {\n getPropertyValue(name: string): string;\n}\n\n/**\n * How colours are copied:\n * - `readable` (default): every colour, made opaque, except text that would be hard to\n * read where it lands (contrast under 3:1 on its background, or on white), such as\n * light text from a dark theme\n * - `keep`: every colour, made opaque\n * - `none`: no colours: the destination's own text colour and background\n */\nexport type RichColors = 'readable' | 'keep' | 'none';\n\nexport const INHERITED = ['color', 'font-family', 'font-size', 'font-style', 'font-weight', 'text-align', 'white-space', 'text-transform', 'list-style-type', 'border-collapse'] as const;\nconst SIDES = ['top', 'right', 'bottom', 'left'] as const;\nconst OWN = [\n 'background-color',\n 'text-decoration-line',\n 'vertical-align',\n 'border-top-width', 'border-top-style', 'border-top-color', 'padding-top',\n 'border-right-width', 'border-right-style', 'border-right-color', 'padding-right',\n 'border-bottom-width', 'border-bottom-style', 'border-bottom-color', 'padding-bottom',\n 'border-left-width', 'border-left-style', 'border-left-color', 'padding-left',\n] as const;\nexport const PROPERTIES: readonly [...typeof INHERITED, ...typeof OWN] = [...INHERITED, ...OWN] as const;\nexport type Property = (typeof PROPERTIES)[number];\nconst INHERITED_SET: ReadonlySet<Property> = /* @__PURE__ */ new Set<Property>(INHERITED);\n\n/**\n * What an element gets from its parent: the inherited values, with its own declared\n * ones on top. Lists set their own marker, as browsers' default styles do, so a list\n * doesn't inherit its parent list's marker.\n */\nexport function inherit(parent: Values, own?: Values, tag = ''): Values {\n const merged = {} as Record<Property, string>;\n for (const name of PROPERTIES) {\n const value = own === undefined ? '' : own[name];\n const inherits = INHERITED_SET.has(name) && !(name === 'list-style-type' && (tag === 'ul' || tag === 'ol'));\n merged[name] = value !== '' ? value : inherits ? parent[name] : '';\n }\n return merged;\n}\n\n/** Raw values of every property above, as the source reports them (`''` when unset), and the display type. */\nexport type Values = Readonly<Record<Property, string>> & { readonly display?: string };\n\nexport function readValues(source: StyleSource): Values {\n const values = {} as Record<Property, string>;\n for (const name of PROPERTIES) values[name] = source.getPropertyValue(name).trim().toLowerCase();\n return values;\n}\n\n/** Inherited values every rendering starts from: an empty parent for the root. */\nexport const ROOT_PARENT: Values = /* @__PURE__ */ Object.freeze({\n ...(Object.fromEntries(PROPERTIES.map((name) => [name, ''])) as Record<Property, string>),\n 'font-style': 'normal',\n 'font-weight': '400',\n 'text-align': 'start',\n 'white-space': 'normal',\n 'text-transform': 'none',\n 'border-collapse': 'separate',\n});\n\nconst KEYWORDS: Readonly<Record<string, RegExp>> = {\n 'font-style': /^(?:normal|italic|oblique)$/,\n 'text-align': /^(?:left|right|center|justify)$/,\n 'white-space': /^(?:normal|pre|pre-wrap|pre-line|nowrap|break-spaces)$/,\n 'text-transform': /^(?:none|uppercase|lowercase|capitalize)$/,\n 'list-style-type': /^(?:none|disc|circle|square|decimal|decimal-leading-zero|lower-alpha|upper-alpha|lower-latin|upper-latin|lower-roman|upper-roman|lower-greek)$/,\n 'border-collapse': /^(?:collapse|separate)$/,\n 'vertical-align': /^(?:top|bottom)$/,\n};\nconst LENGTH = /^(?:0|\\d{1,4}(?:\\.\\d+)?(?:px|pt|em|%))$/;\nconst FONT_FAMILY = /^[\\w\\s,'\"-]{1,200}$/;\n\n/** Elements whose default style already shows a value: writing it again adds nothing. */\nconst TAG_DEFAULTS: Readonly<Record<string, Readonly<Partial<Record<Property, string>>>>> = {\n b: { 'font-weight': '700' },\n strong: { 'font-weight': '700' },\n th: { 'font-weight': '700', 'text-align': 'center' },\n h1: { 'font-weight': '700' },\n h2: { 'font-weight': '700' },\n h3: { 'font-weight': '700' },\n h4: { 'font-weight': '700' },\n h5: { 'font-weight': '700' },\n h6: { 'font-weight': '700' },\n em: { 'font-style': 'italic' },\n i: { 'font-style': 'italic' },\n cite: { 'font-style': 'italic' },\n dfn: { 'font-style': 'italic' },\n var: { 'font-style': 'italic' },\n pre: { 'white-space': 'pre' },\n ol: { 'list-style-type': 'decimal' },\n ul: { 'list-style-type': 'disc' },\n li: { 'list-style-type': '' },\n a: { 'text-decoration-line': 'underline' },\n u: { 'text-decoration-line': 'underline' },\n ins: { 'text-decoration-line': 'underline' },\n s: { 'text-decoration-line': 'line-through' },\n del: { 'text-decoration-line': 'line-through' },\n};\n\nconst weight = (value: string): string => (value === 'bold' ? '700' : value === 'normal' ? '400' : /^[1-9]00$/.test(value) ? value : '');\n/** `start` and `end` as the left and right they mean in left-to-right text. */\nconst align = (value: string): string => {\n if (value === 'start') return 'left';\n if (value === 'end') return 'right';\n // Engines' internal names for the default centring of table headers.\n return value === '-webkit-center' || value === '-internal-center' || value === '-moz-center' ? 'center' : value;\n};\n\n/** A colour as an opaque hex value, drawn over `under`; `null` for none or invisible. */\nfunction opaque(value: string, under: Color): Color | null {\n const c = parseColor(value);\n if (c === null || c.alpha === 0) return null;\n const mapped = toGamut(c);\n const mix = (top: number, bottom: number) => top * c.alpha + bottom * (1 - c.alpha);\n return rgb(mix(mapped.r, under.r), mix(mapped.g, under.g), mix(mapped.b, under.b));\n}\n\nexport const WHITE: Color = /* @__PURE__ */ rgb(1, 1, 1);\n\n/** Pixel lengths rounded to 2 decimals; other units kept as written. */\nfunction length(value: string): string | null {\n if (!LENGTH.test(value)) return null;\n return value.endsWith('px') ? `${String(Math.round(parseFloat(value) * 100) / 100)}px` : value;\n}\n\nexport interface StyleResult {\n /** The `style` attribute to write, or `''`. */\n readonly css: string;\n /** The background the element's content is drawn on, for its children's contrast checks. */\n readonly background: Color;\n /** Whether a text colour was left out to stay readable. */\n readonly droppedColor: boolean;\n}\n\n/**\n * The declarations to write for an element: inherited properties where they differ\n * from the parent (all of them at the root), and the element's own box and decoration.\n */\nexport function declarations(tag: string, values: Values, parent: Values, background: Color, colors: RichColors): StyleResult {\n const out: string[] = [];\n const defaults = TAG_DEFAULTS[tag] ?? {};\n const changed = (name: Property, value: string) => value !== '' && value !== parent[name] && value !== defaults[name];\n let droppedColor = false;\n let own = background;\n\n // Background first: the text colour's contrast is checked against it.\n if (colors !== 'none') {\n const bg = opaque(values['background-color'], background);\n if (bg !== null) {\n own = bg;\n out.push(`background-color:${formatColor(bg)}`);\n }\n }\n const family = values['font-family'];\n if (changed('font-family', family) && FONT_FAMILY.test(family)) out.push(`font-family:${family}`);\n const size = length(values['font-size']);\n if (size !== null && changed('font-size', values['font-size'])) out.push(`font-size:${size}`);\n const fontWeight = weight(values['font-weight']);\n if (fontWeight !== weight(parent['font-weight']) && changed('font-weight', fontWeight)) out.push(`font-weight:${fontWeight}`);\n for (const name of ['font-style', 'white-space', 'text-transform', 'border-collapse'] as const) {\n const value = values[name];\n if (changed(name, value) && (KEYWORDS[name] as RegExp).test(value)) out.push(`${name}:${value}`);\n }\n const textAlign = align(values['text-align']);\n if (textAlign !== align(parent['text-align']) && textAlign !== defaults['text-align'] && (KEYWORDS['text-align'] as RegExp).test(textAlign)) {\n out.push(`text-align:${textAlign}`);\n }\n if (tag === 'ul' || tag === 'ol') {\n const list = values['list-style-type'];\n if (list !== defaults['list-style-type'] && list !== 'circle' && list !== 'square' && (KEYWORDS['list-style-type'] as RegExp).test(list)) out.push(`list-style-type:${list}`);\n }\n if (colors !== 'none' && changed('color', values['color'])) {\n const text = opaque(values['color'], own);\n if (text !== null) {\n if (colors === 'readable' && contrastRatio(text, own) < 3) droppedColor = true;\n else out.push(`color:${formatColor(text)}`);\n }\n }\n const decoration = values['text-decoration-line'];\n if (decoration !== '' && decoration !== defaults['text-decoration-line'] && /^(?:none|(?:underline|overline|line-through)(?: (?:underline|overline|line-through))*)$/.test(decoration)) {\n // Links are underlined by default in mail: a link drawn without one says so.\n if (decoration !== 'none' || tag === 'a') out.push(`text-decoration:${decoration}`);\n }\n const vertical = values['vertical-align'];\n if ((tag === 'td' || tag === 'th') && (KEYWORDS['vertical-align'] as RegExp).test(vertical)) out.push(`vertical-align:${vertical}`);\n out.push(...box(values, own, colors));\n return { css: out.join(';'), background: own, droppedColor };\n}\n\n/** Borders and padding, as shorthands where every side is the same. */\nfunction box(values: Values, background: Color, colors: RichColors): string[] {\n const borders = SIDES.map((side) => {\n const width = length(values[`border-${side}-width`]);\n const style = values[`border-${side}-style`];\n if (width === null || width === '0' || width === '0px' || !/^(?:solid|dashed|dotted|double)$/.test(style)) return null;\n const lineColor = colors === 'none' ? null : opaque(values[`border-${side}-color`], background);\n return `${width} ${style}${lineColor === null ? '' : ` ${formatColor(lineColor)}`}`;\n });\n const out: string[] = [];\n if (borders.every((border) => border !== null && border === borders[0])) out.push(`border:${borders[0] as string}`);\n else borders.forEach((border, index) => {\n if (border !== null) out.push(`border-${SIDES[index] as string}:${border}`);\n });\n const padding = SIDES.map((side) => length(values[`padding-${side}`]) ?? '0');\n if (padding.some((value) => value !== '0' && value !== '0px')) {\n out.push(`padding:${padding.map((value) => (value === '0px' ? '0' : value)).join(' ')}`);\n }\n return out;\n}\n","import { TEXT_BLOCKS } from './policy';\n\n/**\n * Readable plain text for sanitized rich content: blocks on their own lines, list\n * items with bullets or numbers (indented when nested), table cells separated by tabs,\n * images by their alt text, and preformatted text as it is.\n */\nexport function plainText(root: HTMLElement): string {\n const lines: string[] = [];\n let line = '';\n const flush = () => {\n const trimmed = line.replace(/[ \\t\\u00A0]+$/, '');\n if (trimmed !== '' || (lines.length > 0 && lines[lines.length - 1] !== '')) lines.push(trimmed);\n line = '';\n };\n const breakBlock = () => {\n if (line.trim() !== '') flush();\n else line = '';\n };\n\n const walk = (node: Node, pre: boolean, depth: number): void => {\n if (node.nodeType === 3) {\n const data = (node as Text).data;\n if (pre) line += data.replace(/\\r\\n?/g, '\\n');\n else {\n // Whitespace collapses across text nodes too, as it does when a browser renders it.\n const collapsed = data.replace(/\\s+/g, ' ');\n // A space at the start of a line or a cell shows nothing.\n line += /(?:^|[ \\t])$/.test(line) && collapsed.startsWith(' ') ? collapsed.slice(1) : collapsed;\n }\n if (pre && line.includes('\\n')) {\n const parts = line.split('\\n');\n line = parts.pop() as string;\n for (const part of parts) lines.push(part);\n }\n if (!pre && line.trimStart() === '') line = '';\n return;\n }\n if (node.nodeType !== 1) return;\n const element = node as HTMLElement;\n const tag = element.localName;\n switch (tag) {\n case 'br':\n flush();\n return;\n case 'img':\n line += element.getAttribute('alt') ?? '';\n return;\n case 'hr':\n breakBlock();\n lines.push('\\u2014'.repeat(3));\n return;\n case 'td':\n case 'th':\n if (element.previousElementSibling !== null) line += '\\t';\n element.childNodes.forEach((child) => {\n walk(child, pre, depth);\n });\n return;\n case 'li': {\n breakBlock();\n const list = element.parentElement;\n const ordered = list?.localName === 'ol';\n let marker = '\\u2022';\n if (ordered) {\n const items = Array.from(list.children).filter((child) => child.localName === 'li');\n const start = Number(list.getAttribute('start') ?? '1');\n const own = element.getAttribute('value');\n marker = `${String(own === null ? start + items.indexOf(element) : Number(own))}.`;\n }\n line = `${' '.repeat(Math.max(0, depth - 1))}${marker} `;\n element.childNodes.forEach((child) => {\n walk(child, pre, depth);\n });\n breakBlock();\n return;\n }\n default: {\n const block = TEXT_BLOCKS.has(tag);\n const list = tag === 'ul' || tag === 'ol';\n if (block) breakBlock();\n const keep = pre || tag === 'pre' || /white-space:\\s*pre/.test(element.getAttribute('style') ?? '');\n element.childNodes.forEach((child) => {\n walk(child, keep, list ? depth + 1 : depth);\n });\n if (block) breakBlock();\n }\n }\n };\n walk(root, false, 0);\n flush();\n return lines\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n}\n","import type { Color } from '../color/convert';\nimport { copyFailure } from '../core/errors';\nimport { linkUrlResolver, type LinkUrlOptions } from '../link/url';\nimport { AS_BLOCK, attributeAllowed, closesItem, CLOSES_P, DROP, HEADINGS, KEEP, PHRASING, TABLE_CHILDREN, TABLE_PARTS } from './policy';\nimport { parseColor } from '../color/parse';\nimport { declarations, inherit, readValues, ROOT_PARENT, WHITE, type RichColors, type StyleSource, type Values } from './style';\nimport { plainText } from './text';\nimport { parseInertHtml } from '../core/inert-html';\n\nexport interface RichOptions extends Pick<LinkUrlOptions, 'protocols'> {\n /** Resolves relative links and images. Default: the source document's address. */\n readonly base?: string | URL;\n /** Default `\"readable\"`. See {@link RichColors}. */\n readonly colors?: RichColors;\n /**\n * Images: `\"keep\"` (default) with absolute `https:` and `http:` addresses and their\n * displayed size; `\"alt\"` writes their alt text instead; `\"drop\"` leaves them out.\n */\n readonly images?: 'keep' | 'alt' | 'drop';\n /** Also keep `data:` images (PNG, JPEG, GIF, WebP, up to 2 MB each). Many mail clients block them. Default `false`. */\n readonly dataImages?: boolean;\n /**\n * Where styles come from: `\"computed\"` (default for elements and selections on the\n * page: what the reader sees), `\"inline\"` (only `style` attributes: the default for\n * HTML strings and detached nodes), or `\"none\"`.\n */\n readonly styles?: 'computed' | 'inline' | 'none';\n /** More elements to leave out, as a CSS selector. `[data-copy-ignore]`, `[hidden]` and `[aria-hidden=\"true\"]` always are. */\n readonly ignore?: string;\n /** The background the content is pasted on, for readability checks. Default `\"#ffffff\"`. */\n readonly background?: string;\n /** Most elements written; the rest is left out and `truncated` is set. Default 10,000. */\n readonly maxElements?: number;\n /** Most characters of HTML written, roughly. Default 1,000,000. */\n readonly maxLength?: number;\n /** The plain-text version. Default: readable text with lists, tables and line breaks. Pass `htmlToMarkdown` for Markdown. */\n readonly text?: (root: HTMLElement) => string;\n /** Reads an element's computed style. Default `getComputedStyle`; set it for DOMs that lack one. */\n readonly computedStyle?: (element: Element) => StyleSource | null;\n}\n\n/**\n * Why something was left out: `unsafe-element` (scripts, embeds, forms, SVG, media),\n * `hidden`, `ignored`, `unsafe-link`, `unsafe-image`, `image` (by the `images` option),\n * `unreadable-color` (by `colors: \"readable\"`), or `misplaced` (content a table can't\n * hold where it is, which every HTML parser would move out of the table).\n */\nexport type RichRemovalReason = 'unsafe-element' | 'hidden' | 'ignored' | 'unsafe-link' | 'unsafe-image' | 'image' | 'unreadable-color' | 'misplaced';\n\nexport interface RichRemoval {\n readonly reason: RichRemovalReason;\n /** The element name, or the URL scheme for links and images. */\n readonly name: string;\n readonly count: number;\n}\n\nexport interface RichResult {\n /** Portable HTML: allowlisted elements and attributes, inline styles, absolute URLs. */\n readonly html: string;\n /** The same content as plain text. */\n readonly text: string;\n /** What was left out, and why: for logs and audits. */\n readonly removed: readonly RichRemoval[];\n /** The content went past `maxElements` or `maxLength` and was cut there. */\n readonly truncated: boolean;\n}\n\n/** What can be copied: an element, a selection range, a fragment, or HTML text. */\nexport type RichSource = Element | DocumentFragment | Range | string;\n\nconst VOID = new Set(['br', 'hr', 'img', 'col']);\nconst BLOCK_DISPLAY = /^(?:block|flex|grid|flow-root|list-item|table)$/;\nconst DATA_IMAGE = /^data:image\\/(?:png|jpeg|gif|webp);base64,[a-z\\d+/]+=*$/i;\n\nfunction positive(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (Number.isInteger(value) && value > 0) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer.`);\n}\n\n/** Whether `source` holds an element that would close a paragraph around it. */\nfunction holdsBlocks(source: Element): boolean {\n for (let child = source.firstElementChild; child !== null; child = child.nextElementSibling) {\n if (CLOSES_P.has(child.localName) || holdsBlocks(child)) return true;\n }\n return false;\n}\n\n/** Whether `node` is (inside) a link in the output. */\nfunction insideLink(node: Node | null): boolean {\n for (let current = node; current !== null; current = current.parentNode) if ((current as Element).localName === 'a') return true;\n return false;\n}\n\nconst isRange = (value: unknown): value is Range =>\n typeof value === 'object' && value !== null && 'commonAncestorContainer' in value && typeof (value as Range).intersectsNode === 'function';\n\nclass Builder {\n readonly removals = new Map<string, RichRemoval>();\n truncated = false;\n private elements = 0;\n private size = 0;\n /** Table parts added around misplaced cells and rows, which later cells and rows share. */\n private readonly implied = new WeakSet<Node>();\n private readonly resolveLink: (url: string) => string;\n private readonly resolveImage: (url: string) => string;\n\n constructor(\n readonly out: Document,\n private readonly options: RichOptions,\n private readonly mode: 'computed' | 'inline' | 'none',\n private readonly computed: (element: Element) => StyleSource | null,\n private readonly colors: RichColors,\n private readonly ignore: string | null,\n private readonly maxElements: number,\n private readonly maxLength: number,\n base: string | URL | undefined,\n ) {\n const baseOption = base === undefined ? {} : { base };\n this.resolveLink = linkUrlResolver({ ...baseOption, ...(options.protocols === undefined ? {} : { protocols: options.protocols }) });\n this.resolveImage = linkUrlResolver({ ...baseOption, protocols: options.dataImages === true ? ['https:', 'http:', 'data:'] : ['https:', 'http:'] });\n }\n\n remove(reason: RichRemovalReason, name: string): void {\n const key = `${reason} ${name}`;\n const known = this.removals.get(key);\n this.removals.set(key, { reason, name, count: (known?.count ?? 0) + 1 });\n }\n\n /** The style values to use for an element, or `null` when it is hidden. */\n private values(element: Element, parent: Values): Values | null {\n if (this.mode === 'computed') {\n const style = this.computed(element);\n if (style === null) return inherit(parent, undefined, element.localName);\n const display = style.getPropertyValue('display').trim();\n const visibility = style.getPropertyValue('visibility').trim();\n if (display === 'none' || visibility === 'hidden' || visibility === 'collapse') return null;\n return { ...readValues(style), display };\n }\n const declared = (element as Partial<HTMLElement>).style;\n if (declared?.getPropertyValue('display').trim() === 'none') return null;\n // Declared values on top of the inherited ones, as the browser would compute them.\n const tag = element.localName;\n return this.mode === 'none' || declared === undefined ? inherit(parent, undefined, tag) : inherit(parent, readValues(declared), tag);\n }\n\n private url(raw: string | null, resolve: (url: string) => string): string | null {\n if (raw === null || raw.trim() === '') return null;\n try {\n return resolve(raw);\n } catch {\n return null;\n }\n }\n\n private budget(cost: number): boolean {\n if (this.elements >= this.maxElements || this.size + cost > this.maxLength) {\n this.truncated = true;\n return false;\n }\n this.size += cost;\n return true;\n }\n\n /** A URL's scheme for reports, read as the URL parser reads it: tabs and line breaks inside it don't count. */\n private scheme = (raw: string | null): string => /^\\s*([a-z][a-z\\d+.-]*):/i.exec((raw ?? '').replace(/[\\t\\n\\r]/g, ''))?.[1]?.toLowerCase() ?? 'relative';\n\n /** Converts `source` into `parent`, keeping only what lies inside `range` when given. */\n node(source: Node, parent: Node, inherited: Values, background: Color, range: Range | null, root = false): void {\n if (source.nodeType === 3) {\n let text = (source as Text).data;\n if (range !== null) {\n const end = source === range.endContainer ? range.endOffset : text.length;\n text = text.slice(source === range.startContainer ? range.startOffset : 0, end);\n }\n if (TABLE_CHILDREN[(parent as Element).localName] !== undefined && text.trim() !== '') {\n this.remove('misplaced', '#text');\n return;\n }\n if (text !== '' && this.budget(text.length)) parent.appendChild(this.out.createTextNode(text));\n return;\n }\n if (source.nodeType === 11 || source.nodeType === 9) {\n this.children(source, parent, inherited, background, range);\n return;\n }\n if (source.nodeType !== 1) return;\n this.element(source as Element, parent, inherited, background, range, root);\n }\n\n children(source: Node, parent: Node, inherited: Values, background: Color, range: Range | null): void {\n for (let child = source.firstChild; child !== null && !this.truncated; child = child.nextSibling) {\n if (range === null || range.intersectsNode(child)) this.node(child, parent, inherited, background, range);\n }\n }\n\n private element(source: Element, parent: Node, inherited: Values, background: Color, range: Range | null, root: boolean): void {\n const tag = source.localName.toLowerCase();\n if (DROP.has(tag) || source.namespaceURI !== 'http://www.w3.org/1999/xhtml') {\n this.remove('unsafe-element', tag);\n return;\n }\n // Attribute checks, not a selector: selector engines are slow to start in DOMs like jsdom.\n if (\n source.hasAttribute('data-copy-ignore') ||\n source.hasAttribute('hidden') ||\n source.getAttribute('aria-hidden') === 'true' ||\n (this.ignore !== null && source.matches(this.ignore))\n ) {\n this.remove('ignored', tag);\n return;\n }\n let values = this.values(source, inherited);\n if (values === null) {\n this.remove('hidden', tag);\n return;\n }\n // A selection's container is page chrome: only its inherited text style is kept.\n if (root && range !== null) values = { ...values, 'background-color': '', 'border-top-style': '', 'border-right-style': '', 'border-bottom-style': '', 'border-left-style': '', 'padding-top': '', 'padding-right': '', 'padding-bottom': '', 'padding-left': '' };\n if (tag === 'img') {\n this.image(source as HTMLImageElement, parent);\n return;\n }\n let name = KEEP.has(tag) ? tag : AS_BLOCK.has(tag) || BLOCK_DISPLAY.test(values.display ?? '') ? 'div' : 'span';\n let href: string | null = null;\n if (tag === 'a') {\n const raw = source.getAttribute('href');\n href = this.url(raw, this.resolveLink);\n if (href === null) {\n if (raw !== null && raw.trim() !== '') this.remove('unsafe-link', this.scheme(raw));\n name = 'span';\n }\n }\n let target = parent;\n let parentTag = (parent as Element).localName;\n // Outside a table, HTML parsers ignore table tags: a selection inside a table gets its table, anything else is a block.\n if (TABLE_PARTS.has(name) && TABLE_CHILDREN[parentTag] === undefined) {\n if (root) {\n target = parent.appendChild(this.out.createElement('table'));\n parentTag = 'table';\n } else if (name === 'col') {\n this.remove('misplaced', tag);\n return;\n } else name = 'div';\n }\n // The table parts that HTML parsers add around cells, rows and columns.\n const implied: string[] = [];\n if (parentTag === 'table' && (name === 'tr' || name === 'td' || name === 'th')) implied.push('tbody');\n if ((name === 'td' || name === 'th') && (implied.length > 0 || parentTag === 'tbody' || parentTag === 'thead' || parentTag === 'tfoot')) implied.push('tr');\n if (parentTag === 'table' && name === 'col') implied.push('colgroup');\n // A table part can hold only its own parts: anything else is left out, not moved around.\n const allowed = TABLE_CHILDREN[implied.at(-1) ?? parentTag];\n if (allowed !== undefined && !allowed.has(name)) {\n this.remove('misplaced', tag);\n return;\n }\n // What HTML parsers would split apart: a paragraph around blocks, a heading in a heading, a list item in a list item.\n if (name === 'p' && holdsBlocks(source)) name = 'div';\n if (HEADINGS.has(name) && HEADINGS.has(parentTag)) name = 'span';\n if ((name === 'li' || name === 'dd' || name === 'dt') && closesItem(name, parent)) name = 'div';\n // Inside text-level content, a block becomes inline and a link inside a link loses its link.\n if (name === 'div' && PHRASING.has(parentTag)) name = 'span';\n if (name === 'a' && insideLink(parent)) name = 'span';\n if (!this.budget(name.length * 2 + 5)) return;\n for (const wrapper of implied) {\n const last = (target as Element).lastElementChild;\n target = last !== null && this.implied.has(last) && last.localName === wrapper ? last : target.appendChild(this.out.createElement(wrapper));\n this.implied.add(target);\n }\n this.elements += 1;\n const out = this.out.createElement(name);\n if (href !== null && name === 'a') out.setAttribute('href', href);\n for (const attribute of Array.from(source.attributes)) {\n const key = attribute.name.toLowerCase();\n if (name === tag && attributeAllowed(tag, key, attribute.value)) out.setAttribute(key, attribute.value);\n }\n const style = declarations(name, values, root ? ROOT_PARENT : inherited, background, this.colors);\n if (style.droppedColor) this.remove('unreadable-color', tag);\n if (style.css !== '' && this.budget(style.css.length)) out.setAttribute('style', style.css);\n target.appendChild(out);\n if (!VOID.has(name)) this.children(source, out, values, style.background, range);\n }\n\n private image(source: HTMLImageElement, parent: Node): void {\n const alt = source.getAttribute('alt') ?? '';\n const policy = this.options.images ?? 'keep';\n if (policy === 'drop') {\n this.remove('image', 'img');\n return;\n }\n const raw = this.mode === 'computed' && source.currentSrc !== '' ? source.currentSrc : source.getAttribute('src');\n const src = policy === 'keep' ? this.url(raw, this.resolveImage) : null;\n const safe = src !== null && (!src.startsWith('data:') || (DATA_IMAGE.test(src) && src.length <= 2_000_000));\n if (!safe) {\n this.remove(policy === 'keep' ? 'unsafe-image' : 'image', policy === 'keep' ? this.scheme(raw) : 'img');\n if (alt !== '' && this.budget(alt.length)) parent.appendChild(this.out.createTextNode(alt));\n return;\n }\n if (!this.budget(src.length + alt.length + 40)) return;\n this.elements += 1;\n const out = this.out.createElement('img');\n out.setAttribute('src', src);\n if (alt !== '') out.setAttribute('alt', alt);\n // Mail clients size images by their attributes: write the displayed size.\n for (const side of ['width', 'height'] as const) {\n const shown = this.mode === 'computed' ? Math.round(source[side]) : NaN;\n const declared = source.getAttribute(side) ?? '';\n const value = shown > 0 ? String(shown) : /^\\d{1,5}$/.test(declared) ? declared : '';\n if (value !== '') out.setAttribute(side, value);\n }\n const title = source.getAttribute('title');\n if (title !== null) out.setAttribute('title', title);\n parent.appendChild(out);\n }\n}\n\n/** The DOM document to read and write with, or a typed error outside a browser. */\nfunction domFor(source: RichSource): { readonly doc: Document; readonly root: Node; readonly range: Range | null; readonly live: boolean } {\n if (typeof source === 'string') {\n if (typeof DOMParser === 'undefined') throw copyFailure('unsupported', 'Reading HTML text needs a DOM (DOMParser); pass a DOM node, or use a browser or jsdom.');\n // Inert: scripts never run and nothing is fetched. In standards mode, as pages and mail clients\n // read HTML (not quirks mode, which keeps a table inside a paragraph).\n const doc = parseInertHtml(`<!doctype html><body>${source}`);\n return { doc, root: doc.body, range: null, live: false };\n }\n if (isRange(source)) {\n const container = source.commonAncestorContainer;\n const element = container.nodeType === 1 ? container : container.parentNode;\n if (element === null || container.ownerDocument === null) throw copyFailure('invalid-payload', 'The range is not in a document.');\n return { doc: container.ownerDocument, root: element, range: source, live: container.isConnected };\n }\n const value: unknown = source;\n if (typeof value !== 'object' || value === null || !('nodeType' in value) || ((value as Node).nodeType !== 1 && (value as Node).nodeType !== 11)) {\n throw copyFailure('invalid-payload', 'Rich content must be an element, a fragment, a range or HTML text.');\n }\n const node = value as Node;\n return { doc: node.ownerDocument as Document, root: node, range: null, live: node.isConnected };\n}\n\n/**\n * Converts content into portable rich text: the HTML that mail clients, Google Docs,\n * Word, Notion and Slack paste as it looks, plus a plain-text version.\n *\n * - Only safe, widely supported elements and attributes are kept: never scripts,\n * event handlers, embeds, forms or tracking pixels from `data:` or `blob:` URLs.\n * - Styles are inline, from what the reader sees (computed styles) for content on\n * the page. Classes, stylesheets and CSS variables can't travel; their result can.\n * - Every colour becomes an opaque hex value, which every mail client understands\n * (not `oklch()` or `rgb(r g b / 50%)`). Text that would be unreadable on a white\n * page, such as light text from a dark theme, keeps the destination's colour.\n * - Links and images get absolute, scheme-checked URLs; images get their displayed size.\n *\n * Never inserts anything into the page: the output is built in a separate, inert document.\n *\n * @example\n * const { html, text, removed } = prepareRich(articleRef.current);\n */\nexport function prepareRich(source: RichSource, options: RichOptions = {}): RichResult {\n const { doc, root, range, live } = domFor(source);\n // Computed styles need content on a page with a window; anything else has only its style attributes.\n const mode = options.styles ?? (live && doc.defaultView !== null ? 'computed' : 'inline');\n const modeValue: unknown = mode; // Plain-JS callers can pass anything.\n if (modeValue !== 'computed' && modeValue !== 'inline' && modeValue !== 'none') throw copyFailure('invalid-payload', '`styles` must be \"computed\", \"inline\" or \"none\".');\n const colors = options.colors ?? 'readable';\n const colorsValue: unknown = colors;\n if (colorsValue !== 'readable' && colorsValue !== 'keep' && colorsValue !== 'none') throw copyFailure('invalid-payload', '`colors` must be \"readable\", \"keep\" or \"none\".');\n const images: unknown = options.images ?? 'keep';\n if (images !== 'keep' && images !== 'alt' && images !== 'drop') throw copyFailure('invalid-payload', '`images` must be \"keep\", \"alt\" or \"drop\".');\n const view = doc.defaultView;\n const computed = options.computedStyle ?? ((element: Element) => (view === null ? null : view.getComputedStyle(element)));\n const page = options.background === undefined ? WHITE : declarationsBackground(options.background);\n if (options.ignore !== undefined) {\n // An invalid selector is a programming error: it throws a typed error here, not mid-copy.\n try {\n doc.createElement('div').matches(options.ignore);\n } catch (cause) {\n throw copyFailure('invalid-payload', `\\`ignore\\` is not a valid CSS selector: ${options.ignore}`, cause);\n }\n }\n const out = doc.implementation.createHTMLDocument('');\n const builder = new Builder(\n out,\n options,\n mode,\n computed,\n colors,\n options.ignore ?? null,\n positive(options.maxElements, 10_000, 'maxElements'),\n positive(options.maxLength, 1_000_000, 'maxLength'),\n options.base ?? (doc.baseURI === 'about:blank' ? undefined : doc.baseURI),\n );\n const container = out.createElement('div');\n // HTML text is its body's content; anything else is converted with its root element.\n if (typeof source === 'string') builder.children(root, container, ROOT_PARENT, page, null);\n else builder.node(root, container, ROOT_PARENT, page, range, true);\n // Left-out nodes can leave text in pieces: join them, as reading the HTML back would.\n container.normalize();\n const text = (options.text ?? plainText)(container);\n if (typeof text !== 'string') throw copyFailure('invalid-payload', '`text` must return a string.');\n // Whitespace at the very edges shows nothing, and HTML parsers drop it when reading the copy.\n const first = container.firstChild;\n if (first?.nodeType === 3) (first as Text).data = (first as Text).data.replace(/^\\s+/, '');\n const last = container.lastChild;\n if (last?.nodeType === 3) (last as Text).data = (last as Text).data.replace(/\\s+$/, '');\n // Only whitespace is no content: nothing to copy.\n const empty = container.textContent.trim() === '' && container.querySelector('img, br, hr') === null;\n return { html: empty ? '' : container.innerHTML, text: empty ? '' : text, removed: [...builder.removals.values()], truncated: builder.truncated };\n}\n\n/** The destination background as an opaque colour; a typed error for anything else. */\nfunction declarationsBackground(value: string): Color {\n const parsed: Color | null = typeof value === 'string' ? parseColor(value) : null;\n if (parsed === null || parsed.alpha !== 1) throw copyFailure('invalid-payload', '`background` must be an opaque CSS colour.');\n return parsed;\n}\n","import type { CopyInterceptTransform, CopySelection, SyncCopyPayload } from '../core/copy-interceptor';\nimport { copyFailure } from '../core/errors';\nimport type { HtmlPayload } from '../core/payload';\nimport { prepareRich, type RichOptions, type RichSource } from './walk';\n\n/**\n * Content to copy as portable rich text: the sanitized HTML, and its plain text for\n * editors and plain fields. A typed `invalid-payload` error when nothing is left to copy.\n *\n * @example\n * const { copy } = useCopy();\n * <button onClick={() => copy(() => richPayload(noteRef.current))}>Copy note</button>\n */\nexport function richPayload(source: RichSource, options: RichOptions = {}): HtmlPayload {\n const { html, text } = prepareRich(source, options);\n if (html === '' || text === '') throw copyFailure('invalid-payload', 'There is nothing to copy: the content is empty, hidden or entirely left out.');\n return { kind: 'html', html, text };\n}\n\n/**\n * A copy interceptor transform that makes Ctrl/Cmd+C (and cut) of a selection in your\n * page portable: what the reader selected, with the styles they see, sanitized. The\n * plain text stays the browser's own. Selections in text fields are left alone.\n *\n * @example\n * useCopyInterceptor(articleRef, { transform: richTransform() });\n */\nexport function richTransform(options: RichOptions = {}): CopyInterceptTransform {\n return (selection: CopySelection): SyncCopyPayload | undefined => {\n if (selection.field !== null || typeof document === 'undefined') return undefined;\n const live = document.getSelection();\n if (live === null || live.rangeCount === 0) return undefined;\n const parts: string[] = [];\n for (let index = 0; index < live.rangeCount; index += 1) {\n const { html, text } = prepareRich(live.getRangeAt(index), options);\n // Nothing visible left (only scripts or hidden content, say): not worth a paste.\n if (text !== '' || html.includes('<img')) parts.push(html);\n }\n const html = parts.join('');\n return html === '' ? undefined : { kind: 'html', html, text: selection.text };\n };\n}\n","import { copyFailure } from '../core/errors';\nimport { linkUrlResolver } from '../link/url';\nimport { unwrapRedirect } from '../markdown/url';\nimport { DROP } from './policy';\nimport { prepareRich, type RichOptions, type RichRemoval, type RichRemovalReason, type RichResult } from './walk';\nimport { parseInertHtml } from '../core/inert-html';\n\n/**\n * What a destination can hold. A format left out of `formats` is written as the closest thing\n * that is allowed, and its text is always kept:\n *\n * - `bold`, `italic`, `underline`, `strike`, `code`, `superscript`, `subscript`: the text, unformatted.\n * - `link`: the link text. `image`: the image's alt text.\n * - `heading`: a paragraph, in bold when `bold` is allowed.\n * - `list`: a paragraph per item, after its marker (`\\u2022`, `1.`).\n * - `quote`: its paragraphs. `table`: a paragraph per cell, in reading order.\n * - `codeBlock`: a paragraph per line, as inline code when `code` is allowed.\n * - `rule`: nothing.\n */\nexport type RichPasteFormat =\n | 'bold'\n | 'italic'\n | 'underline'\n | 'strike'\n | 'code'\n | 'superscript'\n | 'subscript'\n | 'link'\n | 'image'\n | 'heading'\n | 'list'\n | 'quote'\n | 'codeBlock'\n | 'table'\n | 'rule';\n\n/** Every format, in the order the docs list them. */\nexport const RICH_PASTE_FORMATS: readonly RichPasteFormat[] = [\n 'bold', 'italic', 'underline', 'strike', 'code', 'superscript', 'subscript', 'link', 'image',\n 'heading', 'list', 'quote', 'codeBlock', 'table', 'rule',\n];\n\nexport interface PasteToRichOptions extends Pick<RichOptions, 'protocols' | 'dataImages' | 'maxElements' | 'maxLength' | 'text'> {\n /**\n * What the destination can hold, such as an editor's schema or a comment box's toolbar.\n * Default: every format. See {@link RichPasteFormat} for what happens to the rest.\n */\n readonly formats?: readonly RichPasteFormat[];\n /**\n * Resolves relative links and images, when you know where the content was copied from\n * (your own site, say). Default: none, so relative links keep only their text: a pasted\n * `/docs` would otherwise point into your site, not the one it came from.\n */\n readonly base?: string | URL;\n /** Most nodes of the pasted HTML read; the rest is left out and `truncated` is set. Default 200,000. */\n readonly maxNodes?: number;\n}\n\n/** Cleaned rich content: semantic HTML, its plain text, and what was left out. */\nexport interface RichPaste extends RichResult {\n /** `html` when cleaned from the rich flavour; `text` when built from plain text (paragraphs and line breaks). */\n readonly source: 'html' | 'text';\n}\n\n/** The clipboard flavours: a `PasteResult` from `usePaste`, or anything with `html` / `text`. */\nexport interface RichPasteSource {\n readonly html?: string | null;\n readonly text?: string | null;\n}\n\n/* ---------------------------------------------------------------- Inline */\n\nconst STRONG = 1;\nconst EM = 2;\nconst UNDERLINE = 4;\nconst STRIKE = 8;\nconst CODE = 16;\nconst SUP = 32;\nconst SUB = 64;\n\n/** Inline formats, outermost first: the fixed order makes the output canonical. */\nconst INLINE: readonly (readonly [bit: number, tag: string, format: RichPasteFormat])[] = [\n [STRONG, 'strong', 'bold'],\n [EM, 'em', 'italic'],\n [UNDERLINE, 'u', 'underline'],\n [STRIKE, 's', 'strike'],\n [CODE, 'code', 'code'],\n [SUP, 'sup', 'superscript'],\n [SUB, 'sub', 'subscript'],\n];\n\nconst TAG_BITS: Readonly<Record<string, number>> = {\n b: STRONG, strong: STRONG,\n i: EM, em: EM, cite: EM, dfn: EM, var: EM,\n u: UNDERLINE, ins: UNDERLINE,\n s: STRIKE, strike: STRIKE, del: STRIKE,\n code: CODE, kbd: CODE, samp: CODE, tt: CODE,\n sup: SUP, sub: SUB,\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\ntype Run =\n | { readonly kind: 'text'; readonly text: string; readonly bits: number; readonly href: string | null }\n | { readonly kind: 'break'; readonly bits: number; readonly href: string | null }\n | { readonly kind: 'image'; readonly image: Element; readonly bits: number; readonly href: string | null };\n\n/** Inline CSS, lower-cased. */\nfunction styleOf(element: Element): ReadonlyMap<string, string> {\n const map = new Map<string, string>();\n for (const declaration of (element.getAttribute('style') ?? '').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\n/** Formats after this element: its tag first, then its inline CSS, which wins (Google Docs, Word). */\nfunction bitsOf(bits: number, tag: string, style: ReadonlyMap<string, string>): number {\n let next = bits | (TAG_BITS[tag] ?? 0);\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 !== undefined) {\n if (decoration.includes('underline')) next |= UNDERLINE;\n if (decoration.includes('line-through')) next |= STRIKE;\n if (decoration === 'none') next &= ~(UNDERLINE | STRIKE);\n }\n const vertical = style.get('vertical-align');\n if (vertical === 'super') next = (next | SUP) & ~SUB;\n else if (vertical === 'sub') next = (next | SUB) & ~SUP;\n else if (vertical === 'baseline') next &= ~(SUP | SUB);\n const family = style.get('font-family');\n if (family !== undefined && MONOSPACE.test(family)) next |= CODE;\n return next;\n}\n\n/* ---------------------------------------------------------------- Blocks */\n\n/** Never content: scripts, metadata, embeds, media, controls, and Word's `<o:p>` spacers. */\nconst SKIP: ReadonlySet<string> = /* @__PURE__ */ new Set([...DROP, 'xml', 'o:p', 'area', 'menuitem']);\n\n/** Left out without a report: what every clipboard document carries (its head, Office markup), not content. */\nconst QUIET: ReadonlySet<string> = /* @__PURE__ */ new Set(['head', 'meta', 'title', 'link', 'base', 'style', 'xml', 'o:p']);\n\nconst HEADINGS: ReadonlySet<string> = /* @__PURE__ */ new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n\n/** Elements that start a new block. Anything else is inline: its content joins the current line. */\nconst BLOCKS: ReadonlySet<string> = /* @__PURE__ */ new Set([\n 'address', 'article', 'aside', 'blockquote', 'body', 'caption', 'center', 'dd', 'details', 'dialog', 'dir', 'div', 'dl', 'dt',\n 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'legend',\n 'li', 'listing', 'main', 'menu', 'nav', 'ol', 'p', 'pre', 'search', 'section', 'summary', 'table', 'tbody', 'td', 'tfoot',\n 'th', 'thead', 'tr', 'ul', 'xmp',\n]);\n\n/** What ends a line in an item already: a line break, or a block written into it. */\nconst LINE_ENDS: ReadonlySet<string> = /* @__PURE__ */ new Set(['br', 'ul', 'ol', 'table', 'pre', 'blockquote', 'hr', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n\n/** Containers that hold their own lines: inline content goes straight into them, not into a paragraph. */\nconst ITEMS: ReadonlySet<string> = /* @__PURE__ */ new Set(['li', 'td', 'th', 'dt', 'dd', 'caption']);\n\nconst BLOCK_SELECTOR = /* @__PURE__ */ [...BLOCKS].join(',');\n\nconst WORD_LIST = /mso-list\\s*:\\s*l\\d+\\s+level(\\d+)/i;\nconst ORDERED_MARKER = /^\\(?(\\d+|[a-z]|[ivxlcdm]+)[.)]/i;\n\n/** Deeper than this, content is kept as plain text: nothing is lost, and nothing overflows the stack. */\nconst MAX_DEPTH = 200;\n/** Most characters of pasted HTML read. */\nconst MAX_INPUT = 16 * 1024 * 1024;\n\nfunction isHidden(element: Element, style: ReadonlyMap<string, string>): boolean {\n return (\n element.hasAttribute('hidden') ||\n element.getAttribute('aria-hidden') === 'true' ||\n style.get('display') === 'none' ||\n style.get('visibility') === 'hidden' ||\n style.get('mso-list') === 'ignore' // Word's list markers: the list carries them\n );\n}\n\nconst isWordListParagraph = (node: Node): node is Element => node.nodeType === 1 && WORD_LIST.test((node as Element).getAttribute('style') ?? '');\n\n/**\n * The text of a code block, with its lines: line breaks, and one per block (as code editors put each\n * line in a `<div>`). `skipped` hears of each element left out.\n */\nfunction codeText(element: Element, skipped: (tag: string) => void): string {\n let text = '';\n const walk = (node: Node): void => {\n if (node.nodeType === 3) {\n text += (node as Text).data.replace(/\\u00A0/g, ' ');\n return;\n }\n if (node.nodeType !== 1) return;\n const child = node as Element;\n const tag = child.localName;\n if (SKIP.has(tag)) {\n skipped(tag);\n return;\n }\n if (isHidden(child, styleOf(child))) return;\n if (tag === 'br') {\n text += '\\n';\n return;\n }\n const block = BLOCKS.has(tag);\n if (block && text !== '' && !text.endsWith('\\n')) text += '\\n';\n child.childNodes.forEach(walk);\n if (block && text !== '' && !text.endsWith('\\n')) text += '\\n';\n };\n element.childNodes.forEach(walk);\n return text.replace(/\\r\\n?/g, '\\n').replace(/\\n$/, '');\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/** A table used for layout (mail, old pages): its cells are just content, in reading order. */\nfunction isLayoutTable(table: Element): boolean {\n const role = table.getAttribute('role');\n if (role === 'presentation' || role === 'none') return true;\n const cells = table.querySelectorAll('td, th');\n return cells.length === 1 || table.querySelector('td table, th table') !== null;\n}\n\ninterface WordList {\n readonly ordered: boolean;\n readonly start: number;\n readonly items: { readonly runs: readonly Run[]; readonly nested: WordList[] }[];\n}\n\ninterface Ctx {\n readonly bits: number;\n readonly href: string | null;\n readonly depth: number;\n}\n\n/** A URL's scheme for reports, read as the URL parser reads it: tabs and line breaks inside it don't count. */\nfunction positive(value: number | undefined, fallback: number, name: string): number {\n if (value === undefined) return fallback;\n if (Number.isInteger(value) && value > 0) return value;\n throw copyFailure('invalid-payload', `\\`${name}\\` must be a positive integer.`);\n}\n\nconst scheme = (raw: string): string => /^\\s*([a-z][a-z\\d+.-]*):/i.exec(raw.replace(/[\\t\\n\\r]/g, ''))?.[1]?.toLowerCase() ?? 'relative';\n\nclass Cleaner {\n private nodes = 0;\n truncated = false;\n readonly removals = new Map<string, RichRemoval>();\n private readonly allowedBits: number;\n private readonly resolveLink: (url: string) => string;\n private readonly resolveImage: (url: string) => string;\n /** Pasted content has no address of its own: relative URLs resolve only against `base`, never the page's. */\n private readonly absolute: (raw: string) => string;\n private readonly maxNodes: number;\n\n constructor(\n private readonly out: Document,\n private readonly formats: ReadonlySet<RichPasteFormat>,\n options: PasteToRichOptions,\n ) {\n this.allowedBits = INLINE.reduce((bits, [bit, , format]) => (formats.has(format) ? bits | bit : bits), 0);\n // The sanitizer's own checks, run here so a rejected link keeps only its text and a rejected image its alt text.\n const base = options.base === undefined ? {} : { base: options.base };\n this.resolveLink = linkUrlResolver({ ...base, ...(options.protocols === undefined ? {} : { protocols: options.protocols }) });\n this.resolveImage = linkUrlResolver({ ...base, protocols: options.dataImages === true ? ['https:', 'http:', 'data:'] : ['https:', 'http:'] });\n this.absolute = options.base === undefined ? (raw) => new URL(raw.trim()).href : (raw) => raw;\n this.maxNodes = positive(options.maxNodes, 200_000, 'maxNodes');\n }\n\n private remove(reason: RichRemovalReason, name: string): void {\n const key = `${reason} ${name}`;\n this.removals.set(key, { reason, name, count: (this.removals.get(key)?.count ?? 0) + 1 });\n }\n\n /** A link's address, absolute and scheme-checked, with click-tracking redirects (Google, Outlook Safe Links) unwrapped; `null` when unsafe. */\n private link(element: Element): string | null {\n const raw = (element.getAttribute('href') ?? '').trim();\n if (raw === '') return null;\n try {\n return unwrapRedirect(new URL(this.resolveLink(this.absolute(raw)))).href;\n } catch {\n this.remove('unsafe-link', scheme(raw));\n return null;\n }\n }\n\n /** Whether an image may be kept: an absolute, scheme-checked address. */\n private safeImage(image: Element): boolean {\n const raw = image.getAttribute('src') ?? '';\n try {\n this.resolveImage(this.absolute(raw));\n return true;\n } catch {\n this.remove('unsafe-image', scheme(raw));\n return false;\n }\n }\n\n private el(tag: string, ...children: Node[]): HTMLElement {\n const element = this.out.createElement(tag);\n element.append(...children);\n return element;\n }\n\n /** Whether reading may go on: a budget on source nodes, so huge or hostile input stays bounded. */\n private count(): boolean {\n if (this.nodes >= this.maxNodes) {\n this.truncated = true;\n return false;\n }\n this.nodes += 1;\n return true;\n }\n\n /**\n * Converts `nodes` into blocks inside `parent`. Inline content goes straight into `parent` when it is an\n * item (a list item, a table cell), or into paragraphs otherwise.\n */\n blocks(nodes: readonly Node[], parent: HTMLElement | DocumentFragment, ctx: Ctx): void {\n const item = parent.nodeType === 1 && ITEMS.has((parent as Element).localName);\n let runs: Run[] = [];\n const flush = (): void => {\n if (item) {\n // Paragraphs in a list item or a cell (Google Docs writes them) are its lines.\n this.line(runs, parent as HTMLElement);\n } else {\n const paragraph = this.out.createElement('p');\n if (this.emit(runs, paragraph)) parent.append(paragraph);\n }\n runs = [];\n };\n for (let index = 0; index < nodes.length; index += 1) {\n const node = nodes[index] as Node;\n if (isWordListParagraph(node)) {\n flush();\n index += this.wordList(nodes, index, parent, ctx) - 1;\n continue;\n }\n if (node.nodeType !== 1 || !BLOCKS.has((node as Element).localName)) {\n const wrapper = node.nodeType === 1 ? this.wrapper(node as Element, ctx) : null;\n if (wrapper === null) this.inline(node, ctx, runs);\n else {\n // An inline element around blocks (Google Docs wraps the whole document in a <b>): its formats\n // and link carry over, and its blocks stay blocks.\n flush();\n this.blocks(Array.from(node.childNodes), parent, wrapper);\n }\n continue;\n }\n const element = node as Element;\n const tag = element.localName;\n const style = styleOf(element);\n if (isHidden(element, style) || !this.count()) continue;\n if (item && (tag === 'p' || (tag === 'div' && !isCodeContainer(tag, style)))) {\n // A paragraph in an item: a line of the item.\n flush();\n runs = this.runsOf(element, ctx);\n flush();\n continue;\n }\n flush();\n this.block(element, tag, style, parent, ctx);\n }\n flush();\n }\n\n /** The context inside an inline element that holds blocks, or `null` for one that holds only inline content. */\n private wrapper(element: Element, ctx: Ctx): Ctx | null {\n if (ctx.depth >= MAX_DEPTH || element.querySelector(BLOCK_SELECTOR) === null) return null;\n const tag = element.localName;\n const style = styleOf(element);\n if (SKIP.has(tag) || element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || isHidden(element, style)) return null;\n return this.inner(element, tag, style, ctx);\n }\n\n /** The formats and link inside an inline element. */\n private inner(element: Element, tag: string, style: ReadonlyMap<string, string>, ctx: Ctx): Ctx {\n const href = tag === 'a' && ctx.href === null && this.formats.has('link') ? this.link(element) : ctx.href;\n // CSS wins over the tag, so Google Docs' wrapper, a `<b style=\"font-weight:normal\">`, is not bold.\n return { bits: bitsOf(ctx.bits, tag, style), href, depth: ctx.depth + 1 };\n }\n\n private block(element: Element, tag: string, style: ReadonlyMap<string, string>, parent: HTMLElement | DocumentFragment, ctx: Ctx): void {\n const deeper: Ctx = { ...ctx, depth: ctx.depth + 1 };\n if (ctx.depth >= MAX_DEPTH) {\n this.paragraph([{ kind: 'text', text: element.textContent, bits: 0, href: null }], parent);\n return;\n }\n if (tag === 'pre' || tag === 'listing' || tag === 'xmp' || isCodeContainer(tag, style)) {\n this.codeBlock(codeText(element, (skipped) => { if (!QUIET.has(skipped)) this.remove('unsafe-element', skipped); }), parent);\n return;\n }\n if (HEADINGS.has(tag)) {\n // Headings are bold already: bold inside one is noise.\n const runs = this.runsOf(element, deeper).map((run) => ({ ...run, bits: run.bits & ~STRONG }));\n if (this.formats.has('heading')) {\n const heading = this.out.createElement(tag);\n if (this.emit(runs, heading)) parent.append(heading);\n } else this.paragraph(runs.map((run) => ({ ...run, bits: run.bits | STRONG })), parent);\n return;\n }\n if (tag === 'ul' || tag === 'ol' || tag === 'menu' || tag === 'dir') {\n this.list(element, tag === 'ol', parent, deeper);\n return;\n }\n if (tag === 'li') {\n // A list item outside a list: the list is implied.\n this.list(element, false, parent, deeper, [element]);\n return;\n }\n if (tag === 'blockquote') {\n if (!this.formats.has('quote')) {\n this.blocks(Array.from(element.childNodes), parent, deeper);\n return;\n }\n const quote = this.out.createElement('blockquote');\n this.blocks(Array.from(element.childNodes), quote, deeper);\n if (quote.firstChild !== null) parent.append(quote);\n return;\n }\n if (tag === 'table') {\n this.table(element, parent, deeper);\n return;\n }\n if (tag === 'hr') {\n if (this.formats.has('rule')) parent.append(this.out.createElement('hr'));\n return;\n }\n if (tag === 'dl') {\n // A description list keeps its terms and details as paragraphs: few editors have one.\n this.blocks(Array.from(element.childNodes), parent, deeper);\n return;\n }\n // Paragraphs, divisions and sections: their inline content forms paragraphs, their blocks stay blocks.\n this.blocks(Array.from(element.childNodes), parent, deeper);\n }\n\n /** A new line of an item: after a line break when the item already ends in text. */\n private line(runs: readonly Run[], item: HTMLElement): void {\n const last = item.lastChild;\n if (last !== null && hasContent(runs) && (last.nodeType !== 1 || !LINE_ENDS.has((last as Element).localName))) item.append(this.out.createElement('br'));\n this.emit(runs, item);\n }\n\n /** A paragraph for `runs` (or the item's own line), when they hold anything. */\n private paragraph(runs: readonly Run[], parent: HTMLElement | DocumentFragment): void {\n if (parent.nodeType === 1 && ITEMS.has((parent as Element).localName)) {\n this.line(runs, parent as HTMLElement);\n return;\n }\n const paragraph = this.out.createElement('p');\n if (this.emit(runs, paragraph)) parent.append(paragraph);\n }\n\n private codeBlock(text: string, parent: HTMLElement | DocumentFragment): void {\n if (text.trim() === '') return;\n if (this.formats.has('codeBlock')) {\n parent.append(this.el('pre', this.el('code', this.out.createTextNode(text))));\n return;\n }\n // A line per paragraph, its spaces kept as no-break spaces so indentation survives.\n for (const line of text.split('\\n')) {\n this.paragraph([{ kind: 'text', text: line.replace(/ /g, '\\u00A0'), bits: CODE, href: null }], parent);\n }\n }\n\n private list(element: Element, ordered: boolean, parent: HTMLElement | DocumentFragment, ctx: Ctx, items?: readonly Element[]): void {\n const start = ordered ? Number.parseInt(element.getAttribute('start') ?? '1', 10) : 1;\n const first = Number.isFinite(start) ? start : 1;\n if (!this.formats.has('list')) {\n // Each item a paragraph after its marker, nested lists after their item.\n let number = first;\n for (const child of items ?? Array.from(element.childNodes)) {\n if (child.nodeType !== 1 || (child as Element).localName !== 'li') {\n this.blocks([child], parent, ctx);\n continue;\n }\n const marker: Run = { kind: 'text', text: ordered ? `${String(number)}. ` : '\\u2022 ', bits: 0, href: null };\n number += 1;\n const own = Array.from(child.childNodes).filter((node) => !(node.nodeType === 1 && /^(?:ul|ol|menu|dir)$/.test((node as Element).localName)));\n const runs = own.flatMap((node) => (node.nodeType === 1 && BLOCKS.has((node as Element).localName) ? [...this.runsOf(node as Element, ctx), BREAK] : this.inlineRuns(node, ctx)));\n this.paragraph([marker, ...trimBreaks(runs)], parent);\n for (const nested of Array.from((child as Element).children)) if (/^(?:ul|ol|menu|dir)$/.test(nested.localName)) this.list(nested, nested.localName === 'ol', parent, ctx);\n }\n return;\n }\n const list = this.out.createElement(ordered ? 'ol' : 'ul');\n if (ordered && first !== 1) list.setAttribute('start', String(first));\n for (const child of items ?? Array.from(element.childNodes)) {\n if (child.nodeType === 1 && (child as Element).localName === 'li') {\n const li = this.out.createElement('li');\n this.blocks(Array.from(child.childNodes), li, ctx);\n list.append(li);\n continue;\n }\n // Google Docs nests a list as the sibling of its item, not inside it; text between items is an item.\n const host = list.lastElementChild ?? list.appendChild(this.out.createElement('li'));\n this.blocks([child], host as HTMLElement, ctx);\n }\n // Items with nothing in them are left out; a list with no items is too.\n for (const li of Array.from(list.children)) if (li.firstChild === null) li.remove();\n if (list.firstChild !== null) parent.append(list);\n }\n\n /**\n * Word writes lists as paragraphs with `mso-list: l0 level2`, and each marker (`1.`, `·`) as\n * text in a span hidden with `mso-list: Ignore`. Rebuilds the consecutive list paragraphs\n * from `nodes[start]` as nested lists. Returns how many nodes they took.\n */\n private wordList(nodes: readonly Node[], start: number, parent: HTMLElement | DocumentFragment, ctx: Ctx): number {\n const roots: WordList[] = [];\n const stack: { level: number; list: WordList }[] = [];\n let consumed = 0;\n const flat = !this.formats.has('list');\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 // Taken even past the node budget, so the caller always moves on.\n consumed = index - start + 1;\n if (!this.count()) break;\n const level = Number(WORD_LIST.exec(node.getAttribute('style') as string)?.[1]);\n const marker = (node.querySelector('[style*=\"mso-list\"][style*=\"gnore\"]')?.textContent ?? '').replace(/\\s+/g, '');\n const ordered = ORDERED_MARKER.exec(marker);\n const runs = this.runsOf(node, ctx);\n if (flat) {\n // Word's own marker, as Word shows it.\n const shown = ordered !== null ? `${marker} ` : '\\u2022 ';\n this.paragraph([{ kind: 'text', text: shown, bits: 0, href: null }, ...runs], parent);\n continue;\n }\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 number = ordered !== null && /^\\d+$/.test(ordered[1] as string) ? Number(ordered[1]) : 1;\n const list: WordList = { ordered: ordered !== null, start: number, items: [] };\n const host = top?.list.items[top.list.items.length - 1];\n if (host === undefined) roots.push(list);\n else host.nested.push(list);\n top = { level, list };\n stack.push(top);\n }\n top.list.items.push({ runs, nested: [] });\n }\n for (const list of roots) this.writeWordList(list, parent);\n return consumed;\n }\n\n /** Writes a rebuilt Word list. An item with nothing in it is left out, unless it holds a nested list. */\n private writeWordList(list: WordList, parent: Node): void {\n const element = this.out.createElement(list.ordered ? 'ol' : 'ul');\n if (list.ordered && list.start !== 1) element.setAttribute('start', String(list.start));\n for (const item of list.items) {\n const li = this.out.createElement('li');\n this.emit(item.runs, li);\n for (const nested of item.nested) this.writeWordList(nested, li);\n if (li.firstChild !== null) element.append(li);\n }\n if (element.firstChild !== null) parent.appendChild(element);\n }\n\n private table(table: Element, parent: HTMLElement | DocumentFragment, ctx: Ctx): void {\n const rows = Array.from(table.querySelectorAll('tr')).filter((row) => row.closest('table') === table);\n const caption = Array.from(table.children).find((child) => child.localName === 'caption');\n if (!this.formats.has('table') || isLayoutTable(table)) {\n // Its content in reading order: the caption, then each cell's blocks.\n if (caption !== undefined) this.blocks(Array.from(caption.childNodes), parent, ctx);\n for (const row of rows) for (const cell of Array.from(row.children)) if (cell.localName === 'td' || cell.localName === 'th') this.blocks(Array.from(cell.childNodes), parent, ctx);\n return;\n }\n const out = this.out.createElement('table');\n if (caption !== undefined) {\n const element = this.out.createElement('caption');\n this.blocks(Array.from(caption.childNodes), element, ctx);\n if (element.firstChild !== null) out.append(element);\n }\n const sections = new Map<Element, HTMLElement>();\n for (const row of rows) {\n if (!this.count()) break;\n // The HTML parser puts every row in a section (a <tbody> when none is written).\n const group = row.parentElement as Element;\n let section = sections.get(group);\n if (section === undefined) {\n section = this.out.createElement(group.localName === 'thead' || group.localName === 'tfoot' ? group.localName : 'tbody');\n sections.set(group, section);\n out.append(section);\n }\n const tr = this.out.createElement('tr');\n for (const cell of Array.from(row.children)) {\n if (cell.localName !== 'td' && cell.localName !== 'th') continue;\n const element = this.out.createElement(cell.localName);\n for (const attribute of ['colspan', 'rowspan', 'scope']) {\n const value = cell.getAttribute(attribute);\n if (value !== null) element.setAttribute(attribute, value);\n }\n // Header cells are bold already.\n this.blocks(Array.from(cell.childNodes), element, cell.localName === 'th' ? { ...ctx, bits: ctx.bits & ~STRONG } : ctx);\n if (cell.localName === 'th') stripBold(element);\n tr.append(element);\n }\n section.append(tr);\n }\n if (rows.length > 0) parent.append(out);\n }\n\n /** The inline content of `element` as runs: its blocks become lines, separated by line breaks. */\n private runsOf(element: Element, ctx: Ctx): Run[] {\n const runs: Run[] = [];\n const inner = { ...ctx, bits: bitsOf(ctx.bits, element.localName, styleOf(element)) };\n for (const child of Array.from(element.childNodes)) {\n if (child.nodeType === 1 && BLOCKS.has((child as Element).localName) && (child as Element).localName !== 'br') {\n const element = child as Element;\n if (isHidden(element, styleOf(element))) continue;\n if (runs.length > 0) runs.push(BREAK);\n runs.push(...this.runsOf(element, { ...inner, depth: inner.depth + 1 }));\n runs.push(BREAK);\n continue;\n }\n this.inline(child, inner, runs);\n }\n return trimBreaks(runs);\n }\n\n private inlineRuns(node: Node, ctx: Ctx): Run[] {\n const runs: Run[] = [];\n this.inline(node, ctx, runs);\n return runs;\n }\n\n /** Inline content into runs: text with its formats and link, line breaks and images. */\n private inline(node: Node, ctx: Ctx, runs: Run[]): void {\n if (!this.count()) return;\n if (node.nodeType === 3) {\n runs.push({ kind: 'text', text: (node as Text).data, bits: ctx.bits, href: ctx.href });\n return;\n }\n if (node.nodeType !== 1) return;\n const element = node as Element;\n const tag = element.localName;\n const style = styleOf(element);\n if (SKIP.has(tag) || element.namespaceURI !== 'http://www.w3.org/1999/xhtml') {\n if (!QUIET.has(tag)) this.remove('unsafe-element', tag);\n return;\n }\n if (isHidden(element, style)) return;\n if (tag === 'br') {\n runs.push({ kind: 'break', bits: ctx.bits, href: ctx.href });\n return;\n }\n if (tag === 'img') {\n if (!this.formats.has('image') || this.safeImage(element)) runs.push({ kind: 'image', image: element, bits: ctx.bits, href: ctx.href });\n else runs.push({ kind: 'text', text: element.getAttribute('alt') ?? '', bits: ctx.bits, href: ctx.href });\n return;\n }\n if (ctx.depth >= MAX_DEPTH) {\n runs.push({ kind: 'text', text: element.textContent, bits: ctx.bits, href: ctx.href });\n return;\n }\n const inner = this.inner(element, tag, style, ctx);\n if (BLOCKS.has(tag)) {\n // A block inside inline content (a heading's paragraphs, a link around a division): a line of its own.\n runs.push(BREAK, ...this.runsOf(element, inner), BREAK);\n return;\n }\n for (const child of Array.from(element.childNodes)) this.inline(child, inner, runs);\n }\n\n /**\n * Writes `runs` into `target` as minimal, canonical markup: links outermost, then the formats in a\n * fixed order, each over the longest stretch it covers. Whitespace collapses as the browser shows it.\n * Returns whether anything was written.\n */\n emit(runs: readonly Run[], target: Node): boolean {\n const cleaned = collapse(\n runs.map((run) => {\n const bits = run.bits & this.allowedBits;\n const href = this.formats.has('link') ? run.href : null;\n return run.kind === 'image' && !this.formats.has('image')\n ? ({ kind: 'text', text: run.image.getAttribute('alt') ?? '', bits, href } as const)\n : { ...run, bits, href };\n }),\n );\n if (cleaned.length === 0) return false;\n this.write(cleaned, target, 0);\n return true;\n }\n\n private write(runs: readonly Run[], target: Node, level: number): void {\n if (level === 0) {\n for (const group of groups(runs, (run) => run.href)) {\n const href = (group[0] as Run).href;\n if (href === null) this.write(group, target, 1);\n else {\n const link = this.out.createElement('a');\n link.setAttribute('href', href);\n this.write(group, link, 1);\n target.appendChild(link);\n }\n }\n return;\n }\n const format = INLINE[level - 1];\n if (format === undefined) {\n for (const run of runs) {\n if (run.kind === 'text') target.appendChild(this.out.createTextNode(run.text));\n else if (run.kind === 'break') target.appendChild(this.out.createElement('br'));\n else target.appendChild(copyImage(this.out, run.image));\n }\n return;\n }\n const [bit, tag] = format;\n for (const group of groups(runs, (run) => (run.bits & bit) !== 0)) {\n if (((group[0] as Run).bits & bit) === 0) this.write(group, target, level + 1);\n else {\n const element = this.out.createElement(tag);\n this.write(group, element, level + 1);\n target.appendChild(element);\n }\n }\n }\n}\n\nconst BREAK: Run = { kind: 'break', bits: 0, href: null };\n\nconst hasContent = (runs: readonly Run[]): boolean => runs.some((run) => run.kind === 'image' || (run.kind === 'text' && /[^\\s]/.test(run.text)));\n\nfunction trimBreaks(runs: Run[]): Run[] {\n let start = 0;\n let end = runs.length;\n while (start < end && (runs[start] as Run).kind === 'break') start += 1;\n while (end > start && (runs[end - 1] as Run).kind === 'break') end -= 1;\n return runs.slice(start, end);\n}\n\n/** Maximal stretches of runs with the same key. */\nfunction groups(runs: readonly Run[], key: (run: Run) => unknown): Run[][] {\n const out: Run[][] = [];\n let last: unknown;\n for (const run of runs) {\n const value = key(run);\n const current = out[out.length - 1];\n if (current !== undefined && value === last) current.push(run);\n else out.push([run]);\n last = value;\n }\n return out;\n}\n\n/**\n * Whitespace as the browser shows it: runs of it are one space, none at the start or end of a line,\n * and line breaks without text after them (or several in a row at the edges) are left out.\n * Spaces take no formats, so formatting never starts or ends with one.\n */\nfunction collapse(runs: readonly Run[]): Run[] {\n const out: Run[] = [];\n let lineStart = true;\n let pendingSpace = false;\n for (const run of runs) {\n if (run.kind === 'break') {\n pendingSpace = false;\n out.push(run);\n lineStart = true;\n continue;\n }\n if (run.kind === 'image') {\n if (pendingSpace) out.push({ kind: 'text', text: ' ', bits: 0, href: null });\n pendingSpace = false;\n out.push(run);\n lineStart = false;\n continue;\n }\n const parts = run.text.split(/[ \\t\\n\\r\\f]+/);\n for (let index = 0; index < parts.length; index += 1) {\n const part = parts[index] as string;\n if (index > 0 && !lineStart) pendingSpace = true;\n if (part === '') continue;\n if (pendingSpace) {\n // A space takes the formats and link on both sides of it, so \"<b>on</b> <b>Friday</b>\" stays one bold run.\n // A pending space always follows text or an image on the same line.\n const last = out[out.length - 1] as Run;\n out.push({ kind: 'text', text: ' ', bits: last.bits & run.bits, href: last.href === run.href ? run.href : null });\n }\n pendingSpace = false;\n out.push({ kind: 'text', text: part, bits: run.bits, href: run.href });\n lineStart = false;\n }\n }\n // Join neighbouring text with the same formats and link, so the output is canonical.\n const merged: Run[] = [];\n for (const run of trimBreaks(out)) {\n const last = merged[merged.length - 1];\n if (run.kind === 'text' && last?.kind === 'text' && last.bits === run.bits && last.href === run.href) merged[merged.length - 1] = { ...last, text: last.text + run.text };\n else merged.push(run);\n }\n return hasContent(merged) ? merged : [];\n}\n\n/** An image with what describes it, never its styles or event handlers. */\nfunction copyImage(doc: Document, image: Element): HTMLElement {\n const out = doc.createElement('img');\n for (const name of ['src', 'alt', 'title', 'width', 'height']) {\n const value = image.getAttribute(name);\n if (value !== null) out.setAttribute(name, value);\n }\n return out;\n}\n\n/** Bold inside a header cell is noise: the cell is bold already. */\nfunction stripBold(cell: Element): void {\n for (const strong of Array.from(cell.querySelectorAll('strong'))) strong.replaceWith(...Array.from(strong.childNodes));\n cell.normalize();\n}\n\n/* ---------------------------------------------------------------- Public */\n\nfunction resolveFormats(formats: readonly RichPasteFormat[] | undefined): ReadonlySet<RichPasteFormat> {\n if (formats === undefined) return new Set(RICH_PASTE_FORMATS);\n const value: unknown = formats;\n if (!Array.isArray(value) || !value.every((format) => (RICH_PASTE_FORMATS as readonly unknown[]).includes(format))) {\n throw copyFailure('invalid-payload', `\\`formats\\` must be an array of: ${RICH_PASTE_FORMATS.join(', ')}.`);\n }\n return new Set(formats);\n}\n\nconst escapeHtml = (text: string): string => text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');\n\n/** Plain text as rich content: a paragraph per block of lines, a line break per line. Needs no DOM. */\nfunction fromText(text: string, maxLength: number): RichPaste {\n const normalized = text.replace(/\\r\\n?/g, '\\n');\n const paragraphs = normalized\n .split(/\\n[ \\t]*\\n+/)\n .map((block) => block.split('\\n').map((line) => escapeHtml(line.trim())).filter((line) => line !== ''))\n .filter((lines) => lines.length > 0);\n let html = '';\n let truncated = false;\n for (const lines of paragraphs) {\n const paragraph = `<p>${lines.join('<br>')}</p>`;\n if (html.length + paragraph.length > maxLength) {\n truncated = true;\n break;\n }\n html += paragraph;\n }\n return { html, text: normalized.trim(), removed: [], truncated, source: 'text' };\n}\n\n/**\n * Cleans what was pasted into semantic, safe HTML for a rich-text editor: the HTML Google Docs,\n * Word, Outlook, Gmail, Notion and web pages put on the clipboard becomes paragraphs, headings,\n * lists, quotes, code blocks, tables, links and images, with bold, italic, underline,\n * strikethrough, code, superscript and subscript as tags (`<strong>`, `<em>`, ...).\n *\n * - Formatting set by CSS (`font-weight: 700`, `font-style: italic`) becomes tags, and every\n * style, class and id is left out: pasted content takes the editor's look, not the source's.\n * - Word's paragraph lists become real lists; Google Docs' wrappers, empty spacers and hidden\n * markers go. Layout tables (mail) become their content.\n * - The output is canonical (the same content always gives the same HTML) and goes through the\n * same sanitizer as {@link prepareRich}: only allowlisted elements and attributes, links and\n * images with absolute, scheme-checked URLs. `removed` says what was left out.\n * - `formats` limits the output to what your editor holds, keeping all of the text.\n *\n * Plain text (no HTML on the clipboard) becomes paragraphs and line breaks. Returns `null` when\n * there is nothing to paste. HTML needs `DOMParser` (any browser, or jsdom); without one, the\n * plain text is used.\n *\n * @example\n * // TipTap / ProseMirror\n * editorProps: { transformPastedHTML: (html) => pasteToRich({ html })?.html ?? '' }\n */\nexport function pasteToRich(source: RichPasteSource, options: PasteToRichOptions = {}): RichPaste | null {\n const formats = resolveFormats(options.formats); // invalid options are a programming error: they throw\n const maxLength = options.maxLength ?? 1_000_000;\n const html = source.html ?? null;\n const text = source.text ?? null;\n if (html !== null && html.trim() !== '' && typeof DOMParser !== 'undefined') {\n // Inert: scripts never run and nothing is fetched. Its nodes are only read.\n const parsed = parseInertHtml(`<!doctype html><body>${html.slice(0, MAX_INPUT)}`);\n // Built in a document with no address, so relative links resolve only against `base`.\n const out = parsed.implementation.createHTMLDocument('');\n const cleaner = new Cleaner(out, formats, options);\n const fragment = out.createDocumentFragment();\n cleaner.blocks(Array.from(parsed.body.childNodes), fragment, { bits: 0, href: null, depth: 0 });\n const result = prepareRich(fragment, {\n styles: 'none',\n images: formats.has('image') ? 'keep' : 'alt',\n ...(options.base === undefined ? {} : { base: options.base }),\n ...(options.protocols === undefined ? {} : { protocols: options.protocols }),\n ...(options.dataImages === undefined ? {} : { dataImages: options.dataImages }),\n ...(options.maxElements === undefined ? {} : { maxElements: options.maxElements }),\n maxLength,\n ...(options.text === undefined ? {} : { text: options.text }),\n });\n if (result.html !== '') {\n // Never the same entry twice: the sanitizer only sees what the cleaner kept.\n const removed = [...cleaner.removals.values(), ...result.removed];\n return { ...result, removed, truncated: result.truncated || cleaner.truncated || html.length > MAX_INPUT, source: 'html' };\n }\n }\n if (text === null || text.trim() === '') return null;\n const value: unknown = maxLength;\n if (!(Number.isInteger(value) && maxLength > 0)) throw copyFailure('invalid-payload', '`maxLength` must be a positive integer.');\n return fromText(text, maxLength);\n}\n\n/** Structural paste event: a DOM `ClipboardEvent` and React's `onPaste` event both fit. */\nexport interface RichPasteEvent {\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\nexport interface PasteAsRichOptions extends PasteToRichOptions {\n /**\n * Called with the cleaned content before it is inserted. Return `false` to insert it yourself\n * (through your editor's API, say): the browser's paste is still prevented.\n */\n readonly onPaste?: (pasted: RichPaste) => boolean | undefined;\n}\n\n/** The editable element a paste lands in: the handler's element when it is `contenteditable`. */\nfunction editableHost(event: RichPasteEvent): HTMLElement | null {\n const target: unknown = event.currentTarget ?? event.target;\n if (typeof target !== 'object' || target === null || (target as Partial<Node>).nodeType !== 1) return null;\n const element = target as HTMLElement;\n return element.isContentEditable ? element : null;\n}\n\n/**\n * Inserts HTML at the selection in an editable element, as a paste would: the browser's undo\n * (Ctrl/Cmd+Z) still works and `input` events fire. Without a selection inside the element,\n * the HTML goes at its end.\n */\nfunction insertHtml(host: HTMLElement, html: string): void {\n const doc = host.ownerDocument;\n const selection = doc.getSelection();\n const current = selection !== null && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;\n // Where it goes: the selection in the element, or its end. Kept across focusing, which can move the\n // caret, and insertHTML acts in the focused editing host.\n let range: Range;\n if (current !== null && host.contains(current.commonAncestorContainer)) range = current.cloneRange();\n else {\n range = doc.createRange();\n range.selectNodeContents(host);\n range.collapse(false);\n }\n if (doc.activeElement !== host) host.focus();\n selection?.removeAllRanges();\n selection?.addRange(range);\n try {\n // The only way to keep the native undo stack. The HTML is sanitized: allowlisted elements and\n // attributes only, scheme-checked URLs, no styles, scripts or event handlers.\n // eslint-disable-next-line @typescript-eslint/no-deprecated -- no replacement keeps undo history\n if (doc.activeElement === host && doc.execCommand('insertHTML', false, html)) return;\n } catch {\n // Fall through to the manual insertion.\n }\n range.deleteContents();\n // codeql[js/xss] Sanitized above: allowlisted elements and attributes, scheme-checked URLs.\n const fragment = range.createContextualFragment(html);\n // Never empty: an empty cleaning result is not inserted.\n const last = fragment.lastChild as Node;\n range.insertNode(fragment);\n range.setStartAfter(last);\n range.collapse(true);\n const view = doc.defaultView;\n host.dispatchEvent(\n view !== null && typeof view.InputEvent === 'function'\n ? new view.InputEvent('input', { bubbles: true, inputType: 'insertFromPaste' })\n : new Event('input', { bubbles: true }),\n );\n}\n\n/**\n * A paste handler for `contenteditable` elements: what is pasted from Google Docs, Word, mail or\n * a web page goes in as clean, semantic HTML (see {@link pasteToRich}), with undo intact. Plain-text\n * pastes are left to the browser. Returns whether it handled the paste.\n *\n * Rich-text editors (TipTap, ProseMirror, Lexical, Quill) have their own paste pipelines: use\n * {@link pasteToRich} in their hook instead, so the editor keeps its document model.\n *\n * @example\n * <div contentEditable onPaste={pasteAsRich} />\n * <div contentEditable onPaste={(event) => pasteAsRich(event, { formats: ['bold', 'italic', 'link', 'list'] })} />\n */\nexport function pasteAsRich(event: RichPasteEvent, options?: PasteAsRichOptions): boolean {\n if (event.defaultPrevented || event.clipboardData === null) return false;\n const host = editableHost(event);\n if (host === null) return false;\n const html = event.clipboardData.getData('text/html');\n if (html === '') return false;\n let pasted: RichPaste | null;\n try {\n pasted = pasteToRich({ 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 if (options?.onPaste?.(pasted) === false) return true;\n insertHtml(host, pasted.html);\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;AAOA,MAAa,uBAA4C,IAAI,IAAI;CAC/D;CAAK;CAAQ;CAAK;CAAO;CAAO;CAAc;CAAM;CAAW;CAAQ;CAAQ;CAAO;CAAY;CAAM;CAAO;CAAO;CAAO;CAAM;CACnI;CAAM;CAAc;CAAU;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAM;CAAK;CAAO;CAAO;CAAO;CAAM;CAAQ;CAAM;CAAK;CAAO;CAAK;CACvI;CAAQ;CAAS;CAAQ;CAAU;CAAO;CAAO;CAAS;CAAS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