Document processing and templates
Deterministic template filling, table updates, redline comparison, and batch conversion without an LLM.
Every document operation in revise and revise/server works deterministically from ordinary TypeScript—no AI model is required.
Fill a .docx template#
Open a template .docx in "editing" mode on Node, substitute placeholders with replaceAll(), verify no unintended misses remain, and export DOCX (preserving untouched template bytes) or archival PDF:
import { writeFile } from "node:fs/promises";
import { ReviseDocument } from "revise/server";
const doc = await ReviseDocument.open("nda-template.docx", {
mode: "editing",
author: "Contract Generator",
});
try {
const vars: Record<string, string> = {
"{{CLIENT_NAME}}": "Northstar Labs, Inc.",
"{{EFFECTIVE_DATE}}": "November 21, 2026",
"{{GOVERNING_LAW}}": "Delaware",
};
for (const [token, value] of Object.entries(vars)) {
const res = await doc.replaceAll(token, value, { exact: true });
if (res.failures.length > 0) {
throw new Error(`Failed replacing ${token}: ${res.failures[0].message}`);
}
}
// Verify no unfilled placeholders remain
const remaining = doc.grep(/\{\{[A-Z0-9_]+\}\}/);
if (remaining.length > 0) {
throw new Error(`Unfilled placeholders in blocks: ${remaining.map((h) => h.id).join(", ")}`);
}
const docx = await doc.export({ format: "docx", mode: "final" });
await writeFile("nda-northstar.docx", docx.bytes);
const pdf = await doc.export({ format: "pdf", pdfStandard: "pdf-a-2b" });
await writeFile("nda-northstar.pdf", pdf.bytes);
} finally {
doc.dispose();
}replaceAll() runs across body paragraphs, lists, tables, headers, footers, footnotes, and endnotes. Pass exact: true for literal placeholder tokens; omit it to normalize curly/straight quotes and non-breaking spaces.
Populate tables deterministically#
Table mutation tools enforce read-before-write on the session so row IDs and merged cells cannot shift silently. Call read_table with mode: "rows" first, then batch up to 50 cell updates in edit_table_cells (or append rows with insert_table_row):
const summary = await doc.summary();
const tableId = summary.tables[0]?.id;
if (!tableId) throw new Error("No table found");
const rows = await doc.tools.call("read_table", {
table_id: tableId,
mode: "rows",
});
if (!rows.ok) throw new Error(rows.error.message);
const edit = await doc.tools.call(
"edit_table_cells",
{
table_id: tableId,
mode: "replace",
cells: [
{ row_id: "r1", column: 1, text: "$12,000" },
{ row_id: "r2", column: 1, text: "$4,500" },
],
},
{ directMode: true },
);
if (!edit.ok) throw new Error(edit.error.message);For rich block insertions or new documents built from structured data, emit Revise semantic HTML into ReviseDocument.create({ html }) or insert_block.
Compare two versions into a redline#
Generate a tracked-changes redline between two .docx files, inspect or filter changes by section, and either export .docx or transfer the Yjs state to <ReviseEditor /> for human review:
import * as Y from "yjs";
import { compare } from "revise/server";
const redline = await compare("msa-v1.docx", "msa-v2.docx");
try {
// Sanity check that accept-all reproduces v2 and reject-all reproduces v1
console.log(redline.verified);
// Inspect or selectively settle by section
const feeChanges = await redline.document.changes({ section: "Fees" });
await redline.document.accept({ ids: feeChanges.map((c) => c.id) });
// Export as Word redline, or send Yjs update bytes to a browser editor
const { bytes } = await redline.document.export({ format: "docx" });
const yjsUpdate = Y.encodeStateAsUpdate(redline.document.ydoc);
} finally {
redline.document.dispose();
}Batch format conversion#
import { writeFile } from "node:fs/promises";
import { convert } from "revise/server";
const pdfBytes = await convert("contract.docx", "pdf");
const mdBytes = await convert("contract.docx", "markdown");
await writeFile("contract.pdf", pdfBytes);
await writeFile("contract.md", mdBytes);Browser vs. server API differences#
The browser editor (revise) and Node library (revise/server) share the same document model and tool schemas, with a few surface differences:
| Operation | Browser (editor) | Node (revise/server doc) |
|---|---|---|
| Typed tool call (non-throwing) | editor.tools.execute(name, input, { directMode }) | doc.tools.call(name, input, { directMode }) |
Typed tool call (throws ReviseToolError) | editor.tools.call(name, input, { directMode }) | — (check result.ok) |
| Untyped model call | editor.tools.executeDynamic(name, input, { directMode }) | doc.tools.run(name, input, { direct }) |
| High-level helpers | getStatistics(), getSourceFidelity(), review.listChanges() | replaceAll(), grep(), outline(), summary(), diff(), compare(), convert() |
Current boundaries for template apps#
- Word Content Controls (
w:sdt): Existing block, inline, row, cell, and nested SDTs (tags, aliases, IDs, bindings) are preserved on.docxround trip, but there is no public API yet to list or populate SDTs by tag. - Custom inline widgets: Because the editor renders to
<canvas>, host React components cannot be mounted inside document pages; render template controls (variable pickers, clause sidebars, approval panels) outside the canvas using handle controllers. - Multi-DOCX merging: Combining multiple
.docxfiles into one document is not a single built-in call; insert semantic HTML blocks or append content per section.