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 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
 
@@ -96,6 +102,75 @@ Conversion happens entirely in your browser: your Markdown and the Word document
96
102
  - Very large documents can be slow, since everything runs in the browser. Files are limited to 5 MB.
97
103
  - The site works in current versions of Chrome, Edge, Firefox, and Safari. The end-to-end tests run in Chrome.
98
104
 
105
+ ## Command line
106
+
107
+ Run it directly with `npx` (downloads and runs the latest published version):
108
+
109
+ ```console
110
+ npx markdown-to-word report.md
111
+ ```
112
+
113
+ Or install it globally to get the `md2w` command:
114
+
115
+ ```console
116
+ npm install -g markdown-to-word
117
+ md2w report.md
118
+ ```
119
+
120
+ It writes the `.docx` next to the input with the same name (`report.md` becomes `report.docx`), replacing any file already there, and prints where it wrote it to **stderr**. It needs Node 22.12 or later, and exits with status 1 and a message if the file is missing or empty.
121
+
122
+ To read the Markdown from **stdin**, pass `-` as the file, or leave it out and pipe the Markdown in. There's no file name to go on then, so `-o` is required:
123
+
124
+ ```console
125
+ cat reply.md | md2w -o reply.docx
126
+ md2w - -o - < report.md > report.docx
127
+ ```
128
+
129
+ Options:
130
+
131
+ - `-o, --output <file>`: write the `.docx` to `<file>`, creating folders as needed. `-o -` writes it to stdout.
132
+ - `--font-preset <name>`: restyle the document with a font preset. `chinese-official` is the Chinese official document (公文) style described in [Optional Font Presets](#optional-font-presets).
133
+ - `-q, --quiet`: print nothing to stderr except errors.
134
+ - `-V, --version`: print the version.
135
+
136
+ ## MCP server
137
+
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.
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
+
142
+ Add it to Claude Code:
143
+
144
+ ```console
145
+ claude mcp add markdown-to-word -- npx -y markdown-to-word mcp
146
+ ```
147
+
148
+ Or to any MCP client that takes a JSON config:
149
+
150
+ ```json
151
+ {
152
+ "mcpServers": {
153
+ "markdown-to-word": {
154
+ "command": "npx",
155
+ "args": ["-y", "markdown-to-word", "mcp"]
156
+ }
157
+ }
158
+ }
159
+ ```
160
+
161
+ It has one tool, `convert_markdown_to_word`:
162
+
163
+ - `markdown` or `path` (exactly one): the Markdown as a string, or the path of a Markdown file (`.md`, `.markdown`, `.mdown`, or `.txt`). Prefer absolute paths; relative ones resolve against the server's working directory.
164
+ - `output_path` (required): where to write the `.docx`; it must end in `.docx`. Missing folders are created.
165
+ - `overwrite`: replace `output_path` if it already exists. Off by default, so the tool refuses to clobber an existing file and says so.
166
+ - `font_preset`: `chinese-official` for the 公文 style; omit for Word's default styling.
167
+
168
+ It returns the `output_path`, the file's size in `bytes`, and any `warnings` (remote images it didn't download, or a `.docx` patch that had to be skipped), also as structured content.
169
+
170
+ An agent may be following instructions from a document or web page it read, so the tool limits what it can be talked into: it reads only Markdown files, writes only `.docx` files, never writes through a symlink, and never replaces a file unless asked. It also never downloads remote images, since a URL in a document could point anywhere, your own network included: they appear in the document as links. An agent that wants an image embedded can fetch it itself and put it in the Markdown as a `data:` URI. The CLI, run by you, has none of these limits and embeds remote images like the website.
171
+
172
+ In the browser, md2word.app registers the same conversion as a [WebMCP](https://webmachinelearning.github.io/webmcp/) tool, `convert_markdown_to_docx` (`markdown`, plus optional `filename` and `font_preset`), for agents in browsers that support it. It runs in the tab like a paste, shows the result on the page, and returns the `.docx` as base64. The page also tries to download the file, which a browser may block when no one clicked.
173
+
99
174
  ## Use it from code
100
175
 
101
176
  The converter is also on npm as [`markdown-to-word`](https://www.npmjs.com/package/markdown-to-word), for Node 22.12+ and for browsers through a bundler (Vite, webpack, esbuild):
package/build/cli.js ADDED
@@ -0,0 +1,172 @@
1
+ #!/usr/bin/env node
2
+ // The `md2w` command (also installed as `markdown-to-word`): converts a
3
+ // Markdown file, or stdin, to a .docx on disk. Patterned on word2md.com's
4
+ // `w2m` CLI (benbalter/word-to-markdown-js), in reverse. It loads the Node
5
+ // entry, which supplies the DOM APIs the converter needs.
6
+ import { Command, Option } from 'commander';
7
+ import { createRequire } from 'module';
8
+ import { mkdir, readFile, stat, writeFile } from 'fs/promises';
9
+ import path from 'path';
10
+ import { convertMarkdownToWord, FONT_PRESETS } from './node.js';
11
+ import { looksBinary, WORD_FILE } from './input-checks.js';
12
+ // Read our own version from package.json. createRequire resolves relative to
13
+ // this module, so `../package.json` points at the package root both from the
14
+ // TypeScript source (src/) and the compiled CLI (build/) after publish.
15
+ const require = createRequire(import.meta.url);
16
+ const { version } = require('../package.json');
17
+ async function readStdin() {
18
+ const chunks = [];
19
+ for await (const chunk of process.stdin)
20
+ chunks.push(chunk);
21
+ return Buffer.concat(chunks).toString('utf8');
22
+ }
23
+ /** `notes.md` → `notes.docx`, next to the input. */
24
+ function defaultOutputPath(input) {
25
+ const { dir, name } = path.parse(input);
26
+ return path.join(dir, `${name}.docx`);
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
+ }
72
+ const EXAMPLES = `
73
+ Examples:
74
+ $ md2w report.md # writes report.docx
75
+ $ md2w report.md -o out/report.docx
76
+ $ md2w --font-preset chinese-official notice.md
77
+ $ cat reply.md | md2w -o reply.docx
78
+ $ md2w - -o - < report.md > report.docx`;
79
+ const program = new Command();
80
+ program.name('md2w');
81
+ program.description('Convert Markdown to a formatted Word (.docx) document');
82
+ program.version(version);
83
+ program.addHelpText('after', `\nRun "md2w convert --help" for all conversion options.\n${EXAMPLES}`);
84
+ program
85
+ .command('mcp')
86
+ .description('Run a local MCP server on stdio so AI agents can convert Markdown to ' +
87
+ '.docx files on this machine (e.g. claude mcp add markdown-to-word -- ' +
88
+ 'npx -y markdown-to-word mcp)')
89
+ .action(async () => {
90
+ // Loaded only here, so conversions never pay for the MCP SDK.
91
+ const { startMcpServer } = await import('./mcp.js');
92
+ await startMcpServer(version);
93
+ });
94
+ const convert = program
95
+ .command('convert', { isDefault: true })
96
+ .argument('[file]', 'The Markdown file to convert. Use - (or omit it and pipe the Markdown ' +
97
+ 'in) to read from stdin.')
98
+ .option('-o, --output <file>', 'Write the .docx to <file> (- means stdout). Defaults to the input ' +
99
+ 'file name with .docx; required when reading stdin.')
100
+ .addOption(new Option('--font-preset <name>', 'Restyle the document with a font preset, e.g. chinese-official for ' +
101
+ 'a Chinese official document (公文) after GB/T 9704-2012').choices(Object.keys(FONT_PRESETS)))
102
+ .option('-q, --quiet', 'Print nothing to stderr except errors')
103
+ .addHelpText('after', EXAMPLES)
104
+ .action(async (file, options) => {
105
+ const toStderr = console.error.bind(console);
106
+ console.log = console.info = console.debug = toStderr;
107
+ const note = (message) => {
108
+ if (!options.quiet)
109
+ console.error(message);
110
+ };
111
+ try {
112
+ // An explicit `-`, or no file with something piped in, reads stdin. No
113
+ // file at an interactive terminal would just hang, so ask for one.
114
+ const fromStdin = file === '-' || (!file && !process.stdin.isTTY);
115
+ if (!file && !fromStdin) {
116
+ convert.help({ error: true });
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
+ }
123
+ if (fromStdin && !options.output) {
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).');
125
+ }
126
+ const markdown = fromStdin
127
+ ? await readStdin()
128
+ : await readFile(file, 'utf8').catch((error) => {
129
+ if (error.code === 'ENOENT') {
130
+ throw new Error(`${file} was not found.`);
131
+ }
132
+ throw error;
133
+ });
134
+ if (markdown.trim() === '') {
135
+ throw new Error(fromStdin
136
+ ? 'Nothing was piped to stdin. Pass a Markdown file, or pipe one in: md2w -o report.docx < report.md'
137
+ : `${file} is empty.`);
138
+ }
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, {
149
+ fontPreset: options.fontPreset
150
+ ? FONT_PRESETS[options.fontPreset]
151
+ : undefined,
152
+ });
153
+ const blob = options.quiet
154
+ ? await withConsoleSilenced(generate)
155
+ : await generate();
156
+ const bytes = Buffer.from(await blob.arrayBuffer());
157
+ if (output === '-') {
158
+ process.stdout.write(bytes);
159
+ }
160
+ else {
161
+ await mkdir(path.dirname(output), { recursive: true });
162
+ await writeFile(output, bytes);
163
+ note(`Wrote ${output}`);
164
+ }
165
+ }
166
+ catch (error) {
167
+ console.error('Error:', error instanceof Error ? error.message : String(error));
168
+ process.exit(1);
169
+ }
170
+ });
171
+ await program.parseAsync();
172
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +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,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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AAO,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"]}
@@ -11,7 +11,9 @@ import { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';
11
11
  export async function convertMarkdownToWord(markdown, options = {}) {
12
12
  try {
13
13
  let html = parseMarkdownToHtml(markdown);
14
- if (html.includes('<img')) {
14
+ // Case-insensitive: raw HTML in the Markdown can say <IMG>, and an image
15
+ // this skips is left for html-to-docx to download on its own.
16
+ if (/<img/i.test(html)) {
15
17
  // Before generation, so a failed image can keep its alt text.
16
18
  html = await embedImages(html);
17
19
  }
@@ -1 +1 @@
1
- {"version":3,"file":"converter.js","sourceRoot":"","sources":["../src/converter.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,OAAO,oBAAoB,CAAC;AAC5B,OAAO,UAAU,MAAM,yBAAyB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/C,OAAO,EAAE,SAAS,EAAmB,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAiBzE;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,QAAgB,EAChB,UAA6B,EAAE;IAE/B,IAAI,CAAC;QACH,IAAI,IAAI,GAAG,mBAAmB,CAAC,QAAQ,CAAC,CAAC;QACzC,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;YAC1B,8DAA8D;YAC9D,IAAI,GAAG,MAAM,WAAW,CAAC,IAAI,CAAC,CAAC;QACjC,CAAC;QAED,M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,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE;YAC9D,MAAM,QAAQ,GAAG,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;YAC3C,OAAO,CACL,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC;gBACpB,OAAO,CAAC,QAAQ,IAAI,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,CAC3D,CAAC;QACJ,CAAC,CAAC;KACH,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,WAAW,CACxB,YAAkB,EAClB,IAAY,EACZ,KAA4C;IAE5C,IAAI,CAAC;QACH,OAAO,MAAM,KAAK,CAAC,YAAY,CAAC,CAAC;IACnC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CACV,eAAe,IAAI,yCAAyC,EAC5D,KAAK,CACN,CAAC;QACF,OAAO,YAAY,CAAC;IACtB,CAAC;AACH,CAAC","sourcesContent":["// Must come first: it sets the global Buffer html-to-docx needs for images.\nimport './buffer-global.js';\nimport HTMLtoDOCX from '@turbodocx/html-to-docx';\nimport { prepareHtmlForDocx } from './docx-html.js';\nimport { embedImages } from './docx-images.js';\nimport type { DocumentStructure } from './docx-structure.js';\nimport { mmToTwips, type FontPreset } from './font-presets.js';\nimport { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';\n\nexport interface ConversionOptions {\n /** Page margins in inches. Overrides the margins of `fontPreset.page`. */\n pageMargins?: {\n top: number;\n right: number;\n bottom: number;\n left: number;\n };\n /**\n * Rewrites the document fonts, and the page layout if the preset has one.\n * Omit to keep the default styling.\n */\n fontPreset?: FontPreset;\n}\n\n/**\n * Convert markdown text to a Word document blob using HTML as an intermediary format\n */\nexport async function convertMarkdownToWord(\n markdown: string,\n options: ConversionOptions = {}\n): Promise<Blob> {\n try {\n let html = parseMarkdownToHtml(markdown);\n if (html.includes('<img')) {\n // Before generation, so a failed image can keep its alt text.\n html = await embedImages(html);\n }\n\n const documentOptions: HTMLtoDOCX.DocumentOptions = {\n // The generator's default border size is 0, so tables had no grid lines.\n // A thin light gray rule (size in eighths of a point) matches how\n // GitHub draws tables.\n table: { borderOptions: { size: 4, stroke: 'single', color: 'BFBFBF' } },\n };\n\n const title = extractTitle(markdown);\n if (title) {\n documentOptions.title = title;\n }\n\n const page = options.fontPreset?.page;\n if (page) {\n documentOptions.pageSize = {\n width: mmToTwips(page.widthMm),\n height: mmToTwips(page.heightMm),\n };\n documentOptions.margins = {\n top: mmToTwips(page.marginsMm.top),\n right: mmToTwips(page.marginsMm.right),\n bottom: mmToTwips(page.marginsMm.bottom),\n left: mmToTwips(page.marginsMm.left),\n };\n }\n\n if (options.pageMargins) {\n // Convert inches to twips (1 inch = 1440 twips)\n documentOptions.margins = {\n top: options.pageMargins.top * 1440,\n right: options.pageMargins.right * 1440,\n bottom: options.pageMargins.bottom * 1440,\n left: options.pageMargins.left * 1440,\n };\n }\n\n const result = await HTMLtoDOCX(\n prepareHtmlForDocx(html),\n null,\n documentOptions\n );\n\n // HTMLtoDOCX returns Blob in browser, Buffer/ArrayBuffer in Node.js\n const generated =\n result instanceof Blob ? result : new Blob([result as BlobPart]);\n\n // The patches rewrite the .docx zip with JSZip. html-to-docx bundles its own\n // copy, so ours is a second one, in the patch chunks. The structure patch\n // runs on every document, so it always loads; the others only when they\n // apply.\n\n // Code blocks are broken in the generator output itself, so they are fixed\n // whether or not a font preset is requested.\n let wordDocument = generated;\n if (html.includes('<pre')) {\n const codeBlocks = codeBlockTexts(html);\n wordDocument = await patchOrKeep(\n wordDocument,\n 'code block',\n async (document) => {\n const { formatCodeBlocks } = await import('./docx-code-blocks.js');\n return formatCodeBlocks(document, codeBlocks);\n }\n );\n }\n\n // Every document: the generator writes <w:sectPr> first in the body, and\n // the schema wants it last.\n const structure = documentStructure(html);\n wordDocument = await patchOrKeep(\n wordDocument,\n 'structure',\n async (document) => {\n const { patchStructure } = await import('./docx-structure.js');\n return patchStructure(document, structure);\n }\n );\n\n const { fontPreset } = options;\n if (fontPreset) {\n wordDocument = await patchOrKeep(\n wordDocument,\n 'font preset',\n async (document) => {\n const { applyFontPreset } = await import('./docx-font-preset.js');\n return applyFontPreset(document, fontPreset);\n }\n );\n }\n\n return wordDocument;\n } catch (error) {\n console.error('Word document generation error:', error);\n throw new Error('Failed to generate Word document', { cause: error });\n }\n}\n\n/** The text of each `<pre>` in `html`, in document order. */\nfunction codeBlockTexts(html: string): string[] {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n return Array.from(\n dom.querySelectorAll('pre'),\n (pre) => pre.textContent ?? ''\n );\n}\n\n/** The rules and table header rows in `html`, for the structure patch. */\nfunction documentStructure(html: string): DocumentStructure {\n if (!html.includes('<hr') && !html.includes('<table')) {\n return { rules: 0, headerRows: [] };\n }\n const dom = new DOMParser().parseFromString(html, 'text/html');\n return {\n rules: dom.querySelectorAll('hr').length,\n headerRows: Array.from(dom.querySelectorAll('table'), (table) => {\n const firstRow = table.querySelector('tr');\n return (\n Boolean(table.tHead) ||\n Boolean(firstRow && firstRow.querySelector('td') === null)\n );\n }),\n };\n}\n\n/**\n * The patches polish a document html-to-docx already produced, so a failure in\n * one (including its chunk failing to load) keeps the unpatched document\n * rather than failing the whole conversion.\n */\nasync function patchOrKeep(\n wordDocument: Blob,\n name: string,\n patch: (wordDocument: Blob) => Promise<Blob>\n): Promise<Blob> {\n try {\n return await patch(wordDocument);\n } catch (error) {\n console.warn(\n `Skipped the ${name} patch; keeping the unpatched document:`,\n error\n );\n return wordDocument;\n }\n}\n"]}
1
+ {"version":3,"file":"converter.js","sourceRoot":"","sources":["../src/converter.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,OAAO,oBAAoB,CAAC;AAC5B,OAAO,UAAU,MAAM,yBAAyB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC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;AAC1E,SAAS,iBAAiB,CAAC,IAAY;IACrC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;QACtD,OAAO,EAAE,KAAK,EAAE,CAAC,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC;IACtC,CAAC;IACD,MAAM,GAAG,GAAG,IAAI,SAAS,EAAE,CAAC,eAAe,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IAC/D,OAAO;QACL,KAAK,EAAE,GAAG,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC,MAAM;QACxC,UAAU,EAAE,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE;YAC9D,MAAM,QAAQ,GAAG,KAAK,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;YAC3C,OAAO,CACL,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC;gBACpB,OAAO,CAAC,QAAQ,IAAI,QAAQ,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC,CAC3D,CAAC;QACJ,CAAC,CAAC;KACH,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,WAAW,CACxB,YAAkB,EAClB,IAAY,EACZ,KAA4C;IAE5C,IAAI,CAAC;QACH,OAAO,MAAM,KAAK,CAAC,YAAY,CAAC,CAAC;IACnC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CACV,eAAe,IAAI,yCAAyC,EAC5D,KAAK,CACN,CAAC;QACF,OAAO,YAAY,CAAC;IACtB,CAAC;AACH,CAAC","sourcesContent":["// Must come first: it sets the global Buffer html-to-docx needs for images.\nimport './buffer-global.js';\nimport HTMLtoDOCX from '@turbodocx/html-to-docx';\nimport { prepareHtmlForDocx } from './docx-html.js';\nimport { embedImages } from './docx-images.js';\nimport type { DocumentStructure } from './docx-structure.js';\nimport { mmToTwips, type FontPreset } from './font-presets.js';\nimport { parseMarkdownToHtml, extractTitle } from './markdown-parser.js';\n\nexport interface ConversionOptions {\n /** Page margins in inches. Overrides the margins of `fontPreset.page`. */\n pageMargins?: {\n top: number;\n right: number;\n bottom: number;\n left: number;\n };\n /**\n * Rewrites the document fonts, and the page layout if the preset has one.\n * Omit to keep the default styling.\n */\n fontPreset?: FontPreset;\n}\n\n/**\n * Convert markdown text to a Word document blob using HTML as an intermediary format\n */\nexport async function convertMarkdownToWord(\n markdown: string,\n options: ConversionOptions = {}\n): Promise<Blob> {\n try {\n let html = parseMarkdownToHtml(markdown);\n // Case-insensitive: raw HTML in the Markdown can say <IMG>, and an image\n // this skips is left for html-to-docx to download on its own.\n if (/<img/i.test(html)) {\n // Before generation, so a failed image can keep its alt text.\n html = await embedImages(html);\n }\n\n const documentOptions: HTMLtoDOCX.DocumentOptions = {\n // The generator's default border size is 0, so tables had no grid lines.\n // A thin light gray rule (size in eighths of a point) matches how\n // GitHub draws tables.\n table: { borderOptions: { size: 4, stroke: 'single', color: 'BFBFBF' } },\n };\n\n const title = extractTitle(markdown);\n if (title) {\n documentOptions.title = title;\n }\n\n const page = options.fontPreset?.page;\n if (page) {\n documentOptions.pageSize = {\n width: mmToTwips(page.widthMm),\n height: mmToTwips(page.heightMm),\n };\n documentOptions.margins = {\n top: mmToTwips(page.marginsMm.top),\n right: mmToTwips(page.marginsMm.right),\n bottom: mmToTwips(page.marginsMm.bottom),\n left: mmToTwips(page.marginsMm.left),\n };\n }\n\n if (options.pageMargins) {\n // Convert inches to twips (1 inch = 1440 twips)\n documentOptions.margins = {\n top: options.pageMargins.top * 1440,\n right: options.pageMargins.right * 1440,\n bottom: options.pageMargins.bottom * 1440,\n left: options.pageMargins.left * 1440,\n };\n }\n\n const result = await HTMLtoDOCX(\n prepareHtmlForDocx(html),\n null,\n documentOptions\n );\n\n // HTMLtoDOCX returns Blob in browser, Buffer/ArrayBuffer in Node.js\n const generated =\n result instanceof Blob ? result : new Blob([result as BlobPart]);\n\n // The patches rewrite the .docx zip with JSZip. html-to-docx bundles its own\n // copy, so ours is a second one, in the patch chunks. The structure patch\n // runs on every document, so it always loads; the others only when they\n // apply.\n\n // Code blocks are broken in the generator output itself, so they are fixed\n // whether or not a font preset is requested.\n let wordDocument = generated;\n if (html.includes('<pre')) {\n const codeBlocks = codeBlockTexts(html);\n wordDocument = await patchOrKeep(\n wordDocument,\n 'code block',\n async (document) => {\n const { formatCodeBlocks } = await import('./docx-code-blocks.js');\n return formatCodeBlocks(document, codeBlocks);\n }\n );\n }\n\n // Every document: the generator writes <w:sectPr> first in the body, and\n // the schema wants it last.\n const structure = documentStructure(html);\n wordDocument = await patchOrKeep(\n wordDocument,\n 'structure',\n async (document) => {\n const { patchStructure } = await import('./docx-structure.js');\n return patchStructure(document, structure);\n }\n );\n\n const { fontPreset } = options;\n if (fontPreset) {\n wordDocument = await patchOrKeep(\n wordDocument,\n 'font preset',\n async (document) => {\n const { applyFontPreset } = await import('./docx-font-preset.js');\n return applyFontPreset(document, fontPreset);\n }\n );\n }\n\n return wordDocument;\n } catch (error) {\n console.error('Word document generation error:', error);\n throw new Error('Failed to generate Word document', { cause: error });\n }\n}\n\n/** The text of each `<pre>` in `html`, in document order. */\nfunction codeBlockTexts(html: string): string[] {\n const dom = new DOMParser().parseFromString(html, 'text/html');\n return Array.from(\n dom.querySelectorAll('pre'),\n (pre) => pre.textContent ?? ''\n );\n}\n\n/** The rules and table header rows in `html`, for the structure patch. */\nfunction documentStructure(html: string): DocumentStructure {\n if (!html.includes('<hr') && !html.includes('<table')) {\n return { rules: 0, headerRows: [] };\n }\n const dom = new DOMParser().parseFromString(html, 'text/html');\n return {\n rules: dom.querySelectorAll('hr').length,\n headerRows: Array.from(dom.querySelectorAll('table'), (table) => {\n const firstRow = table.querySelector('tr');\n return (\n Boolean(table.tHead) ||\n Boolean(firstRow && firstRow.querySelector('td') === null)\n );\n }),\n };\n}\n\n/**\n * The patches polish a document html-to-docx already produced, so a failure in\n * one (including its chunk failing to load) keeps the unpatched document\n * rather than failing the whole conversion.\n */\nasync function patchOrKeep(\n wordDocument: Blob,\n name: string,\n patch: (wordDocument: Blob) => Promise<Blob>\n): Promise<Blob> {\n try {\n return await patch(wordDocument);\n } catch (error) {\n console.warn(\n `Skipped the ${name} patch; keeping the unpatched document:`,\n error\n );\n return wordDocument;\n }\n}\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