Skip to content
Apertura
API reference

@apertura/core

Apertura core: byte sources, format detection, plugin registry, shared document model

114 exported symbols · 114 declared here · 0 re-exported

Classes

AperturaError
class AperturaError extends Error

Base class for every error raised by Apertura. A common ancestor lets consumers distinguish "the file failed to open" from a genuine bug in their own code with a single `instanceof` check.

code
string
Stable machine-readable code; unaffected by message wording changes.
BlobByteSource
class BlobByteSource implements ByteSource

A source backed by a browser `Blob`/`File`, read lazily in chunks.

name
string | undefined
File name when known. Used as a hint for format detection.
mimeType
string | undefined
MIME type when the source reports one.
byteLength
number
Total size of the source in bytes.
slice
(start: number, end?: number) => Promise<Uint8Array>
Reads the `[start, end)` range. Implementations must return exactly the requested number of bytes or throw {@link OutOfBoundsError}. Short reads are not allowed, otherwise every parser would have to re-check the length after each call.
ByteReader
class ByteReader

A synchronous cursor-based reader over a `Uint8Array`. Binary formats (ZIP headers, OLE2/CFB, PDF xref tables, TIFF IFDs) are read as sequences of fixed-width fields, and tracking the offset by hand in every parser is a reliable way to introduce bugs. The reader does it for us and bounds-checks every step.

offset
number
offset
number
byteLength
number
remaining
number
eof
boolean
skip
(count: number) => this
seek
(offset: number) => this
u8
() => number
u16
(littleEndian?: boolean) => number
u32
(littleEndian?: boolean) => number
u64
(littleEndian?: boolean) => bigint
u64AsNumber
(littleEndian?: boolean) => number
Reads a 64-bit value as a `number`. ZIP64 and PDF use 64-bit offsets, but real files never exceed 2^53 bytes and `number` is far more convenient for offset arithmetic.
i8
() => number
i16
(littleEndian?: boolean) => number
i32
(littleEndian?: boolean) => number
f32
(littleEndian?: boolean) => number
f64
(littleEndian?: boolean) => number
bytes
(count: number) => Uint8Array
Returns a view onto the underlying buffer without copying.
peek
(count: number) => Uint8Array
Reads without advancing the cursor.
matches
(signature: readonly number[]) => boolean
Checks a signature at the current position without advancing the cursor.
CancelledError
class CancelledError extends AperturaError

The operation was aborted through an AbortSignal.

CorruptFileError
class CorruptFileError extends AperturaError

The file was identified, but its contents violate the format specification.

offset
number | undefined
Byte offset where the violation was found, when known.
EncryptedFileError
class EncryptedFileError extends AperturaError

The document is encrypted and no usable password was supplied.

FormatRegistry
class FormatRegistry

Registry of parsers. An instance rather than a global singleton: a single page may host several independently configured viewers, and tests must not see each other's registrations. {@link defaultRegistry} is available for simple cases. Renderers are registered in `ViewRegistry` from `@apertura/render`, which extends this class. The split is what lets a server open a document without the DOM appearing anywhere in the type graph.

registerParser
<TDocument extends AperturaDocument>(plugin: ParserPlugin<TDocument>) => this
getParser
(format: FormatId) => ParserPlugin | undefined
supportedFormats
() => FormatId[]
Formats that have a registered parser.
open
(source: ByteSource, options?: OpenOptions) => Promise<AperturaDocument>
Detects the format and opens the document with the matching plugin. When detection returns `unknown` (the typical case for a ZIP container) the registered plugins are polled through `canOpen`, so docx, xlsx and pptx sort themselves out without the core knowing anything about their internals.
HttpByteSource
class HttpByteSource implements ByteSource

A source backed by HTTP range requests. Lets a document be opened from a URL without downloading it in full: a few kilobytes of tail data are enough to list the contents of a 200 MB file. If the server does not support ranges, the source downloads the file once and serves subsequent reads from memory.

