# JavaScript API

JavaScript conventions, WASM loading, the error hierarchy, and a map of the texform module.

https://texform.dev/api/js

The `texform` npm package exposes the parser, document model, transform engine, and serializer from one Rust core, compiled to WebAssembly. Install it with `npm install texform`; see [Installation](/docs/installation) for supported runtimes and per-bundler notes. Methods, function names, and option keys use camelCase; the Python binding uses snake_case. Both bindings share the parsing and transform core, but configuration interfaces and some exception types differ.

The package ships Node, bundler, and lazy web builds behind one exports map. Importing the bare specifier `texform` resolves to `texform/node` under Node.js and `texform/bundler` under a bundler or browser; import a subpath only to force a build. The Node build loads the WebAssembly module through the filesystem and offers both ESM and CommonJS entry points, and needs no setup. The bundler build initializes WebAssembly during module evaluation, so it runs top-level `await` and your toolchain must treat `.wasm` as an asset. TypeScript declarations are bundled and shared by both builds.

Structured data crosses the boundary as plain objects described by interfaces in the bundled declarations, never custom wrapper classes. `Document`, `Node`, `Parser`, and `TransformEngine` are live class instances holding a WASM handle, and each exposes `free()` and `[Symbol.dispose]()` — under a `using` declaration the handle is released at scope exit, otherwise garbage collection reclaims it. A `SyntaxNode` is a plain object snapshot. A `Node`'s `kind` is a lowercase property, unlike Python's capitalized `kind()`; the discriminators inside argument and group views keep their capitalized form (`arg.kind === "Math"`).

Configuration is a single overlay layer: `ParseConfig`, `TransformConfig`, and `NormalizeConfig` are plain objects whose keys are all optional, and an omitted key keeps the profile or parser default. Unknown keys, snake_case keys, and wrong scalar types throw `TexformConfigError` with a field path. Enum *values* stay snake_case (`"sub_first"`) even though the keys are camelCase. The parse baseline is lenient.

The structured library errors derive from `TexformError` (which extends `Error`) and carry a `kind` discriminator: `TexformParseError`, `TexformEditError`, `TexformConfigError`, and `TexformTransformError`. `Parser.parse` returns malformed-input diagnostics and a `document` that may be `null`; invalid configuration still throws `TexformConfigError`.

## Modules

### [Parser](https://texform.dev/api/js/parser.md)

- `Parser` (class): A knowledge-driven LaTeX parser.
- `ParserOptions` (interface)
- `ParseConfig` (interface): Parser strictness configuration overlay, as a plain object with camelCase keys. All fields are optional; `null` / `undefined` means not set. Unknown keys, snake_case keys, arrays in object positions, and wrong scalar types throw TexformConfigError with a path.
- `ParseResult` (interface): The outcome of Parser.parse (and TransformEngine.parse): an optional Document plus the diagnostics emitted while parsing.
- `ParseDiagnostic` (interface): One diagnostic emitted while parsing, describing a recovered or rejected condition.
- `ParseDiagnosticContext` (interface): One nested context frame attached to a ParseDiagnostic, locating the enclosing construct (such as the command or environment) the error occurred within.
- `ParseDiagnosticKind` (typeAlias): The category of a ParseDiagnostic, or `null` when the parser emits a diagnostic without a specific category.
- `Span` (interface): A source byte range, half-open as `[start, end)`, indexing into the original LaTeX input.
- `SyntaxNode` (typeAlias): The lossless, immutable parse snapshot — the single serde wire format.
- `ContextItem` (typeAlias): One custom knowledge entry supplied to KnowledgeBase through the `items` option, discriminated by `target`.
- `CommandInfo` (interface): The knowledge-base entry for a command, returned by KnowledgeBase.lookupCommand and related lookups.
- `EnvInfo` (interface): The knowledge-base entry for an environment, returned by KnowledgeBase.lookupEnv.
- `CharacterInfo` (interface): The knowledge-base entry for a special character, returned by KnowledgeBase.lookupCharacter.
- `CharacterAttributesInfo` (interface): Rendering attributes for a special character in the knowledge base.
- `AllowedMode` (typeAlias): The content modes a command, environment, or character is allowed in: `"math"`, `"text"`, or `"both"`.
- `CommandKind` (typeAlias): The syntactic role of a command in the knowledge base: `"prefix"` (takes its arguments after the control sequence), `"infix"` (binds operands on both sides, like `\over`), or `"declarative"` (a scope-affecting declaration).
- `ArgSpecKindInfo` (typeAlias): The value kind one parsed argument slot accepts, with a `type` discriminator.
- `DelimiterTokenInfo` (typeAlias): A single delimiter token in an argspec form: a literal `char` (such as `(`) or a `control-seq` (such as `langle`).
- `ArgSpecFormInfo` (typeAlias): The syntactic form one parsed argument slot takes, with a `type` discriminator: a `standard` argument, a `star` flag, a brace `group`, a `delimited` argument bounded by an `open`/`close` pair, or a `paired` argument accepting any of several interchangeable delimiter `pairs`.

