Skip to content
Apertura
API reference

@apertura/viewer

Framework-independent Apertura viewer: detects the format, parses the file and mounts a view

31 exported symbols · 7 declared here · 24 re-exported

Classes

AperturaErrorfrom @apertura/core
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.
CorruptFileErrorfrom @apertura/core
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.
FormatRegistryfrom @apertura/core
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.
NotImplementedErrorfrom @apertura/core
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.

UnsupportedFormatErrorfrom @apertura/core
class UnsupportedFormatError extends AperturaError

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

detectedFormat
string | undefined
Viewer
class Viewer

A framework-independent document viewer. The single place that knows the full path from bytes to format to document to DOM. The React, Vue and Angular wrappers are thin adapters over this class, so their behaviour is identical by construction rather than by convention.

state
ViewerState
container
HTMLElement
view
DocumentView | undefined
The live view, for reaching format-specific APIs such as page navigation.
subscribe
(listener: (state: ViewerState) => void) => () => void
Subscribes to state changes. Returns an unsubscribe function.
open
(input: ByteSourceInput, options?: ViewerOptions) => Promise<void>
Opens a file and mounts its view. Calling it again before the previous call settles is correct: the older result is discarded. That is the normal case when a user picks files in quick succession.
refresh
() => void
Re-renders the current view.
close
() => void
Closes the document and clears the container.
destroy
() => void
Releases every resource. The instance must not be used afterwards.

Functions

createDefaultRegistry
function createDefaultRegistry(): FormatRegistry

A registry with every supported format registered. The convenient entry point for an application that just needs to open a file. When bundle size matters, build a {@link FormatRegistry} by hand so only the parsers actually used are included.

createDocxRegistry
function createDocxRegistry(): FormatRegistry

A registry holding only the Word format, for applications that need just that.

createViewer
function createViewer(container: HTMLElement, options?: ViewerOptions): Viewer

Creates a viewer mounted into the given element.

describeFormatfrom @apertura/core
function describeFormat(id: FormatId): FormatDescriptor | undefined
detectFormatfrom @apertura/core
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.

toByteSourcefrom @apertura/core
function toByteSource(input: ByteSourceInput): Promise<ByteSource>

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

Interfaces

AperturaDocumentfrom @apertura/core
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.
ByteSourcefrom @apertura/core
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.
DetectionResultfrom @apertura/core
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.
DocumentMetadatafrom @apertura/core
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.
DocumentViewfrom @apertura/core
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.
OpenOptionsfrom @apertura/core
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.
ViewerOptions
interface ViewerOptions extends ViewOptions, OpenOptions
registry?
FormatRegistry | undefined
The plugin set to use. Defaults to every supported format. Pass a custom registry to keep unused parsers out of the bundle.
renderOptions?
Record<string, unknown> | undefined
Extra options forwarded to the format renderer.
ViewerState
interface ViewerState
status
ViewerStatus
document
AperturaDocument | undefined
detection
DetectionResult | undefined
error
Error | undefined
progress
number
Parse progress, 0..1.
ViewOptionsfrom @apertura/core
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.
signal?
AbortSignal | undefined

Type aliases

ByteSourceInputfrom @apertura/core
type ByteSourceInput = ByteSource | Blob | ArrayBuffer | Uint8Array | string

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

DocumentKindfrom @apertura/core
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.

FormatIdfrom @apertura/core
type FormatId = 'docx' | 'xlsx' | 'pptx' | 'doc' | 'xls' | 'ppt' | 'pdf' | 'odt' | 'ods' | 'odp' | 'txt' | 'md' | 'csv' | 'json' | 'xml' | 'html' | 'png' | 'jpeg' | 'gif' | 'webp' | 'bmp' | 'tiff' | 'svg' | '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.

ViewerStatus
type ViewerStatus = 'idle' | 'loading' | 'ready' | 'error'

Viewer state; UI wrappers render indicators from it.

Values

docxParserfrom @apertura/docx
docxParser: ParserPlugin<DocxDocument>

The docx parser plugin for {@link FormatRegistry }. `canOpen` looks inside the ZIP: the extension cannot be trusted, and every OOXML format shares one signature. Opening the package for the check is cheap — only the central directory and `[Content_Types].xml` are read — and the result is cached by the archive, so the subsequent `open` pays nothing twice.

docxViewfrom @apertura/docx-view
docxView: ViewPlugin<DocxDocument>

The docx renderer plugin for {@link FormatRegistry }.

pptxParserfrom @apertura/pptx
pptxParser: ParserPlugin<PptxDocument>
pptxViewfrom @apertura/pptx-view
pptxView: ViewPlugin<PptxDocument>
xlsxParserfrom @apertura/xlsx
xlsxParser: ParserPlugin<XlsxDocument>
xlsxViewfrom @apertura/xlsx-view
xlsxView: ViewPlugin<XlsxDocument>