name
string | undefined
File name when known. Used as a hint for format detection.
mimeType
string | undefined
MIME type when the source reports one.
create
(url: string, init?: RequestInit) => Promise<HttpByteSource>
byteLength
number
Total size of the source in bytes.
slice
(start: number, end?: number) => Promise<Uint8Array>
Reads the `[start, end)` range. Implementations must return exactly the requested number of bytes or throw {@link OutOfBoundsError}. Short reads are not allowed, otherwise every parser would have to re-check the length after each call.
dispose
() => void
Releases retained resources such as caches or network connections.
MemoryByteSource
class MemoryByteSource implements ByteSource

A source backed by a buffer already held in memory.

name
string | undefined
File name when known. Used as a hint for format detection.
mimeType
string | undefined
MIME type when the source reports one.
byteLength
number
Total size of the source in bytes.
slice
(start: number, end?: number) => Promise<Uint8Array>
Reads the `[start, end)` range. Implementations must return exactly the requested number of bytes or throw {@link OutOfBoundsError}. Short reads are not allowed, otherwise every parser would have to re-check the length after each call.
bytes
() => Uint8Array
Synchronous access to the whole buffer; for internal parser use only.
NotImplementedError
class NotImplementedError extends AperturaError

A format feature that has not been implemented yet. A dedicated type lets the viewer show "this part of the document is not supported yet" instead of a generic read failure.

OutOfBoundsError
class OutOfBoundsError extends AperturaError

A read ran past the end of the byte source.

UnsupportedFormatError
class UnsupportedFormatError extends AperturaError

The file format was not recognised, or no plugin is registered for it.

detectedFormat
string | undefined
UnsupportedMarkupError
class UnsupportedMarkupError extends AperturaError

Markup the reader walked past that nothing has declared it may walk past. Only ever raised in strict mode, which no viewer turns on: a reader that stops at the first unknown attribute is useless against real files, where every generator writes something nobody has seen. What it is for is the opposite situation — a development run over a corpus, where an element the parser silently ignores is indistinguishable from one it handles, and a gap therefore survives for as long as nobody happens to look at the right page. Strict mode makes the ignoring explicit: everything the parser passes over must be named in the registry of markup we have decided draws nothing, with the reason. Anything else stops the parse and names itself.

markup
string
The markup that was not accounted for, as `w:element` or `w:element@w:attr`.
context
string
The element the markup was found in, when it has one.

Functions

columnWidthToPixels
function columnWidthToPixels(width: number, maxDigitWidth?: number): number

Excel column width in "characters" converted to pixels. Excel measures width in multiples of the width of the "0" glyph of the Normal style font and adds 5 pixels of cell padding (MS-OI29500, Column Width): `px = trunc(width * mdw) + 5`, where `mdw` is the digit width in pixels (7 for the default Calibri 11pt). This is where Excel's well-known default comes from: 8.43 characters is exactly 64 pixels.

compareLocators
function compareLocators(a: Locator, b: Locator): number

Orders two locators the way the document reads. Needed wherever a range has to be normalised — a user selects backwards about half the time — and wherever highlights are merged. Flows are ordered by their kind and index so that a body address always precedes a footnote's, which is arbitrary but stable, and stable is the property that matters.

contentHash
function contentHash(bytes: Uint8Array): string

Eight hex digits identifying the bytes a locator was made against. FNV-1a over the whole buffer, which is not a cryptographic hash and is not meant to be. The question it answers is "is this the same file as the one the address came from", where the alternative to a wrong answer is a wrong highlight, not a security breach. Sixty-four bits folded to thirty-two make an accidental collision a once-in-four-billion event between two files a user has open at the same moment, and a real hash would cost a megabyte of bookkeeping and a dependency for it.

contrastingTextColor
function contrastingTextColor(background: Rgba): Rgba

Picks a readable text colour for a given background. Needed wherever a format specifies only a fill: a table header with a dark shade and default black text would be unreadable. The 0.5 threshold is on WCAG relative luminance.

decodeCp1251
function decodeCp1251(bytes: Uint8Array): string

CP1251: Cyrillic text in legacy Microsoft Office files.

decodeLatin1
function decodeLatin1(bytes: Uint8Array): string

Latin-1 (ISO-8859-1): used for legacy ZIP entry names and PDF strings.

decodeUtf16le
function decodeUtf16le(bytes: Uint8Array): string