### [KnowledgeBase](https://texform.dev/api/js/knowledge-base.md)

- `KnowledgeBase` (class): Immutable knowledge shared by parsers, engines and documents.
- `KnowledgeBaseOptions` (interface): Construction options for an immutable KnowledgeBase.
- `DelimiterInfo` (interface)
- `ConstructionOptions` (interface): Options for the `create*` methods. `mode` is the context mode of the detached subtree. It defaults to text for `createInlineMath`, math for `createDelimitedGroup`, `createScripted`, `createPrime`, and `createInfix`, the group's own mode for `createGroup`, and the document root mode otherwise.

### [Document](https://texform.dev/api/js/document.md)

- `Document` (class): The editable LaTeX document tree — the working format you read, mutate, serialize, and transform.
- `NodeSpanEntry` (interface): One entry of Document.nodeSpans: a node identifier paired with its recorded source Span.
- `TokenizedLatex` (interface): Serialized LaTeX and tokens produced by the same serializer traversal.
- `SerializationToken` (interface): One non-empty serialization fragment.
- `SerializationTokenKind` (typeAlias): Closed semantic categories emitted by tokenized serialization.
- `NodeTable` (interface): Preorder node columns; field names stay snake_case in both bindings.
- `ArgumentTable` (interface): All argument slots, ordered by owner row and slot index.
- `ColumnarTree` (interface): Tree columns for bulk structural analysis with Arrow or DataFrame tools.

### [Node](https://texform.dev/api/js/node.md)

- `Node` (class): A read-only handle into a Document.
- `NodeKind` (typeAlias): The runtime kind of a Node, read from the lowercase Node.kind property.
- `SyntaxContentMode` (typeAlias): Content mode as it appears in a SyntaxNode snapshot: `"Math"` or `"Text"` (capitalized snapshot form).
- `RuntimeContentMode` (typeAlias): Content mode as reported by the runtime tree API: `"math"` or `"text"` (lowercase form used by Node.contentMode and the `mode` arguments of lookup methods).
- `GroupKind` (typeAlias): The kind of a group in SyntaxNode snapshot form: an `Explicit` brace group, an `Implicit` group, a `Delimited` group carrying its `left`/`right` delimiters, or an `InlineMath` group.
- `GroupKindRef` (typeAlias): The kind of a group in runtime view form, with a `kind` discriminator. Returned by Node.groupKind; the discriminator keeps its capitalized form (`'Explicit'`, `'Delimited'`, ...). A `Delimited` group carries `left` and `right` delimiter strings.
- `Delimiter` (typeAlias): A delimiter token in SyntaxNode snapshot form: the literal `"None"`, a single character (`{ Char }`), or a control sequence (`{ Control }`). Runtime views use delimiter strings instead: `.`, one character, or a backslash-prefixed control sequence such as `\langle`.
- `Argument` (interface): A present command/environment argument in SyntaxNode snapshot form, pairing its syntactic ArgumentKind with its parsed ArgumentValue.
- `ArgumentKind` (typeAlias): The syntactic kind of a command argument in SyntaxNode snapshot form (mandatory, optional, starred, group, until, or delimited/paired). Until forms carry `close`; delimited/paired forms carry `open` and `close`.
- `ArgumentValue` (typeAlias): The parsed value carried by an Argument in snapshot form: math or text content, a delimiter, a control-sequence name, a dimension, an integer, a key=value list, a column spec, or a boolean flag.
- `ArgumentSlot` (typeAlias): An argument slot of a Node's argument list: either a present Argument or an empty slot (`null`/`undefined`).
- `ArgRef` (typeAlias): A command/environment argument in runtime view form, returned by Node.arg and Node.argSlots.
- `ArgForm` (typeAlias): The delimiter form of an argument slot; `close` is present for `until`, and both `open` and `close` for `delimited` and `paired` forms.
- `NodeSlot` (typeAlias): The parent slot a Node fills; `index` is set for indexed slots such as children and arguments.
- `Arg` (typeAlias): A slot value accepted by construction and editing methods: a `string` is the source written inside the slot's boundaries, a detached Node is content, `boolean` sets a star slot, `null` omits an optional slot, and `{ value, open, close }` selects an explicit delimiter pair.

### [TransformEngine](https://texform.dev/api/js/transform-engine.md)

