Skip to Content
API Referenceautomation

@stesura/automation

Document automation nodes (conditionals, repeats, components) and the commands that apply your app’s results to them. Framework-free; the editor UI is in @stesura/automation-react. Concepts and setup are in the Automation guide.

Schema and plugins

withAutomation

Merges the automation nodes and grants into stesuraSchema props: stesuraSchema(withAutomation({ nodes: myNodes })). The caller’s own grants for the same attribute are merged, not replaced.

Parameters:
NameTypeDefault
propsSchemaProps
Returns:
{ nodes: { [x: string]: StesuraNodeSpec; }; globalAttributes: { nodes: { hidden: { conditional_block: true; conditional_inline: true; repeat_block_template: true; repeat_inline_template: true; }; }; definitions?: Record<...>; }; marks?: Record<...>; }

automationPlugins

Every automation plugin, for extraPlugins.

Parameters:
NameTypeDefault
options{ mode?: AutomationMode; }
Returns:
(Plugin<any> | Plugin<AutomationMode> | Plugin<DiagnosticsState>)[]

RepeatInlinePunctuation

Punctuation between inline repeat items: rendered by the node view and export, never stored as text.

NameTypeDefault
separatorstring | null

Between items, e.g. ”, ”.

lastSeparatorstring | null

Between the last two items, e.g. ” and ”; separator when null.

terminatorstring | null

After the last item, e.g. ”.”.

Applying results

Each apply is one transaction, kept out of undo history and track changes. Run setRepeatItems first: it creates the copies the other commands address.

setVisibility

Shows or hides nodes by id: true shows, false hides, an absent id is left alone. Applies to every node carrying the hidden attribute except repeat templates, whose visibility follows the mode. One undo-less, untracked transaction; false when nothing changes.

Parameters:
NameTypeDefault
visibleByIdReadonlyMap<string, boolean>
Returns:
Command

setRepeatItems

Sets the items of repeat repeatId to keys, in that order (see reconcileItems). An undo-less, untracked apply; false when the repeat is missing or already matches.

Parameters:
NameTypeDefault
repeatIdstring
keysreadonly string[]
Returns:
Command

setFieldValues

Sets the value of field nodes. An apply; false when nothing changes.

Parameters:
NameTypeDefault
valuesFieldValues
Returns:
Command

FieldValues

type FieldValues = | ReadonlyMap<string, string | null> | ((field: FieldTarget) => string | null | undefined);

A field’s value by name, or a resolver for fields whose value depends on where they are (a field in a repeat item takes that item’s value). A string shows it, null goes back to {{name}}, absent or undefined leaves the field.

FieldTarget

A field as a value resolver sees it: its name and the repeat items around it.

NameTypeDefault
namestring
framesFrame[]
posnumber

setComponentContent

Replaces the content of every component whose componentId is componentId (it bypasses the lock), and its version when given. An apply; false when nothing changes.

Parameters:
NameTypeDefault
componentIdstring
contentFragment
versionstring
Returns:
Command

createRepeatItem

A new item for key: a copy of the template’s content with derived ids.

Parameters:
NameTypeDefault
repeatNode
keystring
Returns:
Node | null

Structure

Template-mode authoring commands, and the mode itself.

insertConditional

Inserts a conditional at the cursor, or wraps the selection in one (selected blocks for block, the selected inline content for inline). Template mode only.

Parameters:
NameTypeDefault
kindAutomationKind
Returns:
Command

wrapInConditional

Wraps the selection in a conditional; false on an empty selection. Template mode only.

Parameters:
NameTypeDefault
kindAutomationKind
Returns:
Command

insertRepeat

Inserts a repeat whose template holds the selection (or placeholder content at a bare cursor), with no items: items come from setRepeatItems. Template mode only.

Parameters:
NameTypeDefault
kindAutomationKind
Returns:
Command

unwrapAutomationNode

Replaces the automation node at pos with its content. Template mode only.

Parameters:
NameTypeDefault
posnumber
Returns:
Command

deleteAutomationNode

Deletes the automation node at pos with its content. Template mode only.

Parameters:
NameTypeDefault
posnumber
Returns:
Command

addRepeatItem

Adds item key to repeat repeatId at index (default: last). False when the key exists.

Parameters:
NameTypeDefault
repeatIdstring
keystring
indexnumber
Returns:
Command

removeRepeatItem

Removes item key from repeat repeatId.

Parameters:
NameTypeDefault
repeatIdstring
keystring
Returns:
Command