UTF-16LE: the native string encoding of OLE2/CFB and many Windows structures.

decodeUtf8
function decodeUtf8(bytes: Uint8Array, fatal?: boolean): string
decodeXml
function decodeXml(bytes: Uint8Array): string

Decodes an XML part, honouring the byte order mark it may start with. Nearly every OOXML part is UTF-8, and this exists for the ones that are not: XML permits UTF-16, a writer occasionally uses it, and Excel opens such a file without comment. Decoding those bytes as UTF-8 yields a string of NULs with no root element — a whole workbook lost to two bytes at the front.

describeFormat
function describeFormat(id: FormatId): FormatDescriptor | undefined
detectFormat
function detectFormat(source: ByteSource): Promise<DetectionResult>

Determines the file format from its contents, name and MIME type. For ZIP containers the result is always `probable`: telling docx, xlsx, pptx and odt apart requires looking inside the archive, which is the job of `@apertura/ooxml`. The core deliberately avoids pulling in decompression just to detect a format.

eighthPointsToPoints
function eighthPointsToPoints(eighths: number): number

Eighths of a point: the unit of `w:sz` on border elements.

emuToInches
function emuToInches(emu: number): number
emuToPixels
function emuToPixels(emu: number): number
emuToPoints
function emuToPoints(emu: number): number
encodeUtf8
function encodeUtf8(text: string): Uint8Array
formatByExtension
function formatByExtension(value: string): FormatDescriptor | undefined

Looks up a format by extension. Accepts `docx`, `.docx` or a whole file name.

formatByMimeType
function formatByMimeType(mimeType: string): FormatDescriptor | undefined
formatLocator
function formatLocator(parts: { version?: number; hash?: string; flow: LocatorFlow; steps?: readonly LocatorStep[]; offset?: number | undefined; cell?: string | undefined; }): Locator

Builds a locator string. The inverse of {@link parseLocator} for every input it accepts; the pair is covered by a round-trip test rather than by inspection, because the grammar is small enough to be exhaustively generated and too fiddly to eyeball.

grayscale
function grayscale(color: Rgba): Rgba

`a:gray`: the colour rendered in shades of grey, by perceived brightness.

halfPointsToPoints
function halfPointsToPoints(halfPoints: number): number

Half-points: the unit Word uses for font sizes (`w:sz w:val="24"` is 12pt).

hslToRgb
function hslToRgb(hsl: Hsl, alpha?: number): Rgba
invert
function invert(color: Rgba): Rgba

`a:inv`: every channel inverted.

isLocator
function isLocator(value: unknown): value is Locator

True when the string is shaped like a locator. Does not validate the path.

lengthToCss
function lengthToCss(length: Length | undefined): string | undefined

Converts a {@link Length} to a CSS string, or `undefined` when it is `auto`.

lengthToPixels
function lengthToPixels(length: Length | undefined, reference?: number): number

Converts a {@link Length} to pixels; percentages need a reference size.

locatorFlow
function locatorFlow(locator: Locator): LocatorFlow

The flow a locator addresses, without parsing the rest of it.

locatorSteps
function locatorSteps(locator: Locator): readonly LocatorStep[]

The path steps of a locator.

locatorWithOffset
function locatorWithOffset(locator: Locator, offset: number | undefined): Locator

The same locator with a different character offset.

modulateHue
function modulateHue(color: Rgba, hueMod?: number, hueOff?: number): Rgba

Applies the `hueMod`/`hueOff` hue rotation of DrawingML; both wrap.

modulateLuminance
function modulateLuminance(color: Rgba, lumMod?: number, lumOff?: number): Rgba

Applies the `lumMod`/`lumOff` luminance modulation used by DrawingML themes. Word writes theme colour variations this way, e.g. "Accent 1, lighter 40%" becomes `lumMod 60000` + `lumOff 40000` (values are thousandths of a percent).

modulateSaturation
function modulateSaturation(color: Rgba, satMod?: number, satOff?: number): Rgba

Applies the `satMod`/`satOff` saturation modulation of DrawingML. The other half of the pair Office writes for a theme variation. Every theme Word ships states its fills as a scheme colour with both a luminance and a saturation modifier on it — a heading colour is `accent1` at 110% saturation and 75% luminance — and applying only the first paints a colour that is the right lightness and visibly the wrong intensity.

