@docx-editor.dev/docx-to-markdown

v2.19.0 · 2 published subpaths with full TypeScript signatures and JSDoc.

npmv2.19.0licenseApache-2.0sourcegithub

Subpaths

Package root

Functions (7)

createMarkdownZipfunctionSource ↗

Create a portable ZIP containing document.md, document.json, and media files.

declare function createMarkdownZip(result: MarkdownExportResult): Promise<Uint8Array>;

exportMarkdownfunctionSource ↗

Convert untrusted DOCX bytes with Node-safe resource and shaping defaults.

declare function exportMarkdown(source: ExportDocumentSource, options?: MarkdownExportOptions): Promise<MarkdownExportResult>;

exportMarkdownFromfunctionSource ↗

Translate an existing shared export session without reopening or re-laying out it.

declare function exportMarkdownFrom(session: ExportSession, options?: MarkdownProjectionOptions): Promise<MarkdownExportResult>;

exportMarkdownLayoutfunctionSource ↗

Translate a detached immutable core layout after its producer session is disposed.

declare function exportMarkdownLayout(layout: ExportSemanticLayout): MarkdownExportResult;

forEachSemanticDrawingfunction

Visit every drawing through the canonical root-story and recursive textbox walks.

declare function forEachSemanticDrawing(layout: SemanticLayout, visit: (drawing: SemanticDrawingVisit) => void): void;

openDocumentForExportfunctionSource ↗

Open a reusable export session with packaged fonts and HarfBuzz shaping by default.

declare function openDocumentForExport(source: ExportDocumentSource, options?: OpenMarkdownDocumentForExportOptions): Promise<OpenMarkdownDocumentForExportResult>;

toMarkdownJSONfunctionSource ↗

Omit image bytes and normalize arbitrary font failure causes to diagnostic strings.

declare function toMarkdownJSON(result: MarkdownExportResult): MarkdownJSONResult;

Classes (4)

DocumentOpenErrorclassSource ↗

Typed one-shot failure for bytes that cannot be opened as a supported DOCX.

declare class DocumentOpenError extends Error
MemberTypeSummary
(constructor)Constructs a new instance of the `DocumentOpenError` class
detail?string | undefined
reasonHeadlessDocumentRejection | 'aborted'

ExportResourceErrorclassSource ↗

Bounded failure from a headless export session.

declare class ExportResourceError extends Error
MemberTypeSummary
(constructor)Constructs a new instance of the `ExportResourceError` class
code'aborted' | 'timedOut' | 'nonConvergent' | 'disposed' | 'layoutInvariant' | 'layoutFailed'

MarkdownBundleErrorclassSource ↗

Failure to write a complete portable Markdown bundle.

declare class MarkdownBundleError extends Error
MemberTypeSummary
(constructor)Constructs a new instance of the `MarkdownBundleError` class
code'invalid-media-path' | 'duplicate-output-path' | 'non-portable-image-url' | 'output-not-empty' | 'write-failed' | 'archive-failed'
name
path?string

MarkdownMediaErrorclassSource ↗

Failure to produce a complete image export.

declare class MarkdownMediaError extends Error
MemberTypeSummary
(constructor)Constructs a new instance of the `MarkdownMediaError` class
actualBytes?number
assetId?string
code'media-limit' | 'url-resolution-failed' | 'invalid-image-url' | 'image-bytes-unavailable'
limitBytes?number
name

Interfaces (48)

AnchoredDrawingRecordinterface

interface AnchoredDrawingRecord extends Omit<InlineDrawingRecord, 'kind' | 'baselineOffset' | 'advanceStart' | 'advanceEnd' | 'distL' | 'distR' | 'distT' | 'distB'>
MemberTypeSummary
allowOverlapboolean
anchorParagraphIdstring
behindDocumentboolean
horizontalFrameDrawingHorizontalReferenceFrame
horizontalFrameOriginnumber
kind'anchoredDrawing'
layoutFallback?AnchoredDrawingLayoutFallback
layoutInCellboolean
relativeHeightnumber
sourceOrder?numberCanonical document traversal index within the owner story part.
textboxStory?TextboxStoryLayoutLaid-out textbox story for a `wps:txbx` drawing; paint renders it clipped inside the extent instead of a placeholder. Absent when the drawing carries no story or the host did not thread story layout (the record then degrades to the placeholder path).
verticalFrameDrawingVerticalReferenceFrame
verticalFrameOriginnumber
wrapExclude<ImageWrapTarget, 'inline'>

DrawingAccessibilityinterface

interface DrawingAccessibility
MemberTypeSummary
decorativeboolean
hiddenboolean
labelstring | null

DrawingGeometryinterface

interface DrawingGeometry
MemberTypeSummary
clipFallbackDrawingClipFallback
clipPolygonreadonly DrawingPoint[] | null
contentBoundsLayoutBox
effectInsetsDrawingInsets
hitBoundsLayoutBox
paintBoundsLayoutBox
transformedCornersreadonly DrawingPoint[]

DrawingTransforminterface

interface DrawingTransform
MemberTypeSummary
extentEmuReadonly<{ cx: number; cy: number; }>Source `a:ext` in EMU; zero falls back to `wp:extent` at geometry time.
flipHorizontalboolean
flipVerticalboolean
offsetEmuReadonly<{ x: number; y: number; }>Source `a:off` in EMU; defaults to origin when absent.
rotationDegreesnumber

ExportContentWarninginterface

Source content that cannot be certified by the layout snapshot.

