markdown-to-word 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +77 -2
- package/build/cli.js +172 -0
- package/build/cli.js.map +1 -0
- package/build/converter.js +3 -1
- package/build/converter.js.map +1 -1
- package/build/docx-html.d.ts +14 -6
- package/build/docx-html.js +157 -21
- package/build/docx-html.js.map +1 -1
- package/build/docx-images.d.ts +3 -1
- package/build/docx-images.js +144 -13
- package/build/docx-images.js.map +1 -1
- package/build/docx-structure.d.ts +9 -0
- package/build/docx-structure.js +51 -1
- package/build/docx-structure.js.map +1 -1
- package/build/input-checks.d.ts +4 -0
- package/build/input-checks.js +9 -0
- package/build/input-checks.js.map +1 -0
- package/build/markdown-parser.d.ts +6 -5
- package/build/markdown-parser.js +14 -8
- package/build/markdown-parser.js.map +1 -1
- package/build/mcp.js +240 -0
- package/build/mcp.js.map +1 -0
- package/package.json +22 -11
package/build/docx-html.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docx-html.js","sourceRoot":"","sources":["../src/docx-html.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,aAAa,CAAC;AAEvC,+EAA+E;AAC/E,MAAM,QAAQ,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC;AAElD;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,OAAO,CAAC;AAEjC;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG,iBAAiB,CAAC;AAE5C,qDAAqD;AACrD,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAEhC,4DAA4D;AAC5D,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;AAE5E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BAAiB,GAAG,EAAE,SAAS,CAAC,CACjD,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,WAAW,CAAC,KAAc,EAAE,KAAa;IAChD,MAAM,MAAM,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC;IAC5C,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC/C,IAAI,KAAK,CAAC,SAAS,KAAK,YAAY,EAAE,CAAC;YACrC,WAAW,CAAC,KAAK,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;QAChC,CAAC;aAAM,IAAI,gBAAgB,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC;YACjD,MAAM,KAAK,GAAG,kBAAkB,CAAC;YACjC,MAAM,MAAM,GAAG,MAAM;gBACnB,CAAC,CAAC,KAAK;gBACP,CAAC,CAAC,gBAAgB,KAAK,GAAG,mBAAmB,OAAO,KAAK,EAAE,CAAC;YAC9D,MAAM,KAAK,GAAG,KAAK,CAAC,YAAY,CAAC,iBAAiB,CAAC,CAAC;YACpD,KAAK,CAAC,YAAY,CAChB,iBAAiB,EACjB,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,KAAK,MAAM,EAAE,CAAC,CAAC,CAAC,MAAM,CACvC,CAAC;QACJ,CAAC;IACH,CAAC;IACD,KAAK,CAAC,WAAW,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC;AACrD,CAAC","sourcesContent":["/**\n * A monospace face that ships with Windows, so Chinese comments stay aligned.\n * Defined here rather than in the code block patch so the main bundle can use\n * it without loading that patch and JSZip.\n */\nexport const CODE_FONT = 'Courier New';\n\n/** What Word shows in place of a task list checkbox, which it can't render. */\nconst CHECKBOX = { checked: '☒', unchecked: '☐' };\n\n/**\n * Stands in for `<hr>`, which the generator drops. The structure patch turns\n * each one into a bordered paragraph; if that patch fails, a centered `* * *`\n * still reads as a section break.\n */\nexport const RULE_TEXT = '* * *';\n\n/**\n * Stands in for `style` while the HTML is a live DOM. The page's CSP applies\n * to DOMParser documents too, and blocks (and reports) `style` attributes set\n * there. (CSSOM is allowed, but it quotes a font name with a space, which the\n * generator would read as part of the name.) Renamed back to `style` in the\n * serialized tags, where the CSP doesn't reach.\n */\nconst STYLE_PLACEHOLDER = 'data-docx-style';\n\n/** How far each level of block quote is indented. */\nconst QUOTE_INDENT_INCHES = 0.5;\n\n/** Block quote children that become indented paragraphs. */\nconst QUOTE_PARAGRAPHS = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n\n/**\n * Inline elements the generator doesn't know, whose text it drops. Each is\n * replaced by what a browser shows: a span (in the code font, for the ones a\n * browser draws in monospace), emphasis, or quotation marks.\n */\nconst UNKNOWN_INLINE: Record<string, 'code' | 'em' | 'quote' | 'text'> = {\n kbd: 'code',\n samp: 'code',\n tt: 'code',\n var: 'em',\n cite: 'em',\n dfn: 'em',\n q: 'quote',\n abbr: 'text',\n acronym: 'text',\n bdi: 'text',\n bdo: 'text',\n big: 'text',\n data: 'text',\n font: 'text',\n label: 'text',\n small: 'text',\n time: 'text',\n};\n\n/** `Node.TEXT_NODE`, which Node's globals lack. */\nconst TEXT_NODE = 3;\n\n/** The highlight browsers give `<mark>`; the generator drops it. */\nconst MARK_COLOR = '#FFFF00';\n\n/**\n * Adjusts the parser's HTML for html-to-docx, which drops or flattens some of\n * what the browser preview renders:\n *\n * - Task list checkboxes: `<input>` is dropped, so done and pending items read\n * the same. Each becomes a ☒ or ☐ character.\n * - Inline code: `<code>` keeps the body font. Its text is wrapped in a span\n * naming the code block font, which the generator does carry over.\n * - Table header cells: `<th>` isn't bold, so its content is wrapped in\n * `<strong>`. Column alignment from GFM's `align` attribute is ignored, but\n * the same value as a `text-align` style is honored.\n * - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT\n * paragraph for the structure patch to draw as a rule.\n * - Block quotes: the generator joins everything in a `<blockquote>` into one\n * justified paragraph. Its paragraphs and headings are kept apart instead,\n * left aligned and indented one step per level of nesting.\n * - Inline elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, ...): their\n * text is dropped, so each is replaced by a span or `<em>` (see\n * UNKNOWN_INLINE). `<mark>` loses its highlight, so it's set as a shading.\n * - Footnotes: the reference and back links point into the page, which a\n * Word reader can't follow, so references keep only their number and the\n * back links (↩) go. So does the footnotes heading, which the page only\n * shows to screen readers.\n *\n * Only the HTML bound for the .docx changes; the preview keeps the original.\n */\nexport function prepareHtmlForDocx(html: string): string {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n\n for (const input of Array.from(\n dom.querySelectorAll('input[type=\"checkbox\"]')\n )) {\n const box = input.hasAttribute('checked')\n ? CHECKBOX.checked\n : CHECKBOX.unchecked;\n input.replaceWith(dom.createTextNode(box));\n }\n\n for (const code of Array.from(dom.querySelectorAll('code'))) {\n if (code.closest('pre')) continue;\n const span = dom.createElement('span');\n // A raw attribute, not `style.fontFamily`: see STYLE_PLACEHOLDER.\n span.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);\n span.append(...Array.from(code.childNodes));\n code.append(span);\n }\n\n for (const cell of Array.from(dom.querySelectorAll('th, td'))) {\n const align = cell.getAttribute('align');\n if (align) {\n (cell as HTMLElement).style.textAlign = align;\n cell.removeAttribute('align');\n }\n if (cell.localName === 'th' && cell.textContent?.trim()) {\n const strong = dom.createElement('strong');\n strong.append(...Array.from(cell.childNodes));\n cell.append(strong);\n }\n }\n\n for (const quote of Array.from(dom.querySelectorAll('blockquote'))) {\n // Outermost first; each one unwraps its nested quotes as it goes.\n if (quote.isConnected) unwrapQuote(quote, 1);\n }\n\n for (const element of Array.from(dom.body.querySelectorAll('*'))) {\n const kind = UNKNOWN_INLINE[element.localName];\n if (!kind || element.closest('pre')) continue;\n if (kind === 'quote') {\n element.replaceWith('“', ...Array.from(element.childNodes), '”');\n continue;\n }\n const replacement = dom.createElement(kind === 'em' ? 'em' : 'span');\n if (kind === 'code') {\n replacement.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);\n }\n replacement.append(...Array.from(element.childNodes));\n element.replaceWith(replacement);\n }\n\n for (const mark of Array.from(dom.querySelectorAll('mark'))) {\n const span = dom.createElement('span');\n span.setAttribute(STYLE_PLACEHOLDER, `background-color: ${MARK_COLOR}`);\n span.append(...Array.from(mark.childNodes));\n mark.replaceWith(span);\n }\n\n for (const reference of Array.from(\n dom.querySelectorAll('a[data-footnote-ref]')\n )) {\n reference.replaceWith(...Array.from(reference.childNodes));\n }\n for (const backReference of Array.from(\n dom.querySelectorAll('a[data-footnote-backref]')\n )) {\n // The space before it, too, so the note doesn't end in one.\n const before = backReference.previousSibling;\n if (before?.nodeType === TEXT_NODE && before.textContent?.endsWith(' ')) {\n before.textContent = before.textContent.slice(0, -1);\n }\n backReference.remove();\n }\n dom.querySelector('section[data-footnotes] > h2')?.remove();\n\n for (const rule of Array.from(dom.querySelectorAll('hr'))) {\n const paragraph = dom.createElement('p');\n paragraph.setAttribute(STYLE_PLACEHOLDER, 'text-align: center');\n paragraph.textContent = RULE_TEXT;\n rule.replaceWith(paragraph);\n }\n\n // Only inside tags: text can't contain a raw `<`, so it's never touched.\n return dom.body.innerHTML.replace(/<[^>]+>/g, (tag) =>\n tag.replace(` ${STYLE_PLACEHOLDER}=`, ' style=')\n );\n}\n\n/**\n * Replaces `quote` with its children, indenting its paragraphs and headings\n * `depth` steps. Other blocks (lists, code, tables) keep their own layout, and\n * so does a quote in a list item: the generator indents that paragraph for the\n * list already, and a second indent would be invalid or move the bullet.\n */\nfunction unwrapQuote(quote: Element, depth: number): void {\n const inList = quote.closest('li') !== null;\n for (const child of Array.from(quote.children)) {\n if (child.localName === 'blockquote') {\n unwrapQuote(child, depth + 1);\n } else if (QUOTE_PARAGRAPHS.has(child.localName)) {\n const align = 'text-align: left';\n const layout = inList\n ? align\n : `margin-left: ${depth * QUOTE_INDENT_INCHES}in; ${align}`;\n const style = child.getAttribute(STYLE_PLACEHOLDER);\n child.setAttribute(\n STYLE_PLACEHOLDER,\n style ? `${style}; ${layout}` : layout\n );\n }\n }\n quote.replaceWith(...Array.from(quote.childNodes));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"docx-html.js","sourceRoot":"","sources":["../src/docx-html.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,aAAa,CAAC;AAEvC,+EAA+E;AAC/E,MAAM,QAAQ,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC;AAElD;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,OAAO,CAAC;AAEjC;;;;;;GAMG;AACH,MAAM,iBAAiB,GAAG,iBAAiB,CAAC;AAE5C,qDAAqD;AACrD,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAEhC,4DAA4D;AAC5D,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;AAE5E;;;;;GAKG;AACH,MAAM,cAAc,GAA4C;IAC9D,GAAG,EAAE,MAAM;IACX,IAAI,EAAE,MAAM;IACZ,EAAE,EAAE,MAAM;IACV,GAAG,EAAE,IAAI;IACT,IAAI,EAAE,IAAI;IACV,GAAG,EAAE,IAAI;IACT,CAAC,EAAE,OAAO;CACX,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC;IACjC,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,CAAC;IACrE,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,YAAY,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AAI,CACL,CAAC;YACF,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC;YACvC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QAC5B,CAAC;QACD,uEAAuE;QACvE,mEAAmE;QACnE,MAAM,GAAG,GACP,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC;YACnC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;YACxC,CAAC,CAAC,SAAS,CAAC;QAChB,OAAO,GAAG,IAAI,eAAe,CAAC,OAAO,CAAC,CAAC;IACzC,CAAC;CACF;AAED,sDAAsD;AACtD,SAAS,eAAe,CAAC,OAAgB;IACvC,MAAM,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC;SAC9C,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,KAAK,KAAK,GAAG,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC;SACtE,IAAI,CAAC,EAAE,CAAC,CAAC;IACZ,OAAO,IAAI,OAAO,CAAC,SAAS,GAAG,UAAU,GAAG,CAAC;AAC/C,CAAC","sourcesContent":["/**\n * A monospace face that ships with Windows, so Chinese comments stay aligned.\n * Defined here rather than in the code block patch so the main bundle can use\n * it without loading that patch and JSZip.\n */\nexport const CODE_FONT = 'Courier New';\n\n/** What Word shows in place of a task list checkbox, which it can't render. */\nconst CHECKBOX = { checked: '☒', unchecked: '☐' };\n\n/**\n * Stands in for `<hr>`, which the generator drops. The structure patch turns\n * each one into a bordered paragraph; if that patch fails, a centered `* * *`\n * still reads as a section break.\n */\nexport const RULE_TEXT = '* * *';\n\n/**\n * Stands in for `style` while the HTML is a live DOM. The page's CSP applies\n * to DOMParser documents too, and blocks (and reports) `style` attributes set\n * there. (CSSOM is allowed, but it quotes a font name with a space, which the\n * generator would read as part of the name.) Renamed back to `style` in the\n * serialized tags, where the CSP doesn't reach.\n */\nconst STYLE_PLACEHOLDER = 'data-docx-style';\n\n/** How far each level of block quote is indented. */\nconst QUOTE_INDENT_INCHES = 0.5;\n\n/** Block quote children that become indented paragraphs. */\nconst QUOTE_PARAGRAPHS = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\n\n/**\n * Inline elements the generator doesn't know, whose text it drops. Each is\n * replaced by what a browser shows: a span in the code font (for the ones a\n * browser draws in monospace), emphasis, or quotation marks. Other unknown\n * elements are unwrapped (see GENERATOR_ELEMENTS).\n */\nconst UNKNOWN_INLINE: Record<string, 'code' | 'em' | 'quote'> = {\n kbd: 'code',\n samp: 'code',\n tt: 'code',\n var: 'em',\n cite: 'em',\n dfn: 'em',\n q: 'quote',\n};\n\n/**\n * Elements the generator keeps the text of (each checked against it), or\n * that a later step here rewrites (`hr`, `mark`, `input`). Any other element\n * in a paragraph loses its text, so it's replaced by its children: an\n * allowlist, because a list of the ones it drops (`<abbr>`, `<small>`, a\n * custom `<my-element>`, ...) is never complete.\n */\nconst GENERATOR_ELEMENTS = new Set([\n ...['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'section', 'pre'],\n ...['ul', 'ol', 'li', 'blockquote', 'hr', 'br', 'img', 'input'],\n ...['table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'colgroup', 'col'],\n ...['a', 'span', 'code', 'strong', 'b', 'em', 'i', 'u', 's', 'del'],\n ...['strike', 'ins', 'sub', 'sup', 'mark', 'caption', 'figcaption'],\n ...['article', 'aside', 'header', 'footer', 'main', 'nav', 'address'],\n ...['hgroup', 'dl', 'dt', 'dd', 'details', 'summary', 'fieldset', 'legend'],\n]);\n\n/**\n * Elements whose content isn't prose: code, fallbacks a browser hides, and\n * drawings. The generator drops them, which is right; unwrapping them would\n * put a script, or an SVG's or formula's bare parts, in the document.\n */\nconst HIDDEN_CONTENT = new Set([\n ...['script', 'style', 'template', 'noscript', 'iframe', 'object'],\n ...['video', 'audio', 'canvas', 'svg', 'math'],\n]);\n\n/** `Node.TEXT_NODE`, which Node's globals lack. */\nconst TEXT_NODE = 3;\n\n/** The highlight browsers give `<mark>`; the generator drops it. */\nconst MARK_COLOR = '#FFFF00';\n\n/** `Node.ELEMENT_NODE`, which Node's globals lack too. */\nconst ELEMENT_NODE = 1;\n\n/**\n * Elements that start their own paragraph in a table cell. Anything else is\n * inline, and a run of it is kept together in one paragraph.\n */\nconst CELL_BLOCKS = new Set([\n ...['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'pre', 'blockquote'],\n ...['ul', 'ol', 'table', 'hr', 'section'],\n]);\n\n/**\n * Adjusts the parser's HTML for html-to-docx, which drops or flattens some of\n * what the browser preview renders:\n *\n * - Task list checkboxes: `<input>` is dropped, so done and pending items read\n * the same. Each becomes a ☒ or ☐ character.\n * - Inline code: `<code>` keeps the body font. Its text is wrapped in a span\n * naming the code block font, which the generator does carry over.\n * - Table cells: the generator makes each inline child of a cell its own\n * paragraph, so `**bold** text` would read as two lines. Each run of\n * inline content is wrapped in one `<p>`. `<th>` isn't bold, so its\n * content is wrapped in `<strong>`. Column alignment from GFM's `align`\n * attribute is ignored, but the same value as a `text-align` style is\n * honored.\n * - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT\n * paragraph for the structure patch to draw as a rule.\n * - Block quotes: the generator joins everything in a `<blockquote>` into one\n * justified paragraph. Its paragraphs and headings are kept apart instead,\n * left aligned and indented one step per level of nesting.\n * - Elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, `<my-element>`,\n * ...): the generator drops their text, so this keeps it. Some are\n * replaced by a span or `<em>` (see UNKNOWN_INLINE), the rest by their\n * children; content a browser wouldn't show as text (HIDDEN_CONTENT) is\n * left for the generator to drop. A placeholder like `<your-name>` that's\n * never closed isn't markup at all, so it stays as literal text, spelled\n * as in the source. `<mark>` loses its highlight, so it's set as a\n * shading.\n * - Footnotes: the reference and back links point into the page, which a\n * Word reader can't follow, so references keep only their number and the\n * back links (↩) go. So does the footnotes heading, which the page only\n * shows to screen readers.\n *\n * Only the HTML bound for the .docx changes; the preview keeps the original.\n */\nexport function prepareHtmlForDocx(html: string): string {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n\n for (const input of Array.from(\n dom.querySelectorAll('input[type=\"checkbox\"]')\n )) {\n const box = input.hasAttribute('checked')\n ? CHECKBOX.checked\n : CHECKBOX.unchecked;\n input.replaceWith(dom.createTextNode(box));\n }\n\n for (const code of Array.from(dom.querySelectorAll('code'))) {\n if (code.closest('pre')) continue;\n const span = dom.createElement('span');\n // A raw attribute, not `style.fontFamily`: see STYLE_PLACEHOLDER.\n span.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);\n span.append(...Array.from(code.childNodes));\n code.append(span);\n }\n\n for (const cell of Array.from(dom.querySelectorAll('th, td'))) {\n const align = cell.getAttribute('align');\n if (align) {\n (cell as HTMLElement).style.textAlign = align;\n cell.removeAttribute('align');\n }\n if (cell.localName === 'th' && cell.textContent?.trim()) {\n const strong = dom.createElement('strong');\n strong.append(...Array.from(cell.childNodes));\n cell.append(strong);\n }\n wrapInlineRuns(cell);\n }\n\n for (const quote of Array.from(dom.querySelectorAll('blockquote'))) {\n // Outermost first; each one unwraps its nested quotes as it goes.\n if (quote.isConnected) unwrapQuote(quote, 1);\n }\n\n const elements = Array.from(dom.body.querySelectorAll('*'));\n const startTags = new SourceStartTags(html, elements);\n for (const element of elements) {\n const name = element.localName;\n if (GENERATOR_ELEMENTS.has(name) || element.closest('pre')) continue;\n if (HIDDEN_CONTENT.has(name) || element.closest('svg, math')) continue;\n const kind = UNKNOWN_INLINE[name];\n if (!kind) {\n const children = Array.from(element.childNodes);\n if (isUnclosedPlaceholder(element, html)) {\n element.replaceWith(startTags.of(element), ...children);\n } else {\n element.replaceWith(...children);\n }\n continue;\n }\n if (kind === 'quote') {\n element.replaceWith('“', ...Array.from(element.childNodes), '”');\n continue;\n }\n const replacement = dom.createElement(kind === 'em' ? 'em' : 'span');\n if (kind === 'code') {\n replacement.setAttribute(STYLE_PLACEHOLDER, `font-family: ${CODE_FONT}`);\n }\n replacement.append(...Array.from(element.childNodes));\n element.replaceWith(replacement);\n }\n\n for (const mark of Array.from(dom.querySelectorAll('mark'))) {\n const span = dom.createElement('span');\n span.setAttribute(STYLE_PLACEHOLDER, `background-color: ${MARK_COLOR}`);\n span.append(...Array.from(mark.childNodes));\n mark.replaceWith(span);\n }\n\n for (const reference of Array.from(\n dom.querySelectorAll('a[data-footnote-ref]')\n )) {\n reference.replaceWith(...Array.from(reference.childNodes));\n }\n for (const backReference of Array.from(\n dom.querySelectorAll('a[data-footnote-backref]')\n )) {\n // The space before it, too, so the note doesn't end in one.\n const before = backReference.previousSibling;\n if (before?.nodeType === TEXT_NODE && before.textContent?.endsWith(' ')) {\n before.textContent = before.textContent.slice(0, -1);\n }\n backReference.remove();\n }\n dom.querySelector('section[data-footnotes] > h2')?.remove();\n\n for (const rule of Array.from(dom.querySelectorAll('hr'))) {\n const paragraph = dom.createElement('p');\n paragraph.setAttribute(STYLE_PLACEHOLDER, 'text-align: center');\n paragraph.textContent = RULE_TEXT;\n rule.replaceWith(paragraph);\n }\n\n // Only inside tags: text can't contain a raw `<`, so it's never touched.\n return dom.body.innerHTML.replace(/<[^>]+>/g, (tag) =>\n tag.replace(` ${STYLE_PLACEHOLDER}=`, ' style=')\n );\n}\n\n/**\n * Wraps each run of `cell`'s inline children (text, links, emphasis, `<br>`)\n * in a `<p>`, which the generator keeps as one paragraph. Whitespace-only runs\n * are left alone, so an empty cell stays empty.\n */\nfunction wrapInlineRuns(cell: Element): void {\n const document = cell.ownerDocument;\n let run: ChildNode[] = [];\n const flush = (before: ChildNode | null): void => {\n const hasContent = run.some(\n (node) =>\n node.nodeType === ELEMENT_NODE ||\n (node.nodeType === TEXT_NODE && node.textContent?.trim())\n );\n if (hasContent) {\n const paragraph = document.createElement('p');\n cell.insertBefore(paragraph, before);\n paragraph.append(...run);\n }\n run = [];\n };\n for (const child of Array.from(cell.childNodes)) {\n const isBlock =\n child.nodeType === ELEMENT_NODE &&\n CELL_BLOCKS.has((child as Element).localName);\n if (isBlock) {\n flush(child);\n } else {\n run.push(child);\n }\n }\n flush(null);\n}\n\n/**\n * Replaces `quote` with its children, indenting its paragraphs and headings\n * `depth` steps. Other blocks (lists, code, tables) keep their own layout, and\n * so does a quote in a list item: the generator indents that paragraph for the\n * list already, and a second indent would be invalid or move the bullet.\n */\nfunction unwrapQuote(quote: Element, depth: number): void {\n const inList = quote.closest('li') !== null;\n for (const child of Array.from(quote.children)) {\n if (child.localName === 'blockquote') {\n unwrapQuote(child, depth + 1);\n } else if (QUOTE_PARAGRAPHS.has(child.localName)) {\n const align = 'text-align: left';\n const layout = inList\n ? align\n : `margin-left: ${depth * QUOTE_INDENT_INCHES}in; ${align}`;\n const style = child.getAttribute(STYLE_PLACEHOLDER);\n child.setAttribute(\n STYLE_PLACEHOLDER,\n style ? `${style}; ${layout}` : layout\n );\n }\n }\n quote.replaceWith(...Array.from(quote.childNodes));\n}\n\n/**\n * Whether `element` is a made-up tag, like `<your-name>`, that `html` never\n * closes: a placeholder meant to be read, which a browser would hide.\n */\nfunction isUnclosedPlaceholder(element: Element, html: string): boolean {\n const isMadeUp =\n element.localName.includes('-') ||\n Object.prototype.toString.call(element) === '[object HTMLUnknownElement]';\n return isMadeUp && !html.toLowerCase().includes(`</${element.localName}`);\n}\n\n/**\n * Each element's start tag as written in the source, so a placeholder shown\n * as text keeps its exact spelling (case, quotes, entities). The DOM only\n * has decoded attribute values, which can't say whether the source wrote\n * `&` or `&`.\n */\nclass SourceStartTags {\n private readonly ordinals = new Map<Element, number>();\n private readonly counts = new Map<string, number>();\n private readonly tags = new Map<string, string[]>();\n\n constructor(\n private readonly html: string,\n elements: Element[]\n ) {\n // Document order is source order of start tags, so the nth <x> element\n // is the nth `<x` in the source.\n for (const element of elements) {\n const count = this.counts.get(element.localName) ?? 0;\n this.ordinals.set(element, count);\n this.counts.set(element.localName, count + 1);\n }\n }\n\n of(element: Element): string {\n const name = element.localName;\n let tags = this.tags.get(name);\n if (!tags) {\n // Quoted values may hold `>`. Each alternative starts with a different\n // character, so this can't backtrack.\n const escaped = name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const startTag = new RegExp(\n `<${escaped}(?=[\\\\s/>])(?:\"[^\"]*\"|'[^']*'|[^'\">])*>`,\n 'gi'\n );\n tags = this.html.match(startTag) ?? [];\n this.tags.set(name, tags);\n }\n // A mismatch means a `<x` the parser didn't turn into an element (in a\n // comment, say), so the ordinal can't be trusted: rebuild the tag.\n const tag =\n tags.length === this.counts.get(name)\n ? tags[this.ordinals.get(element) ?? -1]\n : undefined;\n return tag ?? rebuiltStartTag(element);\n }\n}\n\n/** A start tag for `element` rebuilt from the DOM. */\nfunction rebuiltStartTag(element: Element): string {\n const attributes = Array.from(element.attributes)\n .map(({ name, value }) => (value ? ` ${name}=\"${value}\"` : ` ${name}`))\n .join('');\n return `<${element.localName}${attributes}>`;\n}\n"]}
|
package/build/docx-images.d.ts
CHANGED
|
@@ -16,7 +16,9 @@ export declare const CONCURRENCY = 4;
|
|
|
16
16
|
* which html-to-docx embeds without downloading it again. An image that can't
|
|
17
17
|
* be fetched becomes its alt text, linked to its URL, where html-to-docx would
|
|
18
18
|
* drop it without a trace. Other sources it can't embed either, such as a
|
|
19
|
-
* relative path, keep their alt text too.
|
|
19
|
+
* relative path, keep their alt text too. So does a `data:` URI that isn't a
|
|
20
|
+
* PNG, JPEG, GIF, BMP or SVG image; one that is gets rewritten as base64 of
|
|
21
|
+
* the type its bytes show, which is the form html-to-docx reads.
|
|
20
22
|
*
|
|
21
23
|
* Each URL is fetched once, however many times it appears: at most
|
|
22
24
|
* MAX_IMAGES of them, CONCURRENCY at a time.
|
package/build/docx-images.js
CHANGED
|
@@ -22,19 +22,33 @@ const ATTEMPTS = 2;
|
|
|
22
22
|
*/
|
|
23
23
|
const GENERATOR_URL = /http(s)?:\/\/(\w+:?\w*@)?(\S+)(:\d+)?((?<=\.)\w+)+(\/([\w#!:.?+=&%@!\-/])*)?/i;
|
|
24
24
|
const WEB_URL = /^https?:\/\//i;
|
|
25
|
-
/**
|
|
25
|
+
/**
|
|
26
|
+
* Leading bytes of the bitmap formats Word embeds. An image is checked
|
|
27
|
+
* against them whatever its declared type: html-to-docx drops a file it can't
|
|
28
|
+
* read (with its alt text), and embeds a format Word can't show, such as
|
|
29
|
+
* HEIC, as a broken picture.
|
|
30
|
+
*/
|
|
26
31
|
const SIGNATURES = [
|
|
27
32
|
['image/png', [0x89, 0x50, 0x4e, 0x47]],
|
|
28
33
|
['image/jpeg', [0xff, 0xd8, 0xff]],
|
|
29
34
|
['image/gif', [0x47, 0x49, 0x46, 0x38]],
|
|
30
35
|
['image/bmp', [0x42, 0x4d]],
|
|
31
36
|
];
|
|
37
|
+
/** The other format Word embeds, recognized by its root element. */
|
|
38
|
+
const SVG_TYPE = 'image/svg+xml';
|
|
39
|
+
/** How far into a file to look for SVG_START. */
|
|
40
|
+
const SVG_SNIFF_BYTES = 4096;
|
|
41
|
+
/** `data:[type][;params][;base64],payload` */
|
|
42
|
+
const DATA_URI = /^data:([^,]*?)(;base64)?,(.*)$/is;
|
|
43
|
+
const PERCENT = 0x25;
|
|
32
44
|
/**
|
|
33
45
|
* Downloads each web image in `html` and swaps its `src` for a `data:` URI,
|
|
34
46
|
* which html-to-docx embeds without downloading it again. An image that can't
|
|
35
47
|
* be fetched becomes its alt text, linked to its URL, where html-to-docx would
|
|
36
48
|
* drop it without a trace. Other sources it can't embed either, such as a
|
|
37
|
-
* relative path, keep their alt text too.
|
|
49
|
+
* relative path, keep their alt text too. So does a `data:` URI that isn't a
|
|
50
|
+
* PNG, JPEG, GIF, BMP or SVG image; one that is gets rewritten as base64 of
|
|
51
|
+
* the type its bytes show, which is the form html-to-docx reads.
|
|
38
52
|
*
|
|
39
53
|
* Each URL is fetched once, however many times it appears: at most
|
|
40
54
|
* MAX_IMAGES of them, CONCURRENCY at a time.
|
|
@@ -60,9 +74,9 @@ export async function embedImages(html) {
|
|
|
60
74
|
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker));
|
|
61
75
|
for (const image of images) {
|
|
62
76
|
const src = image.getAttribute('src') ?? '';
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
77
|
+
const dataUri = /^data:/i.test(src)
|
|
78
|
+
? checkDataUri(src)
|
|
79
|
+
: downloads.get(src);
|
|
66
80
|
if (dataUri) {
|
|
67
81
|
image.setAttribute('src', dataUri);
|
|
68
82
|
}
|
|
@@ -72,6 +86,73 @@ export async function embedImages(html) {
|
|
|
72
86
|
}
|
|
73
87
|
return dom.body.innerHTML;
|
|
74
88
|
}
|
|
89
|
+
/**
|
|
90
|
+
* `src`, a `data:` URI, as base64 of the image type its bytes show, or null
|
|
91
|
+
* if it's malformed, too large, or not an image Word embeds.
|
|
92
|
+
*/
|
|
93
|
+
function checkDataUri(src) {
|
|
94
|
+
const match = DATA_URI.exec(src);
|
|
95
|
+
if (!match)
|
|
96
|
+
return null;
|
|
97
|
+
const [, type, base64, payload] = match;
|
|
98
|
+
// At most four characters of payload make one byte (an escaped base64
|
|
99
|
+
// character, %2B, is a quarter of three bytes), so one this long decodes
|
|
100
|
+
// to more than the limit: turn it away before decoding allocates it.
|
|
101
|
+
if (payload.length > MAX_IMAGE_BYTES * 4 + 4)
|
|
102
|
+
return null;
|
|
103
|
+
let bytes;
|
|
104
|
+
try {
|
|
105
|
+
bytes = base64 ? base64Decode(payload) : percentDecode(payload);
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
if (!bytes || bytes.length === 0 || bytes.length > MAX_IMAGE_BYTES) {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
const actual = imageType(type, bytes);
|
|
114
|
+
if (!actual)
|
|
115
|
+
return null;
|
|
116
|
+
return `data:${actual};base64,${Buffer.from(bytes).toString('base64')}`;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The bytes of a base64 `data:` payload, or null if it isn't base64. Decoded
|
|
120
|
+
* as a browser does (the fetch spec's forgiving-base64): percent-escapes and
|
|
121
|
+
* whitespace are allowed, any other stray character fails. `Buffer.from`
|
|
122
|
+
* alone skips stray characters, which would embed a corrupted picture.
|
|
123
|
+
*/
|
|
124
|
+
function base64Decode(payload) {
|
|
125
|
+
let text = new TextDecoder().decode(percentDecode(payload));
|
|
126
|
+
text = text.replace(/[\t\n\f\r ]+/g, '');
|
|
127
|
+
if (text.length % 4 === 0)
|
|
128
|
+
text = text.replace(/={1,2}$/, '');
|
|
129
|
+
if (text.length % 4 === 1 || !/^[A-Za-z0-9+/]*$/.test(text))
|
|
130
|
+
return null;
|
|
131
|
+
return Buffer.from(text, 'base64');
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* The bytes of a URL-encoded `data:` payload. A `%` without two hex digits
|
|
135
|
+
* after it stays a `%`, as in a browser, so `width="100%"` in an SVG works.
|
|
136
|
+
*/
|
|
137
|
+
function percentDecode(payload) {
|
|
138
|
+
// `%` and hex digits are ASCII, so escapes can be read off the UTF-8 bytes.
|
|
139
|
+
const encoded = new TextEncoder().encode(payload);
|
|
140
|
+
const bytes = new Uint8Array(encoded.length);
|
|
141
|
+
let length = 0;
|
|
142
|
+
for (let index = 0; index < encoded.length; index++) {
|
|
143
|
+
const hex = encoded[index] === PERCENT
|
|
144
|
+
? String.fromCharCode(...encoded.subarray(index + 1, index + 3))
|
|
145
|
+
: '';
|
|
146
|
+
if (/^[0-9a-f]{2}$/i.test(hex)) {
|
|
147
|
+
bytes[length++] = parseInt(hex, 16);
|
|
148
|
+
index += 2;
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
bytes[length++] = encoded[index];
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return bytes.subarray(0, length);
|
|
155
|
+
}
|
|
75
156
|
function isFetchable(src) {
|
|
76
157
|
return WEB_URL.test(src) && GENERATOR_URL.test(src);
|
|
77
158
|
}
|
|
@@ -140,16 +221,66 @@ async function readBody(response, tooLarge) {
|
|
|
140
221
|
return bytes;
|
|
141
222
|
}
|
|
142
223
|
/**
|
|
143
|
-
* The image's media type
|
|
144
|
-
*
|
|
145
|
-
*
|
|
224
|
+
* The image's media type, read from its first bytes: PNG, JPEG, GIF or BMP,
|
|
225
|
+
* whatever `declared` says, or SVG if it says so (or names no image type)
|
|
226
|
+
* and the file starts like one. Null for anything else, such as an error
|
|
227
|
+
* page served with 200, or HEIC, which html-to-docx would embed but Word
|
|
228
|
+
* can't show.
|
|
146
229
|
*/
|
|
147
|
-
function imageType(
|
|
148
|
-
const declared = contentType?.split(';')[0].trim().toLowerCase();
|
|
149
|
-
if (declared?.startsWith('image/'))
|
|
150
|
-
return declared;
|
|
230
|
+
function imageType(declared, bytes) {
|
|
151
231
|
const match = SIGNATURES.find(([, signature]) => signature.every((byte, index) => bytes[index] === byte));
|
|
152
|
-
|
|
232
|
+
if (match)
|
|
233
|
+
return match[0];
|
|
234
|
+
const type = declared?.split(';')[0].trim().toLowerCase() ?? '';
|
|
235
|
+
if (type !== SVG_TYPE && type.startsWith('image/'))
|
|
236
|
+
return null;
|
|
237
|
+
const head = new TextDecoder().decode(bytes.subarray(0, SVG_SNIFF_BYTES));
|
|
238
|
+
return startsWithSvg(head) ? SVG_TYPE : null;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Whether `text` is an SVG file: `<svg` first, after at most a byte-order
|
|
242
|
+
* mark, an XML declaration, comments and a doctype. Anchored, so an HTML page
|
|
243
|
+
* with an inline icon doesn't count. A scan rather than one regular
|
|
244
|
+
* expression, which backtracks exponentially on input like
|
|
245
|
+
* `<!----><!----><!--...` (a comment's end can also be read as part of a
|
|
246
|
+
* longer comment).
|
|
247
|
+
*/
|
|
248
|
+
function startsWithSvg(text) {
|
|
249
|
+
let at = text.startsWith('\uFEFF') ? 1 : 0;
|
|
250
|
+
const skipSpace = () => {
|
|
251
|
+
while (at < text.length && /\s/.test(text[at]))
|
|
252
|
+
at++;
|
|
253
|
+
};
|
|
254
|
+
const startsHere = (prefix) => text.slice(at, at + prefix.length).toLowerCase() === prefix;
|
|
255
|
+
/** Moves past `end`, searching from `from`; false if it never comes. */
|
|
256
|
+
const skipPast = (end, from) => {
|
|
257
|
+
const index = text.indexOf(end, from);
|
|
258
|
+
if (index === -1)
|
|
259
|
+
return false;
|
|
260
|
+
at = index + end.length;
|
|
261
|
+
return true;
|
|
262
|
+
};
|
|
263
|
+
skipSpace();
|
|
264
|
+
if (startsHere('<?xml')) {
|
|
265
|
+
if (!skipPast('>', at))
|
|
266
|
+
return false;
|
|
267
|
+
skipSpace();
|
|
268
|
+
}
|
|
269
|
+
for (;;) {
|
|
270
|
+
if (startsHere('<!--')) {
|
|
271
|
+
if (!skipPast('-->', at + 4))
|
|
272
|
+
return false;
|
|
273
|
+
}
|
|
274
|
+
else if (startsHere('<!doctype')) {
|
|
275
|
+
if (!skipPast('>', at))
|
|
276
|
+
return false;
|
|
277
|
+
}
|
|
278
|
+
else {
|
|
279
|
+
break;
|
|
280
|
+
}
|
|
281
|
+
skipSpace();
|
|
282
|
+
}
|
|
283
|
+
return startsHere('<svg') && /[\s>]/.test(text[at + 4] ?? '');
|
|
153
284
|
}
|
|
154
285
|
/**
|
|
155
286
|
* Puts the image's alt text where it was, as a link to `src` when that's a web
|
package/build/docx-images.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docx-images.js","sourceRoot":"","sources":["../src/docx-images.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,6E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AC,WAAW,CAAC,QAAQ,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC;QACjD,OAAO;IACT,CAAC;IACD,MAAM,IAAI,GAAG,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;IACzC,IAAI,CAAC,YAAY,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC/B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IACxB,KAAK,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["import { Buffer } from 'buffer';\n\n/** html-to-docx's own limit for one image (imageProcessing.maxImageSize). */\nexport const MAX_IMAGE_BYTES = 10 * 1024 * 1024;\n\n/**\n * The most distinct image URLs fetched for one document: html-to-docx keeps\n * at most this many in its image cache (imageProcessing.maxCacheEntries). The\n * rest keep their alt text.\n */\nexport const MAX_IMAGES = 100;\n\n/**\n * How many downloads run at once. html-to-docx fetched one at a time; a few\n * in parallel is faster without opening a connection per image.\n */\nexport const CONCURRENCY = 4;\n\n/** Per attempt; the second attempt waits twice as long, as html-to-docx's do. */\nconst TIMEOUT_MS = 5000;\nconst ATTEMPTS = 2;\n\n/**\n * The URLs html-to-docx downloads (its `isValidUrl`, without the `g` flag\n * that makes `test()` stateful), anchored so the whole `src` is the URL.\n * Requiring both means this module never fetches what it wouldn't.\n */\nconst GENERATOR_URL =\n /http(s)?:\\/\\/(\\w+:?\\w*@)?(\\S+)(:\\d+)?((?<=\\.)\\w+)+(\\/([\\w#!:.?+=&%@!\\-/])*)?/i;\nconst WEB_URL = /^https?:\\/\\//i;\n\n/** Leading bytes of the image formats Word embeds, for servers that don't say. */\nconst SIGNATURES: [string, number[]][] = [\n ['image/png', [0x89, 0x50, 0x4e, 0x47]],\n ['image/jpeg', [0xff, 0xd8, 0xff]],\n ['image/gif', [0x47, 0x49, 0x46, 0x38]],\n ['image/bmp', [0x42, 0x4d]],\n];\n\n/**\n * Downloads each web image in `html` and swaps its `src` for a `data:` URI,\n * which html-to-docx embeds without downloading it again. An image that can't\n * be fetched becomes its alt text, linked to its URL, where html-to-docx would\n * drop it without a trace. Other sources it can't embed either, such as a\n * relative path, keep their alt text too.\n *\n * Each URL is fetched once, however many times it appears: at most\n * MAX_IMAGES of them, CONCURRENCY at a time.\n */\nexport async function embedImages(html: string): Promise<string> {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n const images = Array.from(dom.querySelectorAll('img'));\n if (images.length === 0) return html;\n\n const urls = new Set<string>();\n for (const image of images) {\n const src = image.getAttribute('src') ?? '';\n if (isFetchable(src) && urls.size < MAX_IMAGES) urls.add(src);\n }\n\n const queue = Array.from(urls);\n const downloads = new Map<string, string | null>();\n const worker = async (): Promise<void> => {\n for (let url = queue.shift(); url !== undefined; url = queue.shift()) {\n downloads.set(url, await fetchImage(url));\n }\n };\n await Promise.all(\n Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker)\n );\n\n for (const image of images) {\n const src = image.getAttribute('src') ?? '';\n if (src.startsWith('data:')) continue;\n const dataUri = downloads.get(src);\n if (dataUri) {\n image.setAttribute('src', dataUri);\n } else {\n replaceWithAltText(image, src);\n }\n }\n\n return dom.body.innerHTML;\n}\n\nfunction isFetchable(src: string): boolean {\n return WEB_URL.test(src) && GENERATOR_URL.test(src);\n}\n\n/** The image at `url` as a `data:` URI, or null if it can't be fetched. */\nasync function fetchImage(url: string): Promise<string | null> {\n for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {\n const tooLarge = new AbortController();\n try {\n const response = await fetch(url, {\n signal: AbortSignal.any([\n tooLarge.signal,\n AbortSignal.timeout(TIMEOUT_MS * attempt),\n ]),\n });\n // Not found, forbidden or too large won't change on a retry.\n if (!response.ok) return null;\n if (Number(response.headers.get('content-length')) > MAX_IMAGE_BYTES) {\n tooLarge.abort();\n return null;\n }\n const bytes = await readBody(response, tooLarge);\n if (!bytes || bytes.length === 0) return null;\n const type = imageType(response.headers.get('content-type'), bytes);\n if (!type) return null;\n return `data:${type};base64,${Buffer.from(bytes).toString('base64')}`;\n } catch {\n if (tooLarge.signal.aborted) return null;\n // Offline, blocked by CORS or the CSP, or timed out: try once more.\n }\n }\n return null;\n}\n\n/**\n * The response body, read a chunk at a time so a server that sends more than\n * MAX_IMAGE_BYTES (whatever its Content-Length said) is cut off there rather\n * than held in memory. Null if it was too large.\n */\nasync function readBody(\n response: Response,\n tooLarge: AbortController\n): Promise<Uint8Array | null> {\n if (!response.body) {\n const bytes = new Uint8Array(await response.arrayBuffer());\n return bytes.length > MAX_IMAGE_BYTES ? null : bytes;\n }\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (\n let chunk = await reader.read();\n !chunk.done;\n chunk = await reader.read()\n ) {\n total += chunk.value.length;\n if (total > MAX_IMAGE_BYTES) {\n tooLarge.abort();\n await reader.cancel().catch(() => {});\n return null;\n }\n chunks.push(chunk.value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n\n/**\n * The image's media type: the server's, if it says it's an image, or else\n * read from the file's first bytes. Null for anything else (an error page\n * served with 200, say), which html-to-docx would fail to measure and drop.\n */\nfunction imageType(\n contentType: string | null,\n bytes: Uint8Array\n): string | null {\n const declared = contentType?.split(';')[0].trim().toLowerCase();\n if (declared?.startsWith('image/')) return declared;\n const match = SIGNATURES.find(([, signature]) =>\n signature.every((byte, index) => bytes[index] === byte)\n );\n return match?.[0] ?? null;\n}\n\n/**\n * Puts the image's alt text where it was, as a link to `src` when that's a web\n * URL and the image isn't already inside a link. With no alt text, the URL\n * itself is the text.\n */\nfunction replaceWithAltText(image: HTMLImageElement, src: string): void {\n const document = image.ownerDocument;\n const isWebUrl = WEB_URL.test(src);\n const text = image.getAttribute('alt')?.trim() || (isWebUrl ? src : '');\n if (!text) {\n image.remove();\n return;\n }\n if (!isWebUrl || image.closest('a')) {\n image.replaceWith(document.createTextNode(text));\n return;\n }\n const link = document.createElement('a');\n link.setAttribute('href', src);\n link.textContent = text;\n image.replaceWith(link);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"docx-images.js","sourceRoot":"","sources":["../src/docx-images.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,6EAA6E;AAC7E,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAEhD;;;;GAIG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,GAAG,CAAC;AAE9B;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,CAAC;AAE7B,iFAAiF;AACjF,MAAM,UAAU,GAAG,IAAI,CAAC;AACxB,MAAM,QAAQ,GAAG,CAAC,CAAC;AAEnB;;;;GAIG;AACH,MAAM,aAAa,GACjB,+EAA+E,CAAC;AAClF,MAAM,OAAO,GAAG,eAAe,CAAC;AAEhC;;;;;GAKG;AACH,MAAM,UAAU,GAAyB;IACvC,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IACvC,CAAC,YAAY,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IACvC,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;CAC5B,CAAC;AAEF,oEAAoE;AACpE,MAAM,QAAQ,GAAG,eAAe,CAAC;AAEjC,iDAAiD;AACjD,MAAM,eAAe,GAAG,IAAI,CAAC;AAE7B,8CAA8C;AAC9C,MAAM,QAAQ,GAAG,kCAAkC,CAAC;AAEpD,MAAM,OAAO,GAAG,IAAI,CAAC;AAErB;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,IAAY;IAC5C,MAAM,GAAG,GAAG,IAAI,S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,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["import { Buffer } from 'buffer';\n\n/** html-to-docx's own limit for one image (imageProcessing.maxImageSize). */\nexport const MAX_IMAGE_BYTES = 10 * 1024 * 1024;\n\n/**\n * The most distinct image URLs fetched for one document: html-to-docx keeps\n * at most this many in its image cache (imageProcessing.maxCacheEntries). The\n * rest keep their alt text.\n */\nexport const MAX_IMAGES = 100;\n\n/**\n * How many downloads run at once. html-to-docx fetched one at a time; a few\n * in parallel is faster without opening a connection per image.\n */\nexport const CONCURRENCY = 4;\n\n/** Per attempt; the second attempt waits twice as long, as html-to-docx's do. */\nconst TIMEOUT_MS = 5000;\nconst ATTEMPTS = 2;\n\n/**\n * The URLs html-to-docx downloads (its `isValidUrl`, without the `g` flag\n * that makes `test()` stateful), anchored so the whole `src` is the URL.\n * Requiring both means this module never fetches what it wouldn't.\n */\nconst GENERATOR_URL =\n /http(s)?:\\/\\/(\\w+:?\\w*@)?(\\S+)(:\\d+)?((?<=\\.)\\w+)+(\\/([\\w#!:.?+=&%@!\\-/])*)?/i;\nconst WEB_URL = /^https?:\\/\\//i;\n\n/**\n * Leading bytes of the bitmap formats Word embeds. An image is checked\n * against them whatever its declared type: html-to-docx drops a file it can't\n * read (with its alt text), and embeds a format Word can't show, such as\n * HEIC, as a broken picture.\n */\nconst SIGNATURES: [string, number[]][] = [\n ['image/png', [0x89, 0x50, 0x4e, 0x47]],\n ['image/jpeg', [0xff, 0xd8, 0xff]],\n ['image/gif', [0x47, 0x49, 0x46, 0x38]],\n ['image/bmp', [0x42, 0x4d]],\n];\n\n/** The other format Word embeds, recognized by its root element. */\nconst SVG_TYPE = 'image/svg+xml';\n\n/** How far into a file to look for SVG_START. */\nconst SVG_SNIFF_BYTES = 4096;\n\n/** `data:[type][;params][;base64],payload` */\nconst DATA_URI = /^data:([^,]*?)(;base64)?,(.*)$/is;\n\nconst PERCENT = 0x25;\n\n/**\n * Downloads each web image in `html` and swaps its `src` for a `data:` URI,\n * which html-to-docx embeds without downloading it again. An image that can't\n * be fetched becomes its alt text, linked to its URL, where html-to-docx would\n * drop it without a trace. Other sources it can't embed either, such as a\n * relative path, keep their alt text too. So does a `data:` URI that isn't a\n * PNG, JPEG, GIF, BMP or SVG image; one that is gets rewritten as base64 of\n * the type its bytes show, which is the form html-to-docx reads.\n *\n * Each URL is fetched once, however many times it appears: at most\n * MAX_IMAGES of them, CONCURRENCY at a time.\n */\nexport async function embedImages(html: string): Promise<string> {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n const images = Array.from(dom.querySelectorAll('img'));\n if (images.length === 0) return html;\n\n const urls = new Set<string>();\n for (const image of images) {\n const src = image.getAttribute('src') ?? '';\n if (isFetchable(src) && urls.size < MAX_IMAGES) urls.add(src);\n }\n\n const queue = Array.from(urls);\n const downloads = new Map<string, string | null>();\n const worker = async (): Promise<void> => {\n for (let url = queue.shift(); url !== undefined; url = queue.shift()) {\n downloads.set(url, await fetchImage(url));\n }\n };\n await Promise.all(\n Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker)\n );\n\n for (const image of images) {\n const src = image.getAttribute('src') ?? '';\n const dataUri = /^data:/i.test(src)\n ? checkDataUri(src)\n : downloads.get(src);\n if (dataUri) {\n image.setAttribute('src', dataUri);\n } else {\n replaceWithAltText(image, src);\n }\n }\n\n return dom.body.innerHTML;\n}\n\n/**\n * `src`, a `data:` URI, as base64 of the image type its bytes show, or null\n * if it's malformed, too large, or not an image Word embeds.\n */\nfunction checkDataUri(src: string): string | null {\n const match = DATA_URI.exec(src);\n if (!match) return null;\n const [, type, base64, payload] = match;\n // At most four characters of payload make one byte (an escaped base64\n // character, %2B, is a quarter of three bytes), so one this long decodes\n // to more than the limit: turn it away before decoding allocates it.\n if (payload.length > MAX_IMAGE_BYTES * 4 + 4) return null;\n let bytes: Uint8Array | null;\n try {\n bytes = base64 ? base64Decode(payload) : percentDecode(payload);\n } catch {\n return null;\n }\n if (!bytes || bytes.length === 0 || bytes.length > MAX_IMAGE_BYTES) {\n return null;\n }\n const actual = imageType(type, bytes);\n if (!actual) return null;\n return `data:${actual};base64,${Buffer.from(bytes).toString('base64')}`;\n}\n\n/**\n * The bytes of a base64 `data:` payload, or null if it isn't base64. Decoded\n * as a browser does (the fetch spec's forgiving-base64): percent-escapes and\n * whitespace are allowed, any other stray character fails. `Buffer.from`\n * alone skips stray characters, which would embed a corrupted picture.\n */\nfunction base64Decode(payload: string): Uint8Array | null {\n let text = new TextDecoder().decode(percentDecode(payload));\n text = text.replace(/[\\t\\n\\f\\r ]+/g, '');\n if (text.length % 4 === 0) text = text.replace(/={1,2}$/, '');\n if (text.length % 4 === 1 || !/^[A-Za-z0-9+/]*$/.test(text)) return null;\n return Buffer.from(text, 'base64');\n}\n\n/**\n * The bytes of a URL-encoded `data:` payload. A `%` without two hex digits\n * after it stays a `%`, as in a browser, so `width=\"100%\"` in an SVG works.\n */\nfunction percentDecode(payload: string): Uint8Array {\n // `%` and hex digits are ASCII, so escapes can be read off the UTF-8 bytes.\n const encoded = new TextEncoder().encode(payload);\n const bytes = new Uint8Array(encoded.length);\n let length = 0;\n for (let index = 0; index < encoded.length; index++) {\n const hex =\n encoded[index] === PERCENT\n ? String.fromCharCode(...encoded.subarray(index + 1, index + 3))\n : '';\n if (/^[0-9a-f]{2}$/i.test(hex)) {\n bytes[length++] = parseInt(hex, 16);\n index += 2;\n } else {\n bytes[length++] = encoded[index];\n }\n }\n return bytes.subarray(0, length);\n}\n\nfunction isFetchable(src: string): boolean {\n return WEB_URL.test(src) && GENERATOR_URL.test(src);\n}\n\n/** The image at `url` as a `data:` URI, or null if it can't be fetched. */\nasync function fetchImage(url: string): Promise<string | null> {\n for (let attempt = 1; attempt <= ATTEMPTS; attempt++) {\n const tooLarge = new AbortController();\n try {\n const response = await fetch(url, {\n signal: AbortSignal.any([\n tooLarge.signal,\n AbortSignal.timeout(TIMEOUT_MS * attempt),\n ]),\n });\n // Not found, forbidden or too large won't change on a retry.\n if (!response.ok) return null;\n if (Number(response.headers.get('content-length')) > MAX_IMAGE_BYTES) {\n tooLarge.abort();\n return null;\n }\n const bytes = await readBody(response, tooLarge);\n if (!bytes || bytes.length === 0) return null;\n const type = imageType(response.headers.get('content-type'), bytes);\n if (!type) return null;\n return `data:${type};base64,${Buffer.from(bytes).toString('base64')}`;\n } catch {\n if (tooLarge.signal.aborted) return null;\n // Offline, blocked by CORS or the CSP, or timed out: try once more.\n }\n }\n return null;\n}\n\n/**\n * The response body, read a chunk at a time so a server that sends more than\n * MAX_IMAGE_BYTES (whatever its Content-Length said) is cut off there rather\n * than held in memory. Null if it was too large.\n */\nasync function readBody(\n response: Response,\n tooLarge: AbortController\n): Promise<Uint8Array | null> {\n if (!response.body) {\n const bytes = new Uint8Array(await response.arrayBuffer());\n return bytes.length > MAX_IMAGE_BYTES ? null : bytes;\n }\n const reader = response.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (\n let chunk = await reader.read();\n !chunk.done;\n chunk = await reader.read()\n ) {\n total += chunk.value.length;\n if (total > MAX_IMAGE_BYTES) {\n tooLarge.abort();\n await reader.cancel().catch(() => {});\n return null;\n }\n chunks.push(chunk.value);\n }\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.length;\n }\n return bytes;\n}\n\n/**\n * The image's media type, read from its first bytes: PNG, JPEG, GIF or BMP,\n * whatever `declared` says, or SVG if it says so (or names no image type)\n * and the file starts like one. Null for anything else, such as an error\n * page served with 200, or HEIC, which html-to-docx would embed but Word\n * can't show.\n */\nfunction imageType(declared: string | null, bytes: Uint8Array): string | null {\n const match = SIGNATURES.find(([, signature]) =>\n signature.every((byte, index) => bytes[index] === byte)\n );\n if (match) return match[0];\n const type = declared?.split(';')[0].trim().toLowerCase() ?? '';\n if (type !== SVG_TYPE && type.startsWith('image/')) return null;\n const head = new TextDecoder().decode(bytes.subarray(0, SVG_SNIFF_BYTES));\n return startsWithSvg(head) ? SVG_TYPE : null;\n}\n\n/**\n * Whether `text` is an SVG file: `<svg` first, after at most a byte-order\n * mark, an XML declaration, comments and a doctype. Anchored, so an HTML page\n * with an inline icon doesn't count. A scan rather than one regular\n * expression, which backtracks exponentially on input like\n * `<!----><!----><!--...` (a comment's end can also be read as part of a\n * longer comment).\n */\nfunction startsWithSvg(text: string): boolean {\n let at = text.startsWith('\\uFEFF') ? 1 : 0;\n const skipSpace = (): void => {\n while (at < text.length && /\\s/.test(text[at] as string)) at++;\n };\n const startsHere = (prefix: string): boolean =>\n text.slice(at, at + prefix.length).toLowerCase() === prefix;\n /** Moves past `end`, searching from `from`; false if it never comes. */\n const skipPast = (end: string, from: number): boolean => {\n const index = text.indexOf(end, from);\n if (index === -1) return false;\n at = index + end.length;\n return true;\n };\n\n skipSpace();\n if (startsHere('<?xml')) {\n if (!skipPast('>', at)) return false;\n skipSpace();\n }\n for (;;) {\n if (startsHere('<!--')) {\n if (!skipPast('-->', at + 4)) return false;\n } else if (startsHere('<!doctype')) {\n if (!skipPast('>', at)) return false;\n } else {\n break;\n }\n skipSpace();\n }\n return startsHere('<svg') && /[\\s>]/.test(text[at + 4] ?? '');\n}\n\n/**\n * Puts the image's alt text where it was, as a link to `src` when that's a web\n * URL and the image isn't already inside a link. With no alt text, the URL\n * itself is the text.\n */\nfunction replaceWithAltText(image: HTMLImageElement, src: string): void {\n const document = image.ownerDocument;\n const isWebUrl = WEB_URL.test(src);\n const text = image.getAttribute('alt')?.trim() || (isWebUrl ? src : '');\n if (!text) {\n image.remove();\n return;\n }\n if (!isWebUrl || image.closest('a')) {\n image.replaceWith(document.createTextNode(text));\n return;\n }\n const link = document.createElement('a');\n link.setAttribute('href', src);\n link.textContent = text;\n image.replaceWith(link);\n}\n"]}
|
|
@@ -19,7 +19,16 @@ export interface DocumentStructure {
|
|
|
19
19
|
* - Section properties: the generator writes the body's `<w:sectPr>` (page
|
|
20
20
|
* size and margins) as its first child. The schema requires it last, and
|
|
21
21
|
* strict readers ignore it elsewhere, so it's moved to the end.
|
|
22
|
+
* - Image content types: the generator declares only JPEG, PNG and SVG in
|
|
23
|
+
* `[Content_Types].xml`, but embeds GIF and BMP too. Every part needs a
|
|
24
|
+
* declared type, and Word offers to repair a file that lacks one, so each
|
|
25
|
+
* image extension in `word/media/` gets a `<Default>`.
|
|
22
26
|
*/
|
|
23
27
|
export declare function patchStructure(wordDocument: Blob, structure: DocumentStructure): Promise<Blob>;
|
|
28
|
+
/**
|
|
29
|
+
* Adds a `<Default>` to `typesXml` for each image extension among `paths`
|
|
30
|
+
* under `word/media/` that it doesn't declare yet. Exported for testing.
|
|
31
|
+
*/
|
|
32
|
+
export declare function patchContentTypes(typesXml: string, paths: string[]): string;
|
|
24
33
|
/** Exported for testing. */
|
|
25
34
|
export declare function patchDocumentXml(documentXml: string, structure: DocumentStructure): string;
|
package/build/docx-structure.js
CHANGED
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import JSZip from 'jszip';
|
|
2
2
|
import { RULE_TEXT } from './docx-html.js';
|
|
3
3
|
import { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';
|
|
4
|
+
const CONTENT_TYPES = '[Content_Types].xml';
|
|
5
|
+
const CONTENT_TYPES_NS = 'http://schemas.openxmlformats.org/package/2006/content-types';
|
|
6
|
+
/** The media type of each image extension html-to-docx can write. */
|
|
7
|
+
const IMAGE_CONTENT_TYPES = {
|
|
8
|
+
png: 'image/png',
|
|
9
|
+
jpeg: 'image/jpeg',
|
|
10
|
+
jpg: 'image/jpeg',
|
|
11
|
+
gif: 'image/gif',
|
|
12
|
+
bmp: 'image/bmp',
|
|
13
|
+
svg: 'image/svg+xml',
|
|
14
|
+
};
|
|
4
15
|
/**
|
|
5
16
|
* Restores structure the generator drops or gets wrong:
|
|
6
17
|
*
|
|
@@ -15,6 +26,10 @@ import { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';
|
|
|
15
26
|
* - Section properties: the generator writes the body's `<w:sectPr>` (page
|
|
16
27
|
* size and margins) as its first child. The schema requires it last, and
|
|
17
28
|
* strict readers ignore it elsewhere, so it's moved to the end.
|
|
29
|
+
* - Image content types: the generator declares only JPEG, PNG and SVG in
|
|
30
|
+
* `[Content_Types].xml`, but embeds GIF and BMP too. Every part needs a
|
|
31
|
+
* declared type, and Word offers to repair a file that lacks one, so each
|
|
32
|
+
* image extension in `word/media/` gets a `<Default>`.
|
|
18
33
|
*/
|
|
19
34
|
export async function patchStructure(wordDocument, structure) {
|
|
20
35
|
const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());
|
|
@@ -24,14 +39,49 @@ export async function patchStructure(wordDocument, structure) {
|
|
|
24
39
|
}
|
|
25
40
|
const documentXml = await documentEntry.async('string');
|
|
26
41
|
const patched = patchDocumentXml(documentXml, structure);
|
|
27
|
-
|
|
42
|
+
const typesEntry = zip.file(CONTENT_TYPES);
|
|
43
|
+
const typesXml = typesEntry ? await typesEntry.async('string') : null;
|
|
44
|
+
const patchedTypes = typesXml === null
|
|
45
|
+
? null
|
|
46
|
+
: patchContentTypes(typesXml, Object.keys(zip.files));
|
|
47
|
+
if (patched === documentXml && patchedTypes === typesXml) {
|
|
28
48
|
return wordDocument;
|
|
29
49
|
}
|
|
30
50
|
zip.file('word/document.xml', patched);
|
|
51
|
+
if (patchedTypes !== null)
|
|
52
|
+
zip.file(CONTENT_TYPES, patchedTypes);
|
|
31
53
|
return new Blob([await zip.generateAsync({ type: 'arraybuffer' })], {
|
|
32
54
|
type: wordDocument.type,
|
|
33
55
|
});
|
|
34
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* Adds a `<Default>` to `typesXml` for each image extension among `paths`
|
|
59
|
+
* under `word/media/` that it doesn't declare yet. Exported for testing.
|
|
60
|
+
*/
|
|
61
|
+
export function patchContentTypes(typesXml, paths) {
|
|
62
|
+
const dom = new DOMParser().parseFromString(typesXml, 'application/xml');
|
|
63
|
+
const types = dom.documentElement;
|
|
64
|
+
const declared = new Set(Array.from(types.getElementsByTagNameNS(CONTENT_TYPES_NS, 'Default'), (d) => (d.getAttribute('Extension') ?? '').toLowerCase()));
|
|
65
|
+
let changed = false;
|
|
66
|
+
for (const path of paths) {
|
|
67
|
+
if (!path.startsWith('word/media/'))
|
|
68
|
+
continue;
|
|
69
|
+
const extension = /\.([^./]+)$/.exec(path)?.[1].toLowerCase();
|
|
70
|
+
const contentType = extension && IMAGE_CONTENT_TYPES[extension];
|
|
71
|
+
if (!contentType || declared.has(extension))
|
|
72
|
+
continue;
|
|
73
|
+
const entry = dom.createElementNS(CONTENT_TYPES_NS, 'Default');
|
|
74
|
+
entry.setAttribute('Extension', extension);
|
|
75
|
+
entry.setAttribute('ContentType', contentType);
|
|
76
|
+
// Defaults come before Overrides in the schema.
|
|
77
|
+
types.insertBefore(entry, types.getElementsByTagNameNS(CONTENT_TYPES_NS, 'Override')[0] ?? null);
|
|
78
|
+
declared.add(extension);
|
|
79
|
+
changed = true;
|
|
80
|
+
}
|
|
81
|
+
if (!changed)
|
|
82
|
+
return typesXml;
|
|
83
|
+
return keepXmlDeclaration(typesXml, new XMLSerializer().serializeToString(dom));
|
|
84
|
+
}
|
|
35
85
|
/** Exported for testing. */
|
|
36
86
|
export function patchDocumentXml(documentXml, structure) {
|
|
37
87
|
const dom = new DOMParser().parseFromString(documentXml, 'application/xml');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docx-structure.js","sourceRoot":"","sources":["../src/docx-structure.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,IAAI,IAAI,EAAE,MAAM,eAAe,CAAC;AAU9E;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,YAAkB,EAClB,SAA4B;IAE5B,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,SAAS,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G,CAAC,CAAC;IACzC,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,EAAE,GAAG,CAAC,CAAC;IAC5C,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;AACjD,CAAC;AAED,SAAS,aAAa,CAAC,GAAY;IACjC,MAAM,QAAQ,GAAG,GAAG,CAAC,aAAa,CAAC;IACnC,IAAI,IAAI,GAAG,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IACpC,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,IAAI,GAAG,GAAG,CAAC,YAAY,CACrB,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,QAAQ,CAAC,EACxC,GAAG,CAAC,UAAU,CACf,CAAC;IACJ,CAAC;IACD,IAAI,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC7C,6EAA6E;QAC7E,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC;IAClE,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,MAAe,EAAE,SAAiB;IAClD,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,CACvC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,YAAY,KAAK,IAAI,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,CACxE,CAAC;AACJ,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport { RULE_TEXT } from './docx-html.js';\nimport { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';\n\n/** What the source HTML says about the document's rules and tables. */\nexport interface DocumentStructure {\n /** How many `<hr>` the HTML has. */\n rules: number;\n /** For each `<table>` in document order, whether its first row is a header. */\n headerRows: boolean[];\n}\n\n/**\n * Restores structure the generator drops or gets wrong:\n *\n * - Horizontal rules: each centered RULE_TEXT paragraph that stands in for an\n * `<hr>` (see prepareHtmlForDocx) becomes an empty paragraph with a bottom\n * border. They're matched in order against the number of `<hr>`, so a\n * paragraph that only happens to say `* * *` is left alone once they run out.\n * - Header rows: a table's header row gets `<w:tblHeader/>`, so Word repeats\n * it at the top of each page the table spans.\n * - Table grids: the generator writes a second `<w:tblGrid>` between rows,\n * which the schema doesn't allow; only the first is kept.\n * - Section properties: the generator writes the body's `<w:sectPr>` (page\n * size and margins) as its first child. The schema requires it last, and\n * strict readers ignore it elsewhere, so it's moved to the end.\n */\nexport async function patchStructure(\n wordDocument: Blob,\n structure: DocumentStructure\n): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error(\n 'Cannot patch structure: document contains no word/document.xml'\n );\n }\n\n const documentXml = await documentEntry.async('string');\n const patched = patchDocumentXml(documentXml, structure);\n if (patched === documentXml) {\n return wordDocument;\n }\n\n zip.file('word/document.xml', patched);\n return new Blob([await zip.generateAsync({ type: 'arraybuffer' })], {\n type: wordDocument.type,\n });\n}\n\n/** Exported for testing. */\nexport function patchDocumentXml(\n documentXml: string,\n structure: DocumentStructure\n): string {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n let changed = false;\n\n let rulesLeft = structure.rules;\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n if (rulesLeft === 0) break;\n if (isRulePlaceholder(paragraph)) {\n drawRule(paragraph);\n rulesLeft--;\n changed = true;\n }\n }\n\n const tables = Array.from(dom.getElementsByTagNameNS(W_NS, 'tbl'));\n for (const [index, table] of tables.entries()) {\n const grids = children(table, 'tblGrid');\n for (const extra of grids.slice(1)) {\n extra.remove();\n changed = true;\n }\n\n const firstRow = children(table, 'tr')[0];\n if (structure.headerRows[index] && firstRow) {\n markHeaderRow(firstRow);\n changed = true;\n }\n }\n\n const body = dom.getElementsByTagNameNS(W_NS, 'body')[0];\n const sectPr = body && children(body, 'sectPr')[0];\n if (sectPr && body.lastElementChild !== sectPr) {\n body.appendChild(sectPr);\n changed = true;\n }\n\n if (!changed) {\n return documentXml;\n }\n return keepXmlDeclaration(\n documentXml,\n new XMLSerializer().serializeToString(dom)\n );\n}\n\nfunction isRulePlaceholder(paragraph: Element): boolean {\n const text = Array.from(paragraph.getElementsByTagNameNS(W_NS, 't'))\n .map((t) => t.textContent ?? '')\n .join('');\n const jc = children(children(paragraph, 'pPr')[0] ?? paragraph, 'jc')[0];\n return (\n text.trim() === RULE_TEXT && jc?.getAttributeNS(W_NS, 'val') === 'center'\n );\n}\n\n/** Replaces the paragraph's content with nothing but a bottom border. */\nfunction drawRule(paragraph: Element): void {\n const document = paragraph.ownerDocument;\n while (paragraph.firstChild) {\n paragraph.removeChild(paragraph.firstChild);\n }\n\n const pPr = paragraph.appendChild(document.createElementNS(W_NS, 'w:pPr'));\n const pBdr = pPr.appendChild(document.createElementNS(W_NS, 'w:pBdr'));\n const bottom = pBdr.appendChild(document.createElementNS(W_NS, 'w:bottom'));\n bottom.setAttributeNS(W_NS, 'w:val', 'single');\n bottom.setAttributeNS(W_NS, 'w:sz', '6');\n bottom.setAttributeNS(W_NS, 'w:space', '1');\n bottom.setAttributeNS(W_NS, 'w:color', 'auto');\n}\n\nfunction markHeaderRow(row: Element): void {\n const document = row.ownerDocument;\n let trPr = children(row, 'trPr')[0];\n if (!trPr) {\n trPr = row.insertBefore(\n document.createElementNS(W_NS, 'w:trPr'),\n row.firstChild\n );\n }\n if (children(trPr, 'tblHeader').length === 0) {\n // The generator writes at most cantSplit here, which comes before tblHeader.\n trPr.appendChild(document.createElementNS(W_NS, 'w:tblHeader'));\n }\n}\n\nfunction children(parent: Element, localName: string): Element[] {\n return Array.from(parent.children).filter(\n (child) => child.namespaceURI === W_NS && child.localName === localName\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"docx-structure.js","sourceRoot":"","sources":["../src/docx-structure.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EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAC/C,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;IACzC,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,EAAE,GAAG,CAAC,CAAC;IAC5C,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC;AACjD,CAAC;AAED,SAAS,aAAa,CAAC,GAAY;IACjC,MAAM,QAAQ,GAAG,GAAG,CAAC,aAAa,CAAC;IACnC,IAAI,IAAI,GAAG,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IACpC,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,IAAI,GAAG,GAAG,CAAC,YAAY,CACrB,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,QAAQ,CAAC,EACxC,GAAG,CAAC,UAAU,CACf,CAAC;IACJ,CAAC;IACD,IAAI,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC7C,6EAA6E;QAC7E,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC;IAClE,CAAC;AACH,CAAC;AAED,SAAS,QAAQ,CAAC,MAAe,EAAE,SAAiB;IAClD,OAAO,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,MAAM,CACvC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,YAAY,KAAK,IAAI,IAAI,KAAK,CAAC,SAAS,KAAK,SAAS,CACxE,CAAC;AACJ,CAAC","sourcesContent":["import JSZip from 'jszip';\nimport { RULE_TEXT } from './docx-html.js';\nimport { keepXmlDeclaration, WORDPROCESSING_NS as W_NS } from './xml-part.js';\n\nconst CONTENT_TYPES = '[Content_Types].xml';\nconst CONTENT_TYPES_NS =\n 'http://schemas.openxmlformats.org/package/2006/content-types';\n\n/** The media type of each image extension html-to-docx can write. */\nconst IMAGE_CONTENT_TYPES: Record<string, string> = {\n png: 'image/png',\n jpeg: 'image/jpeg',\n jpg: 'image/jpeg',\n gif: 'image/gif',\n bmp: 'image/bmp',\n svg: 'image/svg+xml',\n};\n\n/** What the source HTML says about the document's rules and tables. */\nexport interface DocumentStructure {\n /** How many `<hr>` the HTML has. */\n rules: number;\n /** For each `<table>` in document order, whether its first row is a header. */\n headerRows: boolean[];\n}\n\n/**\n * Restores structure the generator drops or gets wrong:\n *\n * - Horizontal rules: each centered RULE_TEXT paragraph that stands in for an\n * `<hr>` (see prepareHtmlForDocx) becomes an empty paragraph with a bottom\n * border. They're matched in order against the number of `<hr>`, so a\n * paragraph that only happens to say `* * *` is left alone once they run out.\n * - Header rows: a table's header row gets `<w:tblHeader/>`, so Word repeats\n * it at the top of each page the table spans.\n * - Table grids: the generator writes a second `<w:tblGrid>` between rows,\n * which the schema doesn't allow; only the first is kept.\n * - Section properties: the generator writes the body's `<w:sectPr>` (page\n * size and margins) as its first child. The schema requires it last, and\n * strict readers ignore it elsewhere, so it's moved to the end.\n * - Image content types: the generator declares only JPEG, PNG and SVG in\n * `[Content_Types].xml`, but embeds GIF and BMP too. Every part needs a\n * declared type, and Word offers to repair a file that lacks one, so each\n * image extension in `word/media/` gets a `<Default>`.\n */\nexport async function patchStructure(\n wordDocument: Blob,\n structure: DocumentStructure\n): Promise<Blob> {\n const zip = await JSZip.loadAsync(await wordDocument.arrayBuffer());\n const documentEntry = zip.file('word/document.xml');\n if (!documentEntry) {\n throw new Error(\n 'Cannot patch structure: document contains no word/document.xml'\n );\n }\n\n const documentXml = await documentEntry.async('string');\n const patched = patchDocumentXml(documentXml, structure);\n const typesEntry = zip.file(CONTENT_TYPES);\n const typesXml = typesEntry ? await typesEntry.async('string') : null;\n const patchedTypes =\n typesXml === null\n ? null\n : patchContentTypes(typesXml, Object.keys(zip.files));\n if (patched === documentXml && patchedTypes === typesXml) {\n return wordDocument;\n }\n\n zip.file('word/document.xml', patched);\n if (patchedTypes !== null) zip.file(CONTENT_TYPES, patchedTypes);\n return new Blob([await zip.generateAsync({ type: 'arraybuffer' })], {\n type: wordDocument.type,\n });\n}\n\n/**\n * Adds a `<Default>` to `typesXml` for each image extension among `paths`\n * under `word/media/` that it doesn't declare yet. Exported for testing.\n */\nexport function patchContentTypes(typesXml: string, paths: string[]): string {\n const dom = new DOMParser().parseFromString(typesXml, 'application/xml');\n const types = dom.documentElement;\n const declared = new Set(\n Array.from(types.getElementsByTagNameNS(CONTENT_TYPES_NS, 'Default'), (d) =>\n (d.getAttribute('Extension') ?? '').toLowerCase()\n )\n );\n let changed = false;\n for (const path of paths) {\n if (!path.startsWith('word/media/')) continue;\n const extension = /\\.([^./]+)$/.exec(path)?.[1].toLowerCase();\n const contentType = extension && IMAGE_CONTENT_TYPES[extension];\n if (!contentType || declared.has(extension)) continue;\n const entry = dom.createElementNS(CONTENT_TYPES_NS, 'Default');\n entry.setAttribute('Extension', extension);\n entry.setAttribute('ContentType', contentType);\n // Defaults come before Overrides in the schema.\n types.insertBefore(\n entry,\n types.getElementsByTagNameNS(CONTENT_TYPES_NS, 'Override')[0] ?? null\n );\n declared.add(extension);\n changed = true;\n }\n if (!changed) return typesXml;\n return keepXmlDeclaration(\n typesXml,\n new XMLSerializer().serializeToString(dom)\n );\n}\n\n/** Exported for testing. */\nexport function patchDocumentXml(\n documentXml: string,\n structure: DocumentStructure\n): string {\n const dom = new DOMParser().parseFromString(documentXml, 'application/xml');\n let changed = false;\n\n let rulesLeft = structure.rules;\n for (const paragraph of Array.from(dom.getElementsByTagNameNS(W_NS, 'p'))) {\n if (rulesLeft === 0) break;\n if (isRulePlaceholder(paragraph)) {\n drawRule(paragraph);\n rulesLeft--;\n changed = true;\n }\n }\n\n const tables = Array.from(dom.getElementsByTagNameNS(W_NS, 'tbl'));\n for (const [index, table] of tables.entries()) {\n const grids = children(table, 'tblGrid');\n for (const extra of grids.slice(1)) {\n extra.remove();\n changed = true;\n }\n\n const firstRow = children(table, 'tr')[0];\n if (structure.headerRows[index] && firstRow) {\n markHeaderRow(firstRow);\n changed = true;\n }\n }\n\n const body = dom.getElementsByTagNameNS(W_NS, 'body')[0];\n const sectPr = body && children(body, 'sectPr')[0];\n if (sectPr && body.lastElementChild !== sectPr) {\n body.appendChild(sectPr);\n changed = true;\n }\n\n if (!changed) {\n return documentXml;\n }\n return keepXmlDeclaration(\n documentXml,\n new XMLSerializer().serializeToString(dom)\n );\n}\n\nfunction isRulePlaceholder(paragraph: Element): boolean {\n const text = Array.from(paragraph.getElementsByTagNameNS(W_NS, 't'))\n .map((t) => t.textContent ?? '')\n .join('');\n const jc = children(children(paragraph, 'pPr')[0] ?? paragraph, 'jc')[0];\n return (\n text.trim() === RULE_TEXT && jc?.getAttributeNS(W_NS, 'val') === 'center'\n );\n}\n\n/** Replaces the paragraph's content with nothing but a bottom border. */\nfunction drawRule(paragraph: Element): void {\n const document = paragraph.ownerDocument;\n while (paragraph.firstChild) {\n paragraph.removeChild(paragraph.firstChild);\n }\n\n const pPr = paragraph.appendChild(document.createElementNS(W_NS, 'w:pPr'));\n const pBdr = pPr.appendChild(document.createElementNS(W_NS, 'w:pBdr'));\n const bottom = pBdr.appendChild(document.createElementNS(W_NS, 'w:bottom'));\n bottom.setAttributeNS(W_NS, 'w:val', 'single');\n bottom.setAttributeNS(W_NS, 'w:sz', '6');\n bottom.setAttributeNS(W_NS, 'w:space', '1');\n bottom.setAttributeNS(W_NS, 'w:color', 'auto');\n}\n\nfunction markHeaderRow(row: Element): void {\n const document = row.ownerDocument;\n let trPr = children(row, 'trPr')[0];\n if (!trPr) {\n trPr = row.insertBefore(\n document.createElementNS(W_NS, 'w:trPr'),\n row.firstChild\n );\n }\n if (children(trPr, 'tblHeader').length === 0) {\n // The generator writes at most cantSplit here, which comes before tblHeader.\n trPr.appendChild(document.createElementNS(W_NS, 'w:tblHeader'));\n }\n}\n\nfunction children(parent: Element, localName: string): Element[] {\n return Array.from(parent.children).filter(\n (child) => child.namespaceURI === W_NS && child.localName === localName\n );\n}\n"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Checks for input that isn't Markdown, shared by the page (src/index.ts) and
|
|
2
|
+
// the `md2w` CLI (src/cli.ts) so both refuse the same files.
|
|
3
|
+
/** Word and other word-processor files: the reverse direction, word2md's job. */
|
|
4
|
+
export const WORD_FILE = /\.(docx?|dotx?|odt|rtf)$/i;
|
|
5
|
+
/** A file that's mostly binary isn't Markdown. NUL never appears in text. */
|
|
6
|
+
export function looksBinary(text) {
|
|
7
|
+
return text.slice(0, 8192).includes('\u0000');
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=input-checks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"input-checks.js","sourceRoot":"","sources":["../src/input-checks.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,6DAA6D;AAE7D,iFAAiF;AACjF,MAAM,CAAC,MAAM,SAAS,GAAG,2BAA2B,CAAC;AAErD,6EAA6E;AAC7E,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;AAChD,CAAC","sourcesContent":["// Checks for input that isn't Markdown, shared by the page (src/index.ts) and\n// the `md2w` CLI (src/cli.ts) so both refuse the same files.\n\n/** Word and other word-processor files: the reverse direction, word2md's job. */\nexport const WORD_FILE = /\\.(docx?|dotx?|odt|rtf)$/i;\n\n/** A file that's mostly binary isn't Markdown. NUL never appears in text. */\nexport function looksBinary(text: string): boolean {\n return text.slice(0, 8192).includes('\\u0000');\n}\n"]}
|
|
@@ -16,10 +16,11 @@ export declare function renderPreviewHtml(markdown: string): string;
|
|
|
16
16
|
*/
|
|
17
17
|
export declare function extractTitle(markdown: string): string | null;
|
|
18
18
|
/**
|
|
19
|
-
* Convert a string into a URL/filename-safe slug.
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* and
|
|
23
|
-
*
|
|
19
|
+
* Convert a string into a URL/filename-safe slug, used to name the download.
|
|
20
|
+
* NFC-normalizes and lowercases, keeps letters, digits, and the combining
|
|
21
|
+
* marks attached to them in any script (so 关于开展2026年工作的通知,
|
|
22
|
+
* Привет мир, and Café survive), strips everything else, including punctuation and the characters file
|
|
23
|
+
* systems reject (/ \ : * ? " < > |), then turns runs of whitespace,
|
|
24
|
+
* underscores, and hyphens into one hyphen.
|
|
24
25
|
*/
|
|
25
26
|
export declare function slugify(text: string): string;
|
package/build/markdown-parser.js
CHANGED
|
@@ -90,20 +90,26 @@ function plainText(tokens) {
|
|
|
90
90
|
.join('');
|
|
91
91
|
}
|
|
92
92
|
/**
|
|
93
|
-
* Convert a string into a URL/filename-safe slug.
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
* and
|
|
97
|
-
*
|
|
93
|
+
* Convert a string into a URL/filename-safe slug, used to name the download.
|
|
94
|
+
* NFC-normalizes and lowercases, keeps letters, digits, and the combining
|
|
95
|
+
* marks attached to them in any script (so 关于开展2026年工作的通知,
|
|
96
|
+
* Привет мир, and Café survive), strips everything else, including punctuation and the characters file
|
|
97
|
+
* systems reject (/ \ : * ? " < > |), then turns runs of whitespace,
|
|
98
|
+
* underscores, and hyphens into one hyphen.
|
|
98
99
|
*/
|
|
99
100
|
export function slugify(text) {
|
|
100
|
-
return text
|
|
101
|
+
return (text
|
|
102
|
+
.normalize('NFC')
|
|
101
103
|
.toLowerCase()
|
|
102
104
|
.trim()
|
|
103
|
-
|
|
105
|
+
// A mark left with nothing to attach to (the U+FE0F after an emoji) is
|
|
106
|
+
// invisible, and would keep an all-emoji title from falling back to
|
|
107
|
+
// "document".
|
|
108
|
+
.replace(/(?<![\p{L}\p{M}\p{N}])\p{M}+/gu, '')
|
|
109
|
+
.replace(/[^\p{L}\p{M}\p{N}\s_-]/gu, '')
|
|
104
110
|
.replace(/[\s_]+/g, '-')
|
|
105
111
|
.replace(/-+/g, '-')
|
|
106
|
-
.replace(/^-+|-+$/g, '');
|
|
112
|
+
.replace(/^-+|-+$/g, ''));
|
|
107
113
|
}
|
|
108
114
|
const HTML_ESCAPES = {
|
|
109
115
|
'&': '&',
|