markdown-to-word 0.4.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 CHANGED
@@ -1,9 +1,15 @@
1
1
  # Markdown to Word
2
2
 
3
- [![CI](https://github.com/benbalter/markdown-to-word-js/actions/workflows/ci.yml/badge.svg)](https://github.com/benbalter/markdown-to-word-js/actions/workflows/ci.yml)
3
+ [![npm version](https://img.shields.io/npm/v/markdown-to-word.svg)](https://www.npmjs.com/package/markdown-to-word) [![npm downloads](https://img.shields.io/npm/dm/markdown-to-word.svg)](https://www.npmjs.com/package/markdown-to-word) [![MCP registry](https://img.shields.io/badge/MCP_registry-io.github.benbalter%2Fmarkdown--to--word-blue)](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.benbalter/markdown-to-word) [![CI](https://github.com/benbalter/markdown-to-word-js/actions/workflows/ci.yml/badge.svg)](https://github.com/benbalter/markdown-to-word-js/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/npm/l/markdown-to-word.svg)](https://github.com/benbalter/markdown-to-word-js/blob/main/LICENSE)
4
4
 
5
5
  Convert GitHub Flavored Markdown to a formatted Word (`.docx`) document, entirely in your browser, at **[md2word.app](https://md2word.app)**. Nothing is uploaded.
6
6
 
7
+ The same converter is on npm as [`markdown-to-word`](https://www.npmjs.com/package/markdown-to-word): a [command-line tool](#command-line), a [Node library](#use-it-from-code), and an [MCP server](#mcp-server) for AI agents, no clone required:
8
+
9
+ ```console
10
+ npx markdown-to-word input.md
11
+ ```
12
+
7
13
  It's the mirror image of [word2md.com](https://word2md.com) ([word-to-markdown-js](https://github.com/benbalter/word-to-markdown-js)), which goes the other way, and the successor to [markdown_to_word](https://github.com/benbalter/markdown_to_word), the original Ruby gem and web demo, first published in 2015 and now archived.
8
14
 
9
15
  ## Usage
@@ -82,7 +88,7 @@ const blob = await convertMarkdownToWord(markdown, {
82
88
 
83
89
  ## Privacy
84
90
 
85
- Conversion happens entirely in your browser: your Markdown and the Word document never leave your device. Images your Markdown links to load from the sites that host them, like on any web page. md2word.app uses cookie-free Cloudflare Web Analytics; a local or self-hosted copy has no analytics. Raw HTML in the preview is sanitized, so a shared file can't run script. See the [privacy policy](https://md2word.app/privacy/).
91
+ Conversion happens entirely in your browser: your Markdown and the Word document never leave your device. Images your Markdown links to load from the sites that host them, like on any web page. md2word.app uses cookie-free Cloudflare Web Analytics and keeps an anonymous count of conversions (whether each succeeded and if not why, the page's language, and how it started; never the content, filename, size, or anything that identifies you); a local or self-hosted copy sends neither. Raw HTML in the preview is sanitized, so a shared file can't run script. See the [privacy policy](https://md2word.app/privacy/).
86
92
 
87
93
  ## Limitations
88
94
 
@@ -131,6 +137,8 @@ Options:
131
137
 
132
138
  `md2w mcp` runs a local [Model Context Protocol](https://modelcontextprotocol.io) server on stdio, so AI agents can turn Markdown into Word documents on your machine. Like the website, it never uploads anything: the server converts in-process and writes the `.docx` to disk.
133
139
 
140
+ In Claude Desktop, it's one click: [download `markdown-to-word.mcpb`](https://github.com/benbalter/markdown-to-word-js/releases/latest/download/markdown-to-word.mcpb) and double-click it. Claude Desktop installs it as an extension. You don't need Node or a terminal, since Claude Desktop includes Node.
141
+
134
142
  Add it to Claude Code:
135
143
 
136
144
  ```console
package/build/cli.js CHANGED
@@ -5,9 +5,10 @@
5
5
  // entry, which supplies the DOM APIs the converter needs.
6
6
  import { Command, Option } from 'commander';
7
7
  import { createRequire } from 'module';
8
- import { mkdir, readFile, writeFile } from 'fs/promises';
8
+ import { mkdir, readFile, stat, writeFile } from 'fs/promises';
9
9
  import path from 'path';
10
10
  import { convertMarkdownToWord, FONT_PRESETS } from './node.js';
11
+ import { looksBinary, WORD_FILE } from './input-checks.js';
11
12
  // Read our own version from package.json. createRequire resolves relative to
12
13
  // this module, so `../package.json` points at the package root both from the
13
14
  // TypeScript source (src/) and the compiled CLI (build/) after publish.
@@ -24,6 +25,50 @@ function defaultOutputPath(input) {
24
25
  const { dir, name } = path.parse(input);
25
26
  return path.join(dir, `${name}.docx`);
26
27
  }
28
+ /**
29
+ * Whether `a` and `b` are the same file on disk. Compares inodes, not paths,
30
+ * so a symlink or a different case on a case-insensitive disk still counts.
31
+ * BigInt stats, because some filesystems hand out inode numbers above
32
+ * Number.MAX_SAFE_INTEGER, where two different files could round to the same
33
+ * number.
34
+ */
35
+ async function isSameFile(a, b) {
36
+ const [statA, statB] = await Promise.all([
37
+ stat(a, { bigint: true }).catch(() => undefined),
38
+ stat(b, { bigint: true }).catch(() => undefined),
39
+ ]);
40
+ return (statA !== undefined &&
41
+ statB !== undefined &&
42
+ statA.dev === statB.dev &&
43
+ statA.ino === statB.ino);
44
+ }
45
+ /**
46
+ * `value` as one shell word, for commands we print for the user to copy.
47
+ * Plain names stay bare so the common case reads cleanly.
48
+ */
49
+ function shellQuote(value) {
50
+ return /^[\w@%+=:,./-]+$/.test(value)
51
+ ? value
52
+ : `'${value.replaceAll("'", "'\\''")}'`;
53
+ }
54
+ // html-to-docx logs as it works: debug lines with console.log, which would
55
+ // land in front of a .docx written to stdout, and skipped images or a missing
56
+ // sharp with console.warn and console.error. The convert action sends the
57
+ // console.log family to stderr, and with -q drops all of it while the
58
+ // generator runs; our own errors print afterward. (`md2w mcp` has its own
59
+ // guard in src/mcp.ts.)
60
+ async function withConsoleSilenced(run) {
61
+ const saved = { ...console };
62
+ const silent = () => { };
63
+ console.log = console.info = console.debug = silent;
64
+ console.warn = console.error = silent;
65
+ try {
66
+ return await run();
67
+ }
68
+ finally {
69
+ Object.assign(console, saved);
70
+ }
71
+ }
27
72
  const EXAMPLES = `
28
73
  Examples:
29
74
  $ md2w report.md # writes report.docx
@@ -57,6 +102,8 @@ const convert = program
57
102
  .option('-q, --quiet', 'Print nothing to stderr except errors')
58
103
  .addHelpText('after', EXAMPLES)
59
104
  .action(async (file, options) => {
105
+ const toStderr = console.error.bind(console);
106
+ console.log = console.info = console.debug = toStderr;
60
107
  const note = (message) => {
61
108
  if (!options.quiet)
62
109
  console.error(message);
@@ -68,6 +115,11 @@ const convert = program
68
115
  if (!file && !fromStdin) {
69
116
  convert.help({ error: true });
70
117
  }
118
+ // A Word file would otherwise be read as garbage text and, with no -o,
119
+ // written back over itself as report.docx.
120
+ if (!fromStdin && WORD_FILE.test(file)) {
121
+ throw new Error(`${file} is already a Word document. To turn it into Markdown, use word2md.com or its CLI: npx word-to-markdown ${shellQuote(file)} > ${shellQuote(`${path.parse(file).name}.md`)}`);
122
+ }
71
123
  if (fromStdin && !options.output) {
72
124
  throw new Error('Reading from stdin, so there is no file name to name the .docx after. Pass -o report.docx (or -o - for stdout).');
73
125
  }
@@ -84,13 +136,24 @@ const convert = program
84
136
  ? 'Nothing was piped to stdin. Pass a Markdown file, or pipe one in: md2w -o report.docx < report.md'
85
137
  : `${file} is empty.`);
86
138
  }
87
- const blob = await convertMarkdownToWord(markdown, {
139
+ if (looksBinary(markdown)) {
140
+ throw new Error(`${fromStdin ? 'stdin' : file} doesn't look like a Markdown or text file, so it can't be converted.`);
141
+ }
142
+ const output = options.output ?? defaultOutputPath(file);
143
+ if (output !== '-' &&
144
+ !fromStdin &&
145
+ (await isSameFile(output, file))) {
146
+ throw new Error(`${output} is the input file, so writing the .docx there would overwrite it. Pass a different -o.`);
147
+ }
148
+ const generate = () => convertMarkdownToWord(markdown, {
88
149
  fontPreset: options.fontPreset
89
150
  ? FONT_PRESETS[options.fontPreset]
90
151
  : undefined,
91
152
  });
153
+ const blob = options.quiet
154
+ ? await withConsoleSilenced(generate)
155
+ : await generate();
92
156
  const bytes = Buffer.from(await blob.arrayBuffer());
93
- const output = options.output ?? defaultOutputPath(file);
94
157
  if (output === '-') {
95
158
  process.stdout.write(bytes);
96
159
  }
package/build/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA,wEAAwE;AACxE,0EAA0E;AAC1E,2EAA2E;AAC3E,0DAA0D;AAE1D,OAAO,EAAE,OAAO,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CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YACvD,MAAM,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;YAC/B,IAAI,CAAC,SAAS,MAAM,EAAE,CAAC,CAAC;QAC1B,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CACX,QAAQ,EACR,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CACvD,CAAC;QACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC,CAAC,CAAC;AAEL,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC","sourcesContent":["#!/usr/bin/env node\n\n// The `md2w` command (also installed as `markdown-to-word`): converts a\n// Markdown file, or stdin, to a .docx on disk. Patterned on word2md.com's\n// `w2m` CLI (benbalter/word-to-markdown-js), in reverse. It loads the Node\n// entry, which supplies the DOM APIs the converter needs.\n\nimport { Command, Option } from 'commander';\nimport { createRequire } from 'module';\nimport { mkdir, readFile, writeFile } from 'fs/promises';\nimport path from 'path';\nimport { convertMarkdownToWord, FONT_PRESETS } from './node.js';\n\n// Read our own version from package.json. createRequire resolves relative to\n// this module, so `../package.json` points at the package root both from the\n// TypeScript source (src/) and the compiled CLI (build/) after publish.\nconst require = createRequire(import.meta.url);\nconst { version } = require('../package.json') as { version: string };\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString('utf8');\n}\n\n/** `notes.md` → `notes.docx`, next to the input. */\nfunction defaultOutputPath(input: string): string {\n const { dir, name } = path.parse(input);\n return path.join(dir, `${name}.docx`);\n}\n\nconst EXAMPLES = `\nExamples:\n $ md2w report.md # writes report.docx\n $ md2w report.md -o out/report.docx\n $ md2w --font-preset chinese-official notice.md\n $ cat reply.md | md2w -o reply.docx\n $ md2w - -o - < report.md > report.docx`;\n\nconst program = new Command();\nprogram.name('md2w');\nprogram.description('Convert Markdown to a formatted Word (.docx) document');\nprogram.version(version);\nprogram.addHelpText(\n 'after',\n `\\nRun \"md2w convert --help\" for all conversion options.\\n${EXAMPLES}`\n);\nprogram\n .command('mcp')\n .description(\n 'Run a local MCP server on stdio so AI agents can convert Markdown to ' +\n '.docx files on this machine (e.g. claude mcp add markdown-to-word -- ' +\n 'npx -y markdown-to-word mcp)'\n )\n .action(async () => {\n // Loaded only here, so conversions never pay for the MCP SDK.\n const { startMcpServer } = await import('./mcp.js');\n await startMcpServer(version);\n });\nconst convert = program\n .command('convert', { isDefault: true })\n .argument(\n '[file]',\n 'The Markdown file to convert. Use - (or omit it and pipe the Markdown ' +\n 'in) to read from stdin.'\n )\n .option(\n '-o, --output <file>',\n 'Write the .docx to <file> (- means stdout). Defaults to the input ' +\n 'file name with .docx; required when reading stdin.'\n )\n .addOption(\n new Option(\n '--font-preset <name>',\n 'Restyle the document with a font preset, e.g. chinese-official for ' +\n 'a Chinese official document (公文) after GB/T 9704-2012'\n ).choices(Object.keys(FONT_PRESETS))\n )\n .option('-q, --quiet', 'Print nothing to stderr except errors')\n .addHelpText('after', EXAMPLES)\n .action(async (file: string | undefined, options) => {\n const note = (message: string): void => {\n if (!options.quiet) console.error(message);\n };\n try {\n // An explicit `-`, or no file with something piped in, reads stdin. No\n // file at an interactive terminal would just hang, so ask for one.\n const fromStdin = file === '-' || (!file && !process.stdin.isTTY);\n if (!file && !fromStdin) {\n convert.help({ error: true });\n }\n if (fromStdin && !options.output) {\n throw new Error(\n 'Reading from stdin, so there is no file name to name the .docx after. Pass -o report.docx (or -o - for stdout).'\n );\n }\n\n const markdown = fromStdin\n ? await readStdin()\n : await readFile(file as string, 'utf8').catch((error: unknown) => {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`${file} was not found.`);\n }\n throw error;\n });\n if (markdown.trim() === '') {\n throw new Error(\n fromStdin\n ? 'Nothing was piped to stdin. Pass a Markdown file, or pipe one in: md2w -o report.docx < report.md'\n : `${file} is empty.`\n );\n }\n\n const blob = await convertMarkdownToWord(markdown, {\n fontPreset: options.fontPreset\n ? FONT_PRESETS[options.fontPreset]\n : undefined,\n });\n const bytes = Buffer.from(await blob.arrayBuffer());\n\n const output: string = options.output ?? defaultOutputPath(file!);\n if (output === '-') {\n process.stdout.write(bytes);\n } else {\n await mkdir(path.dirname(output), { recursive: true });\n await writeFile(output, bytes);\n note(`Wrote ${output}`);\n }\n } catch (error) {\n console.error(\n 'Error:',\n error instanceof Error ? error.message : String(error)\n );\n process.exit(1);\n }\n });\n\nawait program.parseAsync();\n"]}
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA,wEAAwE;AACxE,0EAA0E;AAC1E,2EAA2E;AAC3E,0DAA0D;AAE1D,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AACvC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAE3D,6EAA6E;AAC7E,6EAA6E;AAC7E,wEAAwE;AACxE,MAAM,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC/C,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,iBAAiB,CAAwB,CAAC;AAEtE,KAAK,UAAU,SAAS;IACtB,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,IAAI,KAAK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nC,qBAAqB,CAAC,QAAQ,EAAE;YAC9B,UAAU,EAAE,OAAO,CAAC,UAAU;gBAC5B,CAAC,CAAC,YAAY,CAAC,OAAO,CAAC,UAAU,CAAC;gBAClC,CAAC,CAAC,SAAS;SACd,CAAC,CAAC;QACL,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK;YACxB,CAAC,CAAC,MAAM,mBAAmB,CAAC,QAAQ,CAAC;YACrC,CAAC,CAAC,MAAM,QAAQ,EAAE,CAAC;QACrB,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC;QAEpD,IAAI,MAAM,KAAK,GAAG,EAAE,CAAC;YACnB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAC9B,CAAC;aAAM,CAAC;YACN,MAAM,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;YACvD,MAAM,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;YAC/B,IAAI,CAAC,SAAS,MAAM,EAAE,CAAC,CAAC;QAC1B,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CACX,QAAQ,EACR,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CACvD,CAAC;QACF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC,CAAC,CAAC;AAEL,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC","sourcesContent":["#!/usr/bin/env node\n\n// The `md2w` command (also installed as `markdown-to-word`): converts a\n// Markdown file, or stdin, to a .docx on disk. Patterned on word2md.com's\n// `w2m` CLI (benbalter/word-to-markdown-js), in reverse. It loads the Node\n// entry, which supplies the DOM APIs the converter needs.\n\nimport { Command, Option } from 'commander';\nimport { createRequire } from 'module';\nimport { mkdir, readFile, stat, writeFile } from 'fs/promises';\nimport path from 'path';\nimport { convertMarkdownToWord, FONT_PRESETS } from './node.js';\nimport { looksBinary, WORD_FILE } from './input-checks.js';\n\n// Read our own version from package.json. createRequire resolves relative to\n// this module, so `../package.json` points at the package root both from the\n// TypeScript source (src/) and the compiled CLI (build/) after publish.\nconst require = createRequire(import.meta.url);\nconst { version } = require('../package.json') as { version: string };\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString('utf8');\n}\n\n/** `notes.md` → `notes.docx`, next to the input. */\nfunction defaultOutputPath(input: string): string {\n const { dir, name } = path.parse(input);\n return path.join(dir, `${name}.docx`);\n}\n\n/**\n * Whether `a` and `b` are the same file on disk. Compares inodes, not paths,\n * so a symlink or a different case on a case-insensitive disk still counts.\n * BigInt stats, because some filesystems hand out inode numbers above\n * Number.MAX_SAFE_INTEGER, where two different files could round to the same\n * number.\n */\nasync function isSameFile(a: string, b: string): Promise<boolean> {\n const [statA, statB] = await Promise.all([\n stat(a, { bigint: true }).catch(() => undefined),\n stat(b, { bigint: true }).catch(() => undefined),\n ]);\n return (\n statA !== undefined &&\n statB !== undefined &&\n statA.dev === statB.dev &&\n statA.ino === statB.ino\n );\n}\n\n/**\n * `value` as one shell word, for commands we print for the user to copy.\n * Plain names stay bare so the common case reads cleanly.\n */\nfunction shellQuote(value: string): string {\n return /^[\\w@%+=:,./-]+$/.test(value)\n ? value\n : `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\n// html-to-docx logs as it works: debug lines with console.log, which would\n// land in front of a .docx written to stdout, and skipped images or a missing\n// sharp with console.warn and console.error. The convert action sends the\n// console.log family to stderr, and with -q drops all of it while the\n// generator runs; our own errors print afterward. (`md2w mcp` has its own\n// guard in src/mcp.ts.)\nasync function withConsoleSilenced<T>(run: () => Promise<T>): Promise<T> {\n const saved = { ...console };\n const silent = (): void => {};\n console.log = console.info = console.debug = silent;\n console.warn = console.error = silent;\n try {\n return await run();\n } finally {\n Object.assign(console, saved);\n }\n}\n\nconst EXAMPLES = `\nExamples:\n $ md2w report.md # writes report.docx\n $ md2w report.md -o out/report.docx\n $ md2w --font-preset chinese-official notice.md\n $ cat reply.md | md2w -o reply.docx\n $ md2w - -o - < report.md > report.docx`;\n\nconst program = new Command();\nprogram.name('md2w');\nprogram.description('Convert Markdown to a formatted Word (.docx) document');\nprogram.version(version);\nprogram.addHelpText(\n 'after',\n `\\nRun \"md2w convert --help\" for all conversion options.\\n${EXAMPLES}`\n);\nprogram\n .command('mcp')\n .description(\n 'Run a local MCP server on stdio so AI agents can convert Markdown to ' +\n '.docx files on this machine (e.g. claude mcp add markdown-to-word -- ' +\n 'npx -y markdown-to-word mcp)'\n )\n .action(async () => {\n // Loaded only here, so conversions never pay for the MCP SDK.\n const { startMcpServer } = await import('./mcp.js');\n await startMcpServer(version);\n });\nconst convert = program\n .command('convert', { isDefault: true })\n .argument(\n '[file]',\n 'The Markdown file to convert. Use - (or omit it and pipe the Markdown ' +\n 'in) to read from stdin.'\n )\n .option(\n '-o, --output <file>',\n 'Write the .docx to <file> (- means stdout). Defaults to the input ' +\n 'file name with .docx; required when reading stdin.'\n )\n .addOption(\n new Option(\n '--font-preset <name>',\n 'Restyle the document with a font preset, e.g. chinese-official for ' +\n 'a Chinese official document (公文) after GB/T 9704-2012'\n ).choices(Object.keys(FONT_PRESETS))\n )\n .option('-q, --quiet', 'Print nothing to stderr except errors')\n .addHelpText('after', EXAMPLES)\n .action(async (file: string | undefined, options) => {\n const toStderr = console.error.bind(console);\n console.log = console.info = console.debug = toStderr;\n const note = (message: string): void => {\n if (!options.quiet) console.error(message);\n };\n try {\n // An explicit `-`, or no file with something piped in, reads stdin. No\n // file at an interactive terminal would just hang, so ask for one.\n const fromStdin = file === '-' || (!file && !process.stdin.isTTY);\n if (!file && !fromStdin) {\n convert.help({ error: true });\n }\n // A Word file would otherwise be read as garbage text and, with no -o,\n // written back over itself as report.docx.\n if (!fromStdin && WORD_FILE.test(file as string)) {\n throw new Error(\n `${file} is already a Word document. To turn it into Markdown, use word2md.com or its CLI: npx word-to-markdown ${shellQuote(file as string)} > ${shellQuote(`${path.parse(file as string).name}.md`)}`\n );\n }\n if (fromStdin && !options.output) {\n throw new Error(\n 'Reading from stdin, so there is no file name to name the .docx after. Pass -o report.docx (or -o - for stdout).'\n );\n }\n\n const markdown = fromStdin\n ? await readStdin()\n : await readFile(file as string, 'utf8').catch((error: unknown) => {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`${file} was not found.`);\n }\n throw error;\n });\n if (markdown.trim() === '') {\n throw new Error(\n fromStdin\n ? 'Nothing was piped to stdin. Pass a Markdown file, or pipe one in: md2w -o report.docx < report.md'\n : `${file} is empty.`\n );\n }\n if (looksBinary(markdown)) {\n throw new Error(\n `${fromStdin ? 'stdin' : file} doesn't look like a Markdown or text file, so it can't be converted.`\n );\n }\n\n const output: string = options.output ?? defaultOutputPath(file!);\n if (\n output !== '-' &&\n !fromStdin &&\n (await isSameFile(output, file as string))\n ) {\n throw new Error(\n `${output} is the input file, so writing the .docx there would overwrite it. Pass a different -o.`\n );\n }\n\n const generate = (): Promise<Blob> =>\n convertMarkdownToWord(markdown, {\n fontPreset: options.fontPreset\n ? FONT_PRESETS[options.fontPreset]\n : undefined,\n });\n const blob = options.quiet\n ? await withConsoleSilenced(generate)\n : await generate();\n const bytes = Buffer.from(await blob.arrayBuffer());\n\n if (output === '-') {\n process.stdout.write(bytes);\n } else {\n await mkdir(path.dirname(output), { recursive: true });\n await writeFile(output, bytes);\n note(`Wrote ${output}`);\n }\n } catch (error) {\n console.error(\n 'Error:',\n error instanceof Error ? error.message : String(error)\n );\n process.exit(1);\n }\n });\n\nawait program.parseAsync();\n"]}
@@ -18,17 +18,25 @@ export declare const RULE_TEXT = "* * *";
18
18
  * the same. Each becomes a ☒ or ☐ character.
19
19
  * - Inline code: `<code>` keeps the body font. Its text is wrapped in a span
20
20
  * naming the code block font, which the generator does carry over.
21
- * - Table header cells: `<th>` isn't bold, so its content is wrapped in
22
- * `<strong>`. Column alignment from GFM's `align` attribute is ignored, but
23
- * the same value as a `text-align` style is honored.
21
+ * - Table cells: the generator makes each inline child of a cell its own
22
+ * paragraph, so `**bold** text` would read as two lines. Each run of
23
+ * inline content is wrapped in one `<p>`. `<th>` isn't bold, so its
24
+ * content is wrapped in `<strong>`. Column alignment from GFM's `align`
25
+ * attribute is ignored, but the same value as a `text-align` style is
26
+ * honored.
24
27
  * - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT
25
28
  * paragraph for the structure patch to draw as a rule.
26
29
  * - Block quotes: the generator joins everything in a `<blockquote>` into one
27
30
  * justified paragraph. Its paragraphs and headings are kept apart instead,
28
31
  * left aligned and indented one step per level of nesting.
29
- * - Inline elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, ...): their
30
- * text is dropped, so each is replaced by a span or `<em>` (see
31
- * UNKNOWN_INLINE). `<mark>` loses its highlight, so it's set as a shading.
32
+ * - Elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, `<my-element>`,
33
+ * ...): the generator drops their text, so this keeps it. Some are
34
+ * replaced by a span or `<em>` (see UNKNOWN_INLINE), the rest by their
35
+ * children; content a browser wouldn't show as text (HIDDEN_CONTENT) is
36
+ * left for the generator to drop. A placeholder like `<your-name>` that's
37
+ * never closed isn't markup at all, so it stays as literal text, spelled
38
+ * as in the source. `<mark>` loses its highlight, so it's set as a
39
+ * shading.
32
40
  * - Footnotes: the reference and back links point into the page, which a
33
41
  * Word reader can't follow, so references keep only their number and the
34
42
  * back links (↩) go. So does the footnotes heading, which the page only
@@ -26,8 +26,9 @@ const QUOTE_INDENT_INCHES = 0.5;
26
26
  const QUOTE_PARAGRAPHS = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);
27
27
  /**
28
28
  * Inline elements the generator doesn't know, whose text it drops. Each is
29
- * replaced by what a browser shows: a span (in the code font, for the ones a
30
- * browser draws in monospace), emphasis, or quotation marks.
29
+ * replaced by what a browser shows: a span in the code font (for the ones a
30
+ * browser draws in monospace), emphasis, or quotation marks. Other unknown
31
+ * elements are unwrapped (see GENERATOR_ELEMENTS).
31
32
  */
32
33
  const UNKNOWN_INLINE = {
33
34
  kbd: 'code',
@@ -37,21 +38,46 @@ const UNKNOWN_INLINE = {
37
38
  cite: 'em',
38
39
  dfn: 'em',
39
40
  q: 'quote',
40
- abbr: 'text',
41
- acronym: 'text',
42
- bdi: 'text',
43
- bdo: 'text',
44
- big: 'text',
45
- data: 'text',
46
- font: 'text',
47
- label: 'text',
48
- small: 'text',
49
- time: 'text',
50
41
  };
42
+ /**
43
+ * Elements the generator keeps the text of (each checked against it), or
44
+ * that a later step here rewrites (`hr`, `mark`, `input`). Any other element
45
+ * in a paragraph loses its text, so it's replaced by its children: an
46
+ * allowlist, because a list of the ones it drops (`<abbr>`, `<small>`, a
47
+ * custom `<my-element>`, ...) is never complete.
48
+ */
49
+ const GENERATOR_ELEMENTS = new Set([
50
+ ...['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'section', 'pre'],
51
+ ...['ul', 'ol', 'li', 'blockquote', 'hr', 'br', 'img', 'input'],
52
+ ...['table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'colgroup', 'col'],
53
+ ...['a', 'span', 'code', 'strong', 'b', 'em', 'i', 'u', 's', 'del'],
54
+ ...['strike', 'ins', 'sub', 'sup', 'mark', 'caption', 'figcaption'],
55
+ ...['article', 'aside', 'header', 'footer', 'main', 'nav', 'address'],
56
+ ...['hgroup', 'dl', 'dt', 'dd', 'details', 'summary', 'fieldset', 'legend'],
57
+ ]);
58
+ /**
59
+ * Elements whose content isn't prose: code, fallbacks a browser hides, and
60
+ * drawings. The generator drops them, which is right; unwrapping them would
61
+ * put a script, or an SVG's or formula's bare parts, in the document.
62
+ */
63
+ const HIDDEN_CONTENT = new Set([
64
+ ...['script', 'style', 'template', 'noscript', 'iframe', 'object'],
65
+ ...['video', 'audio', 'canvas', 'svg', 'math'],
66
+ ]);
51
67
  /** `Node.TEXT_NODE`, which Node's globals lack. */
52
68
  const TEXT_NODE = 3;
53
69
  /** The highlight browsers give `<mark>`; the generator drops it. */
54
70
  const MARK_COLOR = '#FFFF00';
71
+ /** `Node.ELEMENT_NODE`, which Node's globals lack too. */
72
+ const ELEMENT_NODE = 1;
73
+ /**
74
+ * Elements that start their own paragraph in a table cell. Anything else is
75
+ * inline, and a run of it is kept together in one paragraph.
76
+ */
77
+ const CELL_BLOCKS = new Set([
78
+ ...['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'pre', 'blockquote'],
79
+ ...['ul', 'ol', 'table', 'hr', 'section'],
80
+ ]);
55
81
  /**
56
82
  * Adjusts the parser's HTML for html-to-docx, which drops or flattens some of
57
83
  * what the browser preview renders:
@@ -60,17 +86,25 @@ const MARK_COLOR = '#FFFF00';
60
86
  * the same. Each becomes a ☒ or ☐ character.
61
87
  * - Inline code: `<code>` keeps the body font. Its text is wrapped in a span
62
88
  * naming the code block font, which the generator does carry over.
63
- * - Table header cells: `<th>` isn't bold, so its content is wrapped in
64
- * `<strong>`. Column alignment from GFM's `align` attribute is ignored, but
65
- * the same value as a `text-align` style is honored.
89
+ * - Table cells: the generator makes each inline child of a cell its own
90
+ * paragraph, so `**bold** text` would read as two lines. Each run of
91
+ * inline content is wrapped in one `<p>`. `<th>` isn't bold, so its
92
+ * content is wrapped in `<strong>`. Column alignment from GFM's `align`
93
+ * attribute is ignored, but the same value as a `text-align` style is
94
+ * honored.
66
95
  * - Horizontal rules: `<hr>` is dropped, so it becomes a centered RULE_TEXT
67
96
  * paragraph for the structure patch to draw as a rule.
68
97
  * - Block quotes: the generator joins everything in a `<blockquote>` into one
69
98
  * justified paragraph. Its paragraphs and headings are kept apart instead,
70
99
  * left aligned and indented one step per level of nesting.
71
- * - Inline elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, ...): their
72
- * text is dropped, so each is replaced by a span or `<em>` (see
73
- * UNKNOWN_INLINE). `<mark>` loses its highlight, so it's set as a shading.
100
+ * - Elements it doesn't know (`<kbd>`, `<abbr>`, `<q>`, `<my-element>`,
101
+ * ...): the generator drops their text, so this keeps it. Some are
102
+ * replaced by a span or `<em>` (see UNKNOWN_INLINE), the rest by their
103
+ * children; content a browser wouldn't show as text (HIDDEN_CONTENT) is
104
+ * left for the generator to drop. A placeholder like `<your-name>` that's
105
+ * never closed isn't markup at all, so it stays as literal text, spelled
106
+ * as in the source. `<mark>` loses its highlight, so it's set as a
107
+ * shading.
74
108
  * - Footnotes: the reference and back links point into the page, which a
75
109
  * Word reader can't follow, so references keep only their number and the
76
110
  * back links (↩) go. So does the footnotes heading, which the page only
@@ -106,16 +140,32 @@ export function prepareHtmlForDocx(html) {
106
140
  strong.append(...Array.from(cell.childNodes));
107
141
  cell.append(strong);
108
142
  }
143
+ wrapInlineRuns(cell);
109
144
  }
110
145
  for (const quote of Array.from(dom.querySelectorAll('blockquote'))) {
111
146
  // Outermost first; each one unwraps its nested quotes as it goes.
112
147
  if (quote.isConnected)
113
148
  unwrapQuote(quote, 1);
114
149
  }
115
- for (const element of Array.from(dom.body.querySelectorAll('*'))) {
116
- const kind = UNKNOWN_INLINE[element.localName];
117
- if (!kind || element.closest('pre'))
150
+ const elements = Array.from(dom.body.querySelectorAll('*'));
151
+ const startTags = new SourceStartTags(html, elements);
152
+ for (const element of elements) {
153
+ const name = element.localName;
154
+ if (GENERATOR_ELEMENTS.has(name) || element.closest('pre'))
155
+ continue;
156
+ if (HIDDEN_CONTENT.has(name) || element.closest('svg, math'))
118
157
  continue;
158
+ const kind = UNKNOWN_INLINE[name];
159
+ if (!kind) {
160
+ const children = Array.from(element.childNodes);
161
+ if (isUnclosedPlaceholder(element, html)) {
162
+ element.replaceWith(startTags.of(element), ...children);
163
+ }
164
+ else {
165
+ element.replaceWith(...children);
166
+ }
167
+ continue;
168
+ }
119
169
  if (kind === 'quote') {
120
170
  element.replaceWith('“', ...Array.from(element.childNodes), '”');
121
171
  continue;
@@ -154,6 +204,36 @@ export function prepareHtmlForDocx(html) {
154
204
  // Only inside tags: text can't contain a raw `<`, so it's never touched.
155
205
  return dom.body.innerHTML.replace(/<[^>]+>/g, (tag) => tag.replace(` ${STYLE_PLACEHOLDER}=`, ' style='));
156
206
  }
207
+ /**
208
+ * Wraps each run of `cell`'s inline children (text, links, emphasis, `<br>`)
209
+ * in a `<p>`, which the generator keeps as one paragraph. Whitespace-only runs
210
+ * are left alone, so an empty cell stays empty.
211
+ */
212
+ function wrapInlineRuns(cell) {
213
+ const document = cell.ownerDocument;
214
+ let run = [];
215
+ const flush = (before) => {
216
+ const hasContent = run.some((node) => node.nodeType === ELEMENT_NODE ||
217
+ (node.nodeType === TEXT_NODE && node.textContent?.trim()));
218
+ if (hasContent) {
219
+ const paragraph = document.createElement('p');
220
+ cell.insertBefore(paragraph, before);
221
+ paragraph.append(...run);
222
+ }
223
+ run = [];
224
+ };
225
+ for (const child of Array.from(cell.childNodes)) {
226
+ const isBlock = child.nodeType === ELEMENT_NODE &&
227
+ CELL_BLOCKS.has(child.localName);
228
+ if (isBlock) {
229
+ flush(child);
230
+ }
231
+ else {
232
+ run.push(child);
233
+ }
234
+ }
235
+ flush(null);
236
+ }
157
237
  /**
158
238
  * Replaces `quote` with its children, indenting its paragraphs and headings
159
239
  * `depth` steps. Other blocks (lists, code, tables) keep their own layout, and
@@ -177,4 +257,60 @@ function unwrapQuote(quote, depth) {
177
257
  }
178
258
  quote.replaceWith(...Array.from(quote.childNodes));
179
259
  }
260
+ /**
261
+ * Whether `element` is a made-up tag, like `<your-name>`, that `html` never
262
+ * closes: a placeholder meant to be read, which a browser would hide.
263
+ */
264
+ function isUnclosedPlaceholder(element, html) {
265
+ const isMadeUp = element.localName.includes('-') ||
266
+ Object.prototype.toString.call(element) === '[object HTMLUnknownElement]';
267
+ return isMadeUp && !html.toLowerCase().includes(`</${element.localName}`);
268
+ }
269
+ /**
270
+ * Each element's start tag as written in the source, so a placeholder shown
271
+ * as text keeps its exact spelling (case, quotes, entities). The DOM only
272
+ * has decoded attribute values, which can't say whether the source wrote
273
+ * `&` or `&amp;`.
274
+ */
275
+ class SourceStartTags {
276
+ html;
277
+ ordinals = new Map();
278
+ counts = new Map();
279
+ tags = new Map();
280
+ constructor(html, elements) {
281
+ this.html = html;
282
+ // Document order is source order of start tags, so the nth <x> element
283
+ // is the nth `<x` in the source.
284
+ for (const element of elements) {
285
+ const count = this.counts.get(element.localName) ?? 0;
286
+ this.ordinals.set(element, count);
287
+ this.counts.set(element.localName, count + 1);
288
+ }
289
+ }
290
+ of(element) {
291
+ const name = element.localName;
292
+ let tags = this.tags.get(name);
293
+ if (!tags) {
294
+ // Quoted values may hold `>`. Each alternative starts with a different
295
+ // character, so this can't backtrack.
296
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
297
+ const startTag = new RegExp(`<${escaped}(?=[\\s/>])(?:"[^"]*"|'[^']*'|[^'">])*>`, 'gi');
298
+ tags = this.html.match(startTag) ?? [];
299
+ this.tags.set(name, tags);
300
+ }
301
+ // A mismatch means a `<x` the parser didn't turn into an element (in a
302
+ // comment, say), so the ordinal can't be trusted: rebuild the tag.
303
+ const tag = tags.length === this.counts.get(name)
304
+ ? tags[this.ordinals.get(element) ?? -1]
305
+ : undefined;
306
+ return tag ?? rebuiltStartTag(element);
307
+ }
308
+ }
309
+ /** A start tag for `element` rebuilt from the DOM. */
310
+ function rebuiltStartTag(element) {
311
+ const attributes = Array.from(element.attributes)
312
+ .map(({ name, value }) => (value ? ` ${name}="${value}"` : ` ${name}`))
313
+ .join('');
314
+ return `<${element.localName}${attributes}>`;
315
+ }
180
316
  //# sourceMappingURL=docx-html.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"docx-html.js","sourceRoot":"","sources":["../src/docx-html.ts"],"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AC,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,EAA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AC,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 `&amp;`.\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"]}
@@ -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.