interface ExportContentWarning
MemberTypeSummary
code'legacy-textbox' | 'legacy-drawing' | 'scan-limit'Legacy content is preserved in the DOCX but not laid out.
partNamestringPackage part containing the content, or where the bounded scan stopped.

ExportDestinationAnchorinterface

Model address shared by bookmarks and internal hyperlinks.

interface ExportDestinationAnchor
MemberTypeSummary
namestring
offsetnumber
paragraphIdstring

ExportDestinationGeometryinterface

Laid-out jump target in the coordinate spaces export traversal uses.

interface ExportDestinationGeometry
MemberTypeSummary
anchorExportDestinationAnchor
pageContentReadonly<{ readonly x: number; readonly y: number; readonly height: number; }>Caret geometry in page-content coordinates (same space as line boxes).
pageIndexnumber
pageStackReadonly<{ readonly x: number; readonly y: number; }>Top-left of the caret in stacked page coordinates.

ExportDroppedEmbeddedFontinterface

One document-embedded face the export mapper refused before composition.

interface ExportDroppedEmbeddedFont
MemberTypeSummary
partNamestring
reason'overLimit' | 'malformed'
requestFontRequest

ExportFontFaceResolutioninterface

One paintable face in an export font-resolution report.

interface ExportFontFaceResolution
MemberTypeSummary
faceIndex?number
hash?string
id?string
identity?stringAdmitted face identity (`hash#faceIndex`); remains after session disposal.
sourceFamilystring
style'normal' | 'italic'
substitution?FontSubstitution | nullFull substitution evidence; `null` when the admitted face answers the request directly.
via'direct' | 'substitution'
weight400 | 700

ExportFontFamilyResolutioninterface

Coverage of one family Core layout may request.

interface ExportFontFamilyResolution
MemberTypeSummary
coverage'complete' | 'partial' | 'none'
facesreadonly ExportFontFaceResolution[]
familystring

ExportFontResolutionReportinterface

Exporter-neutral evidence for the font policy behind one layout session.

interface ExportFontResolutionReport
MemberTypeSummary
defaultFamilystring
droppedEmbeddedFonts?readonly ExportDroppedEmbeddedFont[]Bounded drop evidence from the document-embedded font origin; omitted on legacy mocks.
familiesreadonly ExportFontFamilyResolution[]
originFailuresreadonly FontOriginFailure[]
requestedFamiliesreadonly string[]

ExportSemanticLayoutinterface

Export-ready semantic snapshot. Core guarantees normalized review artifacts for every session, including an empty immutable array when the source has none. A resolved snapshot is recursively immutable and remains traversable after its producer session is disposed; disposal only revokes session-owned work and capabilities such as [ExportSession.validatedImageBytes](ExportSession.validatedImageBytes).

interface ExportSemanticLayout extends SemanticLayout
MemberTypeSummary
contentWarnings?readonly ExportContentWarning[]Source omissions that cannot be detected by walking laid-out records.
destinations?readonly ExportDestinationGeometry[]
documentMetadata?ExportDocumentMetadata
reviewArtifactsreadonly SemanticReviewArtifactRecord[]

ExportSessioninterface

A single semantic-layout substrate reusable by Markdown and later exporters. Pagination fidelity is determined by the session's measurer; core's default is deterministic, not font-accurate.

interface ExportSession
MemberTypeSummary
disposeRelease per-document caches, pending resource work, and image-byte capabilities. Idempotent. Previously resolved layout snapshots remain immutable and traversable after disposal.
layoutSettle resources and return the default revision projection.
layoutForSettle resources and cache one explicit revision projection.
validatedImageBytesMint a defensive copy only for a ready drawing from this session.

FontOriginFailureinterface

A failed font origin or a partial failure in an otherwise usable fragment.

interface FontOriginFailure
MemberTypeSummary
causeunknown
originIndexnumberZero-based position in the first-wins origin list.
originName?stringResolver function name when one is safely available.

FontRequestinterface

A face, as something asks for it: family plus the two axes this engine admits.

Only static weights and slants. Variable-font axes are deliberately outside this vocabulary — the shaper refuses variation axes, and a variable file admitted here would render bold at regular weight.

interface FontRequest
MemberTypeSummary
familystring
style'normal' | 'italic'
weightnumber

FontSubstitutioninterface

A request that was answered by a DIFFERENT face than the one asked for.

Recorded rather than silently applied, because a substitution changes measurement: it is part of the shaping fingerprint, so a cached run shaped against a substitute is never reused for the real face.

interface FontSubstitution
MemberTypeSummary
lineMetrics?{ readonly heightEm: number; readonly baselineEm: number; }
requestedFontRequest
resolvedFontRequest

HeadlessDocumentViewinterface

The read capabilities shared by browser layout, server export, and future renderers.

It deliberately exposes resolved package facts rather than a binding or editor session. An exporter can therefore consume the live document without importing ProseMirror or a DOM.

interface HeadlessDocumentView
MemberTypeSummary
currentPackage
documentProperties
documentThemeFonts
headerFooterPartsBySection
headerFooterResolutionBySectionOccurrence-specific relationship metadata for header/footer stories.
numberingRoot
packageRevision
part
relationshipTarget
settingsRoot
stylesRoot

ImageDecodePortinterface

The injected image decoder.

A port rather than a direct Image/createImageBitmap call, so a worker or server runtime supplies its own and the engine never reaches for a browser global.

interface ImageDecodePort
MemberTypeSummary
convertPreservedOptional conversion of media an `<img>` cannot render (EMF/WMF metafiles, TIFF) into a renderable raster. The returned bytes are untrusted and re-enter the full raster validation path (sniff, header, pixel caps, decode) before they can become a ready resource. A null return declines the format and keeps the labelled placeholder; so does a throw, as `decode-failed`.
decode

