diff --git a/REFERENCE.md b/REFERENCE.md index abad4e6..e61012d 100644 --- a/REFERENCE.md +++ b/REFERENCE.md @@ -572,7 +572,7 @@ docx track-changes apply doc.docx --accept rev0 --reject rev1 # finalize: acce **Rich content.** Images insert from a path, `data:` URI, or `http(s)` URL (bounded fetch; SVG sanitized; non-public/metadata addresses refused at every redirect hop). HEIC/HEIF input is refused, by extension, MIME type, or file header, with an `IMAGE_SOURCE` error whose hint gives the conversion command (`sips` on macOS, `heif-convert` or ImageMagick on Linux): Word can't display HEIC, and docx-cli bundles no HEVC decoder. Equations round-trip OOXML `` ↔ LaTeX (reconstructed, not legacy plaintext) — authored via temml (LaTeX→MathML) plus an in-house MathML→OMML adapter. Code blocks emit one `CodeBlock`-styled paragraph per line with optional lowlight syntax highlighting (37 bundled languages); they collapse back to a GFM fenced block on read. GFM task lists round-trip Word's checkbox content control (and the Word-for-Web Wingdings-glyph variant), surfacing as `taskState` in the AST. Tables operate on a merge-aware logical grid so `gridSpan`/`vMerge` cells map onto physical ``, and structural edits refuse to bisect an existing merge. -**Markdown dialect.** `create --from`, `insert/edit --markdown`, and the note bodies all parse the same GFM + math + CriticMarkup + inline-HTML-formatting dialect (remark + remark-gfm + remark-math + an in-house inline-surgery transform), composing the existing OOXML emitters. `read` emits a compatible dialect, so the read → edit → write loop round-trips (lossless for paragraphs, lists, and nested blockquotes; code/tables/math/headings inside a blockquote intentionally escape to top level on import). `read --ast` is the fully lossless JSON form. The `[^tcN]` and `[^cN]` labels `read --current` / `--comments` add (and their definition lines) are read-time hints like the `` comments: the importer drops them, so pasting a `--current` line back applies its CriticMarkup exactly as if the labels weren't there, and never mints a footnote. Real footnotes read as `[^fnN]`/`[^enN]`; name your own anything but `tcN`/`cN`. +**Markdown dialect.** `create --from`, `insert/edit --markdown`, and the note bodies all parse the same GFM + math + CriticMarkup + inline-HTML-formatting dialect (remark + remark-gfm + remark-math + an in-house inline-surgery transform), composing the existing OOXML emitters. `read` emits a compatible dialect, so the read → edit → write loop round-trips (lossless for paragraphs, lists, and nested blockquotes; code/tables/math/headings inside a blockquote intentionally escape to top level on import). `read --ast` is the fully lossless JSON form. The `[^tcN]` and `[^cN]` labels `read --current` / `--comments` add (and their definition lines) are read-time hints like the `` comments: the importer drops them, so pasting a `--current` line back applies its CriticMarkup exactly as if the labels weren't there, and never mints a footnote. Real footnotes read as `[^fnN]`/`[^enN]`; name your own anything but `tcN`/`cN`. Block-level HTML is NOT converted: a line that opens with a block tag (`

`, `

`, `

