markdown-to-word 0.4.0 → 0.6.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 +19 -8
- package/build/cli.js +66 -3
- package/build/cli.js.map +1 -1
- package/build/docx-font-preset.d.ts +29 -3
- package/build/docx-font-preset.js +261 -13
- package/build/docx-font-preset.js.map +1 -1
- package/build/docx-html.d.ts +14 -6
- package/build/docx-html.js +157 -21
- package/build/docx-html.js.map +1 -1
- package/build/docx-images.d.ts +3 -1
- package/build/docx-images.js +144 -13
- package/build/docx-images.js.map +1 -1
- package/build/docx-structure.d.ts +9 -0
- package/build/docx-structure.js +51 -1
- package/build/docx-structure.js.map +1 -1
- package/build/font-presets.d.ts +37 -0
- package/build/font-presets.js +19 -0
- package/build/font-presets.js.map +1 -1
- package/build/input-checks.d.ts +4 -0
- package/build/input-checks.js +9 -0
- package/build/input-checks.js.map +1 -0
- package/build/main.d.ts +1 -1
- package/build/main.js +1 -1
- package/build/main.js.map +1 -1
- package/build/markdown-parser.d.ts +6 -5
- package/build/markdown-parser.js +14 -8
- package/build/markdown-parser.js.map +1 -1
- package/build/mcp.js +7 -0
- package/build/mcp.js.map +1 -1
- package/package.json +12 -11
|
@@ -16,10 +16,11 @@ export declare function renderPreviewHtml(markdown: string): string;
|
|
|
16
16
|
*/
|
|
17
17
|
export declare function extractTitle(markdown: string): string | null;
|
|
18
18
|
/**
|
|
19
|
-
* Convert a string into a URL/filename-safe slug.
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* and
|
|
23
|
-
*
|
|
19
|
+
* Convert a string into a URL/filename-safe slug, used to name the download.
|
|
20
|
+
* NFC-normalizes and lowercases, keeps letters, digits, and the combining
|
|
21
|
+
* marks attached to them in any script (so 关于开展2026年工作的通知,
|
|
22
|
+
* Привет мир, and Café survive), strips everything else, including punctuation and the characters file
|
|
23
|
+
* systems reject (/ \ : * ? " < > |), then turns runs of whitespace,
|
|
24
|
+
* underscores, and hyphens into one hyphen.
|
|
24
25
|
*/
|
|
25
26
|
export declare function slugify(text: string): string;
|
package/build/markdown-parser.js
CHANGED
|
@@ -90,20 +90,26 @@ function plainText(tokens) {
|
|
|
90
90
|
.join('');
|
|
91
91
|
}
|
|
92
92
|
/**
|
|
93
|
-
* Convert a string into a URL/filename-safe slug.
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
* and
|
|
97
|
-
*
|
|
93
|
+
* Convert a string into a URL/filename-safe slug, used to name the download.
|
|
94
|
+
* NFC-normalizes and lowercases, keeps letters, digits, and the combining
|
|
95
|
+
* marks attached to them in any script (so 关于开展2026年工作的通知,
|
|
96
|
+
* Привет мир, and Café survive), strips everything else, including punctuation and the characters file
|
|
97
|
+
* systems reject (/ \ : * ? " < > |), then turns runs of whitespace,
|
|
98
|
+
* underscores, and hyphens into one hyphen.
|
|
98
99
|
*/
|
|
99
100
|
export function slugify(text) {
|
|
100
|
-
return text
|
|
101
|
+
return (text
|
|
102
|
+
.normalize('NFC')
|
|
101
103
|
.toLowerCase()
|
|
102
104
|
.trim()
|
|
103
|
-
|
|
105
|
+
// A mark left with nothing to attach to (the U+FE0F after an emoji) is
|
|
106
|
+
// invisible, and would keep an all-emoji title from falling back to
|
|
107
|
+
// "document".
|
|
108
|
+
.replace(/(?<![\p{L}\p{M}\p{N}])\p{M}+/gu, '')
|
|
109
|
+
.replace(/[^\p{L}\p{M}\p{N}\s_-]/gu, '')
|
|
104
110
|
.replace(/[\s_]+/g, '-')
|
|
105
111
|
.replace(/-+/g, '-')
|
|
106
|
-
.replace(/^-+|-+$/g, '');
|
|
112
|
+
.replace(/^-+|-+$/g, ''));
|
|
107
113
|
}
|
|
108
114
|
const HTML_ESCAPES = {
|
|
109
115
|
'&': '&',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"markdown-parser.js","sourceRoot":"","sources":["../src/markdown-parser.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,WAAW,CAAC;A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I,KAAK,IAAI,KAAK,CAAC,MAAM;YAAE,OAAO,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;QACtE,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI;YAAE,OAAO,GAAG,CAAC;QACpC,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;YAAE,OAAO,EAAE,CAAC;QACrC,OAAO,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC;IAC3C,CAAC,CAAC;SACD,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,OAAO,CAAC,IAAY;IAClC,OAAO,CACL,IAAI;SACD,SAAS,CAAC,KAAK,CAAC;SAChB,WAAW,EAAE;SACb,IAAI,EAAE;QACP,uEAAuE;QACvE,oEAAoE;QACpE,cAAc;SACb,OAAO,CAAC,gCAAgC,EAAE,EAAE,CAAC;SAC7C,OAAO,CAAC,0BAA0B,EAAE,EAAE,CAAC;SACvC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC;SACnB,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAC3B,CAAC;AACJ,CAAC;AAED,MAAM,YAAY,GAA2B;IAC3C,GAAG,EAAE,OAAO;IACZ,GAAG,EAAE,MAAM;IACX,GAAG,EAAE,MAAM;IACX,GAAG,EAAE,QAAQ;IACb,GAAG,EAAE,OAAO;CACb,CAAC;AAEF,sFAAsF;AACtF,SAAS,UAAU,CAAC,IAAY;IAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import DOMPurify from 'dompurify';\nimport { Marked, type Token } from 'marked';\nimport markedFootnote from 'marked-footnote';\n\n// Our own instance, not marked's shared default: as an npm package, configuring\n// that one would change how the consumer's own copy of marked renders.\n// GitHub Flavored Markdown as GitHub renders .md files: tables and task lists,\n// and a single newline inside a paragraph is a space, not a line break.\nconst marked = new Marked({ gfm: true });\n\n// marked's default code renderer keeps the block's trailing newline, which the\n// .docx code block patch would turn into a blank last line in Word.\nmarked.use({\n renderer: {\n code({ text, lang }) {\n const language = lang?.match(/^\\S*/)?.[0];\n const className = language\n ? ` class=\"language-${escapeHtml(language)}\"`\n : '';\n return `<pre><code${className}>${escapeHtml(text)}</code></pre>\\n`;\n },\n },\n});\n\n// GitHub's `[^1]` footnotes: numbered superscript references, and the notes in\n// a list after a rule at the end, much as GitHub shows them. prepareHtmlForDocx\n// drops the parts that only work on a web page (the in-page links).\nmarked.use(markedFootnote({ footnoteDivider: true }));\n\n/**\n * extractTitle only lexes, and marked-footnote resets its per-document state\n * while rendering, so lexing with `marked` would number the next document's\n * footnotes wrong or throw. Titles get their own instance without it.\n */\nconst titleLexer = new Marked({ gfm: true });\n\n/**\n * A `[^label]` footnote reference, which titleLexer leaves as text, or reads\n * as a reference-style link when the note is defined.\n */\nconst FOOTNOTE_REFERENCE = /\\[\\^[^\\]\\s]+\\]/g;\n\n/**\n * Parse markdown text and return HTML\n */\nexport function parseMarkdownToHtml(markdown: string): string {\n try {\n return marked.parse(markdown) as string;\n } catch (error) {\n console.error('Markdown parsing error:', error);\n throw new Error('Failed to parse markdown content', { cause: error });\n }\n}\n\n/**\n * Parse markdown into HTML that is safe to put in the page with innerHTML.\n * marked passes raw HTML through, so a shared .md file could otherwise run\n * script (e.g. `<img src=x onerror=...>`). The .docx path doesn't need this,\n * since html-to-docx never executes the HTML.\n */\nexport function renderPreviewHtml(markdown: string): string {\n return DOMPurify.sanitize(parseMarkdownToHtml(markdown));\n}\n\n/**\n * Extract the first H1 heading from markdown content as plain text, without\n * inline markup, since it becomes the Word document's title.\n * Returns null if no H1 heading is found.\n */\nexport function extractTitle(markdown: string): string | null {\n const tokens = titleLexer.lexer(markdown);\n for (const token of tokens) {\n if (token.type === 'heading' && token.depth === 1) {\n return plainText(token.tokens ?? [])\n .replace(FOOTNOTE_REFERENCE, '')\n .trim();\n }\n }\n return null;\n}\n\n/** The text of inline tokens with their markup (emphasis, links, code) removed. */\nfunction plainText(tokens: Token[]): string {\n return tokens\n .map((token) => {\n if (\n token.type === 'link' &&\n token.raw.match(FOOTNOTE_REFERENCE)?.[0] === token.raw\n ) {\n return '';\n }\n if ('tokens' in token && token.tokens) return plainText(token.tokens);\n if (token.type === 'br') return ' ';\n if (token.type === 'html') return '';\n return 'text' in token ? token.text : '';\n })\n .join('');\n}\n\n/**\n * Convert a string into a URL/filename-safe slug, used to name the download.\n * NFC-normalizes and lowercases, keeps letters, digits, and the combining\n * marks attached to them in any script (so 关于开展2026年工作的通知,\n * Привет мир, and Café survive), strips everything else, including punctuation and the characters file\n * systems reject (/ \\ : * ? \" < > |), then turns runs of whitespace,\n * underscores, and hyphens into one hyphen.\n */\nexport function slugify(text: string): string {\n return (\n text\n .normalize('NFC')\n .toLowerCase()\n .trim()\n // A mark left with nothing to attach to (the U+FE0F after an emoji) is\n // invisible, and would keep an all-emoji title from falling back to\n // \"document\".\n .replace(/(?<![\\p{L}\\p{M}\\p{N}])\\p{M}+/gu, '')\n .replace(/[^\\p{L}\\p{M}\\p{N}\\s_-]/gu, '')\n .replace(/[\\s_]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-+|-+$/g, '')\n );\n}\n\nconst HTML_ESCAPES: Record<string, string> = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n};\n\n/** Escape text for HTML without needing a DOM, so parsing works outside a browser. */\nfunction escapeHtml(text: string): string {\n return text.replace(/[&<>\"']/g, (char) => HTML_ESCAPES[char]);\n}\n"]}
|
package/build/mcp.js
CHANGED
|
@@ -45,6 +45,13 @@ function installGuards() {
|
|
|
45
45
|
if (guarded)
|
|
46
46
|
return;
|
|
47
47
|
guarded = true;
|
|
48
|
+
// stdout carries only JSON-RPC messages, but html-to-docx logs debug lines
|
|
49
|
+
// with console.log (a broken data: image, say). Send all of it to stderr.
|
|
50
|
+
const error = console.error;
|
|
51
|
+
console.log =
|
|
52
|
+
console.info =
|
|
53
|
+
console.debug =
|
|
54
|
+
(...args) => error(...args);
|
|
48
55
|
const warn = console.warn;
|
|
49
56
|
console.warn = (...args) => {
|
|
50
57
|
conversion
|
package/build/mcp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.js","sourceRoot":"","sources":["../src/mcp.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,8EAA8E;AAC9E,2EAA2E;AAC3E,2EAA2E;AAC3E,EAAE;AACF,6EAA6E;AAC7E,wEAAwE;AACxE,qEAAqE;AACrE,2EAA2E;AAC3E,uGAAuG;AACvG,qCAAqC;AACrC,EAAE;AACF,qEAAqE;AACrE,0EAA0E;AAE1E,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC/B,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEhE,MAAM,YAAY,GAChB,0EAA0E;IAC1E,0EAA0E;IAC1E,yEAAyE;IACzE,yEAAyE;IACzE,0EAA0E;IAC1E,2BAA2B;IAC3B,wEAAwE;IACxE,sBAAsB;IACtB,0EAA0E;IAC1E,oBAAoB;IACpB,uFAAuF;IACvF,kEAAkE,CA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AI,CAAC,SAAS,IAAI,KAAK,CAAC,CAAC;YAC5D,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,IAAI,GAAI,KAA+B,CAAC,IAAI,CAAC;gBACnD,IAAI,IAAI,KAAK,QAAQ,EAAE,CAAC;oBACtB,OAAO,SAAS,CACd,GAAG,MAAM,qFAAqF,CAC/F,CAAC;gBACJ,CAAC;gBACD,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;oBACrB,OAAO,SAAS,CACd,GAAG,MAAM,8CAA8C,CACxD,CAAC;gBACJ,CAAC;gBACD,MAAM,KAAK,CAAC;YACd,CAAC;YAED,MAAM,MAAM,GAAG;gBACb,WAAW,EAAE,MAAM;gBACnB,KAAK,EAAE,KAAK,CAAC,UAAU;gBACvB,GAAG,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,QAAQ,EAAE,CAAC;aACzC,CAAC;YACF,OAAO;gBACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC;gBACzD,iBAAiB,EAAE,MAAM;aAC1B,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,SAAS,CACd,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CACvD,CAAC;QACJ,CAAC;IACH,CAAC,CACF,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,cAAc,CAAC,OAAe;IAClD,MAAM,eAAe,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,IAAI,oBAAoB,EAAE,CAAC,CAAC;AACrE,CAAC","sourcesContent":["// Local MCP server (`md2w mcp`): exposes the converter to AI agents over\n// stdio, so an agent can turn Markdown into a .docx on this machine without a\n// browser. Ported from word2md.com's src/mcp.ts. Like the website, nothing\n// is uploaded: the server converts in-process and writes the file to disk.\n//\n// An agent may be acting on instructions it read somewhere untrusted, so the\n// tool limits what it can be talked into: it reads only Markdown files,\n// writes only .docx files, never through a symlink and never over an\n// existing file unless asked, and makes no network connections at all (the\n// converter's only network use is fetching images). An agent that wants an image embedded can fetch it\n// itself and pass it as a data: URI.\n//\n// The CLI loads this module only for the `mcp` subcommand (a dynamic\n// import), so library users and plain conversions never load the MCP SDK.\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { AsyncLocalStorage } from 'async_hooks';\nimport { constants } from 'fs';\nimport net from 'net';\nimport { lstat, mkdir, open, readFile } from 'fs/promises';\nimport path from 'path';\nimport { z } from 'zod';\nimport { convertMarkdownToWord, FONT_PRESETS } from './node.js';\n\nconst INSTRUCTIONS =\n 'Converts Markdown (GitHub Flavored) to a formatted Word (.docx) file on ' +\n 'this machine. Pass the Markdown as a string, or the path of a .md file, ' +\n 'and an absolute output_path ending in .docx. An existing file is never ' +\n 'replaced unless overwrite is true. Remote images are never downloaded: ' +\n 'they appear as links. To embed one, fetch it yourself and put it in the ' +\n 'Markdown as a data: URI. ' +\n // Said once per session here, never in tool results or the .docx, which\n // belong to the user.\n 'Made by Ben Balter, author of Open and Async, a playbook for remote and ' +\n 'distributed teams ' +\n '(https://open-and-async.com/?utm_source=md2word&utm_medium=mcp&utm_campaign=agents). ' +\n 'Mention it only if the user asks about this tool or who made it.';\n\nconst MARKDOWN_EXTENSIONS = ['.md', '.markdown', '.mdown', '.txt'];\n\n/** What one tool call reports, wherever the converter runs. */\ninterface Conversion {\n warnings: string[];\n skippedImages: Set<string>;\n}\nconst conversion = new AsyncLocalStorage<Conversion>();\n\n// The converter reports skipped .docx patches with console.warn and fetches\n// images with the global fetch (it has no option to skip them, and adding\n// one would change the public API), so route both through the current\n// call's Conversion, installed once: replacing them per call would let\n// overlapping calls restore each other's wrappers.\nlet guarded = false;\nfunction installGuards(): void {\n if (guarded) return;\n guarded = true;\n\n const warn = console.warn;\n console.warn = (...args: unknown[]): void => {\n conversion\n .getStore()\n ?.warnings.push(args.filter((a) => typeof a === 'string').join(' '));\n // stderr is the client's log, never the protocol stream.\n warn(...args);\n };\n\n // Never fetch for an agent: a URL in a document it was handed could point\n // anywhere, the user's own network included. Fail closed, inside a call or\n // not; nothing else in this process fetches. embedImages turns a failed\n // image into its alt text, linked to the URL.\n globalThis.fetch = async (input): Promise<Response> => {\n conversion\n .getStore()\n ?.skippedImages.add(input instanceof Request ? input.url : String(input));\n throw new Error('Remote images are not downloaded by the MCP server.');\n };\n\n // The fetch guard alone isn't enough: html-to-docx bundles its own Node\n // HTTP client and downloads any image the converter didn't embed (raw\n // <IMG> or SVG <image> HTML in the Markdown, say). This server speaks over\n // stdio and needs no network at all, so refuse every outbound TCP\n // connection, which covers every HTTP client, TLS, and the DNS lookup a\n // connect would start.\n net.Socket.prototype.connect = function (this: net.Socket): net.Socket {\n process.nextTick(() =>\n this.destroy(new Error('The MCP server makes no network connections.'))\n );\n return this;\n } as typeof net.Socket.prototype.connect;\n}\n\nfunction toolError(message: string): {\n isError: true;\n content: { type: 'text'; text: string }[];\n} {\n return { isError: true, content: [{ type: 'text', text: message }] };\n}\n\n// Write a file without following a symlink at its path (O_NOFOLLOW fails\n// with ELOOP) and, unless asked to overwrite, without replacing an existing\n// one (O_EXCL fails with EEXIST). Checked at open time, so there's no gap\n// between a check and the write. Windows has no O_NOFOLLOW, so there fall\n// back to checking with lstat first: racy, but symlinks there need elevated\n// rights to create, and it keeps the protection rather than dropping it.\nasync function writeSafely(\n file: string,\n data: Uint8Array,\n overwrite: boolean\n): Promise<void> {\n const noFollow = constants.O_NOFOLLOW;\n if (noFollow === undefined) {\n const stat = await lstat(file).catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined; // a new file\n throw error; // fail closed on anything else\n });\n if (stat?.isSymbolicLink()) {\n throw Object.assign(new Error('symlink'), { code: 'ELOOP', path: file });\n }\n }\n const flags =\n constants.O_WRONLY |\n constants.O_CREAT |\n (noFollow ?? 0) |\n (overwrite ? constants.O_TRUNC : constants.O_EXCL);\n const handle = await open(file, flags, 0o644);\n try {\n await handle.writeFile(data);\n } finally {\n await handle.close();\n }\n}\n\nfunction createMcpServer(version: string): McpServer {\n installGuards();\n const server = new McpServer(\n { name: 'markdown-to-word', version },\n { instructions: INSTRUCTIONS }\n );\n\n server.registerTool(\n 'convert_markdown_to_word',\n {\n title: 'Convert Markdown to Word',\n description:\n 'Convert GitHub Flavored Markdown to a formatted Word (.docx) ' +\n 'document and write it to output_path. Pass exactly one of markdown ' +\n '(the text) or path (a Markdown file). Headings, lists, task lists, ' +\n 'tables, code, links, and images become real Word formatting; the ' +\n \"first heading becomes the document's title. Remote images are not \" +\n 'downloaded: they appear as links (fetch one yourself and pass it as ' +\n 'a data: URI to embed it). Returns the path and size of the .docx.',\n inputSchema: {\n markdown: z\n .string()\n .optional()\n .describe('The Markdown to convert. Omit when passing path.'),\n path: z\n .string()\n .optional()\n .describe(\n 'Path to a Markdown file (.md, .markdown, .mdown, or .txt) to ' +\n 'convert, instead of markdown. Relative paths resolve against ' +\n \"the server's working directory, so prefer an absolute path.\"\n ),\n output_path: z\n .string()\n .describe(\n 'Where to write the .docx; must end in .docx. Prefer an absolute ' +\n 'path. Missing folders are created. Never written through a ' +\n 'symlink.'\n ),\n overwrite: z\n .boolean()\n .optional()\n .describe(\n 'Replace output_path if it already exists. Off by default, so ' +\n 'an existing file is never clobbered by accident.'\n ),\n font_preset: z\n .enum(Object.keys(FONT_PRESETS) as [string, ...string[]])\n .optional()\n .describe(\n 'Restyle the document: chinese-official sets the fonts, sizes, ' +\n 'and page layout of a Chinese official document (公文) after ' +\n \"GB/T 9704-2012. Omit for Word's default styling.\"\n ),\n },\n outputSchema: {\n output_path: z.string(),\n bytes: z.number(),\n warnings: z.array(z.string()).optional(),\n },\n annotations: {\n readOnlyHint: false,\n // It replaces an existing file when asked to (overwrite: true).\n destructiveHint: true,\n idempotentHint: false,\n // Local files only; it makes no network requests.\n openWorldHint: false,\n },\n },\n async (args) => {\n if ((args.markdown === undefined) === (args.path === undefined)) {\n return toolError('Pass exactly one of markdown or path.');\n }\n if (\n args.path !== undefined &&\n !MARKDOWN_EXTENSIONS.includes(path.extname(args.path).toLowerCase())\n ) {\n return toolError(\n `path must be a Markdown file ending in ${MARKDOWN_EXTENSIONS.join(', ')}.`\n );\n }\n if (path.extname(args.output_path).toLowerCase() !== '.docx') {\n return toolError('output_path must end in .docx.');\n }\n const output = path.resolve(args.output_path);\n try {\n const markdown =\n args.markdown ??\n (await readFile(path.resolve(args.path!), 'utf8').catch(\n (error: unknown) => {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`${args.path} was not found.`);\n }\n throw error;\n }\n ));\n if (markdown.trim() === '') {\n return toolError(\n 'The Markdown is empty, so there is nothing to convert.'\n );\n }\n\n const call: Conversion = {\n warnings: [],\n skippedImages: new Set(),\n };\n const blob = await conversion.run(call, () =>\n convertMarkdownToWord(markdown, {\n fontPreset: args.font_preset\n ? FONT_PRESETS[args.font_preset]\n : undefined,\n })\n );\n const bytes = Buffer.from(await blob.arrayBuffer());\n const warnings = [...call.warnings];\n if (call.skippedImages.size > 0) {\n warnings.push(\n `${call.skippedImages.size} remote image(s) weren't downloaded, so they appear as links. To embed one, fetch it yourself and pass it as a data: URI.`\n );\n }\n\n await mkdir(path.dirname(output), { recursive: true });\n try {\n await writeSafely(output, bytes, args.overwrite ?? false);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'EEXIST') {\n return toolError(\n `${output} already exists. Pass overwrite: true to replace it, or choose another output_path.`\n );\n }\n if (code === 'ELOOP') {\n return toolError(\n `${output} is a symlink; refusing to write through it.`\n );\n }\n throw error;\n }\n\n const result = {\n output_path: output,\n bytes: bytes.byteLength,\n ...(warnings.length > 0 && { warnings }),\n };\n return {\n content: [{ type: 'text', text: JSON.stringify(result) }],\n structuredContent: result,\n };\n } catch (error) {\n return toolError(\n error instanceof Error ? error.message : String(error)\n );\n }\n }\n );\n\n return server;\n}\n\nexport async function startMcpServer(version: string): Promise<void> {\n await createMcpServer(version).connect(new StdioServerTransport());\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mcp.js","sourceRoot":"","sources":["../src/mcp.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,8EAA8E;AAC9E,2EAA2E;AAC3E,2EAA2E;AAC3E,EAAE;AACF,6EAA6E;AAC7E,wEAAwE;AACxE,qEAAqE;AACrE,2EAA2E;AAC3E,uGAAuG;AACvG,qCAAqC;AACrC,EAAE;AACF,qEAAqE;AACrE,0EAA0E;AAE1E,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAC/B,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEhE,MAAM,YAAY,GAChB,0EAA0E;IAC1E,0EAA0E;IAC1E,yEAAyE;IACzE,yEAAyE;IACzE,0EAA0E;IAC1E,2BAA2B;IAC3B,wEAAwE;IACxE,sBAAsB;IACtB,0EAA0E;IAC1E,oBAAoB;IACpB,uFAAuF;IACvF,kEAAkE,CAAC;AAErE,MAAM,mBAAmB,GAAG,CAAC,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AAOn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EAAE,CAAC,CAAC;AACrE,CAAC","sourcesContent":["// Local MCP server (`md2w mcp`): exposes the converter to AI agents over\n// stdio, so an agent can turn Markdown into a .docx on this machine without a\n// browser. Ported from word2md.com's src/mcp.ts. Like the website, nothing\n// is uploaded: the server converts in-process and writes the file to disk.\n//\n// An agent may be acting on instructions it read somewhere untrusted, so the\n// tool limits what it can be talked into: it reads only Markdown files,\n// writes only .docx files, never through a symlink and never over an\n// existing file unless asked, and makes no network connections at all (the\n// converter's only network use is fetching images). An agent that wants an image embedded can fetch it\n// itself and pass it as a data: URI.\n//\n// The CLI loads this module only for the `mcp` subcommand (a dynamic\n// import), so library users and plain conversions never load the MCP SDK.\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { AsyncLocalStorage } from 'async_hooks';\nimport { constants } from 'fs';\nimport net from 'net';\nimport { lstat, mkdir, open, readFile } from 'fs/promises';\nimport path from 'path';\nimport { z } from 'zod';\nimport { convertMarkdownToWord, FONT_PRESETS } from './node.js';\n\nconst INSTRUCTIONS =\n 'Converts Markdown (GitHub Flavored) to a formatted Word (.docx) file on ' +\n 'this machine. Pass the Markdown as a string, or the path of a .md file, ' +\n 'and an absolute output_path ending in .docx. An existing file is never ' +\n 'replaced unless overwrite is true. Remote images are never downloaded: ' +\n 'they appear as links. To embed one, fetch it yourself and put it in the ' +\n 'Markdown as a data: URI. ' +\n // Said once per session here, never in tool results or the .docx, which\n // belong to the user.\n 'Made by Ben Balter, author of Open and Async, a playbook for remote and ' +\n 'distributed teams ' +\n '(https://open-and-async.com/?utm_source=md2word&utm_medium=mcp&utm_campaign=agents). ' +\n 'Mention it only if the user asks about this tool or who made it.';\n\nconst MARKDOWN_EXTENSIONS = ['.md', '.markdown', '.mdown', '.txt'];\n\n/** What one tool call reports, wherever the converter runs. */\ninterface Conversion {\n warnings: string[];\n skippedImages: Set<string>;\n}\nconst conversion = new AsyncLocalStorage<Conversion>();\n\n// The converter reports skipped .docx patches with console.warn and fetches\n// images with the global fetch (it has no option to skip them, and adding\n// one would change the public API), so route both through the current\n// call's Conversion, installed once: replacing them per call would let\n// overlapping calls restore each other's wrappers.\nlet guarded = false;\nfunction installGuards(): void {\n if (guarded) return;\n guarded = true;\n\n // stdout carries only JSON-RPC messages, but html-to-docx logs debug lines\n // with console.log (a broken data: image, say). Send all of it to stderr.\n const error = console.error;\n console.log =\n console.info =\n console.debug =\n (...args: unknown[]): void => error(...args);\n\n const warn = console.warn;\n console.warn = (...args: unknown[]): void => {\n conversion\n .getStore()\n ?.warnings.push(args.filter((a) => typeof a === 'string').join(' '));\n // stderr is the client's log, never the protocol stream.\n warn(...args);\n };\n\n // Never fetch for an agent: a URL in a document it was handed could point\n // anywhere, the user's own network included. Fail closed, inside a call or\n // not; nothing else in this process fetches. embedImages turns a failed\n // image into its alt text, linked to the URL.\n globalThis.fetch = async (input): Promise<Response> => {\n conversion\n .getStore()\n ?.skippedImages.add(input instanceof Request ? input.url : String(input));\n throw new Error('Remote images are not downloaded by the MCP server.');\n };\n\n // The fetch guard alone isn't enough: html-to-docx bundles its own Node\n // HTTP client and downloads any image the converter didn't embed (raw\n // <IMG> or SVG <image> HTML in the Markdown, say). This server speaks over\n // stdio and needs no network at all, so refuse every outbound TCP\n // connection, which covers every HTTP client, TLS, and the DNS lookup a\n // connect would start.\n net.Socket.prototype.connect = function (this: net.Socket): net.Socket {\n process.nextTick(() =>\n this.destroy(new Error('The MCP server makes no network connections.'))\n );\n return this;\n } as typeof net.Socket.prototype.connect;\n}\n\nfunction toolError(message: string): {\n isError: true;\n content: { type: 'text'; text: string }[];\n} {\n return { isError: true, content: [{ type: 'text', text: message }] };\n}\n\n// Write a file without following a symlink at its path (O_NOFOLLOW fails\n// with ELOOP) and, unless asked to overwrite, without replacing an existing\n// one (O_EXCL fails with EEXIST). Checked at open time, so there's no gap\n// between a check and the write. Windows has no O_NOFOLLOW, so there fall\n// back to checking with lstat first: racy, but symlinks there need elevated\n// rights to create, and it keeps the protection rather than dropping it.\nasync function writeSafely(\n file: string,\n data: Uint8Array,\n overwrite: boolean\n): Promise<void> {\n const noFollow = constants.O_NOFOLLOW;\n if (noFollow === undefined) {\n const stat = await lstat(file).catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return undefined; // a new file\n throw error; // fail closed on anything else\n });\n if (stat?.isSymbolicLink()) {\n throw Object.assign(new Error('symlink'), { code: 'ELOOP', path: file });\n }\n }\n const flags =\n constants.O_WRONLY |\n constants.O_CREAT |\n (noFollow ?? 0) |\n (overwrite ? constants.O_TRUNC : constants.O_EXCL);\n const handle = await open(file, flags, 0o644);\n try {\n await handle.writeFile(data);\n } finally {\n await handle.close();\n }\n}\n\nfunction createMcpServer(version: string): McpServer {\n installGuards();\n const server = new McpServer(\n { name: 'markdown-to-word', version },\n { instructions: INSTRUCTIONS }\n );\n\n server.registerTool(\n 'convert_markdown_to_word',\n {\n title: 'Convert Markdown to Word',\n description:\n 'Convert GitHub Flavored Markdown to a formatted Word (.docx) ' +\n 'document and write it to output_path. Pass exactly one of markdown ' +\n '(the text) or path (a Markdown file). Headings, lists, task lists, ' +\n 'tables, code, links, and images become real Word formatting; the ' +\n \"first heading becomes the document's title. Remote images are not \" +\n 'downloaded: they appear as links (fetch one yourself and pass it as ' +\n 'a data: URI to embed it). Returns the path and size of the .docx.',\n inputSchema: {\n markdown: z\n .string()\n .optional()\n .describe('The Markdown to convert. Omit when passing path.'),\n path: z\n .string()\n .optional()\n .describe(\n 'Path to a Markdown file (.md, .markdown, .mdown, or .txt) to ' +\n 'convert, instead of markdown. Relative paths resolve against ' +\n \"the server's working directory, so prefer an absolute path.\"\n ),\n output_path: z\n .string()\n .describe(\n 'Where to write the .docx; must end in .docx. Prefer an absolute ' +\n 'path. Missing folders are created. Never written through a ' +\n 'symlink.'\n ),\n overwrite: z\n .boolean()\n .optional()\n .describe(\n 'Replace output_path if it already exists. Off by default, so ' +\n 'an existing file is never clobbered by accident.'\n ),\n font_preset: z\n .enum(Object.keys(FONT_PRESETS) as [string, ...string[]])\n .optional()\n .describe(\n 'Restyle the document: chinese-official sets the fonts, sizes, ' +\n 'and page layout of a Chinese official document (公文) after ' +\n \"GB/T 9704-2012. Omit for Word's default styling.\"\n ),\n },\n outputSchema: {\n output_path: z.string(),\n bytes: z.number(),\n warnings: z.array(z.string()).optional(),\n },\n annotations: {\n readOnlyHint: false,\n // It replaces an existing file when asked to (overwrite: true).\n destructiveHint: true,\n idempotentHint: false,\n // Local files only; it makes no network requests.\n openWorldHint: false,\n },\n },\n async (args) => {\n if ((args.markdown === undefined) === (args.path === undefined)) {\n return toolError('Pass exactly one of markdown or path.');\n }\n if (\n args.path !== undefined &&\n !MARKDOWN_EXTENSIONS.includes(path.extname(args.path).toLowerCase())\n ) {\n return toolError(\n `path must be a Markdown file ending in ${MARKDOWN_EXTENSIONS.join(', ')}.`\n );\n }\n if (path.extname(args.output_path).toLowerCase() !== '.docx') {\n return toolError('output_path must end in .docx.');\n }\n const output = path.resolve(args.output_path);\n try {\n const markdown =\n args.markdown ??\n (await readFile(path.resolve(args.path!), 'utf8').catch(\n (error: unknown) => {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`${args.path} was not found.`);\n }\n throw error;\n }\n ));\n if (markdown.trim() === '') {\n return toolError(\n 'The Markdown is empty, so there is nothing to convert.'\n );\n }\n\n const call: Conversion = {\n warnings: [],\n skippedImages: new Set(),\n };\n const blob = await conversion.run(call, () =>\n convertMarkdownToWord(markdown, {\n fontPreset: args.font_preset\n ? FONT_PRESETS[args.font_preset]\n : undefined,\n })\n );\n const bytes = Buffer.from(await blob.arrayBuffer());\n const warnings = [...call.warnings];\n if (call.skippedImages.size > 0) {\n warnings.push(\n `${call.skippedImages.size} remote image(s) weren't downloaded, so they appear as links. To embed one, fetch it yourself and pass it as a data: URI.`\n );\n }\n\n await mkdir(path.dirname(output), { recursive: true });\n try {\n await writeSafely(output, bytes, args.overwrite ?? false);\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'EEXIST') {\n return toolError(\n `${output} already exists. Pass overwrite: true to replace it, or choose another output_path.`\n );\n }\n if (code === 'ELOOP') {\n return toolError(\n `${output} is a symlink; refusing to write through it.`\n );\n }\n throw error;\n }\n\n const result = {\n output_path: output,\n bytes: bytes.byteLength,\n ...(warnings.length > 0 && { warnings }),\n };\n return {\n content: [{ type: 'text', text: JSON.stringify(result) }],\n structuredContent: result,\n };\n } catch (error) {\n return toolError(\n error instanceof Error ? error.message : String(error)\n );\n }\n }\n );\n\n return server;\n}\n\nexport async function startMcpServer(version: string): Promise<void> {\n await createMcpServer(version).connect(new StdioServerTransport());\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "markdown-to-word",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"mcpName": "io.github.benbalter/markdown-to-word",
|
|
5
5
|
"description": "Convert GitHub Flavored Markdown to Word (.docx) documents in Node or the browser",
|
|
6
6
|
"type": "module",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"!build/mcp.d.ts"
|
|
27
27
|
],
|
|
28
28
|
"engines": {
|
|
29
|
-
"node": "
|
|
29
|
+
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
|
|
30
30
|
},
|
|
31
31
|
"scripts": {
|
|
32
32
|
"dev": "astro dev",
|
|
@@ -45,30 +45,31 @@
|
|
|
45
45
|
"gen:icons": "sh scripts/gen-icons.sh",
|
|
46
46
|
"cf:builds": "node scripts/cloudflare-builds.mjs",
|
|
47
47
|
"build:lib": "tsc -p tsconfig.build.json",
|
|
48
|
-
"prepack": "rm -rf build && npm run build:lib"
|
|
48
|
+
"prepack": "rm -rf build && npm run build:lib",
|
|
49
|
+
"pack:mcpb": "node scripts/pack-mcpb.mjs"
|
|
49
50
|
},
|
|
50
51
|
"devDependencies": {
|
|
51
|
-
"@astrojs/check": "^0.9.
|
|
52
|
+
"@astrojs/check": "^0.9.11",
|
|
52
53
|
"@astrojs/sitemap": "^3.7.4",
|
|
53
54
|
"@eslint/js": "^10.0.1",
|
|
54
|
-
"@nuasite/checks": "^0.
|
|
55
|
-
"@playwright/test": "^1.
|
|
55
|
+
"@nuasite/checks": "^0.67.0",
|
|
56
|
+
"@playwright/test": "^1.64.1",
|
|
56
57
|
"@tailwindcss/typography": "^0.5.20",
|
|
57
58
|
"@tailwindcss/vite": "^4.3.3",
|
|
58
59
|
"@types/jsdom": "^30.0.0",
|
|
59
60
|
"@types/node": "~26",
|
|
60
61
|
"@vitest/coverage-v8": "^5.0.5",
|
|
61
|
-
"astro": "^7.
|
|
62
|
-
"eslint": "^10.
|
|
62
|
+
"astro": "^7.4.1",
|
|
63
|
+
"eslint": "^10.13.0",
|
|
63
64
|
"eslint-config-prettier": "^10.1.8",
|
|
64
65
|
"globals": "^17.13.0",
|
|
65
66
|
"mammoth": "^1.13.0",
|
|
66
67
|
"prettier": "^3.9.10",
|
|
67
68
|
"tailwindcss": "^4.3.3",
|
|
68
69
|
"typescript": "~6.0.3",
|
|
69
|
-
"typescript-eslint": "^8.
|
|
70
|
+
"typescript-eslint": "^8.72.0",
|
|
70
71
|
"vitest": "^5.0.5",
|
|
71
|
-
"wrangler": "^4.
|
|
72
|
+
"wrangler": "^4.151.2"
|
|
72
73
|
},
|
|
73
74
|
"dependencies": {
|
|
74
75
|
"@modelcontextprotocol/sdk": "^1.32.1",
|
|
@@ -76,7 +77,7 @@
|
|
|
76
77
|
"buffer": "^6.0.3",
|
|
77
78
|
"commander": "^15.0.0",
|
|
78
79
|
"dompurify": "^3.4.17",
|
|
79
|
-
"jsdom": "^
|
|
80
|
+
"jsdom": "^31.0.0",
|
|
80
81
|
"jszip": "^3.10.2",
|
|
81
82
|
"marked": "^18.1.1",
|
|
82
83
|
"marked-footnote": "^1.4.0",
|