InlineDrawingRecordinterface

interface InlineDrawingRecord
MemberTypeSummary
accessibilityDrawingAccessibility
advanceEndnumberCaret/hit advance end (slot + totalWidth).
advanceStartnumberCaret/hit advance start (slot left, before distL).
baselineOffsetnumber
cropSourceCrop
distBnumber
distLnumber
distRnumber
distTnumber
drawingNodeIdstring
effectsDrawingImageEffects
geometryDrawingGeometry
heightnumber
hitBoundsLayoutBox
hyperlinkHrefstring | nullSanitized external hyperlink projection; inert until an explicit gesture activates it.
kind'inlineDrawing'
ownerPartNamestring
paintBoundsLayoutBox
paragraphIdstring
placeholderGraphicKindstring | nullFixed non-picture graphic kind for refusal labels (`chart`, `group`, …); null for pictures.
resourceImageResourceState
revisions?readonly RevisionAttribution[]The revision wrappers enclosing the owning run, outermost first — the same stack spans carry, so paint and review chrome give a tracked picture the same cues as tracked text. Absent when the drawing is untracked.
startnumber
transformDrawingTransform
vectorShapeVectorShapeProjection | nullTyped solid-geometry payload for a renderable `wps:wsp` shape; null otherwise.
widthnumber
xnumberLeft edge of the extent box (slot + distL).
ynumber

LayoutBoxinterface

A rectangle in layout POINTS.

Points everywhere in this layer — twips convert at property-read boundaries and CSS pixels at paint. A box carrying either of those would eventually be added to one carrying the other.

interface LayoutBox
MemberTypeSummary
heightnumber
widthnumber
xnumber
ynumber

MarkdownExportOptionsinterfaceSource ↗

Layout and resource controls for one-shot Markdown export.

interface MarkdownExportOptions extends OpenMarkdownDocumentForExportOptions, MarkdownProjectionOptions

MarkdownExportResultinterfaceSource ↗

Full logical document plus page-scoped projections.

interface MarkdownExportResult
MemberTypeSummary
fontResolutionExportFontResolutionReport | nullStructured font-resolution evidence, or null when the layout's font origin is unavailable.
markdownstringConvenience logical Markdown with split records joined and repeated furniture excluded.
mediareadonly MarkdownImageAsset[]Unique extracted images; empty unless images are enabled.
pagesreadonly MarkdownPage[]Primary physical page projections, preserving Word layout boundaries and furniture.
paginationMarkdownPaginationInfoHow page numbers and tracked changes were projected for this result.
reviewArtifactsreadonly MarkdownReviewArtifact[]Every normalized comment and tracked change, including artifacts without a page occurrence. Artifact IDs are opaque and stable only within this result.
reviewBindingsreadonly MarkdownReviewBinding[]Markdown offsets valid only within this immutable result, with explicit mapping fidelity.
warningsreadonly MarkdownWarning[]Omitted content and font problems that may affect completeness or pagination.

MarkdownExportSessioninterfaceSource ↗

Reusable Markdown session with the font evidence captured while it opened.

interface MarkdownExportSession extends ExportSession
MemberTypeSummary
fontResolutionExportFontResolutionReport | nullNon-null for document-aware byte sessions opened by Markdown or Core; null for detached layouts, caller-supplied measurers, ordinary Core sessions, and live shared-shaping sessions.

MarkdownImageAssetinterfaceSource ↗

One unique image returned by a Markdown export.

interface MarkdownImageAsset extends MarkdownImageData
MemberTypeSummary
urlstringRaw URL; Markdown output escapes destination syntax separately.

MarkdownImageDatainterfaceSource ↗

Image bytes and provenance supplied to a URL resolver.

interface MarkdownImageData
MemberTypeSummary
byteLengthnumber
bytesUint8ArrayOwned bytes. Treat as read-only to preserve the content identifier.
idstringCore's SHA-256 content identifier for the exported bytes.
mimeTypestring
occurrencesreadonly MarkdownImageOccurrence[]
pathstringPortable relative filename, independent of the resolved URL.
pixelHeightnumberIntrinsic pixel height of the exported bytes; use occurrence dimensions for display.
pixelWidthnumberIntrinsic pixel width of the exported bytes; use occurrence dimensions for display.

MarkdownImageOccurrenceinterfaceSource ↗

One physical occurrence of an extracted image.

interface MarkdownImageOccurrence
MemberTypeSummary
altstring
decorativeboolean
displayHeightPxnumberWord's extent height in CSS pixels (96 px per inch), before crop or rotation.
displayWidthPxnumberWord's extent width in CSS pixels (96 px per inch), before crop or rotation.
drawingNodeIdstring
kind'inline' | 'anchored'Anchored images render at their paragraph position; Markdown does not reproduce text wrapping.
pageNumbernumber
paragraphIdstring
partNamestring
rootStorySemanticDrawingVisit['rootStory']
startnumberSource offset within the paragraph, in UTF-16 code units.
storySemanticDrawingVisit['story']

MarkdownImageOptionsinterfaceSource ↗

Portable image extraction and optional application-owned storage.