normalizeForMatch
function normalizeForMatch(source: string, options?: NormalizeOptions): NormalizedText

Normalises text for quote matching and records where every character came from. The map back is the whole point, and the reason this is not three chained `replace` calls: a match found in normalised space has to become a range in the document, and every transformation that changes a length has to be accounted for as it happens. Unicode normalisation is applied per cluster rather than to the finished string. Running NFC over the assembled result would silently shorten the text out from under the offsets just recorded — the map would be right for every document without a diacritic and wrong for every document with one, which is the worst failure mode on offer. Per *character* would be no better in the other direction: NFC composes a base and its combining mark into one character, and a character examined alone has nothing to compose with, so decomposed text would stay decomposed and a quote stored precomposed would never match it. So a base character and the marks that follow it are normalised together, and every character that comes out is mapped to where the base came from.

parseHexColor
function parseHexColor(value: string | undefined): Rgba | undefined

Parses `ST_HexColor`: six or eight hex digits, with or without a leading hash. The special value `auto` means "the application picks the colour", so it returns `undefined` and lets the caller apply its own contextual rule (usually black text on a light background).

parseLocator
function parseLocator(locator: Locator): LocatorParts

Parses a locator, or throws. Throwing rather than returning `undefined` because a malformed locator is a programming error on the caller's side — locators are produced by this library, not typed by hand — and a silent `undefined` here surfaces three layers away as a highlight that does not appear.

percent
function percent(value: number): Length
pixelsToColumnWidth
function pixelsToColumnWidth(pixels: number, maxDigitWidth?: number): number

Inverse of {@link columnWidthToPixels}.

pixelsToPoints
function pixelsToPoints(pixels: number): number
pixelsToTwips
function pixelsToTwips(pixels: number): number
points
function points(value: number): Length
pointsToEmu
function pointsToEmu(points: number): number
pointsToPixels
function pointsToPixels(points: number): number
presetGeometryPath
function presetGeometryPath(geometry: PresetGeometry): string | undefined

Builds the outline of a preset shape.

pt
function pt(value: number): string

Formats a value as a CSS point string, rounded to two decimals.

px
function px(value: number): string

Formats a value as a CSS pixel string, rounded to two decimals.

rectanglePath
function rectanglePath(width: number, height: number): string

An axis-aligned rectangle path, the fallback for an unknown preset.

relativeLuminance
function relativeLuminance(color: Rgba): number

WCAG 2.1 relative luminance, 0..1.

rgbToHsl
function rgbToHsl(color: Rgba): Hsl
rowHeightToPixels
function rowHeightToPixels(heightInPoints: number): number

Excel row heights are expressed in points.

shade
function shade(color: Rgba, amount: number): Rgba

Darkening (`shade`): mixes towards black.

throwIfAborted
function throwIfAborted(signal: AbortSignal | undefined, what?: string): void

Throws {@link CancelledError} if the signal has already been aborted.

tint
function tint(color: Rgba, amount: number): Rgba

Lightening (`tint` in DrawingML): mixes towards white.

toByteSource
function toByteSource(input: ByteSourceInput): Promise<ByteSource>

Normalises any supported input into a {@link ByteSource}. Strings are URLs.

toCssColor
function toCssColor(color: Rgba | undefined): string | undefined
trimNulls
function trimNulls(text: string): string

Strips the trailing NUL padding of a fixed-length string field.

twips
function twips(value: number): Length
twipsToPixels
function twipsToPixels(twips: number): number
twipsToPoints
function twipsToPoints(twips: number): number

Interfaces

AperturaDocument
interface AperturaDocument

An opened document: the contract shared by every parser. Deliberately narrow — it only carries what is meaningful for any format. Everything else (docx sections, xlsx sheets, pptx slides) lives in subtypes inside the format packages. The viewer works against this interface so that it can still show a title and a page count for a format whose renderer is not registered.

