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.
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.
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 and renderers.
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.
registerParser
<TDocument extends AperturaDocument>(plugin: ParserPlugin<TDocument>) => this
registerView
<TDocument extends AperturaDocument>(plugin: ViewPlugin<TDocument>) => this
getParser
(format: FormatId) => ParserPlugin | undefined
getView
(format: FormatId) => ViewPlugin | 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.
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
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
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.
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
throwIfAborted
function throwIfAborted(signal: AbortSignal | undefined, what?: string): void
Throws {@link CancelledError} if the signal has already been aborted.
toByteSource
function toByteSource(input: ByteSourceInput): Promise<ByteSource>
Normalises any supported input into a {@link ByteSource}. Strings are URLs.
trimNulls
function trimNulls(text: string): string
Strips the trailing NUL padding of a fixed-length string field.
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.
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.
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.
keywords?
readonly string[] | undefined
producer?
string | undefined
The application that produced the file.
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.
DocumentView
interface DocumentView
A live view of a document mounted into the DOM.
update
() => void
Re-render after the container was resized or settings changed.
destroy
() => void
Tear the view down and release resources. The container is left empty.
FormatDescriptor
interface FormatDescriptor
Format description: its name, how to open it, how to recognise it.
label
string
Human-readable name for the UI.
extensions
readonly string[]
Extensions without the leading dot, lower-case.
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.
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>
ViewOptions
interface ViewOptions
zoom?
number | undefined
Rendering scale, 1 means 100%.
fit?
"none" | "width" | "page" | undefined
How the page should be fitted into the container.
initialPage?
number | undefined
Initial page/sheet/slide, zero-based.
ViewPlugin
interface ViewPlugin<TDocument extends AperturaDocument = AperturaDocument>
A renderer plugin: turns a parsed document into DOM.
mount
(document: TDocument, container: HTMLElement, options?: ViewOptions) => Promise<DocumentView>
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.