interface MarkdownImageOptions
MemberTypeSummary
maxTotalBytes?numberUnique extracted bytes; default 64 MiB. Not a total parsing/layout memory limit.
resolveUrl?(image: MarkdownImageData, context: { readonly signal?: AbortSignal; }) => string | Promise<string>Called sequentially once per unique image, after all extraction succeeds. Receives a separate byte copy; mutations cannot change result bytes. Return a relative path or HTTP(S) URL. The application owns completed uploads, their cleanup, and signed-URL expiry.
syntax?'markdown' | 'html'Default: `markdown` emits standard image links without dimensions. `html` emits an escaped `<img>` with each occurrence's display width and height, rounded to whole CSS pixels. Your renderer must allow HTML and these attributes. Neither syntax reproduces cropping, rotation, or floating text wrapping.

MarkdownPageinterfaceSource ↗

Markdown emitted for one physical layout page.

interface MarkdownPage
MemberTypeSummary
commentsreadonly MarkdownComment[]Membership view of comments occurring on this page. Each entry is the complete document-wide artifact and can contain occurrences from other pages. For page-local provenance, filter with `occurrence.pageIndex === page.number - 1`.
footerMarkdownstringFooter story for this page, kept separate from logical document content.
headerMarkdownstringHeader story for this page, kept separate from logical document content.
idstringIdentifier for this page within this export result.
markdownstringBody projection, plus local note definitions or labelled continuation blocks.
numbernumberOne-based physical page number.
trackedChangesreadonly MarkdownTrackedChange[]Membership view of tracked changes occurring on this page. Each entry is the complete document-wide artifact and can contain occurrences from other pages. For page-local provenance, filter with `occurrence.pageIndex === page.number - 1`.

MarkdownPaginationInfointerfaceSource ↗

Machine-readable scope of the page numbers returned by this export.

interface MarkdownPaginationInfo
MemberTypeSummary
displayModeRevisionDisplayModeTracked-change display mode used to paginate and translate this snapshot.
layoutRevisionnumberCore store revision from which this layout snapshot was produced.
scope'export-snapshot'Page numbers describe this exact export result.
source'layout-engine'Pages come from the docx-editor semantic layout engine, not stale DOCX page-break hints.

MarkdownProjectionOptionsinterfaceSource ↗

Projection controls for an already-open export session.

interface MarkdownProjectionOptions
MemberTypeSummary
images?boolean | MarkdownImageOptions`true` or `{}` extracts images with portable relative URLs. Default: false.
signal?AbortSignalCancels export waits; cannot interrupt synchronous parsing or layout.

MarkdownReviewBindinginterfaceSource ↗

Honest snapshot-local mapping from a Core review occurrence to generated Markdown.

interface MarkdownReviewBinding
MemberTypeSummary
artifactIdstringID of the corresponding artifact in this export result; do not join it across snapshots.
artifactKindMarkdownReviewArtifact['kind']Discriminant of the corresponding review artifact.
coverageMarkdownReviewCoverageWhether the ranges represent all, some, or none of the source occurrence.
occurrenceIndexnumberIndex into this snapshot's immutable artifact `occurrences` array.
projectionMarkdownReviewProjectionGenerated Markdown string containing this binding.
rangesreadonly MarkdownReviewRange[]Ordered, non-overlapping ranges in the selected projection.
unmappedReason?MarkdownReviewUnmappedReasonPresent when the source occurrence has no honest linear range in this projection.

MarkdownReviewRangeinterfaceSource ↗

A UTF-16 range suitable for slicing the named Markdown projection.

interface MarkdownReviewRange
MemberTypeSummary
endnumberExclusive end offset in the selected Markdown string.
precisionMarkdownReviewRangePrecisionWhether this is an exact text mapping or the smallest generated construct containing it.
startnumberInclusive start offset in the selected Markdown string.
unit'utf16-code-unit'Offsets use JavaScript string indexing and can be passed directly to `String.slice()`.

MarkdownWarninginterfaceSource ↗

Content or resources that could not be represented fully.

interface MarkdownWarning
MemberTypeSummary
code'omitted-drawing' | 'omitted-textbox' | 'font-origin-failed' | 'incomplete-font' | 'content-scan-limit' | 'image-placement-fallback'Stable code for filtering warnings without parsing messages.
messagestringHuman-readable description of the limitation.
pageNumber?numberOne-based page number, when the warning concerns a drawing occurrence.
partName?stringPackage part when the warning comes from source inspection.

OpenDocumentForExportOptionsinterface

Shared session options; translators add their own format-specific options.

interface OpenDocumentForExportOptions
MemberTypeSummary
convertPreservedImage?PreservedImageConverterOptional converter for preserved image formats the default decoder cannot inspect.
displayMode?RevisionDisplayModeRevision projection applied before records reach an exporter. Default: `all-markup`.
imageDecodePort?ImageDecodePortHost image metadata decoder; omit for the bounded DOM-free Node decoder.
measurer?TextMeasurerText measurement used for line wrapping and pagination. Omit only when deterministic approximate pagination is acceptable. Core then uses a fixed-width fallback that neither resolves nor shapes the document's fonts, so line and page breaks can differ from Word. Exporters promising physical-page fidelity must supply a font-backed measurer. For immutable DOCX bytes with document-aware font origins, use [openFontBackedDocumentForExport](openFontBackedDocumentForExport); [acquireSharedExportShaping](acquireSharedExportShaping) is for process-static prepared configurations or a live host that already owns revision-stable shaping.
producer?stringStable measurement implementation identity used by layout caches and diagnostics. Pair it with the exact shaping policy behind `measurer`; it is not a substitute for matching metrics.
resourceTimeoutMs?numberMaximum time spent waiting for image resources in one layout call. Default: 60 seconds.
reuseAcrossRevisions?booleanRetain incremental state for a live view. Defaults to true for views and false for bytes.
signal?AbortSignalCancels resource waits and subsequent layouts.

