Automate a DOCX with Node.js
Query a DOCX, accept its tracked changes, and save the result from Node.js.
Use the SDK when application code knows the operation it needs. No model is involved: the script queries, mutates, and saves deterministically.
1. Install the Node.js SDK
pnpm add @superdoc/sdk@latestThe SDK embeds the SuperDoc runtime. You do not need a separate CLI installation to use SuperDocClient.
2. Prepare a document
Download the tracked-changes fixture. Save it as contract.docx in your working directory. It contains the word termination and one tracked change. Any document meeting those two conditions also works.
3. Query, mutate, and save
Create accept-changes.mjs:
import { SuperDocClient } from '@superdoc/sdk';
/** @param {unknown} value */
function isSuccessfulReceipt(value) {
return typeof value === 'object' && value !== null && 'success' in value && value.success === true;
}
const client = new SuperDocClient();
try {
await client.connect();
const doc = await client.open({ doc: './contract.docx' });
try {
const match = await doc.query.match({
select: { type: 'text', pattern: 'termination' },
require: 'first',
});
console.log('Matched:', match.items[0]);
const receipt = await doc.trackChanges.decide({
decision: 'accept',
target: { kind: 'all' },
});
console.log('Mutation receipt:', receipt);
if (!isSuccessfulReceipt(receipt)) throw new Error('Accepting tracked changes failed.');
await doc.save({
out: './contract.accepted.docx',
force: true,
});
} finally {
await doc.close({ discard: true });
}
} finally {
await client.dispose();
}
Run it with Node.js:
node accept-changes.mjs4. Verify the output
Open contract.accepted.docx in Word or the SuperDoc editor. The tracked changes should be accepted. The original contract.docx remains unchanged.
Saving to a separate path leaves the source session dirty by design. After the output succeeds, close({ discard: true }) closes that in-memory session without overwriting the source file.
For the contract behind each step, read the Document API mental model.
Reuse one client across many operations
One SuperDocClient owns one SuperDoc host process. connect() starts that process once. Every open() adds a document session inside the same process, and every method on a document handle is one request to it. The SDK never starts a process per operation.
A client created per operation pays the whole cold path every time: process start, engine load, and for a collaboration document the room connect and initial sync. That cost is the same for a read, a search, or a comment, so it dominates any workflow that issues many small operations. Hoist the client and the open out of the per-operation path:
import { createSuperDocClient } from '@superdoc/sdk';
// Once per service, or once per collaboration room you serve.
const client = createSuperDocClient({ user: { name: 'AI Assistant', email: 'agent@example.com' } });
await client.connect();
const document = await client.open({
doc: 'contract-123',
collaboration: { providerType: 'hocuspocus', url: 'wss://collaboration.example.com', documentId: 'contract-123' },
});
// Many times per agent turn. Each call reuses the open session.
const info = await document.info();
const matches = await document.query.match({ select: { type: 'text', pattern: 'termination' }, require: 'all' });
// When the room or the service shuts down.
await document.close();
await client.dispose();What that lifetime means in practice:
- A handle is a session. Open a document once and keep the handle for as long as the workflow needs it. One client can hold several open documents; each handle is its own session.
- One host runs one request at a time. Operations on the same client queue. For parallel throughput across documents, run a small pool of clients and lease one per in-flight workflow. A client's
requestTimeoutMsis fixed when its host starts; individual calls can still pass their owntimeoutMs. - Restart is automatic, sessions are not. If the host process exits, the next request starts a new one and every previously open handle is gone; reopen the document. Unsaved changes do not survive that: the session rehydrates from its on-disk context and loses whatever the last autosave had not yet written. Save at a point you choose.
- Refs expire, node ids do not. A
query.matchref is bound to the revision that produced it and stops resolving after any mutation. BlocknodeIdvalues stay stable across edits, so target follow-up work with{ kind: 'block', nodeType, nodeId }and re-runquery.matchonly when you need a text range.
Typical cost of each lifecycle for a 53-operation agent turn on a mid-sized document:
| Lifecycle | Median per call | Whole turn |
|---|---|---|
| New client per operation | ~460 ms | ~24 s |
| One client, open and close per operation | ~140 ms | ~8 s |
| One client, one open document | ~40 ms | ~3 s |
Batch many operations into one request
Two document-level batches collapse several operations into one request:
document.mutations.apply(plan)commits several text or formatting steps as one atomic transaction. Selector targets re-resolve before each step, so you do not re-search between them. See Mutation plans.document.plan.execute({ entries })runs a list of arbitrary operations in one request. Each entry is its own transaction, so a failure partway through keeps the earlier entries committed. Later entries can reference earlier results throughcaptureAsandcapture-refmarkers.
For example, anchor a batch of comments in a single request instead of one request per comment:
const result = await document.plan.execute({
entries: reviewNotes.map(({ quote, note }) => ({
operationId: 'comments.create',
input: { target: { text: quote }, text: note },
})),
});
// plan.execute reports a failed entry in `failure` rather than throwing. An
// ignored result is an ignored batch: it stops at the first hard failure, so
// later entries never ran.
if (result.failure) {
const { entryIndex, operationId, message } = result.failure;
throw new Error(`comment batch stopped at entry ${entryIndex} (${operationId}): ${message}`);
}Open a token-authenticated collaboration document
Pass a Hocuspocus or y-websocket token in the options for that document's open request:
const document = await client.open(
{
doc: './contract.docx',
collaboration: {
providerType: 'hocuspocus',
url: 'wss://collaboration.example.com',
documentId: 'contract-123',
},
},
{ collaborationAuth: { type: 'token', token: userToken } },
);The credential is separate from the collaboration profile and command-line arguments. It applies to the provider created for this open request. Per-open token authentication is not supported for Liveblocks.
To initialize a new room from a DOCX, set roomMode: 'create' for one worker. Later SDK sessions and editors use roomMode: 'join'. If multiple backend workers can start the same document, coordinate room creation in your backend and collaboration server before calling create.
When an opened room is ready to read
When client.open() resolves for a Hocuspocus or y-websocket room, the document already holds everything the collaboration
server it connected to had for that room. Your agent can read and decide right away; it doesn't need a delay or a
poll first. After create, a fresh join can read the new room at once.
That guarantee covers one server. If several server processes can hold the same room, open() doesn't wait for
edits that reached another process but not this one. Route every connection for a room to one process, or share
rooms between processes, for example with Hocuspocus's Redis extension, and treat edits that are still crossing
between processes as not yet in the room.
Being ready to read doesn't mean your agent's edits are stored. Storage depends on your collaboration server.
Confirm the server received your edits
An edit's result means the edit was applied in your agent's copy of the room. To know the collaboration server has it too, wait for a server receipt:
await document.insert({ value: ' Approved by the review agent.' });
await document.collaboration.waitForServerReceipt({ timeoutMs: 10_000 });It resolves once the server has received every edit this document made before the call. If the server doesn't confirm
within timeoutMs (the collaboration profile's syncTimeoutMs, 30 seconds by default, when you leave it out), it
throws COLLABORATION_SYNC_TIMEOUT. The edits stay in your agent's copy and are sent again when the connection
recovers, so you can call it again later. A document opened without a collaboration room throws
CAPABILITY_UNSUPPORTED.
Received is not stored. Your server writes rooms to storage on its own schedule, so a receipt doesn't confirm that the
edit survives a server crash. If you need that, have your storage flow confirm it. The connection states that
SuperDoc reports, such as synced, describe the connection, not a single edit.
Await committed storage and cross-instance initial state
The collaboration server template supports an explicit storage contract:
await writer.insert({ value: ' Terms approved.' });
const { commitId } = await writer.collaboration.waitForStorageCommit({ timeoutMs: 10_000 });
await agent.collaboration.waitForInitialSync({ timeoutMs: 10_000 });
const currentText = await agent.getText();The storage commitment covers edits completed by writer before that call. Its commitId correlates the response
with that commitment call; success is returned after the backing store accepts the write. waitForInitialSync
then integrates the latest committed state before the agent reads or decides, including when it is connected to
another server process. Edits still held only in another client's memory are outside this boundary.
For the qualified multi-instance topology, run multiple template server processes on one host, all using the
same local SQLite database. The template README explains COLLABORATION_SQLITE_FILE, transaction and generation
handling. This contract does not cover separate hosts, network filesystems or Redis deployments.
Storage errors throw COLLABORATION_STORAGE_FAILED; a missing acknowledgement before the deadline throws
COLLABORATION_SYNC_TIMEOUT. A timeout leaves the store outcome uncertain, so keep the document and retry or verify
its state through a fresh reader. These calls require a server implementing the template's storage protocol;
ordinary connection readiness and server receipts retain their existing meaning.
Show the agent to people in the room
A collaborative SDK session is invisible to people in the room by default. Turn on collaboration.presence to show
it like any other participant: people in the browser see its name in the participant list, and its cursor moves to
the end of each edit it makes. With presence: true, the name comes from the client's user (the email is its stable
id). Without a user, the session appears as "CLI".
Pass an object instead of true to set an explicit identity:
const document = await client.open({
doc: './contract.docx',
collaboration: {
providerType: 'hocuspocus',
url: 'wss://collaboration.example.com',
documentId: 'contract-123',
presence: { name: 'Contract Bot', color: '#22AA66', userId: 'contract-bot' },
},
});| Field | Default | Meaning |
|---|---|---|
name | client user name, or "CLI" | Label shown next to the cursor |
color | a palette color | Cursor color as #RRGGBB |
userId | client user email, or the name | Stable identity across sessions |
followEdits | true | Move the cursor to the end of each edit |
Omit presence or pass false to keep the session invisible. To show where the agent is working before it edits,
place its cursor yourself:
await document.presence.set({ blockId: 'p1', start: 0, end: 12 });
await document.presence.set({ clear: true });The cursor stays on that text while other people edit around it. Only body text can hold the cursor. When the session closes, the agent leaves the room.
Reject stale writes from other hosts
expectedRevision checks one session by default.
When several backend workers or browsers write to the same Hocuspocus room, set expectedRevisionScope: 'room' and run the write admission extension on the server.
A write that started from a revision another host has already changed then fails with REVISION_MISMATCH instead of merging.
See Reject stale writes across hosts for the server setup and the REVISION_UNVERIFIED reasons.
Close a collaboration session
In a Hocuspocus or Liveblocks room, close() waits until the server confirms it has every change from the session,
then leaves the room. You can close right after your last edit; you don't need a delay or a poll of the room first.
The wait ends at the collaboration profile's syncTimeoutMs (30 seconds by default) or shortly before the close
request's own timeout, whichever comes first. If the server has not confirmed by then, the session is still released
and close() throws COLLABORATION_SYNC_TIMEOUT. Treat that as
"the room may be missing edits from this session":
import { SuperDocCliError } from '@superdoc/sdk';
try {
await document.close({ discard: true });
} catch (error) {
if (error instanceof SuperDocCliError && error.code === 'COLLABORATION_SYNC_TIMEOUT') {
// Reopen the room with roomMode: 'join' and check or reapply the session's edits.
}
throw error;
}To run an agent next to people editing in the browser, follow Add an agent in the collaboration server guide.
Record who changed what
A Node.js backend can join a room as an observer and copy attributed change records into its own store with await doc.changes.list({ after, waitMs: 30000, includeUpdate: true }). A cursor is valid only in the session that returned it. See Copy records to your own store for a complete observer.
Prefer Python? Follow the Python SDK guide for the same deterministic workflow. For Rust, follow the Rust SDK guide.