AutomationKind

type AutomationKind = "block" | "inline";

Whether a wrapper holds blocks or inline content.

setAutomationMode

Switches the automation mode. Entering document hides every repeat template; entering template reveals everything, so the author sees all the content (conditional visibility in document mode is the consumer’s, through setVisibility). The writes are an apply: no undo, no tracking. Wrapper chrome changes with the mode, so pagination remeasures the wrappers.

Parameters:
NameTypeDefault
modeAutomationMode
Returns:
Command

getAutomationMode

The automation mode; template without the plugin.

Parameters:
NameTypeDefault
stateEditorState
Returns:
AutomationMode

AutomationMode

type AutomationMode = "template" | "document";
  • template: authoring. Wrappers show their chrome, nothing is hidden, repeat templates are visible and editable, fields show {{name}}.
  • document: the applied result. No chrome, conditionals hidden as the consumer decided, templates hidden, fields show their value.

Orthogonal to core’s edit/review/view EditorMode.

Diagnostics

setDiagnostics

Replaces the consumer’s diagnostics (by node id).

Parameters:
NameTypeDefault
byIdReadonlyMap<string, readonly Diagnostic[]>
Returns:
Command

getDiagnostics

A node’s diagnostics, consumer’s first; a stable empty array when none.

Parameters:
NameTypeDefault
stateEditorState
idstring
Returns:
readonly Diagnostic[]

Diagnostic

A problem shown on a node. The consumer’s carry its own message; the package’s structural ones carry a code UIs can translate.

NameTypeDefault
severityDiagnosticSeverity
messagestring
code(string & {}) | StructuralDiagnosticCode

DiagnosticSeverity

type DiagnosticSeverity = "error" | "warning" | "info";

How serious a Diagnostic is.

StructuralDiagnosticCode

type StructuralDiagnosticCode = "xref-into-conditional" | "note-shared-outside-conditional";

The diagnostics the package adds itself: a visible cross-reference points into a conditional, or a note anchor inside a conditional shares its note with one outside.

Reading the document

collectAutomationNodes

Every conditional, repeat, component (by id) and field (by name), in document order, with the repeat items enclosing it. Structure only: what the consumer joins its own logic, data and values onto. Nodes without an id are left out.

Parameters:
NameTypeDefault
docNode
Returns:
AutomationNodeEntry[]

AutomationNodeEntry

One entry of collectAutomationNodes: a conditional, repeat or component by id, or a field by name.

NameTypeDefault
posnumber
nodeNode
framesFrame[]

Enclosing repeat items, outermost first.

inTemplateboolean

Inside a repeat template: authored structure, not an applied copy.

kind"conditional" | "repeat" | "component" | "field"

Frame

An enclosing repeat item.

NameTypeDefault
repeatIdstring
itemKeystring
indexnumber

getFrames

The repeat items enclosing $pos, outermost first.

Parameters:
NameTypeDefault
$posResolvedPos
Returns:
Frame[]

isInTemplate

Whether $pos sits inside a repeat template.

Parameters:
NameTypeDefault
$posResolvedPos
Returns:
boolean

findNodeById

The first node of one of types whose id is id.

Parameters:
NameTypeDefault
docNode
idstring
typesReadonlySet<string>
Returns:
NodeWithPos | null

nodeIdOf

A node’s id attr when it is a non-empty string.

Parameters:
NameTypeDefault
nodeNode
Returns:
string | null

itemKeyOf

A repeat item’s key; attrs are unvalidated on the JSON/collab path.

Parameters:
NameTypeDefault
nodeNode
Returns:
string

deriveItemNodeId

The id a node copied from a repeat template gets in item key: a pure function of the template node’s id and the key, in core’s id format (12 [A-Za-z0-9]). Deterministic so a consumer can address the copies of a template conditional (deriveItemNodeId(templateNodeId, key)) without the document storing provenance, and so two actors applying the same keys produce the same steps.

Parameters:
NameTypeDefault
templateNodeIdstring
keystring
Returns:
string

templateNodeIdOf

The id derivedId was derived from: a node in its repeat’s template, or the repeat itself for an item’s own id. One level: for a copy inside nested repeats, call again on the result. Null when nothing in doc derives it.

Parameters:
NameTypeDefault
docNode
derivedIdstring
Returns:
string | null

Node types

Sets of node type names, for findNodeById and for walking a document.

CONDITIONAL_NODES