OpenMarkdownDocumentForExportOptionsinterfaceSource ↗

Layout controls for a reusable Markdown export session.

interface OpenMarkdownDocumentForExportOptions extends OpenDocumentForExportOptions
MemberTypeSummary
fallbackFonts?MarkdownFontsSourceOpt-in origins consulted only after caller fonts and bundled substitutes. Put `googleFonts()` here to fetch catalogued families the local origins cannot paint. This has the same immutable-bytes restriction and explicit-measurer precedence as [fonts](fonts).
fontPolicy?'best-effort' | 'strict'`strict` refuses failed origins or any requested family missing one of four static faces.
fonts?MarkdownFontsSourceCaller-supplied font bytes or resolvers, in first-wins order. These take precedence over the package's bundled metric-compatible Word substitutes. A resolver is invoked after the DOCX is parsed with the bounded family list layout can render. Custom origins require immutable DOCX bytes; for a live view, supply a revision-stable `measurer` instead. An explicit measurer takes precedence and font origins are not invoked.
onFontResolution?(report: ExportFontResolutionReport) => voidFire-and-forget evidence for the exact direct/substituted faces behind page breaks. Returned promises are observed for rejection but do not delay export.
reuseAcrossRevisions?booleanRetains incremental state for a live view or caller-measured session. Document-aware byte sessions are immutable and reject `true` instead of silently ignoring it.

RevisionAttributioninterface

One revision wrapper's provenance, as authored.

id is the verbatim @w:id string rather than a number: ST_DecimalNumber restricts xsd:integer with no bounds, so a file may carry a value outside the safe integer range, and parsing it to a number would silently merge two distinct revisions.

date is absent when the file omits it. @w:date is optional on CT_TrackChange, and inventing one is a silent content change.

interface RevisionAttribution
MemberTypeSummary
authorstring
date?string
idstring
kindRevisionKind
nodeIdstringThe wrapper's node id, so a surface can address this exact site.

SemanticCommentArtifactRecordinterface

Normalized comment; all relation ids share the opaque snapshot-local id space.

interface SemanticCommentArtifactRecord
MemberTypeSummary
authorstring
date?string
idstring
initialsstring
kind'comment'
occurrencesreadonly SemanticReviewArtifactOccurrence[]
orphanedboolean
parentId?string
parentRevisionId?string
replyIdsreadonly string[]
resolvedboolean
textstring

SemanticDrawingVisitinterface

One drawing in bounded graph-enumeration order with exporter-grade provenance.

Enumeration is deliberately not paint order: story anchors (and nested textboxes) are visited before inline line drawings. Renderers use paintLayer plus record geometry to compose layers.

interface SemanticDrawingVisit extends StoryDrawingContext
MemberTypeSummary
absoluteHitBoundsLayoutBoxAbsolute pointer/hit bounds.
absolutePaintBoundsLayoutBoxAbsolute painted bounds, including effects and clipping.
drawingInlineDrawingRecord | AnchoredDrawingRecordPublished drawing record; inline visits also carry paragraph and line.
drawingOriginReadonly<{ x: number; y: number; }>Absolute origin of this drawing's extent in page-stack coordinates.
noteAreaKindNoteAreaRecord['kind'] | nullOwning note-area kind for note/separator drawings; null elsewhere.
noteScopeIdstring | nullNote scope for drawings in note stories; null elsewhere.
pagePageRecordPhysical page carrying this drawing occurrence.
paintLayerSemanticDrawingLayerLayer relative to text in the immediate owning story.
rootSemanticStoryVisitPrecise root host and absolute origin for story-relative geometry.
rootStorySemanticRootStoryKindRoot story from which textbox descent began.
storySemanticStoryKindImmediate story classification; `textbox` after textbox descent.

SemanticLayoutinterface

A complete layout pass: every page, plus the document-wide indexes derived alongside them.

Stamped with the store revision it was laid out from, so anything holding geometry can tell whether the document has moved underneath it — which is how stale pointer gestures and overlays are refused rather than applied to coordinates that no longer describe anything.

interface SemanticLayout
MemberTypeSummary
contentControls?readonly ContentControlBoundaryRecord[]Every content-control boundary in document order, including multi-page fragment lists.
controlContextToken?stringFingerprint of wrapper-only control metadata (alias, tag, lock, type, placeholder, binding).
displayMode?RevisionDisplayModeRevision projection already applied to every published record.
pagesreadonly PageRecord[]
reviewArtifacts?readonly SemanticReviewArtifactRecord[]Normalized comments and tracked changes from the same package revision as these pages. Exporters consume this plain-data stream instead of re-reading OOXML or review state.
revisionnumberThe store revision these records were laid out from.

SemanticReviewArtifactOccurrenceinterface

One physical occurrence of a comment or tracked-change source range.

interface SemanticReviewArtifactOccurrence
MemberTypeSummary
geometry?SemanticReviewArtifactOccurrenceGeometryLaid-out bounds when this occurrence can be measured; omitted otherwise.
noteAreaKind'footnotes' | 'endnotes' | null
noteScopeIdstring | null
pageIndexnumber
physicalPageNumbernumber
revisionRole?'replaced' | 'replacement' | 'neutral'Replacement-half meaning for tracked-change occurrences; absent for comments.
rootStorySemanticArtifactRootStoryKind
sourceSemanticReviewArtifactSource
storySemanticArtifactStoryKind
textboxPathreadonly string[]Root-to-leaf drawing ids for a textbox occurrence; empty outside textboxes.