- `TransformEngine` (class): A profile-based normalization engine: a parser paired with a transform pipeline.
- `TransformEngineOptions` (interface): Construction options for TransformEngine: a shared knowledge base, the required normalization Profile, and optional rule disabling.
- `NormalizeConfig` (interface): Per-run overlay for TransformEngine.normalize: parse keys from ParseConfig plus transform keys from TransformConfig, flattened together. `null` / `undefined` / omitted means not set.
- `TransformConfig` (interface): The nested, per-phase transform configuration, overriding a profile's transform defaults.
- `RewriteConfig` (interface): Per-run switches for the fixed-point Rewrite phase.
- `LowerAttributesConfig` (interface): Per-run switches for the LowerAttributes phase.
- `FinalizeAstConfig` (interface): Per-run switches for the FinalizeAst phase.
- `FlattenGroupsConfig` (interface): Per-run switches for the FlattenGroups phase (redundant-brace removal).
- `NormalizeReportResult` (interface): Text plus the diagnostic report from TransformEngine.normalizeWithReport.
- `TransformReport` (interface): Diagnostic report for one explicit report call.
- `TransformWarning` (interface): An unknown input name whose arguments or scope cannot be guaranteed.
- `LowerAttributesReport` (interface): The LowerAttributes phase report.
- `AttributeStat` (interface): Activity for one `(attr, value)` pair in LowerAttributes.
- `AttributeFormCounts` (interface): Counts of an attribute form split by carrier: `declaratives` (scope-affecting declarations such as `{\bf ...}`) and `prefixes` (prefix commands such as `\mathbf{...}`).
- `RewriteRuleStat` (interface): One rewrite rule's outcome for a single call.
- `RewriteReport` (interface): The Rewrite phase report.
- `FinalizeAstReport` (interface): The FinalizeAst phase report.
- `FlattenGroupsActionCounts` (interface): Flatten actions that changed the tree.
- `FlattenGroupsGuardCounts` (interface): Preserve-guard hits for one FlattenGroups run.
- `FlattenGroupsReport` (interface): The FlattenGroups phase report.
- `TransformProfile` (typeAlias): Normalization profile selecting the canonical form for one downstream scenario: `authoring` (polished author-facing output), `faithful` (same rendered formula, convenience macros expanded), `corpus` (training-data normalization, layout hints dropped), or `equiv` (aggressive canonicalization for equivalence comparison).
- `Profile` (typeAlias): Normalization profile passed to TransformEngineOptions: `"authoring"`, `"faithful"`, `"corpus"`, or `"equiv"`.
- `RuleLevel` (typeAlias): How aggressively a transform rule may rewrite, layered from least to most destructive of stylistic detail.

### [serialize](https://texform.dev/api/js/serialize.md)

- `serialize` (function): **Deprecated.** Prefer `Document.fromSyntax(node).toLatex(options)` or `document.toLatex(options)`. This remains exported as a compatibility helper for older snapshot call sites and takes the same options as `toLatex`.
- `SerializeOptions` (interface): Options for Document.toLatex, Document.toTokenizedLatex, and serialize. Unknown keys and invalid values throw `TexformConfigError`. For a task-oriented walkthrough, see the Serialization guide.
- `Style` (typeAlias): Spaced output is byte-stable; compact preserves structure and text idempotency.

### [validateArgspec](https://texform.dev/api/js/validate-argspec.md)

- `validateArgspec` (function): Validate an xparse-style argspec string and report its parsed slots.
- `ValidateArgspecResult` (interface): The outcome of validateArgspec: whether the spec is well-formed and, when valid, its parsed slots.
- `ParsedArgSpecSlot` (interface): One parsed argument slot of an argspec, as reported by validateArgspec and by the parser's command/environment lookups.

### [Utilities](https://texform.dev/api/js/utilities.md)

- `listPackages` (function): List all built-in knowledge packages with record counts.
- `PackageInfo` (interface): Summary of one built-in knowledge package, returned by listPackages.
- `TexformError` (exception): Base class for every error the library throws.
- `TexformParseError` (exception): Thrown when source could not be parsed into a complete tree.
- `TexformEditError` (exception): Thrown by Document editing methods on an invalid edit: editing a read-only (error) tree, detaching or removing the root, an out-of-bounds index, or mixing nodes across documents.
- `TexformConfigError` (exception): Thrown on invalid construction or per-call configuration: unknown package or profile names, unknown or snake_case keys, arrays in object positions, and wrong scalar types. Messages include a camelCase field path.
- `TexformTransformError` (exception): Thrown on a transform-engine failure, such as an eliminated-form contract violation, or passing TransformEngine.transform a document that Document.hasErrors or that is bound to a different KnowledgeBase instance.
- `TexformConformanceError` (exception): Thrown when a construction, edit, or syntax import violates the knowledge base or the document's structure.
- `listRules` (function): List all built-in rewrite rules, sorted by key.
- `RuleInfo` (interface): Summary of one built-in rewrite rule, returned by listRules.
- `RuleFidelity` (typeAlias): A rewrite rule's worst-case equivalence guarantee over its declared input domain, ordered least to most faithful: `math` (mathematical meaning is preserved, rendering may change), `reading` (notation content, reading order, and structural roles are preserved), `render` (rendering is equivalent under the reference renderer).