const CONDITIONAL_NODES: ReadonlySet<string>

conditional_block and conditional_inline.

REPEAT_NODES

const REPEAT_NODES: ReadonlySet<string>

repeat_block and repeat_inline.

REPEAT_TEMPLATE_NODES

const REPEAT_TEMPLATE_NODES: ReadonlySet<string>

The repeat templates: repeat_block_template and repeat_inline_template.

REPEAT_ITEM_NODES

const REPEAT_ITEM_NODES: ReadonlySet<string>

The repeat items: repeat_block_item and repeat_inline_item.

COMPONENT_NODES

const COMPONENT_NODES: ReadonlySet<string>

component_block and component_inline.

AUTOMATION_NODES

const AUTOMATION_NODES: ReadonlySet<string>

Every automation node type name.

AutomationNodeName

type AutomationNodeName = | "conditional_block" | "conditional_inline" | "repeat_block" | "repeat_block_template" | "repeat_block_item" | "repeat_inline" | "repeat_inline_template" | "repeat_inline_item" | "component_block" | "component_inline";

The type name of an automation node.

Your own transactions

markApply

Marks tr as an apply: kept out of undo history and track changes (applied results are not edits), and forces numbering and cross-references to re-run.

Parameters:
NameTypeDefault
trTransaction
Returns:
Transaction

isAutomationApply

Whether tr was marked with markApply.

Parameters:
NameTypeDefault
trTransaction
Returns:
boolean

Rendering and export

materialize

Turns an applied automation document into a plain Stesura document, a pure JSON → JSON pass (like docgen’s substituteVariables):

  • hidden subtrees and repeat templates are dropped;
  • visible wrappers (conditionals, repeats, items, components) are replaced by their content, inline repeats with their punctuation as text;
  • a field with a value becomes that text; one without stays a field (for substituteVariables) and is reported;
  • cross-references into dropped content become their stored text (the label kept when the editor hid their target), else Word’s error text, and the bodies of dropped notes go;
  • a container left empty is filled the way the schema requires.

The result is validated against schema, which needs no automation nodes; it throws when the result is not a valid document.

Parameters:
NameTypeDefault
docJSONContent
__1{ schema: Schema<any, any>; }
Returns:
{ doc: JSONContent; warnings: MaterializeWarning[]; }

MaterializeWarning

Something materialize could not render cleanly; the output is still valid.

NameTypeDefault
codeMaterializeWarningCode
messagestring

MaterializeWarningCode

type MaterializeWarningCode = | "field-without-value" | "reference-to-removed-content" | "emptied-container";

Why materialize warned.

automationDocx

DOCX export of a live (applied) document, for downloadDocx(…, automationDocx). The document is materialized first: the serializer’s pre-passes see the whole doc, so hidden footnotes would leave orphan note parts (an invalid file) and references into hidden content would show Word’s “Reference source not found”. The node handlers render a raw state for hosts that drop transformDoc: visible wrappers as their content, hidden content and repeat templates as nothing.

NameTypeDefault
nodesNodeSerializer

Handlers merged over the defaults (same name replaces).

transformDoc(doc: Node) => Node

Rewrites the document before anything reads it (preload, pre-passes, rendering), e.g. to resolve content that must not reach Word. Same schema.

preloadExtra(doc: Node) => Promise<Map<string, Buffer<ArrayBufferLike>>>

Bytes added to the image preload pass, keyed as handlers will ask for them through state.options.getImageBuffer. Runs alongside preloadImages.

traceDocxExportTrace

Filled with where the export’s time and bytes went (createExportTrace()).

lastModifiedBystring

The saving user’s name, stamped as cp:lastModifiedBy as Word does on save.

removeDocumentPropertiesboolean

Leaves the document’s properties (title, author, custom properties) out of the file, as Word’s Inspect Document → “Document Properties” does: kept otherwise, they reach whoever receives it (SEC-98).

redactionReasonsRedactionTaxonomy

Labels and colors of redaction reasons (the host’s taxonomy), for the content controls’ titles and boxes.

automationMarkdown

Markdown serialization of a live (applied) document: wrappers unwrap to their content, hidden content and repeat templates vanish, boundaries are dropped. One-way: markdown has no syntax for the structure, so parsing gives plain content. For a final document prefer materialize.

NameTypeDefault
fenceHandlersReadonly<Record<string, FenceHandler>>
nodeHandlersReadonly<Record<string, PmNodeHandler>>
Last updated on