@docx-editor.dev/editor-api/browser
The same document automation, for a page that already has an editor open.
```ts import { DocxEditor } from '@docx-editor.dev/editor-api/browser';
const runtime = DocxEditor.createBrowser(editor, { author: 'Demo Reviewer' }); await runtime.run(async (context) => { … }); ```
A separate subpath rather than a second export from the package root, because createBrowser reaches the editor lane, and the editor lane brings the painted engine and its font shaper with it. Both namespaces expose createServer: opening bytes is neutral, and a page that opens an attachment beside the document it is showing should not need two imports.
The editor comes from wherever the host got it — @docx-editor.dev/react, @docx-editor.dev/vue, or a plain page that created one directly. This package does not create editors and does not own their lifetime.
Functions (4)
getReviewItemRangefunctionSource ↗
The range a review item covers, by the key the editor's review queue gives it.
Pass the key of an item from editor.getReviewItems() or useReview().items. A tracked change resolves to the characters it covers. A paired replacement key resolves to one range over both its deletion and its insertion. A comment or reply resolves to the range its thread is anchored to. The range is a snapshot like any other.
To act on the card's own change, use [getReviewItemRevisions](getReviewItemRevisions). [Range.revisions](Range.revisions) on this range also lists nested or adjacent changes that the range overlaps.
A key that names nothing in the document, such as one whose change was already accepted, or a comment with no anchor in the document, fails the sync with ItemNotFound. Use [getReviewItemRangeOrNullObject](getReviewItemRangeOrNullObject) to test for that instead. A custom node's key refuses with NotSupported at the call.
This is a DocxEditor addition. Office.js has no review queue and no key for a revision.
declare function getReviewItemRange(context: RequestContext, key: string): Range;Read the words a comment card is about
```ts
import { getReviewItemRange } from '@docx-editor.dev/editor-api/browser';
const key = item.key; // From useReview().items or editor.getReviewItems().
const text = await runtime.run(async (context) => {
const range = getReviewItemRange(context, key);
range.load('text');
await context.sync();
return range.text;
});
```getReviewItemRangeOrNullObjectfunctionSource ↗
The range a review item covers, or a null object when the key names nothing.
The same lookup as [getReviewItemRange](getReviewItemRange). A key that names nothing in the document answers a range whose isNullObject is true after the sync, instead of failing it.
This is a DocxEditor addition. Office.js has no review queue and no key for a revision.
declare function getReviewItemRangeOrNullObject(context: RequestContext, key: string): Range;Skip a card whose change another reviewer already resolved
```ts
import { getReviewItemRangeOrNullObject } from '@docx-editor.dev/editor-api/browser';
const key = item.key; // From useReview().items or editor.getReviewItems().
await runtime.run(async (context) => {
const range = getReviewItemRangeOrNullObject(context, key);
range.load('text');
await context.sync();
if (range.isNullObject) return;
console.log(range.text);
});
```getReviewItemRevisionsfunctionSource ↗
The tracked changes a review card stands for, by the key the editor's review queue gives it.
Pass the key of a revision item from editor.getReviewItems() or useReview().items. The collection holds that change only, or the deletion and the insertion of a paired replacement. Unlike [Range.revisions](Range.revisions) on the card's range, it never holds a nested or adjacent change by another author.
A key that names nothing in the document, such as one whose change was already resolved, loads an empty collection, and acceptAll() or rejectAll() on it refuses with InvalidObjectPath. A comment or custom node key refuses with NotSupported at the call. resolve() and setAuthor() refuse with NotSupported on this collection.
This is a DocxEditor addition. Office.js has no review queue and no key for a revision.
declare function getReviewItemRevisions(context: RequestContext, key: string): RevisionCollection;Accept the change a review card shows
```ts
import { getReviewItemRevisions } from '@docx-editor.dev/editor-api/browser';
const key = item.key; // From useReview().items or editor.getReviewItems().
await runtime.run(async (context) => {
getReviewItemRevisions(context, key).acceptAll();
await context.sync();
});
```isDocxEditorErrorfunctionSource ↗
Whether a caught value is one of ours.
By name as well as by instanceof: a consumer can end up with two copies of this module (a bundle plus a dependency's), and an instanceof that fails across them would send a perfectly ordinary PropertyNotLoaded down a consumer's unexpected-error path.
declare function isDocxEditorError(value: unknown): value is DocxEditorError;Classes (45)
Body_2class
A story: the main body of a document, a header or footer variant, or a note's body — and everything in it in reading order.
Its paragraphs are the DOCUMENT'S, not just the top level's. A paragraph inside a table cell, or inside a table inside a cell, or inside a block-level content control, is an ordinary editable paragraph and appears here, exactly as it does in Word's own paragraph collection. A collection listing only direct children would describe a smaller document than the one on screen.
[Body.clear](Body.clear) leaves one empty paragraph, matching what Word produces when a reader selects everything and deletes. A body that already holds no paragraph reports InvalidArgument rather than inventing a block.
declare class Body extends ModelObject| Member | Type | Summary |
|---|---|---|
| bookmarks | BookmarkCollection | Every bookmark declared in this story, in document order. |
| clear | | Empty the story, leaving one empty paragraph behind. |
| contentControls | ContentControlCollection | The content controls this story holds, in document order — the OUTERMOST ones. |
| endnotes | NoteItemCollection | Endnotes referenced within this body, in reference order. |
| fields | FieldCollection | Fields within this body. |
| font | Font | The character formatting of the whole story: what all of it agrees on, and what a write sets. |
| footnotes | NoteItemCollection | Footnotes referenced within this body, in reference order. |
| getComments | | The comments anchored in this story, in document order. Replies hang off the comment. |
| getRange | | The whole body or one edge. Await sync before addressing the returned range. |
| inlinePictures | InlinePictureCollection | Inline pictures within this body. |
| insertParagraph | | Add a paragraph at the start or the end of the story. Answers the new paragraph. You can load the returned paragraph in the same sync. Editing it needs a sync first. |
| insertTable | | Insert a rectangular table at the start or the end of this body. TrackMineOnly marks rows, cell marks, and values inserted, as `Range.insertTable` does. Sync before configuring the returned table. A table inside a table cell refuses. |
| insertText | | Write text over the whole story, or at either edge of it. Answers the text's own range. |
| lists | ListCollection | Every list this story holds, in the order their numbers first appear. |
| paragraphs | ParagraphCollection | Every paragraph in this story in reading order, at every depth. |
| revisions | RevisionCollection | The tracked changes in this story that this API can publish as typed objects, in document order. |
| search | | Every occurrence of `searchText` in this story, as ranges, in reading order. |
| shapes | ShapeCollection | Floating and inline shapes in this body, such as text boxes and pictures. |
| style | string | The paragraph style, by the name a reader sees in the styles gallery. |
| tables | TableCollection | Top-level tables within this body or table cell. |
| text | string | The whole story's text. |
BookmarkclassSource ↗
A name a document gives to a stretch of itself.
A bookmark IS its name. OOXML writes it as a pair of markers around the text, and the name is the only thing identifying it — so this object is a name plus the range those markers currently enclose. A bookmark whose markers left with the text they surrounded refuses rather than answering where they used to be.
start and end are absent by design: they are document-wide character offsets, the coordinate space this API does not maintain.
declare class Bookmark extends ModelObject implements PromisedItem| Member | Type | Summary |
|---|---|---|
| delete | | Delete this bookmark. The text it marks stays. |
| name | string | The name the document declares this bookmark with. |
| range | Range | The text the bookmark's markers enclose. |
| select | | Put the reader's selection on the bookmark and navigate the editor viewport to it. |
BookmarkCollectionclassSource ↗
The bookmarks of a story or a range, as of the batch that loaded them.
Like every collection here, items is the LOADED answer rather than a live view: bookmarks added after the load are not in it, and reaching them means loading again.
declare class BookmarkCollection extends HandleCollection<Bookmark>ClientObjectclassSource ↗
The base every document proxy extends.
A proxy is three things and no more: the context it belongs to, the path that says whether it can be addressed, and the properties a completed load filled in.
A RELEASED proxy still answers what it already knew. Reading a property loaded before the run ended is served from memory, because that value is a copy the consumer already holds — it is not a reach into a document. Anything that would talk to the document (load, a write, a method) refuses with InvalidObjectPath. The line is "does this need the document", not "does this look like a read".
declare abstract class ClientObject implements RuntimeManagedObject| Member | Type | Summary |
|---|---|---|
| (constructor) | | Constructs a new instance of the `ClientObject` class |
| context | RequestContext | The context this object currently belongs to. |
| handle | | The handle to address this object with, or `InvalidObjectPath`. |
| isNullObject | boolean | Whether this object turned out not to exist. |
| load | | Queue the reads that fill in the selected properties. |
| onLoad | | What this kind of object does with a resolved load request. |
| requireAddressable | | The check every call that talks to the document makes first. |
| requireUsablePath | | Permit queued read dependencies and optional scalar loads; refuse released proxies. |
ClientResultclassSource ↗
A value a queued method promised to produce, readable after the next sync().
Deliberately not a Promise. A method call inside a batch has not been sent yet, so there is no pending work to await and nothing that could resolve on its own — awaiting one would deadlock a consumer who then never calls sync(). A result is a box that stays EMPTY until the sync fills it, and reading it early is ValueNotLoaded rather than undefined flowing onwards into something that misinterprets it.
RevisionCollection.resolve returns a ClientResult with the resolved and skipped decisions.
declare class ClientResult<T>The constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the ClientResult class.
| Member | Type | Summary |
|---|---|---|
| isLoaded | boolean | Whether the sync that fills this has happened. |
| value | T | The value, once a `sync()` has filled it in. |
Comment_2class
A comment: a conversation about a stretch of the document, not a single remark.
[Comment.replies](Comment.replies) holds the answers, and resolving is a property of the whole thread — assigning resolved marks this comment and everything answering it, which is what Word's own pane does.
authorEmail and a writable content are absent: CT_Comment records only an author and initials (Word's addresses live in people.xml, which this API does not read), and a body rewrite is not an operation the canonical write path offers. The comment's text is published as text.
declare class Comment extends CommentBase| Member | Type | Summary |
|---|---|---|
| getRange | | The words the comment is about. |
| replies | CommentReplyCollection | The answers to this comment, in document order. |
| reply | | Answer the comment, over the same words it is anchored to. |
| resolved | boolean | Whether the thread is resolved. |
CommentCollectionclassSource ↗
The comments on a document, story or range, as of the batch that loaded them.
declare class CommentCollection extends HandleCollection<Comment>| Member | Type | Summary |
|---|---|---|
| getFirst | | The first comment. `ItemNotFound` at the sync if there are none. |
CommentReplyclassSource ↗
One answer in a comment thread.
Authored over the parent comment's own range, because that is where the conversation is anchored and OOXML gives a reply no other place to be. Resolving is a property of the whole thread rather than of any one reply — see [Comment.resolved](Comment.resolved).
declare class CommentReply extends CommentBaseCommentReplyCollectionclassSource ↗
The replies to one comment, in thread order, as of the batch that loaded them.
declare class CommentReplyCollection extends HandleCollection<CommentReply>| Member | Type | Summary |
|---|---|---|
| getFirst | | The first reply. `ItemNotFound` at the sync if nobody answered. |
ContentControlclassSource ↗
A part of a document a template marked as a field.
A control is NOT its w:id. The attribute is optional in OOXML and unique nowhere, so a document may hold one control with no id and two with the same one. This object is addressed by an opaque host-minted handle instead, and [ContentControl.id](ContentControl.id) is answered as METADATA — a label the file wrote, empty where it wrote none. getById still exists, because a template author knows their own numbering, and it answers the first match in document order rather than refusing.
A control's contents are not its value. text reads the characters; setValue writes in the vocabulary the control's own type accepts — a declared item for a dropdown, an ISO date for a date picker, a state for a checkbox — because writing "true" into a checkbox's runs would produce a document whose glyph and whose w14:checked disagree.
declare class ContentControl extends ModelObject implements PromisedItem| Member | Type | Summary |
|---|---|---|
| cannotDelete | boolean | Whether the control refuses to be deleted. |
| cannotEdit | boolean | Whether the control's contents refuse to be edited. Resolved like `cannotDelete`. |
| contentControls | ContentControlCollection | The controls INSIDE this one, in document order. |
| delete | | Remove the control. |
| getRange | | The stretch of the story the control's content covers. |
| id | string | The `w:id` the file wrote, as a string, and `''` where it wrote none. |
| insertText | | Put text into the control: over what it holds, or at one end of it. Supports text-like controls. Date, checkbox, and other typed controls refuse with NotSupported. |
| isBound | boolean | Whether the control currently declares an OOXML data binding. |
| paragraphs | ParagraphCollection | The paragraphs the control holds. Empty for an inline control, which holds none. |
| placeholderShown | boolean | Whether the control is showing its prompt rather than a value (`w:showingPlcHdr`). |
| setValue | | Write the control's value. |
| subtype | string | What kind of control it is: `plainText`, `dropDownList`, `checkbox`, `date`, … |
| tag | string | `w:tag` — the machine-readable label a template puts on a field. `''` where absent. |
| temporary | boolean | Whether the control removes its own wrapper on the first content edit (`w:temporary`). |
| text | string | The characters the control encloses, as the document reads them. |
| title | string | `w:alias` — what Word's UI calls the control's title. `''` where absent. |
ContentControlCollectionclassSource ↗
The content controls of a document, story or range, as of the batch that loaded them.
getById answers the first match in document order, because w:id is optional in OOXML and unique nowhere — see [ContentControl](ContentControl) for why choosing predictably beats refusing.
declare class ContentControlCollection extends HandleCollection<ContentControl>| Member | Type | Summary |
|---|---|---|
| getById | | The first control carrying one `w:id`, or `ItemNotFound` where the scope holds none. |
| getByTag | | Every control in the scope carrying one tag, in document order. |
| getByTitle | | Every control in the scope carrying one title, in document order. |
| getFirst | | The first control. `ItemNotFound` at the sync if the scope holds none. |
| getFirstOrNullObject | | The first control, or an object that says `isNullObject` where there is none. |
Document_2class
The document: the root every other object is reached from.
Deliberately thin. A document here is not a bag of content — it is the thing that HAS stories. It publishes the main story as [Document.body](Document.body), plus that story's paragraphs directly as document.paragraphs, because that is how source-compatible code walks a document.
Reached once per [RequestContext](RequestContext) and memoized: context.document is the same object every time, so a property loaded through one reference reads back through any other.
declare class Document extends ModelObject```ts
await runtime.run(async (context) => {
const paragraphs = context.document.paragraphs;
paragraphs.load('items');
await context.sync();
for (const paragraph of paragraphs.items) paragraph.load('text');
await context.sync();
for (const paragraph of paragraphs.items) console.log(paragraph.text);
});
```
The first sync retrieves the collection's items. Once those items are available, the second sync retrieves each paragraph's text.| Member | Type | Summary |
|---|---|---|
| body | Body | The main story. |
| changeTrackingMode | ChangeTrackingMode | 'Off' | 'TrackAll' | 'TrackMineOnly' | Tracking for this automation runtime. Load 'changeTrackingMode' explicitly before reading. Document.load() keeps an empty default property set across hosts. Assignments take effect at sync. TrackMineOnly tracks this runtime's inline text edits using its configured author. TrackAll is unsupported. Browser tracked writes require the review module; this setting does not change the editor UI mode. Unsupported tracked mutation kinds refuse; the setting is session-local and is not saved as a document-wide policy. |
| comments | CommentCollection | The comments anchored in the main story, in document order. |
| compare | | Refuses with `NotSupported` at the sync: the document model has no file system. Read the file yourself and call [Document.compareFromBase64](Document.compareFromBase64). |
| compareFromBase64 | | Compare this document (the original) with the revised document in `base64File`, and record the differences as tracked changes in this document. |
| contentControls | ContentControlCollection | The content controls of the main story, in document order — the outermost ones. |
| deleteBookmark | | Delete the bookmark with this name, compared without case, from whichever story declares it. The text stays. A name no bookmark has changes nothing. |
| endnotes | NoteItemCollection | The document's endnotes, in the order its notes part writes them. |
| footnotes | NoteItemCollection | The document's footnotes, in the order its notes part writes them. |
| getBookmarkRange | | The range of the bookmark with this name, compared without case. The main text is searched first, then headers, footers and notes. `ItemNotFound` at the sync when no bookmark has the name. |
| getBookmarkRangeOrNullObject | | Like [Document.getBookmarkRange](Document.getBookmarkRange), but a missing bookmark answers a null object. |
| getStyles | | The styles the document defines, of every kind, in the order its styles part writes them. Each call answers a new collection; load it before reading `items`. |
| paragraphs | ParagraphCollection | The main story's paragraphs, in reading order. |
| properties | DocumentProperties | Core document metadata. Reads require load; writes commit at sync. |
| removeDocumentInformation | | Remove standard core, extended, and custom document-property parts in one sync. Only DocumentProperties is supported. Tracking and collaboration refuse with NotSupported. This command must be the only write in its sync. It does not anonymize document content. |
| removeDocumentInformation | | |
| revisions | RevisionCollection | The tracked changes of the main-body story that this API can publish as typed objects. |
| sections | SectionCollection | The document's sections, in document order. |
DocumentPropertiesclassSource ↗
Core document properties. Load explicit names before reads; assignments commit at sync. Values are XML-safe strings of at most 4096 characters. Tracked writes are unsupported. Individual dates and custom properties are unsupported. Document.removeDocumentInformation can remove property parts. Collaborative writes require an existing core-properties part. Create properties before joining collaboration when the input omits that part.
declare class DocumentProperties extends ModelObject| Member | Type | Summary |
|---|---|---|
| author | string | Document author metadata, separate from the revision author. Load before reading; assign before sync. |
| category | string | Document category metadata. Load before reading; assign before sync. |
| comments | string | Document description metadata, separate from review comments. Load before reading; assign before sync. |
| keywords | string | Document search keywords. Load before reading; assign before sync. |
| lastAuthor | string | Last saved author, from cp:lastModifiedBy. Load before reading. |
| onLoad | | |
| subject | string | Document subject metadata. Load before reading; assign before sync. |
| title | string | Document title metadata. Load before reading; assign before sync. |
DocxEditorErrorclassSource ↗
Every refusal this runtime throws.
Branch on [DocxEditorError.code](DocxEditorError.code), never on the message. Codes are stable public API — added rather than repurposed — so a consumer that handles PropertyNotLoaded by loading and syncing again keeps working across versions.
Nothing from the engine appears in the message. Host rejection reasons, opaque handle refs and offset ranges are all withheld: a ref in a message is a name a consumer can start depending on, and a store's rejection reason would become a documented one the moment somebody matched on it. What a consumer gets instead is a stable code, a fixed sentence, and target — the consumer-facing path they wrote themselves.
declare class DocxEditorError extends Error```ts
try {
await context.sync();
} catch (error) {
if (isDocxEditorError(error) && error.code === 'StaleDocument') {
// Re-read, re-anchor, and reconsider: someone else changed the document first.
}
}
```| Member | Type | Summary |
|---|---|---|
| (constructor) | | Constructs a new instance of the `DocxEditorError` class |
| actualRevision? | number | For `StaleDocument`: the revision the document was actually at. |
| code | DocxEditorErrorCode | Which refusal this is. Stable across versions; the thing to branch on. |
| debugInfo | DocxEditorDebugInfo | Debug details, as Office.js `OfficeExtension.Error.debugInfo` has them. `innerError` names the engine's reason with a stable diagnostic code and a fixed hint, when there is one. |
| expectedRevision? | number | For `StaleDocument`: the revision the context had last read at, when the refused batch wrote. Absent for a batch that only read, on every host. |
| limit? | DocxEditorErrorInit['limit'] | For `ResourceLimitExceeded`: the resource limit that prevented opening. |
| target? | string | Consumer-facing path of the object or property involved, when there is one to name. |
FieldclassSource ↗
An inert Word field. Code writes and evaluation support PAGE and NUMPAGES. A field inside a pending tracked insertion reads, but refuses code writes and updateResult until accepted. Its cached result reads and writes through [Field.result](Field.result).
declare class Field extends ModelObject implements PromisedItem| Member | Type | Summary |
|---|---|---|
| code | string | |
| delete | | Remove this field, including its cached result. Other fields remain inert and unchanged. |
| onLoad | | |
| result | Range | The field's cached result, as a range. Two members work on it: `text` (with `load('text')`, or `field.load('result')`) reads the result, and `insertText(text, 'Replace')` replaces it with plain text and marks the field `w:dirty`, so a reader that evaluates fields recomputes it. The instruction never changes and is never evaluated. Untracked, the field must sit outside every revision. With `TrackMineOnly`, the field must be your own pending insertion, and the result joins it. Every other range member, and every other insert location, refuses with `NotImplemented` and `edit.field-result-unsupported`. |
| updateResult | | Compute a cached result using actual host pagination. Missing pagination refuses explicitly. |
FieldCollectionclassSource ↗
Fields contained within a body or range.
declare class FieldCollection extends ItemCollection<Field>| Member | Type | Summary |
|---|---|---|
| addressAt | | |
| getFirst | | |
| getFirstOrNullObject | | |
| getLast | | |
| getLastOrNullObject | | |
| itemAt | | |
| listing | | |
| promised | | |
| size | |
FontclassSource ↗
The character formatting of whatever it belongs to: a story, a stretch of one, or a paragraph.
A font has no identity of its own — it is a view onto its owner's characters and shares its owner's path, so a font reached from a deleted paragraph's range refuses at the same moment the range does rather than holding a stale address.
Reading is AGREEMENT, and null means "no agreed value": every run the owner covers says bold, or the answer is null. Null is also the answer when nothing in range authors the property at all. Both are one answer on purpose, because this API reads what the document AUTHORS rather than what the style cascade computes — a heading whose bold comes from styles.xml reads null. Answering the cascade would let a caller read an inherited value, write it straight back, and silently freeze it into the paragraph as if the author had chosen it.
Assignments within one sync() are ONE write: font.bold = true; font.size = 12 accumulates into a single run-property operation. That is required, not an optimisation — a run-property write carries the run's whole property bag, so a second write planned from the same pre-batch tree would carry a bag the first had already superseded, which the host refuses with ConflictingChanges.
declare class Font extends ModelObject| Member | Type | Summary |
|---|---|---|
| bold | boolean | null | Whether every character agrees it is bold, or `null` where they do not. |
| color | string | null | `#RRGGBB`. `null` where the characters disagree, or where the colour is `auto`. |
| highlightColor | string | null | Exact Word palette color, returned as #RRGGBB. Null clears highlighting. |
| italic | boolean | null | Whether every run in range is italic. `null` where they disagree or none says. |
| name | string | null | The typeface name the characters state, or `null` where they do not agree on one. |
| onLoad | | One read for every property asked for. |
| size | number | null | Points. |
| strikeThrough | boolean | null | |
| subscript | boolean | null | |
| superscript | boolean | null | |
| underline | string | null | Office underline styles. Mixed, Hidden, and DotLine refuse at sync. |
InlinePictureclassSource ↗
An inline PNG or JPEG picture. Measurements use points.
declare class InlinePicture extends ModelObject implements PromisedItem| Member | Type | Summary |
|---|---|---|
| altTextDescription | string | |
| delete | | Delete this picture. Shared media relationships remain preserved. |
| height | number | |
| lockAspectRatio | boolean | |
| onLoad | | |
| width | number |
InlinePictureCollectionclassSource ↗
Inline pictures within a body or range. Load items before enumeration.
declare class InlinePictureCollection extends ItemCollection<InlinePicture>| Member | Type | Summary |
|---|---|---|
| addressAt | | |
| getFirst | | |
| getFirstOrNullObject | | |
| getLast | | |
| getLastOrNullObject | | |
| itemAt | | |
| listing | | |
| promised | | |
| size | |
ListclassSource ↗
A list: the set of paragraphs sharing one numbering id.
A list is not an ELEMENT. OOXML has no list — it has paragraphs that each name a w:numId, and a list is the set that name the same one. So [List.id](List.id) is that number, [List.paragraphs](List.paragraphs) is the set, and a list exists exactly as long as some paragraph is still in it.
declare class List extends ModelObject implements PromisedItem| Member | Type | Summary |
|---|---|---|
| getLevelParagraphs | | The list's paragraphs at one level, in reading order. |
| id | number | The `w:numId` the list's paragraphs share — the document's own identity for the list. |
| insertParagraph | | Add a numbered paragraph to the list, at its start or its end. |
| paragraphs | ParagraphCollection | Every paragraph in the list, in reading order. |
| setLevelBullet | | Set a level's bullet glyph. Custom bullets require a Unicode character code. |
| setLevelBullet | | |
| setLevelIndents | | Set text indent and relative first-line indent in points. Negative relative values create hanging indents. |
| setLevelNumbering | | Set decimal, letter, Roman, or unnumbered markers. Numeric format entries identify zero-based levels. |
| setLevelNumbering | | |
| setLevelStartingNumber | | Set the starting counter for this list instance without changing other lists. |
ListCollectionclassSource ↗
The lists in a story, as of the batch that loaded them.
declare class ListCollection extends HandleCollection<List>| Member | Type | Summary |
|---|---|---|
| getById | | The list with one `w:numId`, or `ItemNotFound` where the story has none. |
| getFirst | | The first list. `ItemNotFound` at the sync if the story has none. |
ListItemclassSource ↗
A paragraph's membership of a list: which list, and at what level.
listString (the "3." or "iv)" a reader sees) and siblingIndex are absent because they are PAINTED, not authored — computed during layout by a counter that walks the story applying numbering.xml, its abstract-numbering indirection, restarts and overrides. Answering them here would mean a second counter that disagrees with the one on screen the first time a document overrides a level.
declare class ListItem extends ModelObject| Member | Type | Summary |
|---|---|---|
| level | number | How deeply the item is nested: zero for a top-level item, up to eight. |
NoteItemclassSource ↗
One footnote or endnote: text that belongs to the document but not to its flow.
A note IS a story. Its [NoteItem.body](NoteItem.body) is an ordinary [Body](Body) — paragraphs, formatting, styles, the same operations — laid out at the foot of a page or the end of the document rather than in the column, so everything the object model can do to the main story it can do to a note without a second vocabulary.
delete() removes the reference too. A note's body and the citation that reached it are one thing to a reader, and deleting the body alone would leave a mark pointing at nothing. The engine spells that as a package-level transaction, which is why it travels alone in its batch.
declare class NoteItem extends ModelObject implements PromisedItem| Member | Type | Summary |
|---|---|---|
| body | Body | The note's own story. |
| delete | | Remove the note and every reference to it. |
| getNext | | The next note of the same kind. `ItemNotFound` at the sync when this is the last one. |
| text | string | The note's plain text. |
| type | NoteItemType | Whether this is a footnote or an endnote. |
NoteItemCollectionclassSource ↗
The notes of one kind, in the order the notes part writes them.
DocxEditor's own collection type: the pinned reference fixture does not carry Word.NoteItemCollection, so it is not measured for conformance — recorded as an omission in compat/manifest.json — while NoteItem itself is. Without it a note would be unreachable, which is the one thing worse than an unmeasured collection.
declare class NoteItemCollection extends HandleCollection<NoteItem>| Member | Type | Summary |
|---|---|---|
| getFirst | | The first note. `ItemNotFound` at the sync if the document has none of this kind. |
PageSetupclassSource ↗
The page a section is laid out on: paper size, margins, and orientation.
This is w:sectPr — everything a caller usually wants from a section lives here rather than on [Section](Section) itself, which is mostly navigation.
declare class PageSetup extends ModelObject| Member | Type | Summary |
|---|---|---|
| bottomMargin | number | Points. |
| leftMargin | number | Points. |
| orientation | PageOrientation | 'Portrait' | 'Landscape' | Which way round the page is. |
| pageHeight | number | Points. |
| pageWidth | number | Points. |
| rightMargin | number | Points. |
| topMargin | number | Points. |
ParagraphclassSource ↗
One paragraph: what it says, what it is, and the ways it can be changed.
Identity is the document's own. [Paragraph.uniqueLocalId](Paragraph.uniqueLocalId) is the w14:paraId the file carries — the value Word writes, and the one commentsExtended.xml and coauthoring merges already anchor to — never a position in a collection. Deleting the paragraph above this one does not change it, which is the point: an agent that read a document, thought about it, and now wants to write to "the paragraph I was looking at" cannot express that with an index. A paragraph the file gave no id gets one deterministically at open, so the same bytes always answer the same identities and saving writes them back.
A structural edit owns its paragraph for the batch: delete(), split() and insertParagraph() change what offsets mean, so a second call in the same sync() that also touches this paragraph is refused with ConflictingChanges rather than planned against coordinates that have stopped describing it. Two syncs get both edits, each exactly as asked.
declare class Paragraph extends ModelObject implements PromisedItem| Member | Type | Summary |
|---|---|---|
| alignment | ParagraphAlignment | How the paragraph's lines are aligned, or `Unknown` where it authors no alignment. |
| attachToList | | Join an existing list at a zero-based nesting level. |
| clear | | Empty this paragraph's text, leaving the paragraph itself where it is. |
| contentControls | ContentControlCollection | The content controls in this paragraph, in document order, at any nesting depth. |
| delete | | Remove this paragraph and everything in it. |
| detachFromList | | Remove numbering while preserving the paragraph's text and other formatting. |
| firstLineIndent | number | Points. Negative for a hanging indent — the first line starting left of the rest. |
| font | Font | The character formatting of this paragraph's characters, and of its paragraph mark. |
| getRange | | Address this paragraph's content or an endpoint. Sync before using the returned range. |
| getReviewedText | | This paragraph's text as if every pending tracked change were accepted (`Current`, the default) or rejected (`Original`). The document does not change. |
| getReviewedText | | This paragraph's text as if every pending tracked change were accepted (`Current`, the default) or rejected (`Original`). The document does not change. |
| getTextRanges | | Split this paragraph into ranges that each end after one of `endingMarks`, such as `[' ']` for words. Takes the same arguments and follows the same rules as `Range.getTextRanges`. |
| insertParagraph | | Add a paragraph beside this one. Answers the new paragraph. You can load the returned paragraph in the same sync. Editing it needs a sync first. |
| insertTable | | Insert a rectangular table before or after this paragraph. TrackMineOnly marks rows, cell marks, and values inserted, as `Range.insertTable` does. Sync before configuring the returned table. A table inside a table cell refuses. |
| insertText | | Write text over this paragraph or at either edge of it. Answers the written text's range. |
| leftIndent | number | Points. |
| lineSpacing | number | Points between the paragraph's lines. |
| list | List | The list this paragraph is in. |
| listItem | ListItem | Where this paragraph sits in its list. Reading `level` on a paragraph in none refuses. |
| readingOrder | ParagraphReadingOrder | The direction the paragraph reads in: `LeftToRight` or `RightToLeft`. |
| rightIndent | number | Points. |
| search | | Every occurrence of `searchText` in this paragraph, as ranges, in reading order. |
| shapes | ShapeCollection | Floating and inline shapes in this paragraph, such as text boxes and pictures. |
| spaceAfter | number | Points below the paragraph. |
| spaceBefore | number | Points above the paragraph. |
| split | | Break this paragraph at every occurrence of any delimiter. |
| startNewList | | Start a new independent bullet list with this paragraph. Sync before using the returned list. |
| style | string | The paragraph style, by the name a reader sees in the styles gallery. |
| text | string | This paragraph's text. Readable after `load('text')` and a `sync()`. |
| uniqueLocalId | string | The document's own identity for this paragraph. |
ParagraphCollectionclassSource ↗
The paragraphs of a story, a range, or a list, as of the batch that loaded them.
Contains paragraphs at every depth — inside table cells, nested tables, and block-level content controls — matching Word's own collection rather than only the owner's direct children.
One of the two collections whose members are not plain handles: the pieces a [Paragraph.split](Paragraph.split) answers are filled in by the split's own command rather than by a separate listing read.
Load the paragraphs and a property of each in one sync with an items/ path, such as paragraphs.load('items/text').
declare class ParagraphCollection extends ItemCollection<Paragraph>| Member | Type | Summary |
|---|---|---|
| getFirst | | The first paragraph. `ItemNotFound` at the sync if the collection holds none. |
| getFirstOrNullObject | | The first paragraph, or an object that will report `isNullObject`. |
| getLast | | The last paragraph. `ItemNotFound` at the sync if the collection holds none. |
| getLastOrNullObject | | The last paragraph, or an object that will report `isNullObject`. |
Range_2class
A stretch of a story: two endpoints, each a paragraph and a UTF-16 offset.
A range is a SNAPSHOT, not a tracked region. Its endpoints name the paragraphs they were found in and the offsets they were found at, so it stays meaningful across edits ELSEWHERE in the document and becomes an explicit InvalidObjectPath refusal once one of its paragraphs is gone. What it deliberately does not do is follow edits INSIDE itself: once its paragraph gains a word at offset 0, a range over "alpha" fails with StaleDocument when used, rather than reading or editing whatever now sits at offsets 0..5. Edits after the range, and formatting changes, keep it valid. Word's own ranges do move, by keeping a live region in the document; this API has none, and pretending otherwise would answer text from a place the caller was not looking at.
That is also why start and end are absent rather than unimplemented — they are document-wide character positions, a different addressing scheme from this API's paragraph identity plus UTF-16 offset. Ask a range for its [Range.paragraphs](Range.paragraphs) instead.
declare class Range extends ModelObject implements PromisedItem| Member | Type | Summary |
|---|---|---|
| bookmarks | BookmarkCollection | The bookmarks whose text this range overlaps, in document order. |
| clear | | Clear this range's content, preserving the surrounding structure. |
| contentControls | ContentControlCollection | The content controls this range overlaps, in document order, at any nesting depth. |
| delete | | Delete range content. |
| expandTo | | A new range from the start of whichever range starts first to the end of whichever ends last. This range does not change. |
| fields | FieldCollection | Fields fully contained within this range. |
| font | Font | The character formatting of the characters this range covers. |
| getBookmarks | | The names of the bookmarks in or overlapping this range, in document order. |
| getRange | | The whole range, its content, or one of its endpoints, as a range. The default is `Whole`. |
| getReviewedText | | This range's text as if every pending tracked change were accepted (`Current`, the default) or rejected (`Original`). The document does not change. |
| getReviewedText | | This range's text as if every pending tracked change were accepted (`Current`, the default) or rejected (`Original`). The document does not change. |
| getTextRanges | | Split this range into ranges that each end after one of `endingMarks`, such as `[' ']` for words or `['.', '!', '?']` for sentences. A paragraph end always ends a range. |
| hyperlink | string | The hyperlink over these characters: an absolute URL, or `#anchor` for a place in the document. |
| inlinePictures | InlinePictureCollection | Inline pictures fully contained within this snapshot range. |
| insertBookmark | | Add a bookmark around this range, or at its position when the range is empty. |
| insertBreak | | Line, page, and next-page section breaks are supported; other types refuse at sync. With `TrackMineOnly`, each is a tracked insertion that reject removes. A tracked `SectionNext` refuses with `NotSupported` where the next section does not start on a new page. |
| insertComment | | Create a top-level comment anchored to exactly this range. |
| insertContentControl | | Wrap this single-paragraph range in a rich-text, plain-text, or date-picker content control. Await sync before configuring the returned control. Other types explicitly refuse. TrackMineOnly supports nonempty ordinary text outside collaboration. Existing revisions and empty tracked ranges refuse with NotSupported. |
| insertField | | Insert an inert field: Page, NumPages, Ref, PageRef, NoteRef, Seq, StyleRef, Date, Time, Empty with a whole instruction of one of those types, or TOC with supported switches. `text` holds the field arguments. The instruction is never evaluated, and the cached result is empty. Fields that fetch, embed, link, run, or prompt refuse with `InvalidArgument` (`edit.field-unsupported`). With `TrackMineOnly`, the field is one tracked insertion; tracked TOC creation refuses. |
| insertField | | Insert an inert field: Page, NumPages, Ref, PageRef, NoteRef, Seq, StyleRef, Date, Time, Empty with a whole instruction of one of those types, or TOC with supported switches. `text` holds the field arguments. The instruction is never evaluated, and the cached result is empty. Fields that fetch, embed, link, run, or prompt refuse with `InvalidArgument` (`edit.field-unsupported`). With `TrackMineOnly`, the field is one tracked insertion; tracked TOC creation refuses. |
| insertInlinePictureFromBase64 | | Insert a bounded PNG/JPEG image. Sync before configuring the returned picture. |
| insertOoxml | | Insert one equation from OOXML: a Flat OPC package (`pkg:package`) whose document part holds one paragraph with exactly one inline `m:oMath` and, around it, plain runs. Other OOXML refuses with `NotSupported` or `InvalidArgument` and `edit.ooxml-unsupported`, and nothing is inserted. With `TrackMineOnly`, the equation is one tracked insertion. Returns the range the inserted content occupies. |
| insertParagraph | | Add a paragraph before or after the one this range starts or ends in. You can load the returned paragraph in the same sync. Editing it needs a sync first. |
| insertTable | | Insert a rectangular table before or after this range. TrackMineOnly marks rows, cell marks, and values inserted; when a paragraph splits, see the guide. Sync before configuring the returned table. Nested table authoring refuses. |
| insertText | | Write text at or over this range. Answers the range the written text occupies. Await `context.sync()` before loading or addressing that returned range. |
| paragraphs | ParagraphCollection | The paragraphs this range covers, in reading order. |
| revisions | RevisionCollection | The tracked changes whose characters this range overlaps, in document order. |
| search | | Every occurrence of `searchText` inside this range, as ranges. |
| select | | Put the reader's selection on this range and navigate the editor viewport to it. |
| style | string | The paragraph style of the paragraphs this range covers, by name. A read answers the name they all agree on, which always writes back to the same style, or `null` where there is no such name. A write applies a style the document defines and never creates one: list the names with `context.document.getStyles()` and assign the `nameLocal` of a `Paragraph` style; character, table, and list names are refused. |
| tables | TableCollection | Tables contained by this range, in document order. |
| text | string | The text between this range's endpoints. |
RangeCollectionclassSource ↗
Ranges a read produced — the hits of a search, or the pieces a split answered.
Its members are SPANS rather than handles, which is what separates it from the handle-backed collections: each item carries its own paragraph-plus-offset endpoints instead of an opaque host-minted id.
Load the ranges and a property of each in one sync with an items/ path, such as results.load('items/text').
declare class RangeCollection extends ItemCollection<Range>| Member | Type | Summary |
|---|---|---|
| getFirst | | The first range. `ItemNotFound` at the sync if nothing matched. |
| getFirstOrNullObject | | The first range, or an object that will report `isNullObject`. |
| getLast | | The last range. `ItemNotFound` at the sync if nothing matched. |
RequestContextclassSource ↗
What a run hands its callback: one queue, one document, one sync at a time.
sync() commits all queued commands in one atomic transaction. Supported read-derived proxy dependencies can require additional read-only transport calls before that commit. These reads and the final write share one revision; a concurrent change refuses the sync. A read on an object that a write in the same sync returns (the range insertText wrote, the paragraph insertParagraph created) is answered after that commit, on the revision it produced. If that read fails, the writes stay applied and sync() rejects with the read's error code, with debugInfo.innerError.code edit.read-after-commit: read again, and do not apply the same edit again. A write on such an object requires a separate sync.
Conditional writes come from the same place. A context that has READ from the document remembers the revision it read at, and a later batch that writes goes out conditional on it, failing StaleDocument if the document moved. That is what stops a decision made from a cached read being applied to a document that has since changed — the hazard the read-decide-write shape of any batching API invites. A context that has read nothing has nothing to be stale about, so its writes go out unconditionally.
declare class RequestContext| Member | Type | Summary |
|---|---|---|
| capabilities | DocumentCapabilities | What the document host behind this context can do. |
| document | Document | The document this run is against. |
| sync | | Resolve read prerequisites, then commit queued writes atomically and hydrate answers. |
| trackedObjects | TrackedObjects | Objects kept addressable past the run that created them. See [TrackedObjects](TrackedObjects). |
RevisionclassSource ↗
One tracked change.
A row is listed as Insert or Delete, and a cell or tracked numbering by its own type. A structural card with no single type, such as table grid history, is omitted rather than shipped with an unpublishable type. That listing is not the collection decision set: see [RevisionCollection](RevisionCollection).
declare class Revision extends ModelObject implements PromisedItem| Member | Type | Summary |
|---|---|---|
| accept | | Keep the change, in one transaction, with every part of it: both halves of a move or a cell merge, and the changes inside content it removes, such as another author's insertion in a deleted row. Rejecting a formatting change restores the earlier properties, so another author's change inside the replaced properties, such as tracked numbering, goes with it. |
| author | string | Who proposed the change. |
| date | Date | null | When they proposed it, or `null` where the file recorded no valid date. |
| range | Range | The words the change covers. Each read returns the same proxy, so a load on it is kept. |
| reject | | Undo the change, likewise in one transaction and with the same rules as [Revision.accept](Revision.accept). |
| type | RevisionType | What kind of change it is, by Word's own name for it. |
RevisionCollectionclassSource ↗
The tracked changes on a document, story or range, as of the batch that loaded them.
items omits a structural card with no single revision type; see [Revision](Revision). On a story's collection, acceptAll / rejectAll still resolve every store-resolvable revision in the story and refuse atomically if any read-only or otherwise unsupported revision remains. On [Range.revisions](Range.revisions) and getReviewItemRevisions, they resolve the changes the range overlaps or the key names, and resolve and setAuthor refuse with NotSupported.
declare class RevisionCollection extends HandleCollection<Revision>| Member | Type | Summary |
|---|---|---|
| acceptAll | | Keep every change in this story, as ONE decision and one undo unit. |
| rejectAll | | Undo every change, likewise as one decision. |
| resolve | | Resolve eligible revisions in this story and report skipped decisions after sync. Omit revisions to include unsupported decisions and history absent from items. Named revisions resolve as single `accept()` or `reject()` calls on them would, except that a row kept for a nested table is reported as `retained-structure` while the other named changes resolve, where a single call refuses whole. Pass an empty array to select nothing. Duplicate objects resolve once; stale targets are reported as unknown-revision. This must be the only write in its sync batch. Unlike acceptAll/rejectAll, unsupported decisions do not block independent changes. A collection from `Range.revisions` or `getReviewItemRevisions` refuses this call with `NotSupported`. |
| setAuthor | | Attribute changes in this story to another author. The changes stay pending. |
SectionclassSource ↗
One section: the document's layout, not its content.
Everything a caller usually wants — paper size, margins, orientation — is on [Section.pageSetup](Section.pageSetup). The section itself is mostly navigation: the story it governs, the header and footer stories it declares, and the section after it.
getHeader and getFooter answer a body that may not exist yet. A section with no first-page header inherits the previous section's. When no section declares one, the answer is an empty body: every read on it answers as an empty story, and asking does not create the part. The first text written into it creates the header or footer; asking alone would make a READ write to the document, and a header that exists only because it was asked about is a header the author never added.
declare class Section extends ModelObject implements PromisedItem| Member | Type | Summary |
|---|---|---|
| body | Body | The story this section governs. |
| getFooter | | The footer story, or a virtual empty body created by its first content insertion. |
| getHeader | | The header story, or a virtual empty body created by its first content insertion. |
| getNext | | The next section. `ItemNotFound` at the sync when this is the last one. |
| pageSetup | PageSetup | The page this section is laid out on. |
SectionCollectionclassSource ↗
The sections of a document, in document order, as of the batch that loaded them.
declare class SectionCollection extends HandleCollection<Section>| Member | Type | Summary |
|---|---|---|
| getFirst | | The first section. `ItemNotFound` at the sync if the document has none. |
ShapeclassSource ↗
One floating or inline shape in a body or paragraph.
id, name and type are read-only. [Shape.body](Shape.body) exposes a supported shape's own text story, including text-bearing geometric shapes. Other shapes refuse body access.
declare class Shape extends ModelObject implements PromisedItem| Member | Type | Summary |
|---|---|---|
| body | Body | The shape's own text story in the main body, a header, or a footer. Shapes in notes or nested text boxes refuse body access with `InvalidArgument` at the sync. Shapes without their own supported text story also refuse access. |
| id | number | The shape's id in the document. |
| name | string | The shape's name in the document. |
| type | ShapeType | The shape's type. |
ShapeCollectionclassSource ↗
The floating and inline shapes in a body or paragraph, in reading order.
declare class ShapeCollection extends ItemCollection<Shape>| Member | Type | Summary |
|---|---|---|
| getByTypes | | The shapes of the given types, in the same order. |
| getFirst | | The first shape. `ItemNotFound` at the sync when there is none. |
| getFirstOrNullObject | | The first shape, or a null object when there is none. |
StyleclassSource ↗
One style the document's styles part defines. Every property is read-only and needs a load before it is read; load() with no arguments reads them all.
nameLocal is the name the styles part declares. Only a style whose type is Paragraph can be assigned to paragraph.style, range.style, or body.style; those setters refuse character, table, and list style names. Table.style accepts the nameLocal of a listed table style.
declare class Style extends ModelObjectOffer the paragraph styles a reader would see
```ts
const styles = context.document.getStyles();
styles.load('items/nameLocal,items/type,items/visibility,items/unhideWhenUsed,items/priority');
await context.sync();
// Keep hidden styles that unhide once used, such as heading 2, so they can be applied too.
// Many styles share priority 99, so sort by name next for a stable order.
const choices = styles.items
.filter((style) => style.type === 'Paragraph' && (style.visibility || style.unhideWhenUsed))
.sort((a, b) => a.priority - b.priority || a.nameLocal.localeCompare(b.nameLocal))
.map((style) => style.nameLocal);
```| Member | Type | Summary |
|---|---|---|
| baseStyle | string | The name of the style this one is based on: a listed style of the same kind. An empty string when the style states none or names any other style. Read-only here. |
| builtIn | boolean | False when the styles part marks the style as custom. |
| linked | boolean | Whether the style is linked to its partner: a paragraph style to a listed character style, or a character style to a listed paragraph style. Other kinds, and links to the same kind or to itself, read false. |
| nameLocal | string | The name the styles part declares. Assign it to `paragraph.style` only when `type` is `Paragraph`; the paragraph `style` setters refuse other kinds. A built-in name reads as the part writes it, such as `heading 1`, and the setters accept it that way. The setters and `getByNameOrNullObject` compare names without case, so `Heading 1` finds `heading 1`; compare names the same way rather than with `===`. |
| nextParagraphStyle | string | The name of the style for the paragraph after this one: always a listed paragraph style. A paragraph style that states no next style names itself. An empty string for other kinds, and where the next style it names is not a listed paragraph style. Read-only here. |
| priority | number | The sort order of the style among recommended styles; lower comes first. 99 when the styles part states no priority. Read-only here. |
| quickStyle | boolean | Whether the style is in the quick style gallery. False when not stated. Read-only here. |
| type | StyleType | 'Character' | 'List' | 'Paragraph' | 'Table' | The kind of style. A numbering style reads as `List`. Only `Paragraph` names are accepted by the paragraph, range, and body `style` setters. |
| unhideWhenUsed | boolean | Whether a hidden style becomes visible once it is used. False when not stated. Read-only here. |
| visibility | boolean | Whether the style shows as a recommended style. False when the styles part marks it semi-hidden or hidden; true when it marks neither. Read-only here. |
StyleCollectionclassSource ↗
The styles a document defines, of every kind, in the order its styles part writes them, as of the sync that loaded them.
The listing holds paragraph, character, table, and list styles. The paragraph.style, range.style, and body.style setters accept paragraph style names only; they refuse character, table, and list names. Check type before assigning a nameLocal. Every listed paragraph style applies through those setters. Styles with no name, an invalid name, or an unknown kind are not listed. A document with no styles part lists none.
load() with no arguments, or load('items'), reads every property of each style in the same sync. Name items/ paths to read fewer, such as styles.load('items/nameLocal,items/type').
declare class StyleCollection extends ModelObject| Member | Type | Summary |
|---|---|---|
| getByNameOrNullObject | | The style with this name, or an object that reports `isNullObject` after the sync. Reading `isNullObject` needs no property load; properties loaded on the object before that sync are answered by the same lookup. |
| getCount | | The number of listed styles, of every kind, readable after the next sync. |
| items | readonly Style[] | The styles this collection was loaded with. `PropertyNotLoaded` before a synced load. |
TableclassSource ↗
A canonical table. Reads require load() and sync().
declare class Table extends ModelObject implements PromisedItem| Member | Type | Summary |
|---|---|---|
| addColumns | | Add columns at an edge. Values are row-major; new columns initially copy the nearest edge width. |
| addRows | | Add rows at an edge. Sync before configuring the returned rows; omitted values create empty cells. Ordinary edge rows can belong to a table with unrelated merged headers. TrackMineOnly records native row insertion revisions, including supplied initial values. |
| columnCount | number | Number of columns in the rectangular grid. Load before reading. |
| delete | | Delete this table and its contents through the canonical document transaction. |
| deleteColumns | | Delete consecutive columns from a zero-based index. Defaults to one column. |
| deleteRows | | Delete consecutive rows from a zero-based index. Defaults to one row. Tracking requires one row without a pending deletion to remain and refuses pending row or cell structure revisions. |
| getCell | | Address a cell by zero-based row and column. Read-derived operations may share its next sync. |
| headerRowCount | number | Number of consecutive leading rows repeated as table headers. |
| mergeCells | | Merge the rectangle that the cells at `(topRow, firstCell)` and `(bottomRow, lastCell)` span into one cell. Cell indexes count the cells of each row, as `rows.items[r].cells` lists them, so a merged cell counts once. `bottomRow` must not be above `topRow`; either cell can lie further left. The rectangle grows to whole merged cells; a cell that crosses its edge, or a rectangle of one cell, refuses with `InvalidArgument` and the diagnostic code `edit.table-merge-not-rectangle`. The merged cell keeps every non-empty cell's content in reading order. The returned cell's `value`, `shadingColor`, and `verticalAlignment` can share the sync; a text edit in the table refuses with `ConflictingChanges` until a sync, because the merge moves paragraphs between cells. With tracking off, a pending cell revision refuses with `NotImplemented`. `TrackMineOnly` merges only inside the author's own proposed table, whose insertion the new shape joins; any other table refuses with `NotSupported` and `edit.tracked-structure-unsupported`. |
| onLoad | | |
| rowCount | number | Number of rows. Load this property before reading it. |
| rows | TableRowCollection | Stable row collection. Load `items`, then sync before reading its elements. |
| style | string | The table style, by its display name. Writes must name a table style the document defines: list the names with `context.document.getStyles()` and assign the `nameLocal` of a style whose `type` is `Table`; paragraph, character, and list names are refused. A read answers the name that writes back to the same style, or an empty string where the table has no style or no name of its style writes back to it. |
| values | string[][] | Cell text by row. Writes require the current dimensions and ordinary cell text. TrackMineOnly records text revisions outside collaboration; collaborative tracked writes refuse. |
TableCellclassSource ↗
A table cell. Column width uses points and changes the whole grid column.
declare class TableCell extends ModelObject implements PromisedItem| Member | Type | Summary |
|---|---|---|
| body | Body | A body scoped to this cell for text, ranges, formatting, and nested table navigation. |
| columnWidth | number | Width in points. A write affects the whole grid column, not only this cell. |
| onLoad | | |
| shadingColor | string | Cell background as a supported color string. |
| split | | Split this cell into `rowCount` rows and `columnCount` columns of equal width. Counts run from 1 to 63. A cell merged over several rows splits only into a divisor of them; a one-row cell adds rows to the table. Counts the cell cannot take, such as columns narrower than the minimum width, refuse with `InvalidArgument` and the diagnostic code `edit.table-split-unsupported`. `TrackMineOnly` splits only inside the author's own proposed table, as `Table.mergeCells` does; any other table refuses with `NotSupported`. |
| value | string | Plain cell text. Replacing complex content refuses; use the scoped body for targeted edits. TrackMineOnly records text revisions outside collaboration; collaborative tracked writes refuse. |
| verticalAlignment | VerticalAlignment | 'Top' | 'Center' | 'Bottom' | 'Mixed' | Top, Center, or Bottom. Mixed is a read state and cannot be assigned. |
TableCellCollectionclassSource ↗
A loaded collection of TableCell objects.
declare class TableCellCollection extends HandleCollection<TableCell>| Member | Type | Summary |
|---|---|---|
| getFirst | | Return the first item; an empty collection raises ItemNotFound at sync. |
| getFirstOrNullObject | | Return the first item or a null object. Check isNullObject after sync. |
| itemAt | | |
| listing | | |
| promised | |
TableCollectionclassSource ↗
A loaded collection of Table objects.
declare class TableCollection extends HandleCollection<Table>| Member | Type | Summary |
|---|---|---|
| getFirst | | Return the first item; an empty collection raises ItemNotFound at sync. |
| getFirstOrNullObject | | Return the first item or a null object. Check isNullObject after sync. |
| itemAt | | |
| listing | | |
| promised | |
TableRowclassSource ↗
A row with stable identity. Its cells follow document order.
declare class TableRow extends ModelObject implements PromisedItem| Member | Type | Summary |
|---|---|---|
| cells | TableCellCollection | Stable cell collection for this row. Load `items` and sync before reading. |
| insertRows | | Insert ordinary rows before or after this row. Sync before using the returned rows. Unrelated merged headers remain unchanged. Merged source rows and crossing merges refuse. TrackMineOnly records native row insertion revisions, including initial values. |
TableRowCollectionclassSource ↗
A loaded collection of TableRow objects.
declare class TableRowCollection extends HandleCollection<TableRow>| Member | Type | Summary |
|---|---|---|
| getFirst | | Return the first item; an empty collection raises ItemNotFound at sync. |
| getFirstOrNullObject | | Return the first item or a null object. Check isNullObject after sync. |
| itemAt | | |
| listing | | |
| promised | |
TrackedObjectsclassSource ↗
The objects a context keeps addressable beyond the run that created them.
An ordinary proxy stops being usable when its run ends. Tracking one keeps its address alive so a later run(object, callback) can adopt it, and untracking releases it — which matters for long-lived callers, since a tracked object is a document reference that will not be collected on its own.
declare class TrackedObjectsThe constructor for this class is marked as internal. Third-party code should not call the constructor directly or create subclasses that extend the TrackedObjects class.
| Member | Type | Summary |
|---|---|---|
| add | | Keep these objects usable after this run ends. |
| remove | | Stop keeping them: they are released when this run ends, like any other object. |
Interfaces (22)
CommitPreviewOptionsinterfaceSource ↗
Options for [DocumentPreview.commit](DocumentPreview.commit).
interface CommitPreviewOptions```ts
await preview.commit({ rebase: true });
```| Member | Type | Summary |
|---|---|---|
| rebase? | boolean | When the live document moved after the preview began, replay the preview on the current document instead of refusing. Ranges follow the text they name, so an edit elsewhere, even earlier in the same paragraph, rebases. The replay still refuses with `StaleDocument`, and writes nothing, when a replayed read answers differently or a write would overwrite text that changed: a search finds a different number of matches, text the preview read now reads otherwise, or the range, paragraph, or span a write replaces or formats holds other text. Omitted or false, any move refuses. |
CreateBrowserOptionsinterfaceSource ↗
How DocxEditor.createBrowser borrows a live editor.
interface CreateBrowserOptions| Member | Type | Summary |
|---|---|---|
| author? | string | Who comments this runtime writes are recorded as. |
| revisionTextView? | RevisionTextView | Revision view for ordinary Office-compatible `text` loads and `search()` calls. |
CreateServerOptionsinterfaceSource ↗
How DocxEditor.createServer opens a document.
Opening DOCX bytes is a bounded parse: decompression-ratio and size caps, part and relationship path validation, DTD- and entity-free XML. Malformed input returns InvalidArgument. Resource refusals return ResourceLimitExceeded, with limit identifying the exceeded cap. File-controlled details and internal parser messages are never included.
The bounded parse is complete when this promise resolves. The runtime does not retain the caller's Uint8Array, so the caller may reuse or transfer that input buffer afterward.
interface CreateServerOptions| Member | Type | Summary |
|---|---|---|
| author? | string | Who comments and tracked text edits written by this runtime are recorded as. |
| limits? | DocumentLimits | Budgets for the bounded reader — archive size, part count, and XML elements. |
| modules? | readonly EditorModule[] | Capability modules to register. Collaboration attaches only through a collaboration contribution on this list. A module with `onDiagnostic`, such as a telemetry module, receives the anonymous diagnostics of this runtime: the open, and each refused batch with a known reason. |
| pagination? | ServerPaginationOptions | Font-aware pagination required to calculate PAGE/NUMPAGES fields headlessly. |
| revisionTextView? | RevisionTextView | Revision view for ordinary Office-compatible `text` loads and `search()` calls. |
DocumentCapabilitiesinterfaceSource ↗
Capabilities exposed by a DocxEditor runtime, frozen for its lifetime.
interface DocumentCapabilities| Member | Type | Summary |
|---|---|---|
| document | boolean | There is a document to address at all. False for a browser host between mounts. |
| events | boolean | The host raises document events. |
| layout | boolean | The host lays the document out, so paginated positions are meaningful. |
| preview | boolean | `preview()` is offered: true for a runtime over a live browser editor, false for a server runtime, which has no page to show a preview in. |
| save | boolean | `save()` is offered — true for a server runtime, false for one borrowing an editor. |
| scrolling | boolean | The host can be scrolled to a position. |
| selection | boolean | The host has a user selection to read or move. |
DocumentCompareOptionsinterfaceSource ↗
Options of Document.compareFromBase64.
Supported: authorName, compareTarget (CompareTargetCurrent only), detectFormatChanges, and removeDateAndTime. addToRecentFiles and ignoreAllComparisonWarnings are accepted and have no effect: there is no recent-files list and no warning prompt. true for removePersonalInformation refuses with NotSupported.
interface DocumentCompareOptions| Member | Type | Summary |
|---|---|---|
| addToRecentFiles? | boolean | Accepted; there is no recent-files list. Default `true`. |
| authorName? | string | Author of the revisions. Default: the revised document's author, else `Comparison`. |
| compareTarget? | CompareTarget | 'CompareTargetCurrent' | 'CompareTargetNew' | 'CompareTargetSelected' | Where the result goes. Default and only supported value: `CompareTargetCurrent`. |
| detectFormatChanges? | boolean | Record formatting differences as revisions. Default `true`. |
| ignoreAllComparisonWarnings? | boolean | Accepted; there is no warning prompt. Default `false`. |
| removeDateAndTime? | boolean | Write the revisions without dates. Default `false`. |
| removePersonalInformation? | boolean | `true` refuses with `NotSupported`. Default `false`. |
DocumentLimitsinterfaceSource ↗
Resource budgets applied while opening DOCX bytes, subject to engine ceilings.
interface DocumentLimits| Member | Type | Summary |
|---|---|---|
| maxRelationships? | number | Most relationships the package may declare. |
| maxXmlParts? | number | Most XML parts the package may hold. |
| xml? | DocumentXmlLimits | Per-part XML caps. |
| zip? | DocumentZipLimits | Archive-level caps. |
DocumentPreviewinterfaceSource ↗
Other wording, shown in the page over the live document until it is committed or discarded. Answered by [DocxEditorRuntime.preview](DocxEditorRuntime.preview).
This is DocxEditor infrastructure with no Office.js equivalent.
interface DocumentPreview<T = void>```ts
const preview = await runtime.preview(async (context) => {
context.document.changeTrackingMode = 'TrackMineOnly';
const range = context.document.body.search('thirty (30) days').getFirst();
range.insertText('forty-five (45) days', 'Replace');
await context.sync();
});
preview.reveal(); // scroll to the counter-proposal
// The page shows it as a tracked change. The live document is unchanged.
if (userAccepted) await preview.commit();
else preview.discard();
```| Member | Type | Summary |
|---|---|---|
| commit | | Write the preview to the live document as one undo step, then end the preview. |
| discard | | End the preview without writing anything. The page shows the live document again, with its selection, scroll position, and focus as they were. A tracking mode the callback set is discarded with the preview. Safe to call more than once and after `commit()`. Disposing the runtime that opened the preview discards it too. |
| onStatusChanged | | Be told when [DocumentPreview.status](DocumentPreview.status) changes: to `stale` when the live document moves, and to `ended` once. Returns a function that removes the listener. |
| result | T | What the callback answered, as `run()` answers its callback's value. Return plain data from the callback, never a proxy: proxies end with the callback. |
| reveal | | Scroll the page to the first paragraph of the document body the preview changed. Answers false, scrolling nothing, when the preview has ended or changed no body paragraph: an edit only in a header, a footer, or a note is not found. |
| status | DocumentPreviewStatus | Where the preview is in its life. Read it at any time; it changes without a sync. |
DocumentXmlLimitsinterfaceSource ↗
Resource limits for each parsed XML part.
interface DocumentXmlLimits| Member | Type | Summary |
|---|---|---|
| maxBytes | number | Most bytes any one XML part may be. |
| maxElements? | number | Most elements any one XML part may contain. Defaults to the engine budget (10,000,000); callers may raise it up to the engine ceiling (50,000,000). |
DocumentZipLimitsinterfaceSource ↗
Resource limits for the DOCX archive.
interface DocumentZipLimits| Member | Type | Summary |
|---|---|---|
| maxEntries | number | Most entries the archive may contain. |
| maxRatio? | number | Highest tolerated ratio of the archive's total uncompressed bytes to its own byte length — the zip-bomb guard. Applies once the total exceeds 8 MiB, so a small archive is never refused for compressing well. |
| maxTotalBytes | number | Most bytes the archive may decompress to in total. |
DocxEditorDebugInfointerfaceSource ↗
Debug details in the shape of Office.js OfficeExtension.DebugInfo.
interface DocxEditorDebugInfo| Member | Type | Summary |
|---|---|---|
| code | DocxEditorErrorCode | The same code as [DocxEditorError.code](DocxEditorError.code). |
| errorLocation? | string | The consumer-facing path of the object or property involved, when there is one. |
| innerError? | DocxEditorInnerError | Why the engine refused, when it knows a specific reason. Handle the outer `code`; read `innerError.message` to tell a person or a model what to change. |
| message | string | The same message as the error's own. |
DocxEditorErrorInitinterfaceSource ↗
The fields a [DocxEditorError](DocxEditorError) is constructed from.
interface DocxEditorErrorInit| Member | Type | Summary |
|---|---|---|
| actualRevision? | number | The revision the document was actually at, for `StaleDocument`. |
| code | DocxEditorErrorCode | Which refusal this is. The stable thing to branch on. |
| diagnostic? | DiagnosticCode | The engine's public diagnostic code for this refusal, when it has one. It becomes `debugInfo.innerError`. |
| expectedRevision? | number | The revision the context had read at, for `StaleDocument`. |
| limit? | 'zip.maxEntries' | 'zip.maxTotalBytes' | 'zip.maxRatio' | 'xml.maxBytes' | 'xml.maxElements' | 'xml.maxDepth' | 'maxXmlParts' | 'maxRelationships' | The resource limit exceeded while opening a document. |
| target? | string | The consumer-facing path of the object or property involved — `document.body.text`, not a handle. Omitted when there is nothing to name. |
DocxEditorInnerErrorinterfaceSource ↗
Why the engine refused, as a public diagnostic code with its fixed hint.
interface DocxEditorInnerError| Member | Type | Summary |
|---|---|---|
| code | DiagnosticCode | A stable public diagnostic code, such as `edit.tracked-drawing-delete-unsupported`. |
| message | string | The fixed hint for the code: the cause, then the action. Never document content. |
DocxEditorNamespaceinterfaceSource ↗
The entry point, with the editor-bound factory. A superset of the one at the package root.
interface DocxEditorNamespace| Member | Type | Summary |
|---|---|---|
| createBrowser | | A runtime over an editor that is already open. The editor keeps its own lifetime. |
| createCollaborative | | A DOM-free runtime over one experimental collaboration replica. |
| createServer | | A runtime over DOCX bytes. Additionally offers `save()`. |
DocxEditorRuntimeinterfaceSource ↗
A runtime: one document host, many runs.
Runs are ISOLATED, not serialized. Every [DocxEditorRuntime.run](DocxEditorRuntime.run) gets its own context and its own queue, so two runs cannot interleave into one batch, and a run started inside another run works instead of waiting for a lock its own caller holds. Batches are still ordered — each sync() commits writes atomically; read dependencies can use additional read-only batches.
Disposal is final: [DocxEditorRuntime.dispose](DocxEditorRuntime.dispose) releases the host once and is safe to call again, and every later run fails with RuntimeDisposed.
interface DocxEditorRuntime| Member | Type | Summary |
|---|---|---|
| capabilities | DocumentCapabilities | What the document host behind this runtime can do. Frozen at construction. |
| dispose | | Release the host. Idempotent. |
| preview | | Show other wording in the page without writing it, until the answered preview is committed or discarded. |
| run | | Run one batch of work against the document. Answers with the callback's value. |
| run | | Run one batch of work, adopting objects a previous run tracked. |
| run | | Run one batch of work with options, such as an editor history group. |
DocxEditorServerRuntimeinterfaceSource ↗
A runtime over DOCX bytes rather than a live editor — what DocxEditor.createServer answers.
Adds [DocxEditorServerRuntime.save](DocxEditorServerRuntime.save) to the shared contract, because a server runtime owns its document and can serialize it; a browser runtime borrows the editor's and cannot.
interface DocxEditorServerRuntime extends DocxEditorRuntime| Member | Type | Summary |
|---|---|---|
| save | | The current document as a fresh, caller-owned DOCX byte array. |
EditorModuleinterfaceSource ↗
Capability module accepted by [createServer](createServer). Collaboration attaches through a collaboration contribution. Other contributions are ignored here.
interface EditorModule| Member | Type | Summary |
|---|---|---|
| collaboration? | CollaborationModuleContribution | |
| id | string | |
| onDiagnostic? | (event: RuntimeDiagnostic) => void | Told about this runtime's anonymous diagnostics: the open, and each refused batch with a known reason. A telemetry module's listener fits here unchanged. |
| review? | {
readonly compareDocuments?: CompareDocumentsEngine;
} | Review contribution. Its compare engine enables `Document.compareFromBase64`; the rest of the contribution is ignored here. |
LoadQueryOptionsinterfaceSource ↗
The object form of load(...): which properties, and how much of a collection.
An unknown key, a non-integer top, a property name that is not an identifier, or a value of the wrong type is refused as InvalidArgument here, naming the option — a misspelled key is the difference between "load selected properties" and "load nothing", which would otherwise surface as a PropertyNotLoaded much later at a call that looks correct.
interface LoadQueryOptions| Member | Type | Summary |
|---|---|---|
| expand? | string | readonly string[] | Reserved for Office.js source compatibility. Navigation-property expansion is not supported yet: a non-empty value is refused as `InvalidArgument`. Omit it or pass an empty array. |
| select? | string | readonly string[] | Which properties to load. |
| skip? | number | For a collection: skip this many items first. |
| top? | number | For a collection: at most this many items. |
RevisionAuthorOptionsinterfaceSource ↗
Options for [RevisionCollection.setAuthor](RevisionCollection.setAuthor).
interface RevisionAuthorOptions| Member | Type | Summary |
|---|---|---|
| date? | Date | The date to record. Omit it to keep each change's own date. |
RevisionAuthorSelectioninterfaceSource ↗
Select every change these authors made, for [RevisionCollection.setAuthor](RevisionCollection.setAuthor). Matches w:author exactly.
interface RevisionAuthorSelection| Member | Type | Summary |
|---|---|---|
| authors | readonly string[] |
RunOptionsinterfaceSource ↗
Options for [DocxEditorRuntime.run](DocxEditorRuntime.run), passed before the callback.
This is DocxEditor infrastructure, not part of the Office.js object model: the Office.js run function has no options and no undo grouping.
interface RunOptions```ts
// One review decision, one undo step: the editor's writes and every sync of the run.
const decision = editor.beginHistoryGroup();
try {
const resolved = editor.exec(
{ type: 'resolveAllReviewChanges', action: 'reject', keys },
{ historyGroup: decision }
);
if (!resolved.ok) throw new Error(resolved.reason);
await runtime.run({ historyGroup: decision }, async (context) => {
const ranges = context.document.body.search('30 days');
ranges.load('items');
await context.sync();
const target = ranges.items[0];
if (!target) throw new Error('The document has no "30 days" text.');
const replaced = target.insertText('45 days', 'Replace');
await context.sync();
replaced.insertComment('Counter-proposal: 45 days.');
await context.sync();
});
} finally {
decision.end();
}
```| Member | Type | Summary |
|---|---|---|
| historyGroup? | HistoryGroup | Make every write this run commits part of an open editor history group, so one undo reverts them together with the group's other writes. |
| previousObjects? | ClientObject | readonly ClientObject[] | Objects a previous run tracked, adopted by this run. The same as the object argument. |
SearchOptionsinterfaceSource ↗
How a search is narrowed.
Every flag is honoured or REFUSED — never quietly ignored. A search that accepted matchWildcards and then ran a plain-text scan would answer the wrong offsets to a caller who edits at them, so the unimplemented options reach the host and come back as NotSupported.
They are declared here rather than left off the type because omitting them would make { matchWildcards: true } a compile error in code that is otherwise source-compatible with Word. The honest answer to that code is a runtime refusal naming the option, not a type error naming the interface.
interface SearchOptions| Member | Type | Summary |
|---|---|---|
| ignorePunct? | boolean | Not implemented; `true` is refused with `NotSupported`. |
| ignoreSpace? | boolean | Not implemented; `true` is refused with `NotSupported`. |
| matchCase? | boolean | Match the query's case. Off by default, like Word's Find. |
| matchWholeWord? | boolean | Only match where the query stands alone as a word. |
| matchWildcards? | boolean | Not implemented; `true` is refused with `NotSupported`. |
ServerPaginationOptionsinterfaceSource ↗
Explicit measurement inputs for headless field calculation.
interface ServerPaginationOptions extends AutomationPaginationOptionsType aliases (23)
BesideLocationtypeSource ↗
Which side of a paragraph or a range a new paragraph goes on.
type BesideLocation = Extract<RangeInsertTextLocation, 'Before' | 'After'>;BodyInsertParagraphLocationtypeSource ↗
Where a story accepts a paragraph. Start/End mean "before the first"/"after the last".
type BodyInsertParagraphLocation = Extract<RangeInsertTextLocation, 'Start' | 'End'>;BodyInsertTextLocationtypeSource ↗
Where a story accepts text: over all of it, or at either edge.
type BodyInsertTextLocation = Extract<RangeInsertTextLocation, 'Replace' | 'Start' | 'End'>;ContentControlLockStatetypeSource ↗
The lock a control carries. ST_Lock, spelled as the schema spells it.
type ContentControlLockState = 'unlocked' | 'sdtLocked' | 'contentLocked' | 'sdtContentLocked';ContentControlSubtypetypeSource ↗
The control types this API can create. Picture and repeating section are deferred.
type ContentControlSubtype = 'richText' | 'plainText' | 'dropDownList' | 'comboBox' | 'date';ContentControlValuetypeSource ↗
What a control's own type accepts as a value.
A discriminated union rather than unknown: a dropdown and a checkbox do not take the same kind of thing, and a single setValue(value: string) would have to guess what 'true' means to a date picker.
type ContentControlValue = {
readonly kind: 'text';
readonly text: string;
} | {
readonly kind: 'listItem';
readonly value: string;
} | {
readonly kind: 'checkbox';
readonly checked: boolean;
}
/** `YYYY-MM-DD`, or a full ISO-8601 instant. */
| {
readonly kind: 'date';
readonly iso: string;
};CreateCollaborativeOptionstypeSource ↗
Options for [createCollaborative](createCollaborative).
type CreateCollaborativeOptions = CreateServerOptions;DocumentPreviewStatustypeSource ↗
Where a [DocumentPreview](DocumentPreview) is in its life.
- active: the page shows the preview, and the live document has not moved since the preview began. - stale: the live document moved after the preview began: a collaboration peer edited it, or a local write landed while the callback ran. The page still shows the preview. commit() refuses with StaleDocument; commit({ rebase: true }) replays it on the current document instead. - ended: the preview was committed, discarded, or ended because its runtime was disposed or the editor loaded, detached, or remounted. The page shows the live document. Final.
type DocumentPreviewStatus = 'active' | 'stale' | 'ended';```ts
preview.onStatusChanged((status) => {
applyButton.textContent = status === 'stale' ? 'Apply to the current text' : 'Apply';
});
```DocxEditorErrorCodetypeSource ↗
What went wrong, as a value a consumer may branch on.
type DocxEditorErrorCode =
/** A property was read before a `load(...)` for it completed in a `sync()`. */
'PropertyNotLoaded'
/** A `ClientResult` value was read before the sync that fills it. */
| 'ValueNotLoaded'
/**
* The object cannot be addressed, in one of three ways.
*
* NOT YET: an item accessor answers a proxy the read that names it has not answered for, and it
* becomes usable at the next `sync()`. NOT ANY MORE: its run ended and nothing tracked it, which
* is terminal. GONE: the document no longer holds the object, because an edit removed or merged
* it; `debugInfo.innerError.code` is then `edit.stale-target` and the message says so. One
* code because from a consumer's side all three are "this object cannot be used here"; the
* message says which one, because the fix for one is not the fix for the others.
*/
| 'InvalidObjectPath'
/** The object still belongs to a run that has not finished, so it cannot be handed over. */
| 'ObjectInUse'
/** An argument or load option this API does not accept. */
| 'InvalidArgument'
/** Opening the document exceeded a bounded reader resource limit. */
| 'ResourceLimitExceeded'
/** The collection has no such item — `getFirst()` on an empty one. */
| 'ItemNotFound'
/**
* The call is outside the supported subset for this host, mode, or content, and nothing
* changed. Examples: a server has no selection to move; `TrackMineOnly` has no tracked form
* for the operation; the OOXML or the field result holds content the subset does not take.
*
* Never retry the same call. Read `debugInfo.innerError.code` for the rule, then choose a
* supported call, another mode, or other content.
*/
| 'NotSupported'
/**
* The member or rule is one this API does not implement for the target, and nothing changed.
* Examples: a range member that a field result does not support; a tracked edit that touches
* your own pending change or another author's pending structural change.
*
* Never retry the same call. Read `debugInfo.innerError.code` for the rule, then read the
* target again and edit a different range, decide the pending change first, or use another
* member.
*/
| 'NotImplemented'
/**
* Two calls in one batch make claims on the same paragraph that cannot both hold.
*
* A batch is one transaction planned against the state at its start, which stops being
* unambiguous once two calls restructure the same paragraph. Split them across two `sync()`
* calls and each gets exactly what it asked for.
*/
| 'ConflictingChanges'
/** The request context's `run` has finished, so it can no longer be used. */
| 'InvalidRequestContext'
/** The runtime was disposed. Every later operation fails this way. */
| 'RuntimeDisposed'
/**
* The request was built from an older read, so nothing was applied: another writer moved the
* document, or a range's text moved since the range was read, including by this context's own
* earlier sync. Read again before retrying.
*/
| 'StaleDocument'
/** The host is live but holds no document right now — an editor between mounts. */
| 'DocumentUnavailable'
/**
* A preview is open over the editor, so it refuses this write or a second preview. Commit or
* discard the open preview first. Browser runtime only.
*/
| 'PreviewActive'
/** The preview has ended — committed, discarded, or replaced by a remount — so it cannot commit. */
| 'PreviewEnded'
/** The document refused the change, or answered something this runtime cannot use. */
| 'GeneralException';FieldTypeLiteraltypeSource ↗
String forms of Office field types.
type FieldTypeLiteral = `${FieldType}`;HeaderFooterTypetypeSource ↗
Which header or footer of a section: Word's own three variants.
type HeaderFooterType = 'Primary' | 'FirstPage' | 'EvenPages';LoadOptiontypeSource ↗
Everything load(...) accepts: one property name, several, or a [LoadQueryOptions](LoadQueryOptions) object.
type LoadOption = string | readonly string[] | LoadQueryOptions;```ts
paragraph.load('text');
paragraph.load(['text', 'style']);
paragraphs.load({ select: 'items', top: 5 });
paragraphs.load('items/text,items/style');
```
On a collection, `items/<property>` loads `items` and that property on each item in the same `context.sync()`. A property name without the `items/` prefix means the same thing on a collection, so `paragraphs.load('text')` equals `paragraphs.load('items/text')`.
Only one level of navigation is supported. A deeper path, such as `items/font/bold`, and a navigation path on an object that is not a collection, such as `font/bold`, are refused as `InvalidArgument`, with the path as the error's `target`. Load the navigation object itself instead, for example `paragraph.font.load('bold')` for each item.NoteItemTypetypeSource ↗
Which kind of note: Word's own two.
type NoteItemType = 'Footnote' | 'Endnote';ParagraphAlignmenttypeSource ↗
Paragraph alignment values readable and writable through this object model.
type ParagraphAlignment = Alignment | 'Mixed' | 'Unknown' | 'Left' | 'Centered' | 'Right' | 'Justified';ParagraphInsertTextLocationtypeSource ↗
Where a paragraph accepts text: over all of it, or at either edge of it.
type ParagraphInsertTextLocation = Extract<RangeInsertTextLocation, 'Replace' | 'Start' | 'End'>;ParagraphReadingOrdertypeSource ↗
A paragraph's base direction, as [Paragraph.readingOrder](Paragraph.readingOrder) reads and writes it.
type ParagraphReadingOrder = 'LeftToRight' | 'RightToLeft';PreviewCallbacktypeSource ↗
What [DocxEditorRuntime.preview](DocxEditorRuntime.preview) hands its callback: an ordinary request context whose reads and writes address the preview, not the live document.
Write it as you would write the final edit, from data you already have. The editor stays editable while the callback runs, so a callback that waits on a model call lets the document move under it, and the preview then starts stale. Ask the model first, then preview.
Text and formatting edits work in the body, headers, footers, and notes. The callback cannot write tables, pictures, fields, lists, hyperlinks, content controls, or page setup, create or delete headers, footers, or notes, or move the selection: context.sync() refuses those with NotSupported. Comments are written in the body only, as in run().
type PreviewCallback<T = void> = (context: RequestContext) => Promise<T>;```ts
const proposal = await model.propose(clauseText); // before the preview, not inside it
const preview = await runtime.preview(async (context) => {
context.document.changeTrackingMode = 'TrackMineOnly';
const range = context.document.body.search(proposal.find).getFirst();
range.insertText(proposal.replace, 'Replace');
await context.sync();
});
```RangeInsertTextLocationtypeSource ↗
Where a range accepts text. See Range#insertText for what Before/Start mean here.
type RangeInsertTextLocation = 'Replace' | 'Start' | 'End' | 'Before' | 'After';RevisionTextViewtypeSource ↗
The tracked-revision view used by this runtime's ordinary Office-compatible text reads.
allMarkup preserves the historical behavior. original matches Word's Original review view: pending deletions remain visible and pending insertions stay hidden.
This is a DocxEditor runtime option. It is not part of the Office.js object model.
type RevisionTextView = 'allMarkup' | 'original';RevisionTypetypeSource ↗
Word's own names for a kind of change.
The WHOLE upstream vocabulary, because a declaration says what a caller may be handed and a caller switching on it should not have to be told which subset this engine happens to produce. Nine of these occur as published objects: Insert, Delete, Property, MovedFrom, MovedTo, CellInsertion, CellDeletion, CellMerge and ParagraphNumber. A structural card with no single type, such as table grid history, is omitted from items; collection-wide decisions still resolve every store-resolvable revision. See compat/manifest.json.
type RevisionType = 'None' | 'Insert' | 'Delete' | 'Property' | 'ParagraphNumber' | 'DisplayField' | 'Reconcile' | 'Conflict' | 'Style' | 'Replace' | 'ParagraphProperty' | 'TableProperty' | 'SectionProperty' | 'StyleDefinition' | 'MovedFrom' | 'MovedTo' | 'CellInsertion' | 'CellDeletion' | 'CellMerge' | 'CellSplit' | 'ConflictInsert' | 'ConflictDelete';RunCallbacktypeSource ↗
What a run callback is given, and what it may answer with.
type RunCallback<T> = (context: RequestContext) => Promise<T>;RuntimeDiagnostictypeSource ↗
A diagnostic from a headless runtime: the open, and each refused batch. Each one is also a valid EditorDiagnostic, so a telemetry module written for the editor receives these unchanged.
type RuntimeDiagnostic = {
readonly schemaVersion: number;
readonly editorSessionId: string;
readonly time: number;
} & ({
readonly kind: 'document.open';
readonly outcome: 'opened';
readonly sizeBucket: ByteSizeBucket;
readonly durationMs: number;
} | {
readonly kind: 'document.open';
readonly outcome: 'rejected';
readonly code: DocumentOpenDiagnosticCode;
readonly sizeBucket?: ByteSizeBucket;
readonly cause?: string;
readonly part?: DocumentPartKind;
readonly errorName?: DiagnosticErrorName;
} | {
readonly kind: 'edit.rejected';
readonly code: EditDiagnosticCode;
readonly origin: 'automation';
readonly tracked: boolean;
readonly cause?: string;
readonly errorName?: DiagnosticErrorName;
readonly stage?: 'automation';
} | {
readonly kind: 'review.skipped';
readonly code: ReviewDiagnosticCode;
readonly count: number;
readonly operation?: ReviewOperation;
readonly cause?: string;
});SelectionMode_2type
Where a selection lands: over the range, or collapsed to one of its edges.
type SelectionMode = 'Select' | 'Start' | 'End';Enums (17)
AlignmentenumSource ↗
Paragraph alignment vocabulary. Mixed and unknown are read states, not authoring modes.
declare enum Alignment| Member | Type | Summary |
|---|---|---|
| centered | | |
| justified | | |
| left | | |
| mixed | | |
| right | | |
| unknown | |
BreakTypeenumSource ↗
Office break vocabulary; enum presence does not imply support for every break kind.
declare enum BreakType| Member | Type | Summary |
|---|---|---|
| line | | |
| next | | |
| page | | |
| sectionContinuous | | |
| sectionEven | | |
| sectionNext | | |
| sectionOdd | |
ChangeTrackingModeenumSource ↗
Tracking policy vocabulary. Unsupported policies fail explicitly at sync.
declare enum ChangeTrackingMode| Member | Type | Summary |
|---|---|---|
| off | | |
| trackAll | | |
| trackMineOnly | |
ChangeTrackingVersionenumSource ↗
Which version of tracked text getReviewedText reads: as if every pending revision were rejected (Original) or accepted (Current).
declare enum ChangeTrackingVersion| Member | Type | Summary |
|---|---|---|
| current | | |
| original | |
CompareTargetenumSource ↗
Where a document compare puts its result. Only CompareTargetCurrent is supported: the revisions go into the document the call is made on.
declare enum CompareTarget| Member | Type | Summary |
|---|---|---|
| compareTargetCurrent | | |
| compareTargetNew | | |
| compareTargetSelected | |
ContentControlTypeenumSource ↗
Content-control kinds, including the read subtypes that insertion does not accept.
declare enum ContentControlType| Member | Type | Summary |
|---|---|---|
| buildingBlockGallery | | |
| checkBox | | |
| comboBox | | |
| datePicker | | |
| dropDownList | | |
| group | | |
| picture | | |
| plainText | | |
| plainTextInline | | |
| plainTextParagraph | | |
| repeatingSection | | |
| richText | | |
| richTextInline | | |
| richTextParagraphs | | |
| richTextTable | | |
| richTextTableCell | | |
| richTextTableRow | | |
| unknown | |
FieldTypeenumSource ↗
Office field types. This runtime authors Page, NumPages, Ref, PageRef, NoteRef, Seq, StyleRef, Date, Time, TOC, and Empty with an instruction of one of those types.
declare enum FieldType| Member | Type | Summary |
|---|---|---|
| addin | | |
| addressBlock | | |
| advance | | |
| ask | | |
| author | | |
| autoText | | |
| autoTextList | | |
| barCode | | |
| bibliography | | |
| bidiOutline | | |
| citation | | |
| comments | | |
| compare | | |
| createDate | | |
| data | | |
| database | | |
| date | | |
| displayBarcode | | |
| docProperty | | |
| docVariable | | |
| editTime | | |
| embedded | | |
| empty | | |
| eq | | |
| expression | | |
| fileName | | |
| fileSize | | |
| fillIn | | |
| formCheckbox | | |
| formDropdown | | |
| formText | | |
| gotoButton | | |
| greetingLine | | |
| hyperlink | | |
| if | | |
| import | | |
| include | | |
| includePicture | | |
| includeText | | |
| index | | |
| info | | |
| keywords | | |
| lastSavedBy | | |
| link | | |
| listNum | | |
| macroButton | | |
| mergeBarcode | | |
| mergeField | | |
| mergeRec | | |
| mergeSeq | | |
| next | | |
| nextIf | | |
| noteRef | | |
| numChars | | |
| numPages | | |
| numWords | | |
| ocx | | |
| others | | |
| page | | |
| pageRef | | |
| ||
| printDate | | |
| private | | |
| quote | | |
| rd | | |
| ref | | |
| revNum | | |
| saveDate | | |
| section | | |
| sectionPages | | |
| seq | | |
| set | | |
| shape | | |
| skipIf | | |
| styleRef | | |
| subject | | |
| subscriber | | |
| symbol | | |
| ta | | |
| tc | | |
| template | | |
| time | | |
| title | | |
| toa | | |
| toc | | |
| undefined | | |
| userAddress | | |
| userInitials | | |
| userName | | |
| xe | |
InsertLocationenumSource ↗
Locations used by Office-shaped insertion calls. Each call validates its allowed subset.
declare enum InsertLocation| Member | Type | Summary |
|---|---|---|
| after | | |
| before | | |
| end | | |
| replace | | |
| start | |
ListBulletenumSource ↗
Supported Word bullet styles.
declare enum ListBullet| Member | Type | Summary |
|---|---|---|
| arrow | | |
| checkmark | | |
| custom | | |
| diamonds | | |
| hollow | | |
| solid | | |
| square | |
ListNumberingenumSource ↗
Supported Word numbering styles.
declare enum ListNumbering| Member | Type | Summary |
|---|---|---|
| arabic | | |
| lowerLetter | | |
| lowerRoman | | |
| none | | |
| upperLetter | | |
| upperRoman | |
PageOrientationenumSource ↗
Physical page orientation.
declare enum PageOrientation| Member | Type | Summary |
|---|---|---|
| landscape | | |
| portrait | |
RangeLocationenumSource ↗
Which part of an object a getRange call answers. Each call validates its allowed subset; Range.getRange supports Whole, Content, Start, and End.
declare enum RangeLocation| Member | Type | Summary |
|---|---|---|
| after | | |
| before | | |
| content | | |
| end | | |
| start | | |
| whole | |
RemoveDocInfoTypeenumSource ↗
Document information categories. Only DocumentProperties removal is supported.
declare enum RemoveDocInfoType| Member | Type | Summary |
|---|---|---|
| all | | |
| atMentions | | |
| commentReactions | | |
| comments | | |
| contentType | | |
| documentIntelligence | | |
| documentManagementPolicy | | |
| documentProperties | | |
| documentServerProperties | | |
| documentTasks | | |
| documentWorkspace | | |
| emailHeader | | |
| inkAnnotations | | |
| removePersonalInformation | | |
| revisions | | |
| routingSlip | | |
| sendForReview | | |
| taskpaneWebExtensions | | |
| template | | |
| versions | |
ShapeTypeenumSource ↗
Word's shape types. Supported text-bearing shapes expose their own body.
declare enum ShapeType| Member | Type | Summary |
|---|---|---|
| canvas | | |
| geometricShape | | |
| group | | |
| picture | | |
| textBox | | |
| unsupported | |
StyleTypeenumSource ↗
The kind of a style.
declare enum StyleType| Member | Type | Summary |
|---|---|---|
| character | | A character style. The paragraph `style` setters refuse its name. |
| list | | A numbering style, which defines list formatting. The paragraph `style` setters refuse its name. |
| paragraph | | A paragraph style, which `paragraph.style` accepts by its `nameLocal`. |
| table | | A table style. The paragraph `style` setters refuse its name; `Table.style` accepts its `nameLocal`. |
UnderlineTypeenumSource ↗
Office.js underline values. Unsupported runtime modes refuse at sync.
declare enum UnderlineType| Member | Type | Summary |
|---|---|---|
| dashLine | | |
| dashLineHeavy | | |
| dashLineLong | | |
| dashLineLongHeavy | | |
| dotDashLine | | |
| dotDashLineHeavy | | |
| dotLine | | |
| dotted | | |
| dottedHeavy | | |
| double | | |
| mixed | | |
| none | | |
| single | | |
| thick | | |
| twoDotDashLine | | |
| twoDotDashLineHeavy | | |
| wave | | |
| waveDouble | | |
| waveHeavy | | |
| word | |
VerticalAlignmentenumSource ↗
Vertical placement of content within a table cell. Mixed cannot be authored.
declare enum VerticalAlignment| Member | Type | Summary |
|---|---|---|
| bottom | | |
| center | | |
| mixed | | |
| top | |
Variables (1)
DocxEditorconstSource ↗
The entry point, with the editor-bound factory — a superset of the package root's.
createBrowser borrows an editor that is already open, so the runtime reads and writes the document the user is looking at. The editor keeps its own lifetime: disposing the runtime does not close the editor.
DocxEditor: DocxEditorNamespace```ts
import { DocxEditor } from '@docx-editor.dev/editor-api/browser';
const runtime = DocxEditor.createBrowser(editor, { author: 'Demo Reviewer' });
await runtime.run(async (context) => {
const paragraphs = context.document.paragraphs;
paragraphs.load('items');
await context.sync();
for (const paragraph of paragraphs.items) paragraph.load('text');
await context.sync();
});
```