SemanticReviewArtifactOccurrenceGeometryinterface

Laid-out bounds for one review occurrence.

pageContent uses the same space as line boxes. pageStack uses stacked page coordinates. A point occurrence publishes width: 0.

interface SemanticReviewArtifactOccurrenceGeometry
MemberTypeSummary
pageContentreadonly LayoutBox[]
pageStackreadonly LayoutBox[]

SemanticReviewArtifactPositioninterface

One model position retained as exporter provenance.

interface SemanticReviewArtifactPosition
MemberTypeSummary
offsetnumber
paragraphIdstring

SemanticReviewArtifactSourceinterface

Package-relative snapshot provenance, not durable public identity.

Engine-produced occurrences keep start.paragraphId === end.paragraphId. Cross-paragraph source ranges are sliced into per-paragraph occurrences before geometry attaches.

interface SemanticReviewArtifactSource
MemberTypeSummary
endSemanticReviewArtifactPosition
partNamestring
startSemanticReviewArtifactPosition

SemanticTrackedChangeArtifactRecordinterface

Normalized change; ids are opaque and stable only within the source snapshot.

interface SemanticTrackedChangeArtifactRecord
MemberTypeSummary
authorstring
change'insert' | 'delete' | 'replace' | 'moveFrom' | 'moveTo' | 'format' | 'paragraphMark' | 'structural'
date?string
idstring
kind'tracked-change'
markDirection?'insert' | 'delete' | 'moveFrom' | 'moveTo'
nestingnumberNested tracked-change depth, where the innermost decision is operative.
occurrencesreadonly SemanticReviewArtifactOccurrence[]
pairedWith?string
readOnlyboolean
replacedRangeCount?numberNumber of leading source ranges belonging to struck text in a replacement.
replacedTextstring
replyIdsreadonly string[]
textstring

SourceCropinterface

a:srcRect — how much of each edge of the source image is cropped away, as fractions.

interface SourceCrop
MemberTypeSummary
bottomnumber
leftnumber
rightnumber
topnumber

TextboxStoryLayoutinterface

One text box's story laid out inside its extent, in content-box-relative coordinates.

Fragments origin at the content box's top-left; paint places the content box at drawing origin + contentOffset and clips to the extent.