`, ``, …) swallows everything up to the next blank line, so a block that carries text is refused with a `USAGE` error (exit 2, nothing written) rather than silently dropped — an HTML file passed to `create --from` fails instead of producing an empty document. Tag-only wrappers (`
` around real markdown) and `` comments still drop silently; inline tags inside a paragraph are unaffected. **Literal text — the parser-free channel.** When you want prose inserted _exactly_ — reviewer notes, quoted excerpts, anything where Markdown would misfire — use `create --text-file PATH` / `insert --text-file PATH` (or `-` for stdin). Every character lands verbatim and each newline starts a new paragraph; nothing is interpreted, so `3. note` stays `3.` (no ordered-list renumber), and `*x*`, `[t](u)`, bare URLs, and `{++x++}` are kept as written. This exists because GFM corruption isn't always escapable: bare URLs autolink with no escape sequence at all, and CriticMarkup eats `{++…++}` regardless of backslashes — so a literal path is the only safe way to author untouched prose. diff --git a/src/cli/create/index.tsx b/src/cli/create/index.tsx index 844eadc..87c8f4d 100644 --- a/src/cli/create/index.tsx +++ b/src/cli/create/index.tsx @@ -48,6 +48,9 @@ Options: stdin). One content source only. Uses the same markdown dialect as 'docx insert --markdown'. This is the canonical way to build a whole .docx from a markdown file. + HTML is not converted: block HTML that carries text + (an .html page,
/
/

blocks) is refused + and nothing is written — rewrite it as markdown. Footnote/endnote bodies keep bold/italic + hyperlinks; footnote labels renumber to [^fnN] on import. (Under track-changes, note bodies flatten to plain text.) @@ -193,43 +196,45 @@ export async function run(args: string[]): Promise { (parsed.values.author as string | undefined) ?? Bun.env.DOCX_AUTHOR ?? ""; const title = (parsed.values.title as string | undefined) ?? ""; - // Seed with --text (or empty) first. If --from was passed, we re-open the - // just-written package, replace the placeholder paragraph with parsed - // markdown blocks, and save again. We don't try to do the markdown parse - // inline against the raw template tree because MarkdownImport needs a - // full Document (relationships, content-types, lazy-provisioned views) to - // register footnote bodies / hyperlinks / images — all of which only come - // alive once the package is on disk and re-opened. We write the blank - // package straight to `destination` (the --output target if given, else - // FILE), then re-open and re-save that same file for the markdown pass. + // Build the blank package (seeded with --text, or empty) and run every + // content/geometry/marginals step against ONE in-memory Document over it, + // saving once at the end. `Document.fromPackage` gives MarkdownImport the + // full view set it needs (relationships, content-types, lazy-provisioned + // views) without a disk round-trip — and a refused source (bad image, block + // HTML that would drop text) writes NOTHING, so an existing FILE under + // --force survives a failed create. const pkg = buildBlankPackage({ path: destination, title, author, text }); - await pkg.save(); + const document = await Document.fromPackage(pkg); let blockCount = 1; // the seed paragraph buildBlankPackage emitted if (fromPath !== undefined) { - const applied = await applyMarkdownToBody(destination, fromPath); + const applied = await applyMarkdownToBody(document, fromPath); if (typeof applied === "number") return applied; blockCount = applied.blockCount; } else if (textFilePath !== undefined) { - const applied = await applyLiteralToBody(destination, textFilePath); + const applied = await applyLiteralToBody(document, textFilePath); if (typeof applied === "number") return applied; blockCount = applied.blockCount; } - // Apply page geometry to the fresh doc's trailing by re-opening - // (same build → re-open → mutate → save pattern --from/--text-file use). No - // tracking: a brand-new document has no prior state to snapshot. - if (hasGeometry) { - const applied = await applyGeometryToBody(destination, geometry); - if (typeof applied === "number") return applied; + // No tracking for geometry: a brand-new document has no prior state to + // snapshot. Headers/footers follow geometry so the part lands on the final + // trailing sectPr. + if (hasGeometry || hasMarginals) { + const sectPr = document.body.body.children + .filter((child) => child.tag === "w:sectPr") + .pop(); + if (!sectPr) { + return fail( + "USAGE", + "Internal: trailing not found in blank-package body", + ); + } + if (hasGeometry) applyPageGeometry(sectPr, geometry); + if (hasMarginals) applyMarginals(document, sectPr, marginals); } - // Headers/footers, applied after geometry so the part lands on the final - // trailing sectPr (same re-open-and-mutate pattern as the geometry step). - if (hasMarginals) { - const applied = await applyMarginalsToBody(destination, marginals); - if (typeof applied === "number") return applied; - } + await document.save(); await respondAck({ ok: true, @@ -246,7 +251,7 @@ export async function run(args: string[]): Promise { * empty placeholder paragraph. Returns an exit code on failure, or the * applied block count on success so the caller can report it in the ack. */ async function applyMarkdownToBody( - docxPath: string, + document: Document, markdownPath: string, ): Promise { let source: string; @@ -263,7 +268,6 @@ async function applyMarkdownToBody( ); } - const document = await Document.open(docxPath); let blocks: XmlNode[]; try { blocks = await new MarkdownImport(document).blocks(source); @@ -274,7 +278,7 @@ async function applyMarkdownToBody( throw error; } - return replacePlaceholderAndSave(document, blocks); + return replacePlaceholder(document, blocks); } /** Read literal text from PATH (or stdin), split it into one paragraph per line @@ -282,7 +286,7 @@ async function applyMarkdownToBody( * over the seed paragraph. The `create` counterpart of `insert --text-file`, * for building a doc from prose that GFM would corrupt. */ async function applyLiteralToBody( - docxPath: string, + document: Document, textFilePath: string, ): Promise { let source: string; @@ -299,48 +303,16 @@ async function applyLiteralToBody( ); } - const document = await Document.open(docxPath); - return replacePlaceholderAndSave(document, literalParagraphs(source)); + return replacePlaceholder(document, literalParagraphs(source)); } -/** Re-open the freshly-written doc and apply page geometry to its trailing - * `` (the document-wide one buildBlankPackage emits). Returns an exit - * code on failure, or void on success. */ -async function applyGeometryToBody( - docxPath: string, - geometry: PageGeometry, -): Promise { - const document = await Document.open(docxPath); - const sectPr = document.body.body.children - .filter((child) => child.tag === "w:sectPr") - .pop(); - if (!sectPr) { - return fail( - "USAGE", - "Internal: trailing not found in blank-package body", - ); - } - applyPageGeometry(sectPr, geometry); - await document.save(); - return undefined; -} - -/** Re-open the freshly-written doc and apply create-time headers/footers to its - * trailing `` (document-wide) via the `Marginals` lens. */ -async function applyMarginalsToBody( - docxPath: string, +/** Apply create-time headers/footers to the trailing (document-wide) + * `` via the `Marginals` lens. */ +function applyMarginals( + document: Document, + sectPr: XmlNode, marginals: { header?: string; footer?: string; pageNumbers: boolean }, -): Promise { - const document = await Document.open(docxPath); - const sectPr = document.body.body.children - .filter((child) => child.tag === "w:sectPr") - .pop(); - if (!sectPr) { - return fail( - "USAGE", - "Internal: trailing not found in blank-package body", - ); - } +): void { const lens = new Marginals(document); if (marginals.header !== undefined) { lens.set([sectPr], "header", "default", { text: marginals.header }); @@ -354,24 +326,22 @@ async function applyMarginalsToBody( align: "center", }); } - await document.save(); - return undefined; } -/** Replace the blank package's single seed `` with `blocks` and save. - * `buildBlankPackage` always emits exactly one placeholder `` plus the +/** Replace the blank package's single seed `` with `blocks` (the caller + * saves). `buildBlankPackage` always emits exactly one placeholder `` plus the * trailing ``; we swap the placeholder for the real content and leave * the sectPr at the tail. An empty `blocks` (markdown source that walked to * nothing) keeps the seed paragraph — splicing zero blocks would leave a bare * `` as a direct `` child, which ECMA-376 §17.2.2 frowns on * and Word for Mac flags on save. */ -async function replacePlaceholderAndSave( +async function replacePlaceholder( document: Document, blocks: XmlNode[], ): Promise { if (blocks.length === 0) return { blockCount: 1 }; - // `Document.open()` populated the embedded views; `document.body.body` is + // `Document.fromPackage()` populated the embedded views; `document.body.body` is // the parsed `` XmlNode. No need to re-walk the tree. const body = document.body.body; const placeholderIndex = body.children.findIndex( @@ -384,6 +354,5 @@ async function replacePlaceholderAndSave( ); } body.children.splice(placeholderIndex, 1, ...blocks); - await document.save(); return { blockCount: blocks.length }; } diff --git a/src/core/markdown/CLAUDE.md b/src/core/markdown/CLAUDE.md index d7572a4..bc2a167 100644 --- a/src/core/markdown/CLAUDE.md +++ b/src/core/markdown/CLAUDE.md @@ -90,7 +90,10 @@ itself round-trips through the ordinal). **These are read-time VISIBILITY hints, not round-trip carriers — ONE contract.** The importer DROPS every one: `walkBlock`'s `case "html"` returns `[]`, and the -inline walker drops inline comments. The structure survives normal edits via +inline walker drops inline comments. (One guard rides that drop: a block-HTML node whose +markup carries visible TEXT — `