format
FormatId
kind
DocumentKind
metadata
DocumentMetadata
pageCount?
number | undefined
Number of pages/sheets/slides, when the format exposes it cheaply. For docx this is `undefined` until the document has been laid out: splitting a text flow into pages depends on fonts, hyphenation and the printable area.
extractText
() => Promise<string>
Extracts the whole document text for search, indexing and previews. A dedicated method because this is the one operation every format needs in the same way and which requires no rendering.
dispose
() => void
Releases retained resources. Calling it twice is safe.
ByteSource
interface ByteSource

A random-access source of bytes. This is the central abstraction of the project: parsers never touch `File`, `Blob` or the network directly. That makes it possible to read a ZIP central directory at the end of a file, or a PDF xref table, without pulling the whole document into memory, and to run the same parser in a browser, in Node, or on top of HTTP range requests.

byteLength
number
Total size of the source in bytes.
name?
string | undefined
File name when known. Used as a hint for format detection.
mimeType?
string | undefined
MIME type when the source reports one.
slice
(start: number, end?: number) => Promise<Uint8Array>
Reads the `[start, end)` range. Implementations must return exactly the requested number of bytes or throw {@link OutOfBoundsError}. Short reads are not allowed, otherwise every parser would have to re-check the length after each call.
dispose?
(() => void) | undefined
Releases retained resources such as caches or network connections.
DetectionResult
interface DetectionResult

Result of format detection.

format
FormatId
container
ContainerKind
confidence
"certain" | "probable" | "guess"
How much the detector can be trusted. `certain` — an unambiguous signature matched; `probable` — the container was identified and the concrete format was inferred from the extension or MIME type and still needs confirmation from the contents; `guess` — no signature matched and the decision rests on the file name alone.
reason
string
What led to the decision — useful when debugging third-party files.
DocumentMetadata
interface DocumentMetadata

Metadata common to every format.

title?
string | undefined
author?
string | undefined
subject?
string | undefined
keywords?
readonly string[] | undefined
description?
string | undefined
producer?
string | undefined
The application that produced the file.
createdAt?
Date | undefined
modifiedAt?
Date | undefined
language?
string | undefined
Language of the main content, BCP 47.
custom?
Readonly<Record<string, string | number | boolean | Date>> | undefined
Format-specific fields that do not fit the common schema.
FormatDescriptor
interface FormatDescriptor

Format description: its name, how to open it, how to recognise it.

id
FormatId
label
string
Human-readable name for the UI.
kind
DocumentKind
container
ContainerKind
extensions
readonly string[]
Extensions without the leading dot, lower-case.
mimeTypes
readonly string[]
Hsl
interface Hsl
h
number
0..1
s
number
0..1
l
number
0..1
Length
interface Length

A length as stored in the file, together with the unit it was stored in. Keeping the unit lets the renderer decide how to emit it: some measurements are better expressed in `pt` so the browser can round them itself, others must be pixels because they take part in layout arithmetic.

value
number
unit
"pt" | "px" | "percent" | "auto"
LocatorParts
interface LocatorParts
version
number
hash
string
Eight hex digits of the document hash, or `''` when unbound.
flow
LocatorFlow
steps
readonly LocatorStep[]
offset
number | undefined
Offset into the text of the addressed node, in UTF-16 code units. UTF-16 rather than code points because the other end of every offset in this system is a DOM `Range`, which counts UTF-16 code units, and a conversion at the boundary is a conversion that can be forgotten.
cell
string | undefined
A cell reference, for the one format that has a native address. `Sheet!C14` is the address an Excel user already knows, already types into a formula and already sees in the name box. Encoding it as `c3/w14` would be a private language for a public fact.
LocatorSelector
interface LocatorSelector

Exact: a range between two locators. Valid while the file's bytes are.

type
"AperturaLocator"
start
string
end
string
LocatorStep
interface LocatorStep

One step down the tree. `kind` is a single letter so the whole path stays short — a locator is stored per chunk, and a corpus of a million chunks pays for every character. The letters are mnemonic rather than clever: `b` block, `t` table, `w` row (`r` was taken), `c` cell, `p` paragraph, `r` run, `s` shape, `i` inline object.

kind
LocatorStepKind
index
number
ModelRange
interface ModelRange

A resolved range in the document model.

start
string
end
string
NormalizedText
interface NormalizedText