interface TextboxStoryLayout
MemberTypeSummary
clippedResourceToken?stringResource identities of the drawings the clip DROPPED, in flow order.
contentHeightnumberContent box height (extent minus vertical insets).
contentOffsetReadonly<{ x: number; y: number; }>Offset of the content box inside the drawing extent: insets plus vertical anchoring.
contentWidthnumberContent box width (extent minus horizontal insets).
fallbackReason?TextboxStoryFallbackReasonTrue when layout hit a named bound and returned a truncated / empty story.
fillHexstring | nullSolid fill of the hosting shape, painted behind the story; null for no fill.
flowHeightnumberHeight the blocks flow to (points), before vertical anchoring.
fragmentsreadonly BlockFragmentRecord[]Content-box-relative fragments (origin at the content box's top-left).
strokeHexstring | nullSolid outline of the hosting shape; null for no outline.
strokeWidthPtnumberOutline width in points; 0 when absent.

TextMeasurerinterface

Text measurement, injected.

A real implementation shapes with the resolved font; the tests supply a deterministic one. Layout never reads the DOM, so this is the only way width and height enter it.

interface TextMeasurer
MemberTypeSummary
caretAdvancesOptional whole-span logical caret advances, indexed by UTF-16 offset. Values are nondecreasing, start at zero, and end at the measured advance. Ligature interiors may share an edge. Undefined selects a bounded approximate fallback.
inkBoundsOptional conservative ink bounds for one grapheme, in points from its origin. Includes size and horizontal scale, but not trailing character spacing. Undefined keeps layout on the advance-only path.
lineMetricsLine height and baseline for the resolved style.
measureAdvance width of `text` in the resolved style.

VectorShapeProjectioninterface

The renderable subset of a wps:wsp non-picture graphic, or of one bounded wpg:wgp group of them: closed polygon subpaths (a:custGeom with move/line/close/cubicBezTo verbs, or a supported a:prstGeom) with a solid fill and/or stroke. The colour may come from a:srgbClr or from the theme, through a:schemeClr or a wps:style matrix reference. Anything richer (gradient and picture fills, text bodies, rotation, a nested group) projects as null and paints the labelled placeholder instead.

interface VectorShapeProjection
MemberTypeSummary
componentsreadonly VectorShapeComponent[]Independently styled paths, always non-empty. A direct shape has one component.
extentEmuReadonly<{ cx: number; cy: number; }>The drawing extent that frames the subpath coordinate space.
fillAlpha?number
fillHexstring | nullValidated 6-digit sRGB hex (no `#`) of the one component, or null. A group of two or more components has no single fill, so this is null there as well: null means "no one fill to name", not "nothing is filled". Read `components` to paint.
strokeAlpha?number
strokeHexstring | nullAs `fillHex`, for the stroke: the one component's stroke, else null.
strokeWidthEmunumberThe one component's stroke width in EMU; 0 when absent or when grouped.
subpathsEmureadonly (readonly Readonly<{ x: number; y: number; }>[])[]Every component's subpath polygons, flattened, in extent-EMU space; fill rule is even-odd. Painting reads `components`, which keeps each polygon with its own colours; this stays the geometry summary (bounds, hit tests, wrap holes).

Type aliases (27)

AnchoredDrawingLayoutFallbacktype

Named fallback when a positioning frame cannot be resolved (OpenSpec 4.6).

type AnchoredDrawingLayoutFallback = 'unresolvable-frame' | 'page-defer-exhausted';

DrawingHorizontalReferenceFrametype

type DrawingHorizontalReferenceFrame = 'character' | 'column' | 'insideMargin' | 'leftMargin' | 'margin' | 'outsideMargin' | 'page' | 'rightMargin';

DrawingVerticalReferenceFrametype

type DrawingVerticalReferenceFrame = 'bottomMargin' | 'insideMargin' | 'line' | 'margin' | 'outsideMargin' | 'page' | 'paragraph' | 'topMargin';

ExportDocumentMetadatatype

Bounded package metadata for exporter output dictionaries.

type ExportDocumentMetadata = Readonly<DocumentProperties>;

ExportDocumentSourcetype

Source accepted by every exporter: untrusted bytes or an already-open live view.

type ExportDocumentSource = Uint8Array | HeadlessDocumentView;

HeadlessDocumentRejectiontype

A bad package is data, not an exceptional control path.

type HeadlessDocumentRejection = OoxmlPackageRejection | 'no-main-document-tree';

ImageResourceStatetype

What is known about one embedded image: validated, refused, or still decoding.

Content type is a CLAIM. Signature sniffing, structural header validation and the decode port are authoritative, and bytes that fail them never enter public state.

type ImageResourceState = {
    readonly kind: 'ready';
    readonly partName: string;
    readonly contentId: string;
    readonly resourceKey: string;
    readonly validatedHandle: ValidatedImageBytesHandle;
    readonly mime: RenderableImageMime;
    readonly pixelWidth: number;
    readonly pixelHeight: number;
    readonly dpiX: number;
    readonly dpiY: number;
} | {
    readonly kind: 'unrenderable';
    readonly partName: string | null;
    readonly mime: RenderableImageMime | PreservedImageMime | 'unknown';
    readonly reason: 'unsupported-format' | 'non-picture-graphic' | 'signature-mismatch' | 'decode-failed' | 'resource-limit';
} | {
    readonly kind: 'external';
    readonly relationshipId: string;
    readonly sinkSafe: boolean;
} | {
    readonly kind: 'missing';
    readonly relationshipId: string;
} | {
    readonly kind: 'pending';
    readonly resourceKey: string;
};

ImageWrapTargettype

Nine Word wrap menu targets (inline plus eight floating modes).

type ImageWrapTarget = 'inline' | 'square' | 'squareLeft' | 'squareRight' | 'tight' | 'through' | 'topAndBottom' | 'behind' | 'inFront';

MarkdownCommenttypeSource ↗

Normalized DOCX comment, independent of editor UI state.

Its ID is opaque and stable only within one [MarkdownExportResult](MarkdownExportResult). Never persist the ID across exports; pair citations with the caller's own document version or content hash.

type MarkdownComment = SemanticCommentArtifactRecord;

MarkdownFontOrigintypeSource ↗

One caller-controlled font origin used for headless pagination.

type MarkdownFontOrigin = FontOrigin;

MarkdownFontsSourcetypeSource ↗

One font origin, or an ordered first-wins list of origins.

type MarkdownFontsSource = MarkdownFontOrigin | readonly MarkdownFontOrigin[];

MarkdownJSONImagetypeSource ↗

JSON-safe image metadata. Binary bytes are delivered separately.

type MarkdownJSONImage = Omit<MarkdownImageAsset, 'bytes'>;

MarkdownJSONResulttypeSource ↗

JSON-safe export for HTTP responses and portable bundle manifests.

type MarkdownJSONResult = Omit<MarkdownExportResult, 'media' | 'fontResolution'> & {
    readonly media: readonly MarkdownJSONImage[];
    readonly fontResolution: (Omit<NonNullable<MarkdownExportResult['fontResolution']>, 'originFailures'> & {
        readonly originFailures: readonly {
            readonly originIndex: number;
            readonly originName?: string;
            readonly cause: string;
        }[];
    }) | null;
};

MarkdownReviewArtifacttypeSource ↗

Comment or tracked change returned by Markdown export. IDs are opaque and result-local.

type MarkdownReviewArtifact = SemanticReviewArtifactRecord;

MarkdownReviewCoveragetypeSource ↗

How much of one Core source occurrence is represented by the returned ranges.

type MarkdownReviewCoverage = 'complete' | 'partial' | 'none';

MarkdownReviewOccurrencetypeSource ↗

Page/story/source provenance for one exported review artifact.

type MarkdownReviewOccurrence = SemanticReviewArtifactRecord['occurrences'][number];

MarkdownReviewProjectiontypeSource ↗

Markdown string containing one review binding.

type MarkdownReviewProjection = {
    readonly kind: 'document';
} | {
    readonly kind: 'page';
    readonly pageIndex: number;
    readonly pageNumber: number;
    readonly field: 'markdown' | 'headerMarkdown' | 'footerMarkdown';
};

MarkdownReviewRangePrecisiontypeSource ↗

Precision of a source-to-Markdown review range.

type MarkdownReviewRangePrecision = 'exact' | 'containing-construct';

MarkdownReviewUnmappedReasontypeSource ↗

Why a source occurrence has no range in a particular Markdown projection.

type MarkdownReviewUnmappedReason = 'not-represented-in-markdown' | 'non-linear-structural-change' | 'omitted-story-content';

MarkdownTrackedChangetypeSource ↗

Normalized DOCX tracked change, independent of editor UI state.

Its ID is opaque and stable only within one [MarkdownExportResult](MarkdownExportResult). Never persist the ID across exports; pair citations with the caller's own document version or content hash.

type MarkdownTrackedChange = SemanticTrackedChangeArtifactRecord;

OpenDocumentForExportResulttype

Typed refusal for bytes that cannot become a document view, or an already-aborted open.

type OpenDocumentForExportResult = {
    readonly ok: true;
    readonly session: ExportSession;
} | {
    readonly ok: false;
    readonly reason: HeadlessDocumentRejection | 'aborted';
    readonly detail?: string;
};

OpenMarkdownDocumentForExportResulttypeSource ↗

Open result whose successful session retains its structured font-resolution report.

type OpenMarkdownDocumentForExportResult = {
    readonly ok: true;
    readonly session: MarkdownExportSession;
} | Exclude<OpenDocumentForExportResult, {
    readonly ok: true;
}>;

PreservedImageConvertertype

Optional caller conversion for preserved formats such as EMF/WMF/TIFF.

type PreservedImageConverter = (bytes: Uint8Array, mime: PreservedImageMime, limits: ImageResourceLimits, 
signal?: AbortSignal) => Promise<Readonly<{
    bytes: Uint8Array;
    mime: SupportedImageMime;
}> | null>;

RevisionDisplayModetype

Which revisions layout resolves before producing pages.

- all-markup shows both halves of every change. - proposed shows what the document becomes if every change is accepted. - original shows what it was before any of them.

The last two are specified as equal to accept-all and reject-all OUTPUT, which is what makes them testable, without either applying an op.

type RevisionDisplayMode = 'all-markup' | 'proposed' | 'original';

SemanticArtifactRootStoryKindtype

Published root story containing an artifact occurrence.

type SemanticArtifactRootStoryKind = 'body' | 'header' | 'footer' | 'footnote' | 'endnote' | 'note-separator';

SemanticArtifactStoryKindtype

Exact story in which a review artifact's source anchor was laid out.

type SemanticArtifactStoryKind = SemanticArtifactRootStoryKind | 'textbox';

SemanticReviewArtifactRecordtype

Exporter-neutral review artifact normalized by core.

type SemanticReviewArtifactRecord = SemanticTrackedChangeArtifactRecord | SemanticCommentArtifactRecord;

Variables (3)

HARD_MAX_AGGREGATE_FONT_BYTESconst

Most bytes all admitted faces may total, whatever a caller configures.

HARD_MAX_AGGREGATE_FONT_BYTES: number

HARD_MAX_FONT_BYTESconst

Largest single face this engine will ever admit, whatever a caller configures.

A CEILING, not a default: a host may set a smaller maxFontBytes, but nothing can raise it past this. Font bytes come from files, and an unbounded face is a memory-exhaustion vector.

HARD_MAX_FONT_BYTES: number

HARD_MAX_FONT_SOURCESconst

Most faces one snapshot may hold, whatever a caller configures.

HARD_MAX_FONT_SOURCES = 256

On this page

SubpathsPackage rootFunctionscreateMarkdownZipexportMarkdownexportMarkdownFromexportMarkdownLayoutforEachSemanticDrawingopenDocumentForExporttoMarkdownJSONClassesDocumentOpenErrorExportResourceErrorMarkdownBundleErrorMarkdownMediaErrorInterfacesAnchoredDrawingRecordDrawingAccessibilityDrawingGeometryDrawingTransformExportContentWarningExportDestinationAnchorExportDestinationGeometryExportDroppedEmbeddedFontExportFontFaceResolutionExportFontFamilyResolutionExportFontResolutionReportExportSemanticLayoutExportSessionFontOriginFailureFontRequestFontSubstitutionHeadlessDocumentViewImageDecodePortInlineDrawingRecordLayoutBoxMarkdownExportOptionsMarkdownExportResultMarkdownExportSessionMarkdownImageAssetMarkdownImageDataMarkdownImageOccurrenceMarkdownImageOptionsMarkdownPageMarkdownPaginationInfoMarkdownProjectionOptionsMarkdownReviewBindingMarkdownReviewRangeMarkdownWarningOpenDocumentForExportOptionsOpenMarkdownDocumentForExportOptionsRevisionAttributionSemanticCommentArtifactRecordSemanticDrawingVisitSemanticLayoutSemanticReviewArtifactOccurrenceSemanticReviewArtifactOccurrenceGeometrySemanticReviewArtifactPositionSemanticReviewArtifactSourceSemanticTrackedChangeArtifactRecordSourceCropTextboxStoryLayoutTextMeasurerVectorShapeProjectionType aliasesAnchoredDrawingLayoutFallbackDrawingHorizontalReferenceFrameDrawingVerticalReferenceFrameExportDocumentMetadataExportDocumentSourceHeadlessDocumentRejectionImageResourceStateImageWrapTargetMarkdownCommentMarkdownFontOriginMarkdownFontsSourceMarkdownJSONImageMarkdownJSONResultMarkdownReviewArtifactMarkdownReviewCoverageMarkdownReviewOccurrenceMarkdownReviewProjectionMarkdownReviewRangePrecisionMarkdownReviewUnmappedReasonMarkdownTrackedChangeOpenDocumentForExportResultOpenMarkdownDocumentForExportResultPreservedImageConverterRevisionDisplayModeSemanticArtifactRootStoryKindSemanticArtifactStoryKindSemanticReviewArtifactRecordVariablesHARD_MAX_AGGREGATE_FONT_BYTESHARD_MAX_FONT_BYTESHARD_MAX_FONT_SOURCES