Body

`, an `.html` page — is refused with +`USAGE` by `rejectTextBearingHtml` rather than dropped with its prose, issue #61; +comments and tag-only wrappers carry no text, so every `read` hint still drops.) The structure survives normal edits via in-place XML mutation; `read --ast` is the lossless view; and the authoring verbs (`docx sections`, `docx tables …`) manage it. So a from-scratch `create` is deliberately lossy for non-Markdown structure (a section break read → diff --git a/src/core/markdown/walker.tsx b/src/core/markdown/walker.tsx index ac20a4e..bb547e4 100644 --- a/src/core/markdown/walker.tsx +++ b/src/core/markdown/walker.tsx @@ -65,7 +65,9 @@ function walkBlock(node: RootContent, ctx: WalkContext): XmlNode[] { // `read` emits) — drop. These are read-time hints, not parse-back: the // importer never reconstructs structure from them (`--ast` is the // lossless view; edit-in-place + `docx sections` - // manage layout). Agents author through markdown features. + // manage layout). Agents author through markdown features. A block + // that would take TEXT with it is refused instead (issue #61). + rejectTextBearingHtml(node.value, node.position?.start.line); return []; case "footnoteDefinition": // The lens pre-collects footnote definitions and registers their @@ -88,6 +90,30 @@ function walkBlock(node: RootContent, ctx: WalkContext): XmlNode[] { } } +/** Refuse a raw block-HTML node whose markup carries visible text. CommonMark + * swallows a line that opens with a block tag (`