Text prepared for matching, with a way back to the original offsets. Quote matching has to ignore differences no reader would call a difference: a non-breaking space against a space, a soft hyphen left over from justification, the zero-width joiners a copy-paste through a word processor leaves behind, and the two spellings Unicode allows for any accented letter. Normalising all of that changes the offsets, so the map back is built at the same time — without it a match in normalised space cannot be turned into a range in the document.

text
string
sourceOffsets
Int32Array<ArrayBufferLike>
For each character of `text`, its offset in the source string.
sourceLength
number
OpenOptions
interface OpenOptions

Options shared by every parser.

signal?
AbortSignal | undefined
Aborts parsing of large files.
tolerant?
boolean | undefined
Keep parsing when the file locally violates the specification. Defaults to `true`: real files produced by office suites break the standard routinely, and failing the whole document where a single paragraph could be dropped is a bad trade.
password?
string | undefined
Password for encrypted documents.
onProgress?
((fraction: number) => void) | undefined
Progress callback, 0..1.
ParserPlugin
interface ParserPlugin<TDocument extends AperturaDocument = AperturaDocument>

A parser plugin for one format. Parsers are registered explicitly rather than auto-discovered: an application that only needs to view spreadsheets should not ship a presentation parser in its bundle.

format
FormatId
canOpen
(source: ByteSource, detection: DetectionResult) => Promise<boolean>
Confirms that the source really is this format. Called after the core detection pass; needed wherever a signature is not enough. The docx plugin, for instance, inspects `[Content_Types].xml` inside the ZIP archive to tell a Word document from an Excel workbook.
open
(source: ByteSource, options?: OpenOptions) => Promise<TDocument>
PresetGeometry
interface PresetGeometry

Everything a preset needs to produce its path.

preset
string
`a:prstGeom/@prst`.
width
number
height
number
adjust?
ReadonlyMap<string, number> | undefined
`a:avLst` values by name, in their raw units.
ResolvedRange
interface ResolvedRange

A resolution, and how much to trust it. `resolvedBy` is not decoration. An application that watches it can see its documents drifting — the day the exact selectors stop matching and everything falls through to quotes is the day somebody started editing the corpus — and it can see that before a user reports a highlight in the wrong place.

range
ModelRange
resolvedBy
"locator" | "position" | "quote" | "native"
confidence
number
1 for an exact match, lower for a fuzzy one.
Rgba
interface Rgba

Colour handling for office formats. OOXML expresses colour in three different ways: a direct RGB value (`FF0000`), a reference to a theme colour (`accent1`), and modifiers applied on top of a theme colour (`lumMod`, `tint`, `shade`). This module holds the conversions that are common to every format; resolving theme references stays in the format packages, which are the ones with access to `theme1.xml`.

r
number
0..255
g
number
0..255
b
number
0..255
a
number
0..1
SheetSelector
interface SheetSelector

Native: the address an Excel user already knows.

type
"Sheet"
sheet
string
ref
string
`C14` or `C14:E20`.
SlideSelector
interface SlideSelector

Native: a slide, and optionally one shape on it.

type
"Slide"
index
number
Zero-based.
shape?
number | undefined
TextPositionSelector
interface TextPositionSelector

Portable: offsets into extracted text. For everyone who chunked the text with something else. LangChain and its cousins keep a start and an end and nothing else, and this is the selector that lets those chunks come back. `profile` is a hash of the extraction options that produced the offsets. Markdown with GFM tables and markdown with HTML tables are different strings, and without the profile the difference would show up as a highlight that is forty characters off rather than as an error.

type
"TextPosition"
start
number
end
number
profile?
string | undefined
TextQuoteSelector
interface TextQuoteSelector

Robust: the text with enough of its neighbours to be unambiguous. `prefix` and `suffix` are what separate the fourteenth "Total" in a workbook from the fifteenth. Thirty-two characters each is the figure the annotation community converged on: enough to disambiguate ordinary prose, short enough that storing it per chunk is free next to the chunk itself.

type
"TextQuote"
exact
string
prefix?
string | undefined
suffix?
string | undefined

Type aliases

ByteSourceInput
type ByteSourceInput = ByteSource | Blob | ArrayBuffer | Uint8Array | string

Everything Apertura can turn into a {@link ByteSource}.

ContainerKind
type ContainerKind = 'zip' | 'ole2' | 'pdf' | 'plain-text' | 'binary-image' | 'unknown'

Container kind: what can be determined from the first bytes of a file. This intermediate layer exists because many formats share one signature: docx, xlsx, pptx, odt and epub all start with `PK\x03\x04`. The core detector identifies the container, and the package that knows how to read that container narrows it down to a specific format.

DocumentKind
type DocumentKind = | 'text-document' /** A grid of cells: xlsx, ods, csv. */ | 'spreadsheet' /** A sequence of slides: pptx, odp. */ | 'presentation' /** Fixed page layout: pdf. */ | 'paged-document' /** A raster or vector image. */ | 'image'

Broad document category; determines which viewer applies.

FormatId
type FormatId = | 'docx' | 'xlsx' | 'pptx' // Legacy Microsoft Office (OLE2/CFB) — planned | 'doc' | 'xls' | 'ppt' // Fixed-layout documents — planned | 'pdf' // OpenDocument — planned | 'odt' | 'ods' | 'odp' // Plain formats — planned | 'txt' | 'md' | 'csv' | 'json' | 'xml' | 'html' // Images — planned | 'png' | 'jpeg' | 'gif' | 'webp' | 'bmp' | 'tiff' | 'svg' // Internal | 'unknown'

Identifier of a concrete file format. A string literal union rather than an enum: the values are part of the public API, get serialised to JSON, and are used as registry keys.

Locator
type Locator = string

The opaque wire form. Parse it with {@link parseLocator}.

LocatorFlow
type LocatorFlow = | { readonly kind: 'body' } /** A header or footer part, named by the relationship that reaches it. */ | { readonly kind: 'header' | 'footer'; readonly id: string } /** A note, comment or thread, named by its own id in the part. */ | { readonly kind: 'footnote' | 'endnote' | 'comment'; readonly id: string } /** A slide, its speaker notes, or a worksheet. */ | { readonly kind: 'slide' | 'notes'; readonly index: number } | { readonly kind: 'sheet'; readonly name: string }

The independent content streams of a document. A document is not one sequence of blocks. Headers, footers, footnotes, endnotes, comments and speaker notes are separate flows that interleave with the body only once it is laid out, and addressing them as if they were part of the body would make every address after the first footnote wrong.

Selector
type Selector = LocatorSelector | TextPositionSelector | TextQuoteSelector | SheetSelector | SlideSelector

Values

AUTO_LENGTH
AUTO_LENGTH: Length
BLACK
BLACK: Rgba
defaultRegistry
defaultRegistry: FormatRegistry

Shared registry for applications that do not need isolation.

EIGHTHS_PER_POINT
EIGHTHS_PER_POINT: 8

Eighths of a point: the unit of border widths in WordprocessingML.

EMU_PER_CM
EMU_PER_CM: 360000

EMUs per centimetre.

EMU_PER_INCH
EMU_PER_INCH: 914400

English Metric Units: 914400 per inch. The base unit of DrawingML.

EMU_PER_POINT
EMU_PER_POINT: 12700

EMUs per point: 914400 / 72.

FORMATS
FORMATS: readonly FormatDescriptor[]

Catalogue of known formats. It also lists formats that have no parser yet: the catalogue answers "what is this file", not "can we open it". That lets the viewer say "this is a PowerPoint 97-2003 presentation, support is planned" instead of a bare "unknown format".

HIGHLIGHT_COLORS
HIGHLIGHT_COLORS: Readonly<Record<string, string>>

Named `ST_HighlightColor` values from WordprocessingML.

LOCATOR_SCHEME
LOCATOR_SCHEME: "apertura"
PX_PER_INCH
PX_PER_INCH: 96

CSS pixels per inch — 96, as is conventional on the web.

PX_PER_POINT
PX_PER_POINT: number
TWIPS_PER_INCH
TWIPS_PER_INCH: 1440

Twentieths of a point: 1440 per inch. The unit of WordprocessingML.

TWIPS_PER_POINT
TWIPS_PER_POINT: 20
WHITE
WHITE: Rgba