`, `

`, `

`, + * `

`, …) — and everything up to the next blank line — into ONE opaque + * `html` node, so dropping it drops the prose inside: an HTML file passed to + * `create --from` used to become an empty document at exit 0. Tag-only blocks + * (a README's `
` wrapper around real markdown) and comments + * (every `read` hint) carry no text and still drop silently. */ +function rejectTextBearingHtml(html: string, line: number | undefined): void { + const text = html + .replace(/|$)/g, " ") + .replace(/<[^>]*>/g, " ") + .replace(/&(?:nbsp|#160|#x0*a0);/gi, " ") + .replace(/\s+/g, " ") + .trim(); + if (text === "") return; + const where = line === undefined ? "" : ` at line ${line}`; + const preview = text.length > 60 ? `${text.slice(0, 57)}...` : text; + throw new MarkdownImportError( + "USAGE", + `Block-level HTML${where} would be dropped along with its text ("${preview}") — markdown input doesn't convert HTML blocks`, + "Rewrite it as markdown: `# Heading`, plain paragraphs, `| a | b |` tables, `**bold**`. Inline //// inside a paragraph are fine. To keep the text verbatim instead, strip the tags (or use --text-file where available).", + ); +} + function paragraphBlock( node: MdParagraph, ctx: WalkContext, diff --git a/tests/cli/create.test.ts b/tests/cli/create.test.ts index a9a4ed3..22cede8 100644 --- a/tests/cli/create.test.ts +++ b/tests/cli/create.test.ts @@ -467,3 +467,65 @@ describe("docx create — inline escape decoding (--text)", () => { expect(paragraph?.runs).toEqual([{ type: "text", text: "Hello world" }]); }); }); + +describe("docx create --from — block HTML (issue #61)", () => { + test("refuses an HTML file instead of writing an empty document", async () => { + const workspace = tempWorkspace("create-html"); + const source = join(workspace, "page.html"); + await Bun.write(source, "

Title

Body

"); + const docPath = join(workspace, "out.docx"); + + const result = await runCli("create", docPath, "--from", source); + expect(result.exitCode).toBe(2); + const error = result.parsed as { code: string; error: string }; + expect(error.code).toBe("USAGE"); + expect(error.error).toContain("Title"); + // Nothing is written when the content is refused. + expect(await Bun.file(docPath).exists()).toBe(false); + }); + + test("refuses block HTML with text inside otherwise-valid markdown", async () => { + const workspace = tempWorkspace("create-html-block"); + const source = join(workspace, "draft.md"); + await Bun.write( + source, + "Intro\n\n
Cell text
\n\nAfter\n", + ); + const docPath = join(workspace, "out.docx"); + + const result = await runCli("create", docPath, "--from", source); + expect(result.exitCode).toBe(2); + expect((result.parsed as { error: string }).error).toContain("line 3"); + expect(await Bun.file(docPath).exists()).toBe(false); + }); + + test("--force over an existing file leaves it untouched on refusal", async () => { + const workspace = tempWorkspace("create-html-force"); + const docPath = join(workspace, "out.docx"); + expect( + (await runCli("create", docPath, "--text", "Keep me")).exitCode, + ).toBe(0); + const source = join(workspace, "page.html"); + await Bun.write(source, "
Lost
"); + + const result = await runCli("create", docPath, "--from", source, "--force"); + expect(result.exitCode).toBe(2); + expect((await runCli("read", docPath)).stdout).toContain("Keep me"); + }); + + test("tag-only HTML and comments still pass (their content is markdown)", async () => { + const workspace = tempWorkspace("create-html-wrapper"); + const source = join(workspace, "readme.md"); + await Bun.write( + source, + '
\n\n# Title\n\nBody text\n\n
\n\n\n\n

 

\n', + ); + const docPath = join(workspace, "out.docx"); + + const result = await runCli("create", docPath, "--from", source); + expect(result.exitCode).toBe(0); + const markdown = (await runCli("read", docPath)).stdout; + expect(markdown).toContain("# Title"); + expect(markdown).toContain("Body text"); + }); +}); diff --git a/tests/cli/images.test.ts b/tests/cli/images.test.ts index 7a9ff94..33c2888 100644 --- a/tests/cli/images.test.ts +++ b/tests/cli/images.test.ts @@ -1225,12 +1225,9 @@ describe("HEIC/HEIF input is refused on every image ingress", () => { code: "IMAGE_SOURCE", hint: expect.stringContaining("sips -s format jpeg"), }); - // `create` stages the blank package before its markdown pass (a - // pre-existing trait of every --from failure), so assert no image landed. - const pkg = await Pkg.open(docPath); - expect(pkg.listParts().some((part) => part.startsWith("word/media/"))).toBe( - false, - ); + // `create` builds in memory and saves once, so a refused source writes + // nothing at all. + expect(await Bun.file(docPath).exists()).toBe(false); }); test("images replace refuses a .heic file or HEIC behind a .jpg label", async () => { diff --git a/tests/cli/insert.test.ts b/tests/cli/insert.test.ts index 28f1b3e..16a8c9b 100644 --- a/tests/cli/insert.test.ts +++ b/tests/cli/insert.test.ts @@ -1416,3 +1416,27 @@ describe("insert — inline markdown keeps backslash image paths intact", () => expect(xml).not.toContain("[site]"); }); }); + +describe("insert --markdown — block HTML (issue #61)", () => { + test("refuses block HTML that would drop its text, leaving the doc untouched", async () => { + const workspace = tempWorkspace("insert-html"); + const docPath = join(workspace, "doc.docx"); + expect((await runCli("create", docPath, "--text", "Seed")).exitCode).toBe( + 0, + ); + const before = await Bun.file(docPath).bytes(); + + const result = await runCli( + "insert", + docPath, + "--after", + "p0", + "
Lost paragraph
", + ); + expect(result.exitCode).toBe(2); + expect((result.parsed as { error: string }).error).toContain( + "Lost paragraph", + ); + expect(await Bun.file(docPath).bytes()).toEqual(before); + }); +});